diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql index d39d679..e6d4610 100644 --- a/migrations/001_initial.sql +++ b/migrations/001_initial.sql @@ -5,9 +5,10 @@ INSERT INTO config VALUES ('{}'); CREATE TABLE aws_credentials ( - name VARCHAR PRIMARY KEY, - created_at TIMESTAMP WITH TIME ZONE, - updated_at TIMESTAMP WITH TIME ZONE, - access_key_id VARCHAR UNIQUE, - secret_access_key VARCHAR, + name VARCHAR PRIMARY KEY NOT NULL, + created_at TIMESTAMP WITH TIME ZONE NOT NULL, + updated_at TIMESTAMP WITH TIME ZONE NOT NULL, + access_key_id VARCHAR UNIQUE NOT NULL, + secret_access_key VARCHAR NOT NULL, + is_default BOOLEAN DEFAULT false ); diff --git a/src/credentials/aws.rs b/src/credentials/aws.rs index 5b8ffce..5228044 100644 --- a/src/credentials/aws.rs +++ b/src/credentials/aws.rs @@ -5,6 +5,7 @@ use serde::{Serialize, Deserialize}; pub struct AwsCredential { pub access_key_id: String, pub secret_access_key: String, + pub is_default: bool, } #[derive(Clone, Debug, Serialize, Deserialize)] diff --git a/src/db/aws.rs b/src/db/aws.rs index c296752..281daab 100644 --- a/src/db/aws.rs +++ b/src/db/aws.rs @@ -7,41 +7,55 @@ impl Db { pub fn load_aws_credential(&self, name: &str) -> Result { let conn = self.connection.lock().unwrap(); conn.query_row( - "SELECT access_key_id, secret_access_key FROM aws_credentials WHERE name = ?", + "SELECT access_key_id, secret_access_key, is_default FROM aws_credentials WHERE name = ?", params![name], - |row| Ok(AwsCredential { access_key_id: row.get(0)?, secret_access_key: row.get(1)? }) + |row| Ok(AwsCredential { + access_key_id: row.get(0)?, + secret_access_key: row.get(1)?, + is_default: row.get(2)?, + }) ) } pub fn save_aws_credential(&self, name: &str, cred: &AwsCredential) -> Result<(), Error> { - let conn = self.connection.lock().unwrap(); - let _ = conn.execute( + let mut conn = self.connection.lock().unwrap(); + let tx = conn.transaction()?; + if cred.is_default { + tx.execute( + "UPDATE aws_credentials SET is_default = false WHERE is_default AND name != ?", + params![name], + )?; + } + tx.execute( "INSERT INTO aws_credentials ( name, created_at, updated_at, access_key_id, secret_access_key, + is_default, ) - VALUES (?, now(), now(), ?, ?) + VALUES (?, now(), now(), ?, ?, ?) ON CONFLICT (name) DO UPDATE SET updated_at = now(), access_key_id = EXCLUDED.access_key_id, - secret_access_key = EXCLUDED.secret_access_key", - params![name, cred.access_key_id, cred.secret_access_key], + secret_access_key = EXCLUDED.secret_access_key, + is_default = EXCLUDED.is_default", + params![name, cred.access_key_id, cred.secret_access_key, cred.is_default], )?; - Ok(()) + tx.commit() } pub fn list_aws_credentials(&self) -> Result, Error> { 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("SELECT name, access_key_id, secret_access_key, is_default FROM aws_credentials")?; let rows = stmt.query_map([], |row| { let key: String = row.get(0)?; let cred = AwsCredential{ access_key_id: row.get(1)?, secret_access_key: row.get(2)?, + is_default: row.get(3)?, }; Ok((key, cred)) })?; @@ -64,6 +78,7 @@ mod tests { let cred = AwsCredential { access_key_id: "AKIAEXAMPLE".into(), secret_access_key: "EXAMPLESECRET".into(), + is_default: false, }; db.save_aws_credential("test", &cred)?; Ok(()) @@ -77,6 +92,7 @@ mod tests { let cred = AwsCredential { access_key_id: "AKIAEXAMPLE".into(), secret_access_key: "EXAMPLESECRET".into(), + is_default: false, }; db.save_aws_credential("test", &cred)?; @@ -95,6 +111,7 @@ mod tests { let mut cred = AwsCredential { access_key_id: "KEY1".into(), secret_access_key: "EXAMPLESECRET".into(), + is_default: false, }; db.save_aws_credential("test", &cred)?; @@ -124,12 +141,14 @@ mod tests { let cred1 = AwsCredential { access_key_id: "KEY1".into(), secret_access_key: "EXAMPLESECRET".into(), + is_default: false, }; db.save_aws_credential("test", &cred1)?; let cred2 = AwsCredential { access_key_id: "KEY2".into(), secret_access_key: "EXAMPLESECRET2".into(), + is_default: false, }; db.save_aws_credential("test2", &cred2)?; @@ -145,4 +164,37 @@ mod tests { Ok(()) } + + #[test] + fn test_change_default() -> TestResult { + let env = TestEnv::new()?; + let db = env.db()?; + + let cred1 = AwsCredential { + access_key_id: "KEY1".into(), + secret_access_key: "EXAMPLESECRET".into(), + is_default: true, + }; + db.save_aws_credential("test", &cred1)?; + + let cred2 = AwsCredential { + access_key_id: "KEY2".into(), + secret_access_key: "EXAMPLESECRET2".into(), + is_default: true, + }; + db.save_aws_credential("test2", &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("test2", &cred2)?; + assert!(db.load_aws_credential("test2")?.is_default); + + db.save_aws_credential("test", &cred1)?; + assert!(db.load_aws_credential("test")?.is_default); + assert!(!db.load_aws_credential("test2")?.is_default); + + Ok(()) + } } diff --git a/src/main.rs b/src/main.rs index fc87534..1288a40 100644 --- a/src/main.rs +++ b/src/main.rs @@ -261,6 +261,7 @@ mod tests { let cred = AwsCredential { access_key_id: "AKIAEXAMPLE".into(), secret_access_key: "EXAMPLESECRET".into(), + is_default: false, }; env.db().unwrap().save_aws_credential("work", &cred).unwrap(); let window = open_app(&env, cx); @@ -276,4 +277,81 @@ mod tests { 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::() 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 { + access_key_id: "AKIAEXAMPLE".into(), + secret_access_key: "EXAMPLESECRET".into(), + is_default: false, + }; + env.db().unwrap().save_aws_credential("work", &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::() else { panic!("locked") }; + db.load_aws_credential("work").unwrap() + }); + assert_eq!(saved.access_key_id, "AKIAEXAMPLE"); + } } diff --git a/src/screens/credentials.rs b/src/screens/credentials.rs index 2d83ea4..b3a9528 100644 --- a/src/screens/credentials.rs +++ b/src/screens/credentials.rs @@ -1,13 +1,14 @@ +use gpui_kit::base::input::{InputEvent, InputState}; use gpui_kit::{ - Context, FontWeight, InteractiveElement, IntoElement, ParentElement, Render, SharedString, - Styled, TestSupportExt, Window, div, rems, + AppContext, Context, Div, Entity, FontWeight, InteractiveElement, IntoElement, ParentElement, + Render, SharedString, Styled, Subscription, TestSupportExt, Window, div, rems, }; use gpui_omarchy::{ - ActiveTheme, ButtonVariant, ChoiceItem, IconName, empty_state, focus_scope, icon_button, - tab_list, + ActiveTheme, ButtonVariant, ChoiceItem, IconName, Status, badge, button, empty_state, + focus_scope, icon_button, input, switch, tab_list, }; -use crate::components::error_alert; +use crate::components::{PassphraseInput, PassphraseInputEvent, error_alert}; use crate::credentials::AwsCredential; use crate::session::AppSession; use super::Screen; @@ -16,32 +17,206 @@ use super::Screen; pub struct CredentialsScreen { tab: usize, aws: Vec<(String, AwsCredential)>, + aws_form: Option, error: Option, } +struct AwsForm { + name: Entity, + access_key_id: Entity, + secret_access_key: Entity, + is_default: bool, + _subscriptions: Vec, +} + impl CredentialsScreen { pub fn new(cx: &mut Context) -> Self { + let mut this = Self { tab: 0, aws: Vec::new(), aws_form: None, error: None }; + this.load_aws(cx); + this + } + + fn load_aws(&mut self, cx: &mut Context) { let AppSession::Unlocked(db) = cx.global::() else { unreachable!("credentials screen is only shown while unlocked"); }; - let (aws, error) = match db.list_aws_credentials() { + match db.list_aws_credentials() { Ok(creds) => { - let mut creds: Vec<_> = creds.into_iter().collect(); - creds.sort_by(|a, b| a.0.cmp(&b.0)); - (creds, None) + self.aws = creds.into_iter().collect(); + self.aws.sort_by(|a, b| a.0.cmp(&b.0)); + self.error = None; }, - Err(e) => (Vec::new(), Some(format!("Failed to load credentials: {e}").into())), + Err(e) => self.error = Some(format!("Failed to load credentials: {e}").into()), + } + } + + fn add_aws(&mut self, window: &mut Window, cx: &mut Context) { + let name = cx.new(|cx| InputState::new(window, cx)); + let access_key_id = cx.new(|cx| InputState::new(window, cx)); + let show = cx.new(|_| false); + let secret_access_key = cx.new(|cx| PassphraseInput::new("aws-secret", show, 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 { + name, + access_key_id, + secret_access_key, + is_default: false, + _subscriptions, + }); + self.error = None; + cx.notify(); + } + + fn save_aws(&mut self, cx: &mut Context) { + let Some(form) = &self.aws_form else { return }; + let name = form.name.read(cx).value().trim().to_string(); + let cred = AwsCredential { + 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, }; - Self { tab: 0, aws, error } + if 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; + } + // saving is an upsert, so without this a new credential would silently replace the old one + if self.aws.iter().any(|(existing, _)| *existing == name) { + self.error = Some(format!("An AWS credential named \"{name}\" already exists.").into()); + cx.notify(); + return; + } + + let AppSession::Unlocked(db) = cx.global::() else { + unreachable!("credentials screen is only shown while unlocked"); + }; + match db.save_aws_credential(&name, &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 render_aws_tab(&self, window: &mut Window, cx: &mut Context) -> Div { + let t = cx.omarchy().clone(); + + let list = if self.aws.is_empty() { + empty_state("AWS access keys", "You have no saved AWS credentials.", cx) + } else { + div() + .flex() + .flex_col() + .gap(rems(0.5)) + .children(self.aws.iter().map(|(name, cred)| { + div() + .id(SharedString::from(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(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()), + ) + })) + }; + + let Some(form) = &self.aws_form else { + return div().flex().flex_col().gap(rems(1.)).child(list).child( + button("aws-add", "Add", ButtonVariant::Primary, cx) + .self_center() + .on_click(cx.listener(|this, _, window, cx| this.add_aws(window, cx))), + ); + }; + + 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.)).child(list).child( + 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( + switch("aws-default", "Default AWS access key", form.is_default, 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) -> impl IntoElement { - let t = cx.omarchy().clone(); - let this = cx.entity(); let tabs = tab_list( "credential-tabs", @@ -61,32 +236,7 @@ impl Render for CredentialsScreen { ); let panel = match self.tab { - 0 if self.aws.is_empty() => empty_state( - "AWS access keys", - "You have no saved AWS credentials.", - cx, - ), - 0 => div() - .flex() - .flex_col() - .gap(rems(0.5)) - .children(self.aws.iter().map(|(name, cred)| { - div() - .id(SharedString::from(name)) - .test_support() - .flex() - .justify_between() - .p(rems(0.625)) - .border_1() - .border_color(t.border) - .child(div().font_weight(FontWeight::BOLD).child(name.clone())) - .child( - div() - .font_family(t.mono_font.clone()) - .text_color(t.secondary) - .child(cred.access_key_id.clone()), - ) - })), + 0 => self.render_aws_tab(window, cx), 1 => empty_state("SSH keys", "Not implemented yet.", cx), _ => empty_state("Docker credentials", "Not implemented yet.", cx), };