zlayer_core/auth/
docker_config.rs1use crate::error::Result;
7use serde::{Deserialize, Serialize};
8use std::collections::HashMap;
9use std::fs;
10use std::path::{Path, PathBuf};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct DockerConfigAuth {
15 #[serde(default)]
16 auths: HashMap<String, AuthEntry>,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
21struct AuthEntry {
22 auth: Option<String>,
24 username: Option<String>,
26 password: Option<String>,
28}
29
30impl DockerConfigAuth {
31 pub fn load() -> Result<Self> {
37 let path = Self::default_config_path()?;
38 Self::load_from_path(&path)
39 }
40
41 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 #[must_use]
68 pub fn get_credentials(&self, registry: &str) -> Option<(String, String)> {
69 if let Some(entry) = self.auths.get(registry) {
71 return Self::extract_credentials(entry);
72 }
73
74 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 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 fn extract_credentials(entry: &AuthEntry) -> Option<(String, String)> {
92 if let (Some(username), Some(password)) = (&entry.username, &entry.password) {
94 return Some((username.clone(), password.clone()));
95 }
96
97 if let Some(auth) = &entry.auth {
99 return Self::decode_auth(auth);
100 }
101
102 None
103 }
104
105 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 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 #[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 let (username, password) = config.get_credentials("ghcr.io").unwrap();
162 assert_eq!(username, "username");
163 assert_eq!(password, "password");
164
165 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 assert!(config.get_credentials("ghcr.io").is_some());
190
191 assert!(config.get_credentials("docker.io").is_some());
193 }
194
195 #[test]
196 fn test_decode_auth() {
197 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}