Compare commits

...

4 Commits

12 changed files with 310 additions and 4 deletions

View File

@ -0,0 +1,27 @@
use std::io;
use anyhow::bail;
use crate::proto::{CliResponse, DockerCredential};
use super::{
CliCredential,
CliRequest,
GlobalArgs
};
pub fn docker_store(global_args: GlobalArgs) -> anyhow::Result<()> {
let input: DockerCredential = serde_json::from_reader(io::stdin())?;
dbg!(&input);
let req = CliRequest::SaveCredential {
name: input.username.clone(),
is_default: false, // is_default doesn't really mean anything for Docker credentials
credential: CliCredential::Docker(input),
};
match super::make_request(global_args.server_addr, &req)?? {
CliResponse::Empty => Ok(()),
r => bail!("Unexpected response from server: {r}"),
}
}

View File

@ -22,6 +22,8 @@ use crate::proto::{
ShortcutAction, ShortcutAction,
}; };
mod docker;
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[command( #[command(
@ -70,6 +72,9 @@ pub enum Action {
Exec(ExecArgs), Exec(ExecArgs),
/// Invoke an action normally triggered by hotkey (e.g. launch terminal) /// Invoke an action normally triggered by hotkey (e.g. launch terminal)
Shortcut(InvokeArgs), Shortcut(InvokeArgs),
/// Interact with Docker credentials via the docker-credential-helper protocol
#[command(subcommand)]
Docker(DockerCmd),
} }
@ -101,6 +106,17 @@ pub struct InvokeArgs {
} }
#[derive(Debug, Subcommand)]
pub enum DockerCmd {
/// Get a stored Docker credential
Get,
/// Store a new Docker credential
Store,
/// Remove a stored Docker credential
Erase,
}
pub fn get(args: GetArgs, global: GlobalArgs) -> anyhow::Result<()> { pub fn get(args: GetArgs, global: GlobalArgs) -> anyhow::Result<()> {
let req = CliRequest::GetCredential { let req = CliRequest::GetCredential {
name: args.name, name: args.name,
@ -185,10 +201,20 @@ pub fn invoke_shortcut(args: InvokeArgs, global: GlobalArgs) -> anyhow::Result<(
} }
pub fn docker_credential_helper(cmd: DockerCmd, global_args: GlobalArgs) -> anyhow::Result<()> {
match cmd {
DockerCmd::Get => todo!(),
DockerCmd::Store => docker::docker_store(global_args),
DockerCmd::Erase => todo!(),
}
}
// Explanation for double-result: the server will return a (serialized) Result // Explanation for double-result: the server will return a (serialized) Result
// to indicate when the operation succeeded or failed, which we deserialize. // to indicate when the operation succeeded or failed, which we deserialize.
// However, the operation may fail to even communicate with the server, in // However, the operation may fail to even communicate with the server, in
// which case we return the outer Result // which case we return the outer Result
// (probably this should be modeled differently)
#[tokio::main] #[tokio::main]
async fn make_request( async fn make_request(
addr: Option<PathBuf>, addr: Option<PathBuf>,

View File

@ -5,6 +5,7 @@ pub use cli::{
exec, exec,
get, get,
invoke_shortcut, invoke_shortcut,
docker_credential_helper,
}; };
pub(crate) use platform::connect; pub(crate) use platform::connect;

View File

@ -11,6 +11,7 @@ fn main() {
Some(Action::Get(args)) => creddy_cli::get(args, cli.global_args), Some(Action::Get(args)) => creddy_cli::get(args, cli.global_args),
Some(Action::Exec(args)) => creddy_cli::exec(args, cli.global_args), Some(Action::Exec(args)) => creddy_cli::exec(args, cli.global_args),
Some(Action::Shortcut(args)) => creddy_cli::invoke_shortcut(args, cli.global_args), Some(Action::Shortcut(args)) => creddy_cli::invoke_shortcut(args, cli.global_args),
Some(Action::Docker(cmd)) => creddy_cli::docker_credential_helper(cmd, cli.global_args),
}; };
if let Err(e) = res { if let Err(e) = res {

View File

@ -14,6 +14,11 @@ pub enum CliRequest {
name: Option<String>, name: Option<String>,
base: bool, base: bool,
}, },
SaveCredential {
name: String,
is_default: bool,
credential: CliCredential,
},
InvokeShortcut(ShortcutAction), InvokeShortcut(ShortcutAction),
} }
@ -36,6 +41,7 @@ impl Display for CliResponse {
match self { match self {
CliResponse::Credential(CliCredential::AwsBase(_)) => write!(f, "Credential (AwsBase)"), CliResponse::Credential(CliCredential::AwsBase(_)) => write!(f, "Credential (AwsBase)"),
CliResponse::Credential(CliCredential::AwsSession(_)) => write!(f, "Credential (AwsSession)"), CliResponse::Credential(CliCredential::AwsSession(_)) => write!(f, "Credential (AwsSession)"),
CliResponse::Credential(CliCredential::Docker(_)) => write!(f, "Credential (Docker)"),
CliResponse::Empty => write!(f, "Empty"), CliResponse::Empty => write!(f, "Empty"),
} }
} }
@ -46,6 +52,7 @@ impl Display for CliResponse {
pub enum CliCredential { pub enum CliCredential {
AwsBase(AwsBaseCredential), AwsBase(AwsBaseCredential),
AwsSession(AwsSessionCredential), AwsSession(AwsSessionCredential),
Docker(DockerCredential),
} }
@ -75,6 +82,16 @@ pub struct AwsSessionCredential {
fn default_aws_version() -> usize { 1 } fn default_aws_version() -> usize { 1 }
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DockerCredential {
#[serde(rename = "ServerURL")]
pub server_url: String,
pub username: String,
pub secret: String,
}
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct ServerError { pub struct ServerError {
code: String, code: String,

View File

@ -0,0 +1,11 @@
CREATE TABLE docker_credentials (
id BLOB UNIQUE NOT NULL,
-- The Docker credential helper protocol only sends the server_url, so
-- we should guarantee that we will only ever have one matching credential.
-- Also, it's easier to go from unique -> not-unique than vice versa if we
-- decide that's necessary in the future
server_url TEXT UNIQUE NOT NULL,
username TEXT NOT NULL,
secret_enc BLOB NOT NULL,
nonce BLOB NOT NULL
);

View File

@ -0,0 +1,197 @@
use chacha20poly1305::XNonce;
use serde::{Serialize, Deserialize};
use sqlx::{
FromRow,
Sqlite,
Transaction,
types::Uuid,
};
use super::{Credential, Crypto, PersistentCredential};
use crate::errors::*;
#[derive(Debug, Clone, FromRow)]
pub struct DockerRow {
id: Uuid,
server_url: String,
username: String,
secret_enc: Vec<u8>,
nonce: Vec<u8>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub struct DockerCredential {
#[serde(rename = "ServerURL")]
pub server_url: String,
pub username: String,
pub secret: String,
}
impl PersistentCredential for DockerCredential {
type Row = DockerRow;
fn type_name() -> &'static str { "docker" }
fn into_credential(self) -> Credential { Credential::Docker(self) }
fn row_id(row: &DockerRow) -> Uuid { row.id }
fn from_row(row: DockerRow, crypto: &Crypto) -> Result<Self, LoadCredentialsError> {
let nonce = XNonce::clone_from_slice(&row.nonce);
let secret_bytes = crypto.decrypt(&nonce, &row.secret_enc)?;
let secret = String::from_utf8(secret_bytes)
.map_err(|_| LoadCredentialsError::InvalidData)?;
Ok(DockerCredential {
server_url: row.server_url,
username: row.username,
secret
})
}
async fn save_details(&self, id: &Uuid, crypto: &Crypto, txn: &mut Transaction<'_, Sqlite>) -> Result<(), SaveCredentialsError> {
let (nonce, ciphertext) = crypto.encrypt(self.secret.as_bytes())?;
let nonce_bytes = &nonce.as_slice();
sqlx::query!(
"INSERT OR REPLACE INTO docker_credentials (
id,
server_url,
username,
secret_enc,
nonce
)
VALUES (?, ?, ?, ?, ?)",
id, self.server_url, self.username, ciphertext, nonce_bytes,
).execute(&mut **txn).await?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::credentials::CredentialRecord;
use creddy_cli::proto::DockerCredential as CliDockerCredential;
use sqlx::SqlitePool;
use sqlx::types::uuid::uuid;
fn test_credential() -> DockerCredential {
DockerCredential {
server_url: "https://registry.jfmonty2.com".into(),
username: "joe@jfmonty2.com".into(),
secret: "correct horse battery staple".into(),
}
}
fn test_credential_2() -> DockerCredential {
DockerCredential {
server_url: "https://index.docker.io/v1".into(),
username: "test@example.com".into(),
secret: "a very secure passphrase".into(),
}
}
fn test_record() -> CredentialRecord {
CredentialRecord {
id: uuid!("00000000-0000-0000-0000-000000000000"),
name: "docker_test".into(),
is_default: false,
credential: Credential::Docker(test_credential()),
}
}
fn test_record_2() -> CredentialRecord {
CredentialRecord {
id: uuid!("ffffffff-ffff-ffff-ffff-ffffffffffff"),
name: "docker_test_2".into(),
is_default: false,
credential: Credential::Docker(test_credential_2()),
}
}
#[sqlx::test]
fn test_save(pool: SqlitePool) {
let crypt = Crypto::random();
test_record().save(&crypt, &pool).await
.expect("Failed to save record");
}
#[sqlx::test(fixtures("docker_credentials"))]
fn test_load(pool: SqlitePool) {
let crypt = Crypto::fixed();
let id = uuid!("00000000-0000-0000-0000-000000000000");
let loaded = DockerCredential::load(&id, &crypt, &pool).await
.expect("Failed to load record");
assert_eq!(test_credential(), loaded);
}
#[sqlx::test(fixtures("docker_credentials"))]
async fn test_overwrite(pool: SqlitePool) {
let crypt = Crypto::fixed();
let mut record = test_record_2();
// give it the same id as test_record so that it overwrites
let id = uuid!("00000000-0000-0000-0000-000000000000");
record.id = id;
record.save(&crypt, &pool).await
.expect("Failed to overwrite original record with second record");
let loaded = DockerCredential::load(&id, &crypt, &pool).await
.expect("Failed to load again after overwriting");
assert_eq!(test_credential_2(), loaded);
}
#[sqlx::test(fixtures("docker_credentials"))]
async fn test_list(pool: SqlitePool) {
let crypt = Crypto::fixed();
let records = CredentialRecord::list(&crypt, &pool).await
.expect("Failed to list credentials");
assert_eq!(test_record(), records[0]);
}
// make sure that CLI credentials and app credentials don't drift apart
#[test]
fn test_cli_to_app() {
let cli_creds = CliDockerCredential {
server_url: "https://registry.jfmonty2.com".into(),
username: "joe@jfmonty2.com".into(),
secret: "correct horse battery staple".into(),
};
let json = serde_json::to_string(&cli_creds).unwrap();
let computed: DockerCredential = serde_json::from_str(&json)
.expect("Failed to deserialize Docker credentials from CLI -> main app");
assert_eq!(test_credential(), computed);
}
#[test]
fn test_app_to_cli() {
let app_creds = test_credential();
let json = serde_json::to_string(&app_creds).unwrap();
let computed: CliDockerCredential = serde_json::from_str(&json)
.expect("Failed to deserialize Docker credentials from main app -> CLI");
let expected = CliDockerCredential {
server_url: "https://registry.jfmonty2.com".into(),
username: "joe@jfmonty2.com".into(),
secret: "correct horse battery staple".into(),
};
assert_eq!(expected, computed);
}
}

View File

@ -0,0 +1,11 @@
INSERT INTO credentials (id, name, credential_type, is_default, created_at)
VALUES (X'00000000000000000000000000000000', 'docker_test', 'docker', 0, 1726756380);
INSERT INTO docker_credentials (id, server_url, username, secret_enc, nonce)
VALUES (
X'00000000000000000000000000000000',
'https://registry.jfmonty2.com',
'joe@jfmonty2.com',
X'C0B36EE54539D4113A8F73E99FB96B2BF4D87E91F7C3B48256C07E83E3E7EC738888B2FDE2B4DB0BE48BEFDE',
X'C5F7F627BBE09A1BB275BE8D2390596C76143881A7766E60'
);

View File

@ -17,6 +17,9 @@ pub use aws::{AwsBaseCredential, AwsSessionCredential};
mod crypto; mod crypto;
pub use crypto::Crypto; pub use crypto::Crypto;
mod docker;
pub use docker::DockerCredential;
mod record; mod record;
pub use record::CredentialRecord; pub use record::CredentialRecord;
@ -32,6 +35,7 @@ pub use ssh::SshKey;
pub enum Credential { pub enum Credential {
AwsBase(AwsBaseCredential), AwsBase(AwsBaseCredential),
AwsSession(AwsSessionCredential), AwsSession(AwsSessionCredential),
Docker(DockerCredential),
Ssh(SshKey), Ssh(SshKey),
} }
@ -99,15 +103,15 @@ pub trait PersistentCredential: for<'a> Deserialize<'a> + Sized {
async fn list(crypto: &Crypto, pool: &SqlitePool) -> Result<Vec<(Uuid, Credential)>, LoadCredentialsError> { async fn list(crypto: &Crypto, pool: &SqlitePool) -> Result<Vec<(Uuid, Credential)>, LoadCredentialsError> {
let q = format!( let q = format!(
"SELECT details.* "SELECT details.*
FROM FROM
{} details {} details
JOIN credentials c JOIN credentials c
ON c.id = details.id ON c.id = details.id
ORDER BY c.created_at", ORDER BY c.created_at",
Self::table_name(), Self::table_name(),
); );
let mut rows = sqlx::query_as::<_, Self::Row>(&q).fetch(pool); let mut rows = sqlx::query_as::<_, Self::Row>(&q).fetch(pool);
let mut creds = Vec::new(); let mut creds = Vec::new();
while let Some(row) = rows.try_next().await? { while let Some(row) = rows.try_next().await? {
let id = Self::row_id(&row); let id = Self::row_id(&row);

View File

@ -20,6 +20,7 @@ use super::{
AwsBaseCredential, AwsBaseCredential,
Credential, Credential,
Crypto, Crypto,
DockerCredential,
PersistentCredential, PersistentCredential,
SshKey, SshKey,
}; };
@ -51,6 +52,7 @@ impl CredentialRecord {
let type_name = match &self.credential { let type_name = match &self.credential {
Credential::AwsBase(_) => AwsBaseCredential::type_name(), Credential::AwsBase(_) => AwsBaseCredential::type_name(),
Credential::Ssh(_) => SshKey::type_name(), Credential::Ssh(_) => SshKey::type_name(),
Credential::Docker(_) => DockerCredential::type_name(),
_ => return Err(SaveCredentialsError::NotPersistent), _ => return Err(SaveCredentialsError::NotPersistent),
}; };
@ -86,6 +88,7 @@ impl CredentialRecord {
match &self.credential { match &self.credential {
Credential::AwsBase(b) => b.save_details(&self.id, crypto, &mut txn).await, Credential::AwsBase(b) => b.save_details(&self.id, crypto, &mut txn).await,
Credential::Ssh(s) => s.save_details(&self.id, crypto, &mut txn).await, Credential::Ssh(s) => s.save_details(&self.id, crypto, &mut txn).await,
Credential::Docker(d) => d.save_details(&self.id, crypto, &mut txn).await,
_ => Err(SaveCredentialsError::NotPersistent), _ => Err(SaveCredentialsError::NotPersistent),
}?; }?;
@ -167,6 +170,11 @@ impl CredentialRecord {
.ok_or(LoadCredentialsError::InvalidData)?; .ok_or(LoadCredentialsError::InvalidData)?;
records.push(Self::from_parts(parent, credential)); records.push(Self::from_parts(parent, credential));
} }
for (id, credential) in DockerCredential::list(crypto, pool).await? {
let parent = parent_map.remove(&id)
.ok_or(LoadCredentialsError::InvalidData)?;
records.push(Self::from_parts(parent, credential));
}
Ok(records) Ok(records)
} }

View File

@ -21,6 +21,7 @@ fn main() {
Some(Action::Get(args)) => creddy_cli::get(args, cli.global_args), Some(Action::Get(args)) => creddy_cli::get(args, cli.global_args),
Some(Action::Exec(args)) => creddy_cli::exec(args, cli.global_args), Some(Action::Exec(args)) => creddy_cli::exec(args, cli.global_args),
Some(Action::Shortcut(args)) => creddy_cli::invoke_shortcut(args, cli.global_args), Some(Action::Shortcut(args)) => creddy_cli::invoke_shortcut(args, cli.global_args),
Some(Action::Docker(cmd)) => creddy_cli::docker_credential_helper(cmd, cli.global_args),
}; };
if let Err(e) = res { if let Err(e) = res {

View File

@ -19,7 +19,7 @@
let alert; let alert;
let passphrase = ''; let passphrase = '';
let saving = false; let saving = false;
async function unlock() { async function unlock() {
saving = true; saving = true;
@ -40,6 +40,8 @@
</script> </script>
<svelte:window on:focus={input.focus} />
<div class="fixed top-0 w-full p-2 text-center"> <div class="fixed top-0 w-full p-2 text-center">
<h1 class="text-3xl font-bold">Creddy is locked</h1> <h1 class="text-3xl font-bold">Creddy is locked</h1>
</div> </div>