use bollard::container::{ Config, CreateContainerOptions, ListContainersOptions, RemoveContainerOptions, StartContainerOptions, StopContainerOptions, }; use bollard::image::{CommitContainerOptions, RemoveImageOptions}; use bollard::models::{ContainerSummary, HostConfig, Mount, MountTypeEnum, PortBinding}; use std::collections::HashMap; use sha2::{Sha256, Digest}; use super::ca_certs; use super::client::get_docker; use crate::models::{Backend, BedrockAuthMethod, ClaudeCodeSettings, ContainerInfo, EnvVar, GlobalAwsSettings, GlobalLlamaCppSettings, GlobalOllamaSettings, GlobalOpenAiCompatibleSettings, PortMapping, Project, ProjectPath}; const SCHEDULER_INSTRUCTIONS: &str = r#"## Scheduled Tasks This container supports scheduled tasks via `triple-c-scheduler`. You can set up recurring or one-time tasks that run as separate Claude Code agents. ### Commands - `triple-c-scheduler add --name "NAME" --schedule "CRON" --prompt "TASK"` — Add a recurring task - `triple-c-scheduler add --name "NAME" --at "YYYY-MM-DD HH:MM" --prompt "TASK"` — Add a one-time task - `triple-c-scheduler list` — List all scheduled tasks, with a running/idle status column - `triple-c-scheduler remove --id ID` — Remove a task - `triple-c-scheduler enable --id ID` / `triple-c-scheduler disable --id ID` — Toggle tasks - `triple-c-scheduler status [--id ID] [--watch]` — Show what is running right now, and for how long - `triple-c-scheduler logs [--id ID] [--tail N]` — View execution logs - `triple-c-scheduler run --id ID` — Manually trigger a task immediately (streams its log) - `triple-c-scheduler notifications [--clear]` — View or clear completion notifications ### Cron format Standard 5-field cron: `minute hour day-of-month month day-of-week` Examples: `*/30 * * * *` (every 30 min), `0 9 * * 1-5` (9am weekdays), `0 */2 * * *` (every 2 hours) ### One-time tasks Use `--at "YYYY-MM-DD HH:MM"` instead of `--schedule`. The task automatically removes itself after execution. ### Working directory Use `--working-dir /workspace/project` to set where the task runs (default: /workspace). ### Checking results While a task is running, `triple-c-scheduler status` reports it with elapsed time — a log that has stopped growing is normal, because `claude -p` writes its answer only at the end, so use `status` rather than log silence to tell a slow run from a dead one. After tasks run, check notifications with `triple-c-scheduler notifications` and detailed output with `triple-c-scheduler logs`. ### Timezone Scheduled times use the container's configured timezone (check with `date`). If no timezone is configured, UTC is used."#; const MISSION_CONTROL_GLOBAL_INSTRUCTIONS: &str = r#"## Mission Control The `/workspace/mission-control/` directory contains **Flight Control** — an AI-first development methodology for structured project management. Use it for all project work. ### How It Works - **Mission Control is a tool, not a project.** It provides skills and methodology for managing other projects. - All Flight Control skills are installed as personal skills in `~/.claude/skills/` and are automatically available as `/slash-commands` - The methodology docs and project registry live in `/workspace/mission-control/` ### When to Use When working on any project that has a `.flightops/` directory, follow the Flight Control methodology: 1. Read the project's `.flightops/ARTIFACTS.md` to understand artifact storage 2. Read `.flightops/FLIGHT_OPERATIONS.md` for the implementation workflow 3. Use Mission Control skills for planning and execution ### Available Skills | Skill | When to Use | |-------|-------------| | `/init-project` | Setting up a new project for Flight Control | | `/mission` | Defining new work outcomes (days-to-weeks scope) | | `/flight` | Creating technical specs from missions (hours-to-days scope) | | `/leg` | Generating implementation steps from flights (minutes-to-hours scope) | | `/agentic-workflow` | Executing legs with multi-agent workflow (implement, review, commit) | | `/flight-debrief` | Post-flight analysis after a flight lands | | `/mission-debrief` | Post-mission retrospective after completion | | `/daily-briefing` | Cross-project status report | ### Key Rules - **Planning skills produce artifacts only** — never modify source code directly - **Phase gates require human confirmation** — missions before flights, flights before legs - **Legs are immutable once in-flight** — create new ones instead of modifying - **`/agentic-workflow` orchestrates implementation** — it spawns separate Developer and Reviewer agents - **Artifacts live in the target project** — not in mission-control"#; const MISSION_CONTROL_PROJECT_INSTRUCTIONS: &str = r#"## Flight Operations This project uses **Flight Control** (bundled with Triple-C) for structured development. **Before any mission/flight/leg work, read these files in order:** 1. `.flightops/README.md` — What the flightops directory contains 2. `.flightops/FLIGHT_OPERATIONS.md` — **The workflow you MUST follow** 3. `.flightops/ARTIFACTS.md` — Where all artifacts are stored 4. `.flightops/agent-crews/` — Project crew definitions for each phase (read the relevant crew file)"#; const SANDBOX_INSTRUCTIONS: &str = r#"## Sandbox Mode This container has Claude Code's bash sandbox enabled, managed by Triple-C (toggle it from the project's "Sandbox mode" switch in the Triple-C UI). Bash commands run inside `bubblewrap` with filesystem and network isolation (`enableWeakerNestedSandbox` is on because we are inside Docker). ### When a command fails because of sandbox restrictions Triple-C disables the `dangerouslyDisableSandbox` escape hatch (`allowUnsandboxedCommands: false`), so failing commands cannot bypass the sandbox at runtime. To make a blocked command work, edit `~/.claude/settings.json` and restart Claude Code: | Need | Setting | |---|---| | Write to a path outside the project (e.g. `~/.kube`) | Add to `sandbox.filesystem.allowWrite` | | Reach a new domain | Will prompt; or add permanently to `sandbox.allowedDomains` | | Run a specific tool entirely outside the sandbox | Add a glob (e.g. `"docker *"`) to `sandbox.excludedCommands` | ### Docker commands The `docker` CLI does not work inside the sandbox. If this project has "Allow container spawning" enabled in Triple-C and you need to run `docker` commands, add `"docker *"` to `sandbox.excludedCommands` in `~/.claude/settings.json`. Other tools known to be sandbox-incompatible include `watchman` — pass `--no-watchman` to `jest`. ### Disabling sandbox mode Do not change `sandbox.enabled` in `settings.json` — Triple-C overwrites it on every container start. To turn sandbox off, stop the container in Triple-C, flip the "Sandbox mode" switch off, then start the container."#; /// Build the full CLAUDE_INSTRUCTIONS value by merging global + project /// instructions, appending port mapping docs, and appending scheduler docs. /// Used by both create_container() and container_needs_recreation() to ensure /// the same value is produced in both paths. fn build_claude_instructions( global_instructions: Option<&str>, project_instructions: Option<&str>, port_mappings: &[PortMapping], mission_control_enabled: bool, sandbox_enabled: bool, ) -> Option { let mut combined = merge_claude_instructions( global_instructions, project_instructions, mission_control_enabled, ); if !port_mappings.is_empty() { let mut port_lines: Vec = Vec::new(); port_lines.push("## Available Port Mappings".to_string()); port_lines.push("The following ports are mapped from the host to this container. Use these container ports when starting services that need to be accessible from the host:".to_string()); for pm in port_mappings { port_lines.push(format!( "- Host port {} -> Container port {} ({})", pm.host_port, pm.container_port, pm.protocol )); } let port_info = port_lines.join("\n"); combined = Some(match combined { Some(existing) => format!("{}\n\n{}", existing, port_info), None => port_info, }); } combined = Some(match combined { Some(existing) => format!("{}\n\n{}", existing, SCHEDULER_INSTRUCTIONS), None => SCHEDULER_INSTRUCTIONS.to_string(), }); if sandbox_enabled { combined = Some(match combined { Some(existing) => format!("{}\n\n{}", existing, SANDBOX_INSTRUCTIONS), None => SANDBOX_INSTRUCTIONS.to_string(), }); } combined } /// The env var Claude Code reads a long-lived `claude setup-token` credential /// from. Named once so injection, the reserved-name blocklist, and the /// stale-value neutralization pass can never disagree about the spelling. pub const CLAUDE_OAUTH_TOKEN_ENV: &str = "CLAUDE_CODE_OAUTH_TOKEN"; /// Every managed env var whose *value* is a credential. /// /// These are the names that must never survive into a snapshot image. A /// container's env is visible to `docker inspect`, which is bad but bounded — /// the container is recreated whenever the credential rotates, and removed /// with the project. An **image**'s env is neither: `docker commit` copies the /// container's full environment into `triple-c-snapshot-{id}:latest`, that tag /// outlives every container built from it, and nothing about deleting a /// keychain entry touches it. A ~1-year OAuth token baked in that way is /// readable by `docker image inspect` for as long as the image exists, long /// after the user has clicked Revoke. /// /// [`commit_container_snapshot`] therefore blanks all of them at commit time, /// and [`scrub_secrets_from_snapshots`] rewrites images committed before that /// was true. /// /// Blanked rather than omitted, because Docker's commit endpoint *merges* the /// supplied config over the container's rather than replacing it: a key left /// out of the list is inherited with its original value, so `KEY=` is the only /// way to clear one. That matches how `MANAGED_AUTH_KEYS` already works at /// create time, and Claude Code, the AWS SDK and git all treat an empty value /// as unset. pub const SECRET_ENV_KEYS: &[&str] = &[ CLAUDE_OAUTH_TOKEN_ENV, "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_BEARER_TOKEN_BEDROCK", "GIT_TOKEN", ]; /// Env var name prefixes Triple-C manages itself; users cannot set these by hand. /// The label every container Triple-C creates carries — and, because /// `docker commit` copies a container's labels onto the image, every snapshot it /// commits. [`sweep_orphaned_snapshots`] treats it as the mark of provenance, /// which is what keeps the sweep away from the user's own images. pub(crate) const LABEL_MANAGED: &str = "triple-c.managed"; /// Marks the throwaway container [`rewrite_image_without_secrets`] commits /// from. It exists so the Disk panel's reclaim bucket can distinguish a live /// credential rewrite from a leftover by label rather than by age. pub(crate) const LABEL_SCRUB: &str = "triple-c.scrub"; /// Marks the image built from `container/Dockerfile` itself, as opposed to a /// project snapshot committed from a container. Only ever `"true"` on a base /// image; `create_container` writes it explicitly empty so an inherited value /// cannot travel onto a snapshot. See the `LABEL` block in the Dockerfile. pub(crate) const LABEL_BASE: &str = "triple-c.base"; const RESERVED_ENV_PREFIXES: &[&str] = &["ANTHROPIC_", "AWS_", "GIT_", "HOST_", "TRIPLE_C_"]; /// Exact env var names Triple-C manages itself. Not covered by /// [`RESERVED_ENV_PREFIXES`] because they don't share those prefixes. /// /// `MCP_SERVERS_JSON` is reserved for legacy reasons: the built-in MCP feature /// was removed, but the name stays blocked so users cannot hand-set it. /// `CLAUDE_CODE_OAUTH_TOKEN` is reserved because Triple-C owns it — a hand-set /// value would silently outrank the keychain-held shared token and be invisible /// to the auth UI. const RESERVED_ENV_EXACT: &[&str] = &[ "CLAUDE_INSTRUCTIONS", "MCP_SERVERS_JSON", "CLAUDE_CODE_SETTINGS_JSON", "CLAUDE_CODE_SETTINGS_CLEAR", "MISSION_CONTROL_ENABLED", "VPN_SUPPORT_ENABLED", "TRIPLE_C_PERMISSION_MODE", // The four env vars the Claude Code settings editor drives. Reserved for // the `VPN_SUPPORT_ENABLED` reason: each is now written on every create, // including its off value, so a hand-set custom var of the same name would // either be overridden without explanation or override the setting behind // the UI's back, depending on which one Docker kept. "CLAUDE_CODE_NO_FLICKER", "CLAUDE_CODE_ENABLE_AWAY_SUMMARY", "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB", "ENABLE_PROMPT_CACHING_1H", CLAUDE_OAUTH_TOKEN_ENV, // The model-alias vars are already covered by the `ANTHROPIC_` prefix // above; they are listed explicitly so that a future narrowing of the // prefix list cannot silently unreserve them, and so `is_reserved_env_key` // reads as the single, complete statement of what Triple-C owns. ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL, ANTHROPIC_DEFAULT_FABLE_MODEL, ]; /// Claude Code's model-alias env vars. Each names the concrete model id that /// one of the `opus` / `sonnet` / `haiku` / `fable` aliases resolves to. /// /// `ANTHROPIC_DEFAULT_HAIKU_MODEL` is the important one: it is documented as /// *"Model ID that the `haiku` alias resolves to, also used for background /// functionality"* — conversation titles, summarisation, and other out-of-band /// calls. Left unset against a local server, Claude Code sends /// Anthropic's own Haiku model id to a server that has never heard of it and /// every background call fails, usually silently. /// /// (`ANTHROPIC_SMALL_FAST_MODEL` is the deprecated predecessor of the Haiku /// var and is deliberately *not* used.) pub const ANTHROPIC_DEFAULT_OPUS_MODEL: &str = "ANTHROPIC_DEFAULT_OPUS_MODEL"; pub const ANTHROPIC_DEFAULT_SONNET_MODEL: &str = "ANTHROPIC_DEFAULT_SONNET_MODEL"; pub const ANTHROPIC_DEFAULT_HAIKU_MODEL: &str = "ANTHROPIC_DEFAULT_HAIKU_MODEL"; pub const ANTHROPIC_DEFAULT_FABLE_MODEL: &str = "ANTHROPIC_DEFAULT_FABLE_MODEL"; /// Resolve the four `ANTHROPIC_DEFAULT_*_MODEL` values for a backend that /// points Claude Code at a custom endpoint. /// /// All four aliases fall back to `effective_model` — the backend's configured /// model id, already resolved per-project → global. That is the right default: /// a local server almost always serves exactly one model, so every alias must /// name it or the calls that use an alias (notably the background ones, which /// use `haiku`) go to a model the server does not have. /// /// `haiku_override` exists because that is the one alias someone might /// legitimately want to point elsewhere — at a second, smaller server-side /// model kept for cheap background work. A blank override falls back to /// `effective_model` like the others. /// /// Returns pairs in `(name, value)` form; a blank resolved value emits nothing /// at all rather than an empty var, so an unconfigured backend is left exactly /// as Claude Code found it. pub fn compute_model_aliases( effective_model: Option<&str>, haiku_override: Option<&str>, ) -> Vec<(&'static str, String)> { let base = effective_model.map(str::trim).filter(|s| !s.is_empty()); let haiku = haiku_override .map(str::trim) .filter(|s| !s.is_empty()) .or(base); let mut out: Vec<(&'static str, String)> = Vec::new(); if let Some(m) = base { out.push((ANTHROPIC_DEFAULT_OPUS_MODEL, m.to_string())); out.push((ANTHROPIC_DEFAULT_SONNET_MODEL, m.to_string())); } if let Some(h) = haiku { out.push((ANTHROPIC_DEFAULT_HAIKU_MODEL, h.to_string())); } if let Some(m) = base { out.push((ANTHROPIC_DEFAULT_FABLE_MODEL, m.to_string())); } out } /// The fingerprint contribution of the model aliases, so that changing an /// alias (or the model it falls back to) forces a container recreation. /// `container_needs_recreation` is label-based and never diffs env, so an /// env-only change is invisible without this. fn model_alias_fingerprint_part( effective_model: Option<&str>, haiku_override: Option<&str>, ) -> String { compute_model_aliases(effective_model, haiku_override) .into_iter() .map(|(k, v)| format!("{}={}", k, v)) .collect::>() .join(",") } /// Whether `key` is an env var name Triple-C reserves for itself. fn is_reserved_env_key(key: &str) -> bool { let upper = key.to_uppercase(); RESERVED_ENV_PREFIXES.iter().any(|p| upper.starts_with(p)) || RESERVED_ENV_EXACT.iter().any(|e| upper == *e) } /// Compute a fingerprint for the custom environment variables. /// /// Sorted alphabetically so order changes do not cause spurious recreation, and /// **hashed**, because this value is written as the /// `triple-c.custom-env-fingerprint` label. Labels are readable by anything on /// the host through `docker inspect`, `docker commit` copies them onto the /// project's snapshot image, and `container_needs_recreation` logs both sides on /// a mismatch — so a plaintext `KEY=VALUE` join published every custom /// variable's *value*, API tokens included, to all three places. Same treatment /// as `triple-c.git-token-hash`. /// /// Empty stays empty rather than becoming the hash of the empty string: an empty /// label is how every other `triple-c.*` key says "nothing configured". fn compute_env_fingerprint(custom_env_vars: &[EnvVar]) -> String { let mut parts: Vec = Vec::new(); for env_var in custom_env_vars { let key = env_var.key.trim(); if key.is_empty() || is_reserved_env_key(key) { continue; } parts.push(format!("{}={}", key, env_var.value)); } parts.sort(); if parts.is_empty() { return String::new(); } sha256_hex(&parts.join(",")) } /// The shared Claude Code OAuth token to inject for this project, paired with /// its rotation id. /// /// `None` unless *all* of: the backend is Anthropic (the token is meaningless /// to Bedrock/Ollama/OpenAI-compatible), the project has not opted out, and a /// non-blank token is actually in the keychain. Read here rather than passed in /// because the token is global, not part of the per-project record. /// /// The returned token is never logged and never leaves this module except as /// the env var value handed to Docker. fn shared_claude_auth(project: &Project) -> Option<(String, String)> { if project.backend != Backend::Anthropic || !project.use_shared_auth_token { return None; } let token = crate::storage::secure::get_claude_oauth_token() .unwrap_or_else(|e| { log::warn!("Could not read the shared Claude token from the keychain: {}", e); None }) .filter(|t| !t.trim().is_empty())?; // A token with no rotation id predates versioning (or the id write failed). // A constant stand-in still differs from the empty "no token" label, so // presence changes are caught; only rotations could be missed. let version = crate::storage::secure::get_claude_oauth_token_version() .unwrap_or(None) .unwrap_or_else(|| "unversioned".to_string()); Some((token, version)) } /// Label value tracking which shared Claude token (if any) a container was /// created with. Empty means "none injected". See /// [`crate::storage::secure`] for why this is a random rotation id rather than /// a hash of the token. fn claude_token_label(project: &Project) -> String { shared_claude_auth(project) .map(|(_, version)| version) .unwrap_or_default() } /// Merge global and per-project custom environment variables. /// Per-project variables override global variables with the same key. fn merge_custom_env_vars(global: &[EnvVar], project: &[EnvVar]) -> Vec { let mut merged: std::collections::HashMap = std::collections::HashMap::new(); for ev in global { let key = ev.key.trim().to_string(); if !key.is_empty() { merged.insert(key, ev.clone()); } } for ev in project { let key = ev.key.trim().to_string(); if !key.is_empty() { merged.insert(key, ev.clone()); } } merged.into_values().collect() } /// Merge global and per-project Claude instructions into a single string. /// When mission_control_enabled is true, appends Mission Control global /// instructions after global and project instructions after project. fn merge_claude_instructions( global_instructions: Option<&str>, project_instructions: Option<&str>, mission_control_enabled: bool, ) -> Option { // Build the global portion (user global + optional MC global) let global_part = if mission_control_enabled { match global_instructions { Some(g) => Some(format!("{}\n\n{}", g, MISSION_CONTROL_GLOBAL_INSTRUCTIONS)), None => Some(MISSION_CONTROL_GLOBAL_INSTRUCTIONS.to_string()), } } else { global_instructions.map(|g| g.to_string()) }; // Build the project portion (user project + optional MC project) let project_part = if mission_control_enabled { match project_instructions { Some(p) => Some(format!("{}\n\n{}", p, MISSION_CONTROL_PROJECT_INSTRUCTIONS)), None => Some(MISSION_CONTROL_PROJECT_INSTRUCTIONS.to_string()), } } else { project_instructions.map(|p| p.to_string()) }; match (global_part, project_part) { (Some(g), Some(p)) => Some(format!("{}\n\n{}", g, p)), (Some(g), None) => Some(g), (None, Some(p)) => Some(p), (None, None) => None, } } /// Hash a string with SHA-256 and return the hex digest. fn sha256_hex(input: &str) -> String { let mut hasher = Sha256::new(); hasher.update(input.as_bytes()); format!("{:x}", hasher.finalize()) } /// Resolve a per-project string value with a global fallback. Returns `None` /// when both are blank, otherwise the per-project value if set, else the global. fn resolve_with_global<'a>(per_project: Option<&'a str>, global: Option<&'a str>) -> Option<&'a str> { let project_val = per_project.map(str::trim).filter(|s| !s.is_empty()); if project_val.is_some() { return project_val; } global.map(str::trim).filter(|s| !s.is_empty()) } /// Compute a fingerprint for the Bedrock configuration so we can detect changes. /// Includes the resolved model_id (per-project blank → global default) so that /// changing the global default forces a container recreation. fn compute_bedrock_fingerprint(project: &Project, global_aws: &GlobalAwsSettings) -> String { if let Some(ref bedrock) = project.bedrock_config { let effective_model = resolve_with_global( bedrock.model_id.as_deref(), global_aws.default_model_id.as_deref(), ).unwrap_or("").to_string(); // NOTE: the static credential fields (access key / secret / session // token) are intentionally NOT part of the fingerprint. They are // written to ~/.aws/credentials on every start by // sync_bedrock_credentials(), so a key rotation should refresh // in place rather than force a full container recreation. Region, // profile, and bearer token remain env-based and so stay here. let parts = vec![ format!("{:?}", bedrock.auth_method), bedrock.aws_region.clone(), bedrock.aws_profile.as_deref().unwrap_or("").to_string(), bedrock.aws_bearer_token.as_deref().unwrap_or("").to_string(), effective_model, format!("{}", bedrock.disable_prompt_caching), bedrock.service_tier.as_deref().unwrap_or("").to_string(), ]; sha256_hex(&parts.join("|")) } else { String::new() } } /// Compute a fingerprint for the Ollama configuration so we can detect changes. /// Includes the resolved base_url and model_id (per-project blank → global /// default) and the resolved model aliases. /// /// NOTE: adding the alias part changes this hash for every existing Ollama /// container, so each will be recreated once on the next start. That is exactly /// what is wanted — recreation is the only way to get the new /// `ANTHROPIC_DEFAULT_*_MODEL` vars into the container's env. fn compute_ollama_fingerprint(project: &Project, global_ollama: &GlobalOllamaSettings) -> String { if let Some(ref ollama) = project.ollama_config { let effective_url = resolve_with_global( Some(&ollama.base_url), global_ollama.base_url.as_deref(), ).unwrap_or("").to_string(); let effective_model = resolve_with_global( ollama.model_id.as_deref(), global_ollama.default_model_id.as_deref(), ).unwrap_or("").to_string(); let aliases = model_alias_fingerprint_part( Some(&effective_model), resolve_with_global( ollama.haiku_model_id.as_deref(), global_ollama.default_haiku_model_id.as_deref(), ), ); let parts = vec![effective_url, effective_model, aliases]; sha256_hex(&parts.join("|")) } else { String::new() } } /// Compute a fingerprint for the llama.cpp configuration so we can detect /// changes. Mirrors [`compute_ollama_fingerprint`]. fn compute_llamacpp_fingerprint( project: &Project, global_llamacpp: &GlobalLlamaCppSettings, ) -> String { if let Some(ref cfg) = project.llamacpp_config { let effective_url = resolve_with_global( Some(&cfg.base_url), global_llamacpp.base_url.as_deref(), ).unwrap_or("").to_string(); let effective_model = resolve_with_global( cfg.model_id.as_deref(), global_llamacpp.default_model_id.as_deref(), ).unwrap_or("").to_string(); let aliases = model_alias_fingerprint_part( Some(&effective_model), resolve_with_global( cfg.haiku_model_id.as_deref(), global_llamacpp.default_haiku_model_id.as_deref(), ), ); let parts = vec![effective_url, effective_model, aliases]; sha256_hex(&parts.join("|")) } else { String::new() } } /// Compute a fingerprint for the OpenAI Compatible configuration so we can detect changes. /// Includes the resolved base_url and model_id (per-project blank → global default). fn compute_openai_compatible_fingerprint( project: &Project, global_openai_compatible: &GlobalOpenAiCompatibleSettings, ) -> String { if let Some(ref config) = project.openai_compatible_config { let effective_url = resolve_with_global( Some(&config.base_url), global_openai_compatible.base_url.as_deref(), ).unwrap_or("").to_string(); let effective_model = resolve_with_global( config.model_id.as_deref(), global_openai_compatible.default_model_id.as_deref(), ).unwrap_or("").to_string(); let aliases = model_alias_fingerprint_part( Some(&effective_model), resolve_with_global( config.haiku_model_id.as_deref(), global_openai_compatible.default_haiku_model_id.as_deref(), ), ); let parts = vec![ effective_url, config.api_key.as_deref().unwrap_or("").to_string(), effective_model, aliases, ]; sha256_hex(&parts.join("|")) } else { String::new() } } /// Compute a fingerprint for the project paths so we can detect changes. /// Sorted by mount_name so order changes don't cause spurious recreation. fn compute_paths_fingerprint(paths: &[ProjectPath]) -> String { let mut parts: Vec = paths .iter() .map(|p| format!("{}:{}", p.mount_name, p.host_path)) .collect(); parts.sort(); let joined = parts.join(","); sha256_hex(&joined) } /// Compute a fingerprint for port mappings so we can detect changes. /// Sorted so order changes don't cause spurious recreation. fn compute_ports_fingerprint(port_mappings: &[PortMapping]) -> String { let mut parts: Vec = port_mappings .iter() .map(|p| format!("{}:{}:{}", p.host_port, p.container_port, p.protocol)) .collect(); parts.sort(); let joined = parts.join(","); sha256_hex(&joined) } /// Merge global and per-project `ClaudeCodeSettings`. /// /// A project field that is `Some` wins outright — **including `Some(false)`**. /// That is the point of the widening: these used to be plain `bool`s ORed /// together (`if p.x { true } else { g.x }`), so a project could only ever add /// to the global set and never turn a globally-enabled setting off. `None` at /// project level means "inherit", which is now a state the project can /// actually be in rather than the only state an off switch could produce. fn merge_claude_code_settings( global: Option<&ClaudeCodeSettings>, project: Option<&ClaudeCodeSettings>, ) -> Option { match (global, project) { (None, None) => None, (Some(g), None) => Some(g.clone()), (None, Some(p)) => Some(p.clone()), (Some(g), Some(p)) => { Some(ClaudeCodeSettings { tui_mode: p.tui_mode.clone().or_else(|| g.tui_mode.clone()), effort: p.effort.clone().or_else(|| g.effort.clone()), auto_scroll_disabled: p.auto_scroll_disabled.or(g.auto_scroll_disabled), focus_mode: p.focus_mode.or(g.focus_mode), show_thinking_summaries: p.show_thinking_summaries.or(g.show_thinking_summaries), session_recap_disabled: p.session_recap_disabled.or(g.session_recap_disabled), env_scrub: p.env_scrub.or(g.env_scrub), prompt_caching_1h: p.prompt_caching_1h.or(g.prompt_caching_1h), }) } } } /// Compute a fingerprint for the Claude Code settings so we can detect changes. /// The `sandbox_enabled` flag is included so that toggling sandbox mode forces /// a container recreation (re-injecting the merged settings.json). /// /// **This formula changed, and the change is not free.** It used to read /// `format!("{}", bool)`; the booleans are now `Option` and it reads /// `format!("{:?}")`, because `None` (inherit) and `Some(false)` (a deliberate /// off) must not hash alike — conflating them leaves a container un-recreated /// on a real change. The consequence is that **every existing project holding /// a settings object gets a different fingerprint on first launch after this /// upgrade, and is recreated once.** A recreation commits a snapshot layer, so /// that is a one-off disk cost per project, paid silently. /// /// An earlier version of this comment claimed the opposite — that "the /// historical fingerprint is preserved unchanged so that upgrading triple-c /// does not spuriously flag every existing container for recreation." That was /// carried over from before the widening and was false the moment the format /// string changed. It is recorded here because a reviewer who believed it would /// conclude the churn cannot happen. fn compute_claude_code_settings_fingerprint( settings: Option<&ClaudeCodeSettings>, sandbox_enabled: bool, ) -> String { let base_fp = match settings { None => String::new(), Some(s) => { let parts = vec![ s.tui_mode.as_deref().unwrap_or("").to_string(), s.effort.as_deref().unwrap_or("").to_string(), // `{:?}` rather than `{}` so `None` and `Some(false)` produce // different text. They mean different things — inherit versus a // deliberate off — and a fingerprint that conflated them would // leave the container un-recreated on a real change. format!("{:?}", s.auto_scroll_disabled), format!("{:?}", s.focus_mode), format!("{:?}", s.show_thinking_summaries), format!("{:?}", s.session_recap_disabled), format!("{:?}", s.env_scrub), format!("{:?}", s.prompt_caching_1h), ]; sha256_hex(&parts.join("|")) } }; if sandbox_enabled { sha256_hex(&format!("{}|sandbox=true", base_fp)) } else { base_fp } } /// The four Claude Code env vars the settings editor drives, as `KEY=VALUE`. /// /// **All four are emitted on every create, including their off value.** This is /// the `MANAGED_AUTH_KEYS` rule: `docker commit` bakes a container's env into /// the snapshot image, and the next container inherits anything the create does /// not override. A `=1` written once would ride that snapshot into every future /// container and make the switch impossible to turn back off — the same /// stickiness [`build_claude_code_settings_json`] fixes on the settings.json /// side, in a place where it is even less visible. /// /// Two of them use an **empty** value for "off", and the distinction matters: /// /// * `CLAUDE_CODE_NO_FLICKER` documents `1` as fullscreen-on and `0` as /// fullscreen-*off*, and it overrides the `tui` setting. `0` is therefore not /// neutral — it would silently pin every project that has expressed no /// preference to the classic renderer, when an unset `tui` is supposed to let /// Claude Code choose. Empty is neither value, so it reads as unset while /// still overriding a baked `1`. /// * `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` outranks both `awaySummaryEnabled` and /// the in-container `/config` toggle. `0` is exactly right for "the user /// turned the recap off in Triple-C", but a blanket `1` for the default state /// would force the recap back on for someone who had turned it off with /// `/config` inside their own container. Triple-C's default must not overrule /// a choice it never asked about. /// /// The other two are documented as "set to `1` to …" with no meaning attached /// to `0`, so `0` is unambiguously neutral and is stated outright. fn claude_code_env_vars(settings: Option<&ClaudeCodeSettings>) -> Vec { let owned; let s = match settings { Some(s) => s, None => { owned = ClaudeCodeSettings::default(); &owned } }; vec![ format!( "CLAUDE_CODE_NO_FLICKER={}", match s.tui_mode.as_deref() { Some("fullscreen") => "1", Some("default") => "0", _ => "", } ), format!( "CLAUDE_CODE_ENABLE_AWAY_SUMMARY={}", if s.session_recap_disabled.unwrap_or(false) { "0" } else { "" } ), format!( "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB={}", if s.env_scrub.unwrap_or(false) { "1" } else { "0" } ), format!( "ENABLE_PROMPT_CACHING_1H={}", if s.prompt_caching_1h.unwrap_or(false) { "1" } else { "0" } ), ] } /// Build the settings.json payload for Claude Code, handed to the container as /// `CLAUDE_CODE_SETTINGS_JSON` and applied by `entrypoint.sh`. /// /// ## Every managed key is always present, and `null` means "delete" /// /// The settings file lives on `triple-c-claude-config-{projectId}`, a named /// volume that outlives the container, and the entrypoint *merges* into it. So /// a key emitted only when it is non-default can be written once and never /// taken back: turning the setting off simply omits the key, the merge /// preserves whatever was there, and the setting stays on forever. Only a /// destructive Reset — which also deletes the OAuth login, skills and /// transcripts — ever cleared it. Four of the six keys here were sticky that /// way; the `sandbox` block already carried the workaround and the comment /// explaining it, and this is the same treatment applied to the rest. /// /// Two shapes of "off" are needed, because Claude Code's own defaults differ: /// /// * **A boolean with a documented default** (`autoScrollEnabled` is `true`, /// `showThinkingSummaries` is `false`) is emitted with that neutral value. /// * **A key whose neutral state is *unset*** (`tui`, `effortLevel`, /// `viewMode`, `awaySummaryEnabled`) is emitted as JSON `null`, and the /// entrypoint deletes rather than merges those. Writing a stand-in value /// would not be neutral: an unset `tui` lets Claude Code choose the renderer /// (`"default"` pins the classic one), and an unset `viewMode` lets the /// user's own sticky `/focus` choice and `verbose` setting apply /// (`"default"` overrides both). /// /// Returns a `String` rather than an `Option`: there is no longer any /// input for which this produces nothing to say. fn build_claude_code_settings_json( settings: Option<&ClaudeCodeSettings>, sandbox_enabled: bool, ) -> String { let owned; let s = match settings { Some(s) => s, // No struct at all is not "say nothing" — it is "every setting is at // its default", which still has to be asserted over a stale file. None => { owned = ClaudeCodeSettings::default(); &owned } }; let mut map = serde_json::Map::new(); // `null` clears; see the module doc above. map.insert( "tui".to_string(), match s.tui_mode { Some(ref tui) => serde_json::json!(tui), None => serde_json::Value::Null, }, ); // `effortLevel`, not `effort`. Claude Code has never read a key called // `effort`, so the previous value was written and silently ignored. map.insert( "effortLevel".to_string(), match s.effort { Some(ref effort) => serde_json::json!(effort), None => serde_json::Value::Null, }, ); // Documented default `true`, so the neutral value is a value. map.insert( "autoScrollEnabled".to_string(), serde_json::json!(!s.auto_scroll_disabled.unwrap_or(false)), ); // Documented default `false`. map.insert( "showThinkingSummaries".to_string(), serde_json::json!(s.show_thinking_summaries.unwrap_or(false)), ); // `viewMode: "focus"` is the real setting behind what the UI calls focus // mode — "collapses tool output to one-line summaries" is that key's // documented behaviour. The `focusMode` key it replaces was invented and // did nothing. map.insert( "viewMode".to_string(), if s.focus_mode.unwrap_or(false) { serde_json::json!("focus") } else { serde_json::Value::Null }, ); // The recap is on by default, so only the *off* case has anything to write. // `CLAUDE_CODE_ENABLE_AWAY_SUMMARY` (set unconditionally at creation) takes // precedence over this key and is what actually enforces the choice; this // is here so the container's settings.json does not contradict it. map.insert( "awaySummaryEnabled".to_string(), if s.session_recap_disabled.unwrap_or(false) { serde_json::json!(false) } else { serde_json::Value::Null }, ); // Always emit `sandbox.enabled` so that toggling the per-project sandbox // off in triple-c clears any prior on-state in the persisted // settings.json (which lives in a named volume that survives recreation). // Inside a Docker container we can't rely on privileged user namespaces, // so `enableWeakerNestedSandbox` is required when sandbox is on. let sandbox_obj = if sandbox_enabled { serde_json::json!({ "enabled": true, "enableWeakerNestedSandbox": true, "allowUnsandboxedCommands": false, }) } else { serde_json::json!({ "enabled": false }) }; map.insert("sandbox".to_string(), sandbox_obj); serde_json::Value::Object(map).to_string() } /// Split the managed payload into the half that is safe to merge anywhere and /// the list of keys to delete. /// /// The null-means-delete convention is only understood by the `entrypoint.sh` /// shipped alongside this code — and an existing project recreates from *its /// own snapshot image*, which carries whatever entrypoint it was built with. An /// older one merges with a plain `.[0] * .[1]`, which would write the literal /// `null`s straight into the user's `settings.json` rather than clearing the /// keys. A settings file Claude Code then rejects would take the user's own /// `model`, `statusLine` and everything else in it down with it. /// /// So the nulls never leave Rust. `CLAUDE_CODE_SETTINGS_JSON` carries only real /// values and stays safe under either merge; `CLAUDE_CODE_SETTINGS_CLEAR` /// carries the key names to delete and is simply ignored by an entrypoint that /// predates it. Such a project keeps the old sticky behaviour until it is /// migrated or Reset — which is the pre-existing state, not a regression. pub(crate) fn split_claude_code_settings_payload(payload: &str) -> (String, String) { let parsed: serde_json::Value = match serde_json::from_str(payload) { Ok(v) => v, // Not our business to fix; hand it through and let the merge fail loudly. Err(_) => return (payload.to_string(), "[]".to_string()), }; let Some(obj) = parsed.as_object() else { return (payload.to_string(), "[]".to_string()); }; let mut set = serde_json::Map::new(); let mut clear: Vec = Vec::new(); for (k, v) in obj { if v.is_null() { clear.push(serde_json::json!(k)); } else { set.insert(k.clone(), v.clone()); } } ( serde_json::Value::Object(set).to_string(), serde_json::Value::Array(clear).to_string(), ) } pub async fn find_existing_container(project: &Project) -> Result, String> { let docker = get_docker()?; let container_name = project.container_name(); let filters: HashMap> = HashMap::from([ ("name".to_string(), vec![container_name.clone()]), ]); let containers: Vec = docker .list_containers(Some(ListContainersOptions { all: true, filters, ..Default::default() })) .await .map_err(|e| format!("Failed to list containers: {}", e))?; // Match exact name (Docker prepends /) let expected = format!("/{}", container_name); for c in &containers { if let Some(names) = &c.names { if names.iter().any(|n| n == &expected) { return Ok(c.id.clone()); } } } Ok(None) } /// Extra creation inputs that only base-image migration cares about, kept in /// one struct so `create_container`'s already-long parameter list does not grow /// two more positional arguments that every ordinary call site would have to /// pass as `None`-ish placeholders. #[derive(Debug, Clone, Copy, Default)] pub struct CreateExtras<'a> { /// Extra labels merged in last, overriding anything computed here. /// Migration uses this to stamp `triple-c.migration-state=in-progress`. pub extra_labels: &'a [(&'a str, &'a str)], } /// Resolve the value for the `triple-c.base-image-id` label. /// /// This is the **image ID**, not a `RepoDigests` entry: a locally built image /// (`triple-c:latest`) and any custom image have no repo digest at all, so a /// digest-based lineage would be blank for exactly the users most likely to /// change their base. /// /// Two cases: /// * creating **from the base** — the base's own current `.Id`; /// * creating **from the project's snapshot** — carry forward whatever lineage /// the snapshot image already records, because a snapshot is a commit of a /// container that itself descended from some base. Committing propagates /// container labels onto the image (verified), which is what makes the /// carry-forward chain hold across every recreation. /// /// An empty string means "unknown" — a snapshot that predates this label. It is /// deliberately *not* the same as "stale"; see [`crate::models::ContainerStaleness::known`]. async fn resolve_base_image_id(image_name: &str, base_image_name: &str) -> String { if image_name == base_image_name { return super::migration::image_id(base_image_name) .await .ok() .flatten() .unwrap_or_default(); } super::migration::image_labels(image_name) .await .get(super::migration::LABEL_BASE_IMAGE_ID) .cloned() .unwrap_or_default() } /// The `/dev/net/tun` character device, as it is named on both sides. const TUN_DEVICE: &str = "/dev/net/tun"; /// The `HostConfig` fields "VPN support" contributes: `CapAdd`, `Devices`, /// `Sysctls` — in that order. type VpnHostConfigParts = ( Option>, Option>, Option>, ); /// The three host-config pieces a VPN client needs, or all-`None` when the /// project has not opted in. /// /// Returned as a triple rather than set inline so the exact shape is unit /// testable — a container is created once, by a very long async function, and a /// silently-dropped capability looks identical to a VPN server that is simply /// unreachable. /// /// All three are required together and each fails differently on its own: /// * **`CAP_NET_ADMIN`** — without it the client cannot create an interface or /// write a route. Docker's default bounding set grants `net_raw` but not /// `net_admin`, which is why a client can ping but never connect. /// * **`/dev/net/tun`** — the device is absent from a default container, so /// there is nothing to open even with the capability. It is passed through /// from the host rather than `mknod`-ed inside, so the kernel's `tun` module /// backs it. /// * **`net.ipv4.conf.all.src_valid_mark`** — WireGuard's own `wg-quick` sets /// this, and cannot from inside a container (`/proc/sys` is read-only), so /// its handshake packets are dropped by reverse-path filtering. Harmless for /// OpenVPN-based clients, so it is set unconditionally with the rest. /// /// What it costs, stated accurately: Docker does not enable user-namespace /// remapping by default, so this is a real `CAP_NET_ADMIN` in the *initial* /// user namespace and only the **network** namespace confines it. It cannot /// touch the host's interfaces, but within its own namespace it can set /// promiscuous mode and add arbitrary addresses, routes and NAT rules on the /// shared `docker0` L2 segment — which puts sibling containers (the LiteLLM /// gateway among them) within reach of ARP spoofing, and lets netlink trigger /// host-kernel module auto-loading. It is also enough to flush netfilter rules /// inside the container, so pair it with `sandbox_mode_enabled` advisedly. /// Hence opt-in, per project, rather than on for everyone. /// The env var `entrypoint.sh` installs and removes the `pia-vpn` skill from. /// /// **Emitted either way, never omitted.** `~/.claude` is a persisted volume, so /// turning the toggle off has to actively tell entrypoint to remove a skill an /// earlier run left there, and an absent variable cannot say that. It is also /// what stops a `=1` baked into a snapshot by `docker commit` from outliving /// the setting — the explicit `=0` overwrites it. /// /// Extracted for the same reason as [`vpn_host_config`]: the emitting code sits /// in a very long function where a dropped or inverted value is invisible, and /// `MISSION_CONTROL_ENABLED` twenty lines above shows the failure this avoids — /// it is pushed only when true, so a snapshot's baked `=1` survives the toggle /// going off. fn vpn_env_var(enabled: bool) -> String { format!("VPN_SUPPORT_ENABLED={}", u8::from(enabled)) } fn vpn_host_config(enabled: bool) -> VpnHostConfigParts { if !enabled { return (None, None, None); } let devices = vec![bollard::models::DeviceMapping { path_on_host: Some(TUN_DEVICE.to_string()), path_in_container: Some(TUN_DEVICE.to_string()), cgroup_permissions: Some("rwm".to_string()), }]; let sysctls = HashMap::from([( "net.ipv4.conf.all.src_valid_mark".to_string(), "1".to_string(), )]); ( Some(vec!["NET_ADMIN".to_string()]), Some(devices), Some(sysctls), ) } /// Turn the daemon's device-passthrough failure into an explanation. /// /// **This fires on `start`, not `create`.** Verified against Docker 29.7: /// `docker create --device /dev/does-not-exist` succeeds and prints an id; the /// device is only resolved when runc builds the container, so the failure lands /// on the *next* call. Sysctls validate at the same point. Anything that /// inspects only the create path will never see it — which is why both paths /// route through here and the tests exercise the start-side string. /// /// Unmapped, this reads as `Failed to start container: Docker responded with /// status code 500: error gathering device information while adding custom /// device "/dev/net/tun": no such file or directory` — a path the user will go /// looking for on the wrong machine, since with Docker Desktop the relevant /// host is the Linux VM rather than their own, and with nothing pointing back /// at the switch that caused it. /// /// Deliberately not gated on `vpn_support_enabled`: nothing else in Triple-C /// ever asks for a device, so an error naming `/dev/net/tun` can only have come /// from a container created with the switch on. That keeps the check usable /// from [`start_container`], which has a container id and no project. fn explain_container_failure(action: &str, err: &str) -> String { let device_missing = err.contains(TUN_DEVICE) && (err.contains("no such file or directory") || err.contains("No such file or directory") || err.contains("error gathering device information")); if device_missing { return format!( "Failed to {} container: the Docker host has no {} device, which \ \"VPN support\" requires. The host kernel needs the `tun` module \ loaded (on Docker Desktop that is the Linux VM, not your own \ machine). Turn VPN support off in Config → Runtime to start this \ project without it. Original error: {}", action, TUN_DEVICE, err ); } format!("Failed to {} container: {}", action, err) } /// One bind mount per stored project path, skipping the rows that cannot /// produce a usable one. /// /// Both halves of the filter are about data that is **already on disk**, which /// is why this is a silent skip and not a validation error. `project_commands` /// now refuses an empty `mount_name` or `host_path` on save, and the Workspace /// pane can no longer send a half-filled row — but neither of those reaches a /// record written before they existed, and the two failures such a record /// causes are not equally visible: /// /// * An empty `host_path` becomes `{"Target":"/workspace/x","Source":""}`, and /// the daemon answers `invalid mount config for type "bind": field Source /// must not be empty` for the whole create. The project cannot be started or /// recreated at all — it is bricked, and it stays bricked however carefully /// the next save is validated. Skipping the row lets it start again, minus a /// mount that was never going to work. /// * An empty `mount_name` targets `/workspace/` itself, mounting the row's /// host directory *over* the workspace volume. The daemon then creates the /// other rows' mount points inside the user's real folder, which is a /// directory tree appearing in their project from nowhere. /// /// Failing louder is the wrong instinct here: the loud version is the one that /// already happened, and it took the project down with it. See /// `project_commands.rs`'s `check_mount_name_stays_under_workspace` for the /// save-time half — deliberately still tolerant of an empty name there, since /// refusing it would re-brick every project holding a legacy row. fn project_path_mounts(paths: &[crate::models::project::ProjectPath]) -> Vec { paths .iter() // Trimmed, because a name of `" "` targets `/workspace/ ` and a source // of `" "` is a path the daemon will happily create at the filesystem // root — neither is what anyone typed on purpose. .filter(|pp| { let keep = !pp.mount_name.trim().is_empty() && !pp.host_path.trim().is_empty(); if !keep { // Silence here means a folder the user configured simply does // not appear in the container, with no error and no toast. // Skipping is still right — the alternative is a project that // cannot start — but it should leave a trace. log::warn!( "Skipping an unmountable project path row (host_path={:?}, mount_name={:?}): \ both are required. The project will start without it.", pp.host_path, pp.mount_name ); } keep }) .map(|pp| Mount { target: Some(format!("/workspace/{}", pp.mount_name)), source: Some(pp.host_path.clone()), typ: Some(MountTypeEnum::BIND), read_only: Some(false), ..Default::default() }) .collect() } pub async fn create_container( project: &Project, docker_socket_path: &str, image_name: &str, base_image_name: &str, extras: CreateExtras<'_>, aws_config_path: Option<&str>, global_aws: &GlobalAwsSettings, global_ollama: &GlobalOllamaSettings, global_llamacpp: &GlobalLlamaCppSettings, global_openai_compatible: &GlobalOpenAiCompatibleSettings, global_claude_instructions: Option<&str>, global_custom_env_vars: &[EnvVar], timezone: Option<&str>, global_claude_code_settings: Option<&ClaudeCodeSettings>, default_ssh_key_path: Option<&str>, default_ca_cert_path: Option<&str>, default_git_user_name: Option<&str>, default_git_user_email: Option<&str>, ) -> Result { let docker = get_docker()?; let container_name = project.container_name(); let mut env_vars: Vec = Vec::new(); // Tell CLI tools the terminal supports 24-bit RGB color env_vars.push("COLORTERM=truecolor".to_string()); // Pass host UID/GID so the entrypoint can remap the container user #[cfg(unix)] { let uid = std::process::Command::new("id").arg("-u").output(); let gid = std::process::Command::new("id").arg("-g").output(); if let Ok(out) = uid { if out.status.success() { let val = String::from_utf8_lossy(&out.stdout).trim().to_string(); if !val.is_empty() { log::debug!("Host UID detected: {}", val); env_vars.push(format!("HOST_UID={}", val)); } } else { log::debug!("Failed to detect host UID (exit code {:?})", out.status.code()); } } if let Ok(out) = gid { if out.status.success() { let val = String::from_utf8_lossy(&out.stdout).trim().to_string(); if !val.is_empty() { log::debug!("Host GID detected: {}", val); env_vars.push(format!("HOST_GID={}", val)); } } else { log::debug!("Failed to detect host GID (exit code {:?})", out.status.code()); } } } #[cfg(windows)] { log::debug!("Skipping HOST_UID/HOST_GID on Windows — Docker Desktop's Linux VM handles user mapping"); } if let Some(ref token) = project.git_token { env_vars.push(format!("GIT_TOKEN={}", token)); } // Per-project git user overrides global defaults let effective_git_name = project.git_user_name.as_deref().or(default_git_user_name); let effective_git_email = project.git_user_email.as_deref().or(default_git_user_email); if let Some(name) = effective_git_name { env_vars.push(format!("GIT_USER_NAME={}", name)); } if let Some(email) = effective_git_email { env_vars.push(format!("GIT_USER_EMAIL={}", email)); } // Bedrock configuration if project.backend == Backend::Bedrock { if let Some(ref bedrock) = project.bedrock_config { env_vars.push("CLAUDE_CODE_USE_BEDROCK=1".to_string()); // AWS region: per-project overrides global let region = if !bedrock.aws_region.is_empty() { Some(bedrock.aws_region.clone()) } else { global_aws.aws_region.clone() }; if let Some(ref r) = region { env_vars.push(format!("AWS_REGION={}", r)); } match bedrock.auth_method { BedrockAuthMethod::StaticCredentials => { // Static/session credentials are NOT injected as env vars. // They are written to ~/.aws/credentials by // sync_bedrock_credentials() on every container // start, so rotated/updated keys are picked up without a // full container recreation (and never get baked into the // snapshot image). The empty values set by the // MANAGED_AUTH_KEYS neutralization pass below are ignored by // the AWS SDK, which falls through to the credentials file. } BedrockAuthMethod::Profile => { // Per-project profile overrides global let profile = bedrock.aws_profile.as_ref() .or(global_aws.aws_profile.as_ref()); if let Some(p) = profile { env_vars.push(format!("AWS_PROFILE={}", p)); } env_vars.push("AWS_SSO_AUTH_REFRESH_CMD=triple-c-sso-refresh".to_string()); } BedrockAuthMethod::BearerToken => { if let Some(ref token) = bedrock.aws_bearer_token { env_vars.push(format!("AWS_BEARER_TOKEN_BEDROCK={}", token)); } } } if let Some(model) = resolve_with_global( bedrock.model_id.as_deref(), global_aws.default_model_id.as_deref(), ) { env_vars.push(format!("ANTHROPIC_MODEL={}", model)); } if bedrock.disable_prompt_caching { env_vars.push("DISABLE_PROMPT_CACHING=1".to_string()); } if let Some(ref tier) = bedrock.service_tier { let trimmed = tier.trim(); if !trimmed.is_empty() { env_vars.push(format!("ANTHROPIC_BEDROCK_SERVICE_TIER={}", trimmed)); } } } } // ── Custom-endpoint backends ───────────────────────────────────────────── // Ollama, llama.cpp and the OpenAI-Compatible gateway all point Claude Code // at a non-Anthropic server via ANTHROPIC_BASE_URL. Each resolves its model // id here; the model-alias vars are emitted once below, from // `alias_model` / `alias_haiku`, so the three backends cannot drift apart. let mut alias_model: Option = None; let mut alias_haiku: Option = None; // Ollama configuration if project.backend == Backend::Ollama { if let Some(ref ollama) = project.ollama_config { if let Some(url) = resolve_with_global( Some(&ollama.base_url), global_ollama.base_url.as_deref(), ) { env_vars.push(format!("ANTHROPIC_BASE_URL={}", url)); } env_vars.push("ANTHROPIC_AUTH_TOKEN=ollama".to_string()); if let Some(model) = resolve_with_global( ollama.model_id.as_deref(), global_ollama.default_model_id.as_deref(), ) { env_vars.push(format!("ANTHROPIC_MODEL={}", model)); alias_model = Some(model.to_string()); } alias_haiku = resolve_with_global( ollama.haiku_model_id.as_deref(), global_ollama.default_haiku_model_id.as_deref(), ) .map(str::to_string); } } // llama.cpp (llama-server) configuration if project.backend == Backend::LlamaCpp { if let Some(ref cfg) = project.llamacpp_config { if let Some(url) = resolve_with_global( Some(&cfg.base_url), global_llamacpp.base_url.as_deref(), ) { env_vars.push(format!("ANTHROPIC_BASE_URL={}", url)); } // llama-server only enforces an Authorization header when it was // started with `--api-key` (default: none), so the value here is // ignored in the common case. Claude Code still refuses to run // against a custom base URL with no credential at all, so a // placeholder is always sent — same trick as the Ollama branch // above, which sends the literal "ollama". env_vars.push("ANTHROPIC_AUTH_TOKEN=llama.cpp".to_string()); if let Some(model) = resolve_with_global( cfg.model_id.as_deref(), global_llamacpp.default_model_id.as_deref(), ) { env_vars.push(format!("ANTHROPIC_MODEL={}", model)); alias_model = Some(model.to_string()); } alias_haiku = resolve_with_global( cfg.haiku_model_id.as_deref(), global_llamacpp.default_haiku_model_id.as_deref(), ) .map(str::to_string); } } // OpenAI Compatible configuration if project.backend == Backend::OpenAiCompatible { if let Some(ref config) = project.openai_compatible_config { if let Some(url) = resolve_with_global( Some(&config.base_url), global_openai_compatible.base_url.as_deref(), ) { env_vars.push(format!("ANTHROPIC_BASE_URL={}", url)); } if let Some(ref key) = config.api_key { env_vars.push(format!("ANTHROPIC_AUTH_TOKEN={}", key)); } if let Some(model) = resolve_with_global( config.model_id.as_deref(), global_openai_compatible.default_model_id.as_deref(), ) { env_vars.push(format!("ANTHROPIC_MODEL={}", model)); alias_model = Some(model.to_string()); } alias_haiku = resolve_with_global( config.haiku_model_id.as_deref(), global_openai_compatible.default_haiku_model_id.as_deref(), ) .map(str::to_string); } } // Model aliases — the fix for background Claude Code calls against a local // server. Only for backends that talk to a custom endpoint: Anthropic and // Bedrock reach servers that really do host the Anthropic model ids, so // they keep Claude Code's own defaults. Anything not emitted here is // blanked by the MANAGED_AUTH_KEYS pass below, so switching *away* from a // custom endpoint clears the aliases out of the snapshot image too. if project.backend.uses_custom_endpoint() { for (key, value) in compute_model_aliases(alias_model.as_deref(), alias_haiku.as_deref()) { env_vars.push(format!("{}={}", key, value)); } } // Shared Claude Code OAuth token (Anthropic backend only, opt-out per // project). Injected *before* the neutralization pass below so that pass // sees it as already-set; when it is absent the pass actively blanks the // variable instead of leaving a stale one baked into the snapshot image. let shared_claude = shared_claude_auth(project); if let Some((ref token, _)) = shared_claude { env_vars.push(format!("{}={}", CLAUDE_OAUTH_TOKEN_ENV, token)); log::info!( "Injecting the shared Claude authentication token into the container for project {}", project.id ); } // ── Corporate CA certificates ─────────────────────────────────────────── // Resolved here (rather than down with the mounts) so the env vars land // *before* the neutralization pass below and are seen as already-set. // // A bad path is a hard error, not a warning: behind a TLS-terminating // proxy a container without the CA fails every HTTPS call — npm, pip, git, // and Claude Code's own API requests — each in its own confusing way. One // message naming the path is far kinder. // // The values are set here rather than exported by the entrypoint because a // terminal session is a `docker exec`, which sees the container's // configured env and nothing the entrypoint exported. Same lesson as // `$BROWSER` and the URL relay shim. let effective_ca_path = resolve_with_global(project.ca_cert_path.as_deref(), default_ca_cert_path); let resolved_ca = ca_certs::resolve(effective_ca_path)?; if let Some(ref ca) = resolved_ca { log::info!( "Mounting {} corporate CA certificate(s) from {} into project {}", ca.cert_files.len(), ca.host_path, project.id ); } for (key, value) in ca_certs::ca_env_vars(resolved_ca.as_ref()) { env_vars.push(format!("{}={}", key, value)); } // ── Neutralize stale backend auth env vars ────────────────────────────── // When a project switches backends (e.g. Bedrock → Anthropic) the container // is recreated *from a snapshot image* committed off the previous container, // and `docker commit` copies that container's full ENV into the image. So // any auth var set under the old backend (e.g. CLAUDE_CODE_USE_BEDROCK=1, // AWS_PROFILE, a model alias) survives in the image ENV and stays active // unless we explicitly override it at create time. // // This pass is about *staleness*, not secrecy. It fixes the container it is // building and does nothing to the image, so it is not — and never was — // a defence against a credential baked into a snapshot. That is // `commit_container_snapshot`'s job, via SECRET_ENV_KEYS. // Create-time env takes precedence over image ENV, so we set every managed // auth key the *current* backend did NOT set to an empty value, clearing the // stale baked-in one. const MANAGED_AUTH_KEYS: &[&str] = &[ "CLAUDE_CODE_USE_BEDROCK", "AWS_REGION", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_BEARER_TOKEN_BEDROCK", "AWS_SSO_AUTH_REFRESH_CMD", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_MODEL", "DISABLE_PROMPT_CACHING", "ANTHROPIC_BEDROCK_SERVICE_TIER", // Switching from a custom-endpoint backend to Anthropic or Bedrock must // *clear* the aliases, not merely stop setting them: a stale // ANTHROPIC_DEFAULT_HAIKU_MODEL baked into the snapshot image would // keep pointing background calls at a model id the new backend has // never heard of. ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL, ANTHROPIC_DEFAULT_FABLE_MODEL, // Revoking the shared token, opting a project out, or switching away // from the Anthropic backend must *clear* this, not merely stop setting // it — otherwise the value committed into the snapshot image keeps // authenticating the container with a credential the user removed. CLAUDE_OAUTH_TOKEN_ENV, ]; // Same reasoning for the CA vars — `ca_env_vars` already emits them empty // when no CA is configured, so this list is belt-and-braces for a snapshot // committed by a build that predates the feature. let managed_keys: Vec<&str> = MANAGED_AUTH_KEYS .iter() .copied() .chain(ca_certs::CA_ENV_KEYS.iter().copied()) .collect(); let already_set: std::collections::HashSet = env_vars .iter() .filter_map(|e| e.split('=').next().map(|k| k.to_string())) .collect(); for key in &managed_keys { if !already_set.contains(*key) { env_vars.push(format!("{}=", key)); } } // Custom environment variables (global + per-project, project overrides global for same key) let merged_env = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars); for env_var in &merged_env { let key = env_var.key.trim(); if key.is_empty() { continue; } if is_reserved_env_key(key) { log::warn!("Skipping reserved env var: {}", key); continue; } env_vars.push(format!("{}={}", key, env_var.value)); } let custom_env_fingerprint = compute_env_fingerprint(&merged_env); env_vars.push(format!("TRIPLE_C_CUSTOM_ENV={}", custom_env_fingerprint)); // Container timezone if let Some(tz) = timezone { if !tz.is_empty() { env_vars.push(format!("TZ={}", tz)); } } // Mission Control env var if project.mission_control_enabled { env_vars.push("MISSION_CONTROL_ENABLED=1".to_string()); } env_vars.push(vpn_env_var(project.vpn_support_enabled)); // Permission mode — read by triple-c-task-runner for scheduled (headless) // Claude Code runs. Interactive terminals get the flags directly instead. env_vars.push(format!( "TRIPLE_C_PERMISSION_MODE={}", project.effective_permission_mode().as_env_value() )); // Claude instructions (global + per-project, plus port mapping info + scheduler docs) let combined_instructions = build_claude_instructions( global_claude_instructions, project.claude_instructions.as_deref(), &project.port_mappings, project.mission_control_enabled, project.sandbox_mode_enabled, ); if let Some(ref instructions) = combined_instructions { env_vars.push(format!("CLAUDE_INSTRUCTIONS={}", instructions)); } // Claude Code settings (global + per-project merged) let merged_cc_settings = merge_claude_code_settings( global_claude_code_settings, project.claude_code_settings.as_ref(), ); // Env-var-based settings, read directly by Claude Code. Extracted and unit // tested for the `vpn_host_config` reason: a container is created once, by // a very long function, and a variable emitted with the wrong value here is // invisible until someone wonders why a switch does nothing. env_vars.extend(claude_code_env_vars(merged_cc_settings.as_ref())); // settings.json-based settings (applied by the entrypoint). Always emitted, // even with no `ClaudeCodeSettings` struct present: the payload asserts the // *whole* managed key set, so "no settings" still has to be stated over a // settings.json left behind on the config volume by a previous config. // Split so the payload is safe under an older entrypoint that has never // heard of the null-means-delete convention — see // `split_claude_code_settings_payload`. let (cc_settings_set, cc_settings_clear) = split_claude_code_settings_payload( &build_claude_code_settings_json(merged_cc_settings.as_ref(), project.sandbox_mode_enabled), ); env_vars.push(format!("CLAUDE_CODE_SETTINGS_JSON={}", cc_settings_set)); env_vars.push(format!("CLAUDE_CODE_SETTINGS_CLEAR={}", cc_settings_clear)); let mut mounts: Vec = Vec::new(); // Project directories -> /workspace/{mount_name} mounts.extend(project_path_mounts(&project.paths)); // Named volume for the entire home directory — preserves ~/.claude.json, // ~/.local (pip/npm globals), and any other user-level state across // container stop/start cycles. mounts.push(Mount { target: Some("/home/claude".to_string()), source: Some(home_volume_name(&project.id)), typ: Some(MountTypeEnum::VOLUME), read_only: Some(false), ..Default::default() }); // Named volume for claude config persistence — mounted as a nested volume // inside the home volume; Docker gives the more-specific mount precedence. mounts.push(Mount { target: Some("/home/claude/.claude".to_string()), source: Some(config_volume_name(&project.id)), typ: Some(MountTypeEnum::VOLUME), read_only: Some(false), ..Default::default() }); // SSH keys mount (read-only staging; entrypoint copies to ~/.ssh with correct perms) // Per-project ssh_key_path overrides global default_ssh_key_path let effective_ssh_path = project.ssh_key_path.as_deref().or(default_ssh_key_path); if let Some(ssh_path) = effective_ssh_path { mounts.push(Mount { target: Some("/tmp/.host-ssh".to_string()), source: Some(ssh_path.to_string()), typ: Some(MountTypeEnum::BIND), read_only: Some(true), ..Default::default() }); } // Corporate CA certificates mount (read-only staging; the entrypoint copies // them into /usr/local/share/ca-certificates with a `.crt` name and runs // update-ca-certificates). Mirrors /tmp/.host-ssh and /tmp/.host-aws. // // A directory mounts at /tmp/.host-ca; a single file mounts at // /tmp/.host-ca/.crt so the entrypoint always sees a directory and // the certificate keeps a recognisable name. Docker creates the parent. if let Some(ref ca) = resolved_ca { mounts.push(Mount { target: Some(ca.mount_target.clone()), source: Some(ca.host_path.clone()), typ: Some(MountTypeEnum::BIND), read_only: Some(true), ..Default::default() }); } // AWS config mount (read-only) // Mount if: Bedrock profile auth needs it, OR a global aws_config_path is set let should_mount_aws = if project.backend == Backend::Bedrock { if let Some(ref bedrock) = project.bedrock_config { bedrock.auth_method == BedrockAuthMethod::Profile } else { false } } else { false }; // For static-credential Bedrock, sync_bedrock_credentials() is the sole // owner of ~/.aws/credentials (it rewrites it on every start). Mounting the // host AWS dir would make the entrypoint's `rm -rf ~/.aws; cp -a` race that // write at startup, so we never mount it in that case — the static keys // (+ AWS_REGION env) are self-sufficient and don't need the host config. let is_bedrock_static = project.backend == Backend::Bedrock && project .bedrock_config .as_ref() .map(|b| b.auth_method == BedrockAuthMethod::StaticCredentials) .unwrap_or(false); if (should_mount_aws || aws_config_path.is_some()) && !is_bedrock_static { let aws_dir = aws_config_path .map(|p| std::path::PathBuf::from(p)) .or_else(|| dirs::home_dir().map(|h| h.join(".aws"))); if let Some(ref aws_path) = aws_dir { if aws_path.exists() { mounts.push(Mount { target: Some("/tmp/.host-aws".to_string()), source: Some(aws_path.to_string_lossy().to_string()), typ: Some(MountTypeEnum::BIND), read_only: Some(true), ..Default::default() }); } } } // Docker socket (if allowed) if project.allow_docker_access { // On Windows, the named pipe (//./pipe/docker_engine) cannot be // bind-mounted into a Linux container. Docker Desktop exposes the // daemon socket as /var/run/docker.sock for container mounts. let mount_source = if docker_socket_path == "//./pipe/docker_engine" { "/var/run/docker.sock".to_string() } else { docker_socket_path.to_string() }; mounts.push(Mount { target: Some("/var/run/docker.sock".to_string()), source: Some(mount_source), typ: Some(MountTypeEnum::BIND), read_only: Some(false), ..Default::default() }); } // Port mappings let mut exposed_ports: HashMap> = HashMap::new(); let mut port_bindings: HashMap>> = HashMap::new(); for pm in &project.port_mappings { let container_key = format!("{}/{}", pm.container_port, pm.protocol); exposed_ports.insert(container_key.clone(), HashMap::new()); port_bindings.insert( container_key, Some(vec![PortBinding { host_ip: Some("0.0.0.0".to_string()), host_port: Some(pm.host_port.to_string()), }]), ); } let mut labels = HashMap::new(); labels.insert(LABEL_MANAGED.to_string(), "true".to_string()); labels.insert("triple-c.project-id".to_string(), project.id.clone()); labels.insert("triple-c.project-name".to_string(), project.name.clone()); labels.insert("triple-c.backend".to_string(), format!("{:?}", project.backend)); labels.insert("triple-c.paths-fingerprint".to_string(), compute_paths_fingerprint(&project.paths)); labels.insert("triple-c.bedrock-fingerprint".to_string(), compute_bedrock_fingerprint(project, global_aws)); labels.insert("triple-c.ollama-fingerprint".to_string(), compute_ollama_fingerprint(project, global_ollama)); labels.insert("triple-c.llamacpp-fingerprint".to_string(), compute_llamacpp_fingerprint(project, global_llamacpp)); labels.insert("triple-c.openai-compatible-fingerprint".to_string(), compute_openai_compatible_fingerprint(project, global_openai_compatible)); labels.insert("triple-c.ports-fingerprint".to_string(), compute_ports_fingerprint(&project.port_mappings)); labels.insert("triple-c.image".to_string(), image_name.to_string()); labels.insert("triple-c.timezone".to_string(), timezone.unwrap_or("").to_string()); labels.insert("triple-c.mission-control".to_string(), project.mission_control_enabled.to_string()); // Capabilities, devices and sysctls are fixed at creation, so this is // container state and gets the label-and-compare treatment. Written // unconditionally (`false`, not omitted) because `docker commit` copies // container labels onto the snapshot image: a `true` stamped once would // otherwise ride that snapshot into every future container and make the // switch impossible to turn back off. labels.insert("triple-c.vpn-support".to_string(), project.vpn_support_enabled.to_string()); labels.insert("triple-c.permission-mode".to_string(), project.effective_permission_mode().as_env_value().to_string()); labels.insert("triple-c.custom-env-fingerprint".to_string(), custom_env_fingerprint.clone()); labels.insert("triple-c.claude-code-settings-fingerprint".to_string(), compute_claude_code_settings_fingerprint(merged_cc_settings.as_ref(), project.sandbox_mode_enabled)); labels.insert("triple-c.instructions-fingerprint".to_string(), combined_instructions.as_ref().map(|s| sha256_hex(s)).unwrap_or_default()); // Written unconditionally, even when empty — `container_needs_recreation` // is label-based and never diffs env or mounts, so without this a changed // CA path would silently do nothing until some unrelated setting forced a // rebuild. The fingerprint covers the certificate *bytes* as well as the // path, so swapping a rotated CA in at the same location is caught too. labels.insert("triple-c.ca-fingerprint".to_string(), ca_certs::compute_ca_fingerprint(effective_ca_path)); labels.insert("triple-c.git-user-name".to_string(), effective_git_name.unwrap_or_default().to_string()); labels.insert("triple-c.git-user-email".to_string(), effective_git_email.unwrap_or_default().to_string()); labels.insert("triple-c.git-token-hash".to_string(), project.git_token.as_ref().map(|t| sha256_hex(t)).unwrap_or_default()); // Rotation id, NOT the token and NOT a hash of it — labels are readable by // anything on the host via `docker inspect`. labels.insert("triple-c.claude-token-version".to_string(), shared_claude.as_ref().map(|(_, v)| v.clone()).unwrap_or_default()); // ── Base-image lineage ─────────────────────────────────────────────────── // `triple-c.create-image` is what this container was actually created // from — the snapshot when one exists, otherwise the configured base. It is // what `container_needs_recreation` compares against; the older // `triple-c.image` label recorded the same thing but was compared against // the container's *own* image, which is where it came from, so that check // was a tautology and never fired. `triple-c.image` is still written for // continuity with existing containers but is no longer compared. // // `triple-c.base-image-id` records the lineage — see `resolve_base_image_id`. // // All three (plus the migration marker) are written **unconditionally**, // even when empty. Docker merges an image's labels into a container's at // creation, and `docker commit` copies container labels onto the snapshot // image, so a value stamped once would otherwise ride the snapshot into // every future container forever. Writing the key explicitly overrides the // inherited one — the same defence MANAGED_AUTH_KEYS applies to env. labels.insert( super::migration::LABEL_CREATE_IMAGE.to_string(), image_name.to_string(), ); labels.insert( super::migration::LABEL_BASE_IMAGE_ID.to_string(), resolve_base_image_id(image_name, base_image_name).await, ); labels.insert( super::migration::LABEL_MIGRATION_STATE.to_string(), String::new(), ); // Same defence, applied to the legacy MCP shim — and here it fixes a real, // observed bug rather than pre-empting one. `container_needs_recreation` // recreates any container carrying a non-empty `triple-c.mcp-fingerprint`, // but nothing has written that label since the MCP feature was removed. It // survives only by *inheritance* from a snapshot image committed by an // older build (one such image was found on this host with a non-empty // value), and every recreation re-commits it — so the shim can never // terminate and the project is recreated on every single start. Writing it // explicitly empty makes the shim fire exactly once, which is what it was // always meant to do. labels.insert("triple-c.mcp-fingerprint".to_string(), String::new()); // Same defence, for the label `container/Dockerfile` now stamps on the base // image. Docker merges an image's labels into the container it creates, and // `docker commit` copies the container's labels onto the snapshot — so // without this line every project snapshot would inherit // `triple-c.base=true` from the base it descends from and claim to *be* a // base image. Writing it explicitly empty overrides the inherited value. labels.insert(LABEL_BASE.to_string(), String::new()); for (key, value) in extras.extra_labels { labels.insert((*key).to_string(), (*value).to_string()); } let (cap_add, devices, sysctls) = vpn_host_config(project.vpn_support_enabled); let host_config = HostConfig { mounts: Some(mounts), port_bindings: if port_bindings.is_empty() { None } else { Some(port_bindings) }, init: Some(true), log_config: Some(capped_log_config()), cap_add, devices, sysctls, ..Default::default() }; let working_dir = if project.paths.len() == 1 { format!("/workspace/{}", project.paths[0].mount_name) } else { "/workspace".to_string() }; let config = Config { image: Some(image_name.to_string()), hostname: Some("triple-c".to_string()), env: Some(env_vars), labels: Some(labels), working_dir: Some(working_dir), host_config: Some(host_config), exposed_ports: if exposed_ports.is_empty() { None } else { Some(exposed_ports) }, tty: Some(true), ..Default::default() }; let options = CreateContainerOptions { name: container_name, ..Default::default() }; let response = docker .create_container(Some(options), config) .await .map_err(|e| explain_container_failure("create", &e.to_string()))?; Ok(response.id) } /// The rotation policy every Triple-C container is created with. /// /// Without this a container inherits the daemon's `json-file` default, which /// has **no size limit at all** — `docker logs` for a container that has been /// up for weeks is a single file that grows until the disk does not have room /// for it. Triple-C containers are long-lived by design (stop/start, not /// create/destroy), and the entrypoint plus anything a session leaves running /// on stdout all land in that one file. /// /// 10 MiB × 3 keeps roughly the last 30 MiB, which is far more scrollback than /// anything reads, and bounds the worst case at 30 MiB per project instead of /// unbounded. /// /// **Deliberately not part of `container_needs_recreation`.** That check is /// label-based, so participating would mean a new `triple-c.*` label whose only /// effect is to recreate every existing project once — and a recreation costs a /// `docker commit`, i.e. a permanent multi-gigabyte layer, which is the very /// thing this whole change set exists to avoid. Containers pick the policy up /// on their next natural recreation instead; an existing container keeps its /// unbounded log until then, which is exactly the status quo. fn capped_log_config() -> bollard::models::HostConfigLogConfig { bollard::models::HostConfigLogConfig { typ: Some("json-file".to_string()), config: Some(HashMap::from([ ("max-size".to_string(), "10m".to_string()), ("max-file".to_string(), "3".to_string()), ])), } } pub async fn start_container(container_id: &str) -> Result<(), String> { let docker = get_docker()?; docker .start_container(container_id, None::>) .await .map_err(|e| explain_container_failure("start", &e.to_string())) } pub async fn stop_container(container_id: &str) -> Result<(), String> { let docker = get_docker()?; docker .stop_container( container_id, Some(StopContainerOptions { t: 10 }), ) .await .map_err(|e| format!("Failed to stop container: {}", e)) } pub async fn remove_container(container_id: &str) -> Result<(), String> { let docker = get_docker()?; log::info!( "Removing container {} (v=false: named volumes such as claude config are preserved)", container_id ); match docker .remove_container( container_id, Some(RemoveContainerOptions { v: false, // preserve named volumes (claude config) force: true, ..Default::default() }), ) .await { Ok(()) => Ok(()), // Already gone is the outcome this call wants, not a failure — a // caller retrying a leftover from a previous, partially-failed removal // (see `remove_project`) must not be told it failed forever just // because a *different* attempt already succeeded. Err(bollard::errors::Error::DockerResponseServerError { status_code: 404, .. }) => Ok(()), Err(e) => Err(format!("Failed to remove container: {}", e)), } } /// Return the snapshot image name for a project. pub fn get_snapshot_image_name(project: &Project) -> String { format!("triple-c-snapshot-{}:latest", project.id) } /// Name of the named volume mounted at `/home/claude`. /// /// Takes the id rather than the `Project` because the disk view runs this /// mapping backwards: it reads volume names off the daemon and has to decide /// which project — if any — each one belongs to. See [`HOME_VOLUME_PREFIX`]. pub fn home_volume_name(project_id: &str) -> String { format!("{}{}", HOME_VOLUME_PREFIX, project_id) } /// Name of the named volume mounted at `/home/claude/.claude`, nested inside /// the home volume. This is the one holding the OAuth credential, the plugins /// and every session transcript. pub fn config_volume_name(project_id: &str) -> String { format!("{}{}", CONFIG_VOLUME_PREFIX, project_id) } /// Prefix of [`home_volume_name`]. Split out because orphan detection scans the /// daemon's volume list for these prefixes and strips them back to a project id. pub const HOME_VOLUME_PREFIX: &str = "triple-c-home-"; /// Prefix of [`config_volume_name`]. See [`HOME_VOLUME_PREFIX`]. pub const CONFIG_VOLUME_PREFIX: &str = "triple-c-claude-config-"; /// Keep the container's `~/.aws/credentials` in sync with the project's Bedrock /// auth on every container start: /// - **Bedrock + static credentials**: (re)write `~/.aws/credentials` from the /// latest keychain values and drop a stale `~/.aws/config` left by a prior /// profile/SSO session, so rotated keys are picked up without recreating the /// container. /// - **Any other backend / auth method**: remove a stale `~/.aws/credentials` /// written by a previous static-credential session, so the secrets don't /// linger unused in the persistent home volume after switching away. /// /// Both cleanups are skipped when `/tmp/.host-aws` is mounted (a global /// `aws_config_path` is configured), since the entrypoint already refreshes /// `~/.aws` from the host on every start in that case. pub async fn sync_bedrock_credentials( container_id: &str, project: &Project, ) -> Result<(), String> { let static_bedrock = if project.backend == Backend::Bedrock { project .bedrock_config .as_ref() .filter(|b| b.auth_method == BedrockAuthMethod::StaticCredentials) } else { None }; let bedrock = match static_bedrock { Some(b) if b.aws_access_key_id.as_deref().is_some_and(|k| !k.is_empty()) => b, _ => { // Not static-credential Bedrock (or static selected but no key set): // remove a stale credentials file from a previous static session. if matches!(static_bedrock, Some(_)) { log::warn!("Bedrock static auth selected but no AWS access key id is set"); } let script = r#"if [ ! -d /tmp/.host-aws ]; then rm -f "$HOME/.aws/credentials"; fi"#; let cmd = vec!["sh".to_string(), "-c".to_string(), script.to_string()]; let env = vec!["HOME=/home/claude".to_string()]; if let Err(e) = crate::docker::exec::exec_oneshot_env(container_id, cmd, env).await { log::warn!( "Failed to clear stale AWS credentials in container {}: {}", container_id, e ); } return Ok(()); } }; let key_id = bedrock.aws_access_key_id.as_deref().unwrap_or(""); let secret = bedrock.aws_secret_access_key.as_deref().unwrap_or(""); // Pass secrets via the exec environment, then have the shell write them to // the file. This keeps them out of the process argv (visible via `ps`). let mut env = vec![ "HOME=/home/claude".to_string(), format!("TC_AWS_KEY_ID={}", key_id), format!("TC_AWS_SECRET={}", secret), ]; if let Some(token) = bedrock.aws_session_token.as_deref() { if !token.is_empty() { env.push(format!("TC_AWS_TOKEN={}", token)); } } // umask 077 + explicit chmod guarantees 0600. The session-token line is only // emitted when the variable is non-empty. // // We also remove a stale ~/.aws/config left over from a previous // profile/SSO session on this project (the home volume persists across // backend switches), so its sso_session/profile settings don't shadow the // static [default] credentials. This is skipped when /tmp/.host-aws is // mounted (a global aws_config_path is configured) — in that case the // entrypoint already refreshes ~/.aws from the host on every start and the // config is intentional. let script = r#"set -e umask 077 mkdir -p "$HOME/.aws" if [ ! -d /tmp/.host-aws ] && [ -f "$HOME/.aws/config" ]; then rm -f "$HOME/.aws/config" fi { printf '[default]\n' printf 'aws_access_key_id=%s\n' "$TC_AWS_KEY_ID" printf 'aws_secret_access_key=%s\n' "$TC_AWS_SECRET" if [ -n "${TC_AWS_TOKEN:-}" ]; then printf 'aws_session_token=%s\n' "$TC_AWS_TOKEN" fi } > "$HOME/.aws/credentials" chmod 600 "$HOME/.aws/credentials""#; let cmd = vec!["sh".to_string(), "-c".to_string(), script.to_string()]; let (output, exit_code) = crate::docker::exec::exec_oneshot_env_status(container_id, cmd, env) .await .map_err(|e| format!("Failed to write AWS credentials into container: {}", e))?; if exit_code != 0 { return Err(format!( "Writing AWS credentials into container failed (exit {}): {}", exit_code, output.trim() )); } log::info!("Wrote Bedrock static credentials into container {}", container_id); Ok(()) } /// Paths deleted from a container's writable layer immediately before /// [`commit_container_snapshot`] runs. /// /// ## Why this exists /// /// Every recreation commits the container, and a commit **stacks a new layer** /// on top of the previous snapshot — it never rewrites one. Deleting a file /// after it has been committed does not give the bytes back; it writes a /// whiteout entry and the original bytes stay in the layer below, forever. One /// project was measured carrying 14 stacked commit layers and ~5.1 GB above its /// base image, and 24 different conditions trigger a recreation, so changing a /// single settings field costs a multi-gigabyte layer that nothing can reclaim. /// /// The only moment the bytes are still free to drop is *before* the commit that /// captures them. Measured on one container's 4.48 GB pending writable layer: /// 3.0 GB of agent scratchpad under `/tmp/claude-*`, the drag-and-drop staging /// area (up to 256 MiB per dropped file, and nothing in the app ever removes /// one), one PNG per pasted image, and the apt lists/cache/logs left by every /// runtime `apt-get install` the browser-view installer and the Playwright /// healer run — none of which has an `apt-get clean` behind it. /// /// ## Why a hardcoded list and not a heuristic /// /// A snapshot is the user's system layer: their packages, their `/opt`, their /// `/var/lib/postgresql`. Nothing here may guess. Every entry is an absolute /// path anchored to a directory Triple-C or a package manager owns: /// /// * `/workspace/{mount_name}` subtrees are **host bind mounts** — the user's /// real project directories. No entry may ever reach one, which is why no /// pattern here starts with `/workspace`. /// * The only bind mounts under `/tmp` are `/tmp/.host-ca` and `/tmp/.host-aws` /// (both read-only). A leading-dot name is not matched by a shell glob, and /// none of these patterns share their prefix. /// * The apt entries keep their parent directory and remove only its contents /// (`lists/*`, `archives/*.deb`, `apt/*`); `apt-get` is unhappy when the /// directories themselves are missing. /// /// ## Why a safe-looking *pattern* is not enough (C1) /// /// The list used to be the whole of the defence, and that was wrong. These /// patterns are expanded by `/bin/sh` inside the container running as **root**, /// and for an entry ending `/*` the parent is a *path component*: both the glob /// expansion and the `rm -rf` that follows resolve it. The agent in the /// container has passwordless sudo, so anything able to run /// `ln -s /workspace/myproject /var/log/apt` turns the next commit into a /// recursive delete of the user's real files **on the host**. That was /// reproduced end to end against a live container — a bind mount emptied by a /// scrub whose path list named no `/workspace` anywhere. /// /// (The entries whose glob is in the last component are the benign case: there /// the *match* is the symlink, and `rm -rf -- link` unlinks the link and stops. /// The distinction is not one a reviewer should have to make per entry, so the /// script defends both alike.) /// /// So these entries are only half the contract. The other half is /// [`snapshot_scrub_script`], which validates the parent directory — not /// reached through a symlink, not on another filesystem, inside /// [`SCRUB_CONTAINMENT_PREFIXES`] — before it deletes anything inside it. That /// is also why every entry here must keep its glob in the **final component**: /// the parent has to be literal for the script to be able to check it at all. A /// test enforces it. /// /// A unit test also pins the list itself, because the blast radius of a wrong /// entry here is a user's data and the code that consumes it is a shell string. pub(crate) const SNAPSHOT_SCRUB_PATHS: &[&str] = &[ // Agent scratchpads. The user's global CLAUDE.md instructs every agent to // put temporary files under a scratchpad directory in /tmp, so this is // where a long-running project's writable layer actually goes. // // Not age-limited, and worth being explicit about why that is only *just* // safe: the scrub runs as root against a container that is still running, // so a live Claude Code session or a `triple-c-scheduler` task writing here // has its scratchpad pulled out from under it mid-write. Both callers stop // the container within a line or two — `start_project_container` in // `project_commands.rs` stops and removes it, `migrate_project_to_base` // stops it — so the process that would notice is about to be killed anyway. // That is a property of those two call sites and not of this entry: a third // caller scrubbing a container it means to keep running would be corrupting // a live session, and would need to age-limit this the way the two below // are. "/tmp/claude-*", // Files drag-dropped into a terminal, staged by // `commands/terminal_commands.rs` at up to 256 MiB each, and one PNG per // pasted image from the same module. Nothing else in the repo deletes // either, so leaving them out of this list restores unbounded growth — but // they are the user's *own* files, and often the only copy inside the // container of something handed to the agent seconds ago by a path that is // still sitting in the conversation. Scrubbing them unconditionally meant // "drop a file, change any of the 24 settings that trigger a recreation, // lose it silently". Both are therefore age-limited rather than removed — // see [`SCRUB_MIN_AGE_DAYS`]. "/tmp/triple-c-drops/*", "/tmp/clipboard_*.png", // Runtime apt debris. `browser_view/install.rs` and // `container/triple-c-playwright-heal` both run `apt-get install` inside a // live container without an `apt-get clean` after it. "/var/lib/apt/lists/*", "/var/cache/apt/archives/*.deb", "/var/log/apt/*", "/var/log/dpkg.log", ]; /// Entries of [`SNAPSHOT_SCRUB_PATHS`] that are only deleted once a match's own /// mtime is older than the given number of days. Anything not named here is /// deleted whenever it is present. /// /// Two weeks is chosen against the thing that goes wrong: a recreation can /// happen seconds after a drop, and no conversation is still quoting a path it /// was given a fortnight ago. It is a compromise, not a proof — the alternative /// of dropping these patterns entirely would be silent unbounded growth in a /// directory nothing else ever cleans. const SCRUB_MIN_AGE_DAYS: &[(&str, u32)] = &[ ("/tmp/triple-c-drops/*", 14), ("/tmp/clipboard_*.png", 14), ]; /// The only directory trees [`snapshot_scrub_script`] will operate in, checked /// against the *resolved* parent directory at run time inside the container. /// /// Deliberately **not** derived from [`SNAPSHOT_SCRUB_PATHS`]: it is the /// backstop for the case where that list is itself wrong. An entry added under /// `/workspace`, `/home/claude` or `/etc` fails this check and deletes nothing, /// however plausible it looked in review. const SCRUB_CONTAINMENT_PREFIXES: &[&str] = &["/tmp", "/var/log", "/var/lib/apt", "/var/cache/apt"]; /// Marker the scrub script prints so the byte total can be read back out of the /// exec's interleaved stdout/stderr. const SCRUB_MARKER: &str = "###TRIPLE-C-SCRUBBED "; /// Marker the scrub script prints **instead of** [`SCRUB_MARKER`] when it /// cannot run at all, followed by what was missing. /// /// H3: the script needs five external tools, the root filesystem's device id, /// and an `rm` that honours `--one-file-system` — seven prerequisites in all, /// and on a base image that has none of them where it looked it used to run its /// seven patterns, delete nothing, and print `###TRIPLE-C-SCRUBBED 0` — a /// number indistinguishable from an honest "there was nothing to take". A scrub /// that could not run must never read as one that ran, so it says so in a line /// the caller can tell apart, and prints no total at all. /// /// Deliberately **not** a prefix of [`SCRUB_MARKER`] and not prefixed by it, so /// `parse_scrub_total` can never mistake one for the other. const SCRUB_UNAVAILABLE_MARKER: &str = "###TRIPLE-C-SCRUB-UNAVAILABLE "; /// The external tools [`snapshot_scrub_script`] probes for before it will /// delete anything, in the order the probe names them. /// /// Named once rather than spelled into the script text, because /// [`parse_scrub_unavailable`] has to be able to tell a missing *tool* from the /// other two prerequisites — the root device id, and an `rm` that takes /// `--one-file-system` — so that the log line reads as a sentence rather than /// as a list with `root-device-id` wedged into it. const SCRUB_PREREQ_TOOLS: &[&str] = &["stat", "rm", "du", "cut", "find"]; /// Environment the scrub exec sets explicitly, rather than inheriting. /// /// The exec inherits the container's configured env, and a project's *custom* /// env vars are part of that: `is_reserved_env_key` reserves the `ANTHROPIC_`, /// `AWS_`, `GIT_`, `HOST_` and `TRIPLE_C_` families and a handful of exact /// names, none of which is `LD_PRELOAD`. So a custom env var naming a shared /// object inside the container's *persisted home volume* injects code into /// every tool the scrub runs — as **root**, since that is the user the exec is /// created as — and decides the answer to checks 3 and 4 without ever touching /// `PATH`. `docker commit` bakes env into the snapshot, so it rides along too. /// /// Blanking them in the exec closes that without breaking anything: nothing /// legitimate preloads into `/bin/sh`, `stat`, `du`, `cut`, `find` or `rm`, and /// this env applies to the scrub exec **only** — a terminal session, which is a /// different exec, is untouched. Verified against Engine 29.7 that a /// `docker exec -e LD_PRELOAD=` overrides a container-level `LD_PRELOAD`. /// /// `LD_LIBRARY_PATH` is here for the same reason as `LD_PRELOAD`: it is /// searched ahead of the cache for every `DT_NEEDED` library, so a planted /// `libselinux.so.1` is as good as a preload. /// /// M2: [`SCRUB_BOOTSTRAP`] now starts the shell that runs the script under /// `env -i`, so none of these three reaches the script's own tools whatever /// this list says. They are kept because they still reach the *two processes /// in front of it* — the `/bin/sh` that runs the bootstrap and the `env` it /// calls — and an `env` with a preload in it is an `env` that can hand its /// child any environment it likes. Blanking here and emptying there are the /// same defence applied at the two points it has to hold at. const SCRUB_EXEC_ENV: &[&str] = &["LD_PRELOAD=", "LD_AUDIT=", "LD_LIBRARY_PATH="]; /// The `/bin/sh -c` program that starts the real scrub, with /// [`snapshot_scrub_script`] passed to it as `$1` rather than spliced into it. /// /// ## Why the script is not simply the exec's command (M2) /// /// `docker exec` cannot *replace* a container's environment, only add to and /// override it — which is why [`SCRUB_EXEC_ENV`] works by naming keys. The env /// a project carries is therefore inherited by whatever shell the exec starts, /// and a shell reads more out of its environment than variables. /// /// `bash` imports **functions** from the environment: an env var named /// `BASH_FUNC_stat%%` becomes a shell function called `stat`. Function lookup /// happens *before* `PATH` is ever consulted, so resetting `PATH` does not /// touch it, and `command -v` reports a function as found — so a planted /// function passes the prerequisite probe and then answers the containment /// checks. Measured against `bash` 5.2 on `ubuntu:24.04`, an environment /// carrying `BASH_FUNC_stat%%` had `stat -c %d` return a constant of its /// choosing while `command -v stat` said the tool was present. /// /// Every in-shell answer to that was tried and measured, and each one is /// itself importable: `unset -f stat` is defeated by `BASH_FUNC_unset%%`, /// `command stat` by `BASH_FUNC_command%%`, and — this is what settles it — /// `[`, `test`, `pwd` and `cd` import just as readily, which is checks 0, 1 /// and 2 of the containment guarantee, not merely the tools. There is no /// subset of the script that can be written in shell and still be trusted /// inside a shell that has already imported the attacker's functions. /// /// So the script is not run by that shell. This bootstrap is, and everything /// it uses is either a reserved word (`case`, `esac`), a parameter expansion, /// or a command word containing a `/` — and `bash` refuses to import a /// function whose name contains a `/`, verified on the same image. It hands /// the script to a **second** `/bin/sh` started by `env -i`, which has no /// environment at all: no `BASH_FUNC_*`, no `LD_*`, no `ENV`/`BASH_ENV`, and /// no `PATH` but the one named here. The inner shell's builtins are its own /// again, and the script does not have to care what `/bin/sh` is. /// /// Measured on an `ubuntu:24.04` with `/bin/sh -> bash`, a project env var of /// `BASH_FUNC_stat%%=() { echo 1; }` set on the container the way a custom env /// var is, and a named volume mounted **at** the match `/tmp/claude-x` — the /// position checks 3 and 4 exist for: /// /// * `/bin/sh -c