Rework authentication for local Cloud/Collab development (#35450)

This PR reworks authentication for developing Zed against a local
version of Cloud and/or Collab.

You will still connect the same way—using the `zed-local` script—but
will need to be running an instance of Cloud locally.

Release Notes:

- N/A
This commit is contained in:
Marshall Bowers 2025-07-31 20:55:17 -04:00
parent 7fdbfc9e8d
commit 6e0999fb4f
2 changed files with 25 additions and 93 deletions

View file

@ -7,14 +7,13 @@ pub mod telemetry;
pub mod user; pub mod user;
pub mod zed_urls; pub mod zed_urls;
use anyhow::{Context as _, Result, anyhow, bail}; use anyhow::{Context as _, Result, anyhow};
use async_recursion::async_recursion; use async_recursion::async_recursion;
use async_tungstenite::tungstenite::{ use async_tungstenite::tungstenite::{
client::IntoClientRequest, client::IntoClientRequest,
error::Error as WebsocketError, error::Error as WebsocketError,
http::{HeaderValue, Request, StatusCode}, http::{HeaderValue, Request, StatusCode},
}; };
use chrono::{DateTime, Utc};
use clock::SystemClock; use clock::SystemClock;
use cloud_api_client::CloudApiClient; use cloud_api_client::CloudApiClient;
use credentials_provider::CredentialsProvider; use credentials_provider::CredentialsProvider;
@ -23,7 +22,7 @@ use futures::{
channel::oneshot, future::BoxFuture, channel::oneshot, future::BoxFuture,
}; };
use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity, actions}; use gpui::{App, AsyncApp, Entity, Global, Task, WeakEntity, actions};
use http_client::{AsyncBody, HttpClient, HttpClientWithUrl, http}; use http_client::{HttpClient, HttpClientWithUrl, http};
use parking_lot::RwLock; use parking_lot::RwLock;
use postage::watch; use postage::watch;
use proxy::connect_proxy_stream; use proxy::connect_proxy_stream;
@ -1351,96 +1350,31 @@ impl Client {
self: &Arc<Self>, self: &Arc<Self>,
http: Arc<HttpClientWithUrl>, http: Arc<HttpClientWithUrl>,
login: String, login: String,
mut api_token: String, api_token: String,
) -> Result<Credentials> { ) -> Result<Credentials> {
#[derive(Deserialize)] #[derive(Serialize)]
struct AuthenticatedUserResponse { struct ImpersonateUserBody {
user: User, github_login: String,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct User { struct ImpersonateUserResponse {
id: u64, user_id: u64,
access_token: String,
} }
let github_user = { let url = self
#[derive(Deserialize)] .http
struct GithubUser { .build_zed_cloud_url("/internal/users/impersonate", &[])?;
id: i32, let request = Request::post(url.as_str())
login: String, .header("Content-Type", "application/json")
created_at: DateTime<Utc>, .header("Authorization", format!("Bearer {api_token}"))
} .body(
serde_json::to_string(&ImpersonateUserBody {
let request = { github_login: login,
let mut request_builder =
Request::get(&format!("https://api.github.com/users/{login}"));
if let Ok(github_token) = std::env::var("GITHUB_TOKEN") {
request_builder =
request_builder.header("Authorization", format!("Bearer {}", github_token));
}
request_builder.body(AsyncBody::empty())?
};
let mut response = http
.send(request)
.await
.context("error fetching GitHub user")?;
let mut body = Vec::new();
response
.body_mut()
.read_to_end(&mut body)
.await
.context("error reading GitHub user")?;
if !response.status().is_success() {
let text = String::from_utf8_lossy(body.as_slice());
bail!(
"status error {}, response: {text:?}",
response.status().as_u16()
);
}
serde_json::from_slice::<GithubUser>(body.as_slice()).map_err(|err| {
log::error!("Error deserializing: {:?}", err);
log::error!(
"GitHub API response text: {:?}",
String::from_utf8_lossy(body.as_slice())
);
anyhow!("error deserializing GitHub user")
})? })?
}; .into(),
)?;
let query_params = [
("github_login", &github_user.login),
("github_user_id", &github_user.id.to_string()),
(
"github_user_created_at",
&github_user.created_at.to_rfc3339(),
),
];
// Use the collab server's admin API to retrieve the ID
// of the impersonated user.
let mut url = self.rpc_url(http.clone(), None).await?;
url.set_path("/user");
url.set_query(Some(
&query_params
.iter()
.map(|(key, value)| {
format!(
"{}={}",
key,
url::form_urlencoded::byte_serialize(value.as_bytes()).collect::<String>()
)
})
.collect::<Vec<String>>()
.join("&"),
));
let request: http_client::Request<AsyncBody> = Request::get(url.as_str())
.header("Authorization", format!("token {api_token}"))
.body("".into())?;
let mut response = http.send(request).await?; let mut response = http.send(request).await?;
let mut body = String::new(); let mut body = String::new();
@ -1451,13 +1385,11 @@ impl Client {
response.status().as_u16(), response.status().as_u16(),
body, body,
); );
let response: AuthenticatedUserResponse = serde_json::from_str(&body)?; let response: ImpersonateUserResponse = serde_json::from_str(&body)?;
// Use the admin API token to authenticate as the impersonated user.
api_token.insert_str(0, "ADMIN_TOKEN:");
Ok(Credentials { Ok(Credentials {
user_id: response.user.id, user_id: response.user_id,
access_token: api_token, access_token: response.access_token,
}) })
} }

View file

@ -213,7 +213,7 @@ setTimeout(() => {
platform === "win32" platform === "win32"
? "http://127.0.0.1:8080/rpc" ? "http://127.0.0.1:8080/rpc"
: "http://localhost:8080/rpc", : "http://localhost:8080/rpc",
ZED_ADMIN_API_TOKEN: "secret", ZED_ADMIN_API_TOKEN: "internal-api-key-secret",
ZED_WINDOW_SIZE: size, ZED_WINDOW_SIZE: size,
ZED_CLIENT_CHECKSUM_SEED: "development-checksum-seed", ZED_CLIENT_CHECKSUM_SEED: "development-checksum-seed",
RUST_LOG: process.env.RUST_LOG || "info", RUST_LOG: process.env.RUST_LOG || "info",