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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
mod config;
mod helper;

use base64::engine::general_purpose;
use base64::Engine;
use std::env;
use std::error::Error;
use std::fmt;
use std::fs::File;
use std::io::BufReader;
use std::path::{Path, PathBuf};
use std::str;

type Result<T> = std::result::Result<T, CredentialRetrievalError>;

/// An error that occurred whilst attempting to retrieve a credential.
#[derive(Debug, PartialEq)]
pub enum CredentialRetrievalError {
    HelperCommunicationError,
    MalformedHelperResponse,
    HelperFailure { stdout: String, stderr: String },
    CredentialDecodingError,
    NoCredentialConfigured,
    ConfigNotFound,
    ConfigReadError,
}

impl fmt::Display for CredentialRetrievalError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            CredentialRetrievalError::HelperCommunicationError => {
                write!(f, "Unable to communicate with credential helper")
            }
            CredentialRetrievalError::MalformedHelperResponse => {
                write!(f, "Credential helper response malformed")
            }
            CredentialRetrievalError::HelperFailure { stdout, stderr } => {
                write!(
                    f,
                    "Credential helper returned non-zero response code:\n\
                    stdout:\n{stdout}\n\n\
                    stderr:\n{stderr}\n",
                )
            }
            CredentialRetrievalError::CredentialDecodingError => {
                write!(f, "Unable to decode credential")
            }
            CredentialRetrievalError::NoCredentialConfigured => {
                write!(f, "User has no credential configured")
            }
            CredentialRetrievalError::ConfigNotFound => write!(f, "No config file found"),
            CredentialRetrievalError::ConfigReadError => write!(f, "Unable to read config"),
        }
    }
}

impl Error for CredentialRetrievalError {}

/// A docker credential, either a single identity token or a username/password pair.
#[derive(Debug, PartialEq)]
pub enum DockerCredential {
    IdentityToken(String),
    UsernamePassword(String, String),
}

fn config_dir() -> Option<PathBuf> {
    let home_config = || env::var_os("HOME").map(|home| Path::new(&home).join(".docker"));
    env::var_os("DOCKER_CONFIG")
        .map(PathBuf::from)
        .or_else(home_config)
}

fn decode_auth(encoded_auth: &str) -> Result<DockerCredential> {
    let config = general_purpose::GeneralPurposeConfig::new()
        .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent);

    let engine = general_purpose::GeneralPurpose::new(&base64::alphabet::STANDARD, config);

    let decoded = engine
        .decode(encoded_auth)
        .map_err(|_| CredentialRetrievalError::CredentialDecodingError)?;
    let decoded =
        str::from_utf8(&decoded).map_err(|_| CredentialRetrievalError::CredentialDecodingError)?;
    let parts: Vec<&str> = decoded.splitn(2, ':').collect();
    let username = String::from(*parts.first().unwrap());
    let password = String::from(
        *parts
            .get(1)
            .ok_or(CredentialRetrievalError::CredentialDecodingError)?,
    );
    Ok(DockerCredential::UsernamePassword(username, password))
}

fn extract_credential<T>(
    conf: config::DockerConfig,
    server: &str,
    from_helper: T,
) -> Result<DockerCredential>
where
    T: Fn(&str, &str) -> Result<DockerCredential>,
{
    if let Some(helper_name) = conf.get_helper(server) {
        return from_helper(server, helper_name);
    }

    if let Some(identity_token) = conf.get_identity_token(server) {
        return Ok(DockerCredential::IdentityToken(identity_token.to_string()));
    }

    if let Some(auth) = conf.get_auth(server) {
        return decode_auth(auth);
    }

    if let Some(store_name) = conf.creds_store {
        return from_helper(server, &store_name);
    }

    Err(CredentialRetrievalError::NoCredentialConfigured)
}

/// Retrieve a user's docker credential from a given reader.
///
/// Example:
/// ```no_run
/// use std::{fs::File, io::BufReader};
/// use docker_credential::DockerCredential;
///
/// let file = File::open("config.json").expect("Unable to open config file");
///
/// let reader = BufReader::new(file);
///
/// let credential = docker_credential::get_credential_from_reader(reader, "https://index.docker.io/v1/").expect("Unable to retrieve credential");
///
/// match credential {
///   DockerCredential::IdentityToken(token) => println!("Identity token: {}", token),
///   DockerCredential::UsernamePassword(user_name, password) => println!("Username: {}, Password: {}", user_name, password),
/// };
/// ```
pub fn get_credential_from_reader(
    reader: impl std::io::Read,
    server: &str,
) -> Result<DockerCredential> {
    let conf = config::read_config(reader)?;
    extract_credential(conf, server, helper::credential_from_helper)
}

/// Retrieve a user's docker credential via config.json.
///
/// If necessary, credential helpers/store will be invoked.
///
/// Example:
/// ```no_run
/// use docker_credential::DockerCredential;
///
/// let credential = docker_credential::get_credential("https://index.docker.io/v1/").expect("Unable to retrieve credential");
///
/// match credential {
///   DockerCredential::IdentityToken(token) => println!("Identity token: {}", token),
///   DockerCredential::UsernamePassword(user_name, password) => println!("Username: {}, Password: {}", user_name, password),
/// };
/// ```
pub fn get_credential(server: &str) -> Result<DockerCredential> {
    let config_path = config_dir()
        .ok_or(CredentialRetrievalError::ConfigNotFound)?
        .join("config.json");

    let f = File::open(config_path).map_err(|_| CredentialRetrievalError::ConfigReadError)?;

    get_credential_from_reader(BufReader::new(f), server)
}

/// Retrieve a user's docker credential from auth.json (as used by podman).
///
/// The lookup strategy adheres to the logic described
/// [in the podman docs](https://docs.podman.io/en/stable/markdown/podman-login.1.html#authfile-path).
///
/// For a usage example, refer to [`get_credential`].
pub fn get_podman_credential(server: &str) -> Result<DockerCredential> {
    let config_path = if let Some(auth_path) = env::var_os("REGISTRY_AUTH_FILE") {
        PathBuf::from(auth_path)
    } else {
        let primary_path = if cfg!(target_os = "linux") {
            env::var_os("XDG_RUNTIME_DIR")
                .map(PathBuf::from)
                .ok_or(CredentialRetrievalError::ConfigNotFound)?
                .join("containers/auth.json")
        } else {
            env::var_os("HOME")
                .map(PathBuf::from)
                .ok_or(CredentialRetrievalError::ConfigNotFound)?
                .join(".config/containers/auth.json")
        };

        if primary_path.is_file() {
            primary_path
        } else {
            config_dir()
                .ok_or(CredentialRetrievalError::ConfigNotFound)?
                .join("containers/auth.json")
        }
    };

    let f = File::open(config_path).map_err(|_| CredentialRetrievalError::ConfigReadError)?;

    get_credential_from_reader(BufReader::new(f), server)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[test]
    fn errors_when_no_relevant_config() {
        let empty_config = config::DockerConfig {
            auths: None,
            creds_store: None,
            cred_helpers: None,
        };
        let dummy_helper =
            |_: &str, _: &str| Err(CredentialRetrievalError::HelperCommunicationError);
        let result = extract_credential(empty_config, "some server", dummy_helper);

        assert_eq!(
            result,
            Err(CredentialRetrievalError::NoCredentialConfigured)
        );
    }

    #[test]
    fn decodes_auth_when_no_helpers() {
        let encoded_auth = general_purpose::STANDARD_NO_PAD.encode("some_user:some_password");
        let mut auths = HashMap::new();
        auths.insert(
            String::from("some server"),
            config::AuthConfig {
                auth: Some(encoded_auth),
                identitytoken: None,
            },
        );
        let auth_config = config::DockerConfig {
            auths: Some(auths),
            creds_store: None,
            cred_helpers: None,
        };
        let dummy_helper =
            |_: &str, _: &str| Err(CredentialRetrievalError::HelperCommunicationError);
        let result = extract_credential(auth_config, "some server", dummy_helper);

        assert_eq!(
            result,
            Ok(DockerCredential::UsernamePassword(
                String::from("some_user"),
                String::from("some_password")
            ))
        );
    }

    #[test]
    fn decodes_regardless_of_padding() {
        let encoded_auths = [
            general_purpose::STANDARD.encode("some_user:some_password"),
            general_purpose::STANDARD_NO_PAD.encode("some_user:some_password"),
        ];

        let dummy_helper =
            |_: &str, _: &str| Err(CredentialRetrievalError::HelperCommunicationError);

        for encoded_auth in encoded_auths {
            let auths = HashMap::from([(
                String::from("some server"),
                config::AuthConfig {
                    auth: Some(encoded_auth),
                    identitytoken: None,
                },
            )]);

            let auth_config = config::DockerConfig {
                auths: Some(auths),
                creds_store: None,
                cred_helpers: None,
            };

            let result = extract_credential(auth_config, "some server", dummy_helper);

            assert_eq!(
                result,
                Ok(DockerCredential::UsernamePassword(
                    String::from("some_user"),
                    String::from("some_password")
                ))
            );
        }
    }

    #[test]
    fn gets_credential_from_helper() {
        let mut helpers = HashMap::new();
        helpers.insert(String::from("some server"), String::from("some_helper"));
        let helper_config = config::DockerConfig {
            auths: None,
            creds_store: None,
            cred_helpers: Some(helpers),
        };
        let dummy_helper = |address: &str, helper: &str| {
            if address == "some server" && helper == "some_helper" {
                Ok(DockerCredential::IdentityToken(String::from(
                    "expected_token",
                )))
            } else {
                Err(CredentialRetrievalError::HelperCommunicationError)
            }
        };
        let result = extract_credential(helper_config, "some server", dummy_helper);

        assert_eq!(
            result,
            Ok(DockerCredential::IdentityToken(String::from(
                "expected_token"
            )))
        );
    }

    #[test]
    fn gets_credential_from_store() {
        let store_config = config::DockerConfig {
            auths: None,
            creds_store: Some(String::from("cred_store")),
            cred_helpers: None,
        };
        let dummy_helper = |address: &str, helper: &str| {
            if address == "some server" && helper == "cred_store" {
                Ok(DockerCredential::IdentityToken(String::from(
                    "expected_token",
                )))
            } else {
                Err(CredentialRetrievalError::HelperCommunicationError)
            }
        };
        let result = extract_credential(store_config, "some server", dummy_helper);

        assert_eq!(
            result,
            Ok(DockerCredential::IdentityToken(String::from(
                "expected_token"
            )))
        );
    }
}