From 2857b4ae7dcad97c3e22ed9d9b8dc3f6c8399589 Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Mon, 16 Nov 2026 09:57:07 -0800 Subject: [PATCH] feat(aws): optional LLM gateway sidecar A non-essential 'gateway' container runs the digest-pinned LiteLLM image next to the workspace (Q7): its secrets are exactly the three TRIPLEC_GATEWAY_* keys, the config uses os.environ/ references (no key in it), /bin/sh writes it to a 0600 file and execs LiteLLM on 127.0.0.1:4000. The workspace's ANTHROPIC_BASE_URL/AUTH_TOKEN point at it with a master key minted per task start; under copy-at-connect that token and the gateway keys stay in the secret (R1). Needs the OpenAI-compatible backend and a gateway model (validated on save, start and in the UI). Requests with the toggle off are unchanged. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 11 + app/src-tauri/src/aws/workspace.rs | 196 +++++++++++- app/src-tauri/src/aws/workspace/tests.rs | 288 +++++++++++++++++- .../src/commands/project_commands.rs | 63 +++- app/src-tauri/src/docker/gateway.rs | 38 ++- app/src-tauri/src/host/aws_host.rs | 60 +++- app/src-tauri/src/host/aws_host/connect.rs | 5 + app/src-tauri/src/host/aws_host/tests.rs | 76 +++++ .../projects/home/config/AwsConfig.test.tsx | 115 +++++++ .../projects/home/config/HostSection.tsx | 6 +- .../projects/home/config/ModelSection.tsx | 47 ++- app/src/lib/awsWorkspace.test.ts | 17 ++ app/src/lib/awsWorkspace.ts | 36 ++- 13 files changed, 930 insertions(+), 28 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5ffc248..1ab8a91 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -369,6 +369,17 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li (root-owned; the entrypoint's TERM hook reads it, and the idle watcher writes `idle` or `lifetime`) so the hook doesn't push twice; the marker is cleared if StopTask fails. Claude Code's sandbox is forced off in the generated settings (bubblewrap can't create namespaces on Fargate, verified live). + **LLM gateway sidecar** (`gateway_sidecar`, Q7): a second, `essential: false` container `gateway` + (`docker::gateway::registry_image_ref`, digest-pinned, amd64+arm64; `memoryReservation` 512; no + `environment`, no `dependsOn`) whose `secrets` are exactly `TRIPLEC_GATEWAY_{CONFIG,API_KEY,MASTER_KEY}` + — the workspace container gets every key but those. The config is `sidecar_config` (Docker's + `render_config` with `os.environ/…` key references, so it holds no key); `/bin/sh -c` writes it to a + 0600 `/tmp/litellm.yaml` and `exec`s LiteLLM on **127.0.0.1:4000** only (the image's own entrypoint + can't write a file). The master key is **random per task start** (the Docker gateway's never leaves + the machine); the payload overrides `ANTHROPIC_BASE_URL`/`ANTHROPIC_AUTH_TOKEN` with the sidecar's, + and under copy-at-connect that token stays in the secret too (R1; terminals don't override it). + Log streams: `/gateway/` (the tail reads `workspace` only). Needs the + OpenAI-compatible backend, a gateway model and ≥ 1 vCPU / 2 GiB; off = the request is unchanged. **Environments are OpenTofu modules** (`aws/terraform/{environment,user-onboard,permissions-boundary}`; spec D2–D10). `tofu_modules.rs` embeds them and is the **only** place the shared names are built (environment, `/triple-c/environments/` record, owner key — `sha256(":")`, diff --git a/app/src-tauri/src/aws/workspace.rs b/app/src-tauri/src/aws/workspace.rs index 1e54261..46e15bd 100644 --- a/app/src-tauri/src/aws/workspace.rs +++ b/app/src-tauri/src/aws/workspace.rs @@ -83,6 +83,23 @@ const KEY_MAX_LIFETIME: &str = "TRIPLEC_MAX_LIFETIME_MINUTES"; /// `connect` when the credentials are copied in at connect (Q2) and so are /// not in the secret; absent otherwise. const KEY_CREDENTIALS: &str = "TRIPLEC_CREDENTIALS"; +/// The gateway sidecar's three keys (Q7): its LiteLLM config (key-free, +/// `os.environ/…` references) and the two keys it references. Only the +/// `gateway` container gets them; under copy-at-connect they stay in the +/// secret all the same (R1: the sidecar starts before any connect). +const KEY_GATEWAY_CONFIG: &str = "TRIPLEC_GATEWAY_CONFIG"; +const KEY_GATEWAY_API_KEY: &str = crate::docker::gateway::SIDECAR_API_KEY_ENV; +const KEY_GATEWAY_MASTER_KEY: &str = crate::docker::gateway::SIDECAR_MASTER_KEY_ENV; +const GATEWAY_KEYS: [&str; 3] = [KEY_GATEWAY_API_KEY, KEY_GATEWAY_CONFIG, KEY_GATEWAY_MASTER_KEY]; +/// The sidecar container's name. +pub const GATEWAY_CONTAINER_NAME: &str = "gateway"; +/// Where the workspace reaches the sidecar: the task's shared loopback +/// (awsvpc), LiteLLM bound to 127.0.0.1 only. +pub const GATEWAY_SIDECAR_URL: &str = "http://127.0.0.1:4000"; +/// The sidecar's soft memory limit (MiB). +pub const GATEWAY_MEMORY_RESERVATION_MIB: i32 = 512; +/// Largest sidecar config, in bytes (the constraints' budget). +pub const MAX_GATEWAY_CONFIG_BYTES: usize = 8_192; /// Seconds ECS waits after SIGTERM before SIGKILL (Fargate allows 2–120). pub const STOP_TIMEOUT_SECS: i32 = 120; @@ -152,6 +169,57 @@ pub struct PayloadExtras<'a> { /// `connect`; the app copies them in after each connect instead. /// `None`: everything is in the secret (Secrets Manager delivery). pub connect_only: Option<&'a [String]>, + /// The LLM gateway sidecar (Q7), when the project runs it. + pub gateway: Option>, +} + +/// What the gateway sidecar's payload keys carry. The workspace's +/// `ANTHROPIC_AUTH_TOKEN` is `master_key` too. +#[derive(Clone, Copy)] +pub struct GatewayPayload<'a> { + /// `docker::gateway::sidecar_config`: no key in it. + pub config: &'a str, + /// The provider key (Settings → Model Gateway). + pub api_key: &'a str, + /// The sidecar's own LiteLLM master key. + pub master_key: &'a str, +} + +/// Keys never appear. +impl std::fmt::Debug for GatewayPayload<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GatewayPayload") + .field("config_bytes", &self.config.len()) + .finish_non_exhaustive() + } +} + +/// Why `project` can't run the gateway sidecar with `gateway` (Settings → +/// Model Gateway), or `None` when it can or doesn't ask to. It needs the +/// OpenAI-compatible backend (Claude Code then talks to the sidecar) and at +/// least one complete model row. +pub fn gateway_sidecar_problem( + project: &Project, + gateway: &crate::models::gateway_settings::GatewaySettings, +) -> Option { + if !project.aws.as_ref().is_some_and(|a| a.gateway_sidecar) { + return None; + } + if project.backend != crate::models::project::Backend::OpenAiCompatible { + return Some( + "The LLM gateway sidecar needs the OpenAI Compatible backend: choose it in the \ + project's Model section, or turn the sidecar off" + .into(), + ); + } + if gateway.valid_models().is_empty() { + return Some( + "The LLM gateway sidecar has no models to serve: add at least one in Settings → \ + Model Gateway (a name and a provider model id)" + .into(), + ); + } + None } /// `workspace_env`'s fingerprint of the custom variables' values. @@ -195,6 +263,9 @@ fn payload_map( KEY_SETUP_SCRIPT, KEY_MAX_LIFETIME, KEY_CREDENTIALS, + KEY_GATEWAY_CONFIG, + KEY_GATEWAY_API_KEY, + KEY_GATEWAY_MASTER_KEY, ]; let mut m = BTreeMap::new(); for (k, v) in env_pairs { @@ -245,7 +316,17 @@ fn payload_map( // so its `TRIPLEC_GATEWAY_*` keys are added as payload keys here and stay // in the secret even under copy-at-connect (the UI says so). They are // payload keys, not env pairs, so the credential filter above never - // touches them. + // touches them. The workspace's Claude Code talks to the sidecar: its + // base URL and token (the sidecar's master key) replace whatever the + // OpenAI-compatible settings say, and the token stays in the secret like + // the gateway's keys — scheduled jobs run before any connect too. + if let Some(g) = extras.gateway { + m.insert("ANTHROPIC_BASE_URL".into(), GATEWAY_SIDECAR_URL.into()); + m.insert("ANTHROPIC_AUTH_TOKEN".into(), g.master_key.into()); + m.insert(KEY_GATEWAY_CONFIG.into(), g.config.into()); + m.insert(KEY_GATEWAY_API_KEY.into(), g.api_key.into()); + m.insert(KEY_GATEWAY_MASTER_KEY.into(), g.master_key.into()); + } m.insert(KEY_REPOS.into(), json(&repos)); m.insert(KEY_WIP_PUSH.into(), if wip { "1" } else { "0" }.into()); if let Some(minutes) = idle { @@ -389,6 +470,9 @@ pub struct WorkspacePlan { /// The `/workspace` access point; used only when `storage` is EFS. pub workspace_access_point_id: Option, pub tags: Vec<(String, String)>, + /// The gateway sidecar's image (Q7) when the project runs it; `None` + /// leaves the request exactly as it was before the sidecar existed. + pub gateway_image: Option, } /// sha256 (hex) over the task definition `plan` produces, minus the label @@ -483,18 +567,12 @@ fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { .map(|(k, v)| KeyValuePair::builder().name(*k).value(*v).build()) .collect(), )) - .set_secrets(Some( - plan.secret_keys - .iter() - .map(|k| { - Secret::builder() - .name(k) - .value_from(format!("{}:{k}::", plan.secret_arn)) - .build() - .expect(BUILT) - }) - .collect(), - )) + // Everything but the sidecar's keys: the workspace has no use for the + // provider key (its token, the master key, is ANTHROPIC_AUTH_TOKEN). + .set_secrets(Some(secrets( + plan, + plan.secret_keys.iter().filter(|k| !GATEWAY_KEYS.contains(&k.as_str())), + ))) .health_check( HealthCheck::builder() .command("CMD-SHELL") @@ -568,6 +646,9 @@ fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { .map(|(k, v)| Tag::builder().key(k).value(v).build()) .collect(), )); + if let Some(image) = &plan.gateway_image { + req = req.container_definitions(gateway_container(plan, image)); + } for (name, (fs, ap)) in [(HOME_VOLUME, hybrid), (WORKSPACE_VOLUME, workspace)] .into_iter() .filter_map(|(n, v)| v.map(|v| (n, v))) @@ -577,6 +658,58 @@ fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { req.build().expect(BUILT) } +/// `secrets` entries for `keys`, each by `valueFrom: :::`. +fn secrets<'k>(plan: &WorkspacePlan, keys: impl Iterator) -> Vec { + keys.map(|k| { + Secret::builder() + .name(k) + .value_from(format!("{}:{k}::", plan.secret_arn)) + .build() + .expect("every required field is set") + }) + .collect() +} + +/// The sidecar's shell command: write the config to a root-only file, then +/// replace the shell with LiteLLM on the task's loopback only. The pinned +/// image's ENTRYPOINT (`docker/prod_entrypoint.sh`) only `exec`s `litellm` +/// with its arguments, so the entry point is replaced by its `/bin/sh` +/// (busybox; `printf` is a builtin, `litellm` is on PATH — checked against +/// the pinned digest). The config variable is unset before LiteLLM starts; +/// the two key variables stay, since the config references them. +pub const GATEWAY_COMMAND: &str = "umask 077 && printf '%s' \"$TRIPLEC_GATEWAY_CONFIG\" > \ + /tmp/litellm.yaml && unset TRIPLEC_GATEWAY_CONFIG && exec litellm --config \ + /tmp/litellm.yaml --host 127.0.0.1 --port 4000"; + +/// The non-essential `gateway` container (Q7): the pinned LiteLLM image, +/// exactly the three gateway keys as secrets and no `environment` (P1), the +/// same log group (its streams are `/gateway/`, apart from +/// the workspace's), 512 MiB reserved. Nothing waits on it: the workspace +/// starts, and stays up, whether or not the gateway does. +fn gateway_container(plan: &WorkspacePlan, image: &str) -> ContainerDefinition { + const BUILT: &str = "every required field is set"; + let keys: Vec = GATEWAY_KEYS.iter().map(|k| k.to_string()).collect(); + ContainerDefinition::builder() + .name(GATEWAY_CONTAINER_NAME) + .image(image) + .essential(false) + .memory_reservation(GATEWAY_MEMORY_RESERVATION_MIB) + .entry_point("/bin/sh") + .entry_point("-c") + .command(GATEWAY_COMMAND) + .set_secrets(Some(secrets(plan, keys.iter()))) + .log_configuration( + LogConfiguration::builder() + .log_driver(LogDriver::Awslogs) + .options("awslogs-group", &plan.log_group) + .options("awslogs-region", &plan.region) + .options("awslogs-stream-prefix", &plan.log_stream_prefix) + .build() + .expect(BUILT), + ) + .build() +} + /// An EFS volume through an access point, IAM-authorised, TLS in transit. fn efs_volume(name: &str, fs: &str, ap: &str) -> Volume { Volume::builder() @@ -782,6 +915,7 @@ pub async fn prepare_workspace( files: &[(String, Vec)], custom_env_keys: &[String], image: &str, + gateway: Option>, ) -> Result { let (Some(placement), Some(cfg)) = (project.aws_placement.as_ref(), project.aws.as_ref()) else { @@ -809,6 +943,30 @@ pub async fn prepare_workspace( if image.trim().is_empty() { return Err(other("No container image is set for AWS")); } + // The sidecar runs when the project asks for it, and only then. + let gateway = match (cfg.gateway_sidecar, gateway) { + (false, _) => None, + (true, None) => { + return Err(other("The LLM gateway sidecar's configuration was not prepared")) + } + (true, Some(g)) => { + if g.config.len() > MAX_GATEWAY_CONFIG_BYTES { + return Err(other(format!( + "The LLM gateway configuration is {} bytes; the sidecar's limit is {} \ + (fewer models in Settings → Model Gateway)", + g.config.len(), + MAX_GATEWAY_CONFIG_BYTES + ))); + } + if g.api_key.trim().is_empty() || g.master_key.trim().is_empty() { + return Err(other( + "The LLM gateway sidecar needs the provider API key: set it in Settings → \ + Model Gateway", + )); + } + Some(g) + } + }; let ok = owner_key(region, &who.user_id); let tags = workspace_tags(&who.user_id, &project.id, &env.name); @@ -826,6 +984,7 @@ pub async fn prepare_workspace( max_workspace_hours: env.max_workspace_hours, connect_only: (cfg.secrets_delivery == SecretsDelivery::CopyAtConnect) .then_some(custom_env_keys), + gateway, }, ) .map_err(other)?; @@ -932,6 +1091,7 @@ pub async fn prepare_workspace( access_point_id: access_point_id.clone(), workspace_access_point_id: workspace_access_point_id.clone(), tags, + gateway_image: gateway.map(|_| crate::docker::gateway::registry_image_ref()), }; let fingerprint = workspace_fingerprint(&plan); let task_definition_arn = @@ -989,11 +1149,19 @@ pub fn holds_credentials(old: &str, new: &BTreeMap, custom: &[St let Ok(old) = serde_json::from_str::>(old) else { return true; }; + // The gateway sidecar's token is its own random master key (R1 keeps it + // in the secret), not a credential of the user's. + let sidecar_token = |k: &str| { + k == "ANTHROPIC_AUTH_TOKEN" + && old.get(k).is_some_and(|v| Some(v) == old.get(KEY_GATEWAY_MASTER_KEY)) + }; old.keys().any(|k| { k == KEY_FILES || k == CUSTOM_ENV_FINGERPRINT - || is_credential_key(k, custom) + || (is_credential_key(k, custom) && !sidecar_token(k)) || (!k.starts_with("TRIPLEC_") && !new.contains_key(k)) + // The provider key, once the sidecar is off. + || (k == KEY_GATEWAY_API_KEY && !new.contains_key(k)) }) } diff --git a/app/src-tauri/src/aws/workspace/tests.rs b/app/src-tauri/src/aws/workspace/tests.rs index bea7399..c0670f6 100644 --- a/app/src-tauri/src/aws/workspace/tests.rs +++ b/app/src-tauri/src/aws/workspace/tests.rs @@ -101,6 +101,7 @@ fn sample_plan(storage: StorageMode) -> WorkspacePlan { workspace_access_point_id: (storage == StorageMode::Efs) .then(|| "fsap-4567efab".to_string()), tags: workspace_tags(USER, PROJECT_ID, "dev"), + gateway_image: None, } } @@ -954,7 +955,7 @@ async fn prepare( p: &Project, env: &[(String, String)], ) -> Result { - prepare_workspace(fake, &who(), &env_info(), p, env, &[], &[], IMAGE).await + prepare_workspace(fake, &who(), &env_info(), p, env, &[], &[], IMAGE, None).await } #[tokio::test] @@ -964,7 +965,7 @@ async fn prepare_puts_the_setup_script_and_the_environments_cap_in_the_secret() p.aws.as_mut().unwrap().setup_script = Some("sudo apt-get install -y jq".into()); let mut env = env_info(); env.max_workspace_hours = 12; - prepare_workspace(&fake, &who(), &env, &p, &[], &[], &[], IMAGE).await.unwrap(); + prepare_workspace(&fake, &who(), &env, &p, &[], &[], &[], IMAGE, None).await.unwrap(); let m = payload_map(&fake.secrets.lock().unwrap()[0].2); assert_eq!(m["TRIPLEC_SETUP_SCRIPT"], "sudo apt-get install -y jq"); assert_eq!(m["TRIPLEC_MAX_LIFETIME_MINUTES"], "720"); @@ -1388,6 +1389,7 @@ async fn files_travel_in_the_secret_only() { &files, &[], IMAGE, + None, ) .await .unwrap(); @@ -1627,7 +1629,7 @@ async fn prepare_leaves_the_credentials_out_of_a_copy_at_connect_secret() { p.aws.as_mut().unwrap().secrets_delivery = crate::models::project::SecretsDelivery::CopyAtConnect; let files = vec![("ssh/id_ed25519".to_string(), b"PRIVATE KEY".to_vec())]; let env = pairs(&[("GIT_TOKEN", "ghp_secret"), ("MINE", "x"), ("TZ", "UTC")]); - prepare_workspace(&fake, &who(), &env_info(), &p, &env, &files, &["MINE".to_string()], IMAGE) + prepare_workspace(&fake, &who(), &env_info(), &p, &env, &files, &["MINE".to_string()], IMAGE, None) .await .unwrap(); let m = payload_map(&fake.secrets.lock().unwrap()[0].2); @@ -1651,7 +1653,7 @@ async fn switching_to_copy_at_connect_replaces_a_secret_that_held_credentials() Some(r#"{"GIT_TOKEN":"ghp_old","TRIPLEC_AGENT_TOKEN":"t","TZ":"UTC"}"#.into()); *fake.pending_puts.lock().unwrap() = 2; // AWS still finishing the delete let env = pairs(&[("GIT_TOKEN", "ghp_new"), ("TZ", "UTC")]); - prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE) + prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) .await .unwrap(); assert_eq!(*fake.secret_reads.lock().unwrap(), 1, "read only once it exists"); @@ -1664,7 +1666,7 @@ async fn switching_to_copy_at_connect_replaces_a_secret_that_held_credentials() *fake.existing_secret.lock().unwrap() = Some( r#"{"TRIPLEC_AGENT_TOKEN":"t","TRIPLEC_CREDENTIALS":"connect","TZ":"UTC","TRIPLEC_REPOS":"[]"}"#.into(), ); - prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE) + prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) .await .unwrap(); assert!(fake.deleted_secrets.lock().unwrap().is_empty()); @@ -1673,7 +1675,7 @@ async fn switching_to_copy_at_connect_replaces_a_secret_that_held_credentials() // No secret yet (a first start): created, never read — a read of a // secret that doesn't exist may be refused — nothing deleted. let fake = Fake::onboarded(); - prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE) + prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) .await .unwrap(); assert_eq!(*fake.creates.lock().unwrap(), 1); @@ -1739,3 +1741,277 @@ fn a_copy_at_connect_payload_drops_the_custom_variables_fingerprint() { assert!(!with(Some(&custom)).contains_key("TRIPLE_C_CUSTOM_ENV")); assert_eq!(with(None)["TRIPLE_C_CUSTOM_ENV"], "63ce86"); } + +// ------------------------------------------------------- gateway sidecar (Q7) + +const GW_CONFIG: &str = "model_list: []\ngeneral_settings:\n master_key: \"os.environ/TRIPLEC_GATEWAY_MASTER_KEY\"\n"; + +fn gw() -> GatewayPayload<'static> { + GatewayPayload { config: GW_CONFIG, api_key: "sk-provider", master_key: "mk-sidecar" } +} + +fn sidecar_plan(storage: StorageMode) -> WorkspacePlan { + let mut p = sample_plan(storage); + p.secret_keys = vec![ + "ANTHROPIC_AUTH_TOKEN".into(), + "ANTHROPIC_BASE_URL".into(), + "GIT_TOKEN".into(), + "TRIPLEC_AGENT_TOKEN".into(), + "TRIPLEC_GATEWAY_API_KEY".into(), + "TRIPLEC_GATEWAY_CONFIG".into(), + "TRIPLEC_GATEWAY_MASTER_KEY".into(), + ]; + p.gateway_image = Some(crate::docker::gateway::registry_image_ref()); + p +} + +fn secret_names(c: &aws_sdk_ecs::types::ContainerDefinition) -> Vec { + c.secrets().iter().map(|s| s.name().to_string()).collect() +} + +#[test] +fn a_sidecar_request_has_a_non_essential_gateway_with_only_its_three_keys() { + let plan = sidecar_plan(StorageMode::Hybrid); + let req = task_definition_request(&plan); + let defs = req.container_definitions(); + assert_eq!(defs.len(), 2); + let (ws, gw) = (&defs[0], &defs[1]); + assert_eq!(ws.name(), Some("workspace")); + assert_eq!(ws.essential(), Some(true)); + // The workspace gets everything but the sidecar's keys. + assert_eq!( + secret_names(ws), + ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "GIT_TOKEN", "TRIPLEC_AGENT_TOKEN"] + ); + + assert_eq!(gw.name(), Some("gateway")); + assert_eq!(gw.essential(), Some(false)); + assert_eq!( + gw.image(), + Some("ghcr.io/berriai/litellm@sha256:37e2dafb088a7723beb998590682957386dfc83ffea1848486f8e0e5cfac0b06") + ); + assert_eq!(gw.memory_reservation(), Some(512)); + assert_eq!( + secret_names(gw), + ["TRIPLEC_GATEWAY_API_KEY", "TRIPLEC_GATEWAY_CONFIG", "TRIPLEC_GATEWAY_MASTER_KEY"] + ); + for s in gw.secrets() { + assert_eq!(s.value_from(), format!("{SECRET_ARN}:{}::", s.name())); + } + // P1: no project data in the definition — no environment at all. + assert!(gw.environment().is_empty()); + // Nothing waits on the gateway and it waits on nothing. + assert!(gw.depends_on().is_empty() && ws.depends_on().is_empty()); + assert!(gw.health_check().is_none()); + // The command: config to a root-only file, LiteLLM on loopback 4000. + assert_eq!(gw.entry_point(), ["/bin/sh", "-c"]); + assert_eq!(gw.command(), [GATEWAY_COMMAND]); + assert!(GATEWAY_COMMAND.contains("--host 127.0.0.1 --port 4000")); + assert!(GATEWAY_COMMAND.contains("> /tmp/litellm.yaml")); + assert!(GATEWAY_COMMAND.contains("--config /tmp/litellm.yaml")); + assert!(!GATEWAY_COMMAND.contains("0.0.0.0")); + assert_eq!( + GATEWAY_SIDECAR_URL, + format!("http://127.0.0.1:{}", crate::host::port_forwards::GATEWAY_SIDECAR_PORT) + ); + // Same log group and prefix: awslogs names its streams + // `/gateway/`, apart from the workspace's. + let opts = gw.log_configuration().unwrap().options().unwrap(); + assert_eq!(opts["awslogs-group"], plan.log_group); + assert_eq!(opts["awslogs-region"], plan.region); + assert_eq!(opts["awslogs-stream-prefix"], plan.log_stream_prefix); + // The fingerprint label rides on the workspace container, where + // `describe_task_definition` reads it. + assert!(ws.docker_labels().unwrap().contains_key(FINGERPRINT_LABEL)); +} + +#[test] +fn the_sidecar_changes_the_fingerprint_and_off_leaves_requests_as_they_were() { + for storage in [StorageMode::Ephemeral, StorageMode::Hybrid, StorageMode::Efs] { + let off = sample_plan(storage); + assert_eq!(task_definition_request(&off).container_definitions().len(), 1); + let mut on = off.clone(); + on.gateway_image = Some("img@sha256:x".into()); + assert_ne!(workspace_fingerprint(&on), workspace_fingerprint(&off)); + let mut other = on.clone(); + other.gateway_image = Some("img@sha256:y".into()); + assert_ne!(workspace_fingerprint(&on), workspace_fingerprint(&other)); + } + // (The pinned Hybrid/Ephemeral values are in + // `hybrid_and_ephemeral_requests_are_unchanged_by_efs_mode`.) +} + +#[test] +fn a_sidecar_payload_points_claude_code_at_it_and_carries_its_keys() { + let env = pairs(&[ + ("ANTHROPIC_BASE_URL", "http://host.docker.internal:4000"), + ("ANTHROPIC_AUTH_TOKEN", "sk-local"), + ("ANTHROPIC_MODEL", "gpt-5"), + ("GIT_TOKEN", "ghp"), + ]); + let repos = project(StorageMode::Hybrid).aws.unwrap().repos; + for connect in [false, true] { + let custom: Vec = Vec::new(); + let m = payload_map( + &project_secret_payload_with( + &env, + "tok", + &[], + &repos, + true, + None, + StorageMode::Hybrid, + PayloadExtras { + connect_only: connect.then_some(&custom[..]), + gateway: Some(gw()), + ..Default::default() + }, + ) + .unwrap(), + ); + assert_eq!(m["ANTHROPIC_BASE_URL"], "http://127.0.0.1:4000"); + // R1: the sidecar's token and keys stay, copy-at-connect or not. + assert_eq!(m["ANTHROPIC_AUTH_TOKEN"], "mk-sidecar", "connect={connect}"); + assert_eq!(m["TRIPLEC_GATEWAY_MASTER_KEY"], "mk-sidecar"); + assert_eq!(m["TRIPLEC_GATEWAY_API_KEY"], "sk-provider"); + assert_eq!(m["TRIPLEC_GATEWAY_CONFIG"], GW_CONFIG); + assert_eq!(m["ANTHROPIC_MODEL"], "gpt-5"); + // Other credentials still follow the delivery. + assert_eq!(m.contains_key("GIT_TOKEN"), !connect); + } + // Off: the env pairs as they are, no gateway key. + let m = payload_map( + &project_secret_payload_with(&env, "tok", &[], &repos, true, None, StorageMode::Hybrid, PayloadExtras::default()) + .unwrap(), + ); + assert_eq!(m["ANTHROPIC_BASE_URL"], "http://host.docker.internal:4000"); + assert_eq!(m["ANTHROPIC_AUTH_TOKEN"], "sk-local"); + assert!(!m.keys().any(|k| k.starts_with("TRIPLEC_GATEWAY_"))); +} + +#[test] +fn custom_env_cannot_forge_the_gateway_keys() { + let env = pairs(&[("TRIPLEC_GATEWAY_CONFIG", "evil"), ("TRIPLEC_GATEWAY_MASTER_KEY", "x")]); + let m = payload_map( + &project_secret_payload_with(&env, "t", &[], &[], true, None, StorageMode::Ephemeral, PayloadExtras::default()) + .unwrap(), + ); + assert!(!m.keys().any(|k| k.starts_with("TRIPLEC_GATEWAY_"))); +} + +#[test] +fn a_gateway_payloads_debug_shows_no_key() { + let shown = format!("{:?}", PayloadExtras { gateway: Some(gw()), ..Default::default() }); + assert!(!shown.contains("sk-provider") && !shown.contains("mk-sidecar"), "{shown}"); +} + +fn sidecar_project() -> Project { + let mut p = project(StorageMode::Ephemeral); + p.backend = crate::models::project::Backend::OpenAiCompatible; + p.aws.as_mut().unwrap().gateway_sidecar = true; + p +} + +#[tokio::test] +async fn prepare_registers_the_sidecar_only_when_the_project_runs_it() { + let fake = Fake::onboarded(); + let p = sidecar_project(); + prepare_workspace(&fake, &who(), &env_info(), &p, &[], &[], &[], IMAGE, Some(gw())) + .await + .unwrap(); + assert_eq!(fake.registered.lock().unwrap()[0].container_definitions().len(), 2); + let m = payload_map(&fake.secrets.lock().unwrap()[0].2); + assert_eq!(m["TRIPLEC_GATEWAY_API_KEY"], "sk-provider"); + + // Toggle off: a payload handed in anyway is ignored. + let fake = Fake::onboarded(); + prepare_workspace(&fake, &who(), &env_info(), &project(StorageMode::Ephemeral), &[], &[], &[], IMAGE, Some(gw())) + .await + .unwrap(); + assert_eq!(fake.registered.lock().unwrap()[0].container_definitions().len(), 1); + let m = payload_map(&fake.secrets.lock().unwrap()[0].2); + assert!(!m.keys().any(|k| k.starts_with("TRIPLEC_GATEWAY_"))); +} + +#[tokio::test] +async fn prepare_refuses_a_sidecar_without_its_payload_or_with_an_oversized_config() { + let fake = Fake::onboarded(); + let p = sidecar_project(); + let e = prepare_workspace(&fake, &who(), &env_info(), &p, &[], &[], &[], IMAGE, None) + .await + .unwrap_err(); + assert!(e.to_string().contains("gateway"), "{e}"); + let big = "x".repeat(MAX_GATEWAY_CONFIG_BYTES + 1); + let e = prepare_workspace( + &fake, + &who(), + &env_info(), + &p, + &[], + &[], + &[], + IMAGE, + Some(GatewayPayload { config: &big, ..gw() }), + ) + .await + .unwrap_err(); + assert!(e.to_string().contains("gateway configuration"), "{e}"); + let e = prepare_workspace( + &fake, + &who(), + &env_info(), + &p, + &[], + &[], + &[], + IMAGE, + Some(GatewayPayload { api_key: " ", ..gw() }), + ) + .await + .unwrap_err(); + assert!(e.to_string().contains("API key"), "{e}"); + assert_eq!(fake.writes(), 0); +} + +#[test] +fn the_sidecar_needs_the_openai_backend_and_a_gateway_model() { + use crate::models::gateway_settings::{GatewayModel, GatewaySettings}; + let models = GatewaySettings { + models: vec![GatewayModel { name: "gpt".into(), model_id: "gpt-5".into() }], + ..Default::default() + }; + let p = sidecar_project(); + assert_eq!(gateway_sidecar_problem(&p, &models), None); + assert!(gateway_sidecar_problem(&p, &GatewaySettings::default()) + .unwrap() + .contains("Settings → Model Gateway")); + let mut anthropic = p.clone(); + anthropic.backend = crate::models::project::Backend::Anthropic; + assert!(gateway_sidecar_problem(&anthropic, &models).unwrap().contains("OpenAI Compatible")); + // Off: nothing to say, whatever the backend. + anthropic.aws.as_mut().unwrap().gateway_sidecar = false; + assert_eq!(gateway_sidecar_problem(&anthropic, &GatewaySettings::default()), None); +} + +#[test] +fn the_sidecars_token_is_not_a_leftover_credential_but_a_dropped_provider_key_is() { + let new: BTreeMap = [ + ("ANTHROPIC_AUTH_TOKEN", "mk-new"), + ("TRIPLEC_GATEWAY_MASTER_KEY", "mk-new"), + ("TRIPLEC_GATEWAY_API_KEY", "sk"), + ("TRIPLEC_AGENT_TOKEN", "t"), + ] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let holds = |old: &str, new: &BTreeMap| holds_credentials(old, new, &[]); + // Last start's sidecar key (a different random one): not a credential. + let sidecar_old = r#"{"ANTHROPIC_AUTH_TOKEN":"mk-old","TRIPLEC_GATEWAY_MASTER_KEY":"mk-old","TRIPLEC_GATEWAY_API_KEY":"sk","TRIPLEC_AGENT_TOKEN":"t"}"#; + assert!(!holds(sidecar_old, &new)); + // A user's own token from a Secrets Manager period is. + assert!(holds(r#"{"ANTHROPIC_AUTH_TOKEN":"sk-user","TRIPLEC_AGENT_TOKEN":"t"}"#, &new)); + // Sidecar turned off: the provider key left in the secret counts. + let off: BTreeMap = + [("TRIPLEC_AGENT_TOKEN", "t")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + assert!(holds(sidecar_old, &off)); +} diff --git a/app/src-tauri/src/commands/project_commands.rs b/app/src-tauri/src/commands/project_commands.rs index 9d367e5..a1cd330 100644 --- a/app/src-tauri/src/commands/project_commands.rs +++ b/app/src-tauri/src/commands/project_commands.rs @@ -641,7 +641,9 @@ pub async fn add_project( aws: Option, state: State<'_, AppState>, ) -> Result { - let project = new_project(name, paths, host_id, aws_placement, aws, &state.settings_store.get().hosts)?; + let settings = state.settings_store.get(); + let project = new_project(name, paths, host_id, aws_placement, aws, &settings.hosts)?; + validate_gateway_sidecar_update(&Project::new(String::new(), Vec::new()), &project, &settings.gateway)?; // Nothing can have been blanked on a project that did not exist a line ago. store_secrets_for_project(&project, &[])?; state.projects_store.add(project) @@ -1123,7 +1125,11 @@ pub async fn update_project( // [`crate::models::validate_env_vars_update`]. crate::models::validate_env_vars_update(&stored.custom_env_vars, &project.custom_env_vars)?; - validate_aws_update(&stored, &project, &state.settings_store.get().hosts)?; + { + let settings = state.settings_store.get(); + validate_aws_update(&stored, &project, &settings.hosts)?; + validate_gateway_sidecar_update(&stored, &project, &settings.gateway)?; + } restore_store_owned_fields(&mut project, &stored); project.updated_at = chrono::Utc::now().to_rfc3339(); @@ -1206,6 +1212,26 @@ fn restore_store_owned_fields(project: &mut Project, stored: &Project) { } } +/// The LLM gateway sidecar (Q7) needs the OpenAI-compatible backend and a +/// model in Settings → Model Gateway. A save is refused when the sidecar is +/// on without that backend, or is being turned on with no gateway model; a +/// project that already runs it still saves after the models were removed +/// from Settings (its start says what is missing). +fn validate_gateway_sidecar_update( + stored: &Project, + project: &Project, + gateway: &crate::models::gateway_settings::GatewaySettings, +) -> Result<(), String> { + let Some(problem) = crate::aws::workspace::gateway_sidecar_problem(project, gateway) else { + return Ok(()); + }; + let was_on = stored.aws.as_ref().is_some_and(|a| a.gateway_sidecar); + if was_on && project.backend == crate::models::project::Backend::OpenAiCompatible { + return Ok(()); + } + Err(problem) +} + /// Checks an incoming save's host placement against what is stored and the /// configured connections. fn validate_aws_update( @@ -2807,6 +2833,39 @@ mod tests { p } + #[test] + fn the_gateway_sidecar_needs_the_openai_backend_and_a_gateway_model() { + use crate::models::gateway_settings::{GatewayModel, GatewaySettings}; + use crate::models::project::Backend; + let with_models = GatewaySettings { + models: vec![GatewayModel { name: "gpt".into(), model_id: "gpt-5".into() }], + ..Default::default() + }; + let half = GatewaySettings { + models: vec![GatewayModel { name: "gpt".into(), model_id: " ".into() }], + ..Default::default() + }; + let off = aws_project(); + let mut on = off.clone(); + on.aws.as_mut().unwrap().gateway_sidecar = true; + + // Wrong backend: always refused. + on.backend = Backend::Anthropic; + let e = validate_gateway_sidecar_update(&off, &on, &with_models).unwrap_err(); + assert!(e.contains("OpenAI Compatible"), "{e}"); + assert!(validate_gateway_sidecar_update(&on, &on, &with_models).is_err()); + + // Turning it on without a complete gateway model row: refused. + on.backend = Backend::OpenAiCompatible; + let e = validate_gateway_sidecar_update(&off, &on, &half).unwrap_err(); + assert!(e.contains("Model Gateway"), "{e}"); + assert!(validate_gateway_sidecar_update(&off, &on, &with_models).is_ok()); + // Already on: an unrelated save still goes through. + assert!(validate_gateway_sidecar_update(&on, &on, &half).is_ok()); + // Off: nothing to check. + assert!(validate_gateway_sidecar_update(&off, &off, &half).is_ok()); + } + #[test] fn a_stored_workspace_access_point_blocks_moving_the_host() { let hosts = vec![host("h1"), host("h2")]; diff --git a/app/src-tauri/src/docker/gateway.rs b/app/src-tauri/src/docker/gateway.rs index e5a118c..f4445eb 100644 --- a/app/src-tauri/src/docker/gateway.rs +++ b/app/src-tauri/src/docker/gateway.rs @@ -58,10 +58,30 @@ const GATEWAY_LITELLM_VERSION: &str = "v1.106.6"; const GATEWAY_REGISTRY_DIGEST: &str = "sha256:37e2dafb088a7723beb998590682957386dfc83ffea1848486f8e0e5cfac0b06"; -fn registry_image_ref() -> String { +/// The digest-pinned registry image. The AWS gateway sidecar runs it too +/// (`aws::workspace`); the index covers linux/amd64 and linux/arm64. +pub(crate) fn registry_image_ref() -> String { format!("{}@{}", GATEWAY_REGISTRY_REPO, GATEWAY_REGISTRY_DIGEST) } +/// The environment variables the AWS gateway sidecar gets its two keys in +/// (from the project secret). [`sidecar_config`] names them with LiteLLM's +/// `os.environ/` references, so the config itself holds no key. +pub(crate) const SIDECAR_API_KEY_ENV: &str = "TRIPLEC_GATEWAY_API_KEY"; +pub(crate) const SIDECAR_MASTER_KEY_ENV: &str = "TRIPLEC_GATEWAY_MASTER_KEY"; + +/// The LiteLLM config for the AWS gateway sidecar: [`render_config`]'s, with +/// the provider key and master key as `os.environ/…` references (LiteLLM +/// resolves both: `litellm_params.api_key` and `general_settings.master_key`). +/// Holds no secret, so it can be sized and shown in errors. +pub(crate) fn sidecar_config(settings: &GatewaySettings) -> String { + render_config( + settings, + &format!("os.environ/{SIDECAR_API_KEY_ENV}"), + &format!("os.environ/{SIDECAR_MASTER_KEY_ENV}"), + ) +} + /// Local builds are tagged with the pin plus a hash of the embedded build /// context (`triple-c-gateway:v1.106.6-1a2b3c4d`), never a floating tag. A /// build made by an app version with a different pin *or* a different @@ -1175,6 +1195,22 @@ mod tests { assert!(!render_config(&s, "k", "m").contains("api_base")); } + #[test] + fn sidecar_config_references_the_keys_and_holds_none() { + let yaml = sidecar_config(&settings()); + assert!(yaml.contains("api_key: \"os.environ/TRIPLEC_GATEWAY_API_KEY\"")); + assert!(yaml.contains("master_key: \"os.environ/TRIPLEC_GATEWAY_MASTER_KEY\"")); + // Otherwise exactly what Docker's gateway gets. + assert_eq!( + yaml, + render_config( + &settings(), + "os.environ/TRIPLEC_GATEWAY_API_KEY", + "os.environ/TRIPLEC_GATEWAY_MASTER_KEY" + ) + ); + } + #[test] fn yaml_str_escapes_injection_attempts() { let hostile = "a\"\nmaster_key: \"pwned"; diff --git a/app/src-tauri/src/host/aws_host.rs b/app/src-tauri/src/host/aws_host.rs index ffc6662..a4bf998 100644 --- a/app/src-tauri/src/host/aws_host.rs +++ b/app/src-tauri/src/host/aws_host.rs @@ -40,7 +40,10 @@ use crate::aws::tasks::{ use crate::aws::tofu_modules::{ environment_cluster_name, log_stream_prefix, owner_key, task_family, }; -use crate::aws::workspace::{prepare_workspace, SdkWorkspaceApi, WorkspaceApi}; +use crate::aws::workspace::{ + gateway_sidecar_problem, new_agent_token, prepare_workspace, GatewayPayload, SdkWorkspaceApi, + WorkspaceApi, +}; use crate::aws::{caller_identity, sdk_config, CallerIdentity}; use crate::docker::ca_certs::{container_cert_name, ResolvedCa}; use crate::models::app_settings::ImageSource; @@ -151,6 +154,55 @@ pub fn aws_env(project: &Project, settings: &AppSettings) -> Result, + master_key: zeroize::Zeroizing, +} + +impl SidecarSecrets { + pub fn payload(&self) -> GatewayPayload<'_> { + GatewayPayload { + config: &self.config, + api_key: &self.api_key, + master_key: &self.master_key, + } + } +} + +/// What the gateway sidecar needs for this start, or `None` when the project +/// doesn't run it. Refuses a project the sidecar can't serve +/// ([`gateway_sidecar_problem`]) and a missing provider key (`read_api_key`: +/// the keychain's, Settings → Model Gateway). The master key is new every +/// task start — only this task's sidecar and workspace know it — so the +/// Docker gateway's own master key never leaves this machine. +pub fn gateway_sidecar( + project: &Project, + settings: &AppSettings, + read_api_key: impl FnOnce() -> Result, String>, +) -> Result, String> { + if !project.aws.as_ref().is_some_and(|a| a.gateway_sidecar) { + return Ok(None); + } + if let Some(problem) = gateway_sidecar_problem(project, &settings.gateway) { + return Err(problem); + } + let api_key = read_api_key()? + .filter(|k| !k.trim().is_empty()) + .ok_or_else(|| { + "The LLM gateway sidecar needs the provider API key: set it in Settings → Model \ + Gateway" + .to_string() + })?; + Ok(Some(SidecarSecrets { + config: crate::docker::gateway::sidecar_config(&settings.gateway), + api_key: zeroize::Zeroizing::new(api_key), + master_key: zeroize::Zeroizing::new(new_agent_token()), + })) +} + /// One file read for the secret, refusing anything over [`MAX_FILE_BYTES`] /// (enforced on the bytes read, not on a size the file could change after). fn read_capped(path: &Path, shown: &str) -> Result, String> { @@ -353,6 +405,9 @@ pub struct StartInputs<'a> { /// The custom variables' names: credentials under copy-at-connect. pub custom_env_keys: &'a [String], pub image: &'a str, + /// The gateway sidecar's payload, when the project runs it + /// ([`gateway_sidecar`]). + pub gateway: Option>, pub wait: WaitTiming, pub access_point_wait: PollTiming, /// Called as soon as the project has a task (found, or RunTask @@ -471,6 +526,7 @@ pub async fn start_core Vec<(String, Se let pairs = crate::docker::workspace_env::workspace_env_with_ca(project, settings, None); let custom = crate::docker::workspace_env::custom_env_keys(project, &settings.global_custom_env_vars); + // With the gateway sidecar, the task's own ANTHROPIC_AUTH_TOKEN (the + // sidecar's master key, kept in the secret) is the right one; the + // OpenAI-compatible key would override it with one the sidecar refuses. + let sidecar = project.aws.as_ref().is_some_and(|a| a.gateway_sidecar); credential_pairs(&pairs, &custom) .into_iter() + .filter(|(k, _)| !(sidecar && k == "ANTHROPIC_AUTH_TOKEN")) .map(|(k, v)| (k, Zeroizing::new(v))) .collect() } diff --git a/app/src-tauri/src/host/aws_host/tests.rs b/app/src-tauri/src/host/aws_host/tests.rs index d5a3c04..908c6dd 100644 --- a/app/src-tauri/src/host/aws_host/tests.rs +++ b/app/src-tauri/src/host/aws_host/tests.rs @@ -275,6 +275,7 @@ fn inputs<'a>( files: &[], custom_env_keys: &[], image: REGISTRY_IMAGE, + gateway: None, wait: WaitTiming { interval: Duration::from_millis(1), timeout: Duration::from_millis(30), @@ -1131,4 +1132,79 @@ mod copy_at_connect { // No tunnel registered for it: nothing to push to. assert!(!spawn_connect_push(&p, &AppSettings::default(), |_| panic!("no tunnel"))); } + #[test] + fn a_sidecar_terminal_keeps_the_tasks_own_token() { + use crate::models::project::{Backend, OpenAiCompatibleConfig}; + let mut p = connect_project(SecretsDelivery::CopyAtConnect); + p.backend = Backend::OpenAiCompatible; + p.openai_compatible_config = Some(OpenAiCompatibleConfig { + base_url: "http://host.docker.internal:4000".into(), + api_key: Some("sk-local".into()), + model_id: Some("gpt".into()), + haiku_model_id: None, + }); + p.git_token = Some("ghp_tok".into()); + let settings = AppSettings::default(); + let keys = |p: &Project| -> Vec { + connect_env(p, &settings).into_iter().map(|(k, _)| k).collect() + }; + assert!(keys(&p).contains(&"ANTHROPIC_AUTH_TOKEN".to_string())); + p.aws.as_mut().unwrap().gateway_sidecar = true; + let with_sidecar = keys(&p); + assert!(!with_sidecar.contains(&"ANTHROPIC_AUTH_TOKEN".to_string()), "{with_sidecar:?}"); + assert!(with_sidecar.contains(&"GIT_TOKEN".to_string())); + } } + +// ──────────────────────────────────────────── gateway sidecar (Q7) + +mod gateway_sidecar_inputs { + use super::*; + use crate::models::gateway_settings::GatewayModel; + use crate::models::project::Backend; + + fn sidecar(on: bool) -> (Project, AppSettings) { + let mut p = aws_project(StorageMode::Ephemeral); + p.backend = Backend::OpenAiCompatible; + p.aws.as_mut().unwrap().gateway_sidecar = on; + let mut s = AppSettings::default(); + s.gateway.models = vec![GatewayModel { name: "gpt".into(), model_id: "gpt-5".into() }]; + (p, s) + } + + #[test] + fn off_reads_no_key() { + let (p, s) = sidecar(false); + assert!(gateway_sidecar(&p, &s, || panic!("no keychain read")).unwrap().is_none()); + } + + #[test] + fn on_renders_a_key_free_config_and_a_fresh_master_key_each_start() { + let (p, s) = sidecar(true); + let a = gateway_sidecar(&p, &s, || Ok(Some("sk-provider".into()))).unwrap().unwrap(); + let b = gateway_sidecar(&p, &s, || Ok(Some("sk-provider".into()))).unwrap().unwrap(); + let (pa, pb) = (a.payload(), b.payload()); + assert_eq!(pa.api_key, "sk-provider"); + assert!(!pa.config.contains("sk-provider") && !pa.config.contains(pa.master_key)); + assert!(pa.config.contains("os.environ/TRIPLEC_GATEWAY_API_KEY")); + assert!(pa.config.contains("model: \"openai/gpt-5\"")); + assert_eq!(pa.master_key.len(), 64); + assert_ne!(pa.master_key, pb.master_key); + } + + #[test] + fn on_refuses_a_missing_key_backend_or_model() { + let (p, s) = sidecar(true); + for key in [None, Some(" ".to_string())] { + let e = gateway_sidecar(&p, &s, || Ok(key.clone())).err().unwrap(); + assert!(e.contains("provider API key"), "{e}"); + } + let mut wrong = p.clone(); + wrong.backend = Backend::Anthropic; + assert!(gateway_sidecar(&wrong, &s, || Ok(Some("k".into()))).err().unwrap().contains("OpenAI Compatible")); + let mut empty = s.clone(); + empty.gateway.models.clear(); + assert!(gateway_sidecar(&p, &empty, || Ok(Some("k".into()))).err().unwrap().contains("Model Gateway")); + } +} + diff --git a/app/src/components/projects/home/config/AwsConfig.test.tsx b/app/src/components/projects/home/config/AwsConfig.test.tsx index e8875cf..c4f4b8e 100644 --- a/app/src/components/projects/home/config/AwsConfig.test.tsx +++ b/app/src/components/projects/home/config/AwsConfig.test.tsx @@ -113,10 +113,125 @@ describe("AWS project config", () => { }); }); +describe("LLM gateway sidecar (ModelSection)", () => { + const SIDECAR = "Run Triple-C's LLM gateway in the workspace"; + const withModels = (models: { name: string; model_id: string }[]) => + useAppState.setState({ + appSettings: { gateway: { enabled: false, port: 4000, models } } as unknown as AppSettings, + }); + const oai = (over: Partial = {}) => + awsProject({ + backend: "open_ai_compatible", + openai_compatible_config: { + base_url: "http://host.docker.internal:4000", + api_key: null, + model_id: "gpt", + haiku_model_id: null, + } as never, + ...over, + }); + const renderModel = (p: Project) => + render(); + + it("is offered only for an AWS project on the OpenAI-compatible backend", () => { + withModels([{ name: "gpt", model_id: "gpt-5" }]); + renderModel(awsProject({ backend: "ollama" })); + expect(screen.queryByRole("switch", { name: SIDECAR })).toBeNull(); + cleanup(); + render( + , + ); + expect(screen.queryByRole("switch", { name: SIDECAR })).toBeNull(); + useAppState.setState({ appSettings: null }); + }); + + it("turns on when Settings has a gateway model, and says why not otherwise", async () => { + withModels([{ name: " ", model_id: "gpt-5" }]); + renderModel(oai()); + expect(toggle(SIDECAR)).toBeDisabled(); + expect(screen.getByRole("alert")).toHaveTextContent("Settings → Model Gateway"); + cleanup(); + + withModels([{ name: "gpt", model_id: "gpt-5" }]); + renderModel(oai()); + expect(toggle(SIDECAR)).not.toBeDisabled(); + fireEvent.click(toggle(SIDECAR)); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0].aws.gateway_sidecar).toBe(true); + useAppState.setState({ appSettings: null }); + }); + + it("needs 1 vCPU and 2 GiB", () => { + withModels([{ name: "gpt", model_id: "gpt-5" }]); + const p = oai(); + p.aws = { ...p.aws!, cpu: 512, memory_mib: 1024 }; + renderModel(p); + expect(toggle(SIDECAR)).toBeDisabled(); + expect(screen.getByRole("alert")).toHaveTextContent("1 vCPU and 2 GiB"); + useAppState.setState({ appSettings: null }); + }); + + it("when on, replaces the local-endpoint warning and can always be turned off", async () => { + withModels([]); + const p = oai(); + p.aws = { ...p.aws!, gateway_sidecar: true }; + renderModel(p); + expect(screen.queryByText(/host.docker.internal is this machine/)).toBeNull(); + expect(screen.getByRole("note", { name: "LLM gateway sidecar" })).toHaveTextContent( + "http://127.0.0.1:4000", + ); + expect(toggle(SIDECAR)).toHaveAttribute("aria-checked", "true"); + expect(toggle(SIDECAR)).not.toBeDisabled(); + fireEvent.click(toggle(SIDECAR)); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0].aws.gateway_sidecar).toBe(false); + useAppState.setState({ appSettings: null }); + }); + + it("is turned off with the backend it needs", async () => { + withModels([{ name: "gpt", model_id: "gpt-5" }]); + const p = oai(); + p.aws = { ...p.aws!, gateway_sidecar: true }; + renderModel(p); + fireEvent.change(screen.getByLabelText("Backend"), { target: { value: "anthropic" } }); + await waitFor(() => expect(save).toHaveBeenCalled()); + expect(save.mock.calls[0][0]).toMatchObject({ backend: "anthropic", aws: { gateway_sidecar: false } }); + useAppState.setState({ appSettings: null }); + }); +}); + +function localProjectOai(): Project { + return localProject({ + backend: "open_ai_compatible", + openai_compatible_config: { + base_url: "http://host.docker.internal:4000", + api_key: null, + model_id: null, + haiku_model_id: null, + } as never, + }); +} + describe("HostSection", () => { const renderHost = (p: Project = awsProject(), disabled = false) => render(); + it("offers no CPU below 1 vCPU while the gateway sidecar is on", () => { + const p = awsProject(); + p.aws = { ...p.aws!, gateway_sidecar: true }; + renderHost(p); + const cpus = within(screen.getByLabelText("CPU")) + .getAllByRole("option") + .map((o) => (o as HTMLOptionElement).value); + expect(cpus).not.toContain("256"); + expect(cpus).not.toContain("512"); + expect(cpus).toContain("1024"); + }); + it("saves a CPU change with a memory size valid for it", async () => { renderHost(); // 1024 CPU / 4096 MiB fireEvent.change(screen.getByLabelText("CPU"), { target: { value: "256" } }); diff --git a/app/src/components/projects/home/config/HostSection.tsx b/app/src/components/projects/home/config/HostSection.tsx index 8861380..6614d8e 100644 --- a/app/src/components/projects/home/config/HostSection.tsx +++ b/app/src/components/projects/home/config/HostSection.tsx @@ -4,6 +4,7 @@ import * as commands from "../../../../lib/tauri-commands"; import { useAppState } from "../../../../store/appState"; import { COPY_AT_CONNECT_GATEWAY_NOTE, + GATEWAY_SIDECAR_MIN_CPU, COPY_AT_CONNECT_HINT, COPY_AT_CONNECT_SSH_NOTE, COPY_AT_CONNECT_WARNINGS, @@ -141,7 +142,10 @@ export default function HostSection({ project, save, disabled }: Props) { void saveAws({ cpu, memory_mib }); }} > - {FARGATE_CPUS.map((c) => ( + {FARGATE_CPUS.filter( + // The gateway sidecar needs 1 vCPU / 2 GiB (Rust validates it too). + (c) => !aws.gateway_sidecar || c >= GATEWAY_SIDECAR_MIN_CPU, + ).map((c) => ( diff --git a/app/src/components/projects/home/config/ModelSection.tsx b/app/src/components/projects/home/config/ModelSection.tsx index 832fdba..ff2469a 100644 --- a/app/src/components/projects/home/config/ModelSection.tsx +++ b/app/src/components/projects/home/config/ModelSection.tsx @@ -17,7 +17,14 @@ import Field, { selectClass, } from "../../../ui/Field"; import Toggle from "../../../ui/Toggle"; -import { isAwsProject, localEndpointProblem } from "../../../../lib/awsWorkspace"; +import { + GATEWAY_SIDECAR_HINT, + GATEWAY_SIDECAR_LABEL, + GATEWAY_SIDECAR_ON_NOTE, + gatewaySidecarProblem, + isAwsProject, + localEndpointProblem, +} from "../../../../lib/awsWorkspace"; import { useAppState } from "../../../../store/appState"; /** P6: an AWS workspace can reach a local model only over the network. */ @@ -201,6 +208,10 @@ export default function ModelSection({ project, save, disabled }: Props) { : project.backend === "open_ai_compatible" ? (project.openai_compatible_config ?? DEFAULT_OPENAI_COMPATIBLE_CONFIG).base_url : null; + // Q7: with the sidecar, Claude Code talks to the gateway in the task, so + // the typed base URL is not used on AWS and its warning would mislead. + const sidecarOn = aws && project.aws?.gateway_sidecar === true; + const sidecarProblem = aws ? gatewaySidecarProblem(project, gateway) : null; const endpointProblem = aws && savedBaseUrl ? localEndpointProblem(savedBaseUrl, gateway?.enabled ? gateway.port : null) @@ -208,6 +219,9 @@ export default function ModelSection({ project, save, disabled }: Props) { const handleBackendChange = (mode: Backend) => { const patch: Partial = { backend: mode }; + // The sidecar needs this backend: leaving it turns the sidecar off. + if (sidecarOn && mode !== "open_ai_compatible" && project.aws) + patch.aws = { ...project.aws, gateway_sidecar: false }; if (mode === "bedrock" && !project.bedrock_config) patch.bedrock_config = DEFAULT_BEDROCK_CONFIG; if (mode === "ollama" && !project.ollama_config) @@ -241,7 +255,7 @@ export default function ModelSection({ project, save, disabled }: Props) { )} - {aws && CUSTOM_ENDPOINT_BACKENDS.includes(project.backend) && ( + {aws && CUSTOM_ENDPOINT_BACKENDS.includes(project.backend) && !sidecarOn && (
{endpointProblem}

}
)} + {aws && project.backend === "open_ai_compatible" && project.aws && ( +
+ + save({ aws: { ...project.aws!, gateway_sidecar: value } }) + } + // Turning it off is always allowed; on only when it can run. + disabled={disabled || (!sidecarOn && sidecarProblem !== null)} + /> + } + /> + {sidecarProblem && ( +

+ {sidecarProblem} +

+ )} + {sidecarOn && ( +

+ {GATEWAY_SIDECAR_ON_NOTE} +

+ )} +
+ )} {/* Only Anthropic reads CLAUDE_CODE_OAUTH_TOKEN; the other backends authenticate through their own credentials entirely. */} diff --git a/app/src/lib/awsWorkspace.test.ts b/app/src/lib/awsWorkspace.test.ts index 93c04a5..654eeb0 100644 --- a/app/src/lib/awsWorkspace.test.ts +++ b/app/src/lib/awsWorkspace.test.ts @@ -5,6 +5,7 @@ import { hasSavedFiles, hasWorkspaceFiles, environmentSelectable, + gatewaySidecarProblem, memoryError, memoryOptions, nearestMemory, @@ -88,3 +89,19 @@ describe("phase 6 settings", () => { expect(hasWorkspaceFiles({ aws: null })).toBe(false); }); }); + +describe("gatewaySidecarProblem", () => { + const models = { models: [{ name: "gpt", model_id: "gpt-5" }] }; + const aws = defaultAwsWorkspace(); + it("needs the OpenAI-compatible backend, a complete model and 1 vCPU / 2 GiB", () => { + expect(gatewaySidecarProblem({ backend: "open_ai_compatible", aws }, models)).toBeNull(); + expect(gatewaySidecarProblem({ backend: "anthropic", aws }, models)).toMatch(/OpenAI Compatible/); + expect(gatewaySidecarProblem({ backend: "open_ai_compatible", aws }, null)).toMatch(/Model Gateway/); + expect( + gatewaySidecarProblem({ backend: "open_ai_compatible", aws }, { models: [{ name: "gpt", model_id: " " }] }), + ).toMatch(/Model Gateway/); + expect( + gatewaySidecarProblem({ backend: "open_ai_compatible", aws: { ...aws, cpu: 512, memory_mib: 2048 } }, models), + ).toMatch(/1 vCPU and 2 GiB/); + }); +}); diff --git a/app/src/lib/awsWorkspace.ts b/app/src/lib/awsWorkspace.ts index 4101de4..a6329f6 100644 --- a/app/src/lib/awsWorkspace.ts +++ b/app/src/lib/awsWorkspace.ts @@ -1,6 +1,7 @@ import type { AwsWorkspaceConfig, DetectedEnvironment, + GatewaySettings, Project, RepoSource, UnsavedWork, @@ -152,7 +153,40 @@ export const COPY_AT_CONNECT_WARNINGS = [ export const COPY_AT_CONNECT_SSH_NOTE = "~/.ssh is not kept on EFS: SSH keys copied in, or made in the workspace, are gone when it stops. Keys an earlier start left in /mnt/triple-c-home/.ssh stay there until you remove them."; export const COPY_AT_CONNECT_GATEWAY_NOTE = - "The LLM gateway's keys are still stored in AWS: the gateway starts before Triple-C connects."; + "The LLM gateway's keys are still stored in AWS: the gateway starts before Triple-C connects. So is Claude Code's token for it (ANTHROPIC_AUTH_TOKEN), which scheduled jobs need."; + +/** The LLM gateway sidecar (phase 6 Q7), in ModelSection. */ +export const GATEWAY_SIDECAR_LABEL = "Run Triple-C's LLM gateway in the workspace"; +export const GATEWAY_SIDECAR_HINT = + "Runs the gateway from Settings → Model Gateway (same models, provider and API key) next to the workspace, on its own localhost:4000. Claude Code uses it instead of the base URL and API key below; set the model to one of the gateway's model names."; +export const GATEWAY_SIDECAR_ON_NOTE = + "Claude Code talks to the gateway in the workspace (http://127.0.0.1:4000) with a key made for each start. The provider API key is stored in the project's AWS secret, whichever way credentials are delivered."; +/** Mirrors Rust `validate_aws_workspace`'s sidecar minimum. */ +export const GATEWAY_SIDECAR_MIN_CPU = 1024; +export const GATEWAY_SIDECAR_MIN_MEMORY_MIB = 2048; + +/** + * Why `project` can't turn the gateway sidecar on, or null. Mirrors Rust + * `gateway_sidecar_problem` (OpenAI-compatible backend, a complete gateway + * model) plus the 1 vCPU / 2 GiB minimum. + */ +export function gatewaySidecarProblem( + project: Pick, + gateway: Pick | null, +): string | null { + if (project.backend !== "open_ai_compatible") { + return "The LLM gateway sidecar needs the OpenAI Compatible backend."; + } + const models = (gateway?.models ?? []).filter((m) => m.name.trim() && m.model_id.trim()); + if (models.length === 0) { + return "Add at least one model in Settings → Model Gateway first (a name and a provider model id)."; + } + const aws = project.aws; + if (aws && (aws.cpu < GATEWAY_SIDECAR_MIN_CPU || aws.memory_mib < GATEWAY_SIDECAR_MIN_MEMORY_MIB)) { + return "The LLM gateway sidecar needs at least 1 vCPU and 2 GiB: raise them in the Host section."; + } + return null; +} export const SECRETS_MANAGER_HINT = "API keys, the Git token, custom environment variables and the SSH and CA files are kept in the project's Secrets Manager secret, so the workspace has them from the moment it starts.";