Skip to main content

codewhale_runtime/credentials/
source.rs

1//! Where a credential came from, and — when there isn't one — where we looked.
2//!
3//! Ported from pi-mono's `AuthResult { auth, env, source }`
4//! (`packages/ai/src/auth/types.ts`, MIT, Copyright (c) 2025 Mario Zechner;
5//! full notice in the parent module). pi returns a human-readable `source`
6//! such as `"ANTHROPIC_API_KEY"`, `"OAuth"`, or `"~/.aws/credentials"` from
7//! every resolution so a status surface can say which place won.
8//!
9//! CodeWhale adds the negative half, because that is where its picker was
10//! useless: a failed resolution carries the ordered list of places that were
11//! actually probed, so "missing key" can name them and say what would fix it.
12//!
13//! Nothing here holds secret material — only labels.
14
15use std::borrow::Cow;
16
17/// One place credential resolution looked, and what would put a credential
18/// there. Labels only; never a value.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct CredentialProbe {
21    /// Where we looked, e.g. `"env DEEPSEEK_API_KEY"` or `"secret store slot \"deepseek\""`.
22    pub(crate) place: Cow<'static, str>,
23    /// What the user would do to make this place answer, if there is a
24    /// one-line answer. `None` when the place is informational only.
25    pub fix: Option<Cow<'static, str>>,
26}
27
28impl CredentialProbe {
29    pub fn with_fix(
30        place: impl Into<Cow<'static, str>>,
31        fix: impl Into<Cow<'static, str>>,
32    ) -> Self {
33        Self {
34            place: place.into(),
35            fix: Some(fix.into()),
36        }
37    }
38}
39
40/// The place a credential was resolved from, or the fact that no place had
41/// one. This is the single value every readiness surface should render.
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum CredentialSource {
44    /// `auth_mode = "none"`: the route intentionally sends no credential.
45    AuthModeNone,
46    /// A keyless self-hosted or loopback route.
47    KeylessRoute {
48        base_url: String,
49    },
50    /// `--api-key` on the command line (or the dispatcher's source-marked
51    /// forward of it).
52    CliOverride,
53    /// `[providers.<table>] api_key`.
54    ProviderConfigApiKey {
55        table: String,
56    },
57    /// `[providers.<table>] api_key_env = "<var>"`, resolved from `<var>`.
58    ProviderConfigEnv {
59        var: String,
60    },
61    /// An ambient provider environment variable.
62    AmbientEnv {
63        var: String,
64    },
65    /// CodeWhale's own durable secret store.
66    SecretStore {
67        slot: String,
68    },
69    /// A read-only, explicitly consented credential file owned by another CLI.
70    ExternalGrant {
71        cli: String,
72        path: String,
73    },
74    /// A subscription OAuth sign-in: Codewhale-owned storage, or (xAI) a
75    /// consented Grok CLI import. `account` is the display label (email,
76    /// plan) of the account it signs in as, taken from the same read that
77    /// proved the sign-in usable; never token material.
78    OAuth {
79        flow: String,
80        account: Option<String>,
81    },
82    /// The user-global `~/.codewhale/config.toml`, consulted last so a key
83    /// saved there survives loading a workspace config.
84    UserGlobalConfig,
85    /// An expiring, process-only Codewhale account auth transform.
86    AccountSession,
87    ClaudeOrgLink,
88    SessionKey,
89    /// Nothing had a credential. `probed` is in precedence order.
90    Missing {
91        probed: Vec<CredentialProbe>,
92    },
93}
94
95impl CredentialSource {
96    pub fn is_present(&self) -> bool {
97        !matches!(self, Self::Missing { .. })
98    }
99
100    /// Short human-readable label, in pi's spirit: the name of the place, not
101    /// a sentence. Safe to render anywhere — never contains a secret.
102    pub fn label(&self) -> Cow<'static, str> {
103        match self {
104            Self::AuthModeNone => Cow::Borrowed("auth_mode = \"none\""),
105            Self::KeylessRoute { base_url } => Cow::Owned(format!(
106                "keyless route {}",
107                codewhale_config::structural_url_authority(base_url)
108            )),
109            Self::CliOverride => Cow::Borrowed("--api-key"),
110            Self::ProviderConfigApiKey { table } => Cow::Owned(format!("[{table}] api_key")),
111            Self::ProviderConfigEnv { var } => Cow::Owned(format!("api_key_env {var}")),
112            Self::AmbientEnv { var } => Cow::Owned(var.clone()),
113            Self::SecretStore { slot } => Cow::Owned(format!("secret store \"{slot}\"")),
114            Self::ExternalGrant { cli, path } => {
115                Cow::Owned(format!("{cli} credentials (read-only) {path}"))
116            }
117            Self::OAuth { flow, .. } => Cow::Owned(format!("{flow} OAuth")),
118            Self::AccountSession => Cow::Borrowed("Codewhale account"),
119            Self::ClaudeOrgLink => {
120                Cow::Borrowed(codewhale_config::credentials::CLAUDE_ORG_KEY_SOURCE)
121            }
122            Self::SessionKey => Cow::Borrowed("session key"),
123            Self::UserGlobalConfig => Cow::Borrowed("~/.codewhale/config.toml api_key"),
124            Self::Missing { .. } => Cow::Borrowed("not found"),
125        }
126    }
127
128    /// The ordered places that were probed, for a failed resolution.
129    pub fn probed(&self) -> &[CredentialProbe] {
130        match self {
131            Self::Missing { probed } => probed,
132            _ => &[],
133        }
134    }
135}
136
137/// A resolution plus its source. Deliberately does not carry the credential:
138/// readiness surfaces need the source, and the request path already has its
139/// own resolver that returns the secret.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct CredentialResolution {
142    pub source: CredentialSource,
143}
144
145impl CredentialResolution {
146    pub fn found(source: CredentialSource) -> Self {
147        debug_assert!(source.is_present());
148        Self { source }
149    }
150
151    pub fn missing(probed: Vec<CredentialProbe>) -> Self {
152        Self {
153            source: CredentialSource::Missing { probed },
154        }
155    }
156
157    pub fn is_present(&self) -> bool {
158        self.source.is_present()
159    }
160
161    /// One line naming the places checked, for a status row. Empty when the
162    /// resolution succeeded.
163    pub fn checked_places(&self) -> String {
164        self.source
165            .probed()
166            .iter()
167            .map(|probe| probe.place.as_ref())
168            .collect::<Vec<_>>()
169            .join(", ")
170    }
171
172    /// The first actionable fix among the probed places, if any.
173    pub fn first_fix(&self) -> Option<&str> {
174        self.source
175            .probed()
176            .iter()
177            .find_map(|probe| probe.fix.as_deref())
178    }
179}
180
181#[cfg(test)]
182mod private_label_tests {
183    use super::CredentialSource;
184    #[test]
185    fn keyless_label_omits_credentials_and_still_names_the_endpoint() {
186        for url in [
187            "https://user:label-s10-synthetic@gateway.invalid/v1",
188            "https://label-s10-synthetic@gateway.invalid/v1",
189            "https://gateway.invalid/key/label-s10-synthetic/v1",
190            "https://gateway.invalid/v1?token=label-s10-synthetic",
191            "https://gateway.invalid/v1#label-s10-synthetic",
192        ] {
193            let label = CredentialSource::KeylessRoute {
194                base_url: url.into(),
195            }
196            .label()
197            .into_owned();
198            assert_eq!(label, "keyless route https://gateway.invalid");
199        }
200        let label = CredentialSource::KeylessRoute {
201            base_url: "http://localhost:11434/v1".into(),
202        }
203        .label()
204        .into_owned();
205        assert_eq!(label, "keyless route http://localhost:11434");
206        for url in ["not a url", "file:///etc/passwd", ""] {
207            let label = CredentialSource::KeylessRoute {
208                base_url: url.into(),
209            }
210            .label()
211            .into_owned();
212            assert!(label.contains("configured value omitted"));
213            assert!(!label.contains("passwd"));
214        }
215    }
216}