Compare commits

...
7 Commits
Author SHA1 Message Date
jfmonty2 ce8727ee9a aws credential deletion 2026-11-20 06:18:06 -05:00
jfmonty2 21efa29fdd make aws credentials editable and refactor to hold name and id 2026-11-20 06:14:34 -05:00
jfmonty2 dbcf72fa38 color is_default switch when active 2026-11-20 05:25:38 -05:00
jfmonty2 c1186ad55e use a builder for PassphraseInput 2026-11-20 05:21:09 -05:00
jfmonty2 39b3f74068 adding aws credentials 2026-11-19 20:55:32 -05:00
jfmonty2 31edd55b0a add credentials screen 2026-11-19 20:26:56 -05:00
jfmonty2 b1c8762981 fix aws credential list test 2026-11-19 15:06:44 -05:00
15 changed files with 875 additions and 88 deletions

No files matched your search

Generated
+4 -2
View File
@@ -1447,6 +1447,7 @@ dependencies = [
"tempfile", "tempfile",
"testresult", "testresult",
"thiserror 2.0.21", "thiserror 2.0.21",
"uuid",
] ]
[[package]] [[package]]
@@ -1701,6 +1702,7 @@ dependencies = [
"libduckdb-sys", "libduckdb-sys",
"num-integer", "num-integer",
"strum 0.27.2", "strum 0.27.2",
"uuid",
] ]
[[package]] [[package]]
@@ -7967,9 +7969,9 @@ checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6"
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.29.0" version = "1.29.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64"
dependencies = [ dependencies = [
"getrandom 0.4.3", "getrandom 0.4.3",
"js-sys", "js-sys",
+2 -1
View File
@@ -12,7 +12,7 @@ edition = "2024"
argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] } argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] }
base64ct = "1.8.3" base64ct = "1.8.3"
dirs = "7.0.0" dirs = "7.0.0"
duckdb = { version = "1.20000.1", features = ["bundled"] } duckdb = { version = "1.20000.1", features = ["bundled", "uuid"] }
getrandom = { version = "0.4.3", features = ["sys_rng"] } getrandom = { version = "0.4.3", features = ["sys_rng"] }
gpui-kit = "0.7.0" gpui-kit = "0.7.0"
gpui-omarchy = "0.2.1" gpui-omarchy = "0.2.1"
@@ -22,6 +22,7 @@ serde = "1.0.229"
serde_json = "1.0.154" serde_json = "1.0.154"
testresult = "0.4.2" testresult = "0.4.2"
thiserror = "2.0.21" thiserror = "2.0.21"
uuid = { version = "1.29.3", features = ["v4", "serde"] }
[dev-dependencies] [dev-dependencies]
gpui-kit = { version = "0.7.0", features = ["test-support"] } gpui-kit = { version = "0.7.0", features = ["test-support"] }
+7 -5
View File
@@ -5,9 +5,11 @@ INSERT INTO config VALUES ('{}');
CREATE TABLE aws_credentials ( CREATE TABLE aws_credentials (
name VARCHAR PRIMARY KEY, id UUID PRIMARY KEY NOT NULL,
created_at TIMESTAMP WITH TIME ZONE, name VARCHAR UNIQUE NOT NULL,
updated_at TIMESTAMP WITH TIME ZONE, created_at TIMESTAMP WITH TIME ZONE NOT NULL,
access_key_id VARCHAR UNIQUE, updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
secret_access_key VARCHAR, access_key_id VARCHAR UNIQUE NOT NULL,
secret_access_key VARCHAR NOT NULL,
is_default BOOLEAN DEFAULT false
); );
+1 -1
View File
@@ -5,7 +5,7 @@ use gpui_kit::{AssetSource, Result, SharedString};
// gpui-kit only embeds the icons its own components use, so anything else has to be listed here // gpui-kit only embeds the icons its own components use, so anything else has to be listed here
icon_assets!(CreddyIcons, [LogOut, ShieldCheck]); icon_assets!(CreddyIcons, [Key, LogOut, Pencil, ShieldCheck, Trash]);
/// Our extra icons, falling back to gpui-kit's defaults. /// Our extra icons, falling back to gpui-kit's defaults.
pub struct CreddyAssets; pub struct CreddyAssets;
+54
View File
@@ -0,0 +1,54 @@
use gpui_kit::base::{Switch, SwitchThumb, SwitchTrack};
use gpui_kit::{
App, ElementId, Hsla, InteractiveElement, ParentElement, SharedString,
StatefulInteractiveElement, Styled, rems,
};
use gpui_omarchy::ActiveTheme;
/// gpui-omarchy's switch hard-codes its track and knob colors, so this rebuilds it
/// from the base parts in order to tint them with `color` when checked.
pub fn colored_switch(
id: impl Into<ElementId>,
label: impl Into<SharedString>,
checked: bool,
color: Hsla,
cx: &App,
) -> Switch {
let t = cx.omarchy();
let id = id.into();
let label = label.into();
Switch::new(id.clone())
.checked(checked)
.accessibility_label(label.clone())
.flex()
.items_center()
.gap(rems(0.5))
.p(rems(0.3125))
.border_1()
.border_color(t.foreground.opacity(0.))
.text_size(rems(0.75))
.hover(|s| s.bg(t.hover_fill()).border_color(t.focus_border()))
.focus_visible(|s| s.bg(t.hover_fill()).border_color(t.focus_border()))
.active(|s| s.bg(t.pressed_fill()))
.child(
SwitchTrack::new(id)
.checked(checked)
.w(rems(2.625))
.h(rems(1.375))
.flex_shrink_0()
.p(rems(0.125))
.border_1()
.border_color(if checked { color } else { t.control_border() })
.rounded_none()
.bg(if checked { color.opacity(0.18) } else { t.normal_fill() })
.child(
SwitchThumb::new(checked)
.size(rems(1.))
.rounded_none()
.bg(if checked { color } else { t.secondary })
.ml(rems(if checked { 1.25 } else { 0. })),
),
)
.child(label)
}
+2
View File
@@ -1,5 +1,7 @@
mod colored_switch;
mod error_alert; mod error_alert;
mod passphrase_input; mod passphrase_input;
pub use colored_switch::colored_switch;
pub use error_alert::error_alert; pub use error_alert::error_alert;
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent}; pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
+44 -9
View File
@@ -8,9 +8,6 @@ use gpui_omarchy::{ButtonVariant, icon_button, input};
/// A masked passphrase field with a show/hide toggle. /// A masked passphrase field with a show/hide toggle.
///
/// The `show` flag is passed in from outside so that it can be shared
/// (e.g. passphrase and confirm-passphrase inputs should share it).
pub struct PassphraseInput { pub struct PassphraseInput {
id: SharedString, id: SharedString,
state: Entity<InputState>, state: Entity<InputState>,
@@ -29,17 +26,43 @@ pub enum PassphraseInputEvent {
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {} impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
impl PassphraseInput { pub struct PassphraseInputBuilder {
pub fn new(id: impl Into<SharedString>, show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self { id: SharedString,
show: Option<Entity<bool>>,
placeholder: SharedString,
value: SharedString,
}
impl PassphraseInputBuilder {
/// Share the show/hide flag with other inputs (e.g. passphrase and confirm-passphrase).
pub fn show(mut self, show: Entity<bool>) -> Self {
self.show = Some(show);
self
}
pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
self.placeholder = placeholder.into();
self
}
pub fn value(mut self, value: impl Into<SharedString>) -> Self {
self.value = value.into();
self
}
pub fn build(self, window: &mut Window, cx: &mut App) -> Entity<PassphraseInput> {
let show = self.show.unwrap_or_else(|| cx.new(|_| false));
cx.new(|cx| {
let masked = !*show.read(cx); let masked = !*show.read(cx);
let state = cx.new(|cx| { let state = cx.new(|cx| {
InputState::new(window, cx) InputState::new(window, cx)
.masked(masked) .masked(masked)
.placeholder("correct horse battery staple") .placeholder(self.placeholder)
.default_value(self.value)
}); });
// keep this field's masking in sync with the shared flag // keep this field's masking in sync with the shared flag
let sync_mask = cx.observe_in(&show, window, |this, show, window, cx| { let sync_mask = cx.observe_in(&show, window, |this: &mut PassphraseInput, show, window, cx| {
let masked = !*show.read(cx); let masked = !*show.read(cx);
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx)); this.state.update(cx, |state, cx| state.set_masked(masked, window, cx));
cx.notify(); cx.notify();
@@ -56,12 +79,24 @@ impl PassphraseInput {
cx.emit(event); cx.emit(event);
}); });
Self { PassphraseInput {
id: id.into(), id: self.id,
state, state,
show, show,
_subscriptions: vec![sync_mask, forward], _subscriptions: vec![sync_mask, forward],
} }
})
}
}
impl PassphraseInput {
pub fn builder(id: impl Into<SharedString>) -> PassphraseInputBuilder {
PassphraseInputBuilder {
id: id.into(),
show: None,
placeholder: SharedString::default(),
value: SharedString::default(),
}
} }
pub fn value(&self, cx: &App) -> SharedString { pub fn value(&self, cx: &App) -> SharedString {
+6 -2
View File
@@ -1,13 +1,17 @@
use jiff::Timestamp; use jiff::Timestamp;
use serde::{Serialize, Deserialize}; use serde::{Serialize, Deserialize};
use uuid::Uuid;
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct AwsCredential { pub struct AwsCredential {
pub id: Uuid,
pub name: String,
pub access_key_id: String, pub access_key_id: String,
pub secret_access_key: String, pub secret_access_key: String,
pub is_default: bool,
} }
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AwsSessionCredential { pub struct AwsSessionCredential {
pub version: usize, pub version: usize,
pub access_key_id: String, pub access_key_id: String,
+145 -60
View File
@@ -1,5 +1,5 @@
use std::collections::HashMap;
use duckdb::{Error, params}; use duckdb::{Error, params};
use uuid::Uuid;
use crate::credentials::AwsCredential; use crate::credentials::AwsCredential;
use super::Db; use super::Db;
@@ -7,46 +7,84 @@ impl Db {
pub fn load_aws_credential(&self, name: &str) -> Result<AwsCredential, Error> { pub fn load_aws_credential(&self, name: &str) -> Result<AwsCredential, Error> {
let conn = self.connection.lock().unwrap(); let conn = self.connection.lock().unwrap();
conn.query_row( conn.query_row(
"SELECT access_key_id, secret_access_key FROM aws_credentials WHERE name = ?", "SELECT
id,
name,
access_key_id,
secret_access_key,
is_default
FROM aws_credentials
WHERE name = ?",
params![name], params![name],
|row| Ok(AwsCredential { access_key_id: row.get(0)?, secret_access_key: row.get(1)? }) |row| Ok(AwsCredential {
id: row.get(0)?,
name: row.get(1)?,
access_key_id: row.get(2)?,
secret_access_key: row.get(3)?,
is_default: row.get(4)?,
})
) )
} }
pub fn save_aws_credential(&self, name: &str, cred: &AwsCredential) -> Result<(), Error> { pub fn save_aws_credential(&self, cred: &AwsCredential) -> Result<(), Error> {
let conn = self.connection.lock().unwrap(); let mut conn = self.connection.lock().unwrap();
let _ = conn.execute( let tx = conn.transaction()?;
if cred.is_default {
tx.execute(
"UPDATE aws_credentials SET is_default = false WHERE is_default AND id != ?",
params![cred.id],
)?;
}
tx.execute(
"INSERT INTO aws_credentials ( "INSERT INTO aws_credentials (
id,
name, name,
created_at, created_at,
updated_at, updated_at,
access_key_id, access_key_id,
secret_access_key, secret_access_key,
is_default,
) )
VALUES (?, now(), now(), ?, ?) VALUES (?, ?, now(), now(), ?, ?, ?)
ON CONFLICT (name) DO UPDATE ON CONFLICT (id) DO UPDATE
SET SET
name = EXCLUDED.name,
updated_at = now(), updated_at = now(),
access_key_id = EXCLUDED.access_key_id, access_key_id = EXCLUDED.access_key_id,
secret_access_key = EXCLUDED.secret_access_key", secret_access_key = EXCLUDED.secret_access_key,
params![name, cred.access_key_id, cred.secret_access_key], is_default = EXCLUDED.is_default",
params![cred.id, cred.name, cred.access_key_id, cred.secret_access_key, cred.is_default],
)?; )?;
tx.commit()
}
pub fn delete_aws_credential(&self, id: Uuid) -> Result<(), Error> {
let conn = self.connection.lock().unwrap();
conn.execute("DELETE FROM aws_credentials WHERE id = ?", params![id])?;
Ok(()) Ok(())
} }
pub fn list_aws_credentials(&self) -> Result<HashMap<String, AwsCredential>, Error> { pub fn list_aws_credentials(&self) -> Result<Vec<AwsCredential>, Error> {
let conn = self.connection.lock().unwrap(); let conn = self.connection.lock().unwrap();
let mut stmt = conn.prepare("SELECT name, access_key_id, secret_access_key FROM aws_credentials")?; let mut stmt = conn.prepare(
let rows = stmt.query_map([], |row| { "SELECT
let key: String = row.get(0)?; id,
let cred = AwsCredential{ name,
access_key_id: row.get(1)?, access_key_id,
secret_access_key: row.get(2)?, secret_access_key,
}; is_default
Ok((key, cred)) FROM aws_credentials
})?; ORDER BY created_at"
)?;
rows.collect() stmt.query_map([], |row| {
Ok(AwsCredential{
id: row.get(0)?,
name: row.get(1)?,
access_key_id: row.get(2)?,
secret_access_key: row.get(3)?,
is_default: row.get(4)?,
})
})?.collect()
} }
} }
@@ -56,16 +94,22 @@ mod tests {
use crate::test_data::TestEnv; use crate::test_data::TestEnv;
use super::*; use super::*;
fn test_cred(name: &str, access_key_id: &str) -> AwsCredential {
AwsCredential {
id: Uuid::new_v4(),
name: name.into(),
access_key_id: access_key_id.into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
}
}
#[test] #[test]
fn test_save() -> TestResult { fn test_save() -> TestResult {
let env = TestEnv::new()?; let env = TestEnv::new()?;
let db = env.db()?; let db = env.db()?;
let cred = AwsCredential { db.save_aws_credential(&test_cred("test", "AKIAEXAMPLE"))?;
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
};
db.save_aws_credential("test", &cred)?;
Ok(()) Ok(())
} }
@@ -74,16 +118,12 @@ mod tests {
let env = TestEnv::new()?; let env = TestEnv::new()?;
let db = env.db()?; let db = env.db()?;
let cred = AwsCredential { let cred = test_cred("test", "AKIAEXAMPLE");
access_key_id: "AKIAEXAMPLE".into(), db.save_aws_credential(&cred)?;
secret_access_key: "EXAMPLESECRET".into(),
};
db.save_aws_credential("test", &cred)?;
let loaded = db.load_aws_credential("test")?; let loaded = db.load_aws_credential("test")?;
assert_eq!(loaded.access_key_id, cred.access_key_id); assert_eq!(loaded, cred);
assert_eq!(loaded.secret_access_key, cred.secret_access_key);
Ok(()) Ok(())
} }
@@ -92,22 +132,23 @@ mod tests {
let env = TestEnv::new()?; let env = TestEnv::new()?;
let db = env.db()?; let db = env.db()?;
let mut cred = AwsCredential { let mut cred = test_cred("test", "KEY1");
access_key_id: "KEY1".into(), db.save_aws_credential(&cred)?;
secret_access_key: "EXAMPLESECRET".into(),
};
db.save_aws_credential("test", &cred)?;
cred.name = "renamed".into();
cred.access_key_id = "KEY2".into(); cred.access_key_id = "KEY2".into();
db.save_aws_credential("test", &cred)?; db.save_aws_credential(&cred)?;
let loaded = db.load_aws_credential("test")?; let creds = db.list_aws_credentials()?;
assert_eq!(loaded.access_key_id, "KEY2"); assert_eq!(creds.len(), 1);
assert_eq!(creds[0].id, cred.id);
assert_eq!(creds[0].name, "renamed");
assert_eq!(creds[0].access_key_id, "KEY2");
// confirm that updated_at was modified, but not created_at // confirm that updated_at was modified, but not created_at
let conn = db.connection.lock().unwrap(); let conn = db.connection.lock().unwrap();
let (created_at, updated_at): (i64, i64) = conn.query_row( let (created_at, updated_at): (i64, i64) = conn.query_row(
"SELECT created_at, updated_at FROM aws_credentials WHERE name = 'test'", "SELECT created_at, updated_at FROM aws_credentials WHERE name = 'renamed'",
[], [],
|row| Ok((row.get(0)?, row.get(1)?)) |row| Ok((row.get(0)?, row.get(1)?))
)?; )?;
@@ -116,32 +157,76 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn test_duplicate_name() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
db.save_aws_credential(&test_cred("test", "KEY1"))?;
assert!(db.save_aws_credential(&test_cred("test", "KEY2")).is_err());
Ok(())
}
#[test] #[test]
fn test_list() -> TestResult { fn test_list() -> TestResult {
let env = TestEnv::new()?; let env = TestEnv::new()?;
let db = env.db()?; let db = env.db()?;
let cred1 = AwsCredential { // names are out of alphabetical order, since the list should be in order of creation
access_key_id: "KEY1".into(), let cred1 = test_cred("test2", "KEY1");
secret_access_key: "EXAMPLESECRET".into(), db.save_aws_credential(&cred1)?;
}; let cred2 = test_cred("test1", "KEY2");
db.save_aws_credential("test", &cred1)?; db.save_aws_credential(&cred2)?;
let cred2 = AwsCredential {
access_key_id: "KEY2".into(),
secret_access_key: "EXAMPLESECRET2".into(),
};
db.save_aws_credential("test2", &cred2)?;
let creds = db.list_aws_credentials()?; let creds = db.list_aws_credentials()?;
assert_eq!(creds.len(), 2);
assert_eq!(creds[0], cred1);
assert_eq!(creds[1], cred2);
let loaded1 = creds.get("test").unwrap(); Ok(())
assert_eq!(loaded1.access_key_id, cred1.access_key_id); }
assert_eq!(loaded1.secret_access_key, cred1.secret_access_key);
let loaded2 = creds.get("test").unwrap(); #[test]
assert_eq!(loaded2.access_key_id, cred1.access_key_id); fn test_delete() -> TestResult {
assert_eq!(loaded2.secret_access_key, cred1.secret_access_key); let env = TestEnv::new()?;
let db = env.db()?;
let cred1 = test_cred("test", "KEY1");
db.save_aws_credential(&cred1)?;
let cred2 = test_cred("test2", "KEY2");
db.save_aws_credential(&cred2)?;
db.delete_aws_credential(cred1.id)?;
let creds = db.list_aws_credentials()?;
assert_eq!(creds.len(), 1);
assert_eq!(creds[0].id, cred2.id);
Ok(())
}
#[test]
fn test_change_default() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
let mut cred1 = test_cred("test", "KEY1");
cred1.is_default = true;
db.save_aws_credential(&cred1)?;
let mut cred2 = test_cred("test2", "KEY2");
cred2.is_default = true;
db.save_aws_credential(&cred2)?;
assert!(!db.load_aws_credential("test")?.is_default);
assert!(db.load_aws_credential("test2")?.is_default);
// re-saving the current default shouldn't trip over its own row
db.save_aws_credential(&cred2)?;
assert!(db.load_aws_credential("test2")?.is_default);
db.save_aws_credential(&cred1)?;
assert!(db.load_aws_credential("test")?.is_default);
assert!(!db.load_aws_credential("test2")?.is_default);
Ok(()) Ok(())
} }
+210 -2
View File
@@ -18,7 +18,7 @@ mod test_data;
use config::AppConfig; use config::AppConfig;
use session::AppSession; use session::AppSession;
use screens::{HomeScreen, UnlockScreen, WelcomeScreen}; use screens::{CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen};
struct CreddyApp {} struct CreddyApp {}
@@ -34,9 +34,14 @@ impl Render for CreddyApp {
AppSession::Locked => window AppSession::Locked => window
.use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx)) .use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx))
.into_any_element(), .into_any_element(),
AppSession::Unlocked { .. } => window AppSession::Unlocked { .. } => match cx.global::<Screen>() {
Screen::Home => window
.use_keyed_state("home", cx, |_, _| HomeScreen {}) .use_keyed_state("home", cx, |_, _| HomeScreen {})
.into_any_element(), .into_any_element(),
Screen::Credentials => window
.use_keyed_state("credentials", cx, |_, cx| CredentialsScreen::new(cx))
.into_any_element(),
},
}; };
let theme = cx.omarchy(); let theme = cx.omarchy();
@@ -54,10 +59,12 @@ fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle<
gpui_omarchy::init(cx); gpui_omarchy::init(cx);
cx.set_global(config); cx.set_global(config);
cx.set_global(session); cx.set_global(session);
cx.set_global(Screen::Home);
// refresh_windows() forces everything to re-render, which is kind of a nuclear solution, // refresh_windows() forces everything to re-render, which is kind of a nuclear solution,
// but these values aren't expected to change very frequently, so it shouldn't be a problem // but these values aren't expected to change very frequently, so it shouldn't be a problem
cx.observe_global::<AppConfig>(|cx| cx.refresh_windows()).detach(); cx.observe_global::<AppConfig>(|cx| cx.refresh_windows()).detach();
cx.observe_global::<AppSession>(|cx| cx.refresh_windows()).detach(); cx.observe_global::<AppSession>(|cx| cx.refresh_windows()).detach();
cx.observe_global::<Screen>(|cx| cx.refresh_windows()).detach();
cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {})) cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window") .expect("open window")
@@ -82,7 +89,9 @@ fn main() {
mod tests { mod tests {
use gpui_kit::{AnyWindowHandle, TestAppContext}; use gpui_kit::{AnyWindowHandle, TestAppContext};
use gpui_kit::test::TestWindowExt; use gpui_kit::test::TestWindowExt;
use uuid::Uuid;
use super::*; use super::*;
use crate::credentials::AwsCredential;
use crate::test_data::{TEST_PASSPHRASE, TestEnv}; use crate::test_data::{TEST_PASSPHRASE, TestEnv};
/// Start the app against the test environment, as `main` would. /// Start the app against the test environment, as `main` would.
@@ -225,4 +234,203 @@ mod tests {
assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty.")); assert_eq!(error_message(window, cx).as_deref(), Some("Passphrase is empty."));
assert!(!is_unlocked(cx)); assert!(!is_unlocked(cx));
} }
fn is_visible(window: AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) -> bool {
cx.update_window(window, |_, window, _| window.try_find(id).is_some()).unwrap()
}
#[gpui_kit::test]
fn test_credentials_navigation(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);
click(window, "credentials", cx);
assert_eq!(cx.read(|cx| *cx.global::<Screen>()), Screen::Credentials);
assert!(is_visible(window, "back", cx));
click(window, "back", cx);
assert_eq!(cx.read(|cx| *cx.global::<Screen>()), Screen::Home);
assert!(is_visible(window, "credentials", cx));
}
#[gpui_kit::test]
fn test_credentials_tabs(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let cred = AwsCredential {
id: Uuid::new_v4(),
name: "work".into(),
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
};
env.db().unwrap().save_aws_credential(&cred).unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
click(window, "credentials", cx);
assert!(is_visible(window, "work", cx));
act(window, cx, |window, cx| window.within("credential-tabs").click(1usize, cx));
assert!(!is_visible(window, "work", cx));
act(window, cx, |window, cx| window.within("credential-tabs").click(0usize, cx));
assert!(is_visible(window, "work", cx));
}
#[gpui_kit::test]
fn test_add_aws_credential(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);
click(window, "credentials", cx);
click(window, "aws-add", cx);
fill(window, "aws-name", "work", cx);
fill(window, "aws-key-id", "AKIAEXAMPLE", cx);
fill(window, "aws-secret", "EXAMPLESECRET", cx);
click(window, "aws-default", cx);
click(window, "aws-save", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_visible(window, "work", cx));
assert!(!is_visible(window, "aws-save", cx));
let saved = cx.read(|cx| {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else { panic!("locked") };
db.load_aws_credential("work").unwrap()
});
assert_eq!(saved.access_key_id, "AKIAEXAMPLE");
assert_eq!(saved.secret_access_key, "EXAMPLESECRET");
assert!(saved.is_default);
}
#[gpui_kit::test]
fn test_add_aws_credential_missing_fields(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);
click(window, "credentials", cx);
click(window, "aws-add", cx);
fill(window, "aws-name", "work", cx);
click(window, "aws-save", cx);
assert_eq!(error_message(window, cx).as_deref(), Some("All fields are required."));
assert!(!is_visible(window, "work", cx));
}
#[gpui_kit::test]
fn test_add_aws_credential_duplicate_name(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let cred = AwsCredential {
id: Uuid::new_v4(),
name: "work".into(),
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
};
env.db().unwrap().save_aws_credential(&cred).unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
click(window, "credentials", cx);
click(window, "aws-add", cx);
fill(window, "aws-name", "work", cx);
fill(window, "aws-key-id", "AKIAOTHER", cx);
fill(window, "aws-secret", "OTHERSECRET", cx);
click(window, "aws-save", cx);
assert_eq!(
error_message(window, cx).as_deref(),
Some("An AWS credential named \"work\" already exists."),
);
let saved = cx.read(|cx| {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else { panic!("locked") };
db.load_aws_credential("work").unwrap()
});
assert_eq!(saved.access_key_id, "AKIAEXAMPLE");
}
#[gpui_kit::test]
fn test_edit_aws_credential(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let cred = AwsCredential {
id: Uuid::new_v4(),
name: "work".into(),
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
};
env.db().unwrap().save_aws_credential(&cred).unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
click(window, "credentials", cx);
click(window, "edit-work", cx);
act(window, cx, |window, cx| {
window.click("aws-name", cx);
window.press("ctrl-a", cx);
window.input("personal", cx);
});
click(window, "aws-default", cx);
click(window, "aws-save", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_visible(window, "personal", cx));
assert!(!is_visible(window, "work", cx));
let creds = cx.read(|cx| {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else { panic!("locked") };
db.list_aws_credentials().unwrap()
});
assert_eq!(creds.len(), 1);
// fields that weren't touched keep the values the form was opened with
assert_eq!(creds[0].id, cred.id);
assert_eq!(creds[0].name, "personal");
assert_eq!(creds[0].access_key_id, "AKIAEXAMPLE");
assert_eq!(creds[0].secret_access_key, "EXAMPLESECRET");
assert!(creds[0].is_default);
}
#[gpui_kit::test]
fn test_delete_aws_credential(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let cred = AwsCredential {
id: Uuid::new_v4(),
name: "work".into(),
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
};
env.db().unwrap().save_aws_credential(&cred).unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
click(window, "credentials", cx);
click(window, "delete-work", cx);
click(window, "aws-delete-cancel", cx);
assert!(is_visible(window, "work", cx));
click(window, "delete-work", cx);
click(window, "aws-delete-confirm", cx);
assert_eq!(error_message(window, cx), None);
assert!(!is_visible(window, "work", cx));
let creds = cx.read(|cx| {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else { panic!("locked") };
db.list_aws_credentials().unwrap()
});
assert!(creds.is_empty());
}
} }
+370
View File
@@ -0,0 +1,370 @@
use gpui_kit::base::input::{InputEvent, InputState};
use gpui_kit::{
AppContext, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement,
Render, SharedString, Styled, Subscription, TestSupportExt, Window, div, rems,
};
use gpui_omarchy::{
ActiveTheme, ButtonVariant, ChoiceItem, IconName, Status, badge, button, empty_state,
focus_scope, icon_button, input, tab_list,
};
use crate::components::{PassphraseInput, PassphraseInputEvent, colored_switch, error_alert};
use crate::credentials::AwsCredential;
use crate::session::AppSession;
use super::Screen;
use uuid::Uuid;
pub struct CredentialsScreen {
tab: usize,
aws: Vec<AwsCredential>,
aws_form: Option<AwsForm>,
/// The id of the credential awaiting delete confirmation.
aws_deleting: Option<Uuid>,
error: Option<SharedString>,
}
struct AwsForm {
/// The id of the credential being edited, or None if this is a new one.
editing: Option<Uuid>,
name: Entity<InputState>,
access_key_id: Entity<InputState>,
secret_access_key: Entity<PassphraseInput>,
is_default: bool,
_subscriptions: Vec<Subscription>,
}
impl CredentialsScreen {
pub fn new(cx: &mut Context<Self>) -> Self {
let mut this = Self { tab: 0, aws: Vec::new(), aws_form: None, aws_deleting: None, error: None };
this.load_aws(cx);
this
}
fn load_aws(&mut self, cx: &mut Context<Self>) {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else {
unreachable!("credentials screen is only shown while unlocked");
};
match db.list_aws_credentials() {
Ok(creds) => {
self.aws = creds;
self.error = None;
},
Err(e) => self.error = Some(format!("Failed to load credentials: {e}").into()),
}
}
fn open_aws_form(&mut self, editing: Option<Uuid>, window: &mut Window, cx: &mut Context<Self>) {
let existing = self.aws
.iter()
.find(|cred| Some(cred.id) == editing)
.cloned()
.unwrap_or_default();
let name = cx.new(|cx| InputState::new(window, cx).default_value(existing.name));
let access_key_id = cx.new(|cx| InputState::new(window, cx).default_value(existing.access_key_id));
let secret_access_key = PassphraseInput::builder("aws-secret")
.value(existing.secret_access_key)
.build(window, cx);
name.update(cx, |name, cx| name.focus(window, cx));
let mut _subscriptions = Vec::new();
for input in [&name, &access_key_id] {
_subscriptions.push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
if let InputEvent::PressEnter { .. } = event {
this.save_aws(cx);
}
}));
}
_subscriptions.push(cx.subscribe(&secret_access_key, |this, _, event, cx| {
if let PassphraseInputEvent::Submit = event {
this.save_aws(cx);
}
}));
self.aws_form = Some(AwsForm {
editing,
name,
access_key_id,
secret_access_key,
is_default: existing.is_default,
_subscriptions,
});
self.error = None;
cx.notify();
}
fn save_aws(&mut self, cx: &mut Context<Self>) {
let Some(form) = &self.aws_form else { return };
let editing = form.editing;
let cred = AwsCredential {
id: editing.unwrap_or_else(Uuid::new_v4),
name: form.name.read(cx).value().trim().to_string(),
access_key_id: form.access_key_id.read(cx).value().trim().to_string(),
secret_access_key: form.secret_access_key.read(cx).value(cx).trim().to_string(),
is_default: form.is_default,
};
if cred.name.is_empty() || cred.access_key_id.is_empty() || cred.secret_access_key.is_empty() {
self.error = Some("All fields are required.".into());
cx.notify();
return;
}
if self.aws.iter().any(|existing| existing.name == cred.name && existing.id != cred.id) {
self.error = Some(format!("An AWS credential named \"{}\" already exists.", cred.name).into());
cx.notify();
return;
}
let AppSession::Unlocked(db) = cx.global::<AppSession>() else {
unreachable!("credentials screen is only shown while unlocked");
};
match db.save_aws_credential(&cred) {
Ok(()) => {
self.aws_form = None;
self.load_aws(cx);
},
Err(e) => self.error = Some(format!("Failed to save credential: {e}").into()),
}
cx.notify();
}
fn delete_aws(&mut self, id: Uuid, cx: &mut Context<Self>) {
let AppSession::Unlocked(db) = cx.global::<AppSession>() else {
unreachable!("credentials screen is only shown while unlocked");
};
match db.delete_aws_credential(id) {
Ok(()) => {
self.aws_deleting = None;
self.load_aws(cx);
},
Err(e) => self.error = Some(format!("Failed to delete credential: {e}").into()),
}
cx.notify();
}
fn render_aws_tab(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
let t = cx.omarchy().clone();
let mut panel = div().flex().flex_col().gap(rems(0.5));
if self.aws.is_empty() {
panel = panel.child(empty_state("AWS access keys", "You have no saved AWS credentials.", cx));
}
for cred in &self.aws {
if let Some(form) = &self.aws_form
&& form.editing == Some(cred.id)
{
panel = panel.child(self.render_aws_form(form, window, cx));
continue;
}
let id = cred.id;
if self.aws_deleting == Some(id) {
panel = panel.child(
div()
.flex()
.items_center()
.gap(rems(0.5))
.p(rems(0.625))
.border_1()
.border_color(t.danger)
.child(format!("Delete AWS credential \"{}\"?", cred.name))
.child(
button("aws-delete-cancel", "Cancel", ButtonVariant::Outline, cx)
.ml_auto()
.on_click(cx.listener(|this, _, _, cx| {
this.aws_deleting = None;
cx.notify();
})),
)
.child(
button("aws-delete-confirm", "Delete", ButtonVariant::Danger, cx)
.on_click(cx.listener(move |this, _, _, cx| this.delete_aws(id, cx))),
),
);
continue;
}
panel = panel.child(
div()
.id(SharedString::from(&cred.name))
.test_support()
.flex()
.items_center()
.gap(rems(0.75))
.p(rems(0.625))
.border_1()
.border_color(if cred.is_default { t.accent } else { t.border })
.child(div().font_weight(FontWeight::BOLD).child(cred.name.clone()))
.children(cred.is_default.then(|| badge("Default", Status::Success, cx)))
.child(
div()
.ml_auto()
.font_family(t.mono_font.clone())
.text_color(t.secondary)
.child(cred.access_key_id.clone()),
)
.child(
icon_button(
SharedString::from(format!("edit-{}", cred.name)),
IconName::Pencil,
"Edit",
ButtonVariant::Outline,
cx,
)
.on_click(cx.listener(move |this, _, window, cx| {
this.open_aws_form(Some(id), window, cx)
})),
)
.child(
icon_button(
SharedString::from(format!("delete-{}", cred.name)),
IconName::Trash,
"Delete",
ButtonVariant::Danger,
cx,
)
.on_click(cx.listener(move |this, _, _, cx| {
this.aws_deleting = Some(id);
cx.notify();
})),
),
);
}
match &self.aws_form {
None => panel.child(
button("aws-add", "Add", ButtonVariant::Primary, cx)
.self_center()
.mt(rems(0.5))
.on_click(cx.listener(|this, _, window, cx| this.open_aws_form(None, window, cx))),
),
Some(form) if form.editing.is_none() => panel.child(self.render_aws_form(form, window, cx)),
Some(_) => panel,
}
}
fn render_aws_form(&self, form: &AwsForm, window: &mut Window, cx: &mut Context<Self>) -> Div {
let t = cx.omarchy().clone();
let field = |label: &'static str, input: gpui_kit::AnyElement| {
div()
.flex()
.flex_col()
.gap(rems(0.25))
.child(div().text_size(rems(0.875)).child(label))
.child(input)
};
let this = cx.entity();
div()
.flex()
.flex_col()
.gap(rems(1.))
.p(rems(1.))
.border_1()
.border_color(t.border)
.child(field("Name", input("aws-name", &form.name, window, cx).into_any_element()))
.child(field(
"Key ID",
input("aws-key-id", &form.access_key_id, window, cx)
.font_family(t.mono_font.clone())
.into_any_element(),
))
.child(field("Secret key", form.secret_access_key.clone().into_any_element()))
.child(
div()
.flex()
.items_center()
.gap(rems(0.5))
.child(
colored_switch("aws-default", "Default AWS access key", form.is_default, t.success, cx)
.on_change(move |value, _, _, cx| this.update(cx, |this, cx| {
if let Some(form) = &mut this.aws_form {
form.is_default = value;
}
cx.notify();
})),
)
.child(
button("aws-cancel", "Cancel", ButtonVariant::Outline, cx)
.ml_auto()
.on_click(cx.listener(|this, _, _, cx| {
this.aws_form = None;
this.error = None;
cx.notify();
})),
)
.child(
button("aws-save", "Save", ButtonVariant::Primary, cx)
.on_click(cx.listener(|this, _, _, cx| this.save_aws(cx))),
),
)
}
}
impl Render for CredentialsScreen {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let this = cx.entity();
let tabs = tab_list(
"credential-tabs",
vec![
ChoiceItem::new("aws", "AWS"),
ChoiceItem::new("ssh", "SSH"),
ChoiceItem::new("docker", "Docker"),
],
Some(self.tab),
false,
move |index, _, cx| this.update(cx, |this, cx| {
this.tab = index;
cx.notify();
}),
window,
cx,
);
let panel = match self.tab {
0 => self.render_aws_tab(window, cx),
1 => empty_state("SSH keys", "Not implemented yet.", cx),
_ => empty_state("Docker credentials", "Not implemented yet.", cx),
};
focus_scope("credentials-screen")
.size_full()
.flex()
.flex_col()
.items_center()
.gap(rems(1.))
.p(rems(0.5))
.child(
div()
.relative()
.w_full()
.flex()
.justify_center()
.child(
icon_button("back", IconName::ChevronLeft, "Back", ButtonVariant::Secondary, cx)
.absolute()
.left_0()
.on_click(|_, _, cx| cx.set_global(Screen::Home)),
)
.child(
div()
.text_size(rems(1.875))
.font_weight(FontWeight::BOLD)
.child("Credentials"),
),
)
.child(tabs)
.child(
div()
.w_full()
.max_w(rems(36.))
.flex()
.flex_col()
.gap(rems(1.))
.children(self.error.clone().map(|e| error_alert(e, cx)))
.child(panel),
)
}
}
+4
View File
@@ -6,6 +6,7 @@ use gpui_kit::{
use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon}; use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon};
use crate::session::AppSession; use crate::session::AppSession;
use super::Screen;
pub struct HomeScreen {} pub struct HomeScreen {}
@@ -13,6 +14,8 @@ pub struct HomeScreen {}
impl Render for HomeScreen { impl Render for HomeScreen {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let t = cx.omarchy(); let t = cx.omarchy();
let credentials = nav_tile("credentials", IconName::Key, "Credentials", "Add, remove, and change credentials.", t.success, cx)
.on_click(|_, _, cx| cx.set_global(Screen::Credentials));
let lock = nav_tile("lock", IconName::ShieldCheck, "Lock", "Lock Creddy.", t.warning, cx) let lock = nav_tile("lock", IconName::ShieldCheck, "Lock", "Lock Creddy.", t.warning, cx)
.on_click(|_, _, cx| cx.set_global(AppSession::Locked)); .on_click(|_, _, cx| cx.set_global(AppSession::Locked));
let exit = nav_tile("exit", IconName::LogOut, "Exit", "Close Creddy.", t.accent, cx) let exit = nav_tile("exit", IconName::LogOut, "Exit", "Close Creddy.", t.accent, cx)
@@ -37,6 +40,7 @@ impl Render for HomeScreen {
.flex() .flex()
.items_center() .items_center()
.gap(rems(1.5)) .gap(rems(1.5))
.child(credentials)
.child(lock) .child(lock)
.child(exit), .child(exit),
) )
+14
View File
@@ -1,7 +1,21 @@
use gpui_kit::Global;
mod credentials;
mod home; mod home;
mod unlock; mod unlock;
mod welcome; mod welcome;
pub use credentials::CredentialsScreen;
pub use home::HomeScreen; pub use home::HomeScreen;
pub use unlock::UnlockScreen; pub use unlock::UnlockScreen;
pub use welcome::WelcomeScreen; pub use welcome::WelcomeScreen;
/// Which screen to show while the app is unlocked.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
Home,
Credentials,
}
impl Global for Screen {}
+3 -3
View File
@@ -22,9 +22,9 @@ pub struct UnlockScreen {
impl UnlockScreen { impl UnlockScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
// nothing else shares the show/hide flag, so it's private to this input let passphrase = PassphraseInput::builder("passphrase")
let show = cx.new(|_| false); .placeholder("correct horse battery staple")
let passphrase = cx.new(|cx| PassphraseInput::new("passphrase", show, window, cx)); .build(window, cx);
passphrase.update(cx, |input, cx| input.focus(window, cx)); passphrase.update(cx, |input, cx| input.focus(window, cx));
let submit = cx.subscribe_in(&passphrase, window, |this, _, event, window, cx| { let submit = cx.subscribe_in(&passphrase, window, |this, _, event, window, cx| {
+9 -3
View File
@@ -26,8 +26,14 @@ pub struct WelcomeScreen {
impl WelcomeScreen { impl WelcomeScreen {
pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self { pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
let show = cx.new(|_| false); let show = cx.new(|_| false);
let passphrase = cx.new(|cx| PassphraseInput::new("passphrase", show.clone(), window, cx)); let passphrase = PassphraseInput::builder("passphrase")
let confirm = cx.new(|cx| PassphraseInput::new("confirm", show, window, cx)); .show(show.clone())
.placeholder("correct horse battery staple")
.build(window, cx);
let confirm = PassphraseInput::builder("confirm")
.show(show)
.placeholder("correct horse battery staple")
.build(window, cx);
passphrase.update(cx, |input, cx| input.focus(window, cx)); passphrase.update(cx, |input, cx| input.focus(window, cx));
let mut _subscriptions = Vec::new(); let mut _subscriptions = Vec::new();
@@ -86,7 +92,7 @@ impl WelcomeScreen {
let config = cx.global::<AppConfig>().clone(); let config = cx.global::<AppConfig>().clone();
self.error = None; self.error = None;
// todo: persist the salt (and KDF params) so the database can be unlocked again later // todo: persist the KDF params alongside the salt, so the database can still be unlocked if they change
self.pending = Some(cx.spawn(async move |this, cx| { self.pending = Some(cx.spawn(async move |this, cx| {
// argon2 is deliberately slow, so keep it off the UI thread // argon2 is deliberately slow, so keep it off the UI thread
let result = cx let result = cx