LINE1 10 20 30 40 50 60 70 80 901use std::io::{BufRead, Write};23use clap::ValueEnum;45use crate::{credential_store::CredentialStore, server_url::TwigUrl};67#[derive(Clone, Copy, Debug, ValueEnum)]8#[value(rename_all = "lower")]9pub enum CredentialOperation {10 Get,11 Store,12 Erase,13}1415#[derive(Default)]16struct GitCredentialInput {17 protocol: Option<String>,18 host: Option<String>,19 path: Option<String>,20}2122pub fn run_credential_helper(23 operation: CredentialOperation,24 server: &TwigUrl,25 mut input: impl BufRead,26 mut output: impl Write,27 credentials: &impl CredentialStore,28) -> anyhow::Result<()> {29 if matches!(operation, CredentialOperation::Store) {30 std::io::copy(&mut input, &mut std::io::sink())?;31 return Ok(());32 }3334 let request = parse_git_credential(&mut input)?;35 let matches_server = request36 .protocol37 .as_deref()38 .zip(request.host.as_deref())39 .is_some_and(|(protocol, host)| {40 server.matches_git_request(protocol, host, request.path.as_deref())41 });42 if !matches_server {43 return Ok(());44 }4546 match operation {47 CredentialOperation::Get => {48 if let Some(token) = credentials.get(server)? {49 writeln!(output, "username=tree")?;50 writeln!(output, "password={token}")?;51 writeln!(output)?;52 }53 }54 CredentialOperation::Erase => credentials.erase(server)?,55 CredentialOperation::Store => unreachable!("store returned before parsing credentials"),56 }57 output.flush()?;58 Ok(())59}6061fn parse_git_credential(input: &mut impl BufRead) -> anyhow::Result<GitCredentialInput> {62 let mut request = GitCredentialInput::default();63 for line in input.lines() {64 let line = line?;65 if line.is_empty() {66 break;67 }68 let Some((key, value)) = line.split_once('=') else {69 continue;70 };71 match key {72 "protocol" => request.protocol = Some(value.to_owned()),73 "host" => request.host = Some(value.to_owned()),74 "path" => request.path = Some(value.to_owned()),75 76 _ => {}77 }78 }79 Ok(request)80}8182#[cfg(test)]83mod tests {84 use std::{collections::HashMap, io::Cursor, sync::Mutex};8586 use super::*;8788 #[derive(Default)]89 struct MemoryCredentialStore {90 values: Mutex<HashMap<String, String>>,91 }9293 impl CredentialStore for MemoryCredentialStore {94 fn check_available(&self) -> anyhow::Result<()> {95 Ok(())96 }9798 fn get(&self, server: &TwigUrl) -> anyhow::Result<Option<String>> {99 Ok(self100 .values101 .lock()102 .expect("credential lock")103 .get(server.as_url().as_str())104 .cloned())105 }106107 fn put(&self, server: &TwigUrl, token: &str) -> anyhow::Result<()> {108 self.values109 .lock()110 .expect("credential lock")111 .insert(server.as_url().as_str().to_owned(), token.to_owned());112 Ok(())113 }114115 fn erase(&self, server: &TwigUrl) -> anyhow::Result<()> {116 self.values117 .lock()118 .expect("credential lock")119 .remove(server.as_url().as_str());120 Ok(())121 }122 }123124 #[test]125 fn get_returns_credentials_only_for_the_matching_path() {126 let server = TwigUrl::parse("https://git.example.dev/twig/").unwrap();127 let store = MemoryCredentialStore::default();128 store.put(&server, "twigt_test_secret").unwrap();129130 let mut matching_output = Vec::new();131 run_credential_helper(132 CredentialOperation::Get,133 &server,134 Cursor::new("protocol=https\nhost=git.example.dev\npath=twig/ns/repo.git\n\n"),135 &mut matching_output,136 &store,137 )138 .unwrap();139 let matching = String::from_utf8(matching_output).unwrap();140 assert!(matching.contains("username=tree\n"));141 assert!(matching.contains("password=twigt_test_secret\n"));142143 let mut wrong_path_output = Vec::new();144 run_credential_helper(145 CredentialOperation::Get,146 &server,147 Cursor::new("protocol=https\nhost=git.example.dev\npath=other/repo.git\n\n"),148 &mut wrong_path_output,149 &store,150 )151 .unwrap();152 assert!(wrong_path_output.is_empty());153 }154155 #[test]156 fn store_does_not_persist_passwords_git_sends_to_the_helper() {157 let server = TwigUrl::parse("https://git.example.dev/").unwrap();158 let store = MemoryCredentialStore::default();159 run_credential_helper(160 CredentialOperation::Store,161 &server,162 Cursor::new(163 "protocol=https\nhost=git.example.dev\nusername=someone\npassword=plaintext\n\n",164 ),165 Vec::new(),166 &store,167 )168 .unwrap();169 assert!(store.get(&server).unwrap().is_none());170 }171172 #[test]173 fn erase_removes_only_the_matching_server_entry() {174 let server = TwigUrl::parse("https://git.example.dev/twig/").unwrap();175 let other = TwigUrl::parse("https://other.example.dev/").unwrap();176 let store = MemoryCredentialStore::default();177 store.put(&server, "twigt_scoped").unwrap();178 store.put(&other, "twigt_other").unwrap();179180 run_credential_helper(181 CredentialOperation::Erase,182 &server,183 Cursor::new("protocol=https\nhost=git.example.dev\npath=twig/ns/repo.git\n\n"),184 Vec::new(),185 &store,186 )187 .unwrap();188189 assert!(store.get(&server).unwrap().is_none());190 assert_eq!(store.get(&other).unwrap(), Some("twigt_other".to_string()));191 }192}