Compare commits
15
Commits
ce8727ee9a
...
rewrite
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8164defb1c | ||
|
|
fe9afa2ce0 | ||
|
|
3d22ae0638 | ||
|
|
58e67cc4b7 | ||
|
|
179e853dc6 | ||
|
|
009eec764e | ||
|
|
5f1ff5e4e8 | ||
|
|
49c1e81e1d | ||
|
|
72279f02de | ||
|
|
d5e7de86cb | ||
|
|
e4cfa53bce | ||
|
|
d976eebbbc | ||
|
|
c86a898879 | ||
|
|
d478c8337e | ||
|
|
e46540c077 |
No files matched your search
@@ -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
+852
-38
File diff suppressed because it is too large.
Load diff
+11
@@ -10,16 +10,27 @@ 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", "uuid"] }
|
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 = ["client", "server", "http1"] }
|
||||||
|
hyper-util = { version = "0.1.21", features = ["tokio"] }
|
||||||
include_dir = "0.7.4"
|
include_dir = "0.7.4"
|
||||||
jiff = { version = "1.0.1", features = ["serde"] }
|
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"] }
|
uuid = { version = "1.29.3", features = ["v4", "serde"] }
|
||||||
|
|||||||
+73
@@ -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")
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ use std::borrow::Cow;
|
|||||||
use gpui_kit::assets::{Assets, icon_assets};
|
use gpui_kit::assets::{Assets, icon_assets};
|
||||||
use gpui_kit::{AssetSource, Result, SharedString};
|
use gpui_kit::{AssetSource, Result, SharedString};
|
||||||
|
|
||||||
|
|
||||||
// gpui-kit only embeds the icons its own components use, so anything else has to be listed here
|
// gpui-kit only embeds the icons its own components use, so anything else has to be listed here
|
||||||
icon_assets!(CreddyIcons, [Key, LogOut, Pencil, ShieldCheck, Trash]);
|
icon_assets!(CreddyIcons, [Key, LogOut, Pencil, ShieldCheck, Trash]);
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use gpui_kit::{
|
|||||||
};
|
};
|
||||||
use gpui_omarchy::ActiveTheme;
|
use gpui_omarchy::ActiveTheme;
|
||||||
|
|
||||||
|
|
||||||
/// gpui-omarchy's switch hard-codes its track and knob colors, so this rebuilds it
|
/// 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.
|
/// from the base parts in order to tint them with `color` when checked.
|
||||||
pub fn colored_switch(
|
pub fn colored_switch(
|
||||||
@@ -41,7 +40,11 @@ pub fn colored_switch(
|
|||||||
.border_1()
|
.border_1()
|
||||||
.border_color(if checked { color } else { t.control_border() })
|
.border_color(if checked { color } else { t.control_border() })
|
||||||
.rounded_none()
|
.rounded_none()
|
||||||
.bg(if checked { color.opacity(0.18) } else { t.normal_fill() })
|
.bg(if checked {
|
||||||
|
color.opacity(0.18)
|
||||||
|
} else {
|
||||||
|
t.normal_fill()
|
||||||
|
})
|
||||||
.child(
|
.child(
|
||||||
SwitchThumb::new(checked)
|
SwitchThumb::new(checked)
|
||||||
.size(rems(1.))
|
.size(rems(1.))
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
use gpui_kit::{App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement, TestSupportExt};
|
use gpui_kit::{
|
||||||
|
App, InteractiveElement, IntoElement, Role, SharedString, StatefulInteractiveElement,
|
||||||
|
TestSupportExt,
|
||||||
|
};
|
||||||
use gpui_omarchy::{Status, alert};
|
use gpui_omarchy::{Status, alert};
|
||||||
|
|
||||||
|
|
||||||
/// An error alert whose message is also its accessible label,
|
/// 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.
|
/// 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 {
|
pub fn error_alert(message: SharedString, cx: &App) -> impl IntoElement {
|
||||||
|
|||||||
@@ -6,7 +6,6 @@ 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.
|
||||||
pub struct PassphraseInput {
|
pub struct PassphraseInput {
|
||||||
id: SharedString,
|
id: SharedString,
|
||||||
@@ -62,11 +61,16 @@ impl PassphraseInputBuilder {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// keep this field's masking in sync with the shared flag
|
// keep this field's masking in sync with the shared flag
|
||||||
let sync_mask = cx.observe_in(&show, window, |this: &mut PassphraseInput, show, window, cx| {
|
let sync_mask = cx.observe_in(
|
||||||
let masked = !*show.read(cx);
|
&show,
|
||||||
this.state.update(cx, |state, cx| state.set_masked(masked, window, cx));
|
window,
|
||||||
cx.notify();
|
|this: &mut PassphraseInput, show, window, cx| {
|
||||||
});
|
let masked = !*show.read(cx);
|
||||||
|
this.state
|
||||||
|
.update(cx, |state, cx| state.set_masked(masked, window, cx));
|
||||||
|
cx.notify();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// re-emit the subset of input events that consumers care about
|
// re-emit the subset of input events that consumers care about
|
||||||
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
|
let forward = cx.subscribe(&state, |_, _, event: &InputEvent, cx| {
|
||||||
@@ -119,8 +123,7 @@ 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")
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+49
-47
@@ -4,11 +4,10 @@ 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)]
|
||||||
@@ -29,8 +28,7 @@ impl PublicConfig {
|
|||||||
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::InvalidJSON(e))
|
serde_json::from_reader(f).map_err(|e| CreddyError::InvalidJSON(e))
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
Ok(PublicConfig::default())
|
Ok(PublicConfig::default())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -42,7 +40,7 @@ impl PublicConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Config that can be stored in the encrypted db
|
/// Config that should be stored in the encrypted db
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct PrivateConfig {
|
pub struct PrivateConfig {
|
||||||
@@ -51,15 +49,14 @@ pub struct PrivateConfig {
|
|||||||
|
|
||||||
impl Default for PrivateConfig {
|
impl Default for PrivateConfig {
|
||||||
fn default() -> PrivateConfig {
|
fn default() -> PrivateConfig {
|
||||||
PrivateConfig {
|
PrivateConfig { rehide_ms: 1000 }
|
||||||
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,
|
pub rehide_ms: u64,
|
||||||
}
|
}
|
||||||
@@ -67,31 +64,40 @@ pub struct AppConfig {
|
|||||||
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"),
|
.map(PathBuf::from)
|
||||||
dirs::data_dir(),
|
.or_else(|| dirs::data_dir().map(|d| d.join("creddy")))
|
||||||
)?;
|
.ok_or(CreddyError::DirNotFound)?;
|
||||||
|
|
||||||
AppConfig::load_from(data_dir)
|
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) -> Result<AppConfig, CreddyError> {
|
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 public_config = PublicConfig::load(&data_dir.join("public_config.json"))?;
|
||||||
let private_config = PrivateConfig::default();
|
let private_config = PrivateConfig::default();
|
||||||
Ok(AppConfig::from_parts(data_dir, public_config, private_config))
|
Ok(AppConfig::from_parts(
|
||||||
}
|
data_dir,
|
||||||
|
runtime_dir,
|
||||||
fn resolve_data_dir(creddy_data_dir: Option<OsString>, platform_data_dir: Option<PathBuf>) -> Result<PathBuf, CreddyError> {
|
public_config,
|
||||||
creddy_data_dir
|
private_config,
|
||||||
.map(PathBuf::from)
|
))
|
||||||
.or_else(|| platform_data_dir.map(|d| d.join("creddy")))
|
|
||||||
.ok_or(CreddyError::DataDirNotFound)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
|
/// Pull the appropriate fields from instances of PublicConfig and PrivateConfig (plus data_dir since that comes from neither)
|
||||||
fn from_parts(data_dir: PathBuf, public: PublicConfig, private: PrivateConfig) -> AppConfig {
|
fn from_parts(
|
||||||
|
data_dir: PathBuf,
|
||||||
|
runtime_dir: PathBuf,
|
||||||
|
public: PublicConfig,
|
||||||
|
private: PrivateConfig,
|
||||||
|
) -> AppConfig {
|
||||||
AppConfig {
|
AppConfig {
|
||||||
data_dir,
|
data_dir,
|
||||||
|
runtime_dir,
|
||||||
db_salt: public.db_salt,
|
db_salt: public.db_salt,
|
||||||
rehide_ms: private.rehide_ms,
|
rehide_ms: private.rehide_ms,
|
||||||
}
|
}
|
||||||
@@ -109,6 +115,10 @@ 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,
|
||||||
@@ -128,6 +138,7 @@ impl Default for AppConfig {
|
|||||||
// remaining defaults when constructing otherwise, and data_dir is
|
// remaining defaults when constructing otherwise, and data_dir is
|
||||||
// always specified otherwise
|
// always specified otherwise
|
||||||
AppConfig::from_parts(
|
AppConfig::from_parts(
|
||||||
|
PathBuf::from(""),
|
||||||
PathBuf::from(""),
|
PathBuf::from(""),
|
||||||
PublicConfig::default(),
|
PublicConfig::default(),
|
||||||
PrivateConfig::default(),
|
PrivateConfig::default(),
|
||||||
@@ -137,7 +148,6 @@ impl Default for AppConfig {
|
|||||||
|
|
||||||
impl Global for AppConfig {}
|
impl Global for AppConfig {}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -174,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(())
|
||||||
@@ -183,38 +194,18 @@ 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 mut config = AppConfig::default();
|
let mut config = AppConfig::default();
|
||||||
@@ -224,6 +215,17 @@ mod tests {
|
|||||||
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 mut config = AppConfig::default();
|
let mut config = AppConfig::default();
|
||||||
|
|||||||
+115
-2
@@ -1,7 +1,15 @@
|
|||||||
use jiff::Timestamp;
|
use async_compat::CompatExt;
|
||||||
use serde::{Serialize, Deserialize};
|
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 uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::error::CreddyError;
|
||||||
|
|
||||||
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Eq, PartialEq, Default, Serialize, Deserialize)]
|
||||||
pub struct AwsCredential {
|
pub struct AwsCredential {
|
||||||
pub id: Uuid,
|
pub id: Uuid,
|
||||||
@@ -19,3 +27,108 @@ pub struct AwsSessionCredential {
|
|||||||
pub session_token: String,
|
pub session_token: String,
|
||||||
pub expiration: Timestamp,
|
pub expiration: Timestamp,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct AwsSessionCache {
|
||||||
|
pub 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,3 +1,3 @@
|
|||||||
mod aws;
|
mod aws;
|
||||||
|
|
||||||
pub use aws::{AwsCredential, AwsSessionCredential};
|
pub use aws::{AwsCredential, AwsSessionCache, AwsSessionCredential};
|
||||||
+97
-29
@@ -1,10 +1,10 @@
|
|||||||
use duckdb::{Error, params};
|
|
||||||
use uuid::Uuid;
|
|
||||||
use crate::credentials::AwsCredential;
|
|
||||||
use super::Db;
|
use super::Db;
|
||||||
|
use crate::credentials::AwsCredential;
|
||||||
|
use duckdb::{Error, OptionalExt, params};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
impl Db {
|
impl Db {
|
||||||
pub fn load_aws_credential(&self, name: &str) -> Result<AwsCredential, Error> {
|
pub fn load_aws_credential(&self, name: &str) -> Result<Option<AwsCredential>, Error> {
|
||||||
let conn = self.connection.lock().unwrap();
|
let conn = self.connection.lock().unwrap();
|
||||||
conn.query_row(
|
conn.query_row(
|
||||||
"SELECT
|
"SELECT
|
||||||
@@ -16,14 +16,40 @@ impl Db {
|
|||||||
FROM aws_credentials
|
FROM aws_credentials
|
||||||
WHERE name = ?",
|
WHERE name = ?",
|
||||||
params![name],
|
params![name],
|
||||||
|row| Ok(AwsCredential {
|
|row| {
|
||||||
id: row.get(0)?,
|
Ok(AwsCredential {
|
||||||
name: row.get(1)?,
|
id: row.get(0)?,
|
||||||
access_key_id: row.get(2)?,
|
name: row.get(1)?,
|
||||||
secret_access_key: row.get(3)?,
|
access_key_id: row.get(2)?,
|
||||||
is_default: row.get(4)?,
|
secret_access_key: row.get(3)?,
|
||||||
})
|
is_default: row.get(4)?,
|
||||||
)
|
})
|
||||||
|
},
|
||||||
|
).optional()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn load_aws_default(&self) -> Result<Option<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 is_default = true",
|
||||||
|
[],
|
||||||
|
|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)?,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
).optional()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn save_aws_credential(&self, cred: &AwsCredential) -> Result<(), Error> {
|
pub fn save_aws_credential(&self, cred: &AwsCredential) -> Result<(), Error> {
|
||||||
@@ -53,7 +79,13 @@ impl Db {
|
|||||||
access_key_id = EXCLUDED.access_key_id,
|
access_key_id = EXCLUDED.access_key_id,
|
||||||
secret_access_key = EXCLUDED.secret_access_key,
|
secret_access_key = EXCLUDED.secret_access_key,
|
||||||
is_default = EXCLUDED.is_default",
|
is_default = EXCLUDED.is_default",
|
||||||
params![cred.id, cred.name, cred.access_key_id, cred.secret_access_key, cred.is_default],
|
params![
|
||||||
|
cred.id,
|
||||||
|
cred.name,
|
||||||
|
cred.access_key_id,
|
||||||
|
cred.secret_access_key,
|
||||||
|
cred.is_default
|
||||||
|
],
|
||||||
)?;
|
)?;
|
||||||
tx.commit()
|
tx.commit()
|
||||||
}
|
}
|
||||||
@@ -74,25 +106,26 @@ impl Db {
|
|||||||
secret_access_key,
|
secret_access_key,
|
||||||
is_default
|
is_default
|
||||||
FROM aws_credentials
|
FROM aws_credentials
|
||||||
ORDER BY created_at"
|
ORDER BY created_at",
|
||||||
)?;
|
)?;
|
||||||
stmt.query_map([], |row| {
|
stmt.query_map([], |row| {
|
||||||
Ok(AwsCredential{
|
Ok(AwsCredential {
|
||||||
id: row.get(0)?,
|
id: row.get(0)?,
|
||||||
name: row.get(1)?,
|
name: row.get(1)?,
|
||||||
access_key_id: row.get(2)?,
|
access_key_id: row.get(2)?,
|
||||||
secret_access_key: row.get(3)?,
|
secret_access_key: row.get(3)?,
|
||||||
is_default: row.get(4)?,
|
is_default: row.get(4)?,
|
||||||
})
|
})
|
||||||
})?.collect()
|
})?
|
||||||
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use testresult::TestResult;
|
|
||||||
use crate::test_data::TestEnv;
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::tests::TestEnv;
|
||||||
|
use testresult::TestResult;
|
||||||
|
|
||||||
fn test_cred(name: &str, access_key_id: &str) -> AwsCredential {
|
fn test_cred(name: &str, access_key_id: &str) -> AwsCredential {
|
||||||
AwsCredential {
|
AwsCredential {
|
||||||
@@ -121,12 +154,37 @@ mod tests {
|
|||||||
let cred = test_cred("test", "AKIAEXAMPLE");
|
let cred = test_cred("test", "AKIAEXAMPLE");
|
||||||
db.save_aws_credential(&cred)?;
|
db.save_aws_credential(&cred)?;
|
||||||
|
|
||||||
let loaded = db.load_aws_credential("test")?;
|
let loaded = db.load_aws_credential("test")?.unwrap();
|
||||||
|
|
||||||
assert_eq!(loaded, cred);
|
assert_eq!(loaded, cred);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_load_default() -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
let db = env.db()?;
|
||||||
|
|
||||||
|
let mut cred = test_cred("test", "AKIAEXAMPLE");
|
||||||
|
cred.is_default = true;
|
||||||
|
db.save_aws_credential(&cred)?;
|
||||||
|
|
||||||
|
let loaded = db.load_aws_default()?.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(loaded, cred);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_load_missing() -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
let db = env.db()?;
|
||||||
|
|
||||||
|
let opt = db.load_aws_credential("test")?;
|
||||||
|
assert!(opt.is_none());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_update() -> TestResult {
|
fn test_update() -> TestResult {
|
||||||
let env = TestEnv::new()?;
|
let env = TestEnv::new()?;
|
||||||
@@ -150,7 +208,7 @@ mod tests {
|
|||||||
let (created_at, updated_at): (i64, i64) = conn.query_row(
|
let (created_at, updated_at): (i64, i64) = conn.query_row(
|
||||||
"SELECT created_at, updated_at FROM aws_credentials WHERE name = 'renamed'",
|
"SELECT created_at, updated_at FROM aws_credentials WHERE name = 'renamed'",
|
||||||
[],
|
[],
|
||||||
|row| Ok((row.get(0)?, row.get(1)?))
|
|row| Ok((row.get(0)?, row.get(1)?)),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
assert!(updated_at > created_at);
|
assert!(updated_at > created_at);
|
||||||
@@ -178,14 +236,24 @@ mod tests {
|
|||||||
let cred2 = test_cred("test1", "KEY2");
|
let cred2 = test_cred("test1", "KEY2");
|
||||||
db.save_aws_credential(&cred2)?;
|
db.save_aws_credential(&cred2)?;
|
||||||
|
|
||||||
let creds = db.list_aws_credentials()?;
|
let list = db.list_aws_credentials()?;
|
||||||
assert_eq!(creds.len(), 2);
|
assert_eq!(list.len(), 2);
|
||||||
assert_eq!(creds[0], cred1);
|
assert_eq!(list[0], cred1);
|
||||||
assert_eq!(creds[1], cred2);
|
assert_eq!(list[1], cred2);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_list_empty() -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
let db = env.db()?;
|
||||||
|
|
||||||
|
let list = db.list_aws_credentials()?;
|
||||||
|
assert!(list.is_empty());
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_delete() -> TestResult {
|
fn test_delete() -> TestResult {
|
||||||
let env = TestEnv::new()?;
|
let env = TestEnv::new()?;
|
||||||
@@ -217,16 +285,16 @@ mod tests {
|
|||||||
cred2.is_default = true;
|
cred2.is_default = true;
|
||||||
db.save_aws_credential(&cred2)?;
|
db.save_aws_credential(&cred2)?;
|
||||||
|
|
||||||
assert!(!db.load_aws_credential("test")?.is_default);
|
assert!(!db.load_aws_credential("test")?.unwrap().is_default);
|
||||||
assert!(db.load_aws_credential("test2")?.is_default);
|
assert!(db.load_aws_credential("test2")?.unwrap().is_default);
|
||||||
|
|
||||||
// re-saving the current default shouldn't trip over its own row
|
// re-saving the current default shouldn't trip over its own row
|
||||||
db.save_aws_credential(&cred2)?;
|
db.save_aws_credential(&cred2)?;
|
||||||
assert!(db.load_aws_credential("test2")?.is_default);
|
assert!(db.load_aws_credential("test2")?.unwrap().is_default);
|
||||||
|
|
||||||
db.save_aws_credential(&cred1)?;
|
db.save_aws_credential(&cred1)?;
|
||||||
assert!(db.load_aws_credential("test")?.is_default);
|
assert!(db.load_aws_credential("test")?.unwrap().is_default);
|
||||||
assert!(!db.load_aws_credential("test2")?.is_default);
|
assert!(!db.load_aws_credential("test2")?.unwrap().is_default);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-6
@@ -1,6 +1,6 @@
|
|||||||
|
use super::Db;
|
||||||
use crate::config::PrivateConfig;
|
use crate::config::PrivateConfig;
|
||||||
use crate::error::CreddyError;
|
use crate::error::CreddyError;
|
||||||
use super::Db;
|
|
||||||
|
|
||||||
impl Db {
|
impl Db {
|
||||||
pub fn load_private_config(&self) -> Result<PrivateConfig, CreddyError> {
|
pub fn load_private_config(&self) -> Result<PrivateConfig, CreddyError> {
|
||||||
@@ -21,11 +21,10 @@ impl Db {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use testresult::TestResult;
|
|
||||||
use tempfile::TempDir;
|
|
||||||
use crate::config::AppConfig;
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use crate::config::AppConfig;
|
||||||
|
use tempfile::TempDir;
|
||||||
|
use testresult::TestResult;
|
||||||
|
|
||||||
fn test_db() -> Result<(Db, TempDir), CreddyError> {
|
fn test_db() -> Result<(Db, TempDir), CreddyError> {
|
||||||
let data_dir = tempfile::tempdir()?;
|
let data_dir = tempfile::tempdir()?;
|
||||||
@@ -44,7 +43,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_load_priate_config() -> TestResult {
|
fn test_load_private_config() -> TestResult {
|
||||||
let (db, _data_dir) = test_db()?;
|
let (db, _data_dir) = test_db()?;
|
||||||
let private_config = PrivateConfig::default();
|
let private_config = PrivateConfig::default();
|
||||||
db.save_private_config(&private_config)?;
|
db.save_private_config(&private_config)?;
|
||||||
|
|||||||
+14
-8
@@ -3,16 +3,13 @@ use include_dir::{Dir, include_dir};
|
|||||||
|
|
||||||
use crate::error::CreddyError;
|
use crate::error::CreddyError;
|
||||||
|
|
||||||
|
|
||||||
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
|
static MIGRATIONS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/migrations");
|
||||||
|
|
||||||
|
|
||||||
struct Migration {
|
struct Migration {
|
||||||
id: &'static str,
|
id: &'static str,
|
||||||
sql: &'static str,
|
sql: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// Run all unapplied database migrations.
|
/// Run all unapplied database migrations.
|
||||||
pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> {
|
pub fn migrate(conn: &mut Connection) -> Result<(), CreddyError> {
|
||||||
apply_migrations(conn, &embedded_migrations())
|
apply_migrations(conn, &embedded_migrations())
|
||||||
@@ -25,7 +22,11 @@ fn embedded_migrations() -> Vec<Migration> {
|
|||||||
.filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
|
.filter(|f| f.path().extension().is_some_and(|ext| ext == "sql"))
|
||||||
.map(|f| Migration {
|
.map(|f| Migration {
|
||||||
// these are baked in at compile time, so a bad file is a build problem, not a runtime one
|
// 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"),
|
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"),
|
sql: f.contents_utf8().expect("migration file is not UTF-8"),
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -81,11 +82,10 @@ fn list_applied_migrations(conn: &Connection) -> Result<Vec<String>, CreddyError
|
|||||||
Ok(ids)
|
Ok(ids)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use testresult::TestResult;
|
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use testresult::TestResult;
|
||||||
|
|
||||||
const FIRST: Migration = Migration {
|
const FIRST: Migration = Migration {
|
||||||
id: "0001_first.sql",
|
id: "0001_first.sql",
|
||||||
@@ -110,7 +110,10 @@ mod tests {
|
|||||||
migrate(&mut conn)?;
|
migrate(&mut conn)?;
|
||||||
|
|
||||||
let applied = list_applied_migrations(&conn)?;
|
let applied = list_applied_migrations(&conn)?;
|
||||||
let expected: Vec<_> = embedded_migrations().iter().map(|m| m.id.to_string()).collect();
|
let expected: Vec<_> = embedded_migrations()
|
||||||
|
.iter()
|
||||||
|
.map(|m| m.id.to_string())
|
||||||
|
.collect();
|
||||||
assert_eq!(applied, expected);
|
assert_eq!(applied, expected);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -123,7 +126,10 @@ mod tests {
|
|||||||
|
|
||||||
// already-applied migrations are skipped, so re-running FIRST would fail if it weren't
|
// already-applied migrations are skipped, so re-running FIRST would fail if it weren't
|
||||||
apply_migrations(&mut conn, &[FIRST, SECOND])?;
|
apply_migrations(&mut conn, &[FIRST, SECOND])?;
|
||||||
assert_eq!(list_applied_migrations(&conn)?, ["0001_first.sql", "0002_second.sql"]);
|
assert_eq!(
|
||||||
|
list_applied_migrations(&conn)?,
|
||||||
|
["0001_first.sql", "0002_second.sql"]
|
||||||
|
);
|
||||||
assert!(table_exists(&conn, "b")?);
|
assert!(table_exists(&conn, "b")?);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-20
@@ -1,14 +1,11 @@
|
|||||||
|
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,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::error::CreddyError;
|
|
||||||
use crate::config::AppConfig;
|
use crate::config::AppConfig;
|
||||||
|
use crate::error::CreddyError;
|
||||||
|
|
||||||
mod aws;
|
mod aws;
|
||||||
mod config;
|
mod config;
|
||||||
@@ -29,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>,
|
||||||
@@ -42,21 +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 mut conn = Connection::open_in_memory()?;
|
let mut conn = Connection::open_in_memory()?;
|
||||||
conn.execute(
|
conn.execute("ATTACH ? AS creddy (ENCRYPTION_KEY ?);", params![path, key])?;
|
||||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
|
||||||
params![path, key],
|
|
||||||
)?;
|
|
||||||
// must come before migrating, or the tables end up in the in-memory db
|
// must come before migrating, or the tables end up in the in-memory db
|
||||||
conn.execute("USE creddy;", [])?;
|
conn.execute("USE creddy;", [])?;
|
||||||
migrations::migrate(&mut conn)?;
|
migrations::migrate(&mut conn)?;
|
||||||
Ok(Self{ connection: Mutex::new(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
|
||||||
@@ -77,12 +73,11 @@ impl Db {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use testresult::TestResult;
|
|
||||||
use duckdb::Error;
|
|
||||||
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];
|
||||||
@@ -103,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
|
||||||
@@ -115,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"),
|
||||||
}
|
}
|
||||||
|
|||||||
+15
-3
@@ -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),
|
||||||
@@ -30,4 +30,16 @@ pub enum CreddyError {
|
|||||||
|
|
||||||
#[error("Invalid JSON: {0}")]
|
#[error("Invalid JSON: {0}")]
|
||||||
InvalidJSON(#[from] serde_json::Error),
|
InvalidJSON(#[from] serde_json::Error),
|
||||||
|
|
||||||
|
#[error("Failed to bind socket: {0}")]
|
||||||
|
SocketBind(String),
|
||||||
|
|
||||||
|
#[error("Failed to get AWS session: {0}")]
|
||||||
|
GetSession(String),
|
||||||
|
|
||||||
|
#[error("Credential not found: \"{0}\"")]
|
||||||
|
CredentialNotFound(String),
|
||||||
|
|
||||||
|
#[error("Credential request was denied.")]
|
||||||
|
RequestDenied,
|
||||||
}
|
}
|
||||||
+6
-412
@@ -1,9 +1,4 @@
|
|||||||
use gpui_kit::{
|
mod app;
|
||||||
App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window, WindowHandle,
|
|
||||||
WindowOptions, div,
|
|
||||||
};
|
|
||||||
use gpui_omarchy::ActiveTheme;
|
|
||||||
|
|
||||||
mod assets;
|
mod assets;
|
||||||
mod components;
|
mod components;
|
||||||
mod config;
|
mod config;
|
||||||
@@ -12,63 +7,13 @@ mod db;
|
|||||||
mod error;
|
mod error;
|
||||||
mod screens;
|
mod screens;
|
||||||
mod session;
|
mod session;
|
||||||
|
mod srv;
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test_data;
|
mod tests;
|
||||||
|
|
||||||
use config::AppConfig;
|
use config::AppConfig;
|
||||||
use session::AppSession;
|
use session::AppSession;
|
||||||
use screens::{CredentialsScreen, HomeScreen, Screen, 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 { .. } => match cx.global::<Screen>() {
|
|
||||||
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(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
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.
|
|
||||||
fn launch(cx: &mut App, config: AppConfig, session: AppSession) -> WindowHandle<CreddyApp> {
|
|
||||||
gpui_omarchy::init(cx);
|
|
||||||
cx.set_global(config);
|
|
||||||
cx.set_global(session);
|
|
||||||
cx.set_global(Screen::Home);
|
|
||||||
// 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.open_window(WindowOptions::default(), |_, cx| cx.new(|_| CreddyApp {}))
|
|
||||||
.expect("open window")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn main() {
|
fn main() {
|
||||||
// todo: replace this with proper error handling
|
// todo: replace this with proper error handling
|
||||||
@@ -78,359 +23,8 @@ fn main() {
|
|||||||
// 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(assets::CreddyAssets)
|
.with_assets(assets::CreddyAssets)
|
||||||
.run(|app| {
|
.run(|cx| {
|
||||||
launch(app, app_config, app_session);
|
app::launch(cx, app_config, app_session);
|
||||||
app.activate(true);
|
cx.activate(true);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use gpui_kit::{AnyWindowHandle, TestAppContext};
|
|
||||||
use gpui_kit::test::TestWindowExt;
|
|
||||||
use uuid::Uuid;
|
|
||||||
use super::*;
|
|
||||||
use crate::credentials::AwsCredential;
|
|
||||||
use crate::test_data::{TEST_PASSPHRASE, TestEnv};
|
|
||||||
|
|
||||||
/// 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());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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)),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+88
-33
@@ -8,13 +8,12 @@ use gpui_omarchy::{
|
|||||||
focus_scope, icon_button, input, tab_list,
|
focus_scope, icon_button, input, tab_list,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use super::Screen;
|
||||||
use crate::components::{PassphraseInput, PassphraseInputEvent, colored_switch, error_alert};
|
use crate::components::{PassphraseInput, PassphraseInputEvent, colored_switch, error_alert};
|
||||||
use crate::credentials::AwsCredential;
|
use crate::credentials::AwsCredential;
|
||||||
use crate::session::AppSession;
|
use crate::session::AppSession;
|
||||||
use super::Screen;
|
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
|
||||||
pub struct CredentialsScreen {
|
pub struct CredentialsScreen {
|
||||||
tab: usize,
|
tab: usize,
|
||||||
aws: Vec<AwsCredential>,
|
aws: Vec<AwsCredential>,
|
||||||
@@ -36,7 +35,13 @@ struct AwsForm {
|
|||||||
|
|
||||||
impl CredentialsScreen {
|
impl CredentialsScreen {
|
||||||
pub fn new(cx: &mut Context<Self>) -> Self {
|
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 };
|
let mut this = Self {
|
||||||
|
tab: 0,
|
||||||
|
aws: Vec::new(),
|
||||||
|
aws_form: None,
|
||||||
|
aws_deleting: None,
|
||||||
|
error: None,
|
||||||
|
};
|
||||||
this.load_aws(cx);
|
this.load_aws(cx);
|
||||||
this
|
this
|
||||||
}
|
}
|
||||||
@@ -50,20 +55,27 @@ impl CredentialsScreen {
|
|||||||
Ok(creds) => {
|
Ok(creds) => {
|
||||||
self.aws = creds;
|
self.aws = creds;
|
||||||
self.error = None;
|
self.error = None;
|
||||||
},
|
}
|
||||||
Err(e) => self.error = Some(format!("Failed to load credentials: {e}").into()),
|
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>) {
|
fn open_aws_form(
|
||||||
let existing = self.aws
|
&mut self,
|
||||||
|
editing: Option<Uuid>,
|
||||||
|
window: &mut Window,
|
||||||
|
cx: &mut Context<Self>,
|
||||||
|
) {
|
||||||
|
let existing = self
|
||||||
|
.aws
|
||||||
.iter()
|
.iter()
|
||||||
.find(|cred| Some(cred.id) == editing)
|
.find(|cred| Some(cred.id) == editing)
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
let name = cx.new(|cx| InputState::new(window, cx).default_value(existing.name));
|
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 access_key_id =
|
||||||
|
cx.new(|cx| InputState::new(window, cx).default_value(existing.access_key_id));
|
||||||
let secret_access_key = PassphraseInput::builder("aws-secret")
|
let secret_access_key = PassphraseInput::builder("aws-secret")
|
||||||
.value(existing.secret_access_key)
|
.value(existing.secret_access_key)
|
||||||
.build(window, cx);
|
.build(window, cx);
|
||||||
@@ -106,13 +118,21 @@ impl CredentialsScreen {
|
|||||||
is_default: form.is_default,
|
is_default: form.is_default,
|
||||||
};
|
};
|
||||||
|
|
||||||
if cred.name.is_empty() || cred.access_key_id.is_empty() || cred.secret_access_key.is_empty() {
|
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());
|
self.error = Some("All fields are required.".into());
|
||||||
cx.notify();
|
cx.notify();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if self.aws.iter().any(|existing| existing.name == cred.name && existing.id != cred.id) {
|
if self
|
||||||
self.error = Some(format!("An AWS credential named \"{}\" already exists.", cred.name).into());
|
.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();
|
cx.notify();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -124,7 +144,7 @@ impl CredentialsScreen {
|
|||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
self.aws_form = None;
|
self.aws_form = None;
|
||||||
self.load_aws(cx);
|
self.load_aws(cx);
|
||||||
},
|
}
|
||||||
Err(e) => self.error = Some(format!("Failed to save credential: {e}").into()),
|
Err(e) => self.error = Some(format!("Failed to save credential: {e}").into()),
|
||||||
}
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
@@ -138,7 +158,7 @@ impl CredentialsScreen {
|
|||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
self.aws_deleting = None;
|
self.aws_deleting = None;
|
||||||
self.load_aws(cx);
|
self.load_aws(cx);
|
||||||
},
|
}
|
||||||
Err(e) => self.error = Some(format!("Failed to delete credential: {e}").into()),
|
Err(e) => self.error = Some(format!("Failed to delete credential: {e}").into()),
|
||||||
}
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
@@ -149,7 +169,11 @@ impl CredentialsScreen {
|
|||||||
|
|
||||||
let mut panel = div().flex().flex_col().gap(rems(0.5));
|
let mut panel = div().flex().flex_col().gap(rems(0.5));
|
||||||
if self.aws.is_empty() {
|
if self.aws.is_empty() {
|
||||||
panel = panel.child(empty_state("AWS access keys", "You have no saved AWS credentials.", cx));
|
panel = panel.child(empty_state(
|
||||||
|
"AWS access keys",
|
||||||
|
"You have no saved AWS credentials.",
|
||||||
|
cx,
|
||||||
|
));
|
||||||
}
|
}
|
||||||
for cred in &self.aws {
|
for cred in &self.aws {
|
||||||
if let Some(form) = &self.aws_form
|
if let Some(form) = &self.aws_form
|
||||||
@@ -180,7 +204,9 @@ impl CredentialsScreen {
|
|||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
button("aws-delete-confirm", "Delete", ButtonVariant::Danger, cx)
|
button("aws-delete-confirm", "Delete", ButtonVariant::Danger, cx)
|
||||||
.on_click(cx.listener(move |this, _, _, cx| this.delete_aws(id, cx))),
|
.on_click(
|
||||||
|
cx.listener(move |this, _, _, cx| this.delete_aws(id, cx)),
|
||||||
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
continue;
|
continue;
|
||||||
@@ -197,7 +223,10 @@ impl CredentialsScreen {
|
|||||||
.border_1()
|
.border_1()
|
||||||
.border_color(if cred.is_default { t.accent } else { t.border })
|
.border_color(if cred.is_default { t.accent } else { t.border })
|
||||||
.child(div().font_weight(FontWeight::BOLD).child(cred.name.clone()))
|
.child(div().font_weight(FontWeight::BOLD).child(cred.name.clone()))
|
||||||
.children(cred.is_default.then(|| badge("Default", Status::Success, cx)))
|
.children(
|
||||||
|
cred.is_default
|
||||||
|
.then(|| badge("Default", Status::Success, cx)),
|
||||||
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.ml_auto()
|
.ml_auto()
|
||||||
@@ -213,9 +242,9 @@ impl CredentialsScreen {
|
|||||||
ButtonVariant::Outline,
|
ButtonVariant::Outline,
|
||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.on_click(cx.listener(move |this, _, window, cx| {
|
.on_click(cx.listener(
|
||||||
this.open_aws_form(Some(id), window, cx)
|
move |this, _, window, cx| this.open_aws_form(Some(id), window, cx),
|
||||||
})),
|
)),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
icon_button(
|
icon_button(
|
||||||
@@ -238,9 +267,13 @@ impl CredentialsScreen {
|
|||||||
button("aws-add", "Add", ButtonVariant::Primary, cx)
|
button("aws-add", "Add", ButtonVariant::Primary, cx)
|
||||||
.self_center()
|
.self_center()
|
||||||
.mt(rems(0.5))
|
.mt(rems(0.5))
|
||||||
.on_click(cx.listener(|this, _, window, cx| this.open_aws_form(None, window, cx))),
|
.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(form) if form.editing.is_none() => {
|
||||||
|
panel.child(self.render_aws_form(form, window, cx))
|
||||||
|
}
|
||||||
Some(_) => panel,
|
Some(_) => panel,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -264,27 +297,41 @@ impl CredentialsScreen {
|
|||||||
.p(rems(1.))
|
.p(rems(1.))
|
||||||
.border_1()
|
.border_1()
|
||||||
.border_color(t.border)
|
.border_color(t.border)
|
||||||
.child(field("Name", input("aws-name", &form.name, window, cx).into_any_element()))
|
.child(field(
|
||||||
|
"Name",
|
||||||
|
input("aws-name", &form.name, window, cx).into_any_element(),
|
||||||
|
))
|
||||||
.child(field(
|
.child(field(
|
||||||
"Key ID",
|
"Key ID",
|
||||||
input("aws-key-id", &form.access_key_id, window, cx)
|
input("aws-key-id", &form.access_key_id, window, cx)
|
||||||
.font_family(t.mono_font.clone())
|
.font_family(t.mono_font.clone())
|
||||||
.into_any_element(),
|
.into_any_element(),
|
||||||
))
|
))
|
||||||
.child(field("Secret key", form.secret_access_key.clone().into_any_element()))
|
.child(field(
|
||||||
|
"Secret key",
|
||||||
|
form.secret_access_key.clone().into_any_element(),
|
||||||
|
))
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.flex()
|
.flex()
|
||||||
.items_center()
|
.items_center()
|
||||||
.gap(rems(0.5))
|
.gap(rems(0.5))
|
||||||
.child(
|
.child(
|
||||||
colored_switch("aws-default", "Default AWS access key", form.is_default, t.success, cx)
|
colored_switch(
|
||||||
.on_change(move |value, _, _, cx| this.update(cx, |this, cx| {
|
"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 {
|
if let Some(form) = &mut this.aws_form {
|
||||||
form.is_default = value;
|
form.is_default = value;
|
||||||
}
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
})),
|
})
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
button("aws-cancel", "Cancel", ButtonVariant::Outline, cx)
|
button("aws-cancel", "Cancel", ButtonVariant::Outline, cx)
|
||||||
@@ -315,10 +362,12 @@ impl Render for CredentialsScreen {
|
|||||||
],
|
],
|
||||||
Some(self.tab),
|
Some(self.tab),
|
||||||
false,
|
false,
|
||||||
move |index, _, cx| this.update(cx, |this, cx| {
|
move |index, _, cx| {
|
||||||
this.tab = index;
|
this.update(cx, |this, cx| {
|
||||||
cx.notify();
|
this.tab = index;
|
||||||
}),
|
cx.notify();
|
||||||
|
})
|
||||||
|
},
|
||||||
window,
|
window,
|
||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
@@ -343,10 +392,16 @@ impl Render for CredentialsScreen {
|
|||||||
.flex()
|
.flex()
|
||||||
.justify_center()
|
.justify_center()
|
||||||
.child(
|
.child(
|
||||||
icon_button("back", IconName::ChevronLeft, "Back", ButtonVariant::Secondary, cx)
|
icon_button(
|
||||||
.absolute()
|
"back",
|
||||||
.left_0()
|
IconName::ChevronLeft,
|
||||||
.on_click(|_, _, cx| cx.set_global(Screen::Home)),
|
"Back",
|
||||||
|
ButtonVariant::Secondary,
|
||||||
|
cx,
|
||||||
|
)
|
||||||
|
.absolute()
|
||||||
|
.left_0()
|
||||||
|
.on_click(|_, _, cx| cx.set_global(Screen::Home)),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
|
|||||||
+40
-10
@@ -5,21 +5,41 @@ use gpui_kit::{
|
|||||||
};
|
};
|
||||||
use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon};
|
use gpui_omarchy::{ActiveTheme, IconName, focus_scope, icon};
|
||||||
|
|
||||||
use crate::session::AppSession;
|
|
||||||
use super::Screen;
|
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, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let t = cx.omarchy();
|
let t = cx.omarchy();
|
||||||
let credentials = nav_tile("credentials", IconName::Key, "Credentials", "Add, remove, and change credentials.", t.success, cx)
|
let credentials = nav_tile(
|
||||||
.on_click(|_, _, cx| cx.set_global(Screen::Credentials));
|
"credentials",
|
||||||
let lock = nav_tile("lock", IconName::ShieldCheck, "Lock", "Lock Creddy.", t.warning, cx)
|
IconName::Key,
|
||||||
.on_click(|_, _, cx| cx.set_global(AppSession::Locked));
|
"Credentials",
|
||||||
let exit = nav_tile("exit", IconName::LogOut, "Exit", "Close Creddy.", t.accent, cx)
|
"Add, remove, and change credentials.",
|
||||||
.on_click(|_, _, cx| cx.quit());
|
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")
|
focus_scope("home")
|
||||||
.size_full()
|
.size_full()
|
||||||
@@ -70,6 +90,16 @@ fn nav_tile(
|
|||||||
.focus_visible(|s| s.bg(t.hover_fill()))
|
.focus_visible(|s| s.bg(t.hover_fill()))
|
||||||
.active(|s| s.bg(t.pressed_fill()))
|
.active(|s| s.bg(t.pressed_fill()))
|
||||||
.child(icon(icon_name).size(rems(3.)).text_color(color))
|
.child(icon(icon_name).size(rems(3.)).text_color(color))
|
||||||
.child(div().text_size(rems(1.125)).font_weight(FontWeight::BOLD).child(title))
|
.child(
|
||||||
.child(div().text_size(rems(0.875)).text_center().child(description))
|
div()
|
||||||
|
.text_size(rems(1.125))
|
||||||
|
.font_weight(FontWeight::BOLD)
|
||||||
|
.child(title),
|
||||||
|
)
|
||||||
|
.child(
|
||||||
|
div()
|
||||||
|
.text_size(rems(0.875))
|
||||||
|
.text_center()
|
||||||
|
.child(description),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
+27
-3
@@ -1,21 +1,45 @@
|
|||||||
use gpui_kit::Global;
|
use gpui_kit::{Context, Global};
|
||||||
|
|
||||||
|
mod approval;
|
||||||
mod credentials;
|
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 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
|
||||||
/// Which screen to show while the app is unlocked.
|
/// (e.g. when navigating), so this exists to map app state to the name of a screen.
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
pub enum Screen {
|
pub enum Screen {
|
||||||
|
Welcome,
|
||||||
|
Unlock,
|
||||||
Home,
|
Home,
|
||||||
Credentials,
|
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 {}
|
impl Global for Screen {}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
use gpui_kit::{
|
use gpui_kit::{
|
||||||
AppContext, BorrowAppContext, 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, button, focus_scope};
|
use gpui_omarchy::{ButtonVariant, button, focus_scope};
|
||||||
|
|
||||||
@@ -10,7 +10,6 @@ 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>,
|
||||||
@@ -71,9 +70,11 @@ impl UnlockScreen {
|
|||||||
this.pending = None;
|
this.pending = None;
|
||||||
match result {
|
match result {
|
||||||
Ok((db, private_config)) => {
|
Ok((db, private_config)) => {
|
||||||
cx.update_global::<AppConfig, _>(|config, _cx| config.merge_private(private_config));
|
cx.update_global::<AppConfig, _>(|config, _cx| {
|
||||||
|
config.merge_private(private_config)
|
||||||
|
});
|
||||||
cx.set_global(AppSession::Unlocked(db));
|
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();
|
||||||
|
|||||||
+17
-19
@@ -1,6 +1,6 @@
|
|||||||
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, button, focus_scope};
|
use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope};
|
||||||
|
|
||||||
@@ -9,10 +9,8 @@ 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>,
|
||||||
@@ -38,17 +36,19 @@ impl WelcomeScreen {
|
|||||||
|
|
||||||
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| {
|
||||||
@@ -96,9 +96,7 @@ impl WelcomeScreen {
|
|||||||
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| {
|
||||||
@@ -174,9 +172,9 @@ impl Render for WelcomeScreen {
|
|||||||
.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)),
|
||||||
})),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
+39
-3
@@ -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 {
|
||||||
@@ -18,6 +17,22 @@ impl AppSession {
|
|||||||
AppSession::Empty
|
AppSession::Empty
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Resolves once the session is unlocked, which is immediately if it already is.
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Global for AppSession {}
|
impl Global for AppSession {}
|
||||||
@@ -25,9 +40,10 @@ 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 std::assert_matches;
|
||||||
use testresult::TestResult;
|
use testresult::TestResult;
|
||||||
use crate::test_data::TestEnv;
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_load_empty() -> TestResult {
|
fn test_load_empty() -> TestResult {
|
||||||
@@ -45,4 +61,24 @@ mod tests {
|
|||||||
assert_matches!(session, AppSession::Locked);
|
assert_matches!(session, AppSession::Locked);
|
||||||
Ok(())
|
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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,342 @@
|
|||||||
|
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 {
|
||||||
|
#[serde(skip)]
|
||||||
|
status: StatusCode,
|
||||||
|
name: &'static str,
|
||||||
|
message: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ErrorResponse {
|
||||||
|
fn into_http(&self) -> serde_json::Result<Response<Full<Bytes>>> {
|
||||||
|
let bytes = serde_json::to_vec(self)?;
|
||||||
|
let mut resp = Response::new(Full::new(Bytes::from(bytes)));
|
||||||
|
*resp.status_mut() = self.status;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<CreddyError> for ErrorResponse {
|
||||||
|
fn from(e: CreddyError) -> ErrorResponse {
|
||||||
|
let status = match e {
|
||||||
|
CreddyError::CredentialNotFound(_) => StatusCode::NOT_FOUND,
|
||||||
|
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
};
|
||||||
|
let message = e.to_string();
|
||||||
|
let name: &'static str = e.into();
|
||||||
|
ErrorResponse { status, name, 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?;
|
||||||
|
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(true);
|
||||||
|
|
||||||
|
// 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")
|
||||||
|
};
|
||||||
|
match &name {
|
||||||
|
Some(name) => db.load_aws_credential(name),
|
||||||
|
None => db.load_aws_default(),
|
||||||
|
}
|
||||||
|
})?
|
||||||
|
.ok_or_else(|| CreddyError::CredentialNotFound(name.unwrap_or_else(|| "default".into())))?;
|
||||||
|
|
||||||
|
// regardless of what was requested, the user's response
|
||||||
|
// determines what type of credentials are issued
|
||||||
|
let body = if resp.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)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::tests::TestEnv;
|
||||||
|
use gpui_kit::TestAppContext;
|
||||||
|
use http_body_util::{BodyExt, Empty};
|
||||||
|
use hyper::client::conn::http1::handshake;
|
||||||
|
use super::*;
|
||||||
|
use testresult::TestResult;
|
||||||
|
|
||||||
|
async fn get(uri: &str, addr: &Path, cx: &TestAppContext) -> TestResult<Response<Incoming>> {
|
||||||
|
let stream = UnixStream::connect(addr).await?;
|
||||||
|
let (mut sender, conn) = handshake(FuturesIo::new(stream)).await?;
|
||||||
|
cx.foreground_executor.spawn(conn).detach();
|
||||||
|
|
||||||
|
let req = Request::get(uri).body(Empty::<Bytes>::new())?;
|
||||||
|
let resp = sender.send_request(req).await?;
|
||||||
|
Ok(resp)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unlock the session, and stand in for the user by approving requests as they arrive.
|
||||||
|
fn unlock_and_approve(env: &TestEnv, cx: &mut TestAppContext, session: bool) -> TestResult {
|
||||||
|
let db = env.db()?;
|
||||||
|
cx.update(|cx| {
|
||||||
|
cx.set_global(AppSession::Unlocked(db));
|
||||||
|
cx.set_global(AwsSessionCache::default());
|
||||||
|
cx.set_global(PendingRequests::new());
|
||||||
|
cx.observe_global::<PendingRequests>(move |cx| {
|
||||||
|
// popping notifies this observer again, so make sure that stops when the queue is empty
|
||||||
|
if cx.global::<PendingRequests>().0.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (_, sender) = cx.global_mut::<PendingRequests>().0.pop_front().unwrap();
|
||||||
|
let resp = CredentialResponse { approved: true, session };
|
||||||
|
let _ = sender.send(resp);
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
});
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Save a long-term credential, along with a cached session for it so nothing has to talk to AWS.
|
||||||
|
fn save_cred(name: &str, is_default: bool, cx: &mut TestAppContext) -> (AwsCredential, AwsSessionCredential) {
|
||||||
|
let cred = AwsCredential {
|
||||||
|
id: uuid::Uuid::new_v4(),
|
||||||
|
name: name.into(),
|
||||||
|
access_key_id: format!("AKIA{name}"),
|
||||||
|
secret_access_key: "EXAMPLESECRET".into(),
|
||||||
|
is_default,
|
||||||
|
};
|
||||||
|
let session = AwsSessionCredential {
|
||||||
|
version: 1,
|
||||||
|
access_key_id: format!("ASIA{name}"),
|
||||||
|
secret_access_key: "SESSIONSECRET".into(),
|
||||||
|
session_token: "TOKEN".into(),
|
||||||
|
expiration: "2100-01-01T00:00:00Z".parse().unwrap(),
|
||||||
|
};
|
||||||
|
cx.update(|cx| {
|
||||||
|
let AppSession::Unlocked(db) = cx.global::<AppSession>() else {
|
||||||
|
panic!("locked")
|
||||||
|
};
|
||||||
|
db.save_aws_credential(&cred).unwrap();
|
||||||
|
cx.global_mut::<AwsSessionCache>()
|
||||||
|
.sessions
|
||||||
|
.insert(cred.access_key_id.clone(), session.clone());
|
||||||
|
});
|
||||||
|
(cred, session)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn aws_get<T: serde::de::DeserializeOwned>(uri: &'static str, cx: &TestAppContext) -> TestResult<T> {
|
||||||
|
let resp = handle_aws_get(Uri::from_static(uri), cx.to_async()).await?;
|
||||||
|
let body = resp.into_body().collect().await?.to_bytes();
|
||||||
|
Ok(serde_json::from_slice(&body)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gpui_kit::test]
|
||||||
|
async fn test_start_server(cx: &mut TestAppContext) -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
cx.executor().allow_parking();
|
||||||
|
let addr = env.config.creddy_server_addr();
|
||||||
|
start_creddy_server(&addr, cx.to_async())?;
|
||||||
|
|
||||||
|
let resp = get("/ping", &addr, cx).await?;
|
||||||
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
|
||||||
|
let body = resp.into_body().collect().await?.to_bytes();
|
||||||
|
assert_eq!(body, "pong");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gpui_kit::test]
|
||||||
|
async fn test_aws_get_missing_credential(cx: &mut TestAppContext) -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
cx.executor().allow_parking();
|
||||||
|
unlock_and_approve(&env, cx, true)?;
|
||||||
|
let addr = env.config.creddy_server_addr();
|
||||||
|
start_creddy_server(&addr, cx.to_async())?;
|
||||||
|
|
||||||
|
let resp = get("/aws?name=nonexistent", &addr, cx).await?;
|
||||||
|
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||||
|
let body = resp.into_body().collect().await?.to_bytes();
|
||||||
|
let error: serde_json::Value = serde_json::from_slice(&body)?;
|
||||||
|
assert_eq!(error["name"], "CredentialNotFound");
|
||||||
|
assert_eq!(error["message"], "Credential not found: \"nonexistent\"");
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gpui_kit::test]
|
||||||
|
async fn test_aws_get_default(cx: &mut TestAppContext) -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
unlock_and_approve(&env, cx, true)?;
|
||||||
|
save_cred("other", false, cx);
|
||||||
|
let (_, session) = save_cred("work", true, cx);
|
||||||
|
|
||||||
|
let returned: AwsSessionCredential = aws_get("/aws", cx).await?;
|
||||||
|
assert_eq!(returned, session);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gpui_kit::test]
|
||||||
|
async fn test_aws_get_named(cx: &mut TestAppContext) -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
unlock_and_approve(&env, cx, true)?;
|
||||||
|
let (_, session) = save_cred("other", false, cx);
|
||||||
|
save_cred("work", true, cx);
|
||||||
|
|
||||||
|
let returned: AwsSessionCredential = aws_get("/aws?name=other", cx).await?;
|
||||||
|
assert_eq!(returned, session);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[gpui_kit::test]
|
||||||
|
async fn test_aws_get_longterm(cx: &mut TestAppContext) -> TestResult {
|
||||||
|
let env = TestEnv::new()?;
|
||||||
|
unlock_and_approve(&env, cx, false)?;
|
||||||
|
let (cred, _) = save_cred("work", true, cx);
|
||||||
|
|
||||||
|
let returned: AwsCredential = aws_get("/aws?name=work&session=false", cx).await?;
|
||||||
|
assert_eq!(returned, cred);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
mod creddy_server;
|
||||||
|
|
||||||
|
pub use creddy_server::{
|
||||||
|
CredentialRequest,
|
||||||
|
CredentialResponse,
|
||||||
|
PendingRequests,
|
||||||
|
start_creddy_server
|
||||||
|
};
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
use tempfile::TempDir;
|
|
||||||
use crate::config::AppConfig;
|
|
||||||
use crate::db::Db;
|
|
||||||
use crate::error::CreddyError;
|
|
||||||
|
|
||||||
|
|
||||||
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 config = AppConfig::load_from(dir.path().to_path_buf())?;
|
|
||||||
Ok(TestEnv { _dir: dir, config })
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn db(&self) -> Result<Db, CreddyError> {
|
|
||||||
Db::connect(&self.config, TEST_PASSPHRASE)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -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().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().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));
|
||||||
|
}
|
||||||
Reference in new issue
Block a user