initial commit - just the welcome screen and db connection, at present
This commit is contained in:
1 parent
d67871f491
commit
2bd81a66a4
10 files changed
+9377
No files matched your search
@@ -10,3 +10,8 @@ pacman/*.tar.zst
|
||||
|
||||
# temporary worktree for master while we work on rewrite
|
||||
master
|
||||
|
||||
|
||||
# Added by cargo
|
||||
|
||||
/target
|
||||
Generated
+8983
File diff suppressed because it is too large.
Load diff
+23
@@ -0,0 +1,23 @@
|
||||
[package]
|
||||
name = "creddy"
|
||||
version = "0.7.0"
|
||||
description = "A friendly AWS credentials manager"
|
||||
authors = ["Joseph Montanaro"]
|
||||
license = ""
|
||||
repository = ""
|
||||
default-run = "creddy"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
argon2 = { version = "0.6.0", features = ["parallel", "zeroize"] }
|
||||
base64ct = "1.8.3"
|
||||
dirs = "7.0.0"
|
||||
duckdb = { version = "1.20000.1", features = ["bundled"] }
|
||||
getrandom = { version = "0.4.3", features = ["sys_rng"] }
|
||||
gpui-kit = "0.7.0"
|
||||
gpui-omarchy = "0.2.1"
|
||||
is-terminal = "0.4.17"
|
||||
thiserror = "2.0.21"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.27.0"
|
||||
@@ -0,0 +1,36 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use is_terminal::IsTerminal;
|
||||
|
||||
use crate::error::CreddyError;
|
||||
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AppConfig {
|
||||
pub db_path: PathBuf,
|
||||
}
|
||||
|
||||
impl AppConfig {
|
||||
pub fn default() -> Result<AppConfig, CreddyError> {
|
||||
Ok(AppConfig {
|
||||
db_path: default_db_path()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn default_db_path() -> Result<PathBuf, CreddyError> {
|
||||
let mut path = dirs::data_dir()
|
||||
.ok_or(CreddyError::DataDirNotFound)?;
|
||||
path.push("creddy");
|
||||
|
||||
std::fs::create_dir_all(&path)?;
|
||||
if cfg!(debug_assertions) && std::io::stdout().is_terminal() {
|
||||
path.push("creddy.dev.duckdb");
|
||||
}
|
||||
else {
|
||||
path.push("creddy.duckdb");
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
use base64ct::{Base64, Encoding};
|
||||
use duckdb::{
|
||||
Connection,
|
||||
params,
|
||||
Error,
|
||||
};
|
||||
|
||||
use crate::config::{self, AppConfig};
|
||||
|
||||
|
||||
struct Db {
|
||||
connection: Connection,
|
||||
}
|
||||
|
||||
impl Db {
|
||||
pub fn connect(config: &AppConfig, key: &[u8; 32]) -> Result<Self, Error> {
|
||||
// DuckDB docks say to use base64 for the key, so that's what we'll do
|
||||
let mut b64_key = [0u8; 44]; // 32 bytes take up 44 chars of base64
|
||||
let key_str = Base64::encode(key, &mut b64_key).expect("Wrong-sized input buffer"); // should never happen
|
||||
|
||||
let conn = Connection::open_in_memory()?;
|
||||
// hard-code the path for now, until we get proper config set up
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![config.db_path.to_string_lossy(), key_str],
|
||||
)?;
|
||||
conn.execute("USE creddy;", [])?;
|
||||
Ok(Self{ connection: conn })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_connect_new() {
|
||||
let data_dir = tempfile::tempdir().unwrap();
|
||||
let db_path = data_dir.path().join("creddy.test.db");
|
||||
|
||||
let config = AppConfig { db_path: db_path.clone() };
|
||||
let key = [0u8; 32];
|
||||
let res = Db::connect(&config, &key);
|
||||
assert!(res.is_ok());
|
||||
|
||||
// confirm that db is in fact encrypted
|
||||
match Connection::open(&db_path) {
|
||||
Err(Error::DuckDBFailure(error, _desc)) => {
|
||||
assert!(error.code == duckdb::ErrorCode::Unknown);
|
||||
assert!(error.extended_code == 1);
|
||||
},
|
||||
Err(e) => panic!("Unexpected error type: {e:?}"),
|
||||
Ok(_) => panic!("Should not be able to open newly-created database without encryption key"),
|
||||
};
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_connect_existing() {
|
||||
let data_dir = tempfile::tempdir().unwrap();
|
||||
let db_path = data_dir.path().join("creddy.test.db");
|
||||
let key = [0u8; 32];
|
||||
let key_str = Base64::encode_string(&key);
|
||||
|
||||
let conn = Connection::open_in_memory().unwrap();
|
||||
conn.execute(
|
||||
"ATTACH ? AS creddy (ENCRYPTION_KEY ?);",
|
||||
params![&db_path.to_string_lossy(), &key_str],
|
||||
).unwrap();
|
||||
|
||||
let config = AppConfig { db_path: db_path };
|
||||
let res = Db::connect(&config, &key);
|
||||
assert!(res.is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use thiserror::Error;
|
||||
|
||||
|
||||
#[derive(Error, Debug)]
|
||||
pub enum CreddyError {
|
||||
#[error("Couldn't determine location for app state")]
|
||||
DataDirNotFound,
|
||||
#[error("Error from database: {0}")]
|
||||
Db(#[from] duckdb::Error),
|
||||
#[error("I/O error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
use gpui_kit::{
|
||||
AppContext, Context, Entity, IntoElement, ParentElement, Render, Styled, Window, WindowOptions,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, button, focus_scope, panel};
|
||||
|
||||
mod config;
|
||||
mod db;
|
||||
mod error;
|
||||
mod screens;
|
||||
mod session;
|
||||
|
||||
use session::AppSession;
|
||||
use screens::WelcomeScreen;
|
||||
|
||||
enum AppScreen {
|
||||
Welcome(Entity<WelcomeScreen>),
|
||||
}
|
||||
|
||||
struct CreddyApp {
|
||||
session: Entity<AppSession>,
|
||||
screen: AppScreen,
|
||||
}
|
||||
|
||||
impl Render for CreddyApp {
|
||||
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
|
||||
match &self.screen {
|
||||
AppScreen::Welcome(s) => s.clone().into_any_element(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Icons are read through the asset source, so register the bundle.
|
||||
gpui_kit::application()
|
||||
.with_assets(gpui_kit::assets::Assets)
|
||||
.run(|cx| {
|
||||
gpui_omarchy::init(cx);
|
||||
let session = cx.new(|_| AppSession::Empty);
|
||||
cx.open_window(WindowOptions::default(), |window, cx| {
|
||||
let screen = AppScreen::Welcome(
|
||||
cx.new(|cx| WelcomeScreen::new(session.clone(), window, cx)),
|
||||
);
|
||||
cx.new(|_| CreddyApp { session, screen })
|
||||
})
|
||||
.expect("open window");
|
||||
cx.activate(true);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
mod welcome;
|
||||
|
||||
pub use welcome::WelcomeScreen;
|
||||
@@ -0,0 +1,130 @@
|
||||
use gpui_kit::base::input::{InputEvent, InputState};
|
||||
use gpui_kit::{
|
||||
AppContext, Context, Entity, IntoElement, ParentElement, Render, SharedString, Styled,
|
||||
Subscription, Task, Window, div, rems,
|
||||
};
|
||||
use gpui_omarchy::{ActiveTheme, ButtonVariant, Status, alert, button, focus_scope, input, panel};
|
||||
|
||||
use crate::session::AppSession;
|
||||
|
||||
|
||||
/// First-run screen: choose a passphrase, derive the key, and unlock the session.
|
||||
pub struct WelcomeScreen {
|
||||
session: Entity<AppSession>,
|
||||
passphrase: Entity<InputState>,
|
||||
confirm: Entity<InputState>,
|
||||
error: Option<SharedString>,
|
||||
/// Set while the KDF is running; dropping it cancels the task.
|
||||
pending: Option<Task<()>>,
|
||||
_subscriptions: Vec<Subscription>,
|
||||
}
|
||||
|
||||
impl WelcomeScreen {
|
||||
pub fn new(session: Entity<AppSession>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||
let passphrase = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(true)
|
||||
.placeholder("Passphrase")
|
||||
});
|
||||
let confirm = cx.new(|cx| {
|
||||
InputState::new(window, cx)
|
||||
.masked(true)
|
||||
.placeholder("Confirm passphrase")
|
||||
});
|
||||
passphrase.update(cx, |state, cx| state.focus(window, cx));
|
||||
|
||||
// Enter in either field submits
|
||||
let _subscriptions = [&passphrase, &confirm]
|
||||
.into_iter()
|
||||
.map(|field| {
|
||||
cx.subscribe_in(field, window, |this, _, event, window, cx| {
|
||||
if let InputEvent::PressEnter { .. } = event {
|
||||
this.submit(window, cx);
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
session,
|
||||
passphrase,
|
||||
confirm,
|
||||
error: None,
|
||||
pending: None,
|
||||
_subscriptions,
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(&mut self, _: &mut Window, cx: &mut Context<Self>) {
|
||||
if self.pending.is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let passphrase = self.passphrase.read(cx).value();
|
||||
let confirm = self.confirm.read(cx).value();
|
||||
if passphrase.is_empty() {
|
||||
self.error = Some("Passphrase cannot be empty.".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
if passphrase != confirm {
|
||||
self.error = Some("Passphrases do not match.".into());
|
||||
cx.notify();
|
||||
return;
|
||||
}
|
||||
|
||||
self.error = None;
|
||||
// todo: persist the salt (and KDF params) so the database can be unlocked again later
|
||||
self.pending = Some(cx.spawn(async move |this, cx| {
|
||||
// argon2 is deliberately slow, so keep it off the UI thread
|
||||
let result = cx
|
||||
.background_spawn(async move {
|
||||
let salt = AppSession::salt().map_err(|e| e.to_string())?;
|
||||
AppSession::new(&passphrase, &salt).map_err(|e| e.to_string())
|
||||
})
|
||||
.await;
|
||||
|
||||
let _ = this.update(cx, |this, cx| {
|
||||
this.pending = None;
|
||||
match result {
|
||||
Ok(unlocked) => {
|
||||
this.session.update(cx, |session, cx| {
|
||||
*session = unlocked;
|
||||
cx.notify();
|
||||
});
|
||||
}
|
||||
Err(e) => this.error = Some(format!("Failed to derive key: {e}").into()),
|
||||
}
|
||||
cx.notify();
|
||||
});
|
||||
}));
|
||||
cx.notify();
|
||||
}
|
||||
}
|
||||
|
||||
impl Render for WelcomeScreen {
|
||||
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||
let busy = self.pending.is_some();
|
||||
let label = if busy { "Creating…" } else { "Get started" };
|
||||
|
||||
focus_scope("welcome")
|
||||
.size_full()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.bg(cx.omarchy().background)
|
||||
.child(
|
||||
panel("Welcome to Creddy", cx)
|
||||
.w(rems(24.))
|
||||
.child(div().child("Choose a passphrase to encrypt your credentials."))
|
||||
.child(input("passphrase", &self.passphrase, window, cx))
|
||||
.child(input("confirm", &self.confirm, window, cx))
|
||||
.children(self.error.clone().map(|e| alert(e, Status::Error, cx)))
|
||||
.child(
|
||||
button("get-started", label, ButtonVariant::Primary, cx)
|
||||
.disabled(busy)
|
||||
.on_click(cx.listener(|this, _, window, cx| this.submit(window, cx))),
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use argon2::{Algorithm, Argon2, ParamsBuilder, Result as Argon2Result, Version};
|
||||
|
||||
// tests take forever with production parameters, so we turn them down in dev
|
||||
#[cfg(not(debug_assertions))]
|
||||
const MEM_COST: u32 = 128 * 1024;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const TIME_COST: u32 = 8;
|
||||
#[cfg(not(debug_assertions))]
|
||||
const PARALLELISM_COST: u32 = 4;
|
||||
|
||||
#[cfg(debug_assertions)]
|
||||
const MEM_COST: u32 = 48 * 1024;
|
||||
#[cfg(debug_assertions)]
|
||||
const TIME_COST: u32 = 1;
|
||||
#[cfg(debug_assertions)]
|
||||
const PARALLELISM_COST: u32 = 1;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum AppSession {
|
||||
Empty,
|
||||
Locked,
|
||||
Unlocked { key: [u8; 32] },
|
||||
}
|
||||
|
||||
impl AppSession {
|
||||
pub fn new(passphrase: &str, salt: &[u8]) -> Argon2Result<Self> {
|
||||
let params = ParamsBuilder::new()
|
||||
.m_cost(MEM_COST)
|
||||
.t_cost(TIME_COST)
|
||||
.p_cost(PARALLELISM_COST)
|
||||
.build()
|
||||
.unwrap(); // only errors if the given params are invalid
|
||||
|
||||
let hasher = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
|
||||
|
||||
let mut key = [0; 32]; // todo: replace this with a `zeroize` or `secrecy` type
|
||||
hasher.hash_password_into(passphrase.as_bytes(), &salt, &mut key)?;
|
||||
Ok(Self::Unlocked { key })
|
||||
}
|
||||
|
||||
pub fn salt() -> Result<[u8; 32], getrandom::Error> {
|
||||
let mut salt = [0; 32];
|
||||
getrandom::fill(&mut salt)?;
|
||||
Ok(salt)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new() {
|
||||
let passphrase = "correct horse battery staple";
|
||||
let salt = AppSession::salt().expect("salt generation failed.");
|
||||
let session = AppSession::new(passphrase, &salt).expect("password KDF failed.");
|
||||
match session {
|
||||
AppSession::Unlocked { .. } => (),
|
||||
_ => panic!("AppSession::new() should return an unlocked session"),
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user