Skip to main content

zlayer_core/auth/
docker_config.rs

1//! Docker config.json authentication parser
2//!
3//! This module parses the Docker config file format used by Docker and other container tools
4//! to store registry credentials. The config file is typically located at ~/.docker/config.json.
5
6use crate::error::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11
12/// Docker config.json authentication manager
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct DockerConfigAuth {
15    #[serde(default)]
16    auths: HashMap<String, AuthEntry>,
17}
18
19/// Authentication entry in Docker config
20#[derive(Debug, Clone, Serialize, Deserialize)]
21struct AuthEntry {
22    /// Base64-encoded "username:password"
23    auth: Option<String>,
24    /// Plain username (alternative to auth field)
25    username: Option<String>,
26    /// Plain password (alternative to auth field)
27    password: Option<String>,
28}
29
30impl DockerConfigAuth {
31    /// Load Docker config from the default location (`~/.docker/config.json`)
32    ///
33    /// # Errors
34    /// Returns an error if the home directory cannot be determined or the config
35    /// file exists but cannot be read or parsed.
36    pub fn load() -> Result<Self> {
37        let path = Self::default_config_path()?;
38        Self::load_from_path(&path)
39    }
40
41    /// Load Docker config from a specific path
42    ///
43    /// # Errors
44    /// Returns an error if the file exists but cannot be read or parsed.
45    pub fn load_from_path(path: &Path) -> Result<Self> {
46        if !path.exists() {
47            return Ok(Self {
48                auths: HashMap::new(),
49            });
50        }
51
52        let contents = fs::read_to_string(path).map_err(|e| {
53            crate::error::Error::config(format!("Failed to read Docker config: {e}"))
54        })?;
55
56        let config: DockerConfigAuth = serde_json::from_str(&contents).map_err(|e| {
57            crate::error::Error::config(format!("Failed to parse Docker config: {e}"))
58        })?;
59
60        Ok(config)
61    }
62
63    /// Get credentials for a specific registry
64    ///
65    /// Returns (username, password) if credentials are found for the registry.
66    /// The registry parameter should match the registry hostname (e.g., "docker.io", "ghcr.io").
67    #[must_use]
68    pub fn get_credentials(&self, registry: &str) -> Option<(String, String)> {
69        // Try exact match first
70        if let Some(entry) = self.auths.get(registry) {
71            return Self::extract_credentials(entry);
72        }
73
74        // Try with https:// prefix
75        let https_registry = format!("https://{registry}");
76        if let Some(entry) = self.auths.get(&https_registry) {
77            return Self::extract_credentials(entry);
78        }
79
80        // Try index.docker.io for docker.io
81        if registry == "docker.io" || registry == "registry-1.docker.io" {
82            if let Some(entry) = self.auths.get("https://index.docker.io/v1/") {
83                return Self::extract_credentials(entry);
84            }
85        }
86
87        None
88    }
89
90    /// Extract credentials from an auth entry
91    fn extract_credentials(entry: &AuthEntry) -> Option<(String, String)> {
92        // If username and password are provided directly
93        if let (Some(username), Some(password)) = (&entry.username, &entry.password) {
94            return Some((username.clone(), password.clone()));
95        }
96
97        // If auth field is provided (base64 encoded "username:password")
98        if let Some(auth) = &entry.auth {
99            return Self::decode_auth(auth);
100        }
101
102        None
103    }
104
105    /// Decode base64-encoded "username:password" auth string
106    fn decode_auth(auth: &str) -> Option<(String, String)> {
107        use base64::Engine;
108        let decoded = base64::engine::general_purpose::STANDARD
109            .decode(auth)
110            .ok()?;
111
112        let decoded_str = String::from_utf8(decoded).ok()?;
113        let parts: Vec<&str> = decoded_str.splitn(2, ':').collect();
114
115        if parts.len() == 2 {
116            Some((parts[0].to_string(), parts[1].to_string()))
117        } else {
118            None
119        }
120    }
121
122    /// Get the default Docker config path (~/.docker/config.json)
123    fn default_config_path() -> Result<PathBuf> {
124        let home = dirs::home_dir().ok_or_else(|| {
125            crate::error::Error::config("Cannot determine home directory".to_string())
126        })?;
127
128        Ok(home.join(".docker").join("config.json"))
129    }
130
131    /// Get all configured registry hostnames
132    #[must_use]
133    pub fn registries(&self) -> Vec<String> {
134        self.auths.keys().cloned().collect()
135    }
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    #[test]
143    fn test_parse_docker_config() {
144        let config_json = r#"
145        {
146            "auths": {
147                "ghcr.io": {
148                    "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="
149                },
150                "docker.io": {
151                    "username": "myuser",
152                    "password": "mypass"
153                }
154            }
155        }
156        "#;
157
158        let config: DockerConfigAuth = serde_json::from_str(config_json).unwrap();
159
160        // Test base64 auth field
161        let (username, password) = config.get_credentials("ghcr.io").unwrap();
162        assert_eq!(username, "username");
163        assert_eq!(password, "password");
164
165        // Test plain username/password
166        let (username, password) = config.get_credentials("docker.io").unwrap();
167        assert_eq!(username, "myuser");
168        assert_eq!(password, "mypass");
169    }
170
171    #[test]
172    fn test_registry_normalization() {
173        let config_json = r#"
174        {
175            "auths": {
176                "https://ghcr.io": {
177                    "auth": "dXNlcm5hbWU6cGFzc3dvcmQ="
178                },
179                "https://index.docker.io/v1/": {
180                    "auth": "ZG9ja2VyOnBhc3M="
181                }
182            }
183        }
184        "#;
185
186        let config: DockerConfigAuth = serde_json::from_str(config_json).unwrap();
187
188        // Should find with or without https://
189        assert!(config.get_credentials("ghcr.io").is_some());
190
191        // Should find docker.io credentials from index.docker.io
192        assert!(config.get_credentials("docker.io").is_some());
193    }
194
195    #[test]
196    fn test_decode_auth() {
197        // "username:password" in base64
198        let auth = "dXNlcm5hbWU6cGFzc3dvcmQ=";
199        let (username, password) = DockerConfigAuth::decode_auth(auth).unwrap();
200        assert_eq!(username, "username");
201        assert_eq!(password, "password");
202    }
203
204    #[test]
205    fn test_empty_config() {
206        let config = DockerConfigAuth {
207            auths: HashMap::new(),
208        };
209
210        assert!(config.get_credentials("docker.io").is_none());
211    }
212}