diff --git a/Cargo.lock b/Cargo.lock index 499baaf..6a332ce 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1438,6 +1438,7 @@ dependencies = [ "dirs 7.0.0", "duckdb", "form_urlencoded", + "futures", "getrandom 0.4.3", "gpui-kit", "gpui-omarchy", diff --git a/Cargo.toml b/Cargo.toml index 653e710..7a308df 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ base64ct = "1.8.3" dirs = "7.0.0" duckdb = { version = "1.20000.1", features = ["bundled", "uuid"] } form_urlencoded = "1.2.3" +futures = "0.3.34" getrandom = { version = "0.4.3", features = ["sys_rng"] } gpui-kit = "0.7.0" gpui-omarchy = "0.2.1" diff --git a/src/app.rs b/src/app.rs index 4e48fba..d28758a 100644 --- a/src/app.rs +++ b/src/app.rs @@ -5,7 +5,7 @@ use gpui_kit::{ use gpui_omarchy::ActiveTheme; use crate::config::AppConfig; -use crate::screens::{CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen}; +use crate::screens::{ApprovalScreen, CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen}; use crate::session::AppSession; use crate::srv::{self, PendingRequests}; @@ -27,7 +27,9 @@ impl Render for CreddyApp { Screen::Credentials => window .use_keyed_state("credentials", cx, |_, cx| CredentialsScreen::new(cx)) .into_any_element(), - Screen::RequestApproval => todo!(), + Screen::RequestApproval => window + .use_keyed_state("approval", cx, |_, _| ApprovalScreen {}) + .into_any_element(), Screen::ShowApproval => todo!(), }; @@ -61,6 +63,8 @@ pub fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHan .detach(); cx.observe_global::(|cx| cx.refresh_windows()) .detach(); + cx.observe_global::(|cx| cx.refresh_windows()) + .detach(); cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {})) .expect("open window") diff --git a/src/error.rs b/src/error.rs index 9b6623f..388d9e9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -33,4 +33,7 @@ pub enum CreddyError { #[error("Failed to bind socket: {0}")] SocketBind(String), + + #[error("Credential request was denied.")] + RequestDenied, } diff --git a/src/screens/approval.rs b/src/screens/approval.rs new file mode 100644 index 0000000..ab4ed11 --- /dev/null +++ b/src/screens/approval.rs @@ -0,0 +1,73 @@ +use gpui_kit::{ + App, BorrowAppContext, Context, FontWeight, IntoElement, ParentElement, Render, Styled, Window, + div, rems, +}; +use gpui_omarchy::{ButtonVariant, button, focus_scope}; + +use crate::session::AppSession; +use crate::srv::{CredentialRequest, CredentialResponse, PendingRequests}; + +/// Asks the user to approve or deny the oldest pending request. +pub struct ApprovalScreen {} + +fn respond(approved: bool, cx: &mut App) { + let sender = cx.update_global::(|pending, _| { + let Some((_request, sender)) = pending.0.pop_front() else { + unreachable!("approval screen is only shown while a request is pending"); + }; + sender + }); + + // if this errors, it just means the client went away before we could send the response + // in which case we don't really care + let _ = match approved { + true => sender.send(CredentialResponse::yes_session()), + false => sender.send(CredentialResponse::no()), + }; +} + +impl Render for ApprovalScreen { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let Some((request, _)) = cx.global::().0.front() else { + unreachable!("approval screen is only shown while a request is pending"); + }; + let description = match request { + CredentialRequest::AwsGet { name: Some(name), .. } => { + format!("An application would like to access your AWS access key \"{name}\".") + } + CredentialRequest::AwsGet { name: None, .. } => { + "An application would like to access your default AWS access key.".to_string() + } + }; + + focus_scope("approval") + .size_full() + .flex() + .flex_col() + .items_center() + .justify_center() + .gap(rems(1.5)) + .p(rems(0.5)) + .child( + div() + .max_w(rems(32.)) + .text_center() + .text_size(rems(1.25)) + .font_weight(FontWeight::BOLD) + .child(description), + ) + .child( + div() + .flex() + .gap(rems(1.)) + .child( + button("deny", "Deny", ButtonVariant::Danger, cx) + .on_click(|_, _, cx| respond(false, cx)), + ) + .child( + button("approve", "Approve", ButtonVariant::Primary, cx) + .on_click(|_, _, cx| respond(true, cx)), + ), + ) + } +} diff --git a/src/screens/mod.rs b/src/screens/mod.rs index dbaed25..b38c818 100644 --- a/src/screens/mod.rs +++ b/src/screens/mod.rs @@ -1,11 +1,13 @@ use gpui_kit::{Context, Global}; +mod approval; mod credentials; mod home; mod unlock; mod welcome; use crate::app::CreddyApp; +pub use approval::ApprovalScreen; pub use credentials::CredentialsScreen; pub use home::HomeScreen; pub use unlock::UnlockScreen; @@ -35,7 +37,7 @@ impl Screen { // therwise if locked, ask for unlock AppSession::Locked => Screen::Unlock, // otherwise, fall back to "current screen" global - AppSession::Unlocked{ .. } => *cx.global::(), + AppSession::Unlocked(_) => *cx.global::(), } } } diff --git a/src/srv/creddy_server.rs b/src/srv/creddy_server.rs index 8586f06..8c7c245 100644 --- a/src/srv/creddy_server.rs +++ b/src/srv/creddy_server.rs @@ -1,5 +1,7 @@ use crate::credentials::{AwsCredential, AwsSessionCredential}; use crate::error::CreddyError; +use crate::session::AppSession; +use futures::channel::oneshot::{self, Sender}; use gpui_kit::{AsyncApp, Global}; use http_body_util::Full; use hyper::body::{Bytes, Incoming}; @@ -20,6 +22,7 @@ use std::io; use std::path::Path; use std::time::Duration; +#[derive(Clone)] pub enum CredentialRequest { AwsGet { name: Option, @@ -27,7 +30,26 @@ pub enum CredentialRequest { } } -pub struct PendingRequests(pub VecDeque); +pub struct CredentialResponse { + approved: bool, + session: bool, +} + +impl CredentialResponse { + pub fn yes_session() -> CredentialResponse { + CredentialResponse { approved: true, session: true } + } + + pub fn yes_longterm() -> CredentialResponse { + CredentialResponse { approved: true, session: false } + } + + pub fn no() -> CredentialResponse { + CredentialResponse { approved: false, session: true } + } +} + +pub struct PendingRequests(pub VecDeque<(CredentialRequest, Sender)>); impl PendingRequests { pub fn new() -> PendingRequests { @@ -44,6 +66,13 @@ pub struct ErrorResponse { message: String, } +impl ErrorResponse { + fn into_http(&self) -> serde_json::Result>> { + let bytes = serde_json::to_vec(self)?; + Ok(Response::new(Full::new(Bytes::from(bytes)))) + } +} + impl From for ErrorResponse { fn from(e: CreddyError) -> ErrorResponse { let message = e.to_string(); @@ -101,39 +130,48 @@ async fn handle( app: AsyncApp, ) -> Result>, Infallible> { let (parts, _body) = req.into_parts(); + let response = match (parts.method, parts.uri.path()) { (Method::GET, "/ping") => text(StatusCode::OK, "pong"), - (Method::GET, "/aws") => handle_aws_get(parts.uri), + (Method::GET, "/aws") => handle_aws_get(parts.uri, app).await, (_, p) => text(StatusCode::NOT_FOUND, &format!("Not found: {p}")), }; - Ok(response) + match response { + Ok(r) => Ok(r), + Err(e) => Ok(ErrorResponse::from(e).into_http().unwrap()), + } } -fn handle_aws_get(uri: Uri) -> Response> { +async fn handle_aws_get(uri: Uri, app: AsyncApp) -> Result>, CreddyError> { let qs = uri.query().unwrap_or("").as_bytes(); let params: HashMap<_, _> = form_urlencoded::parse(qs).collect(); - let req = CredentialRequest::AwsGet{ - name: params.get("name").map(|n| n.to_string()), - session: params.get("session").map(|s| s == "true").unwrap_or(false), - }; + let name = params.get("name").map(|n| n.to_string()); + let session = params.get("session").map(|s| s == "true").unwrap_or(false); + let req = CredentialRequest::AwsGet { name: name.clone(), session }; - // todo: actually get credentials from the rest of the app + let (sender, receiver) = oneshot::channel::(); + app.update_global::(|pending, _cx| pending.0.push_back((req.clone(), sender))); - let creds = AwsCredential { - id: uuid::uuid!("b448d315-fe82-41a9-9070-e0977e8dfa0c"), - name: "test".into(), - access_key_id: "AKIAWHATEVER".into(), - secret_access_key: "VERYSECRETSECUREVALUE".into(), - is_default: true, - }; + let resp = receiver.await.unwrap_or_else(|_| CredentialResponse::no()); + if !resp.approved { + return Err(CreddyError::RequestDenied); + } + + // eventually: let session = AppSession::wait_for_unlock().await; or something like that + let creds = app.read_global::(|session, cx| { + let AppSession::Unlocked(db) = session else { unreachable!() }; + db.load_aws_credential(&name.unwrap_or_else(|| "default".into())) + })?; + + // todo: session credential handling let body = serde_json::to_vec(&creds).unwrap(); - Response::new(Full::new(Bytes::from(body))) + Ok(Response::new(Full::new(Bytes::from(body)))) } -fn text(status: StatusCode, body: &str) -> Response> { +fn text(status: StatusCode, body: &str) -> Result>, CreddyError> { let mut response = Response::new(Full::new(Bytes::from(body.to_owned()))); *response.status_mut() = status; - response + Ok(response) } diff --git a/src/srv/mod.rs b/src/srv/mod.rs index 1dee20c..1885ca3 100644 --- a/src/srv/mod.rs +++ b/src/srv/mod.rs @@ -1,3 +1,8 @@ mod creddy_server; -pub use creddy_server::{PendingRequests, start_creddy_server}; +pub use creddy_server::{ + CredentialRequest, + CredentialResponse, + PendingRequests, + start_creddy_server +}; diff --git a/src/tests/mod.rs b/src/tests/mod.rs index b6124c0..267e2c3 100644 --- a/src/tests/mod.rs +++ b/src/tests/mod.rs @@ -5,8 +5,9 @@ use crate::db::Db; use crate::error::CreddyError; use crate::screens::Screen; use crate::session::AppSession; +use crate::srv::{CredentialRequest, PendingRequests}; use gpui_kit::test::TestWindowExt; -use gpui_kit::{AnyWindowHandle, App, AppContext, TestAppContext, Window}; +use gpui_kit::{AnyWindowHandle, App, AppContext, BorrowAppContext, TestAppContext, Window}; use tempfile::TempDir; use uuid::Uuid; @@ -410,3 +411,25 @@ fn test_delete_aws_credential(cx: &mut TestAppContext) { }); assert!(creds.is_empty()); } + +#[gpui_kit::test] +fn test_approve_request(cx: &mut TestAppContext) { + let env = TestEnv::new().unwrap(); + env.db().unwrap(); + let window = open_app(&env, cx); + fill(window, "passphrase", TEST_PASSPHRASE, cx); + click(window, "submit", cx); + assert!(is_visible(window, "credentials", cx)); + + act(window, cx, |_, cx| { + let request = CredentialRequest::AwsGet { name: Some("test".into()), session: true }; + let (sender, _receiver) = futures::channel::oneshot::channel(); + cx.update_global::(|pending, _| pending.0.push_back((request, sender))); + }); + assert!(is_visible(window, "approve", cx)); + assert!(!is_visible(window, "credentials", cx)); + + click(window, "approve", cx); + assert!(cx.read(|cx| cx.global::().0.is_empty())); + assert!(is_visible(window, "credentials", cx)); +}