1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
use git_transport::client;
use quick_error::quick_error;
use std::{
    io::{self, Write},
    process::{Command, Stdio},
};

pub type Result = std::result::Result<Option<Outcome>, Error>;

quick_error! {
    #[derive(Debug)]
    pub enum Error {
        Io(err: io::Error) {
            display("An IO error occurred while communicating to the credentials helper")
            from()
            source(err)
        }
        KeyNotFound(name: String) {
            display("Could not find '{}' in output of git credentials helper", name)
        }
        CredentialsHelperFailed(code: Option<i32>) {
            display("Credentials helper program failed with status code {:?}", code)
        }
    }
}

#[derive(Clone, Debug)]
pub enum Action<'a> {
    /// Provide credentials using the given URL (as &str) as context
    Fill(&'a str),
    Approve(Vec<u8>),
    Reject(Vec<u8>),
}

impl<'a> Action<'a> {
    pub fn is_fill(&self) -> bool {
        matches!(self, Action::Fill(_))
    }
    pub fn as_str(&self) -> &str {
        match self {
            Action::Approve(_) => "approve",
            Action::Fill(_) => "fill",
            Action::Reject(_) => "reject",
        }
    }
}

#[derive(Clone, Debug)]
pub struct NextAction {
    previous_output: Vec<u8>,
}

impl NextAction {
    pub fn approve(self) -> Action<'static> {
        Action::Approve(self.previous_output)
    }
    pub fn reject(self) -> Action<'static> {
        Action::Reject(self.previous_output)
    }
}

pub struct Outcome {
    pub identity: client::Identity,
    pub next: NextAction,
}

#[cfg(windows)]
fn git_program() -> &'static str {
    "git.exe"
}

#[cfg(not(windows))]
fn git_program() -> &'static str {
    "git"
}

pub fn helper(action: Action<'_>) -> Result {
    let mut cmd = Command::new(git_program());
    cmd.arg("credential")
        .arg(action.as_str())
        .stdin(Stdio::piped())
        .stdout(if action.is_fill() {
            Stdio::piped()
        } else {
            Stdio::null()
        });
    let mut child = cmd.spawn()?;
    let mut stdin = child.stdin.take().expect("stdin to be configured");

    match action {
        Action::Fill(url) => encode_message(url, stdin)?,
        Action::Approve(last) | Action::Reject(last) => {
            stdin.write_all(&last)?;
            stdin.write_all(&[b'\n'])?
        }
    }

    let output = child.wait_with_output()?;
    if !output.status.success() {
        return Err(Error::CredentialsHelperFailed(output.status.code()));
    }
    let stdout = output.stdout;
    if stdout.is_empty() {
        Ok(None)
    } else {
        let kvs = decode_message(stdout.as_slice())?;
        let find = |name: &str| {
            kvs.iter()
                .find(|(k, _)| k == name)
                .ok_or_else(|| Error::KeyNotFound(name.into()))
                .map(|(_, n)| n.to_owned())
        };
        Ok(Some(Outcome {
            identity: client::Identity::Account {
                username: find("username")?,
                password: find("password")?,
            },
            next: NextAction {
                previous_output: stdout,
            },
        }))
    }
}

pub fn encode_message(url: &str, mut out: impl io::Write) -> io::Result<()> {
    validate(url)?;
    writeln!(out, "url={}\n", url)
}

fn validate(url: &str) -> io::Result<()> {
    if url.contains('\u{0}') || url.contains('\n') {
        return Err(io::Error::new(
            io::ErrorKind::Other,
            "token to encode must not contain newlines or null bytes",
        ));
    }
    Ok(())
}

pub fn decode_message(mut input: impl io::Read) -> io::Result<Vec<(String, String)>> {
    let mut buf = String::new();
    input.read_to_string(&mut buf)?;
    buf.lines()
        .take_while(|l| !l.is_empty())
        .map(|l| {
            let mut iter = l.splitn(2, '=').map(|s| s.to_owned());
            match (iter.next(), iter.next()) {
                (Some(key), Some(value)) => validate(&key).and_then(|_| validate(&value)).map(|_| (key, value)),
                _ => Err(io::Error::new(
                    io::ErrorKind::Other,
                    "Invalid format, expecting key=value",
                )),
            }
        })
        .collect::<io::Result<Vec<_>>>()
}