Start work on connecting to RPC endpoint
Co-Authored-By: Antonio Scandurra <me@as-cii.com>
This commit is contained in:
parent
e897d1c98e
commit
20542f54ef
9 changed files with 1118 additions and 90 deletions
969
Cargo.lock
generated
969
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
@ -2,7 +2,7 @@ use crate::{
|
||||||
elements::ElementBox,
|
elements::ElementBox,
|
||||||
executor,
|
executor,
|
||||||
keymap::{self, Keystroke},
|
keymap::{self, Keystroke},
|
||||||
platform::{self, PromptLevel, WindowOptions},
|
platform::{self, Platform, PromptLevel, WindowOptions},
|
||||||
presenter::Presenter,
|
presenter::Presenter,
|
||||||
util::{post_inc, timeout},
|
util::{post_inc, timeout},
|
||||||
AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
|
AssetCache, AssetSource, ClipboardItem, FontCache, PathPromptOptions, TextLayoutCache,
|
||||||
|
@ -412,6 +412,10 @@ impl AsyncAppContext {
|
||||||
self.update(|cx| cx.add_model(build_model))
|
self.update(|cx| cx.add_model(build_model))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn platform(&self) -> Arc<dyn Platform> {
|
||||||
|
self.0.borrow().platform()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn background_executor(&self) -> Arc<executor::Background> {
|
pub fn background_executor(&self) -> Arc<executor::Background> {
|
||||||
self.0.borrow().cx.background.clone()
|
self.0.borrow().cx.background.clone()
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,6 +12,7 @@ futures-lite = "1"
|
||||||
prost = "0.7"
|
prost = "0.7"
|
||||||
rsa = "0.4"
|
rsa = "0.4"
|
||||||
rand = "0.8"
|
rand = "0.8"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
prost-build = { git = "https://github.com/sfackler/prost", rev = "082f3e65874fe91382e72482863896b7b4db3728" }
|
prost-build = { git = "https://github.com/sfackler/prost", rev = "082f3e65874fe91382e72482863896b7b4db3728" }
|
||||||
|
|
|
@ -1,2 +1,3 @@
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod proto;
|
pub mod proto;
|
||||||
|
pub mod rest;
|
||||||
|
|
7
zed-rpc/src/rest.rs
Normal file
7
zed-rpc/src/rest.rs
Normal file
|
@ -0,0 +1,7 @@
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct CreateWorktreeResponse {
|
||||||
|
pub worktree_id: u64,
|
||||||
|
pub rpc_address: String,
|
||||||
|
}
|
|
@ -23,6 +23,7 @@ easy-parallel = "3.1.0"
|
||||||
fsevent = { path = "../fsevent" }
|
fsevent = { path = "../fsevent" }
|
||||||
futures-core = "0.3"
|
futures-core = "0.3"
|
||||||
gpui = { path = "../gpui" }
|
gpui = { path = "../gpui" }
|
||||||
|
http-auth-basic = "0.1.3"
|
||||||
ignore = "0.4"
|
ignore = "0.4"
|
||||||
lazy_static = "1.4.0"
|
lazy_static = "1.4.0"
|
||||||
libc = "0.2"
|
libc = "0.2"
|
||||||
|
@ -39,6 +40,7 @@ similar = "1.3"
|
||||||
simplelog = "0.9"
|
simplelog = "0.9"
|
||||||
smallvec = { version = "1.6", features = ["union"] }
|
smallvec = { version = "1.6", features = ["union"] }
|
||||||
smol = "1.2.5"
|
smol = "1.2.5"
|
||||||
|
surf = "2.2"
|
||||||
toml = "0.5"
|
toml = "0.5"
|
||||||
tree-sitter = "0.19.5"
|
tree-sitter = "0.19.5"
|
||||||
tree-sitter-rust = "0.19.0"
|
tree-sitter-rust = "0.19.0"
|
||||||
|
|
188
zed/src/lib.rs
188
zed/src/lib.rs
|
@ -1,8 +1,9 @@
|
||||||
use anyhow::{anyhow, Context};
|
use anyhow::{anyhow, Context, Result};
|
||||||
use gpui::MutableAppContext;
|
use gpui::{AsyncAppContext, MutableAppContext, Task};
|
||||||
use smol::io::{AsyncBufReadExt, AsyncWriteExt};
|
use smol::io::{AsyncBufReadExt, AsyncWriteExt};
|
||||||
use std::convert::TryFrom;
|
use std::convert::TryFrom;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
use util::SurfResultExt;
|
||||||
|
|
||||||
pub mod assets;
|
pub mod assets;
|
||||||
pub mod editor;
|
pub mod editor;
|
||||||
|
@ -26,94 +27,129 @@ pub struct AppState {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn init(cx: &mut MutableAppContext) {
|
pub fn init(cx: &mut MutableAppContext) {
|
||||||
cx.add_global_action("app:authenticate", authenticate);
|
cx.add_global_action("app:share_worktree", share_worktree);
|
||||||
cx.add_global_action("app:quit", quit);
|
cx.add_global_action("app:quit", quit);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn authenticate(_: &(), cx: &mut MutableAppContext) {
|
fn share_worktree(_: &(), cx: &mut MutableAppContext) {
|
||||||
let zed_url = std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev".to_string());
|
let zed_url = std::env::var("ZED_SERVER_URL").unwrap_or("https://zed.dev".to_string());
|
||||||
let platform = cx.platform().clone();
|
cx.spawn::<_, _, surf::Result<()>>(|cx| async move {
|
||||||
|
let (user_id, access_token) = login(zed_url.clone(), cx).await?;
|
||||||
|
|
||||||
cx.background_executor()
|
let mut response = surf::post(format!("{}/api/worktrees", &zed_url))
|
||||||
.spawn(async move {
|
.header(
|
||||||
if let Some((user_id, access_token)) = platform.read_credentials(&zed_url) {
|
"Authorization",
|
||||||
log::info!("already signed in. user_id: {}", user_id);
|
http_auth_basic::Credentials::new(&user_id, &access_token).as_http_header(),
|
||||||
return Ok((user_id, String::from_utf8(access_token).unwrap()));
|
)
|
||||||
}
|
.await
|
||||||
|
.context("")?;
|
||||||
|
|
||||||
// Generate a pair of asymmetric encryption keys. The public key will be used by the
|
let body = response
|
||||||
// zed server to encrypt the user's access token, so that it can'be intercepted by
|
.body_json::<zed_rpc::rest::CreateWorktreeResponse>()
|
||||||
// any other app running on the user's device.
|
.await?;
|
||||||
let (public_key, private_key) =
|
|
||||||
zed_rpc::auth::keypair().expect("failed to generate keypair for auth");
|
|
||||||
let public_key_string =
|
|
||||||
String::try_from(public_key).expect("failed to serialize public key for auth");
|
|
||||||
|
|
||||||
// Listen on an open TCP port. This port will be used by the web browser to notify the
|
// TODO - If the `ZED_SERVER_URL` uses https, then wrap this stream in
|
||||||
// application that the login is complete, and to send the user's id and access token.
|
// a TLS stream using `native-tls`.
|
||||||
let listener = smol::net::TcpListener::bind("127.0.0.1:0").await?;
|
let stream = smol::net::TcpStream::connect(body.rpc_address).await?;
|
||||||
let port = listener.local_addr()?.port();
|
|
||||||
|
|
||||||
// Open the Zed sign-in page in the user's browser, with query parameters that indicate
|
let mut message_stream = zed_rpc::proto::MessageStream::new(stream);
|
||||||
// that the user is signing in from a Zed app running on the same device.
|
message_stream
|
||||||
platform.open_url(&format!(
|
.write_message(&zed_rpc::proto::FromClient {
|
||||||
"{}/sign_in?native_app_port={}&native_app_public_key={}",
|
id: 0,
|
||||||
zed_url, port, public_key_string
|
variant: Some(zed_rpc::proto::from_client::Variant::Auth(
|
||||||
|
zed_rpc::proto::from_client::Auth {
|
||||||
|
user_id: user_id.parse::<i32>()?,
|
||||||
|
access_token,
|
||||||
|
},
|
||||||
|
)),
|
||||||
|
})
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn login(zed_url: String, cx: AsyncAppContext) -> Task<Result<(String, String)>> {
|
||||||
|
let platform = cx.platform();
|
||||||
|
cx.background_executor().spawn(async move {
|
||||||
|
if let Some((user_id, access_token)) = platform.read_credentials(&zed_url) {
|
||||||
|
log::info!("already signed in. user_id: {}", user_id);
|
||||||
|
return Ok((user_id, String::from_utf8(access_token).unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a pair of asymmetric encryption keys. The public key will be used by the
|
||||||
|
// zed server to encrypt the user's access token, so that it can'be intercepted by
|
||||||
|
// any other app running on the user's device.
|
||||||
|
let (public_key, private_key) =
|
||||||
|
zed_rpc::auth::keypair().expect("failed to generate keypair for auth");
|
||||||
|
let public_key_string =
|
||||||
|
String::try_from(public_key).expect("failed to serialize public key for auth");
|
||||||
|
|
||||||
|
// Listen on an open TCP port. This port will be used by the web browser to notify the
|
||||||
|
// application that the login is complete, and to send the user's id and access token.
|
||||||
|
let listener = smol::net::TcpListener::bind("127.0.0.1:0").await?;
|
||||||
|
let port = listener.local_addr()?.port();
|
||||||
|
|
||||||
|
// Open the Zed sign-in page in the user's browser, with query parameters that indicate
|
||||||
|
// that the user is signing in from a Zed app running on the same device.
|
||||||
|
platform.open_url(&format!(
|
||||||
|
"{}/sign_in?native_app_port={}&native_app_public_key={}",
|
||||||
|
zed_url, port, public_key_string
|
||||||
|
));
|
||||||
|
|
||||||
|
// Receive the HTTP request from the user's browser. Parse the first line, which contains
|
||||||
|
// the HTTP method and path.
|
||||||
|
let (mut stream, _) = listener.accept().await?;
|
||||||
|
let mut reader = smol::io::BufReader::new(&mut stream);
|
||||||
|
let mut line = String::new();
|
||||||
|
reader.read_line(&mut line).await?;
|
||||||
|
let mut parts = line.split(" ");
|
||||||
|
let http_method = parts.next();
|
||||||
|
if http_method != Some("GET") {
|
||||||
|
return Err(anyhow!(
|
||||||
|
"unexpected http method {:?} in request from zed web app",
|
||||||
|
http_method
|
||||||
));
|
));
|
||||||
|
}
|
||||||
|
let path = parts.next().ok_or_else(|| {
|
||||||
|
anyhow!("failed to parse http request from zed login redirect - missing path")
|
||||||
|
})?;
|
||||||
|
|
||||||
// Receive the HTTP request from the user's browser. Parse the first line, which contains
|
// Parse the query parameters from the HTTP request.
|
||||||
// the HTTP method and path.
|
let mut user_id = None;
|
||||||
let (mut stream, _) = listener.accept().await?;
|
let mut access_token = None;
|
||||||
let mut reader = smol::io::BufReader::new(&mut stream);
|
let url = Url::parse(&format!("http://example.com{}", path))
|
||||||
let mut line = String::new();
|
.context("failed to parse login notification url")?;
|
||||||
reader.read_line(&mut line).await?;
|
for (key, value) in url.query_pairs() {
|
||||||
let mut parts = line.split(" ");
|
if key == "access_token" {
|
||||||
let http_method = parts.next();
|
access_token = Some(value);
|
||||||
if http_method != Some("GET") {
|
} else if key == "user_id" {
|
||||||
return Err(anyhow!(
|
user_id = Some(value);
|
||||||
"unexpected http method {:?} in request from zed web app",
|
|
||||||
http_method
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
let path = parts.next().ok_or_else(|| {
|
}
|
||||||
anyhow!("failed to parse http request from zed login redirect - missing path")
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Parse the query parameters from the HTTP request.
|
// Write an HTTP response to the user's browser, instructing it to close the tab.
|
||||||
let mut user_id = None;
|
// Then transfer focus back to the application.
|
||||||
let mut access_token = None;
|
stream
|
||||||
let url = Url::parse(&format!("http://example.com{}", path))
|
.write_all(LOGIN_RESPONSE.as_bytes())
|
||||||
.context("failed to parse login notification url")?;
|
.await
|
||||||
for (key, value) in url.query_pairs() {
|
.context("failed to write login response")?;
|
||||||
if key == "access_token" {
|
stream.flush().await.context("failed to flush tcp stream")?;
|
||||||
access_token = Some(value);
|
platform.activate(true);
|
||||||
} else if key == "user_id" {
|
|
||||||
user_id = Some(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Write an HTTP response to the user's browser, instructing it to close the tab.
|
// If login succeeded, then store the credentials in the keychain.
|
||||||
// Then transfer focus back to the application.
|
let user_id = user_id.ok_or_else(|| anyhow!("missing user_id in login request"))?;
|
||||||
stream
|
let access_token =
|
||||||
.write_all(LOGIN_RESPONSE.as_bytes())
|
access_token.ok_or_else(|| anyhow!("missing access_token in login request"))?;
|
||||||
.await
|
let access_token = private_key
|
||||||
.context("failed to write login response")?;
|
.decrypt_string(&access_token)
|
||||||
stream.flush().await.context("failed to flush tcp stream")?;
|
.context("failed to decrypt access token")?;
|
||||||
platform.activate(true);
|
platform.write_credentials(&zed_url, &user_id, access_token.as_bytes());
|
||||||
|
log::info!("successfully signed in. user_id: {}", user_id);
|
||||||
|
|
||||||
// If login succeeded, then store the credentials in the keychain.
|
Ok((user_id.to_string(), access_token))
|
||||||
let user_id = user_id.ok_or_else(|| anyhow!("missing user_id in login request"))?;
|
})
|
||||||
let access_token =
|
|
||||||
access_token.ok_or_else(|| anyhow!("missing access_token in login request"))?;
|
|
||||||
let access_token = private_key
|
|
||||||
.decrypt_string(&access_token)
|
|
||||||
.context("failed to decrypt access token")?;
|
|
||||||
platform.write_credentials(&zed_url, &user_id, access_token.as_bytes());
|
|
||||||
log::info!("successfully signed in. user_id: {}", user_id);
|
|
||||||
|
|
||||||
Ok((user_id.to_string(), access_token))
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn quit(_: &(), cx: &mut MutableAppContext) {
|
fn quit(_: &(), cx: &mut MutableAppContext) {
|
||||||
|
|
|
@ -15,9 +15,9 @@ pub fn menus(state: AppState) -> Vec<Menu<'static>> {
|
||||||
},
|
},
|
||||||
MenuItem::Separator,
|
MenuItem::Separator,
|
||||||
MenuItem::Action {
|
MenuItem::Action {
|
||||||
name: "Log In",
|
name: "Share",
|
||||||
keystroke: None,
|
keystroke: None,
|
||||||
action: "app:authenticate",
|
action: "app:share_worktree",
|
||||||
arg: None,
|
arg: None,
|
||||||
},
|
},
|
||||||
MenuItem::Action {
|
MenuItem::Action {
|
||||||
|
|
|
@ -106,3 +106,33 @@ mod tests {
|
||||||
assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
|
assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Allow surf Results to accept context like other Results do when
|
||||||
|
// using anyhow.
|
||||||
|
pub trait SurfResultExt {
|
||||||
|
fn context<C>(self, cx: C) -> Self
|
||||||
|
where
|
||||||
|
C: std::fmt::Display + Send + Sync + 'static;
|
||||||
|
|
||||||
|
fn with_context<C, F>(self, f: F) -> Self
|
||||||
|
where
|
||||||
|
C: std::fmt::Display + Send + Sync + 'static,
|
||||||
|
F: FnOnce() -> C;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T> SurfResultExt for surf::Result<T> {
|
||||||
|
fn context<C>(self, cx: C) -> Self
|
||||||
|
where
|
||||||
|
C: std::fmt::Display + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
self.map_err(|e| surf::Error::new(e.status(), e.into_inner().context(cx)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_context<C, F>(self, f: F) -> Self
|
||||||
|
where
|
||||||
|
C: std::fmt::Display + Send + Sync + 'static,
|
||||||
|
F: FnOnce() -> C,
|
||||||
|
{
|
||||||
|
self.map_err(|e| surf::Error::new(e.status(), e.into_inner().context(f())))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue