1use crate::backend::container::ContainerManager;
15use crate::backend::registry_probe::probe_anonymous;
16use crate::backend::rpc_types::ContainerImageAccess;
17
18pub const DEFAULT_AGENT_IMAGE: &str = "ghcr.io/agentmuxai/agent-base:latest";
21
22pub(crate) const AGENT_BASE_REPO: &str = "ghcr.io/agentmuxai/agent-base";
24
25pub const DEFAULT_DEVELOPER_IMAGE: &str = "ghcr.io/agentmuxai/agent-base:developer";
29
30const DEVELOPER_TAG_SUFFIX: &str = "-developer";
32
33pub fn versioned_agent_image() -> String {
36 format!("{AGENT_BASE_REPO}:{}", env!("CARGO_PKG_VERSION"))
37}
38
39pub fn versioned_developer_image() -> String {
41 format!("{AGENT_BASE_REPO}:{}{DEVELOPER_TAG_SUFFIX}", env!("CARGO_PKG_VERSION"))
42}
43
44pub fn is_developer_image(image: &str) -> bool {
47 image
48 .trim()
49 .strip_prefix(AGENT_BASE_REPO)
50 .and_then(|rest| rest.strip_prefix(':'))
51 .is_some_and(|tag| tag == "developer" || tag.ends_with(DEVELOPER_TAG_SUFFIX))
52}
53
54pub fn current_image_for(image: &str) -> String {
56 if is_developer_image(image) {
57 versioned_developer_image()
58 } else {
59 versioned_agent_image()
60 }
61}
62
63pub fn floating_image_for(image: &str) -> &'static str {
66 if is_developer_image(image) {
67 DEFAULT_DEVELOPER_IMAGE
68 } else {
69 DEFAULT_AGENT_IMAGE
70 }
71}
72
73pub fn is_agent_base_image(image: &str) -> bool {
76 match image.trim().strip_prefix(AGENT_BASE_REPO) {
77 Some(rest) => rest.is_empty() || rest.starts_with(':') || rest.starts_with('@'),
78 None => false,
79 }
80}
81
82pub fn is_versioned_agent_image(image: &str) -> bool {
86 image
87 .trim()
88 .strip_prefix(AGENT_BASE_REPO)
89 .and_then(|rest| rest.strip_prefix(':'))
90 .is_some_and(|tag| tag.starts_with(|c: char| c.is_ascii_digit()))
91}
92
93const LEGACY_AGENT_IMAGE_REPO: &str = "ghcr.io/agentmuxai/agent-claude";
96
97pub const CONTAINER_CLI_DIR: &str = "/home/agent/.agentmux/cli";
99
100pub fn resolve_container_image(stored: &str) -> String {
106 let stored = stored.trim();
107 if stored.is_empty() || stored == DEFAULT_AGENT_IMAGE || is_legacy_agent_image(stored) {
108 versioned_agent_image()
109 } else if stored == DEFAULT_DEVELOPER_IMAGE {
110 versioned_developer_image()
111 } else {
112 stored.to_string()
113 }
114}
115
116pub fn is_legacy_agent_image(image: &str) -> bool {
118 let image = image.trim();
119 match image.strip_prefix(LEGACY_AGENT_IMAGE_REPO) {
120 Some(rest) => rest.is_empty() || rest.starts_with(':') || rest.starts_with('@'),
121 None => false,
122 }
123}
124
125#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum PullFailure {
128 Denied,
131 NotFound,
133 Network,
135 Stalled,
137 TooSlow,
139 Unverified,
142 Other,
143}
144
145pub const PULL_STALL_SECS: u64 = 60;
147pub const PULL_TOTAL_SECS: u64 = 600;
150
151impl PullFailure {
152 pub fn is_unavailable_image(self) -> bool {
155 matches!(self, Self::Denied | Self::NotFound)
156 }
157}
158
159pub fn classify_pull_error(status: Option<u16>, message: &str) -> PullFailure {
161 let m = message.to_ascii_lowercase();
162 let has = |needles: &[&str]| needles.iter().any(|n| m.contains(n));
163
164 if matches!(status, Some(401 | 403))
165 || has(&[
166 "denied",
167 "unauthorized",
168 "authentication required",
169 "forbidden",
170 "insufficient_scope",
171 ])
172 {
173 return PullFailure::Denied;
174 }
175 if status == Some(404) || has(&["manifest unknown", "name unknown", "not found", "no such image"]) {
176 return PullFailure::NotFound;
177 }
178 if has(&[
179 "no such host",
180 "lookup ",
181 "timeout",
182 "timed out",
183 "deadline exceeded",
184 "connection refused",
185 "connection reset",
186 "tls handshake",
187 "no route to host",
188 "network is unreachable",
189 "dial tcp",
190 "proxyconnect",
191 "unexpected eof",
192 ]) {
193 return PullFailure::Network;
194 }
195 PullFailure::Other
196}
197
198pub fn pull_failure_message(image: &str, kind: PullFailure, detail: &str) -> String {
202 match kind {
203 PullFailure::Denied => format!(
204 "Couldn't start the container for this agent: the registry refused access to {image}. \
205 AgentMux downloads images without signing in, so the image has to be public. \
206 Create the agent to run on this computer (host) instead, or use a public image."
207 ),
208 PullFailure::NotFound => format!(
209 "Couldn't start the container for this agent: {image} was not found in its registry. \
210 Check the image name in the agent's settings, or create the agent to run on this computer (host)."
211 ),
212 PullFailure::Network => format!(
213 "Couldn't start the container for this agent: couldn't reach the registry to download {image}. \
214 Check your internet connection and any proxy set in Docker, then send your message again, \
215 or create the agent to run on this computer (host)."
216 ),
217 PullFailure::Stalled => format!(
218 "Couldn't start the container for this agent: the download of {image} stopped (no data for {PULL_STALL_SECS} s). \
219 Check your internet connection and any proxy set in Docker, then send your message again, \
220 or create the agent to run on this computer (host)."
221 ),
222 PullFailure::TooSlow => format!(
223 "Couldn't start the container for this agent: the download of {image} was still not finished after {} minutes, so AgentMux gave up. \
224 Check your internet connection, then send your message again, \
225 or create the agent to run on this computer (host).",
226 PULL_TOTAL_SECS / 60
227 ),
228 PullFailure::Unverified => format!(
229 "Couldn't start the container for this agent: the signed manifest of this AgentMux release isn't trusted ({}), \
230 so {image} was not downloaded. Update AgentMux, or create the agent to run on this computer (host).",
231 truncate(detail.trim(), 200)
232 ),
233 PullFailure::Other => format!(
234 "Couldn't start the container for this agent: couldn't download {image}: {}. \
235 Send your message again, or create the agent to run on this computer (host).",
236 truncate(detail.trim(), 300)
237 ),
238 }
239}
240
241pub fn cli_install_failure_message(command: &str, detail: &str) -> String {
243 format!(
244 "Couldn't start the container for this agent: couldn't install {command} in it: {}. \
245 Check your internet connection, then send your message again, \
246 or create the agent to run on this computer (host).",
247 truncate(detail.trim(), 400)
248 )
249}
250
251pub fn docker_unreachable_message() -> String {
253 "Couldn't start the container for this agent: Docker isn't responding. \
254 Start Docker Desktop (or your container runtime) and send your message again, \
255 or create the agent to run on this computer (host)."
256 .to_string()
257}
258
259pub fn docker_error_message(detail: &str) -> String {
261 format!(
262 "Couldn't start the container for this agent: Docker reported an error: {}",
263 truncate(detail.trim(), 300)
264 )
265}
266
267pub fn looks_like_daemon_unreachable(message: &str) -> bool {
269 let m = message.to_ascii_lowercase();
270 [
271 "error trying to connect",
272 "cannot connect to the docker daemon",
273 "is the docker daemon running",
274 "the system cannot find the file specified",
275 "the system cannot find the path specified",
276 "docker.sock",
277 "docker_engine",
278 ]
279 .iter()
280 .any(|n| m.contains(n))
281}
282
283fn truncate(s: &str, max: usize) -> String {
284 if s.chars().count() <= max {
285 return s.to_string();
286 }
287 let cut: String = s.chars().take(max).collect();
288 format!("{cut}...")
289}
290
291#[derive(Debug, Clone, PartialEq, Eq)]
293pub struct ImageRef {
294 pub registry: String,
295 pub repo: String,
296 pub reference: String,
297}
298
299pub fn parse_image_ref(image: &str) -> Option<ImageRef> {
302 let image = image.trim();
303 if image.is_empty() {
304 return None;
305 }
306 let (name, reference) = if let Some((name, digest)) = image.split_once('@') {
307 (name, digest.to_string())
308 } else {
309 let last_slash = image.rfind('/').map_or(0, |i| i + 1);
310 match image[last_slash..].rfind(':') {
311 Some(i) => (&image[..last_slash + i], image[last_slash + i + 1..].to_string()),
312 None => (image, "latest".to_string()),
313 }
314 };
315 if reference.is_empty() {
316 return None;
317 }
318
319 let (registry, repo) = match name.split_once('/') {
320 Some((first, rest)) if first.contains('.') || first.contains(':') || first == "localhost" => {
321 (first.to_string(), rest.to_string())
322 }
323 _ => ("docker.io".to_string(), name.to_string()),
324 };
325 if registry == "localhost" || registry.starts_with("localhost:") || registry.contains(':') {
326 return None;
327 }
328 let (registry, repo) = if registry == "docker.io" || registry == "index.docker.io" {
329 let repo = if repo.contains('/') { repo } else { format!("library/{repo}") };
330 ("registry-1.docker.io".to_string(), repo)
331 } else {
332 (registry, repo)
333 };
334 if repo.is_empty() || repo.contains("..") {
335 return None;
336 }
337 Some(ImageRef { registry, repo, reference })
338}
339
340#[derive(Debug, Clone, PartialEq, Eq, Default)]
342pub struct BearerChallenge {
343 pub realm: String,
344 pub service: Option<String>,
345 pub scope: Option<String>,
346}
347
348pub fn parse_bearer_challenge(header: &str) -> Option<BearerChallenge> {
350 let rest = header.trim().strip_prefix("Bearer ").or_else(|| header.trim().strip_prefix("bearer "))?;
351 let mut out = BearerChallenge::default();
352 for part in split_challenge_params(rest) {
353 let Some((key, value)) = part.split_once('=') else { continue };
354 let value = value.trim().trim_matches('"').to_string();
355 match key.trim().to_ascii_lowercase().as_str() {
356 "realm" => out.realm = value,
357 "service" => out.service = Some(value),
358 "scope" => out.scope = Some(value),
359 _ => {}
360 }
361 }
362 (!out.realm.is_empty()).then_some(out)
363}
364
365fn split_challenge_params(s: &str) -> Vec<&str> {
367 let mut parts = Vec::new();
368 let (mut start, mut in_quotes) = (0, false);
369 for (i, c) in s.char_indices() {
370 match c {
371 '"' => in_quotes = !in_quotes,
372 ',' if !in_quotes => {
373 parts.push(s[start..i].trim());
374 start = i + 1;
375 }
376 _ => {}
377 }
378 }
379 parts.push(s[start..].trim());
380 parts.into_iter().filter(|p| !p.is_empty()).collect()
381}
382
383pub async fn check_image_access(manager: Option<&ContainerManager>, image: &str) -> ContainerImageAccess {
387 let image = resolve_container_image(image);
388 let mut candidates = vec![image.clone()];
389 if is_legacy_agent_image(&image) {
390 candidates.push(DEFAULT_AGENT_IMAGE.to_string());
391 } else if is_versioned_agent_image(&image) {
392 candidates.push(floating_image_for(&image).to_string());
393 }
394 let mut best: Option<ContainerImageAccess> = None;
395 for candidate in &candidates {
396 let local = match manager {
397 Some(m) => m.has_image_locally(candidate).await,
398 None => false,
399 };
400 let access = if local { ContainerImageAccess::Local } else { probe_anonymous(candidate).await };
401 best = Some(match best {
402 Some(prev) => better_access(prev, access),
403 None => access,
404 });
405 }
406 best.unwrap_or(ContainerImageAccess::Unknown)
407}
408
409pub fn better_access(a: ContainerImageAccess, b: ContainerImageAccess) -> ContainerImageAccess {
412 fn rank(x: ContainerImageAccess) -> u8 {
413 match x {
414 ContainerImageAccess::Local => 4,
415 ContainerImageAccess::Public => 3,
416 ContainerImageAccess::Unknown => 2,
417 ContainerImageAccess::Denied => 1,
418 ContainerImageAccess::NotFound => 0,
419 }
420 }
421 if rank(b) > rank(a) { b } else { a }
422}
423
424#[cfg(test)]
425mod tests {
426 use super::*;
427
428 #[test]
429 fn an_empty_stored_image_means_this_versions_base_image() {
430 let versioned = format!("ghcr.io/agentmuxai/agent-base:{}", env!("CARGO_PKG_VERSION"));
431 assert_eq!(resolve_container_image(""), versioned);
432 assert_eq!(resolve_container_image(" "), versioned);
433 assert_eq!(resolve_container_image(DEFAULT_AGENT_IMAGE), versioned, "the default definitions carry :latest");
434 assert_eq!(resolve_container_image("my/own:1"), "my/own:1");
435 assert_eq!(resolve_container_image("ghcr.io/agentmuxai/agent-base:0.59.1"), "ghcr.io/agentmuxai/agent-base:0.59.1");
436 }
437
438 #[test]
439 fn the_retired_image_is_never_what_a_container_is_made_from() {
440 let versioned = versioned_agent_image();
441 for legacy in ["ghcr.io/agentmuxai/agent-claude:latest", "ghcr.io/agentmuxai/agent-claude", "ghcr.io/agentmuxai/agent-claude:2026-06-14", "ghcr.io/agentmuxai/agent-claude@sha256:abc"] {
442 assert_eq!(resolve_container_image(legacy), versioned, "{legacy}");
443 }
444 assert_eq!(resolve_container_image("ghcr.io/agentmuxai/agent-claude-extra:latest"), "ghcr.io/agentmuxai/agent-claude-extra:latest");
445 }
446
447 #[test]
448 fn the_developer_variant_resolves_to_this_versions_developer_image() {
449 let developer = format!("ghcr.io/agentmuxai/agent-base:{}-developer", env!("CARGO_PKG_VERSION"));
450 assert_eq!(versioned_developer_image(), developer);
451 assert_eq!(resolve_container_image(DEFAULT_DEVELOPER_IMAGE), developer);
452 assert_eq!(resolve_container_image("ghcr.io/agentmuxai/agent-base:0.59.1-developer"), "ghcr.io/agentmuxai/agent-base:0.59.1-developer");
453 assert_eq!(resolve_container_image(""), versioned_agent_image(), "the base image stays the default");
454 }
455
456 #[test]
457 fn the_developer_variant_is_told_apart_by_its_tag() {
458 assert!(is_developer_image(DEFAULT_DEVELOPER_IMAGE));
459 assert!(is_developer_image(&versioned_developer_image()));
460 assert!(is_developer_image(" ghcr.io/agentmuxai/agent-base:0.59.41-developer "));
461 assert!(is_developer_image("ghcr.io/agentmuxai/agent-base:dispatch-1ddc56f-developer"));
462 assert!(!is_developer_image(DEFAULT_AGENT_IMAGE));
463 assert!(!is_developer_image(&versioned_agent_image()));
464 assert!(!is_developer_image("ghcr.io/agentmuxai/agent-base@sha256:abc"), "a digest names no variant");
465 assert!(!is_developer_image("ghcr.io/agentmuxai/agent-base-extra:1.0.0-developer"));
466 assert!(!is_developer_image("my/own:developer"));
467 assert!(is_agent_base_image(&versioned_developer_image()), "it is the same repository, so the update rules see an agent image");
468 assert_eq!(current_image_for(DEFAULT_DEVELOPER_IMAGE), versioned_developer_image());
469 assert_eq!(current_image_for(DEFAULT_AGENT_IMAGE), versioned_agent_image());
470 }
471
472 #[test]
473 fn a_missing_versioned_developer_image_falls_back_to_the_floating_developer_image_not_the_base() {
474 assert!(is_versioned_agent_image(&versioned_developer_image()));
475 assert_eq!(floating_image_for(&versioned_developer_image()), DEFAULT_DEVELOPER_IMAGE);
476 assert_eq!(floating_image_for(&versioned_agent_image()), DEFAULT_AGENT_IMAGE);
477 assert!(!is_versioned_agent_image(DEFAULT_DEVELOPER_IMAGE));
478 }
479
480 #[test]
481 fn the_base_image_is_recognised_at_any_tag_and_nothing_else_is() {
482 assert!(is_agent_base_image("ghcr.io/agentmuxai/agent-base:0.59.41"));
483 assert!(is_agent_base_image("ghcr.io/agentmuxai/agent-base:latest"));
484 assert!(is_agent_base_image("ghcr.io/agentmuxai/agent-base"));
485 assert!(is_agent_base_image("ghcr.io/agentmuxai/agent-base@sha256:abc"));
486 assert!(!is_agent_base_image("ghcr.io/agentmuxai/agent-base-extra:1.0.0"));
487 assert!(!is_agent_base_image("my/own:1"));
488 }
489
490 #[test]
491 fn only_a_version_pinned_base_image_can_fall_back_to_latest() {
492 assert!(is_versioned_agent_image(&versioned_agent_image()));
493 assert!(is_versioned_agent_image("ghcr.io/agentmuxai/agent-base:0.59.41"));
494 assert!(is_versioned_agent_image(" ghcr.io/agentmuxai/agent-base:1.0.0-beta.1 "));
495 assert!(!is_versioned_agent_image(DEFAULT_AGENT_IMAGE));
496 assert!(!is_versioned_agent_image("ghcr.io/agentmuxai/agent-base:dispatch-1ddc56f"));
497 assert!(!is_versioned_agent_image("ghcr.io/agentmuxai/agent-base"));
498 assert!(!is_versioned_agent_image("ghcr.io/agentmuxai/agent-base-extra:1.0.0"));
499 assert!(!is_versioned_agent_image("my/own:1.0.0"));
500 }
501
502 #[test]
503 fn the_legacy_image_is_recognised_at_any_tag_and_nothing_else_is() {
504 assert!(is_legacy_agent_image("ghcr.io/agentmuxai/agent-claude:latest"));
505 assert!(is_legacy_agent_image("ghcr.io/agentmuxai/agent-claude:2026-06-14"));
506 assert!(is_legacy_agent_image("ghcr.io/agentmuxai/agent-claude"));
507 assert!(is_legacy_agent_image("ghcr.io/agentmuxai/agent-claude@sha256:abc"));
508 assert!(!is_legacy_agent_image("ghcr.io/agentmuxai/agent-claude-extra:latest"));
509 assert!(!is_legacy_agent_image(DEFAULT_AGENT_IMAGE));
510 assert!(!is_legacy_agent_image("someone/agent-claude:latest"));
511 }
512
513 #[test]
514 fn real_daemon_texts_classify_as_denied() {
515 for text in [
516 "Head \"https://ghcr.io/v2/agentmuxai/agent-claude/manifests/latest\": denied",
517 "Error response from daemon: Head \"https://ghcr.io/v2/x/manifests/latest\": unauthorized",
518 "pull access denied for x, repository does not exist or may require 'docker login'",
519 "unauthorized: authentication required",
520 "denied: requested access to the resource is denied",
521 ] {
522 assert_eq!(classify_pull_error(Some(500), text), PullFailure::Denied, "{text}");
523 }
524 assert_eq!(classify_pull_error(Some(401), ""), PullFailure::Denied);
525 assert_eq!(classify_pull_error(Some(403), "whatever"), PullFailure::Denied);
526 }
527
528 #[test]
529 fn missing_images_classify_as_not_found() {
530 assert_eq!(classify_pull_error(Some(404), ""), PullFailure::NotFound);
531 assert_eq!(
532 classify_pull_error(Some(500), "manifest for ghcr.io/x/y:nope not found: manifest unknown: manifest unknown"),
533 PullFailure::NotFound
534 );
535 assert_eq!(classify_pull_error(None, "No such image: foo"), PullFailure::NotFound);
536 }
537
538 #[test]
539 fn unreachable_registries_classify_as_network() {
540 for text in [
541 "Get \"https://ghcr.io/v2/\": dial tcp: lookup ghcr.io on 127.0.0.11:53: no such host",
542 "Get \"https://ghcr.io/v2/\": net/http: TLS handshake timeout",
543 "Get \"https://ghcr.io/v2/\": context deadline exceeded",
544 "dial tcp 140.82.112.34:443: connect: connection refused",
545 "proxyconnect tcp: dial tcp 10.0.0.1:3128: i/o timeout",
546 ] {
547 assert_eq!(classify_pull_error(Some(500), text), PullFailure::Network, "{text}");
548 }
549 }
550
551 #[test]
552 fn denied_wins_over_not_found_when_both_words_appear() {
553 assert_eq!(
555 classify_pull_error(Some(500), "pull access denied for x, repository does not exist or not found"),
556 PullFailure::Denied
557 );
558 }
559
560 #[test]
561 fn anything_else_is_other() {
562 assert_eq!(classify_pull_error(Some(500), "toomanyrequests: rate limit"), PullFailure::Other);
563 assert_eq!(classify_pull_error(None, ""), PullFailure::Other);
564 }
565
566 #[test]
567 fn only_a_refused_or_missing_image_is_worth_a_fallback() {
568 assert!(PullFailure::Denied.is_unavailable_image());
569 assert!(PullFailure::NotFound.is_unavailable_image());
570 assert!(!PullFailure::Network.is_unavailable_image());
571 assert!(!PullFailure::Other.is_unavailable_image());
572 }
573
574 #[test]
575 fn every_message_names_the_image_and_a_next_step_and_never_a_raw_docker_error() {
576 for kind in [PullFailure::Denied, PullFailure::NotFound, PullFailure::Network, PullFailure::Other] {
577 let msg = pull_failure_message("ghcr.io/x/y:1", kind, "some detail");
578 assert!(msg.starts_with("Couldn't start the container for this agent"), "{msg}");
579 assert!(msg.contains("ghcr.io/x/y:1"), "{msg}");
580 assert!(msg.contains("(host)"), "offers the host fallback: {msg}");
581 assert!(!msg.contains("Docker API error"), "{msg}");
582 }
583 }
584
585 #[test]
586 fn only_the_catch_all_message_carries_the_daemons_text() {
587 let denied = pull_failure_message("img", PullFailure::Denied, "Head https://secret-host/v2: denied");
588 assert!(!denied.contains("secret-host"));
589 let other = pull_failure_message("img", PullFailure::Other, "odd failure");
590 assert!(other.contains("odd failure"));
591 }
592
593 #[test]
594 fn a_long_detail_is_cut() {
595 let msg = pull_failure_message("img", PullFailure::Other, &"x".repeat(2000));
596 assert!(msg.len() < 700, "{}", msg.len());
597 }
598
599 #[test]
600 fn daemon_down_texts_are_recognised() {
601 assert!(looks_like_daemon_unreachable("error trying to connect: The system cannot find the file specified. (os error 2)"));
602 assert!(looks_like_daemon_unreachable("Cannot connect to the Docker daemon at unix:///var/run/docker.sock"));
603 assert!(!looks_like_daemon_unreachable("Docker responded with status code 409: name conflict"));
604 }
605
606 #[test]
607 fn image_refs_split_like_docker_does() {
608 let r = parse_image_ref("ghcr.io/agentmuxai/agent-base:latest").unwrap();
609 assert_eq!((r.registry.as_str(), r.repo.as_str(), r.reference.as_str()), ("ghcr.io", "agentmuxai/agent-base", "latest"));
610
611 let r = parse_image_ref("ghcr.io/agentmuxai/agent-base").unwrap();
612 assert_eq!(r.reference, "latest");
613
614 let r = parse_image_ref("alpine").unwrap();
615 assert_eq!((r.registry.as_str(), r.repo.as_str(), r.reference.as_str()), ("registry-1.docker.io", "library/alpine", "latest"));
616
617 let r = parse_image_ref("someone/tool:1.2").unwrap();
618 assert_eq!((r.registry.as_str(), r.repo.as_str(), r.reference.as_str()), ("registry-1.docker.io", "someone/tool", "1.2"));
619
620 let r = parse_image_ref("docker.io/library/node:24-slim").unwrap();
621 assert_eq!((r.registry.as_str(), r.repo.as_str()), ("registry-1.docker.io", "library/node"));
622
623 let r = parse_image_ref("ghcr.io/o/r@sha256:0123").unwrap();
624 assert_eq!((r.repo.as_str(), r.reference.as_str()), ("o/r", "sha256:0123"));
625 }
626
627 #[test]
628 fn local_and_port_registries_are_not_probed() {
629 assert_eq!(parse_image_ref("localhost/foo:1"), None);
630 assert_eq!(parse_image_ref("localhost:5000/foo:1"), None);
631 assert_eq!(parse_image_ref("registry.local:5000/foo:1"), None);
632 assert_eq!(parse_image_ref(""), None);
633 assert_eq!(parse_image_ref("foo:"), None);
634 }
635
636 #[test]
637 fn a_bearer_challenge_is_parsed_including_a_scope_with_a_comma() {
638 let c = parse_bearer_challenge(
639 r#"Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:agentmuxai/agent-base:pull""#,
640 )
641 .unwrap();
642 assert_eq!(c.realm, "https://ghcr.io/token");
643 assert_eq!(c.service.as_deref(), Some("ghcr.io"));
644 assert_eq!(c.scope.as_deref(), Some("repository:agentmuxai/agent-base:pull"));
645
646 let c = parse_bearer_challenge(r#"Bearer realm="https://auth.example/t",scope="repository:a/b:pull,push""#).unwrap();
647 assert_eq!(c.scope.as_deref(), Some("repository:a/b:pull,push"));
648 assert_eq!(c.service, None);
649 }
650
651 #[test]
652 fn a_challenge_that_is_not_bearer_or_has_no_realm_is_none() {
653 assert_eq!(parse_bearer_challenge("Basic realm=\"x\""), None);
654 assert_eq!(parse_bearer_challenge("Bearer service=\"x\""), None);
655 assert_eq!(parse_bearer_challenge(""), None);
656 }
657
658 #[test]
659 fn a_usable_answer_beats_unknown_which_beats_a_refusal() {
660 use ContainerImageAccess::*;
661 assert_eq!(better_access(Denied, Public), Public);
662 assert_eq!(better_access(Public, Denied), Public);
663 assert_eq!(better_access(Denied, Unknown), Unknown);
664 assert_eq!(better_access(NotFound, Denied), Denied);
665 assert_eq!(better_access(Local, Public), Local);
666 }
667}