Compare commits

...
23 Commits
Author SHA1 Message Date
jfmonty2 179e853dc6 add session credential handling 2026-11-24 13:49:55 -05:00
jfmonty2 009eec764e wait for unlock before responding to credentials request 2026-11-24 12:16:13 -05:00
jfmonty2 5f1ff5e4e8 basic working version of approval screen 2026-11-23 14:35:37 -05:00
jfmonty2 49c1e81e1d refactor view-selection once again 2026-11-23 12:51:08 -05:00
jfmonty2 72279f02de add approval to screen selection 2026-11-23 12:33:43 -05:00
jfmonty2 d5e7de86cb refactor server a bit 2026-11-23 10:55:24 -05:00
jfmonty2 e4cfa53bce formatting pass 2026-11-22 06:17:04 -05:00
jfmonty2 d976eebbbc basic echo HTTP server 2026-11-22 06:14:06 -05:00
jfmonty2 c86a898879 remove unused import 2026-11-20 11:46:57 -05:00
jfmonty2 d478c8337e reorganize by moving CreddyApp and tests into their own modules 2026-11-20 11:46:00 -05:00
jfmonty2 e46540c077 add dependencies for local http server, plus module 2026-11-20 11:20:14 -05:00
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
jfmonty2 7ef99e9020 persist aws credentials to the database 2026-11-19 14:33:51 -05:00
jfmonty2 3c06f7e536 add unlock/exit buttons to home screen 2026-11-18 20:12:22 -05:00
jfmonty2 b2a7e5759a add UI tests for welcome and unlock flows 2026-11-18 14:31:00 -05:00
jfmonty2 5999aba0a5 test loading AppSession 2026-11-18 10:14:36 -05:00
jfmonty2 0798124811 add db migrations and restore config on unlock 2026-11-18 05:49:45 -05:00
31 changed files with 4197 additions and 318 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
[env] [env]
# in development (i.e. when running through Cargo), store state in project directory # in development (i.e. when running through Cargo), store state in project directory
CREDDY_DATA_DIR = { value = "data", relative = true } CREDDY_DATA_DIR = { value = "data", relative = true }
CREDDY_RUNTIME_DIR = { value = "data", relative = true }
Generated
+1751 -75
View File
File diff suppressed because it is too large. Load diff
+16 -1
View File
@@ -10,16 +10,31 @@ edition = "2024"
[dependencies] [dependencies]
argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] } argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] }
async-compat = "0.2.7"
aws-sdk-sts = "1.128.0"
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"] }
form_urlencoded = "1.2.3"
futures = "0.3.34"
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"
http-body-util = "0.1.5"
hyper = { version = "1.12.0", features = ["server", "http1"] }
hyper-util = { version = "0.1.21", features = ["tokio"] }
include_dir = "0.7.4"
jiff = { version = "1.0.1", features = ["serde"] }
rustix = { version = "1.1.6", features = ["net"] }
serde = "1.0.229" serde = "1.0.229"
serde_json = "1.0.154" serde_json = "1.0.154"
smol = "2.0.2"
smol-hyper = "0.1.1"
strum = { version = "0.28.0", features = ["derive"] }
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"] }
tempfile = "3.27.0" tempfile = "3.27.0"
+4
View File
@@ -0,0 +1,4 @@
fn main() {
// include_dir! only tracks files that already exist, so rebuild when one is added
println!("cargo:rerun-if-changed=migrations");
}
View File
Whitespace-only changes.
+15
View File
@@ -0,0 +1,15 @@
-- config will only ever hold a single row with a single value
CREATE TABLE config (value JSON);
-- seed it with an empty object, which will be populated with default values on deserialization
INSERT INTO config VALUES ('{}');
CREATE TABLE aws_credentials (
id UUID PRIMARY KEY NOT NULL,
name VARCHAR UNIQUE 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
);
+73
View File
@@ -0,0 +1,73 @@
use gpui_kit::{
App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowHandle,
WindowOptions, div,
};
use gpui_omarchy::ActiveTheme;
use crate::config::AppConfig;
use crate::credentials::AwsSessionCache;
use crate::screens::{ApprovalScreen, CredentialsScreen, HomeScreen, Screen, UnlockScreen, WelcomeScreen};
use crate::session::AppSession;
use crate::srv::{self, PendingRequests};
pub struct CreddyApp {}
impl Render for CreddyApp {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let screen = match Screen::from_context(cx) {
Screen::Welcome => window
.use_keyed_state("welcome", cx, |window, cx| WelcomeScreen::new(window, cx))
.into_any_element(),
Screen::Unlock => window
.use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx))
.into_any_element(),
// Otherwise, fall back to "current screen" global
Screen::Home => window
.use_keyed_state("home", cx, |_, _| HomeScreen {})
.into_any_element(),
Screen::Credentials => window
.use_keyed_state("credentials", cx, |_, cx| CredentialsScreen::new(cx))
.into_any_element(),
Screen::RequestApproval => window
.use_keyed_state("approval", cx, |_, _| ApprovalScreen {})
.into_any_element(),
Screen::ShowApproval => todo!(),
};
let theme = cx.omarchy();
div()
.size_full()
.bg(theme.background)
.text_color(theme.foreground)
.font_family(theme.font.clone())
.child(screen)
}
}
/// Install the globals and open the main window. Tests call this too, so they get the same wiring.
pub fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle<CreddyApp> {
// todo: `SetupError` global, that gets populated if any of the fallible setup fails so we can display it in the UI
gpui_omarchy::init(cx);
srv::start_creddy_server(&config.creddy_server_addr(), cx.to_async())
.expect("Failed to start server, we will add proper error handling for this later");
cx.set_global(config);
cx.set_global(session);
cx.set_global(Screen::Home);
cx.set_global(PendingRequests::new());
cx.set_global(AwsSessionCache::default());
// 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
cx.observe_global::<AppConfig>(|cx| cx.refresh_windows())
.detach();
cx.observe_global::<AppSession>(|cx| cx.refresh_windows())
.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")
}
+27
View File
@@ -0,0 +1,27 @@
use std::borrow::Cow;
use gpui_kit::assets::{Assets, icon_assets};
use gpui_kit::{AssetSource, Result, SharedString};
// gpui-kit only embeds the icons its own components use, so anything else has to be listed here
icon_assets!(CreddyIcons, [Key, LogOut, Pencil, ShieldCheck, Trash]);
/// Our extra icons, falling back to gpui-kit's defaults.
pub struct CreddyAssets;
impl AssetSource for CreddyAssets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
match CreddyIcons.load(path)? {
Some(bytes) => Ok(Some(bytes)),
None => Assets.load(path),
}
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = Assets.list(path)?;
paths.extend(CreddyIcons.list(path)?);
paths.sort();
paths.dedup();
Ok(paths)
}
}
+57
View File
@@ -0,0 +1,57 @@
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)
}
+15
View File
@@ -0,0 +1,15 @@
use gpui_kit::{
App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement,
TestSupportExt,
};
use gpui_omarchy::{Status, alert};
/// An error alert whose message is also its accessible label,
/// so screen readers announce it and UI tests can find it by its "error" ID.
pub fn error_alert(message: SharedString, cx: &App) -> impl IntoElement {
alert(message.clone(), Status::Error, cx)
.id("error")
.role(Role::Alert)
.aria_label(message)
.test_support()
}
+4
View File
@@ -1,3 +1,7 @@
mod colored_switch;
mod error_alert;
mod passphrase_input; mod passphrase_input;
pub use colored_switch::colored_switch;
pub use error_alert::error_alert;
pub use passphrase_input::{PassphraseInput, PassphraseInputEvent}; pub use passphrase_input::{PassphraseInput, PassphraseInputEvent};
+76 -35
View File
@@ -6,12 +6,9 @@ use gpui_kit::{
}; };
use gpui_omarchy::{ButtonVariant, icon_button, input}; 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,
state: Entity<InputState>, state: Entity<InputState>,
show: Entity<bool>, show: Entity<bool>,
_subscriptions: Vec<Subscription>, _subscriptions: Vec<Subscription>,
@@ -28,37 +25,81 @@ pub enum PassphraseInputEvent {
impl EventEmitter<PassphraseInputEvent> for PassphraseInput {} impl EventEmitter<PassphraseInputEvent> for PassphraseInput {}
impl PassphraseInput { pub struct PassphraseInputBuilder {
pub fn new(show: Entity<bool>, window: &mut Window, cx: &mut Context<Self>) -> Self { id: SharedString,
let masked = !*show.read(cx); show: Option<Entity<bool>>,
let state = cx.new(|cx| { placeholder: SharedString,
InputState::new(window, cx) value: SharedString,
.masked(masked) }
.placeholder("correct horse battery staple")
});
// keep this field's masking in sync with the shared flag impl PassphraseInputBuilder {
let sync_mask = cx.observe_in(&show, window, |this, show, window, cx| { /// 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);
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx)); let state = cx.new(|cx| {
cx.notify(); InputState::new(window, cx)
}); .masked(masked)
.placeholder(self.placeholder)
.default_value(self.value)
});
// re-emit the subset of input events that consumers care about // keep this field's masking in sync with the shared flag
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| { let sync_mask = cx.observe_in(
let event = match event { &show,
InputEvent::PressEnter { .. } => PassphraseInputEvent::Submit, window,
InputEvent::Change => PassphraseInputEvent::Change, |this: &mut PassphraseInput, show, window, cx| {
InputEvent::Blur => PassphraseInputEvent::Blur, let masked = !*show.read(cx);
InputEvent::Focus => return, this.state
}; .update(cx, |state, cx| state.set_masked(masked, window, cx));
cx.emit(event); cx.notify();
}); },
);
Self { // re-emit the subset of input events that consumers care about
state, let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
show, let event = match event {
_subscriptions: vec![sync_mask, forward], InputEvent::PressEnter { .. } => PassphraseInputEvent::Submit,
InputEvent::Change => PassphraseInputEvent::Change,
InputEvent::Blur => PassphraseInputEvent::Blur,
InputEvent::Focus => return,
};
cx.emit(event);
});
PassphraseInput {
id: self.id,
state,
show,
_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(),
} }
} }
@@ -82,15 +123,15 @@ impl Render for PassphraseInput {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let (icon, label) = if *self.show.read(cx) { let (icon, label) = if *self.show.read(cx) {
(IconName::EyeOff, "Hide passphrase") (IconName::EyeOff, "Hide passphrase")
} } else {
else {
(IconName::Eye, "Show passphrase") (IconName::Eye, "Show passphrase")
}; };
input("passphrase", &self.state, window, cx) let toggle_id = SharedString::from(format!("{}-toggle-show", self.id));
input(self.id.clone(), &self.state, window, cx)
.w_full() .w_full()
.suffix( .suffix(
icon_button("toggle-show", icon, label, ButtonVariant::Secondary, cx) icon_button(toggle_id, icon, label, ButtonVariant::Secondary, cx)
.on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))), .on_click(cx.listener(|this, _, _, cx| this.toggle_show(cx))),
) )
} }
+102 -58
View File
@@ -1,14 +1,13 @@
use std::env::{self, VarError}; use std::env;
use std::ffi::OsString; use std::ffi::OsString;
use std::fs::File; use std::fs::File;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use gpui_kit::Global; use gpui_kit::Global;
use serde::{Serialize, Deserialize}; use serde::{Deserialize, Serialize};
use crate::error::CreddyError; use crate::error::CreddyError;
/// Config that doesn't need to or can't be stored in the encrypted db /// Config that doesn't need to or can't be stored in the encrypted db
/// (such as settings that must be known at startup, before unlock). /// (such as settings that must be known at startup, before unlock).
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
@@ -28,9 +27,8 @@ impl PublicConfig {
pub fn load(path: &Path) -> Result<PublicConfig, CreddyError> { pub fn load(path: &Path) -> Result<PublicConfig, CreddyError> {
if path.exists() { if path.exists() {
let f = File::open(path)?; let f = File::open(path)?;
serde_json::from_reader(f).map_err(|e| CreddyError::ConfigDecode(e)) serde_json::from_reader(f).map_err(|e| CreddyError::InvalidJSON(e))
} } else {
else {
Ok(PublicConfig::default()) Ok(PublicConfig::default())
} }
} }
@@ -42,36 +40,71 @@ impl PublicConfig {
} }
} }
/// Config that should be stored in the encrypted db
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivateConfig {
rehide_ms: u64,
}
impl Default for PrivateConfig {
fn default() -> PrivateConfig {
PrivateConfig { rehide_ms: 1000 }
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct AppConfig { pub struct AppConfig {
pub data_dir: PathBuf, pub data_dir: PathBuf,
pub runtime_dir: PathBuf,
pub db_salt: [u8; 32], pub db_salt: [u8; 32],
pub rehide_ms: u64,
} }
impl AppConfig { impl AppConfig {
/// Load config from disk, using defaults for non-public values. /// Load config from disk, using defaults for non-public values.
pub fn load() -> Result<AppConfig, CreddyError> { pub fn load() -> Result<AppConfig, CreddyError> {
let data_dir = AppConfig::resolve_data_dir( let data_dir = env::var_os("CREDDY_DATA_DIR")
env::var_os("CREDDY_DATA_DIR"),
dirs::data_dir(),
)?;
AppConfig::load_from(data_dir)
}
fn load_from(data_dir: PathBuf) -> Result<AppConfig, CreddyError> {
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
Ok(AppConfig {
data_dir,
db_salt: public_config.db_salt,
})
}
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
creddy_data_dir
.map(PathBuf::from) .map(PathBuf::from)
.or_else(|| platform_data_dir.map(|d| d.join("creddy"))) .or_else(|| dirs::data_dir().map(|d| d.join("creddy")))
.ok_or(CreddyError::DataDirNotFound) .ok_or(CreddyError::DirNotFound)?;
let runtime_dir = env::var_os("CREDDY_RUNTIME_DIR")
.map(PathBuf::from)
.or_else(|| dirs::runtime_dir())
.ok_or(CreddyError::DirNotFound)?;
AppConfig::load_from(data_dir, runtime_dir)
}
pub fn load_from(data_dir: PathBuf, runtime_dir: PathBuf) -> Result<AppConfig, CreddyError> {
let public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
let private_config = PrivateConfig::default();
Ok(AppConfig::from_parts(
data_dir,
runtime_dir,
public_config,
private_config,
))
}
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
fn from_parts(
data_dir: PathBuf,
runtime_dir: PathBuf,
public: PublicConfig,
private: PrivateConfig,
) -> AppConfig {
AppConfig {
data_dir,
runtime_dir,
db_salt: public.db_salt,
rehide_ms: private.rehide_ms,
}
}
pub fn merge_private(&mut self, private: PrivateConfig) {
self.rehide_ms = private.rehide_ms;
} }
pub fn public_config_path(&self) -> PathBuf { pub fn public_config_path(&self) -> PathBuf {
@@ -82,16 +115,39 @@ impl AppConfig {
self.data_dir.join("creddy.duckdb") self.data_dir.join("creddy.duckdb")
} }
pub fn creddy_server_addr(&self) -> PathBuf {
self.runtime_dir.join("creddy-server.sock")
}
pub fn public_config(&self) -> PublicConfig { pub fn public_config(&self) -> PublicConfig {
PublicConfig { PublicConfig {
db_salt: self.db_salt, db_salt: self.db_salt,
} }
} }
pub fn private_config(&self) -> PrivateConfig {
PrivateConfig {
rehide_ms: self.rehide_ms,
}
}
}
impl Default for AppConfig {
fn default() -> AppConfig {
// AppConfig::default will only be called for testing or to fill in
// remaining defaults when constructing otherwise, and data_dir is
// always specified otherwise
AppConfig::from_parts(
PathBuf::from(""),
PathBuf::from(""),
PublicConfig::default(),
PrivateConfig::default(),
)
}
} }
impl Global for AppConfig {} impl Global for AppConfig {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -128,7 +184,8 @@ mod tests {
#[test] #[test]
fn test_config_load_not_present() -> TestResult { fn test_config_load_not_present() -> TestResult {
let data_dir = tempfile::tempdir()?; let data_dir = tempfile::tempdir()?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?; let data_dir_path = data_dir.path().to_path_buf();
let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?;
assert!(config.data_dir == data_dir.path()); assert!(config.data_dir == data_dir.path());
assert!(config.db_salt.len() == 32); assert!(config.db_salt.len() == 32);
Ok(()) Ok(())
@@ -137,55 +194,42 @@ mod tests {
#[test] #[test]
fn test_config_load_present() -> TestResult { fn test_config_load_present() -> TestResult {
let data_dir = tempfile::tempdir()?; let data_dir = tempfile::tempdir()?;
let data_dir_path = data_dir.path().to_path_buf();
let p = data_dir.path().join("public_config.json"); let p = data_dir.path().join("public_config.json");
let public = PublicConfig::default(); // uses a random db salt let public = PublicConfig::default(); // uses a random db salt
let f = File::create(&p)?; let f = File::create(&p)?;
serde_json::to_writer(f, &public)?; serde_json::to_writer(f, &public)?;
let config = AppConfig::load_from(data_dir.path().to_path_buf())?; let config = AppConfig::load_from(data_dir_path.clone(), data_dir_path)?;
assert!(config.data_dir == data_dir.path()); assert!(config.data_dir == data_dir.path());
assert!(config.db_salt == public.db_salt); assert!(config.db_salt == public.db_salt);
Ok(()) Ok(())
} }
#[test]
fn test_resolve_data_dir_override() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
Some(OsString::from("/tmp/creddy")),
None,
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test]
fn test_resolve_data_dir_default() -> TestResult {
let data_dir = AppConfig::resolve_data_dir(
None,
Some(PathBuf::from("/tmp")),
)?;
assert!(data_dir == PathBuf::from("/tmp/creddy"));
Ok(())
}
#[test] #[test]
fn test_config_paths() { fn test_config_paths() {
let config = AppConfig { let mut config = AppConfig::default();
data_dir: PathBuf::from("/tmp/creddy"), config.data_dir = PathBuf::from("/tmp/creddy");
db_salt: PublicConfig::default().db_salt,
};
assert!(config.db_path() == PathBuf::from("/tmp/creddy/creddy.duckdb")); assert!(config.db_path() == PathBuf::from("/tmp/creddy/creddy.duckdb"));
assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json")); assert!(config.public_config_path() == PathBuf::from("/tmp/creddy/public_config.json"));
} }
#[test]
fn test_server_addr() {
let mut config = AppConfig::default();
config.runtime_dir = PathBuf::from("/tmp/creddy");
assert_eq!(
config.creddy_server_addr(),
PathBuf::from("/tmp/creddy/creddy-server.sock")
);
}
#[test] #[test]
fn test_public_config_from_app_config() { fn test_public_config_from_app_config() {
let config = AppConfig { let mut config = AppConfig::default();
data_dir: PathBuf::from("/tmp/creddy"), config.data_dir = PathBuf::from("/tmp/creddy");
db_salt: PublicConfig::default().db_salt,
};
let public = config.public_config(); let public = config.public_config();
assert!(public.db_salt == config.db_salt); assert!(public.db_salt == config.db_salt);
+134
View File
@@ -0,0 +1,134 @@
use async_compat::CompatExt;
use aws_sdk_sts::config::{BehaviorVersion, Credentials, Region};
use aws_sdk_sts::error::{DisplayErrorContext, ProvideErrorMetadata};
use aws_sdk_sts::{Client, Config};
use gpui_kit::{AsyncApp, Global};
use jiff::{SignedDuration, Timestamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;
use crate::error::CreddyError;
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
pub struct AwsCredential {
pub id: Uuid,
pub name: String,
pub access_key_id: String,
pub secret_access_key: String,
pub is_default: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AwsSessionCredential {
pub version: usize,
pub access_key_id: String,
pub secret_access_key: String,
pub session_token: String,
pub expiration: Timestamp,
}
#[derive(Default)]
pub struct AwsSessionCache {
sessions: HashMap<String, AwsSessionCredential>,
}
impl AwsSessionCache {
pub async fn get_session(
longterm: &AwsCredential,
cx: &AsyncApp,
) -> Result<AwsSessionCredential, CreddyError> {
let cached = cx.read_global::<AwsSessionCache, _>(|cache, _| {
cache.sessions.get(&longterm.access_key_id).cloned()
});
// a session that's about to expire isn't much use to the client
if let Some(session) = cached
&& session.expiration > Timestamp::now() + SignedDuration::from_secs(60)
{
return Ok(session);
}
let config = Config::builder()
.behavior_version(BehaviorVersion::latest())
.region(Region::new("us-east-1"))
.credentials_provider(Credentials::new(
&longterm.access_key_id,
&longterm.secret_access_key,
None,
None,
"Creddy",
))
.build();
// the SDK needs a Tokio context, which compat() supplies
let response = Client::from_conf(config)
.get_session_token()
.duration_seconds(43_200)
.send()
.compat()
.await
.map_err(|e| {
// only errors from the service itself come with a readable message
let message = match e.message() {
Some(message) => message.to_string(),
None => DisplayErrorContext(&e).to_string(),
};
CreddyError::GetSession(message)
})?;
let creds = response
.credentials
.ok_or_else(|| CreddyError::GetSession("response contained no credentials".into()))?;
let session = AwsSessionCredential {
version: 1,
access_key_id: creds.access_key_id,
secret_access_key: creds.secret_access_key,
session_token: creds.session_token,
expiration: Timestamp::new(creds.expiration.secs(), creds.expiration.subsec_nanos() as i32)
.map_err(|e| CreddyError::GetSession(e.to_string()))?,
};
cx.update_global::<AwsSessionCache, _>(|cache, _| {
cache.sessions.insert(longterm.access_key_id.clone(), session.clone())
});
Ok(session)
}
}
impl Global for AwsSessionCache {}
#[cfg(test)]
mod tests {
use super::*;
use gpui_kit::TestAppContext;
fn test_cred() -> AwsCredential {
AwsCredential {
id: Uuid::new_v4(),
name: "test".into(),
access_key_id: "AKIAEXAMPLE".into(),
secret_access_key: "EXAMPLESECRET".into(),
is_default: false,
}
}
#[gpui_kit::test]
fn test_get_session_cached(cx: &mut TestAppContext) {
let cached = AwsSessionCredential {
version: 1,
access_key_id: "ASIAEXAMPLE".into(),
secret_access_key: "SESSIONSECRET".into(),
session_token: "TOKEN".into(),
expiration: Timestamp::now() + SignedDuration::from_hours(1),
};
let mut cache = AwsSessionCache::default();
cache.sessions.insert("AKIAEXAMPLE".into(), cached.clone());
cx.update(|cx| cx.set_global(cache));
// parking isn't allowed here, so this would panic if it went to the network
let cx = cx.to_async();
let session = cx
.foreground_executor()
.block_test(AwsSessionCache::get_session(&test_cred(), &cx))
.unwrap();
assert_eq!(session, cached);
}
}
+3
View File
@@ -0,0 +1,3 @@
mod aws;
pub use aws::{AwsCredential, AwsSessionCache, AwsSessionCredential};
+242
View File
@@ -0,0 +1,242 @@
use super::Db;
use crate::credentials::AwsCredential;
use duckdb::{Error, params};
use uuid::Uuid;
impl Db {
pub fn load_aws_credential(&self, name: &str) -> Result<AwsCredential, Error> {
let conn = self.connection.lock().unwrap();
conn.query_row(
"SELECT
id,
name,
access_key_id,
secret_access_key,
is_default
FROM aws_credentials
WHERE name = ?",
params![name],
|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, cred: &AwsCredential) -> Result<(), Error> {
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 id != ?",
params![cred.id],
)?;
}
tx.execute(
"INSERT INTO aws_credentials (
id,
name,
created_at,
updated_at,
access_key_id,
secret_access_key,
is_default,
)
VALUES (?, ?, now(), now(), ?, ?, ?)
ON CONFLICT (id) DO UPDATE
SET
name = EXCLUDED.name,
updated_at = now(),
access_key_id = EXCLUDED.access_key_id,
secret_access_key = EXCLUDED.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(())
}
pub fn list_aws_credentials(&self) -> Result<Vec<AwsCredential>, Error> {
let conn = self.connection.lock().unwrap();
let mut stmt = conn.prepare(
"SELECT
id,
name,
access_key_id,
secret_access_key,
is_default
FROM aws_credentials
ORDER BY created_at",
)?;
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()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::TestEnv;
use testresult::TestResult;
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]
fn test_save() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
db.save_aws_credential(&test_cred("test", "AKIAEXAMPLE"))?;
Ok(())
}
#[test]
fn test_load() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
let cred = test_cred("test", "AKIAEXAMPLE");
db.save_aws_credential(&cred)?;
let loaded = db.load_aws_credential("test")?;
assert_eq!(loaded, cred);
Ok(())
}
#[test]
fn test_update() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
let mut cred = test_cred("test", "KEY1");
db.save_aws_credential(&cred)?;
cred.name = "renamed".into();
cred.access_key_id = "KEY2".into();
db.save_aws_credential(&cred)?;
let creds = db.list_aws_credentials()?;
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
let conn = db.connection.lock().unwrap();
let (created_at, updated_at): (i64, i64) = conn.query_row(
"SELECT created_at, updated_at FROM aws_credentials WHERE name = 'renamed'",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)?;
assert!(updated_at > created_at);
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]
fn test_list() -> TestResult {
let env = TestEnv::new()?;
let db = env.db()?;
// names are out of alphabetical order, since the list should be in order of creation
let cred1 = test_cred("test2", "KEY1");
db.save_aws_credential(&cred1)?;
let cred2 = test_cred("test1", "KEY2");
db.save_aws_credential(&cred2)?;
let creds = db.list_aws_credentials()?;
assert_eq!(creds.len(), 2);
assert_eq!(creds[0], cred1);
assert_eq!(creds[1], cred2);
Ok(())
}
#[test]
fn test_delete() -> TestResult {
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(())
}
}
+49 -4
View File
@@ -1,9 +1,54 @@
use crate::config::AppConfig;
use crate::error::CreddyError;
use super::Db; use super::Db;
use crate::config::PrivateConfig;
use crate::error::CreddyError;
impl Db { impl Db {
pub fn save_config(&self, config: &AppConfig) -> Result<(), CreddyError> { pub fn load_private_config(&self) -> Result<PrivateConfig, CreddyError> {
todo!() let conn = self.connection.lock().unwrap();
let json: String = conn.query_row("SELECT value FROM config", [], |row| row.get(0))?;
let config: PrivateConfig = serde_json::from_str(&json)?;
Ok(config)
}
pub fn save_private_config(&self, config: &PrivateConfig) -> Result<(), CreddyError> {
let json = serde_json::to_string(&config)?;
let conn = self.connection.lock().unwrap();
// the migration seeds the only row, so this is always an update
conn.execute("UPDATE config SET value = ?;", [&json])?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::AppConfig;
use tempfile::TempDir;
use testresult::TestResult;
fn test_db() -> Result<(Db, TempDir), CreddyError> {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
let db = Db::connect(&config, "correct horse battery staple")?;
Ok((db, data_dir))
}
#[test]
fn test_save_private_config() -> TestResult {
let (db, _data_dir) = test_db()?;
let private_config = PrivateConfig::default();
db.save_private_config(&private_config)?;
Ok(())
}
#[test]
fn test_load_private_config() -> TestResult {
let (db, _data_dir) = test_db()?;
let private_config = PrivateConfig::default();
db.save_private_config(&private_config)?;
let loaded = db.load_private_config()?;
assert_eq!(loaded, private_config);
Ok(())
} }
} }
+180
View File
@@ -0,0 +1,180 @@
use duckdb::Connection;
use include_dir::{Dir, include_dir};
use crate::error::CreddyError;
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
struct Migration {
id: &'static str,
sql: &'static str,
}
/// Run all unapplied database migrations.
pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> {
apply_migrations(conn, &embedded_migrations())
}
/// Sorted list of migration files, checked for utf-8-ness at compile time.
fn embedded_migrations() -> Vec<Migration> {
let mut migrations: Vec<Migration> = MIGRATIONS_DIR
.files()
.filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
.map(|f| Migration {
// these are baked in at compile time, so a bad file is a build problem, not a runtime one
id: f
.path()
.file_name()
.and_then(|n| n.to_str())
.expect("migration filename is not UTF-8"),
sql: f.contents_utf8().expect("migration file is not UTF-8"),
})
.collect();
migrations.sort_by_key(|m| m.id);
migrations
}
/// Run a specific list of migrations. (Makes testing easier than always hard-coding)
fn apply_migrations(conn: &mut Connection, known: &[Migration]) -> Result<(), CreddyError> {
create_migrations_table(conn)?;
let applied = list_applied_migrations(conn)?;
// the applied migrations must be exactly the first N known ones
for (i, id) in applied.iter().enumerate() {
if known.get(i).is_some_and(|m| m.id == id) {
continue;
}
// at this point, either known[i] doesn't exist or doesn't match `id`
if known.iter().any(|m| m.id == id) {
return Err(CreddyError::MigrationOutOfOrder(id.clone()));
}
//
return Err(CreddyError::DbTooNew(id.clone()));
}
for migration in &known[applied.len()..] {
let tx = conn.transaction()?;
tx.execute_batch(migration.sql)?;
tx.execute("INSERT INTO _migrations (id) VALUES (?);", [migration.id])?;
tx.commit()?;
}
Ok(())
}
/// Create the migrations table if it doesn't exist already.
fn create_migrations_table(conn: &Connection) -> Result<(), CreddyError> {
conn.execute_batch(
"CREATE TABLE IF NOT EXISTS _migrations (
id VARCHAR PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT current_timestamp
);",
)?;
Ok(())
}
/// List migrations that have been applied to this database, in the order they were applied.
fn list_applied_migrations(conn: &Connection) -> Result<Vec<String>, CreddyError> {
let mut stmt = conn.prepare("SELECT id FROM _migrations ORDER BY id;")?;
let ids = stmt
.query_map([], |row| row.get(0))?
.collect::<Result<Vec<String>, _>>()?;
Ok(ids)
}
#[cfg(test)]
mod tests {
use super::*;
use testresult::TestResult;
const FIRST: Migration = Migration {
id: "0001_first.sql",
sql: "CREATE TABLE a (x INTEGER);",
};
const SECOND: Migration = Migration {
id: "0002_second.sql",
sql: "CREATE TABLE b (x INTEGER); INSERT INTO b VALUES (1);",
};
fn table_exists(conn: &Connection, name: &str) -> duckdb::Result<bool> {
conn.query_row(
"SELECT count(*) > 0 FROM duckdb_tables() WHERE table_name = ?;",
[name],
|row| row.get(0),
)
}
#[test]
fn test_embedded_migrations_apply() -> TestResult {
let mut conn = Connection::open_in_memory()?;
migrate(&mut conn)?;
let applied = list_applied_migrations(&conn)?;
let expected: Vec<_> = embedded_migrations()
.iter()
.map(|m| m.id.to_string())
.collect();
assert_eq!(applied, expected);
Ok(())
}
#[test]
fn test_apply_incrementally() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[FIRST])?;
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
// already-applied migrations are skipped, so re-running FIRST would fail if it weren't
apply_migrations(&mut conn, &[FIRST, SECOND])?;
assert_eq!(
list_applied_migrations(&conn)?,
["0001_first.sql", "0002_second.sql"]
);
assert!(table_exists(&conn, "b")?);
Ok(())
}
#[test]
fn test_failed_migration_rolls_back() -> TestResult {
let mut conn = Connection::open_in_memory()?;
let broken = Migration {
id: "0002_broken.sql",
sql: "CREATE TABLE b (x INTEGER); this is not sql;",
};
let res = apply_migrations(&mut conn, &[FIRST, broken]);
assert!(matches!(res, Err(CreddyError::Db(_))));
// FIRST stays applied, but nothing from the broken migration survives
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql"]);
assert!(table_exists(&conn, "a")?);
assert!(!table_exists(&conn, "b")?);
Ok(())
}
#[test]
fn test_db_too_new() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[FIRST, SECOND])?;
// simulates running an older version of the app, which doesn't know about SECOND
match apply_migrations(&mut conn, &[FIRST]) {
Err(CreddyError::DbTooNew(id)) => assert_eq!(id, "0002_second.sql"),
res => panic!("Expected DbTooNew, got {res:?}"),
}
Ok(())
}
#[test]
fn test_migration_out_of_order() -> TestResult {
let mut conn = Connection::open_in_memory()?;
apply_migrations(&mut conn, &[SECOND])?;
// FIRST sorts before an already-applied migration, so it was added after the fact
match apply_migrations(&mut conn, &[FIRST, SECOND]) {
Err(CreddyError::MigrationOutOfOrder(id)) => assert_eq!(id, "0002_second.sql"),
res => panic!("Expected MigrationOutOfOrder, got {res:?}"),
}
Ok(())
}
}
+49 -35
View File
@@ -1,17 +1,15 @@
use argon2::{Algorithm, Argon2, Error as Argon2Error, ParamsBuilder, Version};
use base64ct::{Base64, Encoding};
use duckdb::{Connection, params};
use std::fs; use std::fs;
use std::sync::Mutex; use std::sync::Mutex;
use argon2::{Algorithm, Argon2, Version, Error as Argon2Error, ParamsBuilder};
use base64ct::{Base64, Encoding};
use duckdb::{
Connection,
params,
Error,
};
use crate::error::CreddyError;
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::error::CreddyError;
mod aws;
mod config; mod config;
mod migrations;
// tests take forever with production parameters, so we turn them down in dev // tests take forever with production parameters, so we turn them down in dev
#[cfg(not(debug_assertions))] #[cfg(not(debug_assertions))]
@@ -28,7 +26,6 @@ const TIME_COST: u32 = 1;
#[cfg(debug_assertions)] #[cfg(debug_assertions)]
const PARALLELISM_COST: u32 = 1; const PARALLELISM_COST: u32 = 1;
#[derive(Debug)] #[derive(Debug)]
pub struct Db { pub struct Db {
connection: Mutex<Connection>, connection: Mutex<Connection>,
@@ -41,20 +38,21 @@ impl Db {
// since we are about to make use of the salt stored in `config`, we need to save it now // since we are about to make use of the salt stored in `config`, we need to save it now
config.public_config().save(&config.public_config_path())?; config.public_config().save(&config.public_config_path())?;
let path = config.db_path() let path = config
.db_path()
.into_os_string() .into_os_string()
.into_string() .into_string()
.map_err(|s| CreddyError::InvalidPath(s))?; .map_err(|s| CreddyError::InvalidPath(s))?;
let key = Db::derive_key(passphrase, &config.db_salt)?; let key = Db::derive_key(passphrase, &config.db_salt)?;
let conn = Connection::open_in_memory()?; let mut conn = Connection::open_in_memory()?;
// hard-code the path for now, until we get proper config set up conn.execute("ATTACH ? AS creddy (ENCRYPTION_KEY ?);", params![path, key])?;
conn.execute( // must come before migrating, or the tables end up in the in-memory db
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
params![path, key],
)?;
conn.execute("USE creddy;", [])?; conn.execute("USE creddy;", [])?;
Ok(Self{ connection: Mutex::new(conn) }) migrations::migrate(&mut conn)?;
Ok(Self {
connection: Mutex::new(conn),
})
} }
/// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB /// Hash the given passphrase/salt with argon2, then encode to base64 for DuckDB
@@ -75,11 +73,11 @@ impl Db {
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use testresult::TestResult;
use super::*; use super::*;
use duckdb::Error;
use testresult::TestResult;
const TEST_PASSPHRASE: &'static str = "correct horse battery staple"; const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
const TEST_SALT: [u8; 32] = [0; 32]; const TEST_SALT: [u8; 32] = [0; 32];
@@ -89,10 +87,9 @@ mod tests {
#[test] #[test]
fn test_connect_new() -> TestResult { fn test_connect_new() -> TestResult {
let data_dir = tempfile::tempdir()?; let data_dir = tempfile::tempdir()?;
let config = AppConfig { let mut config = AppConfig::default();
data_dir: data_dir.path().to_path_buf(), config.data_dir = data_dir.path().to_path_buf();
db_salt: [0u8; 32],
};
let res = Db::connect(&config, TEST_PASSPHRASE); let res = Db::connect(&config, TEST_PASSPHRASE);
assert!(res.is_ok()); assert!(res.is_ok());
@@ -101,9 +98,11 @@ mod tests {
Err(Error::DuckDBFailure(error, _desc)) => { Err(Error::DuckDBFailure(error, _desc)) => {
assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.code == duckdb::ErrorCode::Unknown);
assert!(error.extended_code == 1); assert!(error.extended_code == 1);
}, }
Err(e) => panic!("Unexpected error type: {e:?}"), Err(e) => panic!("Unexpected error type: {e:?}"),
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"), Ok(_) => {
panic!("Should not be able to open newly-created database without encryption key")
}
}; };
// confirm that using a different passphrase won't work // confirm that using a different passphrase won't work
@@ -113,7 +112,7 @@ mod tests {
assert!(error.code == duckdb::ErrorCode::Unknown); assert!(error.code == duckdb::ErrorCode::Unknown);
assert!(error.extended_code == 1); assert!(error.extended_code == 1);
assert!(desc.contains("Wrong encryption key")); assert!(desc.contains("Wrong encryption key"));
}, }
Err(e) => panic!("Unexpected error type: {e:?}"), Err(e) => panic!("Unexpected error type: {e:?}"),
Ok(_) => panic!("Should not be able to open database with a different passphrase"), Ok(_) => panic!("Should not be able to open database with a different passphrase"),
} }
@@ -124,11 +123,11 @@ mod tests {
#[test] #[test]
fn test_connect_existing() -> TestResult { fn test_connect_existing() -> TestResult {
let data_dir = tempfile::tempdir()?; let data_dir = tempfile::tempdir()?;
let config = AppConfig { let mut config = AppConfig::default();
data_dir: data_dir.path().to_path_buf(), config.data_dir = data_dir.path().to_path_buf();
db_salt: [0u8; 32], config.db_salt = TEST_SALT;
};
dbg!(TEST_KEY);
let conn = Connection::open_in_memory()?; let conn = Connection::open_in_memory()?;
conn.execute( conn.execute(
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);", "ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
@@ -142,18 +141,33 @@ mod tests {
#[test] #[test]
fn test_connect_create_dir() -> TestResult { fn test_connect_create_dir() -> TestResult {
let tmp_dir = tempfile::tempdir()?; let tmp_dir = tempfile::tempdir()?;
let data_dir = tmp_dir.path().join("creddy");
let mut config = AppConfig::default();
config.data_dir = tmp_dir.path().join("creddy");
// data_dir does not exist at this point // data_dir does not exist at this point
let config = AppConfig {
data_dir,
db_salt: TEST_SALT,
};
Db::connect(&config, TEST_PASSPHRASE)?; Db::connect(&config, TEST_PASSPHRASE)?;
Ok(()) Ok(())
} }
#[test]
fn test_connect_migrates_attached_db() -> TestResult {
let data_dir = tempfile::tempdir()?;
let mut config = AppConfig::default();
config.data_dir = data_dir.path().to_path_buf();
let db = Db::connect(&config, TEST_PASSPHRASE)?;
// the migrations table should live in the encrypted db, not the in-memory one
let database: String = db.connection.lock().unwrap().query_row(
"SELECT database_name FROM duckdb_tables() WHERE table_name = '_migrations';",
[],
|row| row.get(0),
)?;
assert_eq!(database, "creddy");
Ok(())
}
#[test] #[test]
fn test_derive_key() -> TestResult { fn test_derive_key() -> TestResult {
let key = Db::derive_key(TEST_PASSPHRASE, &TEST_SALT)?; let key = Db::derive_key(TEST_PASSPHRASE, &TEST_SALT)?;
+21 -6
View File
@@ -1,11 +1,11 @@
use std::ffi::OsString; use std::ffi::OsString;
use strum::IntoStaticStr;
use thiserror::Error; use thiserror::Error;
#[derive(Error, Debug, IntoStaticStr)]
#[derive(Error, Debug)]
pub enum CreddyError { pub enum CreddyError {
#[error("Couldn't determine location for app state")] #[error("Couldn't determine location for app state")]
DataDirNotFound, DirNotFound,
#[error("Invalid path: {0:?}")] #[error("Invalid path: {0:?}")]
InvalidPath(OsString), InvalidPath(OsString),
@@ -16,12 +16,27 @@ pub enum CreddyError {
#[error("I/O error: {0}")] #[error("I/O error: {0}")]
Io(#[from] std::io::Error), Io(#[from] std::io::Error),
#[error("Unable to load saved configuration: {0}")]
ConfigDecode(#[from] serde_json::Error),
#[error("Unable to hash password: {0}")] #[error("Unable to hash password: {0}")]
PasswordHash(#[from] argon2::Error), PasswordHash(#[from] argon2::Error),
#[error("Unable to get random data: {0}")] #[error("Unable to get random data: {0}")]
Entropy(#[from] getrandom::Error), Entropy(#[from] getrandom::Error),
#[error("This database was created by a newer version of Creddy (unknown migration {0})")]
DbTooNew(String),
#[error("Migration {0} was applied before an earlier migration that hasn't been")]
MigrationOutOfOrder(String),
#[error("Invalid JSON: {0}")]
InvalidJSON(#[from] serde_json::Error),
#[error("Failed to bind socket: {0}")]
SocketBind(String),
#[error("Failed to get AWS session: {0}")]
GetSession(String),
#[error("Credential request was denied.")]
RequestDenied,
} }
+11 -49
View File
@@ -1,68 +1,30 @@
use gpui_kit::{ mod app;
AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowOptions, div, mod assets;
};
use gpui_omarchy::ActiveTheme;
mod components; mod components;
mod config; mod config;
mod credentials;
mod db; mod db;
mod error; mod error;
mod screens; mod screens;
mod session; mod session;
mod srv;
#[cfg(test)]
mod tests;
use config::AppConfig; use config::AppConfig;
use session::AppSession; use session::AppSession;
use screens::{HomeScreen, UnlockScreen, WelcomeScreen};
struct CreddyApp {}
impl Render for CreddyApp {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let session = cx.global::<AppSession>();
let screen = match session {
AppSession::Empty => window
.use_keyed_state("welcome", cx, |window, cx| {
WelcomeScreen::new(window, cx)
})
.into_any_element(),
AppSession::Locked => window
.use_keyed_state("unlock", cx, |window, cx| UnlockScreen::new(window, cx))
.into_any_element(),
AppSession::Unlocked { .. } => window
.use_keyed_state("home", cx, |_, _| HomeScreen {})
.into_any_element(),
};
let theme = cx.omarchy();
div()
.size_full()
.bg(theme.background)
.text_color(theme.foreground)
.font_family(theme.font.clone())
.child(screen)
}
}
fn main() { fn main() {
// todo: replace this with proper error handling // todo: replace this with proper error handling
let app_config = AppConfig::load().expect("failed to load config"); let app_config = AppConfig::load().expect("failed to load config");
let app_session = AppSession::load(&app_config); let app_session = AppSession::load(&app_config);
dbg!(&app_session);
// Icons are read through the asset source, so register the bundle. // Icons are read through the asset source, so register the bundle.
gpui_kit::application() gpui_kit::application()
.with_assets(gpui_kit::assets::Assets) .with_assets(assets::CreddyAssets)
.run(|app| { .run(|cx| {
gpui_omarchy::init(app); app::launch(cx, app_config, app_session);
app.set_global(app_config); cx.activate(true);
app.set_global(app_session);
// 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
app.observe_global::<AppConfig>(|app| app.refresh_windows()).detach();
app.observe_global::<AppSession>(|app| app.refresh_windows()).detach();
app.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
.expect("open window");
app.activate(true);
}); });
} }
+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)),
),
)
}
}
+425
View File
@@ -0,0 +1,425 @@
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 super::Screen;
use crate::components::{PassphraseInput, PassphraseInputEvent, colored_switch, error_alert};
use crate::credentials::AwsCredential;
use crate::session::AppSession;
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),
)
}
}
+97 -5
View File
@@ -1,13 +1,105 @@
use gpui_kit::{div, Render, Window, Context, IntoElement, Styled, ParentElement}; use gpui_kit::base::Button;
use gpui_kit::{
App, Context, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Render,
StatefulInteractiveElement, Styled, Window, div, rems,
};
use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon};
use super::Screen;
use crate::session::AppSession;
pub struct HomeScreen {} pub struct HomeScreen {}
impl Render for HomeScreen { impl Render for HomeScreen {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement { fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div() 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,
)
.on_click(|_, _, cx| cx.set_global(AppSession::Locked));
let exit = nav_tile(
"exit",
IconName::LogOut,
"Exit",
"Close Creddy.",
t.accent,
cx,
)
.on_click(|_, _, cx| cx.quit());
focus_scope("home")
.size_full()
.flex() .flex()
.justify_center() .flex_col()
.items_center() .items_center()
.child("Creddy is unlocked") .p(rems(0.5))
.child(
div()
.text_size(rems(1.875))
.font_weight(FontWeight::BOLD)
.child("Creddy"),
)
.child(
// fill the rest of the window so the tiles sit in the middle of it
div()
.flex_1()
.flex()
.items_center()
.gap(rems(1.5))
.child(credentials)
.child(lock)
.child(exit),
)
} }
} }
/// A big square-ish button with an icon, a title, and a short description.
fn nav_tile(
id: &'static str,
icon_name: IconName,
title: &'static str,
description: &'static str,
color: Hsla,
cx: &App,
) -> Button {
let t = cx.omarchy();
Button::new(id)
.accessibility_label(title)
.flex_col()
.justify_start()
.gap(rems(1.))
.w(rems(14.))
.p(rems(1.))
.border_1()
.border_color(color)
.hover(|s| s.bg(t.hover_fill()))
.focus_visible(|s| s.bg(t.hover_fill()))
.active(|s| s.bg(t.pressed_fill()))
.child(icon(icon_name).size(rems(3.)).text_color(color))
.child(
div()
.text_size(rems(1.125))
.font_weight(FontWeight::BOLD)
.child(title),
)
.child(
div()
.text_size(rems(0.875))
.text_center()
.child(description),
)
}
+38
View File
@@ -1,7 +1,45 @@
use gpui_kit::{Context, Global};
mod approval;
mod credentials;
mod home; mod home;
mod unlock; mod unlock;
mod welcome; mod welcome;
use crate::app::CreddyApp;
pub use approval::ApprovalScreen;
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;
use crate::session::AppSession;
use crate::srv::PendingRequests;
/// It's convenient to be able to reference a screen without actually constructing it
/// (e.g. when navigating), so this exists to map app state to the name of a screen.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Screen {
Welcome,
Unlock,
Home,
Credentials,
RequestApproval,
ShowApproval,
}
impl Screen {
pub fn from_context(cx: &Context<CreddyApp>) -> Screen {
match cx.global::<AppSession>() {
// we can't do anything useful when empty except ask for a passphrase, so this state takes precedence
AppSession::Empty => Screen::Welcome,
// otherwise if we have a pending request, ask for approval, even if locked (approval flow will handle unlock)
_ if cx.global::<PendingRequests>().0.len() > 0 => Screen::RequestApproval,
// therwise if locked, ask for unlock
AppSession::Locked => Screen::Unlock,
// otherwise, fall back to "current screen" global
AppSession::Unlocked(_) => *cx.global::<Screen>(),
}
}
}
impl Global for Screen {}
+21 -11
View File
@@ -1,16 +1,15 @@
use gpui_kit::{ use gpui_kit::{
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString, AppContext, BorrowAppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render,
Styled, Subscription, Task, Window, div, rems, SharedString, Styled, Subscription, Task, Window, div, rems,
}; };
use gpui_omarchy::{ButtonVariant, Status, alert, button, focus_scope}; use gpui_omarchy::{ButtonVariant, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent}; use crate::components::{PassphraseInput, PassphraseInputEvent, error_alert};
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::db::Db; use crate::db::Db;
use crate::error::CreddyError; use crate::error::CreddyError;
use crate::session::AppSession; use crate::session::AppSession;
/// Shown at startup when a database exists: enter the passphrase to open it. /// Shown at startup when a database exists: enter the passphrase to open it.
pub struct UnlockScreen { pub struct UnlockScreen {
passphrase: Entity<PassphraseInput>, passphrase: Entity<PassphraseInput>,
@@ -22,9 +21,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(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| {
@@ -58,13 +57,24 @@ impl UnlockScreen {
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
.background_spawn(async move { Db::connect(&config, passphrase.as_str()) }) .background_spawn(async move {
let db = Db::connect(&config, passphrase.as_str())?;
// Some of AppConfig comes from the db, but we couldn't see it until now
let private_config = db.load_private_config()?;
Ok((db, private_config))
})
.await; .await;
// db connection has been established or not, so now we handle the result
let _ = this.update(cx, |this, cx| { let _ = this.update(cx, |this, cx| {
this.pending = None; this.pending = None;
match result { match result {
Ok(db) => cx.set_global(AppSession::Unlocked(db)), Ok((db, private_config)) => {
cx.update_global::<AppConfig, _>(|config, _cx| {
config.merge_private(private_config)
});
cx.set_global(AppSession::Unlocked(db));
}
Err(e) => this.error = Some(error_message(&e)), Err(e) => this.error = Some(error_message(&e)),
} }
cx.notify(); cx.notify();
@@ -116,7 +126,7 @@ impl Render for UnlockScreen {
.font_weight(FontWeight::BOLD) .font_weight(FontWeight::BOLD)
.child("Please enter your passphrase"), .child("Please enter your passphrase"),
) )
.children(self.error.clone().map(|e| alert(e, Status::Error, cx))) .children(self.error.clone().map(|e| error_alert(e, cx)))
.child(self.passphrase.clone()) .child(self.passphrase.clone())
.child( .child(
button("submit", "Submit", ButtonVariant::Primary, cx) button("submit", "Submit", ButtonVariant::Primary, cx)
+29 -25
View File
@@ -1,18 +1,16 @@
use gpui_kit::{ use gpui_kit::{
AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString, AppContext, Context, Entity, FontWeight, IntoElement, ParentElement, Render, SharedString,
Styled, Subscription, Task,Window, div, rems, Styled, Subscription, Task, Window, div, rems,
}; };
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope}; use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope};
use crate::components::{PassphraseInput, PassphraseInputEvent}; use crate::components::{PassphraseInput, PassphraseInputEvent, error_alert};
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::db::Db; use crate::db::Db;
use crate::session::AppSession; use crate::session::AppSession;
const MISMATCH: &str = "Passphrases do not match."; const MISMATCH: &str = "Passphrases do not match.";
/// First-run screen: choose a passphrase, derive the key, and unlock the session. /// First-run screen: choose a passphrase, derive the key, and unlock the session.
pub struct WelcomeScreen { pub struct WelcomeScreen {
passphrase: Entity<PassphraseInput>, passphrase: Entity<PassphraseInput>,
@@ -26,23 +24,31 @@ 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(show.clone(), window, cx)); let passphrase = PassphraseInput::builder("passphrase")
let confirm = cx.new(|cx| PassphraseInput::new(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();
for input in [&passphrase, &confirm] { for input in [&passphrase, &confirm] {
_subscriptions.push(cx.subscribe_in(input, window, |this, _, event, window, cx| { _subscriptions.push(
match event { cx.subscribe_in(input, window, |this, _, event, window, cx| {
PassphraseInputEvent::Submit => this.submit(window, cx), match event {
// typing only dismisses the mismatch error, never raises it PassphraseInputEvent::Submit => this.submit(window, cx),
PassphraseInputEvent::Change if this.passphrases_match(cx) => { // typing only dismisses the mismatch error, never raises it
this.error = None; PassphraseInputEvent::Change if this.passphrases_match(cx) => {
cx.notify(); this.error = None;
cx.notify();
}
_ => (),
} }
_ => (), }),
} );
}));
} }
// leaving the confirm field is what raises the mismatch error // leaving the confirm field is what raises the mismatch error
_subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| { _subscriptions.push(cx.subscribe_in(&confirm, window, |this, _, event, _, cx| {
@@ -86,13 +92,11 @@ 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
.background_spawn(async move { .background_spawn(async move { Db::connect(&config, passphrase.as_str()) })
Db::connect(&config, passphrase.as_str())
})
.await; .await;
let _ = this.update(cx, |this, cx| { let _ = this.update(cx, |this, cx| {
@@ -162,15 +166,15 @@ impl Render for WelcomeScreen {
.flex() .flex()
.flex_col() .flex_col()
.gap(rems(1.)) .gap(rems(1.))
.children(self.error.clone().map(|e| alert(e, Status::Error, cx))) .children(self.error.clone().map(|e| error_alert(e, cx)))
.child(field("Passphrase", &self.passphrase)) .child(field("Passphrase", &self.passphrase))
.child(field("Re-enter passphrase", &self.confirm)) .child(field("Re-enter passphrase", &self.confirm))
.child( .child(
button("submit", "Submit", ButtonVariant::Primary, cx) button("submit", "Submit", ButtonVariant::Primary, cx)
.disabled(self.pending.is_some()) .disabled(self.pending.is_some())
.on_click(cx.listener(|this, _, window, cx| { .on_click(
this.submit(window, cx) cx.listener(|this, _, window, cx| this.submit(window, cx)),
})), ),
), ),
), ),
) )
+55 -14
View File
@@ -1,7 +1,6 @@
use gpui_kit::Global;
use crate::config::AppConfig; use crate::config::AppConfig;
use crate::error::CreddyError;
use crate::db::Db; use crate::db::Db;
use gpui_kit::{AsyncApp, Global};
#[derive(Debug)] #[derive(Debug)]
pub enum AppSession { pub enum AppSession {
@@ -19,8 +18,20 @@ impl AppSession {
} }
} }
pub fn unlock(&mut self, passphrase: &str) -> Result<AppSession, CreddyError> { /// Resolves once the session is unlocked, which is immediately if it already is.
todo!() pub async fn wait_for_unlock(cx: &AsyncApp) {
let (tx, rx) = smol::channel::bounded(1);
let _subscription = cx.update(|cx| {
cx.observe_global::<AppSession>(move |_| {
// a full channel already means "check again", so a failed send loses nothing
let _ = tx.try_send(());
})
});
while !cx.read_global::<AppSession, _>(|session, _| matches!(session, AppSession::Unlocked(_))) {
// the subscription owns the sender, and outlives this loop
rx.recv().await.expect("session observer was dropped");
}
} }
} }
@@ -29,15 +40,45 @@ impl Global for AppSession {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::tests::TestEnv;
use gpui_kit::TestAppContext;
use std::assert_matches;
use testresult::TestResult;
// #[test] #[test]
// fn test_new() { fn test_load_empty() -> TestResult {
// let passphrase = "correct horse battery staple"; let env = TestEnv::new()?;
// let salt = AppSession::salt().expect("salt generation failed."); let session = AppSession::load(&env.config);
// let session = AppSession::new(passphrase, &salt).expect("password KDF failed."); assert_matches!(session, AppSession::Empty);
// match session { Ok(())
// AppSession::Unlocked { .. } => (), }
// _ => panic!("AppSession::new() should return an unlocked session"),
// } #[test]
// } fn test_load_locked() -> TestResult {
let env = TestEnv::new()?;
let _ = env.db()?; // creates the database in the temp dir
let session = AppSession::load(&env.config);
assert_matches!(session, AppSession::Locked);
Ok(())
}
#[gpui_kit::test]
fn test_wait_for_unlock(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let db = env.db().unwrap();
cx.update(|cx| cx.set_global(AppSession::Locked));
let task = cx.spawn(async move |cx| AppSession::wait_for_unlock(&cx).await);
cx.run_until_parked();
assert!(!task.is_ready());
// a change that doesn't unlock shouldn't end the wait
cx.update(|cx| cx.set_global(AppSession::Locked));
cx.run_until_parked();
assert!(!task.is_ready());
cx.update(|cx| cx.set_global(AppSession::Unlocked(db)));
cx.run_until_parked();
assert!(task.is_ready());
}
} }
+186
View File
@@ -0,0 +1,186 @@
use crate::credentials::{AwsCredential, AwsSessionCache, 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};
use hyper::http::Uri;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Method, Request, Response, StatusCode};
use rustix::net::sockopt::socket_peercred;
use rustix::process::Pid;
use serde::{Deserialize, Serialize};
use smol::Timer;
use smol::net::unix::{UnixListener, UnixStream};
use smol_hyper::rt::FuturesIo;
use std::collections::{HashMap, VecDeque};
use std::convert::Infallible;
use std::fs;
use std::io;
use std::path::Path;
use std::time::Duration;
#[derive(Clone)]
pub enum CredentialRequest {
AwsGet {
name: Option<String>,
session: bool,
}
}
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 {
PendingRequests(VecDeque::new())
}
}
impl Global for PendingRequests {}
#[derive(Deserialize, Serialize)]
pub struct ErrorResponse {
code: &'static str,
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();
ErrorResponse {
code: e.into(),
message,
}
}
}
pub fn start_creddy_server(path: &Path, app: AsyncApp) -> Result<(), CreddyError> {
if path.exists() {
fs::remove_file(path)?;
}
let listener = UnixListener::bind(path)
.map_err(|_| CreddyError::SocketBind(path.to_string_lossy().into()))?;
app.spawn(async move |app| {
loop {
let (stream, pid) = match accept(&listener).await {
Ok((stream, pid)) => (stream, pid),
Err(e) => {
eprintln!("Error accepting connection: {e}");
Timer::after(Duration::from_millis(100)).await;
continue;
}
};
app.spawn(async move |app| {
let adapter = FuturesIo::new(stream);
let service = service_fn(|req| handle(req, pid, app.clone()));
let conn = http1::Builder::new().serve_connection(adapter, service);
if let Err(e) = conn.await {
eprintln!("Error serving connection: {e}")
}
})
.detach();
}
})
.detach();
Ok(())
}
async fn accept(listener: &UnixListener) -> io::Result<(UnixStream, Pid)> {
let (stream, _) = listener.accept().await?;
// pid() never returns None on Linux
let pid = socket_peercred(&stream)?.pid;
Ok((stream, pid))
}
async fn handle(
req: Request<Incoming>,
pid: Pid,
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, app).await,
(_, p) => text(StatusCode::NOT_FOUND, &format!("Not found: {p}")),
};
match response {
Ok(r) => Ok(r),
Err(e) => Ok(ErrorResponse::from(e).into_http().unwrap()),
}
}
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 name = params.get("name").map(|n| n.to_string());
let session = params.get("session").map(|s| s == "true").unwrap_or(false);
// we need to hang on to `name` so we can use it to retrieve the credential later
let req = CredentialRequest::AwsGet { name: name.clone(), session };
let (sender, receiver) = oneshot::channel::<CredentialResponse>();
app.update_global::<PendingRequests, _>(|pending, _cx| pending.0.push_back((req, sender)));
let resp = receiver.await.unwrap_or_else(|_| CredentialResponse::no());
if !resp.approved {
return Err(CreddyError::RequestDenied);
}
// it's possible to approve a request while the app is still locked, so we have to account for that
AppSession::wait_for_unlock(&app).await;
let creds = app.read_global::<AppSession, _>(|session, _cx| {
let AppSession::Unlocked(db) = session else {
unreachable!("App re-locked immediately after unlock")
};
db.load_aws_credential(&name.unwrap_or_else(|| "default".into()))
})?;
let body = if session {
let session_creds = AwsSessionCache::get_session(&creds, &app).await?;
serde_json::to_vec(&session_creds).unwrap()
} else {
serde_json::to_vec(&creds).unwrap()
};
Ok(Response::new(Full::new(Bytes::from(body))))
}
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;
Ok(response)
}
+8
View File
@@ -0,0 +1,8 @@
mod creddy_server;
pub use creddy_server::{
CredentialRequest,
CredentialResponse,
PendingRequests,
start_creddy_server
};
+435
View File
@@ -0,0 +1,435 @@
use crate::app::launch;
use crate::config::AppConfig;
use crate::credentials::AwsCredential;
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, BorrowAppContext, TestAppContext, Window};
use tempfile::TempDir;
use uuid::Uuid;
pub const TEST_PASSPHRASE: &'static str = "correct horse battery staple";
pub struct TestEnv {
// we have to keep this around or the tempdir will be deleted as soon as it's dropped
_dir: TempDir,
pub config: AppConfig,
}
impl TestEnv {
pub fn new() -> Result<TestEnv, CreddyError> {
let dir = tempfile::tempdir()?;
let path = dir.path().to_path_buf();
let config = AppConfig::load_from(path.clone(), path)?;
Ok(TestEnv { _dir: dir, config })
}
pub fn db(&self) -> Result<Db, CreddyError> {
Db::connect(&self.config, TEST_PASSPHRASE)
}
}
/// Start the app against the test environment, as `main` would.
fn open_app(env: &TestEnv, cx: &mut TestAppContext) -> AnyWindowHandle {
let window = cx.update(|cx| launch(cx, env.config.clone(), AppSession::load(&env.config)));
// first frame, so that elements exist to be found
cx.update_window(window.into(), |_, window, cx| window.render_frame(cx))
.unwrap();
window.into()
}
/// Do something in the window, then let any resulting tasks (e.g. the KDF) finish.
fn act(window: AnyWindowHandle, cx: &mut TestAppContext, f: impl FnOnce(&mut Window, &mut App)) {
cx.update_window(window, |_, window, cx| f(window, cx))
.unwrap();
cx.run_until_parked();
cx.update_window(window, |_, window, cx| window.render_frame(cx))
.unwrap();
}
/// Click into a field and type.
fn fill(window: AnyWindowHandle, id: &'static str, text: &str, cx: &mut TestAppContext) {
act(window, cx, |window, cx| {
window.click(id, cx);
window.input(text, cx);
});
}
fn click(window: AnyWindowHandle, id: &'static str, cx: &mut TestAppContext) {
act(window, cx, |window, cx| window.click(id, cx));
}
/// The message in the error alert, if one is showing.
fn error_message(window: AnyWindowHandle, cx: &mut TestAppContext) -> Option<String> {
cx.update_window(window, |_, window, _| {
window
.try_find("error")
.and_then(|e| e.label().map(String::from))
})
.unwrap()
}
fn is_unlocked(cx: &TestAppContext) -> bool {
cx.read(|cx| matches!(cx.global::<AppSession>(), AppSession::Unlocked(_)))
}
#[gpui_kit::test]
fn test_welcome_success(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
fill(window, "confirm", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_unlocked(cx));
assert!(env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_welcome_mismatch(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
fill(window, "confirm", "something else", cx);
click(window, "submit", cx);
assert_eq!(
error_message(window, cx).as_deref(),
Some("Passphrases do not match.")
);
assert!(!is_unlocked(cx));
assert!(!env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_welcome_empty(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let window = open_app(&env, cx);
click(window, "submit", cx);
assert_eq!(
error_message(window, cx).as_deref(),
Some("Passphrase is empty.")
);
assert!(!is_unlocked(cx));
assert!(!env.config.db_path().exists());
}
#[gpui_kit::test]
fn test_unlock_success(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
env.db().unwrap(); // create the db, then close it again so the app starts out locked
let window = open_app(&env, cx);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert_eq!(error_message(window, cx), None);
assert!(is_unlocked(cx));
}
#[gpui_kit::test]
fn test_unlock_wrong_passphrase(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
env.db().unwrap();
let window = open_app(&env, cx);
fill(window, "passphrase", "not the passphrase", cx);
click(window, "submit", cx);
assert_eq!(
error_message(window, cx).as_deref(),
Some("Incorrect passphrase.")
);
assert!(!is_unlocked(cx));
}
#[gpui_kit::test]
fn test_unlock_restores_private_config(cx: &mut TestAppContext) {
let env = TestEnv::new().unwrap();
let mut saved = env.config.clone();
saved.rehide_ms = 5000;
env.db()
.unwrap()
.save_private_config(&saved.private_config())
.unwrap();
let window = open_app(&env, cx);
// before unlocking, only the defaults are available
assert_eq!(
cx.read(|cx| cx.global::<AppConfig>().rehide_ms),
env.config.rehide_ms
);
fill(window, "passphrase", TEST_PASSPHRASE, cx);
click(window, "submit", cx);
assert!(is_unlocked(cx));
assert_eq!(cx.read(|cx| cx.global::<AppConfig>().rehide_ms), 5000);
}
#[gpui_kit::test]
fn test_lock(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_unlocked(cx));
click(window, "lock", cx);
assert!(cx.read(|cx| matches!(cx.global::<AppSession>(), AppSession::Locked)));
// The unlock screen should be a new one, not the old one with the passphrase still in it.
// The masked input doesn't expose its value, so check by submitting it as-is.
click(window, "submit", cx);
assert_eq!(
error_message(window, cx).as_deref(),
Some("Passphrase is empty.")
);
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());
}
#[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));
}