basic working version of approval screen

This commit is contained in:
jfmonty2 committed 2026-11-23 14:35:37 -05:00
1 parent 49c1e81e1d
commit 5f1ff5e4e8
9 files changed
+174 -24

No files matched your search

Generated
+1
View File
@@ -1438,6 +1438,7 @@ dependencies = [
"dirs 7.0.0",
"duckdb",
"form_urlencoded",
"futures",
"getrandom 0.4.3",
"gpui-kit",
"gpui-omarchy",
+1
View File
@@ -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"
+6 -2
View File
@@ -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::<Screen>(|cx| cx.refresh_windows())
.detach();
cx.observe_global::<PendingRequests>(|cx| cx.refresh_windows())
.detach();
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window")
+3
View File
@@ -33,4 +33,7 @@ pub enum CreddyError {
#[error("Failed to bind socket: {0}")]
SocketBind(String),
#[error("Credential request was denied.")]
RequestDenied,
}
+73
View File
@@ -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::<PendingRequests, _>(|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<Self>) -> impl IntoElement {
let Some((request, _)) = cx.global::<PendingRequests>().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)),
),
)
}
}
+3 -1
View File
@@ -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::<Screen>(),
AppSession::Unlocked(_) => *cx.global::<Screen>(),
}
}
}
+57 -19
View File
@@ -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<String>,
@@ -27,7 +30,26 @@ pub enum CredentialRequest {
}
}
pub struct PendingRequests(pub VecDeque<CredentialRequest>);
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<CredentialResponse>)>);
impl PendingRequests {
pub fn new() -> PendingRequests {
@@ -44,6 +66,13 @@ pub struct ErrorResponse {
message: String,
}
impl ErrorResponse {
fn into_http(&self) -> serde_json::Result<Response<Full<Bytes>>> {
let bytes = serde_json::to_vec(self)?;
Ok(Response::new(Full::new(Bytes::from(bytes))))
}
}
impl From<CreddyError> for ErrorResponse {
fn from(e: CreddyError) -> ErrorResponse {
let message = e.to_string();
@@ -101,39 +130,48 @@ async fn handle(
app: AsyncApp,
) -> Result<Response<Full<Bytes>>, 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<Full<Bytes>> {
async fn handle_aws_get(uri: Uri, app: AsyncApp) -> Result<Response<Full<Bytes>>, 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::<CredentialResponse>();
app.update_global::<PendingRequests, _>(|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::<AppSession, _>(|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<Full<Bytes>> {
fn text(status: StatusCode, body: &str) -> Result<Response<Full<Bytes>>, CreddyError> {
let mut response = Response::new(Full::new(Bytes::from(body.to_owned())));
*response.status_mut() = status;
response
Ok(response)
}
+6 -1
View File
@@ -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
};
+24 -1
View File
@@ -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::<PendingRequests, _>(|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::<PendingRequests>().0.is_empty()));
assert!(is_visible(window, "credentials", cx));
}