feat(auth): smith auth store, add, list, remove, check
259e77d21a77c62b0d4bc3438c7680b4aa571955
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
- Parent 1: 7e70ce86bff0
There are many coding harnesses - but this one is fast
259e77d21a77c62b0d4bc3438c7680b4aa571955
Oliver Jan Krylow <oliver@bugabinga.net> ·
unsigned
+501 / −18 text lines
+14 / −15 text lines
Credentials resolve deterministically from explicit flags, the Smith auth store, or environment variables.Credentials resolve deterministically from the Smith auth store or environment variables.Auth data persistence, `smith auth` commands, provider and model selection flags, the shared flag surface, and removal of hard-coded OpenAI defaults.Provider plugins, catalogs, aliases, KDL configuration files, and credential refresh beyond existing behavior remain out of scope.Requires the SMH-SPEC-SPEC0001 configuration-precedence amendment adding the environment layer.Builds on the SMH-SPEC-SPEC0001 environment configuration layer.3. **Pre-dispatch check**: `smith auth check` resolves a provider's credential without a model request and prints the winning source.4. **Flag surface**: each option is declared once with a command-line flag and a `SMITH_`-prefixed environment name; eval and RPC expose `--provider`, `--model`, `--base-url`; the command line wins over the environment, and resolved values report their source.Capabilities stay in the catalog; request options such as thinking levels arrive with catalog levels, not as flags.5. **Resolution order**: flag argument, then auth store, then environment variable; first hit wins, ties across sources resolve by this order.5. **Resolution orders**: options resolve command line, then environment, then configuration; credentials resolve auth store, then environment variable. First hit wins in each domain.6. **Explicit failure**: with no provider flag, no stored credential, and no environment variable, commands fail naming the vendor, the missing credential, and every source tried.7. **Hygiene**: credential plaintext never enters logs, session traces, replay output, or diagnostics. F["--provider/--model/--base-url flags"] --> S{"flag set?"} S -- yes --> C["use flag values"] S -- no --> A["auth store lookup"] --> T{"found?"} T -- yes --> C2["use stored credential"] T -- no --> E["environment variable"] --> U{"set?"} U -- yes --> C3["use env credential"] U -- no --> X["fail: name vendor + all sources tried"] C --> D["resolve before dispatch"] C2 --> D C3 --> D subgraph options [options: provider, model, base-url] OF["--flag value"] --> OE["SMITH_ env value"] --> OC["configuration value"] --> OD["default"] end subgraph creds [credentials] CA["auth store entry"] --> CE["vendor env variable"] --> CX["fail: vendor + sources tried"] end OD --> R["resolve before dispatch"] CE --> R CX --> R- `smith auth add` then `list` then `remove` round-trips one provider entry; file permissions are user-only.- Resolution picks flag > store > env deterministically for each vendor.- Options resolve cli > env > configuration; credentials resolve store > env, deterministically per vendor.- Eval without any credential source fails with vendor and all sources named; no OpenAI endpoint or model is implied.+85 / −1 text lines
[[package]]name = "assert_cmd"version = "2.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2aa3a22042e45de04255c7bf3626e239f450200fd0493c1e382263544b20aea6"dependencies = [ "anstyle", "bstr", "libc", "predicates", "predicates-core", "predicates-tree", "wait-timeout",] "regex-automata",[[package]]name = "predicates"version = "3.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ada8f2932f28a27ee7b70dd6c1c39ea0675c55a36879ab92f3a715eaa1e63cfe"dependencies = [ "anstyle", "difflib", "float-cmp", "normalize-line-endings", "predicates-core", "regex",][[package]]name = "predicates-core"version = "1.0.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cad38746f3166b4031b1a0d39ad9f954dd291e7854fcc0eed52ee41a0b50d144"[[package]]name = "predicates-tree"version = "1.0.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0de1b847b39c8131db0467e9df1ff60e6d0562ab8e9a16e568ad0fdb372e2f2"dependencies = [ "predicates-core", "termtree",] "assert_cmd", "predicates",+1 / −0 text lines
+141 / −0 text lines
use std::path::{Path, PathBuf};/// The environment variable carrying a provider's credential.#[must_use]pub const fn credential_env_var(kind: ProviderKind) -> &'static str { match kind { ProviderKind::OpenAiCompatible => "OPENAI_API_KEY", ProviderKind::Anthropic => "ANTHROPIC_API_KEY", ProviderKind::Google => "GEMINI_API_KEY", ProviderKind::Plugin => "SMITH_PLUGIN_API_KEY", }}/// The default endpoint base URL for a provider.#[must_use]pub const fn default_base_url(kind: ProviderKind) -> &'static str { match kind { ProviderKind::OpenAiCompatible => "https://api.openai.com/v1", ProviderKind::Anthropic => "https://api.anthropic.com", ProviderKind::Google => "https://generativelanguage.googleapis.com/v1beta", ProviderKind::Plugin => "https://localhost", }}/// Durable credential store under the Smith data directory.////// One plaintext file per provider, user-only permissions where the/// platform supports them, no keychain dependency.#[derive(Clone, Debug)]pub struct AuthStore { dir: PathBuf,}impl AuthStore { /// The store under the platform Smith data directory. #[must_use] pub fn at_default() -> Self { Self { dir: smith::config::auth_dir(), } } /// A store at an explicit directory, primarily for tests. #[must_use] pub fn at(dir: impl Into<PathBuf>) -> Self { Self { dir: dir.into() } } /// The backing directory. #[must_use] pub fn dir(&self) -> &Path { &self.dir } fn path(&self, kind: ProviderKind) -> PathBuf { self.dir.join(kind.slug()) } /// Persist one provider credential with user-only permissions. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Session`] fault when the store /// directory or file cannot be created or written. pub fn save(&self, kind: ProviderKind, secret: &str) -> smith::error::Result<()> { std::fs::create_dir_all(&self.dir).map_err(|e| store_io("create", &e))?; let path = self.path(kind); std::fs::write(&path, secret).map_err(|e| store_io("write", &e))?; restrict_permissions(&path); Ok(()) } /// The stored credential for a provider, when present. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Session`] fault when the store /// cannot be read. pub fn load(&self, kind: ProviderKind) -> smith::error::Result<Option<String>> { match std::fs::read_to_string(self.path(kind)) { Ok(secret) => Ok(Some(secret)), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(error) => Err(store_io("read", &error)), } } /// Delete one provider credential; reports whether an entry existed. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Session`] fault when deletion /// fails for a reason other than absence. pub fn remove(&self, kind: ProviderKind) -> smith::error::Result<bool> { match std::fs::remove_file(self.path(kind)) { Ok(()) => Ok(true), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false), Err(error) => Err(store_io("remove", &error)), } } /// The providers with a stored credential. /// /// # Errors /// /// Returns a [`smith::error::SmithError::Session`] fault when the store /// directory cannot be listed. pub fn list(&self) -> smith::error::Result<Vec<ProviderKind>> { let mut kinds = Vec::new(); let entries = match std::fs::read_dir(&self.dir) { Ok(entries) => entries, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(kinds), Err(error) => return Err(store_io("list", &error)), }; for entry in entries.flatten() { if let Some(kind) = ProviderKind::from_slug(&entry.file_name().to_string_lossy()) { kinds.push(kind); } } kinds.sort(); Ok(kinds) }}fn store_io(step: &str, error: &std::io::Error) -> smith::error::SmithError { smith::error::SmithError::Session { code: "AUTH_STORE".to_string(), message: format!("auth store {step} failed: {error}"), }}#[cfg(unix)]fn restrict_permissions(path: &Path) { use std::os::unix::fs::PermissionsExt; let permissions = std::fs::Permissions::from_mode(0o600); let _ = std::fs::set_permissions(path, permissions);}#[cfg(not(unix))]fn restrict_permissions(_path: &Path) {}+26 / −1 text lines
#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)]#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize, Deserialize)]impl ProviderKind { /// Stable lowercase file name for this provider. #[must_use] pub const fn slug(self) -> &'static str { match self { Self::OpenAiCompatible => "openai", Self::Anthropic => "anthropic", Self::Google => "google", Self::Plugin => "plugin", } } /// Parse a provider from its slug. #[must_use] pub fn from_slug(slug: &str) -> Option<Self> { match slug { "openai" => Some(Self::OpenAiCompatible), "anthropic" => Some(Self::Anthropic), "google" => Some(Self::Google), "plugin" => Some(Self::Plugin), _ => None, } }}+4 / −0 text lines
+116 / −1 text lines
use smith_harness::{AuthStore, ProviderKind, credential_env_var};/// Credential operations.#[derive(Debug, Parser)]enum AuthAction { /// Store a credential read from standard input. Add { /// Provider the credential belongs to. #[arg(long)] provider: ProviderArg, }, /// List providers with stored credentials. List, /// Delete one stored credential. Remove { /// Provider whose credential is deleted. #[arg(long)] provider: ProviderArg, }, /// Resolve one provider's credential without any network access. Check { /// Provider whose credential is checked. #[arg(long)] provider: ProviderArg, },}/// Provider names accepted on the command line.#[derive(Copy, Clone, Debug, ValueEnum)]enum ProviderArg { /// OpenAI-compatible endpoints. Openai, /// Anthropic Messages API. Anthropic, /// Google Gemini API. Google,}impl ProviderArg { const fn kind(self) -> ProviderKind { match self { Self::Openai => ProviderKind::OpenAiCompatible, Self::Anthropic => ProviderKind::Anthropic, Self::Google => ProviderKind::Google, } }} Command::Auth { action } => auth(&action),#[expect(clippy::print_stdout, reason = "auth command output is the product")]fn auth(action: &AuthAction) -> Result<()> { let store = AuthStore::at_default(); match action { AuthAction::Add { provider } => { let mut secret = String::new(); std::io::stdin() .lock() .read_line(&mut secret) .map_err(|e| smith::error::SmithError::Session { code: "AUTH_READ".to_string(), message: e.to_string(), })?; let secret = secret.trim_end_matches(['\r', '\n']); if secret.is_empty() { return Err(smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: "refusing to store an empty credential".to_string(), }, }); } store.save(provider.kind(), secret)?; println!("{}: stored", provider.kind().slug()); } AuthAction::List => { for kind in store.list()? { println!("{}: store", kind.slug()); } } AuthAction::Remove { provider } => { if store.remove(provider.kind())? { println!("{}: removed", provider.kind().slug()); } else { return Err(smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: format!("no stored credential for {}", provider.kind().slug()), }, }); } } AuthAction::Check { provider } => { let kind = provider.kind(); let var = credential_env_var(kind); if store.load(kind)?.is_some() { println!("{}: store", kind.slug()); } else if std::env::var(var).is_ok_and(|value| !value.is_empty()) { println!("{}: env:{var}", kind.slug()); } else { return Err(smith::error::SmithError::Provider { fault: smith::error::ProviderFault::Authentication { message: format!( "no credential for {} (tried store, env {var})", kind.slug() ), }, }); } } } Ok(())}new file mode 100644+101 / −0 text lines
//! End-to-end credential store behavior through the `smith auth` CLI.use assert_cmd::Command;use std::path::PathBuf;fn scratch(name: &str) -> PathBuf { std::env::temp_dir().join(format!("smith-auth-test-{name}-{}", std::process::id()))}fn smith(name: &str) -> Command { let mut command = Command::cargo_bin("smith").unwrap(); command .env("XDG_DATA_HOME", scratch(name)) .env_remove("ANTHROPIC_API_KEY") .env_remove("OPENAI_API_KEY") .env_remove("GEMINI_API_KEY"); command}#[test]fn add_list_remove_round_trips_with_user_only_permissions() { let mut add = smith("roundtrip"); add.args(["auth", "add", "--provider", "anthropic"]) .write_stdin("sk-test-secret\n") .assert() .success() .stdout("anthropic: stored\n"); let mut list = smith("roundtrip"); list.args(["auth", "list"]) .assert() .success() .stdout("anthropic: store\n"); let mut check = smith("roundtrip"); check .args(["auth", "check", "--provider", "anthropic"]) .assert() .success() .stdout("anthropic: store\n"); let mut remove = smith("roundtrip"); remove .args(["auth", "remove", "--provider", "anthropic"]) .assert() .success() .stdout("anthropic: removed\n"); let mut gone = smith("roundtrip"); gone.args(["auth", "check", "--provider", "anthropic"]) .assert() .failure() .stderr(predicates::str::contains( "no credential for anthropic (tried store, env ANTHROPIC_API_KEY)", )); let mut empty = smith("roundtrip"); empty .args(["auth", "remove", "--provider", "anthropic"]) .assert() .failure() .stderr(predicates::str::contains( "no stored credential for anthropic", ));}#[test]fn stored_secret_never_prints_and_permissions_are_user_only() { let mut add = smith("hygiene"); add.args(["auth", "add", "--provider", "openai"]) .write_stdin("sk-super-secret-value\n") .assert() .success(); let secret_file = scratch("hygiene").join("smith/auth/openai"); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let mode = std::fs::metadata(&secret_file) .unwrap() .permissions() .mode(); assert_eq!(mode & 0o777, 0o600); } let mut list = smith("hygiene"); list.args(["auth", "list"]) .assert() .stdout("openai: store\n");}#[test]fn check_reports_environment_source() { let mut check = smith("envsource"); check .args(["auth", "check", "--provider", "google"]) .env("GEMINI_API_KEY", "sk-env") .assert() .success() .stdout("google: env:GEMINI_API_KEY\n");}+2 / −0 text lines
+11 / −0 text lines