zlayer-core 0.11.2

Shared types and configuration for ZLayer container orchestration
Documentation
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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//! Authentication resolver for OCI registries
//!
//! This module provides flexible authentication resolution supporting multiple sources
//! and per-registry configuration.

use super::DockerConfigAuth;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Authentication source configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthSource {
    /// No authentication
    #[default]
    Anonymous,

    /// Basic authentication with username and password
    Basic { username: String, password: String },

    /// Load from Docker config.json
    DockerConfig,

    /// Load from environment variables
    EnvVar {
        username_var: String,
        password_var: String,
    },

    /// Look up credentials from the `RegistryCredentialStore` by id.
    /// Requires the async resolver -- the sync path returns `Anonymous` with
    /// a warning log.
    SecretStore { credential_id: String },
}

/// Per-registry authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RegistryAuthConfig {
    /// Registry hostname (e.g., "docker.io", "ghcr.io")
    pub registry: String,

    /// Authentication source for this registry
    pub source: AuthSource,
}

/// Global authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AuthConfig {
    /// Per-registry authentication overrides
    #[serde(default)]
    pub registries: Vec<RegistryAuthConfig>,

    /// Default authentication source for registries not in the list
    #[serde(default)]
    pub default: AuthSource,

    /// Custom path to Docker config.json (if not using default)
    pub docker_config_path: Option<PathBuf>,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            registries: Vec::new(),
            default: AuthSource::DockerConfig,
            docker_config_path: None,
        }
    }
}

/// Authentication resolver that converts `AuthConfig` to `oci_client` `RegistryAuth`
pub struct AuthResolver {
    config: AuthConfig,
    docker_config: Option<DockerConfigAuth>,
    registry_map: HashMap<String, AuthSource>,
}

impl AuthResolver {
    /// Create a new authentication resolver
    #[must_use]
    pub fn new(config: AuthConfig) -> Self {
        // Build a map for fast registry lookups
        let registry_map: HashMap<String, AuthSource> = config
            .registries
            .iter()
            .map(|r| (r.registry.clone(), r.source.clone()))
            .collect();

        // Load Docker config if any source uses DockerConfig
        let needs_docker_config = config.default == AuthSource::DockerConfig
            || registry_map
                .values()
                .any(|s| matches!(s, AuthSource::DockerConfig));

        let docker_config = if needs_docker_config {
            Self::load_docker_config(config.docker_config_path.as_ref())
        } else {
            None
        };

        Self {
            config,
            docker_config,
            registry_map,
        }
    }

    /// Resolve authentication for an image reference
    ///
    /// Extracts the registry from the image reference and returns the appropriate
    /// `oci_client::secrets::RegistryAuth`.
    #[must_use]
    pub fn resolve(&self, image: &str) -> oci_client::secrets::RegistryAuth {
        let registry = Self::extract_registry(image);
        let source = self
            .registry_map
            .get(&registry)
            .unwrap_or(&self.config.default);

        self.resolve_source(source, &registry)
    }

    /// Return the `AuthSource` that would be used for the given registry hostname.
    ///
    /// Looks up the per-registry map first, falling back to the default source.
    #[must_use]
    pub fn source_for_registry(&self, registry: &str) -> &AuthSource {
        self.registry_map
            .get(registry)
            .unwrap_or(&self.config.default)
    }

    /// Resolve a specific `AuthSource` to `RegistryAuth`.
    ///
    /// This is the synchronous resolution path. `AuthSource::SecretStore`
    /// cannot be resolved synchronously and returns `Anonymous` with a
    /// warning log.
    pub fn resolve_source(
        &self,
        source: &AuthSource,
        registry: &str,
    ) -> oci_client::secrets::RegistryAuth {
        match source {
            AuthSource::Anonymous => oci_client::secrets::RegistryAuth::Anonymous,

            AuthSource::Basic { username, password } => {
                oci_client::secrets::RegistryAuth::Basic(username.clone(), password.clone())
            }

            AuthSource::DockerConfig => {
                if let Some(ref docker_config) = self.docker_config {
                    if let Some((username, password)) = docker_config.get_credentials(registry) {
                        return oci_client::secrets::RegistryAuth::Basic(username, password);
                    }
                }
                // Fallback to anonymous if no credentials found
                oci_client::secrets::RegistryAuth::Anonymous
            }

            AuthSource::EnvVar {
                username_var,
                password_var,
            } => {
                let username = std::env::var(username_var).unwrap_or_default();
                let password = std::env::var(password_var).unwrap_or_default();

                if !username.is_empty() && !password.is_empty() {
                    oci_client::secrets::RegistryAuth::Basic(username, password)
                } else {
                    oci_client::secrets::RegistryAuth::Anonymous
                }
            }

            AuthSource::SecretStore { .. } => {
                tracing::warn!(
                    "SecretStore auth source requires async resolver; returning Anonymous"
                );
                oci_client::secrets::RegistryAuth::Anonymous
            }
        }
    }

    /// Extract registry hostname from image reference
    ///
    /// Examples:
    /// - "ubuntu:latest" -> "docker.io"
    /// - "ghcr.io/owner/repo:tag" -> "ghcr.io"
    /// - "localhost:5000/image" -> "localhost:5000"
    fn extract_registry(image: &str) -> String {
        // Remove digest if present
        let image_without_digest = image.split('@').next().unwrap_or(image);

        // Split by '/'
        let parts: Vec<&str> = image_without_digest.split('/').collect();

        // If there's no '/', it's just an image name, assume Docker Hub
        if parts.len() == 1 {
            return "docker.io".to_string();
        }

        // Check if first part looks like a hostname (contains '.' or ':' or is 'localhost')
        let first_part = parts[0];
        if first_part.contains('.') || first_part.contains(':') || first_part == "localhost" {
            first_part.to_string()
        } else {
            // No explicit registry (e.g., "library/ubuntu"), assume Docker Hub
            "docker.io".to_string()
        }
    }

    /// Load Docker config from path or default location
    fn load_docker_config(path: Option<&PathBuf>) -> Option<DockerConfigAuth> {
        let config = if let Some(path) = path {
            DockerConfigAuth::load_from_path(path).ok()
        } else {
            DockerConfigAuth::load().ok()
        };

        if config.is_none() {
            tracing::debug!("Failed to load Docker config, using anonymous auth as fallback");
        }

        config
    }
}

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

    #[test]
    fn test_extract_registry() {
        assert_eq!(AuthResolver::extract_registry("ubuntu"), "docker.io");
        assert_eq!(AuthResolver::extract_registry("ubuntu:latest"), "docker.io");
        assert_eq!(
            AuthResolver::extract_registry("library/ubuntu"),
            "docker.io"
        );
        assert_eq!(
            AuthResolver::extract_registry("ghcr.io/owner/repo"),
            "ghcr.io"
        );
        assert_eq!(
            AuthResolver::extract_registry("ghcr.io/owner/repo:tag"),
            "ghcr.io"
        );
        assert_eq!(
            AuthResolver::extract_registry("localhost:5000/image"),
            "localhost:5000"
        );
        assert_eq!(
            AuthResolver::extract_registry("myregistry.com/path/to/image:v1.0"),
            "myregistry.com"
        );
    }

    #[test]
    fn test_anonymous_auth() {
        let config = AuthConfig {
            default: AuthSource::Anonymous,
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);
        let auth = resolver.resolve("ubuntu:latest");

        assert!(matches!(auth, oci_client::secrets::RegistryAuth::Anonymous));
    }

    #[test]
    fn test_basic_auth() {
        let config = AuthConfig {
            default: AuthSource::Basic {
                username: "user".to_string(),
                password: "pass".to_string(),
            },
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);
        let auth = resolver.resolve("ubuntu:latest");

        match auth {
            oci_client::secrets::RegistryAuth::Basic(username, password) => {
                assert_eq!(username, "user");
                assert_eq!(password, "pass");
            }
            _ => panic!("Expected Basic auth"),
        }
    }

    #[test]
    fn test_per_registry_auth() {
        let config = AuthConfig {
            registries: vec![RegistryAuthConfig {
                registry: "ghcr.io".to_string(),
                source: AuthSource::Basic {
                    username: "ghcr_user".to_string(),
                    password: "ghcr_pass".to_string(),
                },
            }],
            default: AuthSource::Anonymous,
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);

        // Should use specific auth for ghcr.io
        let auth = resolver.resolve("ghcr.io/owner/repo:tag");
        match auth {
            oci_client::secrets::RegistryAuth::Basic(username, password) => {
                assert_eq!(username, "ghcr_user");
                assert_eq!(password, "ghcr_pass");
            }
            _ => panic!("Expected Basic auth for ghcr.io"),
        }

        // Should use default (anonymous) for docker.io
        let auth = resolver.resolve("ubuntu:latest");
        assert!(matches!(auth, oci_client::secrets::RegistryAuth::Anonymous));
    }

    #[test]
    fn test_env_var_auth() {
        std::env::set_var("TEST_USERNAME", "env_user");
        std::env::set_var("TEST_PASSWORD", "env_pass");

        let config = AuthConfig {
            default: AuthSource::EnvVar {
                username_var: "TEST_USERNAME".to_string(),
                password_var: "TEST_PASSWORD".to_string(),
            },
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);
        let auth = resolver.resolve("ubuntu:latest");

        match auth {
            oci_client::secrets::RegistryAuth::Basic(username, password) => {
                assert_eq!(username, "env_user");
                assert_eq!(password, "env_pass");
            }
            _ => panic!("Expected Basic auth from env vars"),
        }

        std::env::remove_var("TEST_USERNAME");
        std::env::remove_var("TEST_PASSWORD");
    }

    #[test]
    fn test_env_var_auth_fallback() {
        // Test that missing env vars fall back to anonymous
        let config = AuthConfig {
            default: AuthSource::EnvVar {
                username_var: "NONEXISTENT_USER".to_string(),
                password_var: "NONEXISTENT_PASS".to_string(),
            },
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);
        let auth = resolver.resolve("ubuntu:latest");

        assert!(matches!(auth, oci_client::secrets::RegistryAuth::Anonymous));
    }

    #[test]
    fn test_secret_store_sync_fallback_returns_anonymous() {
        let config = AuthConfig {
            registries: vec![RegistryAuthConfig {
                registry: "private.registry.io".to_string(),
                source: AuthSource::SecretStore {
                    credential_id: "cred-uuid-123".to_string(),
                },
            }],
            default: AuthSource::Anonymous,
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);

        // The sync path cannot resolve SecretStore and must return Anonymous
        let auth = resolver.resolve("private.registry.io/image:latest");
        assert!(matches!(auth, oci_client::secrets::RegistryAuth::Anonymous));

        // The default source should still work normally
        let auth = resolver.resolve("ubuntu:latest");
        assert!(matches!(auth, oci_client::secrets::RegistryAuth::Anonymous));
    }

    #[test]
    fn test_source_for_registry_returns_correct_source() {
        let config = AuthConfig {
            registries: vec![RegistryAuthConfig {
                registry: "ghcr.io".to_string(),
                source: AuthSource::Basic {
                    username: "user".to_string(),
                    password: "pass".to_string(),
                },
            }],
            default: AuthSource::Anonymous,
            ..Default::default()
        };

        let resolver = AuthResolver::new(config);

        // Known registry returns its configured source
        let source = resolver.source_for_registry("ghcr.io");
        assert!(matches!(source, AuthSource::Basic { .. }));

        // Unknown registry returns the default
        let source = resolver.source_for_registry("docker.io");
        assert!(matches!(source, AuthSource::Anonymous));
    }

    #[test]
    fn test_secret_store_serde_roundtrip() {
        let source = AuthSource::SecretStore {
            credential_id: "abc-123".to_string(),
        };
        let json = serde_json::to_string(&source).unwrap();
        let parsed: AuthSource = serde_json::from_str(&json).unwrap();
        assert_eq!(source, parsed);
    }
}