surjection_core/remote/
credential.rs1use 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
17pub const DEFAULT_USERNAME: &str = "x-access-token";
20
21pub fn token_account(remote: &str) -> String {
24 format!("git-remote/{remote}")
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Default)]
30pub struct CredentialRequest {
31 pub attributes: BTreeMap<String, String>,
32}
33
34impl CredentialRequest {
35 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#[derive(Debug, Clone, PartialEq, Eq)]
53pub struct Credential {
54 pub username: String,
55 pub password: SecretValue,
56}
57
58impl Credential {
59 pub fn to_protocol(&self) -> String {
61 format!(
62 "username={}\npassword={}\n",
63 self.username,
64 self.password.expose()
65 )
66 }
67}
68
69pub 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}