Skip to main content

surjection_core/remote/
credential.rs

1//! `surject git-credential` (SPEC 9.6, `auth = token`): git's credential
2//! helper protocol for one git remote. `get` answers with the remote's
3//! `username` (default `x-access-token`) and the token stored in the OS
4//! keyring for that remote, and only for the protocol and host of the
5//! remote's own URL; `store` and `erase` do nothing (git never writes the
6//! keyring through Surjection).
7
8use std::collections::BTreeMap;
9
10use crate::brand;
11use crate::error::{CoreError, ErrorCode};
12use crate::remote::config::RemoteConfig;
13use crate::remote::git::{GitAuth, url_scheme_host};
14use crate::secrets::SecretValue;
15use crate::secrets::providers::keyring::KeyringBackend;
16
17/// The username sent when the remote sets none; GitHub accepts it with any
18/// token (other hosts may need the account name [verify per host]).
19pub const DEFAULT_USERNAME: &str = "x-access-token";
20
21/// The keyring account (service [`brand::KEYRING_SERVICE`]) holding a git
22/// remote's token.
23pub fn token_account(remote: &str) -> String {
24    format!("git-remote/{remote}")
25}
26
27/// What git asks for: the attributes it sent (`protocol`, `host`, `path`,
28/// `username`, ...).
29#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct CredentialRequest {
31    pub attributes: BTreeMap<String, String>,
32}
33
34impl CredentialRequest {
35    /// `key=value` lines up to the first empty line or the end.
36    pub fn parse(input: &str) -> Self {
37        let attributes = input
38            .lines()
39            .take_while(|line| !line.is_empty())
40            .filter_map(|line| line.split_once('='))
41            .map(|(key, value)| (key.to_owned(), value.to_owned()))
42            .collect();
43        Self { attributes }
44    }
45
46    pub fn get(&self, key: &str) -> Option<&str> {
47        self.attributes.get(key).map(String::as_str)
48    }
49}
50
51/// The answer to a `get`.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Credential {
54    pub username: String,
55    pub password: SecretValue,
56}
57
58impl Credential {
59    /// The protocol's output: `username=...` and `password=...` lines.
60    pub fn to_protocol(&self) -> String {
61        format!(
62            "username={}\npassword={}\n",
63            self.username,
64            self.password.expose()
65        )
66    }
67}
68
69/// Answers `get` for `remote`. `Ok(None)` when the request is for another
70/// protocol or host than the remote's URL (git then tries elsewhere);
71/// `missing_secret` when no token is stored.
72pub fn get(
73    remote: &RemoteConfig,
74    request: &CredentialRequest,
75    keyring: &dyn KeyringBackend,
76) -> Result<Option<Credential>, CoreError> {
77    if GitAuth::parse(remote.auth.as_deref())? != GitAuth::Token {
78        return Err(CoreError::new(
79            ErrorCode::InvalidValue,
80            format!("remote {} does not use auth = token", remote.name),
81        ));
82    }
83    let url = remote.url.as_deref().unwrap_or_default();
84    let Some((scheme, host)) = url_scheme_host(url) else {
85        return Ok(None);
86    };
87    let asked_scheme = request.get("protocol").unwrap_or_default();
88    let asked_host = request.get("host").unwrap_or_default();
89    if !asked_scheme.eq_ignore_ascii_case(&scheme) || !asked_host.eq_ignore_ascii_case(&host) {
90        return Ok(None);
91    }
92    let account = token_account(&remote.name);
93    let token = keyring
94        .get_own(&account)
95        .map_err(|resolution| {
96            CoreError::new(
97                ErrorCode::SecretError,
98                format!(
99                    "cannot read the token of remote {}: {}",
100                    remote.name,
101                    resolution.message.unwrap_or_default()
102                ),
103            )
104        })?
105        .ok_or_else(|| {
106            CoreError::new(
107                ErrorCode::MissingSecret,
108                format!(
109                    "no token stored for remote {}; pipe one into `{} remote token {}`",
110                    remote.name,
111                    brand::BIN_NAME,
112                    remote.name
113                ),
114            )
115        })?;
116    Ok(Some(Credential {
117        username: remote
118            .username
119            .clone()
120            .filter(|name| !name.is_empty())
121            .unwrap_or_else(|| DEFAULT_USERNAME.to_owned()),
122        password: token,
123    }))
124}