Skip to main content

codewhale_runtime/
dsh_credentials.rs

1//! Read-only DeepSeek Harness credential import.
2//!
3//! Official `dsh` stores API keys as a YAML mapping in
4//! `$DSH_HOME/.credentials.yaml`. Codewhale may read `DEEPSEEK_API_KEY` from
5//! that exact file only after `codewhale auth external-consent`. The file is
6//! never written, refreshed, or loaded into the process environment.
7
8use anyhow::{Result, bail};
9use codewhale_config::ExternalCredentialReadGrant;
10
11const DEEPSEEK_API_KEY_REF: &str = "DEEPSEEK_API_KEY";
12
13/// Extract the DeepSeek API key from a granted dsh credentials document.
14pub fn deepseek_api_key_from_grant(grant: &ExternalCredentialReadGrant) -> Result<Option<String>> {
15    if grant.source() != codewhale_config::ExternalCredentialSource::DshCli {
16        bail!(
17            "DeepSeek Harness import requires a dsh_cli grant, not {}",
18            grant.source().as_str()
19        );
20    }
21    let Some(text) = crate::external_credentials::read_to_string(grant)? else {
22        return Ok(None);
23    };
24    parse_dsh_deepseek_api_key(&text)
25}
26
27/// Strict subset of dsh-credentials-local: a mapping of POSIX identifiers to
28/// non-empty strings. Nested values, empty strings, and duplicate keys fail
29/// closed. Only `DEEPSEEK_API_KEY` is returned.
30pub fn parse_dsh_deepseek_api_key(text: &str) -> Result<Option<String>> {
31    let mut found = None;
32    let mut seen = std::collections::BTreeSet::new();
33    for (index, raw) in text.lines().enumerate() {
34        let line = raw.trim();
35        if line.is_empty() || line.starts_with('#') {
36            continue;
37        }
38        let Some((key, value)) = line.split_once(':') else {
39            bail!(
40                "DeepSeek Harness credentials line {} is not `KEY: value`",
41                index + 1
42            );
43        };
44        let key = key.trim();
45        if !is_posix_identifier(key) {
46            bail!(
47                "DeepSeek Harness credentials line {} has a non-identifier key",
48                index + 1
49            );
50        }
51        if !seen.insert(key.to_string()) {
52            bail!("DeepSeek Harness credentials declare `{key}` more than once");
53        }
54        let value = unquote_yaml_string(value.trim()).map_err(|reason| {
55            anyhow::anyhow!(
56                "DeepSeek Harness credentials line {} is invalid: {reason}",
57                index + 1
58            )
59        })?;
60        if value.is_empty() {
61            bail!(
62                "DeepSeek Harness credentials line {} has an empty value",
63                index + 1
64            );
65        }
66        if key == DEEPSEEK_API_KEY_REF {
67            found = Some(value);
68        }
69    }
70    Ok(found)
71}
72
73fn is_posix_identifier(value: &str) -> bool {
74    let mut chars = value.chars();
75    matches!(chars.next(), Some('A'..='Z' | 'a'..='z' | '_'))
76        && chars.all(|ch| matches!(ch, 'A'..='Z' | 'a'..='z' | '0'..='9' | '_'))
77}
78
79fn unquote_yaml_string(value: &str) -> Result<String, &'static str> {
80    if value.starts_with('{')
81        || value.starts_with('[')
82        || value.starts_with('|')
83        || value.starts_with('>')
84    {
85        return Err("nested or block YAML is not supported");
86    }
87    if let Some(inner) = value
88        .strip_prefix('"')
89        .and_then(|rest| rest.strip_suffix('"'))
90    {
91        if inner.contains('\\') {
92            return Err("escaped quoted strings are not supported");
93        }
94        return Ok(inner.to_string());
95    }
96    if let Some(inner) = value
97        .strip_prefix('\'')
98        .and_then(|rest| rest.strip_suffix('\''))
99    {
100        if inner.contains('\'') {
101            return Err("escaped single-quoted strings are not supported");
102        }
103        return Ok(inner.to_string());
104    }
105    if value.contains(':') && value.contains(' ') {
106        return Err("unquoted mapping values are not supported");
107    }
108    Ok(value.to_string())
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    #[test]
116    fn parses_plain_and_quoted_deepseek_key() {
117        assert_eq!(
118            parse_dsh_deepseek_api_key("DEEPSEEK_API_KEY: sk-live\n").unwrap(),
119            Some("sk-live".to_string())
120        );
121        assert_eq!(
122            parse_dsh_deepseek_api_key(
123                "DEEPSEEK_API_KEY: \"sk-quoted\"\nOPENAI_API_KEY: sk-other\n"
124            )
125            .unwrap(),
126            Some("sk-quoted".to_string())
127        );
128    }
129
130    #[test]
131    fn missing_deepseek_key_is_absent_not_an_error() {
132        assert_eq!(
133            parse_dsh_deepseek_api_key("OPENAI_API_KEY: sk-other\n").unwrap(),
134            None
135        );
136    }
137
138    #[test]
139    fn rejects_empty_values_duplicates_and_nested_yaml() {
140        assert!(parse_dsh_deepseek_api_key("DEEPSEEK_API_KEY:\n").is_err());
141        assert!(
142            parse_dsh_deepseek_api_key("DEEPSEEK_API_KEY: sk-a\nDEEPSEEK_API_KEY: sk-b\n").is_err()
143        );
144        assert!(parse_dsh_deepseek_api_key("DEEPSEEK_API_KEY: {nested: true}\n").is_err());
145    }
146}