diff --git a/CLAUDE.md b/CLAUDE.md index a201f86..c3a047c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -284,7 +284,7 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li users have migrated. - **`host/`** — Where a project's container runs, and the only way into it. `ContainerTarget` (`Docker`, and `Agent` — reached through the in-container `triple-c-agent` by `agent.rs`, per - `docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md`; AWS planned — + `docs/superpowers/specs/2026-11-13-triple-c-agent-protocol.md`; AWS host, designed in `docs/superpowers/specs/2026-11-13-aws-ecs-host-design.md`) wraps execs, file transfer and `is_running`; `sessions.rs` holds `ExecSessionManager`. `ssm.rs` is the AWS transport to an `Agent` target: one SSM port-forward per task, run through @@ -300,6 +300,17 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li every tunnel (`for_project` is `None` while none is open; `for_project_waiting` covers the background re-attach after an app restart). AWS SDK calls stay in `aws/` (`runtime.rs`, `tasks.rs`, `workspace.rs`). + `port_forwards.rs` is an AWS project's port mappings: each TCP mapping is a **loopback-only** + auth-bridge `PortForward::bind_mapping` over socat-over-attach. Two deliberate differences from + Docker: it reaches the workspace's **loopback** (Docker publishes to eth0), so the agent port, + the browser-view ranges and — with `gateway_sidecar` on — the sidecar's 4000 are refused; and it + has **no gate** (no first-byte wait, no cross-site check, unlike the bridge). Validated on save + (rows the save adds/edits; everything when newly on AWS or the sidecar is switched); a stored row + that would be refused is skipped with a warning at connect. Opens are serialised per project and + re-read the stored mappings under that lock; unchanged forwards are kept with their connections. + Opened after every connect and on a save while connected; closed by every `tunnels::close*` + path. A failing mapping is a `workspace-warning` (`topic: "ports"`). An idle listener makes no + agent request; a connection carrying traffic is activity (keeps the workspace from idling). `agent.rs` reuses `docker/exec.rs`'s `OneshotOutput`, host-file reader and uid probe so the two variants cannot drift; an `Agent` target's token never appears in `Debug` or error text. **Container-interior code must go through `ContainerTarget`, never `docker::exec`, bollard or @@ -355,9 +366,24 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li through the agent, closes the project's terminals and auth bridge (so nothing is written after the push's snapshot), may push first (under an in-container `timeout`, since the agent does not kill an exec the client gave up on), then writes `pushed` or `discard` to `/run/triple-c/stop-reason` - (root-owned; the entrypoint's TERM hook reads it, and the idle watcher writes `idle`) so the hook + (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. + **Cost estimate** (`pricing.rs`, Q5): `pricing:GetProducts` (us-east-1, `AmazonECS`, filters in + `FILTERS`) → per-region x86/ARM rates cached at `/triple-c/aws-pricing/.json` for + 24 h; `aws_cost_estimate(connection_id, region, config)` never errors — denied/offline/slow (8 s) is + `None` ("Estimate unavailable"), a failed region isn't re-asked for 5 min, a stale cache still answers. **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(":")`, @@ -396,20 +422,89 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li every terminal's env and the files hold private keys). Repos clone in the background after the agent starts (terminals are usable before they arrive). Hybrid storage mounts EFS at `/mnt/triple-c-home` and symlinks `~/.claude`, `~/.claude.json`, `~/.ssh` into it (mounting over `/home/claude` would hide - the image's tooling); root never follows those links outside the mount (`aws_hybrid_ssh_dir`). On - TERM the hook pushes unsaved work to a `triple-c/wip/` branch via a temporary index (the - user's index is untouched; needs the task definition's `stopTimeout` raised, 120 s) unless the stop - marker says the app handled it. The idle watcher runs as root under a supervisor and signals the + the image's tooling); root never follows those links outside the mount (`aws_hybrid_ssh_dir`). EFS storage + is Hybrid plus a second access point (root `/triple-c-workspaces//`, a sibling of + the home roots) mounted straight at `/workspace`; the entrypoint links home state the same way + (`aws_storage_links_home`) and never creates or chowns `/workspace`. Because `/workspace` then + outlives the task, `clone_repos` clones into `/workspace/.triple-c-clone/` and renames + into place only on success; it never deletes anything at a final path, empties scratch at each + start, and `triple-c-wip-push` skips scratch. + Switching EFS → Hybrid/Ephemeral keeps `workspace_access_point_id` (store-owned) until "Remove AWS + resources" with discard deletes both access points. On + TERM the hook pushes unsaved work to the run's `triple-c/wip/-` branch via a + temporary index (the user's index is untouched; needs the task definition's `stopTimeout` raised, + 120 s) unless the stop marker says the app handled it. + **One WIP branch per task run and folder:** `aws_prepare_run` (right after the agent-token block) + writes `/run/triple-c/run-id` (`-`, task id from ECS task metadata) + and `start-epoch`; `/run/triple-c` is root 0711 (the stop guard keeps that mode — at 0700 `claude` + could not read the run id). The folder is sanitised to `[A-Za-z0-9._-]` (a name that changed gets + `-<8 hex of sha256(raw name)>`, so `a b` and `a_b` never share a ref) and the ref checked with + `git check-ref-format`; later pushes force (`+`) only that run's own branch, and a tree equal to + `/run/triple-c/wip-last/` (claude-owned dir, written after a successful push) is skipped. + No usable run id (Docker) keeps a per-push `-`, never forced. + **Setup script** (`TRIPLEC_SETUP_SCRIPT`, unset before the snapshot like `TRIPLEC_FILES`): written + to `/run/triple-c-setup/script` (root 0755 dir; root opens `log` and hands the descriptor over, so + claude writes nothing there), run as `claude`, `bash -e`, stdin `/dev/null`, + `timeout -k 10 1800`, chained after the background clone's `done` in the same background + subshell; `status` is `running` from the start until `ok` / `failed ` (a chain that dies + early writes `failed`, so the idle stop is never blocked). `triple-c-workspace-status` (python, + no secrets) prints `{clone:{done,repos},setup:{state,code,tail}}`. Edited in HostSection's + "Setup script" textarea (saved on blur, blank → `null`; the 32 KiB UTF-8 limit is checked in TS + with Rust's own message, `setupScriptProblem`). + **The start does not wait for them** (it ends after "Connecting…": Running, lock released); + `aws_host::spawn_follow` follows in a background task (`host/aws_host/status.rs`: background exec + every 2 s, at most 35 min, holds no project lock; ended by `tunnels::cancel_follow` on Stop/Remove + and by any tunnel close or app exit). Its only output is a `workspace-warning` event (warning + toast) for a failure it saw happen or one on a task this start ran; progress shows in Project + Home's Overview card, which polls `aws_workspace_status` every 5 s while Running and visible. + At load, a Starting/Stopping AWS project becomes Error (not Stopped — a crash mid-start may have + left a billed task), and `reconcile_aws_projects` also checks a Stopped one still holding a task ARN. + **Lifetime cap** (`TRIPLEC_MAX_LIFETIME_MINUTES`, advisory — sudo can kill it): the idle watcher + (started when idle stop *or* a non-zero cap is set) pushes best effort, records `lifetime` and + sends TERM; the hook exits 76 (`aws::tasks::LIFETIME_EXIT_CODE` → `StopKind::LifetimeCap` → + `lifetime` toast). HostSection shows a non-zero cap ("stops workspaces after N h (advisory)") from + `aws_environment_max_hours` (reads the environment record; `None` when it can't, never an error). + The idle watcher runs as root under a supervisor and signals the entrypoint's own PID (not PID 1, which is docker-init), so idle and ECS stops share one trap. Idle = the agent's `last_activity_unix` older than N minutes (open-but-silent attaches/tunnels don't count; requests with `X-Triple-C-Background: 1` — the auth bridge's and the file viewer's polls — never do), - no `claude`, no scheduler job, no running clone, and no unsaved git work: with the WIP push on the + no `claude`, no scheduler job, no running clone or setup script, and no unsaved git work: with the WIP push on the watcher pushes *before* signalling and stays up if that fails; with it off, dirty repos keep the workspace up; activity during the watcher's push sends it back to watching. A repo the background clone is still writing (`/run/triple-c-clone/repos` last says `cloning`, no `done`) is skipped by `triple-c-wip-push` (dry run: `"cloning": true`). The stop trap is set before any background work starts. An idle stop exits 75 (`aws::tasks::IDLE_EXIT_CODE`) so the death watch can tell it from a crash (`classify_stop` → the `ContainerExited` toast). + **Copy-at-connect** (`secrets_delivery: copy_at_connect`, Q2): the secret keeps settings, repos and + the agent token but no `TRIPLEC_FILES` and no credential pairs (`SECRET_ENV_KEYS` + every custom + variable; `TRIPLEC_CREDENTIALS=connect` instead — the gateway sidecar's `TRIPLEC_GATEWAY_*` keys + stay, R1). After every connect (start, attach, background re-attach) `aws_host::connect` + uploads the files and `connect.env` (`KEY=` lines) as root into this connect's own + `/dev/shm/triple-c/connect//` (root 0700 tmpfs; `--prepare` prints the nonce, so two + connects at once never mix) and runs `triple-c-apply-connect `: CA install as root, SSH merge and git + credential helper **as `claude`** (root never walks a live `~/.ssh`), `/run/triple-c/connected`, + then a background re-clone of `failed` repos only (GIT_TOKEN in that clone's env only). The + first clone waits up to 5 min for `connected` (`aws_wait_connect`) — when there are repos **or a + setup script** (the script runs after the clone and needs the CA, SSH and Git credentials). The + CA files are swapped in (`connect-ca.new` → `connect-ca`, old removed last), so a failed move + keeps the CA installed before. Terminals the app opens add + the pairs to their own `ExecSpec.env` (`aws_host::terminal_env`, pairs only — no file read); + nothing reaches the agent's snapshot, so cron/scheduled jobs and the setup script never get them. + A failed push is a `workspace-warning`. Hybrid/EFS do **not** link `~/.ssh` to EFS under + copy-at-connect (R6: keys vanish with the task). When a copy-at-connect start finds the secret + already there (CreateSecret's ResourceExists; a new project's secret is never read first) and it + `holds_credentials`, it is force-deleted and created again (R7: `PutSecretValue` would keep the + old values as AWSPREVIOUS); `TRIPLE_C_CUSTOM_ENV` is left out too. A replace whose re-create + times out (AWS still finishing the forced delete) leaves no secret; every secret write retries + while the name is pending deletion (≤ 30 s), then says to start again in a minute. + **Copy-at-connect limits** (also listed in HostSection's notes): there is no corporate CA until + the first connect (Claude Code's self-update may fail behind a TLS-inspecting proxy until then); + SSH keys, a Git token or variables removed from the project stay in the running task until it + stops (a connect only adds/overwrites them; a removed CA does go at the next connect); the setup script is not re-run + after a later connect's re-clone of a failed repo. + The re-clone closes the apply lock's fd (a later connect never waits for it); `--prepare` takes it. + The functions both scripts use live in `container/entrypoint-lib.sh` + (`/usr/local/lib/triple-c/`), sourced by the entrypoint first; it only defines things. **The `TRIPLEC_` env prefix is reserved** on both hosts (`RESERVED_ENV_PREFIXES`; `workspace.rs` drops custom variables in it): the entrypoint's settings live there. - **Browser runtime libraries are baked in; browser *binaries* are not.** A layer runs @@ -431,7 +526,7 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li approach converges on the worst state: a 400 MB browser present with its libraries gone. - The layer sits immediately after Node (npx is its only prerequisite) and well above the shim `COPY`s, so editing a shim does not re-run a multi-hundred-megabyte apt install. -- **`entrypoint.sh`** — UID/GID remapping to match host user, SSH key setup (`sync_host_ssh` *merges* the host dir into `~/.ssh`; never wipe it — container-made keys live there on the home volume), git config, docker socket permissions, Claude Code settings.json injection, then stays resident **as root** waiting on a root-owned +- **`entrypoint.sh`** (+ `entrypoint-lib.sh`, the CA/SSH/git-credential/clone functions it sources) — UID/GID remapping to match host user, SSH key setup (`sync_host_ssh` *merges* the host dir into `~/.ssh`; never wipe it — container-made keys live there on the home volume), git config, docker socket permissions, Claude Code settings.json injection, then stays resident **as root** waiting on a root-owned `triple-c-keepalive` sleep (respawned if killed; SIGTERM trap so `docker stop` is immediate). **Never hand the container's lifetime to a process the `claude` user owns** — it used to end in `exec su … claude -c "exec sleep infinity"`, and any `pkill sleep` / `kill -9 -1` a Claude diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index b38d3a9..2235acb 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -488,6 +488,31 @@ dependencies = [ "tracing", ] +[[package]] +name = "aws-sdk-pricing" +version = "1.125.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb09af014cbcee1ad1753d54d70c4afd7565dfd7ca4d84d8b702292462fe80f" +dependencies = [ + "arc-swap", + "aws-credential-types", + "aws-runtime", + "aws-smithy-async", + "aws-smithy-http", + "aws-smithy-json", + "aws-smithy-observability", + "aws-smithy-runtime", + "aws-smithy-runtime-api", + "aws-smithy-schema", + "aws-smithy-types", + "aws-types", + "bytes", + "fastrand", + "http", + "regex-lite", + "tracing", +] + [[package]] name = "aws-sdk-s3" version = "1.159.0" @@ -7446,6 +7471,7 @@ dependencies = [ "aws-sdk-efs", "aws-sdk-iam", "aws-sdk-kms", + "aws-sdk-pricing", "aws-sdk-s3", "aws-sdk-secretsmanager", "aws-sdk-ssm", diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index 533e161..17f373c 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -70,6 +70,8 @@ aws-sdk-iam = { version = "1.136.0", default-features = false, features = ["defa aws-sdk-secretsmanager = { version = "1.128.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } aws-sdk-efs = { version = "1.125.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } aws-sdk-cloudwatchlogs = { version = "1.165.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } +# aws/pricing.rs: the Fargate rates behind the hourly cost estimate (Q5). +aws-sdk-pricing = { version = "1.125.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } # Named by src/aws/connection.rs: the credentials-provider trait (its profile # wrapper) and the profile-file set (aws-config's alias for it is deprecated). # Both are the versions aws-config already resolves. diff --git a/app/src-tauri/capabilities/default.json b/app/src-tauri/capabilities/default.json index 2bbe2cd..fb9284c 100644 --- a/app/src-tauri/capabilities/default.json +++ b/app/src-tauri/capabilities/default.json @@ -20,6 +20,8 @@ "allow-stop-project-container", "allow-check-unsaved-work", "allow-aws-task-log", + "allow-aws-workspace-status", + "allow-aws-environment-max-hours", "allow-remove-aws-resources", "allow-rebuild-project-container", "allow-reconcile-project-statuses", @@ -69,6 +71,7 @@ "allow-aws-connection-sso-login", "allow-check-aws-permissions", "allow-aws-policy-document", + "allow-aws-cost-estimate", "allow-detect-aws-environments", "allow-deploy-aws-environment", "allow-update-aws-environment", diff --git a/app/src-tauri/gen/schemas/acl-manifests.json b/app/src-tauri/gen/schemas/acl-manifests.json index 39ed73a..3167ff1 100644 --- a/app/src-tauri/gen/schemas/acl-manifests.json +++ b/app/src-tauri/gen/schemas/acl-manifests.json @@ -1 +1 @@ -{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-aws-task-log":{"identifier":"allow-aws-task-log","description":"Enables the aws_task_log command without any pre-configured scope.","commands":{"allow":["aws_task_log"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":"Enables the check_browser_view_support command without any pre-configured scope.","commands":{"allow":["check_browser_view_support"],"deny":[]}},"allow-check-docker":{"identifier":"allow-check-docker","description":"Enables the check_docker command without any pre-configured scope.","commands":{"allow":["check_docker"],"deny":[]}},"allow-check-for-updates":{"identifier":"allow-check-for-updates","description":"Enables the check_for_updates command without any pre-configured scope.","commands":{"allow":["check_for_updates"],"deny":[]}},"allow-check-gateway-health":{"identifier":"allow-check-gateway-health","description":"Enables the check_gateway_health command without any pre-configured scope.","commands":{"allow":["check_gateway_health"],"deny":[]}},"allow-check-image-exists":{"identifier":"allow-check-image-exists","description":"Enables the check_image_exists command without any pre-configured scope.","commands":{"allow":["check_image_exists"],"deny":[]}},"allow-check-image-update":{"identifier":"allow-check-image-update","description":"Enables the check_image_update command without any pre-configured scope.","commands":{"allow":["check_image_update"],"deny":[]}},"allow-check-unsaved-work":{"identifier":"allow-check-unsaved-work","description":"Enables the check_unsaved_work command without any pre-configured scope.","commands":{"allow":["check_unsaved_work"],"deny":[]}},"allow-clear-claude-token":{"identifier":"allow-clear-claude-token","description":"Enables the clear_claude_token command without any pre-configured scope.","commands":{"allow":["clear_claude_token"],"deny":[]}},"allow-clear-gateway-api-key":{"identifier":"allow-clear-gateway-api-key","description":"Enables the clear_gateway_api_key command without any pre-configured scope.","commands":{"allow":["clear_gateway_api_key"],"deny":[]}},"allow-clear-scheduler-notifications":{"identifier":"allow-clear-scheduler-notifications","description":"Enables the clear_scheduler_notifications command without any pre-configured scope.","commands":{"allow":["clear_scheduler_notifications"],"deny":[]}},"allow-close-browser-view-popout":{"identifier":"allow-close-browser-view-popout","description":"Enables the close_browser_view_popout command without any pre-configured scope.","commands":{"allow":["close_browser_view_popout"],"deny":[]}},"allow-close-container-page":{"identifier":"allow-close-container-page","description":"Enables the close_container_page command without any pre-configured scope.","commands":{"allow":["close_container_page"],"deny":[]}},"allow-close-terminal-session":{"identifier":"allow-close-terminal-session","description":"Enables the close_terminal_session command without any pre-configured scope.","commands":{"allow":["close_terminal_session"],"deny":[]}},"allow-confirm-migration":{"identifier":"allow-confirm-migration","description":"Enables the confirm_migration command without any pre-configured scope.","commands":{"allow":["confirm_migration"],"deny":[]}},"allow-create-container-directory":{"identifier":"allow-create-container-directory","description":"Enables the create_container_directory command without any pre-configured scope.","commands":{"allow":["create_container_directory"],"deny":[]}},"allow-delete-note":{"identifier":"allow-delete-note","description":"Enables the delete_note command without any pre-configured scope.","commands":{"allow":["delete_note"],"deny":[]}},"allow-deploy-aws-environment":{"identifier":"allow-deploy-aws-environment","description":"Enables the deploy_aws_environment command without any pre-configured scope.","commands":{"allow":["deploy_aws_environment"],"deny":[]}},"allow-deploy-aws-permissions-boundary":{"identifier":"allow-deploy-aws-permissions-boundary","description":"Enables the deploy_aws_permissions_boundary command without any pre-configured scope.","commands":{"allow":["deploy_aws_permissions_boundary"],"deny":[]}},"allow-destroy-incomplete-aws-environment":{"identifier":"allow-destroy-incomplete-aws-environment","description":"Enables the destroy_incomplete_aws_environment command without any pre-configured scope.","commands":{"allow":["destroy_incomplete_aws_environment"],"deny":[]}},"allow-detect-aws-config":{"identifier":"allow-detect-aws-config","description":"Enables the detect_aws_config command without any pre-configured scope.","commands":{"allow":["detect_aws_config"],"deny":[]}},"allow-detect-aws-environments":{"identifier":"allow-detect-aws-environments","description":"Enables the detect_aws_environments command without any pre-configured scope.","commands":{"allow":["detect_aws_environments"],"deny":[]}},"allow-detect-host-timezone":{"identifier":"allow-detect-host-timezone","description":"Enables the detect_host_timezone command without any pre-configured scope.","commands":{"allow":["detect_host_timezone"],"deny":[]}},"allow-detect-install-options":{"identifier":"allow-detect-install-options","description":"Enables the detect_install_options command without any pre-configured scope.","commands":{"allow":["detect_install_options"],"deny":[]}},"allow-download-container-backup":{"identifier":"allow-download-container-backup","description":"Enables the download_container_backup command without any pre-configured scope.","commands":{"allow":["download_container_backup"],"deny":[]}},"allow-download-container-file":{"identifier":"allow-download-container-file","description":"Enables the download_container_file command without any pre-configured scope.","commands":{"allow":["download_container_file"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-follow-aws-deployment":{"identifier":"allow-follow-aws-deployment","description":"Enables the follow_aws_deployment command without any pre-configured scope.","commands":{"allow":["follow_aws_deployment"],"deny":[]}},"allow-forget-marketplace-installs":{"identifier":"allow-forget-marketplace-installs","description":"Enables the forget_marketplace_installs command without any pre-configured scope.","commands":{"allow":["forget_marketplace_installs"],"deny":[]}},"allow-get-app-version":{"identifier":"allow-get-app-version","description":"Enables the get_app_version command without any pre-configured scope.","commands":{"allow":["get_app_version"],"deny":[]}},"allow-get-auth-bridge-status":{"identifier":"allow-get-auth-bridge-status","description":"Enables the get_auth_bridge_status command without any pre-configured scope.","commands":{"allow":["get_auth_bridge_status"],"deny":[]}},"allow-get-browser-view-match-window":{"identifier":"allow-get-browser-view-match-window","description":"Enables the get_browser_view_match_window command without any pre-configured scope.","commands":{"allow":["get_browser_view_match_window"],"deny":[]}},"allow-get-browser-view-popout-state":{"identifier":"allow-get-browser-view-popout-state","description":"Enables the get_browser_view_popout_state command without any pre-configured scope.","commands":{"allow":["get_browser_view_popout_state"],"deny":[]}},"allow-get-browser-view-status":{"identifier":"allow-get-browser-view-status","description":"Enables the get_browser_view_status command without any pre-configured scope.","commands":{"allow":["get_browser_view_status"],"deny":[]}},"allow-get-container-info":{"identifier":"allow-get-container-info","description":"Enables the get_container_info command without any pre-configured scope.","commands":{"allow":["get_container_info"],"deny":[]}},"allow-get-container-page-state":{"identifier":"allow-get-container-page-state","description":"Enables the get_container_page_state command without any pre-configured scope.","commands":{"allow":["get_container_page_state"],"deny":[]}},"allow-get-container-staleness":{"identifier":"allow-get-container-staleness","description":"Enables the get_container_staleness command without any pre-configured scope.","commands":{"allow":["get_container_staleness"],"deny":[]}},"allow-get-gateway-auth-token":{"identifier":"allow-get-gateway-auth-token","description":"Enables the get_gateway_auth_token command without any pre-configured scope.","commands":{"allow":["get_gateway_auth_token"],"deny":[]}},"allow-get-gateway-status":{"identifier":"allow-get-gateway-status","description":"Enables the get_gateway_status command without any pre-configured scope.","commands":{"allow":["get_gateway_status"],"deny":[]}},"allow-get-help-content":{"identifier":"allow-get-help-content","description":"Enables the get_help_content command without any pre-configured scope.","commands":{"allow":["get_help_content"],"deny":[]}},"allow-get-marketplace-sync-report":{"identifier":"allow-get-marketplace-sync-report","description":"Enables the get_marketplace_sync_report command without any pre-configured scope.","commands":{"allow":["get_marketplace_sync_report"],"deny":[]}},"allow-get-migration-state":{"identifier":"allow-get-migration-state","description":"Enables the get_migration_state command without any pre-configured scope.","commands":{"allow":["get_migration_state"],"deny":[]}},"allow-get-scheduled-task-log":{"identifier":"allow-get-scheduled-task-log","description":"Enables the get_scheduled_task_log command without any pre-configured scope.","commands":{"allow":["get_scheduled_task_log"],"deny":[]}},"allow-get-scheduler-notifications":{"identifier":"allow-get-scheduler-notifications","description":"Enables the get_scheduler_notifications command without any pre-configured scope.","commands":{"allow":["get_scheduler_notifications"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stt-status":{"identifier":"allow-get-stt-status","description":"Enables the get_stt_status command without any pre-configured scope.","commands":{"allow":["get_stt_status"],"deny":[]}},"allow-get-web-terminal-status":{"identifier":"allow-get-web-terminal-status","description":"Enables the get_web_terminal_status command without any pre-configured scope.","commands":{"allow":["get_web_terminal_status"],"deny":[]}},"allow-has-claude-token":{"identifier":"allow-has-claude-token","description":"Enables the has_claude_token command without any pre-configured scope.","commands":{"allow":["has_claude_token"],"deny":[]}},"allow-inspect-ca-cert-path":{"identifier":"allow-inspect-ca-cert-path","description":"Enables the inspect_ca_cert_path command without any pre-configured scope.","commands":{"allow":["inspect_ca_cert_path"],"deny":[]}},"allow-install-browser-view-browser":{"identifier":"allow-install-browser-view-browser","description":"Enables the install_browser_view_browser command without any pre-configured scope.","commands":{"allow":["install_browser_view_browser"],"deny":[]}},"allow-install-browser-view-support":{"identifier":"allow-install-browser-view-support","description":"Enables the install_browser_view_support command without any pre-configured scope.","commands":{"allow":["install_browser_view_support"],"deny":[]}},"allow-install-marketplace-item":{"identifier":"allow-install-marketplace-item","description":"Enables the install_marketplace_item command without any pre-configured scope.","commands":{"allow":["install_marketplace_item"],"deny":[]}},"allow-list-aws-profiles":{"identifier":"allow-list-aws-profiles","description":"Enables the list_aws_profiles command without any pre-configured scope.","commands":{"allow":["list_aws_profiles"],"deny":[]}},"allow-list-claude-sessions":{"identifier":"allow-list-claude-sessions","description":"Enables the list_claude_sessions command without any pre-configured scope.","commands":{"allow":["list_claude_sessions"],"deny":[]}},"allow-list-container-capabilities":{"identifier":"allow-list-container-capabilities","description":"Enables the list_container_capabilities command without any pre-configured scope.","commands":{"allow":["list_container_capabilities"],"deny":[]}},"allow-list-container-files":{"identifier":"allow-list-container-files","description":"Enables the list_container_files command without any pre-configured scope.","commands":{"allow":["list_container_files"],"deny":[]}},"allow-list-marketplace-snapshots":{"identifier":"allow-list-marketplace-snapshots","description":"Enables the list_marketplace_snapshots command without any pre-configured scope.","commands":{"allow":["list_marketplace_snapshots"],"deny":[]}},"allow-list-marketplace-updates":{"identifier":"allow-list-marketplace-updates","description":"Enables the list_marketplace_updates command without any pre-configured scope.","commands":{"allow":["list_marketplace_updates"],"deny":[]}},"allow-list-notes":{"identifier":"allow-list-notes","description":"Enables the list_notes command without any pre-configured scope.","commands":{"allow":["list_notes"],"deny":[]}},"allow-list-projects":{"identifier":"allow-list-projects","description":"Enables the list_projects command without any pre-configured scope.","commands":{"allow":["list_projects"],"deny":[]}},"allow-list-scheduled-tasks":{"identifier":"allow-list-scheduled-tasks","description":"Enables the list_scheduled_tasks command without any pre-configured scope.","commands":{"allow":["list_scheduled_tasks"],"deny":[]}},"allow-marketplace-gh-host-available":{"identifier":"allow-marketplace-gh-host-available","description":"Enables the marketplace_gh_host_available command without any pre-configured scope.","commands":{"allow":["marketplace_gh_host_available"],"deny":[]}},"allow-marketplace-item-diff":{"identifier":"allow-marketplace-item-diff","description":"Enables the marketplace_item_diff command without any pre-configured scope.","commands":{"allow":["marketplace_item_diff"],"deny":[]}},"allow-migrate-project-to-base":{"identifier":"allow-migrate-project-to-base","description":"Enables the migrate_project_to_base command without any pre-configured scope.","commands":{"allow":["migrate_project_to_base"],"deny":[]}},"allow-onboard-aws-user":{"identifier":"allow-onboard-aws-user","description":"Enables the onboard_aws_user command without any pre-configured scope.","commands":{"allow":["onboard_aws_user"],"deny":[]}},"allow-open-browser-view-popout":{"identifier":"allow-open-browser-view-popout","description":"Enables the open_browser_view_popout command without any pre-configured scope.","commands":{"allow":["open_browser_view_popout"],"deny":[]}},"allow-open-file-viewer":{"identifier":"allow-open-file-viewer","description":"Enables the open_file_viewer command without any pre-configured scope.","commands":{"allow":["open_file_viewer"],"deny":[]}},"allow-open-page-in-container-browser":{"identifier":"allow-open-page-in-container-browser","description":"Enables the open_page_in_container_browser command without any pre-configured scope.","commands":{"allow":["open_page_in_container_browser"],"deny":[]}},"allow-open-terminal-session":{"identifier":"allow-open-terminal-session","description":"Enables the open_terminal_session command without any pre-configured scope.","commands":{"allow":["open_terminal_session"],"deny":[]}},"allow-open-url-external":{"identifier":"allow-open-url-external","description":"Enables the open_url_external command without any pre-configured scope.","commands":{"allow":["open_url_external"],"deny":[]}},"allow-paste-image-to-terminal":{"identifier":"allow-paste-image-to-terminal","description":"Enables the paste_image_to_terminal command without any pre-configured scope.","commands":{"allow":["paste_image_to_terminal"],"deny":[]}},"allow-preview-settings-import":{"identifier":"allow-preview-settings-import","description":"Enables the preview_settings_import command without any pre-configured scope.","commands":{"allow":["preview_settings_import"],"deny":[]}},"allow-pull-gateway-image":{"identifier":"allow-pull-gateway-image","description":"Enables the pull_gateway_image command without any pre-configured scope.","commands":{"allow":["pull_gateway_image"],"deny":[]}},"allow-pull-image":{"identifier":"allow-pull-image","description":"Enables the pull_image command without any pre-configured scope.","commands":{"allow":["pull_image"],"deny":[]}},"allow-pull-stt-image":{"identifier":"allow-pull-stt-image","description":"Enables the pull_stt_image command without any pre-configured scope.","commands":{"allow":["pull_stt_image"],"deny":[]}},"allow-push-aws-saved-state":{"identifier":"allow-push-aws-saved-state","description":"Enables the push_aws_saved_state command without any pre-configured scope.","commands":{"allow":["push_aws_saved_state"],"deny":[]}},"allow-read-container-file":{"identifier":"allow-read-container-file","description":"Enables the read_container_file command without any pre-configured scope.","commands":{"allow":["read_container_file"],"deny":[]}},"allow-rebuild-project-container":{"identifier":"allow-rebuild-project-container","description":"Enables the rebuild_project_container command without any pre-configured scope.","commands":{"allow":["rebuild_project_container"],"deny":[]}},"allow-reconcile-aws-projects":{"identifier":"allow-reconcile-aws-projects","description":"Enables the reconcile_aws_projects command without any pre-configured scope.","commands":{"allow":["reconcile_aws_projects"],"deny":[]}},"allow-reconcile-project-statuses":{"identifier":"allow-reconcile-project-statuses","description":"Enables the reconcile_project_statuses command without any pre-configured scope.","commands":{"allow":["reconcile_project_statuses"],"deny":[]}},"allow-refresh-marketplaces":{"identifier":"allow-refresh-marketplaces","description":"Enables the refresh_marketplaces command without any pre-configured scope.","commands":{"allow":["refresh_marketplaces"],"deny":[]}},"allow-regenerate-gateway-auth-token":{"identifier":"allow-regenerate-gateway-auth-token","description":"Enables the regenerate_gateway_auth_token command without any pre-configured scope.","commands":{"allow":["regenerate_gateway_auth_token"],"deny":[]}},"allow-regenerate-web-terminal-token":{"identifier":"allow-regenerate-web-terminal-token","description":"Enables the regenerate_web_terminal_token command without any pre-configured scope.","commands":{"allow":["regenerate_web_terminal_token"],"deny":[]}},"allow-remove-aws-resources":{"identifier":"allow-remove-aws-resources","description":"Enables the remove_aws_resources command without any pre-configured scope.","commands":{"allow":["remove_aws_resources"],"deny":[]}},"allow-remove-host-connection":{"identifier":"allow-remove-host-connection","description":"Enables the remove_host_connection command without any pre-configured scope.","commands":{"allow":["remove_host_connection"],"deny":[]}},"allow-remove-marketplace":{"identifier":"allow-remove-marketplace","description":"Enables the remove_marketplace command without any pre-configured scope.","commands":{"allow":["remove_marketplace"],"deny":[]}},"allow-remove-marketplace-account":{"identifier":"allow-remove-marketplace-account","description":"Enables the remove_marketplace_account command without any pre-configured scope.","commands":{"allow":["remove_marketplace_account"],"deny":[]}},"allow-remove-project":{"identifier":"allow-remove-project","description":"Enables the remove_project command without any pre-configured scope.","commands":{"allow":["remove_project"],"deny":[]}},"allow-remove-scheduled-task":{"identifier":"allow-remove-scheduled-task","description":"Enables the remove_scheduled_task command without any pre-configured scope.","commands":{"allow":["remove_scheduled_task"],"deny":[]}},"allow-rename-container-path":{"identifier":"allow-rename-container-path","description":"Enables the rename_container_path command without any pre-configured scope.","commands":{"allow":["rename_container_path"],"deny":[]}},"allow-repair-aws-environment":{"identifier":"allow-repair-aws-environment","description":"Enables the repair_aws_environment command without any pre-configured scope.","commands":{"allow":["repair_aws_environment"],"deny":[]}},"allow-rollback-migration":{"identifier":"allow-rollback-migration","description":"Enables the rollback_migration command without any pre-configured scope.","commands":{"allow":["rollback_migration"],"deny":[]}},"allow-run-docker-install":{"identifier":"allow-run-docker-install","description":"Enables the run_docker_install command without any pre-configured scope.","commands":{"allow":["run_docker_install"],"deny":[]}},"allow-run-scheduled-task-now":{"identifier":"allow-run-scheduled-task-now","description":"Enables the run_scheduled_task_now command without any pre-configured scope.","commands":{"allow":["run_scheduled_task_now"],"deny":[]}},"allow-save-aws-admin-bundle":{"identifier":"allow-save-aws-admin-bundle","description":"Enables the save_aws_admin_bundle command without any pre-configured scope.","commands":{"allow":["save_aws_admin_bundle"],"deny":[]}},"allow-save-note":{"identifier":"allow-save-note","description":"Enables the save_note command without any pre-configured scope.","commands":{"allow":["save_note"],"deny":[]}},"allow-send-audio-data":{"identifier":"allow-send-audio-data","description":"Enables the send_audio_data command without any pre-configured scope.","commands":{"allow":["send_audio_data"],"deny":[]}},"allow-set-auth-bridge-enabled":{"identifier":"allow-set-auth-bridge-enabled","description":"Enables the set_auth_bridge_enabled command without any pre-configured scope.","commands":{"allow":["set_auth_bridge_enabled"],"deny":[]}},"allow-set-browser-view-enabled":{"identifier":"allow-set-browser-view-enabled","description":"Enables the set_browser_view_enabled command without any pre-configured scope.","commands":{"allow":["set_browser_view_enabled"],"deny":[]}},"allow-set-browser-view-match-window":{"identifier":"allow-set-browser-view-match-window","description":"Enables the set_browser_view_match_window command without any pre-configured scope.","commands":{"allow":["set_browser_view_match_window"],"deny":[]}},"allow-set-browser-view-popout-always-on-top":{"identifier":"allow-set-browser-view-popout-always-on-top","description":"Enables the set_browser_view_popout_always_on_top command without any pre-configured scope.","commands":{"allow":["set_browser_view_popout_always_on_top"],"deny":[]}},"allow-set-container-page-viewport":{"identifier":"allow-set-container-page-viewport","description":"Enables the set_container_page_viewport command without any pre-configured scope.","commands":{"allow":["set_container_page_viewport"],"deny":[]}},"allow-set-gateway-api-key":{"identifier":"allow-set-gateway-api-key","description":"Enables the set_gateway_api_key command without any pre-configured scope.","commands":{"allow":["set_gateway_api_key"],"deny":[]}},"allow-set-global-item-disabled":{"identifier":"allow-set-global-item-disabled","description":"Enables the set_global_item_disabled command without any pre-configured scope.","commands":{"allow":["set_global_item_disabled"],"deny":[]}},"allow-set-scheduled-task-enabled":{"identifier":"allow-set-scheduled-task-enabled","description":"Enables the set_scheduled_task_enabled command without any pre-configured scope.","commands":{"allow":["set_scheduled_task_enabled"],"deny":[]}},"allow-start-audio-bridge":{"identifier":"allow-start-audio-bridge","description":"Enables the start_audio_bridge command without any pre-configured scope.","commands":{"allow":["start_audio_bridge"],"deny":[]}},"allow-start-gateway":{"identifier":"allow-start-gateway","description":"Enables the start_gateway command without any pre-configured scope.","commands":{"allow":["start_gateway"],"deny":[]}},"allow-start-marketplace-gh-container-login":{"identifier":"allow-start-marketplace-gh-container-login","description":"Enables the start_marketplace_gh_container_login command without any pre-configured scope.","commands":{"allow":["start_marketplace_gh_container_login"],"deny":[]}},"allow-start-project-container":{"identifier":"allow-start-project-container","description":"Enables the start_project_container command without any pre-configured scope.","commands":{"allow":["start_project_container"],"deny":[]}},"allow-start-stt":{"identifier":"allow-start-stt","description":"Enables the start_stt command without any pre-configured scope.","commands":{"allow":["start_stt"],"deny":[]}},"allow-start-web-terminal":{"identifier":"allow-start-web-terminal","description":"Enables the start_web_terminal command without any pre-configured scope.","commands":{"allow":["start_web_terminal"],"deny":[]}},"allow-stop-audio-bridge":{"identifier":"allow-stop-audio-bridge","description":"Enables the stop_audio_bridge command without any pre-configured scope.","commands":{"allow":["stop_audio_bridge"],"deny":[]}},"allow-stop-gateway":{"identifier":"allow-stop-gateway","description":"Enables the stop_gateway command without any pre-configured scope.","commands":{"allow":["stop_gateway"],"deny":[]}},"allow-stop-project-container":{"identifier":"allow-stop-project-container","description":"Enables the stop_project_container command without any pre-configured scope.","commands":{"allow":["stop_project_container"],"deny":[]}},"allow-stop-stt":{"identifier":"allow-stop-stt","description":"Enables the stop_stt command without any pre-configured scope.","commands":{"allow":["stop_stt"],"deny":[]}},"allow-stop-web-terminal":{"identifier":"allow-stop-web-terminal","description":"Enables the stop_web_terminal command without any pre-configured scope.","commands":{"allow":["stop_web_terminal"],"deny":[]}},"allow-submit-claude-token-code":{"identifier":"allow-submit-claude-token-code","description":"Enables the submit_claude_token_code command without any pre-configured scope.","commands":{"allow":["submit_claude_token_code"],"deny":[]}},"allow-sweep-claude-token-snapshots":{"identifier":"allow-sweep-claude-token-snapshots","description":"Enables the sweep_claude_token_snapshots command without any pre-configured scope.","commands":{"allow":["sweep_claude_token_snapshots"],"deny":[]}},"allow-terminal-input":{"identifier":"allow-terminal-input","description":"Enables the terminal_input command without any pre-configured scope.","commands":{"allow":["terminal_input"],"deny":[]}},"allow-terminal-resize":{"identifier":"allow-terminal-resize","description":"Enables the terminal_resize command without any pre-configured scope.","commands":{"allow":["terminal_resize"],"deny":[]}},"allow-test-marketplace-account":{"identifier":"allow-test-marketplace-account","description":"Enables the test_marketplace_account command without any pre-configured scope.","commands":{"allow":["test_marketplace_account"],"deny":[]}},"allow-transcribe-audio":{"identifier":"allow-transcribe-audio","description":"Enables the transcribe_audio command without any pre-configured scope.","commands":{"allow":["transcribe_audio"],"deny":[]}},"allow-uninstall-marketplace-item":{"identifier":"allow-uninstall-marketplace-item","description":"Enables the uninstall_marketplace_item command without any pre-configured scope.","commands":{"allow":["uninstall_marketplace_item"],"deny":[]}},"allow-unlock-aws-state":{"identifier":"allow-unlock-aws-state","description":"Enables the unlock_aws_state command without any pre-configured scope.","commands":{"allow":["unlock_aws_state"],"deny":[]}},"allow-update-aws-connection":{"identifier":"allow-update-aws-connection","description":"Enables the update_aws_connection command without any pre-configured scope.","commands":{"allow":["update_aws_connection"],"deny":[]}},"allow-update-aws-environment":{"identifier":"allow-update-aws-environment","description":"Enables the update_aws_environment command without any pre-configured scope.","commands":{"allow":["update_aws_environment"],"deny":[]}},"allow-update-marketplace":{"identifier":"allow-update-marketplace","description":"Enables the update_marketplace command without any pre-configured scope.","commands":{"allow":["update_marketplace"],"deny":[]}},"allow-update-marketplace-item":{"identifier":"allow-update-marketplace-item","description":"Enables the update_marketplace_item command without any pre-configured scope.","commands":{"allow":["update_marketplace_item"],"deny":[]}},"allow-update-project":{"identifier":"allow-update-project","description":"Enables the update_project command without any pre-configured scope.","commands":{"allow":["update_project"],"deny":[]}},"allow-update-scheduled-task":{"identifier":"allow-update-scheduled-task","description":"Enables the update_scheduled_task command without any pre-configured scope.","commands":{"allow":["update_scheduled_task"],"deny":[]}},"allow-update-settings":{"identifier":"allow-update-settings","description":"Enables the update_settings command without any pre-configured scope.","commands":{"allow":["update_settings"],"deny":[]}},"allow-upload-files-to-container":{"identifier":"allow-upload-files-to-container","description":"Enables the upload_files_to_container command without any pre-configured scope.","commands":{"allow":["upload_files_to_container"],"deny":[]}},"allow-upload-host-file-to-terminal":{"identifier":"allow-upload-host-file-to-terminal","description":"Enables the upload_host_file_to_terminal command without any pre-configured scope.","commands":{"allow":["upload_host_file_to_terminal"],"deny":[]}},"allow-viewer-choose-file":{"identifier":"allow-viewer-choose-file","description":"Enables the viewer_choose_file command without any pre-configured scope.","commands":{"allow":["viewer_choose_file"],"deny":[]}},"allow-viewer-get-state":{"identifier":"allow-viewer-get-state","description":"Enables the viewer_get_state command without any pre-configured scope.","commands":{"allow":["viewer_get_state"],"deny":[]}},"allow-viewer-poll-file":{"identifier":"allow-viewer-poll-file","description":"Enables the viewer_poll_file command without any pre-configured scope.","commands":{"allow":["viewer_poll_file"],"deny":[]}},"allow-viewer-read-file":{"identifier":"allow-viewer-read-file","description":"Enables the viewer_read_file command without any pre-configured scope.","commands":{"allow":["viewer_read_file"],"deny":[]}},"allow-viewer-write-file":{"identifier":"allow-viewer-write-file","description":"Enables the viewer_write_file command without any pre-configured scope.","commands":{"allow":["viewer_write_file"],"deny":[]}},"deny-acquire-claude-token":{"identifier":"deny-acquire-claude-token","description":"Denies the acquire_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["acquire_claude_token"]}},"deny-add-aws-keys-connection":{"identifier":"deny-add-aws-keys-connection","description":"Denies the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["add_aws_keys_connection"]}},"deny-add-aws-profile-connection":{"identifier":"deny-add-aws-profile-connection","description":"Denies the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["add_aws_profile_connection"]}},"deny-add-marketplace":{"identifier":"deny-add-marketplace","description":"Denies the add_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace"]}},"deny-add-marketplace-gh-host-account":{"identifier":"deny-add-marketplace-gh-host-account","description":"Denies the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace_gh_host_account"]}},"deny-add-marketplace-token-account":{"identifier":"deny-add-marketplace-token-account","description":"Denies the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace_token_account"]}},"deny-add-project":{"identifier":"deny-add-project","description":"Denies the add_project command without any pre-configured scope.","commands":{"allow":[],"deny":["add_project"]}},"deny-add-scheduled-task":{"identifier":"deny-add-scheduled-task","description":"Denies the add_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["add_scheduled_task"]}},"deny-apply-marketplace-now":{"identifier":"deny-apply-marketplace-now","description":"Denies the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":[],"deny":["apply_marketplace_now"]}},"deny-apply-settings-import":{"identifier":"deny-apply-settings-import","description":"Denies the apply_settings_import command without any pre-configured scope.","commands":{"allow":[],"deny":["apply_settings_import"]}},"deny-aws-connection-identity":{"identifier":"deny-aws-connection-identity","description":"Denies the aws_connection_identity command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_connection_identity"]}},"deny-aws-connection-sso-login":{"identifier":"deny-aws-connection-sso-login","description":"Denies the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_connection_sso_login"]}},"deny-aws-policy-document":{"identifier":"deny-aws-policy-document","description":"Denies the aws_policy_document command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_policy_document"]}},"deny-aws-sso-refresh":{"identifier":"deny-aws-sso-refresh","description":"Denies the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_sso_refresh"]}},"deny-aws-task-log":{"identifier":"deny-aws-task-log","description":"Denies the aws_task_log command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_task_log"]}},"deny-build-gateway-image":{"identifier":"deny-build-gateway-image","description":"Denies the build_gateway_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_gateway_image"]}},"deny-build-image":{"identifier":"deny-build-image","description":"Denies the build_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_image"]}},"deny-build-stt-image":{"identifier":"deny-build-stt-image","description":"Denies the build_stt_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_stt_image"]}},"deny-cancel-aws-deployment":{"identifier":"deny-cancel-aws-deployment","description":"Denies the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_aws_deployment"]}},"deny-cancel-claude-token":{"identifier":"deny-cancel-claude-token","description":"Denies the cancel_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_claude_token"]}},"deny-cancel-marketplace-gh-login":{"identifier":"deny-cancel-marketplace-gh-login","description":"Denies the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_marketplace_gh_login"]}},"deny-check-aws-permissions":{"identifier":"deny-check-aws-permissions","description":"Denies the check_aws_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_aws_permissions"]}},"deny-check-browser-view-support":{"identifier":"deny-check-browser-view-support","description":"Denies the check_browser_view_support command without any pre-configured scope.","commands":{"allow":[],"deny":["check_browser_view_support"]}},"deny-check-docker":{"identifier":"deny-check-docker","description":"Denies the check_docker command without any pre-configured scope.","commands":{"allow":[],"deny":["check_docker"]}},"deny-check-for-updates":{"identifier":"deny-check-for-updates","description":"Denies the check_for_updates command without any pre-configured scope.","commands":{"allow":[],"deny":["check_for_updates"]}},"deny-check-gateway-health":{"identifier":"deny-check-gateway-health","description":"Denies the check_gateway_health command without any pre-configured scope.","commands":{"allow":[],"deny":["check_gateway_health"]}},"deny-check-image-exists":{"identifier":"deny-check-image-exists","description":"Denies the check_image_exists command without any pre-configured scope.","commands":{"allow":[],"deny":["check_image_exists"]}},"deny-check-image-update":{"identifier":"deny-check-image-update","description":"Denies the check_image_update command without any pre-configured scope.","commands":{"allow":[],"deny":["check_image_update"]}},"deny-check-unsaved-work":{"identifier":"deny-check-unsaved-work","description":"Denies the check_unsaved_work command without any pre-configured scope.","commands":{"allow":[],"deny":["check_unsaved_work"]}},"deny-clear-claude-token":{"identifier":"deny-clear-claude-token","description":"Denies the clear_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_claude_token"]}},"deny-clear-gateway-api-key":{"identifier":"deny-clear-gateway-api-key","description":"Denies the clear_gateway_api_key command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_gateway_api_key"]}},"deny-clear-scheduler-notifications":{"identifier":"deny-clear-scheduler-notifications","description":"Denies the clear_scheduler_notifications command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_scheduler_notifications"]}},"deny-close-browser-view-popout":{"identifier":"deny-close-browser-view-popout","description":"Denies the close_browser_view_popout command without any pre-configured scope.","commands":{"allow":[],"deny":["close_browser_view_popout"]}},"deny-close-container-page":{"identifier":"deny-close-container-page","description":"Denies the close_container_page command without any pre-configured scope.","commands":{"allow":[],"deny":["close_container_page"]}},"deny-close-terminal-session":{"identifier":"deny-close-terminal-session","description":"Denies the close_terminal_session command without any pre-configured scope.","commands":{"allow":[],"deny":["close_terminal_session"]}},"deny-confirm-migration":{"identifier":"deny-confirm-migration","description":"Denies the confirm_migration command without any pre-configured scope.","commands":{"allow":[],"deny":["confirm_migration"]}},"deny-create-container-directory":{"identifier":"deny-create-container-directory","description":"Denies the create_container_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["create_container_directory"]}},"deny-delete-note":{"identifier":"deny-delete-note","description":"Denies the delete_note command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_note"]}},"deny-deploy-aws-environment":{"identifier":"deny-deploy-aws-environment","description":"Denies the deploy_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["deploy_aws_environment"]}},"deny-deploy-aws-permissions-boundary":{"identifier":"deny-deploy-aws-permissions-boundary","description":"Denies the deploy_aws_permissions_boundary command without any pre-configured scope.","commands":{"allow":[],"deny":["deploy_aws_permissions_boundary"]}},"deny-destroy-incomplete-aws-environment":{"identifier":"deny-destroy-incomplete-aws-environment","description":"Denies the destroy_incomplete_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy_incomplete_aws_environment"]}},"deny-detect-aws-config":{"identifier":"deny-detect-aws-config","description":"Denies the detect_aws_config command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_aws_config"]}},"deny-detect-aws-environments":{"identifier":"deny-detect-aws-environments","description":"Denies the detect_aws_environments command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_aws_environments"]}},"deny-detect-host-timezone":{"identifier":"deny-detect-host-timezone","description":"Denies the detect_host_timezone command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_host_timezone"]}},"deny-detect-install-options":{"identifier":"deny-detect-install-options","description":"Denies the detect_install_options command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_install_options"]}},"deny-download-container-backup":{"identifier":"deny-download-container-backup","description":"Denies the download_container_backup command without any pre-configured scope.","commands":{"allow":[],"deny":["download_container_backup"]}},"deny-download-container-file":{"identifier":"deny-download-container-file","description":"Denies the download_container_file command without any pre-configured scope.","commands":{"allow":[],"deny":["download_container_file"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-follow-aws-deployment":{"identifier":"deny-follow-aws-deployment","description":"Denies the follow_aws_deployment command without any pre-configured scope.","commands":{"allow":[],"deny":["follow_aws_deployment"]}},"deny-forget-marketplace-installs":{"identifier":"deny-forget-marketplace-installs","description":"Denies the forget_marketplace_installs command without any pre-configured scope.","commands":{"allow":[],"deny":["forget_marketplace_installs"]}},"deny-get-app-version":{"identifier":"deny-get-app-version","description":"Denies the get_app_version command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_version"]}},"deny-get-auth-bridge-status":{"identifier":"deny-get-auth-bridge-status","description":"Denies the get_auth_bridge_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_auth_bridge_status"]}},"deny-get-browser-view-match-window":{"identifier":"deny-get-browser-view-match-window","description":"Denies the get_browser_view_match_window command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_match_window"]}},"deny-get-browser-view-popout-state":{"identifier":"deny-get-browser-view-popout-state","description":"Denies the get_browser_view_popout_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_popout_state"]}},"deny-get-browser-view-status":{"identifier":"deny-get-browser-view-status","description":"Denies the get_browser_view_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_status"]}},"deny-get-container-info":{"identifier":"deny-get-container-info","description":"Denies the get_container_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_info"]}},"deny-get-container-page-state":{"identifier":"deny-get-container-page-state","description":"Denies the get_container_page_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_page_state"]}},"deny-get-container-staleness":{"identifier":"deny-get-container-staleness","description":"Denies the get_container_staleness command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_staleness"]}},"deny-get-gateway-auth-token":{"identifier":"deny-get-gateway-auth-token","description":"Denies the get_gateway_auth_token command without any pre-configured scope.","commands":{"allow":[],"deny":["get_gateway_auth_token"]}},"deny-get-gateway-status":{"identifier":"deny-get-gateway-status","description":"Denies the get_gateway_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_gateway_status"]}},"deny-get-help-content":{"identifier":"deny-get-help-content","description":"Denies the get_help_content command without any pre-configured scope.","commands":{"allow":[],"deny":["get_help_content"]}},"deny-get-marketplace-sync-report":{"identifier":"deny-get-marketplace-sync-report","description":"Denies the get_marketplace_sync_report command without any pre-configured scope.","commands":{"allow":[],"deny":["get_marketplace_sync_report"]}},"deny-get-migration-state":{"identifier":"deny-get-migration-state","description":"Denies the get_migration_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_migration_state"]}},"deny-get-scheduled-task-log":{"identifier":"deny-get-scheduled-task-log","description":"Denies the get_scheduled_task_log command without any pre-configured scope.","commands":{"allow":[],"deny":["get_scheduled_task_log"]}},"deny-get-scheduler-notifications":{"identifier":"deny-get-scheduler-notifications","description":"Denies the get_scheduler_notifications command without any pre-configured scope.","commands":{"allow":[],"deny":["get_scheduler_notifications"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stt-status":{"identifier":"deny-get-stt-status","description":"Denies the get_stt_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stt_status"]}},"deny-get-web-terminal-status":{"identifier":"deny-get-web-terminal-status","description":"Denies the get_web_terminal_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_web_terminal_status"]}},"deny-has-claude-token":{"identifier":"deny-has-claude-token","description":"Denies the has_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["has_claude_token"]}},"deny-inspect-ca-cert-path":{"identifier":"deny-inspect-ca-cert-path","description":"Denies the inspect_ca_cert_path command without any pre-configured scope.","commands":{"allow":[],"deny":["inspect_ca_cert_path"]}},"deny-install-browser-view-browser":{"identifier":"deny-install-browser-view-browser","description":"Denies the install_browser_view_browser command without any pre-configured scope.","commands":{"allow":[],"deny":["install_browser_view_browser"]}},"deny-install-browser-view-support":{"identifier":"deny-install-browser-view-support","description":"Denies the install_browser_view_support command without any pre-configured scope.","commands":{"allow":[],"deny":["install_browser_view_support"]}},"deny-install-marketplace-item":{"identifier":"deny-install-marketplace-item","description":"Denies the install_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["install_marketplace_item"]}},"deny-list-aws-profiles":{"identifier":"deny-list-aws-profiles","description":"Denies the list_aws_profiles command without any pre-configured scope.","commands":{"allow":[],"deny":["list_aws_profiles"]}},"deny-list-claude-sessions":{"identifier":"deny-list-claude-sessions","description":"Denies the list_claude_sessions command without any pre-configured scope.","commands":{"allow":[],"deny":["list_claude_sessions"]}},"deny-list-container-capabilities":{"identifier":"deny-list-container-capabilities","description":"Denies the list_container_capabilities command without any pre-configured scope.","commands":{"allow":[],"deny":["list_container_capabilities"]}},"deny-list-container-files":{"identifier":"deny-list-container-files","description":"Denies the list_container_files command without any pre-configured scope.","commands":{"allow":[],"deny":["list_container_files"]}},"deny-list-marketplace-snapshots":{"identifier":"deny-list-marketplace-snapshots","description":"Denies the list_marketplace_snapshots command without any pre-configured scope.","commands":{"allow":[],"deny":["list_marketplace_snapshots"]}},"deny-list-marketplace-updates":{"identifier":"deny-list-marketplace-updates","description":"Denies the list_marketplace_updates command without any pre-configured scope.","commands":{"allow":[],"deny":["list_marketplace_updates"]}},"deny-list-notes":{"identifier":"deny-list-notes","description":"Denies the list_notes command without any pre-configured scope.","commands":{"allow":[],"deny":["list_notes"]}},"deny-list-projects":{"identifier":"deny-list-projects","description":"Denies the list_projects command without any pre-configured scope.","commands":{"allow":[],"deny":["list_projects"]}},"deny-list-scheduled-tasks":{"identifier":"deny-list-scheduled-tasks","description":"Denies the list_scheduled_tasks command without any pre-configured scope.","commands":{"allow":[],"deny":["list_scheduled_tasks"]}},"deny-marketplace-gh-host-available":{"identifier":"deny-marketplace-gh-host-available","description":"Denies the marketplace_gh_host_available command without any pre-configured scope.","commands":{"allow":[],"deny":["marketplace_gh_host_available"]}},"deny-marketplace-item-diff":{"identifier":"deny-marketplace-item-diff","description":"Denies the marketplace_item_diff command without any pre-configured scope.","commands":{"allow":[],"deny":["marketplace_item_diff"]}},"deny-migrate-project-to-base":{"identifier":"deny-migrate-project-to-base","description":"Denies the migrate_project_to_base command without any pre-configured scope.","commands":{"allow":[],"deny":["migrate_project_to_base"]}},"deny-onboard-aws-user":{"identifier":"deny-onboard-aws-user","description":"Denies the onboard_aws_user command without any pre-configured scope.","commands":{"allow":[],"deny":["onboard_aws_user"]}},"deny-open-browser-view-popout":{"identifier":"deny-open-browser-view-popout","description":"Denies the open_browser_view_popout command without any pre-configured scope.","commands":{"allow":[],"deny":["open_browser_view_popout"]}},"deny-open-file-viewer":{"identifier":"deny-open-file-viewer","description":"Denies the open_file_viewer command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_viewer"]}},"deny-open-page-in-container-browser":{"identifier":"deny-open-page-in-container-browser","description":"Denies the open_page_in_container_browser command without any pre-configured scope.","commands":{"allow":[],"deny":["open_page_in_container_browser"]}},"deny-open-terminal-session":{"identifier":"deny-open-terminal-session","description":"Denies the open_terminal_session command without any pre-configured scope.","commands":{"allow":[],"deny":["open_terminal_session"]}},"deny-open-url-external":{"identifier":"deny-open-url-external","description":"Denies the open_url_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url_external"]}},"deny-paste-image-to-terminal":{"identifier":"deny-paste-image-to-terminal","description":"Denies the paste_image_to_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["paste_image_to_terminal"]}},"deny-preview-settings-import":{"identifier":"deny-preview-settings-import","description":"Denies the preview_settings_import command without any pre-configured scope.","commands":{"allow":[],"deny":["preview_settings_import"]}},"deny-pull-gateway-image":{"identifier":"deny-pull-gateway-image","description":"Denies the pull_gateway_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_gateway_image"]}},"deny-pull-image":{"identifier":"deny-pull-image","description":"Denies the pull_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_image"]}},"deny-pull-stt-image":{"identifier":"deny-pull-stt-image","description":"Denies the pull_stt_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_stt_image"]}},"deny-push-aws-saved-state":{"identifier":"deny-push-aws-saved-state","description":"Denies the push_aws_saved_state command without any pre-configured scope.","commands":{"allow":[],"deny":["push_aws_saved_state"]}},"deny-read-container-file":{"identifier":"deny-read-container-file","description":"Denies the read_container_file command without any pre-configured scope.","commands":{"allow":[],"deny":["read_container_file"]}},"deny-rebuild-project-container":{"identifier":"deny-rebuild-project-container","description":"Denies the rebuild_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["rebuild_project_container"]}},"deny-reconcile-aws-projects":{"identifier":"deny-reconcile-aws-projects","description":"Denies the reconcile_aws_projects command without any pre-configured scope.","commands":{"allow":[],"deny":["reconcile_aws_projects"]}},"deny-reconcile-project-statuses":{"identifier":"deny-reconcile-project-statuses","description":"Denies the reconcile_project_statuses command without any pre-configured scope.","commands":{"allow":[],"deny":["reconcile_project_statuses"]}},"deny-refresh-marketplaces":{"identifier":"deny-refresh-marketplaces","description":"Denies the refresh_marketplaces command without any pre-configured scope.","commands":{"allow":[],"deny":["refresh_marketplaces"]}},"deny-regenerate-gateway-auth-token":{"identifier":"deny-regenerate-gateway-auth-token","description":"Denies the regenerate_gateway_auth_token command without any pre-configured scope.","commands":{"allow":[],"deny":["regenerate_gateway_auth_token"]}},"deny-regenerate-web-terminal-token":{"identifier":"deny-regenerate-web-terminal-token","description":"Denies the regenerate_web_terminal_token command without any pre-configured scope.","commands":{"allow":[],"deny":["regenerate_web_terminal_token"]}},"deny-remove-aws-resources":{"identifier":"deny-remove-aws-resources","description":"Denies the remove_aws_resources command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_aws_resources"]}},"deny-remove-host-connection":{"identifier":"deny-remove-host-connection","description":"Denies the remove_host_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_host_connection"]}},"deny-remove-marketplace":{"identifier":"deny-remove-marketplace","description":"Denies the remove_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_marketplace"]}},"deny-remove-marketplace-account":{"identifier":"deny-remove-marketplace-account","description":"Denies the remove_marketplace_account command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_marketplace_account"]}},"deny-remove-project":{"identifier":"deny-remove-project","description":"Denies the remove_project command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_project"]}},"deny-remove-scheduled-task":{"identifier":"deny-remove-scheduled-task","description":"Denies the remove_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_scheduled_task"]}},"deny-rename-container-path":{"identifier":"deny-rename-container-path","description":"Denies the rename_container_path command without any pre-configured scope.","commands":{"allow":[],"deny":["rename_container_path"]}},"deny-repair-aws-environment":{"identifier":"deny-repair-aws-environment","description":"Denies the repair_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["repair_aws_environment"]}},"deny-rollback-migration":{"identifier":"deny-rollback-migration","description":"Denies the rollback_migration command without any pre-configured scope.","commands":{"allow":[],"deny":["rollback_migration"]}},"deny-run-docker-install":{"identifier":"deny-run-docker-install","description":"Denies the run_docker_install command without any pre-configured scope.","commands":{"allow":[],"deny":["run_docker_install"]}},"deny-run-scheduled-task-now":{"identifier":"deny-run-scheduled-task-now","description":"Denies the run_scheduled_task_now command without any pre-configured scope.","commands":{"allow":[],"deny":["run_scheduled_task_now"]}},"deny-save-aws-admin-bundle":{"identifier":"deny-save-aws-admin-bundle","description":"Denies the save_aws_admin_bundle command without any pre-configured scope.","commands":{"allow":[],"deny":["save_aws_admin_bundle"]}},"deny-save-note":{"identifier":"deny-save-note","description":"Denies the save_note command without any pre-configured scope.","commands":{"allow":[],"deny":["save_note"]}},"deny-send-audio-data":{"identifier":"deny-send-audio-data","description":"Denies the send_audio_data command without any pre-configured scope.","commands":{"allow":[],"deny":["send_audio_data"]}},"deny-set-auth-bridge-enabled":{"identifier":"deny-set-auth-bridge-enabled","description":"Denies the set_auth_bridge_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_auth_bridge_enabled"]}},"deny-set-browser-view-enabled":{"identifier":"deny-set-browser-view-enabled","description":"Denies the set_browser_view_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_enabled"]}},"deny-set-browser-view-match-window":{"identifier":"deny-set-browser-view-match-window","description":"Denies the set_browser_view_match_window command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_match_window"]}},"deny-set-browser-view-popout-always-on-top":{"identifier":"deny-set-browser-view-popout-always-on-top","description":"Denies the set_browser_view_popout_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_popout_always_on_top"]}},"deny-set-container-page-viewport":{"identifier":"deny-set-container-page-viewport","description":"Denies the set_container_page_viewport command without any pre-configured scope.","commands":{"allow":[],"deny":["set_container_page_viewport"]}},"deny-set-gateway-api-key":{"identifier":"deny-set-gateway-api-key","description":"Denies the set_gateway_api_key command without any pre-configured scope.","commands":{"allow":[],"deny":["set_gateway_api_key"]}},"deny-set-global-item-disabled":{"identifier":"deny-set-global-item-disabled","description":"Denies the set_global_item_disabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_global_item_disabled"]}},"deny-set-scheduled-task-enabled":{"identifier":"deny-set-scheduled-task-enabled","description":"Denies the set_scheduled_task_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_scheduled_task_enabled"]}},"deny-start-audio-bridge":{"identifier":"deny-start-audio-bridge","description":"Denies the start_audio_bridge command without any pre-configured scope.","commands":{"allow":[],"deny":["start_audio_bridge"]}},"deny-start-gateway":{"identifier":"deny-start-gateway","description":"Denies the start_gateway command without any pre-configured scope.","commands":{"allow":[],"deny":["start_gateway"]}},"deny-start-marketplace-gh-container-login":{"identifier":"deny-start-marketplace-gh-container-login","description":"Denies the start_marketplace_gh_container_login command without any pre-configured scope.","commands":{"allow":[],"deny":["start_marketplace_gh_container_login"]}},"deny-start-project-container":{"identifier":"deny-start-project-container","description":"Denies the start_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["start_project_container"]}},"deny-start-stt":{"identifier":"deny-start-stt","description":"Denies the start_stt command without any pre-configured scope.","commands":{"allow":[],"deny":["start_stt"]}},"deny-start-web-terminal":{"identifier":"deny-start-web-terminal","description":"Denies the start_web_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["start_web_terminal"]}},"deny-stop-audio-bridge":{"identifier":"deny-stop-audio-bridge","description":"Denies the stop_audio_bridge command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_audio_bridge"]}},"deny-stop-gateway":{"identifier":"deny-stop-gateway","description":"Denies the stop_gateway command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_gateway"]}},"deny-stop-project-container":{"identifier":"deny-stop-project-container","description":"Denies the stop_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_project_container"]}},"deny-stop-stt":{"identifier":"deny-stop-stt","description":"Denies the stop_stt command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_stt"]}},"deny-stop-web-terminal":{"identifier":"deny-stop-web-terminal","description":"Denies the stop_web_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_web_terminal"]}},"deny-submit-claude-token-code":{"identifier":"deny-submit-claude-token-code","description":"Denies the submit_claude_token_code command without any pre-configured scope.","commands":{"allow":[],"deny":["submit_claude_token_code"]}},"deny-sweep-claude-token-snapshots":{"identifier":"deny-sweep-claude-token-snapshots","description":"Denies the sweep_claude_token_snapshots command without any pre-configured scope.","commands":{"allow":[],"deny":["sweep_claude_token_snapshots"]}},"deny-terminal-input":{"identifier":"deny-terminal-input","description":"Denies the terminal_input command without any pre-configured scope.","commands":{"allow":[],"deny":["terminal_input"]}},"deny-terminal-resize":{"identifier":"deny-terminal-resize","description":"Denies the terminal_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["terminal_resize"]}},"deny-test-marketplace-account":{"identifier":"deny-test-marketplace-account","description":"Denies the test_marketplace_account command without any pre-configured scope.","commands":{"allow":[],"deny":["test_marketplace_account"]}},"deny-transcribe-audio":{"identifier":"deny-transcribe-audio","description":"Denies the transcribe_audio command without any pre-configured scope.","commands":{"allow":[],"deny":["transcribe_audio"]}},"deny-uninstall-marketplace-item":{"identifier":"deny-uninstall-marketplace-item","description":"Denies the uninstall_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["uninstall_marketplace_item"]}},"deny-unlock-aws-state":{"identifier":"deny-unlock-aws-state","description":"Denies the unlock_aws_state command without any pre-configured scope.","commands":{"allow":[],"deny":["unlock_aws_state"]}},"deny-update-aws-connection":{"identifier":"deny-update-aws-connection","description":"Denies the update_aws_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["update_aws_connection"]}},"deny-update-aws-environment":{"identifier":"deny-update-aws-environment","description":"Denies the update_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["update_aws_environment"]}},"deny-update-marketplace":{"identifier":"deny-update-marketplace","description":"Denies the update_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["update_marketplace"]}},"deny-update-marketplace-item":{"identifier":"deny-update-marketplace-item","description":"Denies the update_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["update_marketplace_item"]}},"deny-update-project":{"identifier":"deny-update-project","description":"Denies the update_project command without any pre-configured scope.","commands":{"allow":[],"deny":["update_project"]}},"deny-update-scheduled-task":{"identifier":"deny-update-scheduled-task","description":"Denies the update_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["update_scheduled_task"]}},"deny-update-settings":{"identifier":"deny-update-settings","description":"Denies the update_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["update_settings"]}},"deny-upload-files-to-container":{"identifier":"deny-upload-files-to-container","description":"Denies the upload_files_to_container command without any pre-configured scope.","commands":{"allow":[],"deny":["upload_files_to_container"]}},"deny-upload-host-file-to-terminal":{"identifier":"deny-upload-host-file-to-terminal","description":"Denies the upload_host_file_to_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["upload_host_file_to_terminal"]}},"deny-viewer-choose-file":{"identifier":"deny-viewer-choose-file","description":"Denies the viewer_choose_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_choose_file"]}},"deny-viewer-get-state":{"identifier":"deny-viewer-get-state","description":"Denies the viewer_get_state command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_get_state"]}},"deny-viewer-poll-file":{"identifier":"deny-viewer-poll-file","description":"Denies the viewer_poll_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_poll_file"]}},"deny-viewer-read-file":{"identifier":"deny-viewer-read-file","description":"Denies the viewer_read_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_read_file"]}},"deny-viewer-write-file":{"identifier":"deny-viewer-write-file","description":"Denies the viewer_write_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_write_file"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}}} \ No newline at end of file +{"__app-acl__":{"default_permission":null,"permissions":{"allow-acquire-claude-token":{"identifier":"allow-acquire-claude-token","description":"Enables the acquire_claude_token command without any pre-configured scope.","commands":{"allow":["acquire_claude_token"],"deny":[]}},"allow-add-aws-keys-connection":{"identifier":"allow-add-aws-keys-connection","description":"Enables the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":["add_aws_keys_connection"],"deny":[]}},"allow-add-aws-profile-connection":{"identifier":"allow-add-aws-profile-connection","description":"Enables the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":["add_aws_profile_connection"],"deny":[]}},"allow-add-marketplace":{"identifier":"allow-add-marketplace","description":"Enables the add_marketplace command without any pre-configured scope.","commands":{"allow":["add_marketplace"],"deny":[]}},"allow-add-marketplace-gh-host-account":{"identifier":"allow-add-marketplace-gh-host-account","description":"Enables the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_gh_host_account"],"deny":[]}},"allow-add-marketplace-token-account":{"identifier":"allow-add-marketplace-token-account","description":"Enables the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":["add_marketplace_token_account"],"deny":[]}},"allow-add-project":{"identifier":"allow-add-project","description":"Enables the add_project command without any pre-configured scope.","commands":{"allow":["add_project"],"deny":[]}},"allow-add-scheduled-task":{"identifier":"allow-add-scheduled-task","description":"Enables the add_scheduled_task command without any pre-configured scope.","commands":{"allow":["add_scheduled_task"],"deny":[]}},"allow-apply-marketplace-now":{"identifier":"allow-apply-marketplace-now","description":"Enables the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":["apply_marketplace_now"],"deny":[]}},"allow-apply-settings-import":{"identifier":"allow-apply-settings-import","description":"Enables the apply_settings_import command without any pre-configured scope.","commands":{"allow":["apply_settings_import"],"deny":[]}},"allow-aws-connection-identity":{"identifier":"allow-aws-connection-identity","description":"Enables the aws_connection_identity command without any pre-configured scope.","commands":{"allow":["aws_connection_identity"],"deny":[]}},"allow-aws-connection-sso-login":{"identifier":"allow-aws-connection-sso-login","description":"Enables the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":["aws_connection_sso_login"],"deny":[]}},"allow-aws-cost-estimate":{"identifier":"allow-aws-cost-estimate","description":"Enables the aws_cost_estimate command without any pre-configured scope.","commands":{"allow":["aws_cost_estimate"],"deny":[]}},"allow-aws-environment-max-hours":{"identifier":"allow-aws-environment-max-hours","description":"Enables the aws_environment_max_hours command without any pre-configured scope.","commands":{"allow":["aws_environment_max_hours"],"deny":[]}},"allow-aws-policy-document":{"identifier":"allow-aws-policy-document","description":"Enables the aws_policy_document command without any pre-configured scope.","commands":{"allow":["aws_policy_document"],"deny":[]}},"allow-aws-sso-refresh":{"identifier":"allow-aws-sso-refresh","description":"Enables the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":["aws_sso_refresh"],"deny":[]}},"allow-aws-task-log":{"identifier":"allow-aws-task-log","description":"Enables the aws_task_log command without any pre-configured scope.","commands":{"allow":["aws_task_log"],"deny":[]}},"allow-aws-workspace-status":{"identifier":"allow-aws-workspace-status","description":"Enables the aws_workspace_status command without any pre-configured scope.","commands":{"allow":["aws_workspace_status"],"deny":[]}},"allow-build-gateway-image":{"identifier":"allow-build-gateway-image","description":"Enables the build_gateway_image command without any pre-configured scope.","commands":{"allow":["build_gateway_image"],"deny":[]}},"allow-build-image":{"identifier":"allow-build-image","description":"Enables the build_image command without any pre-configured scope.","commands":{"allow":["build_image"],"deny":[]}},"allow-build-stt-image":{"identifier":"allow-build-stt-image","description":"Enables the build_stt_image command without any pre-configured scope.","commands":{"allow":["build_stt_image"],"deny":[]}},"allow-cancel-aws-deployment":{"identifier":"allow-cancel-aws-deployment","description":"Enables the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":["cancel_aws_deployment"],"deny":[]}},"allow-cancel-claude-token":{"identifier":"allow-cancel-claude-token","description":"Enables the cancel_claude_token command without any pre-configured scope.","commands":{"allow":["cancel_claude_token"],"deny":[]}},"allow-cancel-marketplace-gh-login":{"identifier":"allow-cancel-marketplace-gh-login","description":"Enables the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":["cancel_marketplace_gh_login"],"deny":[]}},"allow-check-aws-permissions":{"identifier":"allow-check-aws-permissions","description":"Enables the check_aws_permissions command without any pre-configured scope.","commands":{"allow":["check_aws_permissions"],"deny":[]}},"allow-check-browser-view-support":{"identifier":"allow-check-browser-view-support","description":"Enables the check_browser_view_support command without any pre-configured scope.","commands":{"allow":["check_browser_view_support"],"deny":[]}},"allow-check-docker":{"identifier":"allow-check-docker","description":"Enables the check_docker command without any pre-configured scope.","commands":{"allow":["check_docker"],"deny":[]}},"allow-check-for-updates":{"identifier":"allow-check-for-updates","description":"Enables the check_for_updates command without any pre-configured scope.","commands":{"allow":["check_for_updates"],"deny":[]}},"allow-check-gateway-health":{"identifier":"allow-check-gateway-health","description":"Enables the check_gateway_health command without any pre-configured scope.","commands":{"allow":["check_gateway_health"],"deny":[]}},"allow-check-image-exists":{"identifier":"allow-check-image-exists","description":"Enables the check_image_exists command without any pre-configured scope.","commands":{"allow":["check_image_exists"],"deny":[]}},"allow-check-image-update":{"identifier":"allow-check-image-update","description":"Enables the check_image_update command without any pre-configured scope.","commands":{"allow":["check_image_update"],"deny":[]}},"allow-check-unsaved-work":{"identifier":"allow-check-unsaved-work","description":"Enables the check_unsaved_work command without any pre-configured scope.","commands":{"allow":["check_unsaved_work"],"deny":[]}},"allow-clear-claude-token":{"identifier":"allow-clear-claude-token","description":"Enables the clear_claude_token command without any pre-configured scope.","commands":{"allow":["clear_claude_token"],"deny":[]}},"allow-clear-gateway-api-key":{"identifier":"allow-clear-gateway-api-key","description":"Enables the clear_gateway_api_key command without any pre-configured scope.","commands":{"allow":["clear_gateway_api_key"],"deny":[]}},"allow-clear-scheduler-notifications":{"identifier":"allow-clear-scheduler-notifications","description":"Enables the clear_scheduler_notifications command without any pre-configured scope.","commands":{"allow":["clear_scheduler_notifications"],"deny":[]}},"allow-close-browser-view-popout":{"identifier":"allow-close-browser-view-popout","description":"Enables the close_browser_view_popout command without any pre-configured scope.","commands":{"allow":["close_browser_view_popout"],"deny":[]}},"allow-close-container-page":{"identifier":"allow-close-container-page","description":"Enables the close_container_page command without any pre-configured scope.","commands":{"allow":["close_container_page"],"deny":[]}},"allow-close-terminal-session":{"identifier":"allow-close-terminal-session","description":"Enables the close_terminal_session command without any pre-configured scope.","commands":{"allow":["close_terminal_session"],"deny":[]}},"allow-confirm-migration":{"identifier":"allow-confirm-migration","description":"Enables the confirm_migration command without any pre-configured scope.","commands":{"allow":["confirm_migration"],"deny":[]}},"allow-create-container-directory":{"identifier":"allow-create-container-directory","description":"Enables the create_container_directory command without any pre-configured scope.","commands":{"allow":["create_container_directory"],"deny":[]}},"allow-delete-note":{"identifier":"allow-delete-note","description":"Enables the delete_note command without any pre-configured scope.","commands":{"allow":["delete_note"],"deny":[]}},"allow-deploy-aws-environment":{"identifier":"allow-deploy-aws-environment","description":"Enables the deploy_aws_environment command without any pre-configured scope.","commands":{"allow":["deploy_aws_environment"],"deny":[]}},"allow-deploy-aws-permissions-boundary":{"identifier":"allow-deploy-aws-permissions-boundary","description":"Enables the deploy_aws_permissions_boundary command without any pre-configured scope.","commands":{"allow":["deploy_aws_permissions_boundary"],"deny":[]}},"allow-destroy-incomplete-aws-environment":{"identifier":"allow-destroy-incomplete-aws-environment","description":"Enables the destroy_incomplete_aws_environment command without any pre-configured scope.","commands":{"allow":["destroy_incomplete_aws_environment"],"deny":[]}},"allow-detect-aws-config":{"identifier":"allow-detect-aws-config","description":"Enables the detect_aws_config command without any pre-configured scope.","commands":{"allow":["detect_aws_config"],"deny":[]}},"allow-detect-aws-environments":{"identifier":"allow-detect-aws-environments","description":"Enables the detect_aws_environments command without any pre-configured scope.","commands":{"allow":["detect_aws_environments"],"deny":[]}},"allow-detect-host-timezone":{"identifier":"allow-detect-host-timezone","description":"Enables the detect_host_timezone command without any pre-configured scope.","commands":{"allow":["detect_host_timezone"],"deny":[]}},"allow-detect-install-options":{"identifier":"allow-detect-install-options","description":"Enables the detect_install_options command without any pre-configured scope.","commands":{"allow":["detect_install_options"],"deny":[]}},"allow-download-container-backup":{"identifier":"allow-download-container-backup","description":"Enables the download_container_backup command without any pre-configured scope.","commands":{"allow":["download_container_backup"],"deny":[]}},"allow-download-container-file":{"identifier":"allow-download-container-file","description":"Enables the download_container_file command without any pre-configured scope.","commands":{"allow":["download_container_file"],"deny":[]}},"allow-export-settings":{"identifier":"allow-export-settings","description":"Enables the export_settings command without any pre-configured scope.","commands":{"allow":["export_settings"],"deny":[]}},"allow-follow-aws-deployment":{"identifier":"allow-follow-aws-deployment","description":"Enables the follow_aws_deployment command without any pre-configured scope.","commands":{"allow":["follow_aws_deployment"],"deny":[]}},"allow-forget-marketplace-installs":{"identifier":"allow-forget-marketplace-installs","description":"Enables the forget_marketplace_installs command without any pre-configured scope.","commands":{"allow":["forget_marketplace_installs"],"deny":[]}},"allow-get-app-version":{"identifier":"allow-get-app-version","description":"Enables the get_app_version command without any pre-configured scope.","commands":{"allow":["get_app_version"],"deny":[]}},"allow-get-auth-bridge-status":{"identifier":"allow-get-auth-bridge-status","description":"Enables the get_auth_bridge_status command without any pre-configured scope.","commands":{"allow":["get_auth_bridge_status"],"deny":[]}},"allow-get-browser-view-match-window":{"identifier":"allow-get-browser-view-match-window","description":"Enables the get_browser_view_match_window command without any pre-configured scope.","commands":{"allow":["get_browser_view_match_window"],"deny":[]}},"allow-get-browser-view-popout-state":{"identifier":"allow-get-browser-view-popout-state","description":"Enables the get_browser_view_popout_state command without any pre-configured scope.","commands":{"allow":["get_browser_view_popout_state"],"deny":[]}},"allow-get-browser-view-status":{"identifier":"allow-get-browser-view-status","description":"Enables the get_browser_view_status command without any pre-configured scope.","commands":{"allow":["get_browser_view_status"],"deny":[]}},"allow-get-container-info":{"identifier":"allow-get-container-info","description":"Enables the get_container_info command without any pre-configured scope.","commands":{"allow":["get_container_info"],"deny":[]}},"allow-get-container-page-state":{"identifier":"allow-get-container-page-state","description":"Enables the get_container_page_state command without any pre-configured scope.","commands":{"allow":["get_container_page_state"],"deny":[]}},"allow-get-container-staleness":{"identifier":"allow-get-container-staleness","description":"Enables the get_container_staleness command without any pre-configured scope.","commands":{"allow":["get_container_staleness"],"deny":[]}},"allow-get-gateway-auth-token":{"identifier":"allow-get-gateway-auth-token","description":"Enables the get_gateway_auth_token command without any pre-configured scope.","commands":{"allow":["get_gateway_auth_token"],"deny":[]}},"allow-get-gateway-status":{"identifier":"allow-get-gateway-status","description":"Enables the get_gateway_status command without any pre-configured scope.","commands":{"allow":["get_gateway_status"],"deny":[]}},"allow-get-help-content":{"identifier":"allow-get-help-content","description":"Enables the get_help_content command without any pre-configured scope.","commands":{"allow":["get_help_content"],"deny":[]}},"allow-get-marketplace-sync-report":{"identifier":"allow-get-marketplace-sync-report","description":"Enables the get_marketplace_sync_report command without any pre-configured scope.","commands":{"allow":["get_marketplace_sync_report"],"deny":[]}},"allow-get-migration-state":{"identifier":"allow-get-migration-state","description":"Enables the get_migration_state command without any pre-configured scope.","commands":{"allow":["get_migration_state"],"deny":[]}},"allow-get-scheduled-task-log":{"identifier":"allow-get-scheduled-task-log","description":"Enables the get_scheduled_task_log command without any pre-configured scope.","commands":{"allow":["get_scheduled_task_log"],"deny":[]}},"allow-get-scheduler-notifications":{"identifier":"allow-get-scheduler-notifications","description":"Enables the get_scheduler_notifications command without any pre-configured scope.","commands":{"allow":["get_scheduler_notifications"],"deny":[]}},"allow-get-settings":{"identifier":"allow-get-settings","description":"Enables the get_settings command without any pre-configured scope.","commands":{"allow":["get_settings"],"deny":[]}},"allow-get-stt-status":{"identifier":"allow-get-stt-status","description":"Enables the get_stt_status command without any pre-configured scope.","commands":{"allow":["get_stt_status"],"deny":[]}},"allow-get-web-terminal-status":{"identifier":"allow-get-web-terminal-status","description":"Enables the get_web_terminal_status command without any pre-configured scope.","commands":{"allow":["get_web_terminal_status"],"deny":[]}},"allow-has-claude-token":{"identifier":"allow-has-claude-token","description":"Enables the has_claude_token command without any pre-configured scope.","commands":{"allow":["has_claude_token"],"deny":[]}},"allow-inspect-ca-cert-path":{"identifier":"allow-inspect-ca-cert-path","description":"Enables the inspect_ca_cert_path command without any pre-configured scope.","commands":{"allow":["inspect_ca_cert_path"],"deny":[]}},"allow-install-browser-view-browser":{"identifier":"allow-install-browser-view-browser","description":"Enables the install_browser_view_browser command without any pre-configured scope.","commands":{"allow":["install_browser_view_browser"],"deny":[]}},"allow-install-browser-view-support":{"identifier":"allow-install-browser-view-support","description":"Enables the install_browser_view_support command without any pre-configured scope.","commands":{"allow":["install_browser_view_support"],"deny":[]}},"allow-install-marketplace-item":{"identifier":"allow-install-marketplace-item","description":"Enables the install_marketplace_item command without any pre-configured scope.","commands":{"allow":["install_marketplace_item"],"deny":[]}},"allow-list-aws-profiles":{"identifier":"allow-list-aws-profiles","description":"Enables the list_aws_profiles command without any pre-configured scope.","commands":{"allow":["list_aws_profiles"],"deny":[]}},"allow-list-claude-sessions":{"identifier":"allow-list-claude-sessions","description":"Enables the list_claude_sessions command without any pre-configured scope.","commands":{"allow":["list_claude_sessions"],"deny":[]}},"allow-list-container-capabilities":{"identifier":"allow-list-container-capabilities","description":"Enables the list_container_capabilities command without any pre-configured scope.","commands":{"allow":["list_container_capabilities"],"deny":[]}},"allow-list-container-files":{"identifier":"allow-list-container-files","description":"Enables the list_container_files command without any pre-configured scope.","commands":{"allow":["list_container_files"],"deny":[]}},"allow-list-marketplace-snapshots":{"identifier":"allow-list-marketplace-snapshots","description":"Enables the list_marketplace_snapshots command without any pre-configured scope.","commands":{"allow":["list_marketplace_snapshots"],"deny":[]}},"allow-list-marketplace-updates":{"identifier":"allow-list-marketplace-updates","description":"Enables the list_marketplace_updates command without any pre-configured scope.","commands":{"allow":["list_marketplace_updates"],"deny":[]}},"allow-list-notes":{"identifier":"allow-list-notes","description":"Enables the list_notes command without any pre-configured scope.","commands":{"allow":["list_notes"],"deny":[]}},"allow-list-projects":{"identifier":"allow-list-projects","description":"Enables the list_projects command without any pre-configured scope.","commands":{"allow":["list_projects"],"deny":[]}},"allow-list-scheduled-tasks":{"identifier":"allow-list-scheduled-tasks","description":"Enables the list_scheduled_tasks command without any pre-configured scope.","commands":{"allow":["list_scheduled_tasks"],"deny":[]}},"allow-marketplace-gh-host-available":{"identifier":"allow-marketplace-gh-host-available","description":"Enables the marketplace_gh_host_available command without any pre-configured scope.","commands":{"allow":["marketplace_gh_host_available"],"deny":[]}},"allow-marketplace-item-diff":{"identifier":"allow-marketplace-item-diff","description":"Enables the marketplace_item_diff command without any pre-configured scope.","commands":{"allow":["marketplace_item_diff"],"deny":[]}},"allow-migrate-project-to-base":{"identifier":"allow-migrate-project-to-base","description":"Enables the migrate_project_to_base command without any pre-configured scope.","commands":{"allow":["migrate_project_to_base"],"deny":[]}},"allow-onboard-aws-user":{"identifier":"allow-onboard-aws-user","description":"Enables the onboard_aws_user command without any pre-configured scope.","commands":{"allow":["onboard_aws_user"],"deny":[]}},"allow-open-browser-view-popout":{"identifier":"allow-open-browser-view-popout","description":"Enables the open_browser_view_popout command without any pre-configured scope.","commands":{"allow":["open_browser_view_popout"],"deny":[]}},"allow-open-file-viewer":{"identifier":"allow-open-file-viewer","description":"Enables the open_file_viewer command without any pre-configured scope.","commands":{"allow":["open_file_viewer"],"deny":[]}},"allow-open-page-in-container-browser":{"identifier":"allow-open-page-in-container-browser","description":"Enables the open_page_in_container_browser command without any pre-configured scope.","commands":{"allow":["open_page_in_container_browser"],"deny":[]}},"allow-open-terminal-session":{"identifier":"allow-open-terminal-session","description":"Enables the open_terminal_session command without any pre-configured scope.","commands":{"allow":["open_terminal_session"],"deny":[]}},"allow-open-url-external":{"identifier":"allow-open-url-external","description":"Enables the open_url_external command without any pre-configured scope.","commands":{"allow":["open_url_external"],"deny":[]}},"allow-paste-image-to-terminal":{"identifier":"allow-paste-image-to-terminal","description":"Enables the paste_image_to_terminal command without any pre-configured scope.","commands":{"allow":["paste_image_to_terminal"],"deny":[]}},"allow-preview-settings-import":{"identifier":"allow-preview-settings-import","description":"Enables the preview_settings_import command without any pre-configured scope.","commands":{"allow":["preview_settings_import"],"deny":[]}},"allow-pull-gateway-image":{"identifier":"allow-pull-gateway-image","description":"Enables the pull_gateway_image command without any pre-configured scope.","commands":{"allow":["pull_gateway_image"],"deny":[]}},"allow-pull-image":{"identifier":"allow-pull-image","description":"Enables the pull_image command without any pre-configured scope.","commands":{"allow":["pull_image"],"deny":[]}},"allow-pull-stt-image":{"identifier":"allow-pull-stt-image","description":"Enables the pull_stt_image command without any pre-configured scope.","commands":{"allow":["pull_stt_image"],"deny":[]}},"allow-push-aws-saved-state":{"identifier":"allow-push-aws-saved-state","description":"Enables the push_aws_saved_state command without any pre-configured scope.","commands":{"allow":["push_aws_saved_state"],"deny":[]}},"allow-read-container-file":{"identifier":"allow-read-container-file","description":"Enables the read_container_file command without any pre-configured scope.","commands":{"allow":["read_container_file"],"deny":[]}},"allow-rebuild-project-container":{"identifier":"allow-rebuild-project-container","description":"Enables the rebuild_project_container command without any pre-configured scope.","commands":{"allow":["rebuild_project_container"],"deny":[]}},"allow-reconcile-aws-projects":{"identifier":"allow-reconcile-aws-projects","description":"Enables the reconcile_aws_projects command without any pre-configured scope.","commands":{"allow":["reconcile_aws_projects"],"deny":[]}},"allow-reconcile-project-statuses":{"identifier":"allow-reconcile-project-statuses","description":"Enables the reconcile_project_statuses command without any pre-configured scope.","commands":{"allow":["reconcile_project_statuses"],"deny":[]}},"allow-refresh-marketplaces":{"identifier":"allow-refresh-marketplaces","description":"Enables the refresh_marketplaces command without any pre-configured scope.","commands":{"allow":["refresh_marketplaces"],"deny":[]}},"allow-regenerate-gateway-auth-token":{"identifier":"allow-regenerate-gateway-auth-token","description":"Enables the regenerate_gateway_auth_token command without any pre-configured scope.","commands":{"allow":["regenerate_gateway_auth_token"],"deny":[]}},"allow-regenerate-web-terminal-token":{"identifier":"allow-regenerate-web-terminal-token","description":"Enables the regenerate_web_terminal_token command without any pre-configured scope.","commands":{"allow":["regenerate_web_terminal_token"],"deny":[]}},"allow-remove-aws-resources":{"identifier":"allow-remove-aws-resources","description":"Enables the remove_aws_resources command without any pre-configured scope.","commands":{"allow":["remove_aws_resources"],"deny":[]}},"allow-remove-host-connection":{"identifier":"allow-remove-host-connection","description":"Enables the remove_host_connection command without any pre-configured scope.","commands":{"allow":["remove_host_connection"],"deny":[]}},"allow-remove-marketplace":{"identifier":"allow-remove-marketplace","description":"Enables the remove_marketplace command without any pre-configured scope.","commands":{"allow":["remove_marketplace"],"deny":[]}},"allow-remove-marketplace-account":{"identifier":"allow-remove-marketplace-account","description":"Enables the remove_marketplace_account command without any pre-configured scope.","commands":{"allow":["remove_marketplace_account"],"deny":[]}},"allow-remove-project":{"identifier":"allow-remove-project","description":"Enables the remove_project command without any pre-configured scope.","commands":{"allow":["remove_project"],"deny":[]}},"allow-remove-scheduled-task":{"identifier":"allow-remove-scheduled-task","description":"Enables the remove_scheduled_task command without any pre-configured scope.","commands":{"allow":["remove_scheduled_task"],"deny":[]}},"allow-rename-container-path":{"identifier":"allow-rename-container-path","description":"Enables the rename_container_path command without any pre-configured scope.","commands":{"allow":["rename_container_path"],"deny":[]}},"allow-repair-aws-environment":{"identifier":"allow-repair-aws-environment","description":"Enables the repair_aws_environment command without any pre-configured scope.","commands":{"allow":["repair_aws_environment"],"deny":[]}},"allow-rollback-migration":{"identifier":"allow-rollback-migration","description":"Enables the rollback_migration command without any pre-configured scope.","commands":{"allow":["rollback_migration"],"deny":[]}},"allow-run-docker-install":{"identifier":"allow-run-docker-install","description":"Enables the run_docker_install command without any pre-configured scope.","commands":{"allow":["run_docker_install"],"deny":[]}},"allow-run-scheduled-task-now":{"identifier":"allow-run-scheduled-task-now","description":"Enables the run_scheduled_task_now command without any pre-configured scope.","commands":{"allow":["run_scheduled_task_now"],"deny":[]}},"allow-save-aws-admin-bundle":{"identifier":"allow-save-aws-admin-bundle","description":"Enables the save_aws_admin_bundle command without any pre-configured scope.","commands":{"allow":["save_aws_admin_bundle"],"deny":[]}},"allow-save-note":{"identifier":"allow-save-note","description":"Enables the save_note command without any pre-configured scope.","commands":{"allow":["save_note"],"deny":[]}},"allow-send-audio-data":{"identifier":"allow-send-audio-data","description":"Enables the send_audio_data command without any pre-configured scope.","commands":{"allow":["send_audio_data"],"deny":[]}},"allow-set-auth-bridge-enabled":{"identifier":"allow-set-auth-bridge-enabled","description":"Enables the set_auth_bridge_enabled command without any pre-configured scope.","commands":{"allow":["set_auth_bridge_enabled"],"deny":[]}},"allow-set-browser-view-enabled":{"identifier":"allow-set-browser-view-enabled","description":"Enables the set_browser_view_enabled command without any pre-configured scope.","commands":{"allow":["set_browser_view_enabled"],"deny":[]}},"allow-set-browser-view-match-window":{"identifier":"allow-set-browser-view-match-window","description":"Enables the set_browser_view_match_window command without any pre-configured scope.","commands":{"allow":["set_browser_view_match_window"],"deny":[]}},"allow-set-browser-view-popout-always-on-top":{"identifier":"allow-set-browser-view-popout-always-on-top","description":"Enables the set_browser_view_popout_always_on_top command without any pre-configured scope.","commands":{"allow":["set_browser_view_popout_always_on_top"],"deny":[]}},"allow-set-container-page-viewport":{"identifier":"allow-set-container-page-viewport","description":"Enables the set_container_page_viewport command without any pre-configured scope.","commands":{"allow":["set_container_page_viewport"],"deny":[]}},"allow-set-gateway-api-key":{"identifier":"allow-set-gateway-api-key","description":"Enables the set_gateway_api_key command without any pre-configured scope.","commands":{"allow":["set_gateway_api_key"],"deny":[]}},"allow-set-global-item-disabled":{"identifier":"allow-set-global-item-disabled","description":"Enables the set_global_item_disabled command without any pre-configured scope.","commands":{"allow":["set_global_item_disabled"],"deny":[]}},"allow-set-scheduled-task-enabled":{"identifier":"allow-set-scheduled-task-enabled","description":"Enables the set_scheduled_task_enabled command without any pre-configured scope.","commands":{"allow":["set_scheduled_task_enabled"],"deny":[]}},"allow-start-audio-bridge":{"identifier":"allow-start-audio-bridge","description":"Enables the start_audio_bridge command without any pre-configured scope.","commands":{"allow":["start_audio_bridge"],"deny":[]}},"allow-start-gateway":{"identifier":"allow-start-gateway","description":"Enables the start_gateway command without any pre-configured scope.","commands":{"allow":["start_gateway"],"deny":[]}},"allow-start-marketplace-gh-container-login":{"identifier":"allow-start-marketplace-gh-container-login","description":"Enables the start_marketplace_gh_container_login command without any pre-configured scope.","commands":{"allow":["start_marketplace_gh_container_login"],"deny":[]}},"allow-start-project-container":{"identifier":"allow-start-project-container","description":"Enables the start_project_container command without any pre-configured scope.","commands":{"allow":["start_project_container"],"deny":[]}},"allow-start-stt":{"identifier":"allow-start-stt","description":"Enables the start_stt command without any pre-configured scope.","commands":{"allow":["start_stt"],"deny":[]}},"allow-start-web-terminal":{"identifier":"allow-start-web-terminal","description":"Enables the start_web_terminal command without any pre-configured scope.","commands":{"allow":["start_web_terminal"],"deny":[]}},"allow-stop-audio-bridge":{"identifier":"allow-stop-audio-bridge","description":"Enables the stop_audio_bridge command without any pre-configured scope.","commands":{"allow":["stop_audio_bridge"],"deny":[]}},"allow-stop-gateway":{"identifier":"allow-stop-gateway","description":"Enables the stop_gateway command without any pre-configured scope.","commands":{"allow":["stop_gateway"],"deny":[]}},"allow-stop-project-container":{"identifier":"allow-stop-project-container","description":"Enables the stop_project_container command without any pre-configured scope.","commands":{"allow":["stop_project_container"],"deny":[]}},"allow-stop-stt":{"identifier":"allow-stop-stt","description":"Enables the stop_stt command without any pre-configured scope.","commands":{"allow":["stop_stt"],"deny":[]}},"allow-stop-web-terminal":{"identifier":"allow-stop-web-terminal","description":"Enables the stop_web_terminal command without any pre-configured scope.","commands":{"allow":["stop_web_terminal"],"deny":[]}},"allow-submit-claude-token-code":{"identifier":"allow-submit-claude-token-code","description":"Enables the submit_claude_token_code command without any pre-configured scope.","commands":{"allow":["submit_claude_token_code"],"deny":[]}},"allow-sweep-claude-token-snapshots":{"identifier":"allow-sweep-claude-token-snapshots","description":"Enables the sweep_claude_token_snapshots command without any pre-configured scope.","commands":{"allow":["sweep_claude_token_snapshots"],"deny":[]}},"allow-terminal-input":{"identifier":"allow-terminal-input","description":"Enables the terminal_input command without any pre-configured scope.","commands":{"allow":["terminal_input"],"deny":[]}},"allow-terminal-resize":{"identifier":"allow-terminal-resize","description":"Enables the terminal_resize command without any pre-configured scope.","commands":{"allow":["terminal_resize"],"deny":[]}},"allow-test-marketplace-account":{"identifier":"allow-test-marketplace-account","description":"Enables the test_marketplace_account command without any pre-configured scope.","commands":{"allow":["test_marketplace_account"],"deny":[]}},"allow-transcribe-audio":{"identifier":"allow-transcribe-audio","description":"Enables the transcribe_audio command without any pre-configured scope.","commands":{"allow":["transcribe_audio"],"deny":[]}},"allow-uninstall-marketplace-item":{"identifier":"allow-uninstall-marketplace-item","description":"Enables the uninstall_marketplace_item command without any pre-configured scope.","commands":{"allow":["uninstall_marketplace_item"],"deny":[]}},"allow-unlock-aws-state":{"identifier":"allow-unlock-aws-state","description":"Enables the unlock_aws_state command without any pre-configured scope.","commands":{"allow":["unlock_aws_state"],"deny":[]}},"allow-update-aws-connection":{"identifier":"allow-update-aws-connection","description":"Enables the update_aws_connection command without any pre-configured scope.","commands":{"allow":["update_aws_connection"],"deny":[]}},"allow-update-aws-environment":{"identifier":"allow-update-aws-environment","description":"Enables the update_aws_environment command without any pre-configured scope.","commands":{"allow":["update_aws_environment"],"deny":[]}},"allow-update-marketplace":{"identifier":"allow-update-marketplace","description":"Enables the update_marketplace command without any pre-configured scope.","commands":{"allow":["update_marketplace"],"deny":[]}},"allow-update-marketplace-item":{"identifier":"allow-update-marketplace-item","description":"Enables the update_marketplace_item command without any pre-configured scope.","commands":{"allow":["update_marketplace_item"],"deny":[]}},"allow-update-project":{"identifier":"allow-update-project","description":"Enables the update_project command without any pre-configured scope.","commands":{"allow":["update_project"],"deny":[]}},"allow-update-scheduled-task":{"identifier":"allow-update-scheduled-task","description":"Enables the update_scheduled_task command without any pre-configured scope.","commands":{"allow":["update_scheduled_task"],"deny":[]}},"allow-update-settings":{"identifier":"allow-update-settings","description":"Enables the update_settings command without any pre-configured scope.","commands":{"allow":["update_settings"],"deny":[]}},"allow-upload-files-to-container":{"identifier":"allow-upload-files-to-container","description":"Enables the upload_files_to_container command without any pre-configured scope.","commands":{"allow":["upload_files_to_container"],"deny":[]}},"allow-upload-host-file-to-terminal":{"identifier":"allow-upload-host-file-to-terminal","description":"Enables the upload_host_file_to_terminal command without any pre-configured scope.","commands":{"allow":["upload_host_file_to_terminal"],"deny":[]}},"allow-viewer-choose-file":{"identifier":"allow-viewer-choose-file","description":"Enables the viewer_choose_file command without any pre-configured scope.","commands":{"allow":["viewer_choose_file"],"deny":[]}},"allow-viewer-get-state":{"identifier":"allow-viewer-get-state","description":"Enables the viewer_get_state command without any pre-configured scope.","commands":{"allow":["viewer_get_state"],"deny":[]}},"allow-viewer-poll-file":{"identifier":"allow-viewer-poll-file","description":"Enables the viewer_poll_file command without any pre-configured scope.","commands":{"allow":["viewer_poll_file"],"deny":[]}},"allow-viewer-read-file":{"identifier":"allow-viewer-read-file","description":"Enables the viewer_read_file command without any pre-configured scope.","commands":{"allow":["viewer_read_file"],"deny":[]}},"allow-viewer-write-file":{"identifier":"allow-viewer-write-file","description":"Enables the viewer_write_file command without any pre-configured scope.","commands":{"allow":["viewer_write_file"],"deny":[]}},"deny-acquire-claude-token":{"identifier":"deny-acquire-claude-token","description":"Denies the acquire_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["acquire_claude_token"]}},"deny-add-aws-keys-connection":{"identifier":"deny-add-aws-keys-connection","description":"Denies the add_aws_keys_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["add_aws_keys_connection"]}},"deny-add-aws-profile-connection":{"identifier":"deny-add-aws-profile-connection","description":"Denies the add_aws_profile_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["add_aws_profile_connection"]}},"deny-add-marketplace":{"identifier":"deny-add-marketplace","description":"Denies the add_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace"]}},"deny-add-marketplace-gh-host-account":{"identifier":"deny-add-marketplace-gh-host-account","description":"Denies the add_marketplace_gh_host_account command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace_gh_host_account"]}},"deny-add-marketplace-token-account":{"identifier":"deny-add-marketplace-token-account","description":"Denies the add_marketplace_token_account command without any pre-configured scope.","commands":{"allow":[],"deny":["add_marketplace_token_account"]}},"deny-add-project":{"identifier":"deny-add-project","description":"Denies the add_project command without any pre-configured scope.","commands":{"allow":[],"deny":["add_project"]}},"deny-add-scheduled-task":{"identifier":"deny-add-scheduled-task","description":"Denies the add_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["add_scheduled_task"]}},"deny-apply-marketplace-now":{"identifier":"deny-apply-marketplace-now","description":"Denies the apply_marketplace_now command without any pre-configured scope.","commands":{"allow":[],"deny":["apply_marketplace_now"]}},"deny-apply-settings-import":{"identifier":"deny-apply-settings-import","description":"Denies the apply_settings_import command without any pre-configured scope.","commands":{"allow":[],"deny":["apply_settings_import"]}},"deny-aws-connection-identity":{"identifier":"deny-aws-connection-identity","description":"Denies the aws_connection_identity command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_connection_identity"]}},"deny-aws-connection-sso-login":{"identifier":"deny-aws-connection-sso-login","description":"Denies the aws_connection_sso_login command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_connection_sso_login"]}},"deny-aws-cost-estimate":{"identifier":"deny-aws-cost-estimate","description":"Denies the aws_cost_estimate command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_cost_estimate"]}},"deny-aws-environment-max-hours":{"identifier":"deny-aws-environment-max-hours","description":"Denies the aws_environment_max_hours command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_environment_max_hours"]}},"deny-aws-policy-document":{"identifier":"deny-aws-policy-document","description":"Denies the aws_policy_document command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_policy_document"]}},"deny-aws-sso-refresh":{"identifier":"deny-aws-sso-refresh","description":"Denies the aws_sso_refresh command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_sso_refresh"]}},"deny-aws-task-log":{"identifier":"deny-aws-task-log","description":"Denies the aws_task_log command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_task_log"]}},"deny-aws-workspace-status":{"identifier":"deny-aws-workspace-status","description":"Denies the aws_workspace_status command without any pre-configured scope.","commands":{"allow":[],"deny":["aws_workspace_status"]}},"deny-build-gateway-image":{"identifier":"deny-build-gateway-image","description":"Denies the build_gateway_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_gateway_image"]}},"deny-build-image":{"identifier":"deny-build-image","description":"Denies the build_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_image"]}},"deny-build-stt-image":{"identifier":"deny-build-stt-image","description":"Denies the build_stt_image command without any pre-configured scope.","commands":{"allow":[],"deny":["build_stt_image"]}},"deny-cancel-aws-deployment":{"identifier":"deny-cancel-aws-deployment","description":"Denies the cancel_aws_deployment command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_aws_deployment"]}},"deny-cancel-claude-token":{"identifier":"deny-cancel-claude-token","description":"Denies the cancel_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_claude_token"]}},"deny-cancel-marketplace-gh-login":{"identifier":"deny-cancel-marketplace-gh-login","description":"Denies the cancel_marketplace_gh_login command without any pre-configured scope.","commands":{"allow":[],"deny":["cancel_marketplace_gh_login"]}},"deny-check-aws-permissions":{"identifier":"deny-check-aws-permissions","description":"Denies the check_aws_permissions command without any pre-configured scope.","commands":{"allow":[],"deny":["check_aws_permissions"]}},"deny-check-browser-view-support":{"identifier":"deny-check-browser-view-support","description":"Denies the check_browser_view_support command without any pre-configured scope.","commands":{"allow":[],"deny":["check_browser_view_support"]}},"deny-check-docker":{"identifier":"deny-check-docker","description":"Denies the check_docker command without any pre-configured scope.","commands":{"allow":[],"deny":["check_docker"]}},"deny-check-for-updates":{"identifier":"deny-check-for-updates","description":"Denies the check_for_updates command without any pre-configured scope.","commands":{"allow":[],"deny":["check_for_updates"]}},"deny-check-gateway-health":{"identifier":"deny-check-gateway-health","description":"Denies the check_gateway_health command without any pre-configured scope.","commands":{"allow":[],"deny":["check_gateway_health"]}},"deny-check-image-exists":{"identifier":"deny-check-image-exists","description":"Denies the check_image_exists command without any pre-configured scope.","commands":{"allow":[],"deny":["check_image_exists"]}},"deny-check-image-update":{"identifier":"deny-check-image-update","description":"Denies the check_image_update command without any pre-configured scope.","commands":{"allow":[],"deny":["check_image_update"]}},"deny-check-unsaved-work":{"identifier":"deny-check-unsaved-work","description":"Denies the check_unsaved_work command without any pre-configured scope.","commands":{"allow":[],"deny":["check_unsaved_work"]}},"deny-clear-claude-token":{"identifier":"deny-clear-claude-token","description":"Denies the clear_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_claude_token"]}},"deny-clear-gateway-api-key":{"identifier":"deny-clear-gateway-api-key","description":"Denies the clear_gateway_api_key command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_gateway_api_key"]}},"deny-clear-scheduler-notifications":{"identifier":"deny-clear-scheduler-notifications","description":"Denies the clear_scheduler_notifications command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_scheduler_notifications"]}},"deny-close-browser-view-popout":{"identifier":"deny-close-browser-view-popout","description":"Denies the close_browser_view_popout command without any pre-configured scope.","commands":{"allow":[],"deny":["close_browser_view_popout"]}},"deny-close-container-page":{"identifier":"deny-close-container-page","description":"Denies the close_container_page command without any pre-configured scope.","commands":{"allow":[],"deny":["close_container_page"]}},"deny-close-terminal-session":{"identifier":"deny-close-terminal-session","description":"Denies the close_terminal_session command without any pre-configured scope.","commands":{"allow":[],"deny":["close_terminal_session"]}},"deny-confirm-migration":{"identifier":"deny-confirm-migration","description":"Denies the confirm_migration command without any pre-configured scope.","commands":{"allow":[],"deny":["confirm_migration"]}},"deny-create-container-directory":{"identifier":"deny-create-container-directory","description":"Denies the create_container_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["create_container_directory"]}},"deny-delete-note":{"identifier":"deny-delete-note","description":"Denies the delete_note command without any pre-configured scope.","commands":{"allow":[],"deny":["delete_note"]}},"deny-deploy-aws-environment":{"identifier":"deny-deploy-aws-environment","description":"Denies the deploy_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["deploy_aws_environment"]}},"deny-deploy-aws-permissions-boundary":{"identifier":"deny-deploy-aws-permissions-boundary","description":"Denies the deploy_aws_permissions_boundary command without any pre-configured scope.","commands":{"allow":[],"deny":["deploy_aws_permissions_boundary"]}},"deny-destroy-incomplete-aws-environment":{"identifier":"deny-destroy-incomplete-aws-environment","description":"Denies the destroy_incomplete_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy_incomplete_aws_environment"]}},"deny-detect-aws-config":{"identifier":"deny-detect-aws-config","description":"Denies the detect_aws_config command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_aws_config"]}},"deny-detect-aws-environments":{"identifier":"deny-detect-aws-environments","description":"Denies the detect_aws_environments command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_aws_environments"]}},"deny-detect-host-timezone":{"identifier":"deny-detect-host-timezone","description":"Denies the detect_host_timezone command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_host_timezone"]}},"deny-detect-install-options":{"identifier":"deny-detect-install-options","description":"Denies the detect_install_options command without any pre-configured scope.","commands":{"allow":[],"deny":["detect_install_options"]}},"deny-download-container-backup":{"identifier":"deny-download-container-backup","description":"Denies the download_container_backup command without any pre-configured scope.","commands":{"allow":[],"deny":["download_container_backup"]}},"deny-download-container-file":{"identifier":"deny-download-container-file","description":"Denies the download_container_file command without any pre-configured scope.","commands":{"allow":[],"deny":["download_container_file"]}},"deny-export-settings":{"identifier":"deny-export-settings","description":"Denies the export_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["export_settings"]}},"deny-follow-aws-deployment":{"identifier":"deny-follow-aws-deployment","description":"Denies the follow_aws_deployment command without any pre-configured scope.","commands":{"allow":[],"deny":["follow_aws_deployment"]}},"deny-forget-marketplace-installs":{"identifier":"deny-forget-marketplace-installs","description":"Denies the forget_marketplace_installs command without any pre-configured scope.","commands":{"allow":[],"deny":["forget_marketplace_installs"]}},"deny-get-app-version":{"identifier":"deny-get-app-version","description":"Denies the get_app_version command without any pre-configured scope.","commands":{"allow":[],"deny":["get_app_version"]}},"deny-get-auth-bridge-status":{"identifier":"deny-get-auth-bridge-status","description":"Denies the get_auth_bridge_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_auth_bridge_status"]}},"deny-get-browser-view-match-window":{"identifier":"deny-get-browser-view-match-window","description":"Denies the get_browser_view_match_window command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_match_window"]}},"deny-get-browser-view-popout-state":{"identifier":"deny-get-browser-view-popout-state","description":"Denies the get_browser_view_popout_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_popout_state"]}},"deny-get-browser-view-status":{"identifier":"deny-get-browser-view-status","description":"Denies the get_browser_view_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_browser_view_status"]}},"deny-get-container-info":{"identifier":"deny-get-container-info","description":"Denies the get_container_info command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_info"]}},"deny-get-container-page-state":{"identifier":"deny-get-container-page-state","description":"Denies the get_container_page_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_page_state"]}},"deny-get-container-staleness":{"identifier":"deny-get-container-staleness","description":"Denies the get_container_staleness command without any pre-configured scope.","commands":{"allow":[],"deny":["get_container_staleness"]}},"deny-get-gateway-auth-token":{"identifier":"deny-get-gateway-auth-token","description":"Denies the get_gateway_auth_token command without any pre-configured scope.","commands":{"allow":[],"deny":["get_gateway_auth_token"]}},"deny-get-gateway-status":{"identifier":"deny-get-gateway-status","description":"Denies the get_gateway_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_gateway_status"]}},"deny-get-help-content":{"identifier":"deny-get-help-content","description":"Denies the get_help_content command without any pre-configured scope.","commands":{"allow":[],"deny":["get_help_content"]}},"deny-get-marketplace-sync-report":{"identifier":"deny-get-marketplace-sync-report","description":"Denies the get_marketplace_sync_report command without any pre-configured scope.","commands":{"allow":[],"deny":["get_marketplace_sync_report"]}},"deny-get-migration-state":{"identifier":"deny-get-migration-state","description":"Denies the get_migration_state command without any pre-configured scope.","commands":{"allow":[],"deny":["get_migration_state"]}},"deny-get-scheduled-task-log":{"identifier":"deny-get-scheduled-task-log","description":"Denies the get_scheduled_task_log command without any pre-configured scope.","commands":{"allow":[],"deny":["get_scheduled_task_log"]}},"deny-get-scheduler-notifications":{"identifier":"deny-get-scheduler-notifications","description":"Denies the get_scheduler_notifications command without any pre-configured scope.","commands":{"allow":[],"deny":["get_scheduler_notifications"]}},"deny-get-settings":{"identifier":"deny-get-settings","description":"Denies the get_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["get_settings"]}},"deny-get-stt-status":{"identifier":"deny-get-stt-status","description":"Denies the get_stt_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_stt_status"]}},"deny-get-web-terminal-status":{"identifier":"deny-get-web-terminal-status","description":"Denies the get_web_terminal_status command without any pre-configured scope.","commands":{"allow":[],"deny":["get_web_terminal_status"]}},"deny-has-claude-token":{"identifier":"deny-has-claude-token","description":"Denies the has_claude_token command without any pre-configured scope.","commands":{"allow":[],"deny":["has_claude_token"]}},"deny-inspect-ca-cert-path":{"identifier":"deny-inspect-ca-cert-path","description":"Denies the inspect_ca_cert_path command without any pre-configured scope.","commands":{"allow":[],"deny":["inspect_ca_cert_path"]}},"deny-install-browser-view-browser":{"identifier":"deny-install-browser-view-browser","description":"Denies the install_browser_view_browser command without any pre-configured scope.","commands":{"allow":[],"deny":["install_browser_view_browser"]}},"deny-install-browser-view-support":{"identifier":"deny-install-browser-view-support","description":"Denies the install_browser_view_support command without any pre-configured scope.","commands":{"allow":[],"deny":["install_browser_view_support"]}},"deny-install-marketplace-item":{"identifier":"deny-install-marketplace-item","description":"Denies the install_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["install_marketplace_item"]}},"deny-list-aws-profiles":{"identifier":"deny-list-aws-profiles","description":"Denies the list_aws_profiles command without any pre-configured scope.","commands":{"allow":[],"deny":["list_aws_profiles"]}},"deny-list-claude-sessions":{"identifier":"deny-list-claude-sessions","description":"Denies the list_claude_sessions command without any pre-configured scope.","commands":{"allow":[],"deny":["list_claude_sessions"]}},"deny-list-container-capabilities":{"identifier":"deny-list-container-capabilities","description":"Denies the list_container_capabilities command without any pre-configured scope.","commands":{"allow":[],"deny":["list_container_capabilities"]}},"deny-list-container-files":{"identifier":"deny-list-container-files","description":"Denies the list_container_files command without any pre-configured scope.","commands":{"allow":[],"deny":["list_container_files"]}},"deny-list-marketplace-snapshots":{"identifier":"deny-list-marketplace-snapshots","description":"Denies the list_marketplace_snapshots command without any pre-configured scope.","commands":{"allow":[],"deny":["list_marketplace_snapshots"]}},"deny-list-marketplace-updates":{"identifier":"deny-list-marketplace-updates","description":"Denies the list_marketplace_updates command without any pre-configured scope.","commands":{"allow":[],"deny":["list_marketplace_updates"]}},"deny-list-notes":{"identifier":"deny-list-notes","description":"Denies the list_notes command without any pre-configured scope.","commands":{"allow":[],"deny":["list_notes"]}},"deny-list-projects":{"identifier":"deny-list-projects","description":"Denies the list_projects command without any pre-configured scope.","commands":{"allow":[],"deny":["list_projects"]}},"deny-list-scheduled-tasks":{"identifier":"deny-list-scheduled-tasks","description":"Denies the list_scheduled_tasks command without any pre-configured scope.","commands":{"allow":[],"deny":["list_scheduled_tasks"]}},"deny-marketplace-gh-host-available":{"identifier":"deny-marketplace-gh-host-available","description":"Denies the marketplace_gh_host_available command without any pre-configured scope.","commands":{"allow":[],"deny":["marketplace_gh_host_available"]}},"deny-marketplace-item-diff":{"identifier":"deny-marketplace-item-diff","description":"Denies the marketplace_item_diff command without any pre-configured scope.","commands":{"allow":[],"deny":["marketplace_item_diff"]}},"deny-migrate-project-to-base":{"identifier":"deny-migrate-project-to-base","description":"Denies the migrate_project_to_base command without any pre-configured scope.","commands":{"allow":[],"deny":["migrate_project_to_base"]}},"deny-onboard-aws-user":{"identifier":"deny-onboard-aws-user","description":"Denies the onboard_aws_user command without any pre-configured scope.","commands":{"allow":[],"deny":["onboard_aws_user"]}},"deny-open-browser-view-popout":{"identifier":"deny-open-browser-view-popout","description":"Denies the open_browser_view_popout command without any pre-configured scope.","commands":{"allow":[],"deny":["open_browser_view_popout"]}},"deny-open-file-viewer":{"identifier":"deny-open-file-viewer","description":"Denies the open_file_viewer command without any pre-configured scope.","commands":{"allow":[],"deny":["open_file_viewer"]}},"deny-open-page-in-container-browser":{"identifier":"deny-open-page-in-container-browser","description":"Denies the open_page_in_container_browser command without any pre-configured scope.","commands":{"allow":[],"deny":["open_page_in_container_browser"]}},"deny-open-terminal-session":{"identifier":"deny-open-terminal-session","description":"Denies the open_terminal_session command without any pre-configured scope.","commands":{"allow":[],"deny":["open_terminal_session"]}},"deny-open-url-external":{"identifier":"deny-open-url-external","description":"Denies the open_url_external command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url_external"]}},"deny-paste-image-to-terminal":{"identifier":"deny-paste-image-to-terminal","description":"Denies the paste_image_to_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["paste_image_to_terminal"]}},"deny-preview-settings-import":{"identifier":"deny-preview-settings-import","description":"Denies the preview_settings_import command without any pre-configured scope.","commands":{"allow":[],"deny":["preview_settings_import"]}},"deny-pull-gateway-image":{"identifier":"deny-pull-gateway-image","description":"Denies the pull_gateway_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_gateway_image"]}},"deny-pull-image":{"identifier":"deny-pull-image","description":"Denies the pull_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_image"]}},"deny-pull-stt-image":{"identifier":"deny-pull-stt-image","description":"Denies the pull_stt_image command without any pre-configured scope.","commands":{"allow":[],"deny":["pull_stt_image"]}},"deny-push-aws-saved-state":{"identifier":"deny-push-aws-saved-state","description":"Denies the push_aws_saved_state command without any pre-configured scope.","commands":{"allow":[],"deny":["push_aws_saved_state"]}},"deny-read-container-file":{"identifier":"deny-read-container-file","description":"Denies the read_container_file command without any pre-configured scope.","commands":{"allow":[],"deny":["read_container_file"]}},"deny-rebuild-project-container":{"identifier":"deny-rebuild-project-container","description":"Denies the rebuild_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["rebuild_project_container"]}},"deny-reconcile-aws-projects":{"identifier":"deny-reconcile-aws-projects","description":"Denies the reconcile_aws_projects command without any pre-configured scope.","commands":{"allow":[],"deny":["reconcile_aws_projects"]}},"deny-reconcile-project-statuses":{"identifier":"deny-reconcile-project-statuses","description":"Denies the reconcile_project_statuses command without any pre-configured scope.","commands":{"allow":[],"deny":["reconcile_project_statuses"]}},"deny-refresh-marketplaces":{"identifier":"deny-refresh-marketplaces","description":"Denies the refresh_marketplaces command without any pre-configured scope.","commands":{"allow":[],"deny":["refresh_marketplaces"]}},"deny-regenerate-gateway-auth-token":{"identifier":"deny-regenerate-gateway-auth-token","description":"Denies the regenerate_gateway_auth_token command without any pre-configured scope.","commands":{"allow":[],"deny":["regenerate_gateway_auth_token"]}},"deny-regenerate-web-terminal-token":{"identifier":"deny-regenerate-web-terminal-token","description":"Denies the regenerate_web_terminal_token command without any pre-configured scope.","commands":{"allow":[],"deny":["regenerate_web_terminal_token"]}},"deny-remove-aws-resources":{"identifier":"deny-remove-aws-resources","description":"Denies the remove_aws_resources command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_aws_resources"]}},"deny-remove-host-connection":{"identifier":"deny-remove-host-connection","description":"Denies the remove_host_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_host_connection"]}},"deny-remove-marketplace":{"identifier":"deny-remove-marketplace","description":"Denies the remove_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_marketplace"]}},"deny-remove-marketplace-account":{"identifier":"deny-remove-marketplace-account","description":"Denies the remove_marketplace_account command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_marketplace_account"]}},"deny-remove-project":{"identifier":"deny-remove-project","description":"Denies the remove_project command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_project"]}},"deny-remove-scheduled-task":{"identifier":"deny-remove-scheduled-task","description":"Denies the remove_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_scheduled_task"]}},"deny-rename-container-path":{"identifier":"deny-rename-container-path","description":"Denies the rename_container_path command without any pre-configured scope.","commands":{"allow":[],"deny":["rename_container_path"]}},"deny-repair-aws-environment":{"identifier":"deny-repair-aws-environment","description":"Denies the repair_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["repair_aws_environment"]}},"deny-rollback-migration":{"identifier":"deny-rollback-migration","description":"Denies the rollback_migration command without any pre-configured scope.","commands":{"allow":[],"deny":["rollback_migration"]}},"deny-run-docker-install":{"identifier":"deny-run-docker-install","description":"Denies the run_docker_install command without any pre-configured scope.","commands":{"allow":[],"deny":["run_docker_install"]}},"deny-run-scheduled-task-now":{"identifier":"deny-run-scheduled-task-now","description":"Denies the run_scheduled_task_now command without any pre-configured scope.","commands":{"allow":[],"deny":["run_scheduled_task_now"]}},"deny-save-aws-admin-bundle":{"identifier":"deny-save-aws-admin-bundle","description":"Denies the save_aws_admin_bundle command without any pre-configured scope.","commands":{"allow":[],"deny":["save_aws_admin_bundle"]}},"deny-save-note":{"identifier":"deny-save-note","description":"Denies the save_note command without any pre-configured scope.","commands":{"allow":[],"deny":["save_note"]}},"deny-send-audio-data":{"identifier":"deny-send-audio-data","description":"Denies the send_audio_data command without any pre-configured scope.","commands":{"allow":[],"deny":["send_audio_data"]}},"deny-set-auth-bridge-enabled":{"identifier":"deny-set-auth-bridge-enabled","description":"Denies the set_auth_bridge_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_auth_bridge_enabled"]}},"deny-set-browser-view-enabled":{"identifier":"deny-set-browser-view-enabled","description":"Denies the set_browser_view_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_enabled"]}},"deny-set-browser-view-match-window":{"identifier":"deny-set-browser-view-match-window","description":"Denies the set_browser_view_match_window command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_match_window"]}},"deny-set-browser-view-popout-always-on-top":{"identifier":"deny-set-browser-view-popout-always-on-top","description":"Denies the set_browser_view_popout_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_browser_view_popout_always_on_top"]}},"deny-set-container-page-viewport":{"identifier":"deny-set-container-page-viewport","description":"Denies the set_container_page_viewport command without any pre-configured scope.","commands":{"allow":[],"deny":["set_container_page_viewport"]}},"deny-set-gateway-api-key":{"identifier":"deny-set-gateway-api-key","description":"Denies the set_gateway_api_key command without any pre-configured scope.","commands":{"allow":[],"deny":["set_gateway_api_key"]}},"deny-set-global-item-disabled":{"identifier":"deny-set-global-item-disabled","description":"Denies the set_global_item_disabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_global_item_disabled"]}},"deny-set-scheduled-task-enabled":{"identifier":"deny-set-scheduled-task-enabled","description":"Denies the set_scheduled_task_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_scheduled_task_enabled"]}},"deny-start-audio-bridge":{"identifier":"deny-start-audio-bridge","description":"Denies the start_audio_bridge command without any pre-configured scope.","commands":{"allow":[],"deny":["start_audio_bridge"]}},"deny-start-gateway":{"identifier":"deny-start-gateway","description":"Denies the start_gateway command without any pre-configured scope.","commands":{"allow":[],"deny":["start_gateway"]}},"deny-start-marketplace-gh-container-login":{"identifier":"deny-start-marketplace-gh-container-login","description":"Denies the start_marketplace_gh_container_login command without any pre-configured scope.","commands":{"allow":[],"deny":["start_marketplace_gh_container_login"]}},"deny-start-project-container":{"identifier":"deny-start-project-container","description":"Denies the start_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["start_project_container"]}},"deny-start-stt":{"identifier":"deny-start-stt","description":"Denies the start_stt command without any pre-configured scope.","commands":{"allow":[],"deny":["start_stt"]}},"deny-start-web-terminal":{"identifier":"deny-start-web-terminal","description":"Denies the start_web_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["start_web_terminal"]}},"deny-stop-audio-bridge":{"identifier":"deny-stop-audio-bridge","description":"Denies the stop_audio_bridge command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_audio_bridge"]}},"deny-stop-gateway":{"identifier":"deny-stop-gateway","description":"Denies the stop_gateway command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_gateway"]}},"deny-stop-project-container":{"identifier":"deny-stop-project-container","description":"Denies the stop_project_container command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_project_container"]}},"deny-stop-stt":{"identifier":"deny-stop-stt","description":"Denies the stop_stt command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_stt"]}},"deny-stop-web-terminal":{"identifier":"deny-stop-web-terminal","description":"Denies the stop_web_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["stop_web_terminal"]}},"deny-submit-claude-token-code":{"identifier":"deny-submit-claude-token-code","description":"Denies the submit_claude_token_code command without any pre-configured scope.","commands":{"allow":[],"deny":["submit_claude_token_code"]}},"deny-sweep-claude-token-snapshots":{"identifier":"deny-sweep-claude-token-snapshots","description":"Denies the sweep_claude_token_snapshots command without any pre-configured scope.","commands":{"allow":[],"deny":["sweep_claude_token_snapshots"]}},"deny-terminal-input":{"identifier":"deny-terminal-input","description":"Denies the terminal_input command without any pre-configured scope.","commands":{"allow":[],"deny":["terminal_input"]}},"deny-terminal-resize":{"identifier":"deny-terminal-resize","description":"Denies the terminal_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["terminal_resize"]}},"deny-test-marketplace-account":{"identifier":"deny-test-marketplace-account","description":"Denies the test_marketplace_account command without any pre-configured scope.","commands":{"allow":[],"deny":["test_marketplace_account"]}},"deny-transcribe-audio":{"identifier":"deny-transcribe-audio","description":"Denies the transcribe_audio command without any pre-configured scope.","commands":{"allow":[],"deny":["transcribe_audio"]}},"deny-uninstall-marketplace-item":{"identifier":"deny-uninstall-marketplace-item","description":"Denies the uninstall_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["uninstall_marketplace_item"]}},"deny-unlock-aws-state":{"identifier":"deny-unlock-aws-state","description":"Denies the unlock_aws_state command without any pre-configured scope.","commands":{"allow":[],"deny":["unlock_aws_state"]}},"deny-update-aws-connection":{"identifier":"deny-update-aws-connection","description":"Denies the update_aws_connection command without any pre-configured scope.","commands":{"allow":[],"deny":["update_aws_connection"]}},"deny-update-aws-environment":{"identifier":"deny-update-aws-environment","description":"Denies the update_aws_environment command without any pre-configured scope.","commands":{"allow":[],"deny":["update_aws_environment"]}},"deny-update-marketplace":{"identifier":"deny-update-marketplace","description":"Denies the update_marketplace command without any pre-configured scope.","commands":{"allow":[],"deny":["update_marketplace"]}},"deny-update-marketplace-item":{"identifier":"deny-update-marketplace-item","description":"Denies the update_marketplace_item command without any pre-configured scope.","commands":{"allow":[],"deny":["update_marketplace_item"]}},"deny-update-project":{"identifier":"deny-update-project","description":"Denies the update_project command without any pre-configured scope.","commands":{"allow":[],"deny":["update_project"]}},"deny-update-scheduled-task":{"identifier":"deny-update-scheduled-task","description":"Denies the update_scheduled_task command without any pre-configured scope.","commands":{"allow":[],"deny":["update_scheduled_task"]}},"deny-update-settings":{"identifier":"deny-update-settings","description":"Denies the update_settings command without any pre-configured scope.","commands":{"allow":[],"deny":["update_settings"]}},"deny-upload-files-to-container":{"identifier":"deny-upload-files-to-container","description":"Denies the upload_files_to_container command without any pre-configured scope.","commands":{"allow":[],"deny":["upload_files_to_container"]}},"deny-upload-host-file-to-terminal":{"identifier":"deny-upload-host-file-to-terminal","description":"Denies the upload_host_file_to_terminal command without any pre-configured scope.","commands":{"allow":[],"deny":["upload_host_file_to_terminal"]}},"deny-viewer-choose-file":{"identifier":"deny-viewer-choose-file","description":"Denies the viewer_choose_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_choose_file"]}},"deny-viewer-get-state":{"identifier":"deny-viewer-get-state","description":"Denies the viewer_get_state command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_get_state"]}},"deny-viewer-poll-file":{"identifier":"deny-viewer-poll-file","description":"Denies the viewer_poll_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_poll_file"]}},"deny-viewer-read-file":{"identifier":"deny-viewer-read-file","description":"Denies the viewer_read_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_read_file"]}},"deny-viewer-write-file":{"identifier":"deny-viewer-write-file","description":"Denies the viewer_write_file command without any pre-configured scope.","commands":{"allow":[],"deny":["viewer_write_file"]}}},"permission_sets":{},"global_scope_schema":null},"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null},"dialog":{"default_permission":{"identifier":"default","description":"This permission set configures the types of dialogs\navailable from the dialog plugin.\n\n#### Granted Permissions\n\nAll dialog types are enabled.\n\n\n","permissions":["allow-message","allow-save","allow-open"]},"permissions":{"allow-ask":{"identifier":"allow-ask","description":"Enables the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-confirm":{"identifier":"allow-confirm","description":"Enables the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `allow-message` and will be removed in v3)","commands":{"allow":["message"],"deny":[]}},"allow-message":{"identifier":"allow-message","description":"Enables the message command without any pre-configured scope.","commands":{"allow":["message"],"deny":[]}},"allow-open":{"identifier":"allow-open","description":"Enables the open command without any pre-configured scope.","commands":{"allow":["open"],"deny":[]}},"allow-save":{"identifier":"allow-save","description":"Enables the save command without any pre-configured scope.","commands":{"allow":["save"],"deny":[]}},"deny-ask":{"identifier":"deny-ask","description":"Denies the ask command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-confirm":{"identifier":"deny-confirm","description":"Denies the confirm command without any pre-configured scope. (**DEPRECATED**: This is now an alias to `deny-message` and will be removed in v3)","commands":{"allow":[],"deny":["message"]}},"deny-message":{"identifier":"deny-message","description":"Denies the message command without any pre-configured scope.","commands":{"allow":[],"deny":["message"]}},"deny-open":{"identifier":"deny-open","description":"Denies the open command without any pre-configured scope.","commands":{"allow":[],"deny":["open"]}},"deny-save":{"identifier":"deny-save","description":"Denies the save command without any pre-configured scope.","commands":{"allow":[],"deny":["save"]}}},"permission_sets":{},"global_scope_schema":null},"opener":{"default_permission":{"identifier":"default","description":"This permission set allows opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application\nas well as reveal file in directories using default file explorer","permissions":["allow-open-url","allow-reveal-item-in-dir","allow-default-urls"]},"permissions":{"allow-default-urls":{"identifier":"allow-default-urls","description":"This enables opening `mailto:`, `tel:`, `https://` and `http://` urls using their default application.","commands":{"allow":[],"deny":[]},"scope":{"allow":[{"url":"mailto:*"},{"url":"tel:*"},{"url":"http://*"},{"url":"https://*"}]}},"allow-open-path":{"identifier":"allow-open-path","description":"Enables the open_path command without any pre-configured scope.","commands":{"allow":["open_path"],"deny":[]}},"allow-open-url":{"identifier":"allow-open-url","description":"Enables the open_url command without any pre-configured scope.","commands":{"allow":["open_url"],"deny":[]}},"allow-reveal-item-in-dir":{"identifier":"allow-reveal-item-in-dir","description":"Enables the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":["reveal_item_in_dir"],"deny":[]}},"deny-open-path":{"identifier":"deny-open-path","description":"Denies the open_path command without any pre-configured scope.","commands":{"allow":[],"deny":["open_path"]}},"deny-open-url":{"identifier":"deny-open-url","description":"Denies the open_url command without any pre-configured scope.","commands":{"allow":[],"deny":["open_url"]}},"deny-reveal-item-in-dir":{"identifier":"deny-reveal-item-in-dir","description":"Denies the reveal_item_in_dir command without any pre-configured scope.","commands":{"allow":[],"deny":["reveal_item_in_dir"]}}},"permission_sets":{},"global_scope_schema":{"$schema":"http://json-schema.org/draft-07/schema#","anyOf":[{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this url with, for example: firefox."},"url":{"description":"A URL that can be opened by the webview when using the Opener APIs.\n\nWildcards can be used following the UNIX glob pattern.\n\nExamples:\n\n- \"https://*\" : allows all HTTPS origin\n\n- \"https://*.github.com/tauri-apps/tauri\": allows any subdomain of \"github.com\" with the \"tauri-apps/api\" path\n\n- \"https://myapi.service.com/users/*\": allows access to any URLs that begins with \"https://myapi.service.com/users/\"","type":"string"}},"required":["url"],"type":"object"},{"properties":{"app":{"allOf":[{"$ref":"#/definitions/Application"}],"description":"An application to open this path with, for example: xdg-open."},"path":{"description":"A path that can be opened by the webview when using the Opener APIs.\n\nThe pattern can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$APP`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.","type":"string"}},"required":["path"],"type":"object"}],"definitions":{"Application":{"anyOf":[{"description":"Open in default application.","type":"null"},{"description":"If true, allow open with any application.","type":"boolean"},{"description":"Allow specific application to open with.","type":"string"}],"description":"Opener scope application."}},"description":"Opener scope entry.","title":"OpenerScopeEntry"}}} \ No newline at end of file diff --git a/app/src-tauri/gen/schemas/capabilities.json b/app/src-tauri/gen/schemas/capabilities.json index 23dbf94..1be6a10 100644 --- a/app/src-tauri/gen/schemas/capabilities.json +++ b/app/src-tauri/gen/schemas/capabilities.json @@ -1 +1 @@ -{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate field and Backup. Two commands still take a host path over IPC as a string — the terminal drop and `download_container_backup` — and for those `validate_host_path` is the boundary rather than defence in depth. This file is the reviewed threat model of record, so keep this census accurate: a stale reference here is worse than none. Note that dragging files *into* the app is unaffected: `dragDropEnabled` and `onDragDropEvent` are core webview behaviour and need no grant. Historical note kept because it is easy to re-introduce: the `store:*` grants were removed — nothing in `app/src` uses `@tauri-apps/plugin-store`, and the plugin's `resolve_store_path` is a `PathBuf::push` against AppData, which `push` discards outright when handed an absolute path, so the grant was an arbitrary host-file read/write primitive (`plugin:store|load` + `set` + `save` on `~/.claude/settings.json` is host code execution). A second capability file, `file-viewer.json`, covers the `file-viewer-*` windows the terminal file viewer opens on `viewer.html`; it is the only other local-origin window, its grants are listed and justified there, and its one non-obvious grant (`core:window:allow-destroy`) exists because `onCloseRequested` cannot close a window without it. App commands are gated by this file too. `build.rs` declares a Tauri `AppManifest` listing every command in `generate_handler!`, which is what makes tauri 2.11.0 apply the ACL to app commands at all (`webview/mod.rs:1794` skips it when no app manifest exists), and the bare `allow-` entries below are the complete list of app commands the main window may call. `build.rs` refuses to build unless every registered command has exactly one such grant, in the file whose `windows` its name says it belongs to (`viewer_*` in `file-viewer.json`, everything else here), and unless every bare entry names a registered command — so a forgotten, misspelled, duplicated or misfiled grant is a failed `cargo check`, not a feature that dies at runtime with `not allowed by ACL`. `deny-*` is banned by the same check: in tauri 2.11.0 a deny matches regardless of window or origin, so a deny meant for the viewer would deny main too. Hand-written files under `permissions/` are refused for the same reason — they would be grants this census cannot see. Because the census can only vouch for what it reads, `build.rs` also refuses any capability it did not check: anything in `capabilities/` other than a top-level `*.json` file (tauri also loads `.toml`/`.json5` there, and subdirectories), a `webviews` or `remote` key in a capability file (either would extend grants beyond what `windows` says), `app.security.capabilities` declared inline in `tauri.conf.json`, any `tauri..conf.json`, or `TAURI_CONFIG`, and a tauri config in a format the census cannot parse (JSON5, TOML). OS/editor junk (`.DS_Store`, `Thumbs.db`, editor swap files) is recognised and skipped in `capabilities/` and `permissions/` rather than refused, since tauri never loads it either. Each failure names the check that failed (\"stray entry in capabilities/\", \"capabilities declared outside capabilities/\", \"hand-written permission\", …) rather than always reading as a grant/handler mismatch. Known gap: adding a new `tauri..conf.json` to a tree that has already been built once only takes effect on a clean build or in CI — cargo's incremental build has no reason to notice a file that did not exist on the previous build. The `*marketplace*` commands fetch user-configured https git repos on the host and push pinned files into containers; account tokens stay in the OS keychain and never cross IPC outward — the only inbound one is the token pasted into `add_marketplace_token_account`. The pop-out stays capability-less. The Rust label gates in `commands/file_viewer_commands.rs` remain, because the ACL says *which* window may call a command and the label says *whose* registry entry it acts on; they are not redundant. The rules live in `src/command_census.rs`, which is unit-tested, and `src/test/capabilities.test.ts` checks the other direction: that the code that runs in each window imports only the wrappers that window is granted. On the CSP side: `app.security.csp` in `tauri.conf.json` covers the shipped bundle, and there is deliberately no `devCsp`. `npm run tauri dev` loads the main document straight from Vite at `build.devUrl` (`http://localhost:1420`), and Tauri only attaches a CSP to documents it serves itself — `protocol/tauri.rs:217` sets the header on `tauri://` assets, and the dev server is proxied through that protocol only when `PROXY_DEV_SERVER`, which is `cfg!(all(dev, mobile))` and therefore false for every desktop build. A `devCsp` here would be inert config that reads as protection, which is worse than its absence. If a CSP in dev is wanted, the only place that can set one is the Vite dev server's own `server.headers` in `app/vite.config.ts`; it is not set today, and dev is not the shipped configuration.","local":true,"windows":["main"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","core:webview:allow-internal-toggle-devtools","dialog:allow-open","dialog:allow-save","allow-check-docker","allow-check-image-exists","allow-build-image","allow-get-container-info","allow-list-projects","allow-add-project","allow-remove-project","allow-update-project","allow-start-project-container","allow-stop-project-container","allow-check-unsaved-work","allow-aws-task-log","allow-remove-aws-resources","allow-rebuild-project-container","allow-reconcile-project-statuses","allow-reconcile-aws-projects","allow-list-notes","allow-save-note","allow-delete-note","allow-get-container-staleness","allow-migrate-project-to-base","allow-confirm-migration","allow-rollback-migration","allow-get-migration-state","allow-set-auth-bridge-enabled","allow-get-auth-bridge-status","allow-set-browser-view-enabled","allow-get-browser-view-status","allow-check-browser-view-support","allow-install-browser-view-support","allow-install-browser-view-browser","allow-open-browser-view-popout","allow-close-browser-view-popout","allow-get-browser-view-popout-state","allow-set-browser-view-popout-always-on-top","allow-open-page-in-container-browser","allow-set-container-page-viewport","allow-get-container-page-state","allow-close-container-page","allow-set-browser-view-match-window","allow-get-browser-view-match-window","allow-acquire-claude-token","allow-submit-claude-token-code","allow-cancel-claude-token","allow-has-claude-token","allow-clear-claude-token","allow-sweep-claude-token-snapshots","allow-get-settings","allow-update-settings","allow-pull-image","allow-detect-aws-config","allow-inspect-ca-cert-path","allow-list-aws-profiles","allow-add-aws-profile-connection","allow-add-aws-keys-connection","allow-update-aws-connection","allow-remove-host-connection","allow-aws-connection-identity","allow-aws-connection-sso-login","allow-check-aws-permissions","allow-aws-policy-document","allow-detect-aws-environments","allow-deploy-aws-environment","allow-update-aws-environment","allow-repair-aws-environment","allow-destroy-incomplete-aws-environment","allow-unlock-aws-state","allow-follow-aws-deployment","allow-cancel-aws-deployment","allow-push-aws-saved-state","allow-onboard-aws-user","allow-deploy-aws-permissions-boundary","allow-save-aws-admin-bundle","allow-detect-host-timezone","allow-export-settings","allow-preview-settings-import","allow-apply-settings-import","allow-open-terminal-session","allow-terminal-input","allow-terminal-resize","allow-close-terminal-session","allow-paste-image-to-terminal","allow-upload-host-file-to-terminal","allow-start-audio-bridge","allow-send-audio-data","allow-stop-audio-bridge","allow-list-container-files","allow-download-container-backup","allow-download-container-file","allow-upload-files-to-container","allow-read-container-file","allow-rename-container-path","allow-create-container-directory","allow-open-file-viewer","allow-aws-sso-refresh","allow-get-app-version","allow-check-for-updates","allow-check-image-update","allow-get-help-content","allow-open-url-external","allow-detect-install-options","allow-run-docker-install","allow-start-web-terminal","allow-stop-web-terminal","allow-get-web-terminal-status","allow-regenerate-web-terminal-token","allow-get-stt-status","allow-start-stt","allow-stop-stt","allow-build-stt-image","allow-pull-stt-image","allow-transcribe-audio","allow-get-gateway-status","allow-start-gateway","allow-stop-gateway","allow-check-gateway-health","allow-build-gateway-image","allow-pull-gateway-image","allow-set-gateway-api-key","allow-clear-gateway-api-key","allow-get-gateway-auth-token","allow-regenerate-gateway-auth-token","allow-list-claude-sessions","allow-list-container-capabilities","allow-list-scheduled-tasks","allow-add-scheduled-task","allow-update-scheduled-task","allow-get-scheduled-task-log","allow-set-scheduled-task-enabled","allow-run-scheduled-task-now","allow-remove-scheduled-task","allow-get-scheduler-notifications","allow-clear-scheduler-notifications","allow-list-marketplace-snapshots","allow-refresh-marketplaces","allow-add-marketplace","allow-update-marketplace","allow-remove-marketplace","allow-install-marketplace-item","allow-uninstall-marketplace-item","allow-set-global-item-disabled","allow-forget-marketplace-installs","allow-list-marketplace-updates","allow-marketplace-item-diff","allow-update-marketplace-item","allow-apply-marketplace-now","allow-get-marketplace-sync-report","allow-add-marketplace-token-account","allow-add-marketplace-gh-host-account","allow-start-marketplace-gh-container-login","allow-cancel-marketplace-gh-login","allow-test-marketplace-account","allow-remove-marketplace-account","allow-marketplace-gh-host-available"]},"file-viewer":{"identifier":"file-viewer","description":"The terminal file viewer windows (`file-viewer-`, opened by `open_file_viewer` on the app's own `viewer.html`). Same rules as `default.json`, including the layout checks: this file itself must stay a top-level `capabilities/*.json` with no `webviews` or `remote` key, or `build.rs` refuses the build rather than grant something the census cannot see. The five bare `allow-viewer-*` grants are the only app commands a viewer window can invoke: `build.rs` declares the AppManifest that makes tauri enforce that, and refuses any other bare grant in this file. The label gate inside `commands/file_viewer_commands.rs` is still what stops window A acting on window B's registry entry, because the ACL only decides which window may call. The rest of this file is the plugin-command surface a compromised viewer webview could reach, and it is the smallest one that lets the window work. `core:event:allow-listen`/`allow-unlisten` are for `file-viewer-goto` (Rust → this window; the viewer subscribes through `getCurrentWindow().listen`, because a bare `listen()` in *any* window receives an `emit_to`). `core:window:allow-destroy` is not optional: `getCurrentWindow().onCloseRequested` in @tauri-apps/api 2.11 makes Rust `prevent_close()` whenever a JS listener exists and then calls `destroy()` itself, so without this grant the window's X button does nothing once the unsaved-changes guard is installed. `allow-close` is deliberately absent — nothing calls it, and `destroy` is the only exit. No `set-title`/`set-focus`/`unminimize`: those are done from Rust when a second click targets an already-open file. `core:webview:allow-internal-toggle-devtools` is the same dev-only convenience `default.json` carries.","local":true,"windows":["file-viewer-*"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","core:window:allow-destroy","core:webview:allow-internal-toggle-devtools","allow-viewer-get-state","allow-viewer-choose-file","allow-viewer-read-file","allow-viewer-poll-file","allow-viewer-write-file"]}} \ No newline at end of file +{"default":{"identifier":"default","description":"Default capabilities for Triple-C. Every entry here is an IPC command a compromised webview can call directly, so the set is an enumeration of what `app/src` actually invokes — plugin and core grants verified against tauri 2.11.0's `PLUGINS` table in tauri's own `build.rs` rather than assumed from a plugin's `default` set, app-command grants (the bare `allow-*` entries) cross-checked by this crate's `build.rs` against `generate_handler!`. `core:default` in particular is NOT used: it is an alias for `core:{path,event,window,webview,app,image,resources,menu,tray}:default`, and `core:image:default` carries `allow-from-path`, whose handler (`tauri-2.11.0/src/image/plugin.rs:41` → `src/image/mod.rs:96`) is a bare `std::fs::read(path)` with no scope mechanism of any kind. Nothing imports `@tauri-apps/api/image`, so the whole plugin is dropped rather than scoped — there is nothing to scope it with. `core:menu` and `core:tray` are dropped for the same reason (no menu, no tray icon); `core:window` and `core:path` because nothing imports them; `core:resources:allow-close` because no frontend value is a `Resource`; and `core:event`'s `allow-emit`/`allow-emit-to` because the frontend only ever *listens* — every emit in this app originates in Rust. Three notes on what is deliberately kept or accepted: (1) `core:webview:allow-internal-toggle-devtools` is not called by `app/src` at all — it is called by Tauri's own injected `toggle-devtools.js`, which binds Ctrl/Cmd+Shift+I. Both that script and the command behind it are `#[cfg(any(debug_assertions, feature = \"devtools\"))]`, so this grant is a `tauri dev` convenience that does not exist in a release bundle. (2) `opener:allow-open-url` is **gone**. It could not be narrowed by host — `TerminalView`'s `WebLinksAddon` opens links Claude printed inside the container, which are arbitrary by construction, so a host allowlist would have deleted the feature rather than bounded it — and it was carried here as an accepted residual risk: a compromised webview could make the OS open an attacker-chosen http(s) URL, an outbound channel. That risk is now closed rather than recorded. Every host-browser open in the app goes through the `open_url_external` command in `url_open.rs`, which exists because the AppImage environment leaks into a cold-launched browser on Linux (triple-c#34) and which re-validates the URL in Rust — scheme allowlist, no embedded credentials, no control characters, length cap, ASCII asserted before `execvp`. On macOS and Windows that command reaches the same plugin as before, via `OpenerExt::open_url`, whose desktop implementation calls `crate::open::open` directly and is therefore not gated by this file at all (`tauri-plugin-opener-2.5.3/src/lib.rs:60`). The plugin stays a dependency for exactly that reason; what is removed is the webview's ability to reach it without passing the Rust validation. (3) `drag:allow-start-drag` is **gone**, together with the OS drag-out it existed for. It could not be scoped — `tauri-plugin-drag` takes the item paths from the caller and has no scope mechanism, so a compromised webview could call `startDrag({ item: ['~/.ssh/id_rsa'] })` against any host path the user can read — and it was carried as an accepted residual risk for one gesture. Drag-out was held back for separate hardening (see branch `hold/disk-and-dragout`) and the plugin is no longer a dependency. Getting a file *out* of a container is either \"Back up container\" on the project's Overview tab, which archives a tree through the Docker API, or the Files tab's per-row \"Save to host…\", which copies one file; getting one *in* is a drop on the Terminal or the Files tab's \"Upload…\". None of the four touches this permission. The Files tab's two are worth separating out here, because they are the only host-path commands in the app whose dialog is opened by **Rust** rather than by the webview — `pick_save_path` and `pick_files_to_upload` in `commands/file_commands.rs` drive `tauri-plugin-dialog` from the backend, so a compromised webview can ask for a picker and nothing more: it cannot name a host path as an *input* to either command. Be precise about the limit of that claim — host paths do still travel outward in error text (`Failed to create /home/j/Documents/x.txt.triple-c-part-1a2b3c4d: Permission denied`), including canonicalized ones, which disclose symlink targets. That is accepted; the app already hands the webview the project paths. What is closed is the direction that mattered — the webview naming where bytes go. That is the shape an earlier revision of this file named as the honest one if the Files tab ever regained host I/O, and it is the shape it regained it in. The `dialog:allow-open` / `dialog:allow-save` grants below are therefore *not* what those two use; they remain for the frontend pickers in Add Project, the Config tab's workspace and access sections, the CA-certificate field and Backup. Two commands still take a host path over IPC as a string — the terminal drop and `download_container_backup` — and for those `validate_host_path` is the boundary rather than defence in depth. This file is the reviewed threat model of record, so keep this census accurate: a stale reference here is worse than none. Note that dragging files *into* the app is unaffected: `dragDropEnabled` and `onDragDropEvent` are core webview behaviour and need no grant. Historical note kept because it is easy to re-introduce: the `store:*` grants were removed — nothing in `app/src` uses `@tauri-apps/plugin-store`, and the plugin's `resolve_store_path` is a `PathBuf::push` against AppData, which `push` discards outright when handed an absolute path, so the grant was an arbitrary host-file read/write primitive (`plugin:store|load` + `set` + `save` on `~/.claude/settings.json` is host code execution). A second capability file, `file-viewer.json`, covers the `file-viewer-*` windows the terminal file viewer opens on `viewer.html`; it is the only other local-origin window, its grants are listed and justified there, and its one non-obvious grant (`core:window:allow-destroy`) exists because `onCloseRequested` cannot close a window without it. App commands are gated by this file too. `build.rs` declares a Tauri `AppManifest` listing every command in `generate_handler!`, which is what makes tauri 2.11.0 apply the ACL to app commands at all (`webview/mod.rs:1794` skips it when no app manifest exists), and the bare `allow-` entries below are the complete list of app commands the main window may call. `build.rs` refuses to build unless every registered command has exactly one such grant, in the file whose `windows` its name says it belongs to (`viewer_*` in `file-viewer.json`, everything else here), and unless every bare entry names a registered command — so a forgotten, misspelled, duplicated or misfiled grant is a failed `cargo check`, not a feature that dies at runtime with `not allowed by ACL`. `deny-*` is banned by the same check: in tauri 2.11.0 a deny matches regardless of window or origin, so a deny meant for the viewer would deny main too. Hand-written files under `permissions/` are refused for the same reason — they would be grants this census cannot see. Because the census can only vouch for what it reads, `build.rs` also refuses any capability it did not check: anything in `capabilities/` other than a top-level `*.json` file (tauri also loads `.toml`/`.json5` there, and subdirectories), a `webviews` or `remote` key in a capability file (either would extend grants beyond what `windows` says), `app.security.capabilities` declared inline in `tauri.conf.json`, any `tauri..conf.json`, or `TAURI_CONFIG`, and a tauri config in a format the census cannot parse (JSON5, TOML). OS/editor junk (`.DS_Store`, `Thumbs.db`, editor swap files) is recognised and skipped in `capabilities/` and `permissions/` rather than refused, since tauri never loads it either. Each failure names the check that failed (\"stray entry in capabilities/\", \"capabilities declared outside capabilities/\", \"hand-written permission\", …) rather than always reading as a grant/handler mismatch. Known gap: adding a new `tauri..conf.json` to a tree that has already been built once only takes effect on a clean build or in CI — cargo's incremental build has no reason to notice a file that did not exist on the previous build. The `*marketplace*` commands fetch user-configured https git repos on the host and push pinned files into containers; account tokens stay in the OS keychain and never cross IPC outward — the only inbound one is the token pasted into `add_marketplace_token_account`. The pop-out stays capability-less. The Rust label gates in `commands/file_viewer_commands.rs` remain, because the ACL says *which* window may call a command and the label says *whose* registry entry it acts on; they are not redundant. The rules live in `src/command_census.rs`, which is unit-tested, and `src/test/capabilities.test.ts` checks the other direction: that the code that runs in each window imports only the wrappers that window is granted. On the CSP side: `app.security.csp` in `tauri.conf.json` covers the shipped bundle, and there is deliberately no `devCsp`. `npm run tauri dev` loads the main document straight from Vite at `build.devUrl` (`http://localhost:1420`), and Tauri only attaches a CSP to documents it serves itself — `protocol/tauri.rs:217` sets the header on `tauri://` assets, and the dev server is proxied through that protocol only when `PROXY_DEV_SERVER`, which is `cfg!(all(dev, mobile))` and therefore false for every desktop build. A `devCsp` here would be inert config that reads as protection, which is worse than its absence. If a CSP in dev is wanted, the only place that can set one is the Vite dev server's own `server.headers` in `app/vite.config.ts`; it is not set today, and dev is not the shipped configuration.","local":true,"windows":["main"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","core:webview:allow-internal-toggle-devtools","dialog:allow-open","dialog:allow-save","allow-check-docker","allow-check-image-exists","allow-build-image","allow-get-container-info","allow-list-projects","allow-add-project","allow-remove-project","allow-update-project","allow-start-project-container","allow-stop-project-container","allow-check-unsaved-work","allow-aws-task-log","allow-aws-workspace-status","allow-aws-environment-max-hours","allow-remove-aws-resources","allow-rebuild-project-container","allow-reconcile-project-statuses","allow-reconcile-aws-projects","allow-list-notes","allow-save-note","allow-delete-note","allow-get-container-staleness","allow-migrate-project-to-base","allow-confirm-migration","allow-rollback-migration","allow-get-migration-state","allow-set-auth-bridge-enabled","allow-get-auth-bridge-status","allow-set-browser-view-enabled","allow-get-browser-view-status","allow-check-browser-view-support","allow-install-browser-view-support","allow-install-browser-view-browser","allow-open-browser-view-popout","allow-close-browser-view-popout","allow-get-browser-view-popout-state","allow-set-browser-view-popout-always-on-top","allow-open-page-in-container-browser","allow-set-container-page-viewport","allow-get-container-page-state","allow-close-container-page","allow-set-browser-view-match-window","allow-get-browser-view-match-window","allow-acquire-claude-token","allow-submit-claude-token-code","allow-cancel-claude-token","allow-has-claude-token","allow-clear-claude-token","allow-sweep-claude-token-snapshots","allow-get-settings","allow-update-settings","allow-pull-image","allow-detect-aws-config","allow-inspect-ca-cert-path","allow-list-aws-profiles","allow-add-aws-profile-connection","allow-add-aws-keys-connection","allow-update-aws-connection","allow-remove-host-connection","allow-aws-connection-identity","allow-aws-connection-sso-login","allow-check-aws-permissions","allow-aws-policy-document","allow-aws-cost-estimate","allow-detect-aws-environments","allow-deploy-aws-environment","allow-update-aws-environment","allow-repair-aws-environment","allow-destroy-incomplete-aws-environment","allow-unlock-aws-state","allow-follow-aws-deployment","allow-cancel-aws-deployment","allow-push-aws-saved-state","allow-onboard-aws-user","allow-deploy-aws-permissions-boundary","allow-save-aws-admin-bundle","allow-detect-host-timezone","allow-export-settings","allow-preview-settings-import","allow-apply-settings-import","allow-open-terminal-session","allow-terminal-input","allow-terminal-resize","allow-close-terminal-session","allow-paste-image-to-terminal","allow-upload-host-file-to-terminal","allow-start-audio-bridge","allow-send-audio-data","allow-stop-audio-bridge","allow-list-container-files","allow-download-container-backup","allow-download-container-file","allow-upload-files-to-container","allow-read-container-file","allow-rename-container-path","allow-create-container-directory","allow-open-file-viewer","allow-aws-sso-refresh","allow-get-app-version","allow-check-for-updates","allow-check-image-update","allow-get-help-content","allow-open-url-external","allow-detect-install-options","allow-run-docker-install","allow-start-web-terminal","allow-stop-web-terminal","allow-get-web-terminal-status","allow-regenerate-web-terminal-token","allow-get-stt-status","allow-start-stt","allow-stop-stt","allow-build-stt-image","allow-pull-stt-image","allow-transcribe-audio","allow-get-gateway-status","allow-start-gateway","allow-stop-gateway","allow-check-gateway-health","allow-build-gateway-image","allow-pull-gateway-image","allow-set-gateway-api-key","allow-clear-gateway-api-key","allow-get-gateway-auth-token","allow-regenerate-gateway-auth-token","allow-list-claude-sessions","allow-list-container-capabilities","allow-list-scheduled-tasks","allow-add-scheduled-task","allow-update-scheduled-task","allow-get-scheduled-task-log","allow-set-scheduled-task-enabled","allow-run-scheduled-task-now","allow-remove-scheduled-task","allow-get-scheduler-notifications","allow-clear-scheduler-notifications","allow-list-marketplace-snapshots","allow-refresh-marketplaces","allow-add-marketplace","allow-update-marketplace","allow-remove-marketplace","allow-install-marketplace-item","allow-uninstall-marketplace-item","allow-set-global-item-disabled","allow-forget-marketplace-installs","allow-list-marketplace-updates","allow-marketplace-item-diff","allow-update-marketplace-item","allow-apply-marketplace-now","allow-get-marketplace-sync-report","allow-add-marketplace-token-account","allow-add-marketplace-gh-host-account","allow-start-marketplace-gh-container-login","allow-cancel-marketplace-gh-login","allow-test-marketplace-account","allow-remove-marketplace-account","allow-marketplace-gh-host-available"]},"file-viewer":{"identifier":"file-viewer","description":"The terminal file viewer windows (`file-viewer-`, opened by `open_file_viewer` on the app's own `viewer.html`). Same rules as `default.json`, including the layout checks: this file itself must stay a top-level `capabilities/*.json` with no `webviews` or `remote` key, or `build.rs` refuses the build rather than grant something the census cannot see. The five bare `allow-viewer-*` grants are the only app commands a viewer window can invoke: `build.rs` declares the AppManifest that makes tauri enforce that, and refuses any other bare grant in this file. The label gate inside `commands/file_viewer_commands.rs` is still what stops window A acting on window B's registry entry, because the ACL only decides which window may call. The rest of this file is the plugin-command surface a compromised viewer webview could reach, and it is the smallest one that lets the window work. `core:event:allow-listen`/`allow-unlisten` are for `file-viewer-goto` (Rust → this window; the viewer subscribes through `getCurrentWindow().listen`, because a bare `listen()` in *any* window receives an `emit_to`). `core:window:allow-destroy` is not optional: `getCurrentWindow().onCloseRequested` in @tauri-apps/api 2.11 makes Rust `prevent_close()` whenever a JS listener exists and then calls `destroy()` itself, so without this grant the window's X button does nothing once the unsaved-changes guard is installed. `allow-close` is deliberately absent — nothing calls it, and `destroy` is the only exit. No `set-title`/`set-focus`/`unminimize`: those are done from Rust when a second click targets an already-open file. `core:webview:allow-internal-toggle-devtools` is the same dev-only convenience `default.json` carries.","local":true,"windows":["file-viewer-*"],"permissions":["core:event:allow-listen","core:event:allow-unlisten","core:window:allow-destroy","core:webview:allow-internal-toggle-devtools","allow-viewer-get-state","allow-viewer-choose-file","allow-viewer-read-file","allow-viewer-poll-file","allow-viewer-write-file"]}} \ No newline at end of file diff --git a/app/src-tauri/gen/schemas/desktop-schema.json b/app/src-tauri/gen/schemas/desktop-schema.json index 6dbe82f..a9cf201 100644 --- a/app/src-tauri/gen/schemas/desktop-schema.json +++ b/app/src-tauri/gen/schemas/desktop-schema.json @@ -416,6 +416,18 @@ "const": "allow-aws-connection-sso-login", "markdownDescription": "Enables the aws_connection_sso_login command without any pre-configured scope." }, + { + "description": "Enables the aws_cost_estimate command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-cost-estimate", + "markdownDescription": "Enables the aws_cost_estimate command without any pre-configured scope." + }, + { + "description": "Enables the aws_environment_max_hours command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-environment-max-hours", + "markdownDescription": "Enables the aws_environment_max_hours command without any pre-configured scope." + }, { "description": "Enables the aws_policy_document command without any pre-configured scope.", "type": "string", @@ -434,6 +446,12 @@ "const": "allow-aws-task-log", "markdownDescription": "Enables the aws_task_log command without any pre-configured scope." }, + { + "description": "Enables the aws_workspace_status command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-workspace-status", + "markdownDescription": "Enables the aws_workspace_status command without any pre-configured scope." + }, { "description": "Enables the build_gateway_image command without any pre-configured scope.", "type": "string", @@ -1370,6 +1388,18 @@ "const": "deny-aws-connection-sso-login", "markdownDescription": "Denies the aws_connection_sso_login command without any pre-configured scope." }, + { + "description": "Denies the aws_cost_estimate command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-cost-estimate", + "markdownDescription": "Denies the aws_cost_estimate command without any pre-configured scope." + }, + { + "description": "Denies the aws_environment_max_hours command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-environment-max-hours", + "markdownDescription": "Denies the aws_environment_max_hours command without any pre-configured scope." + }, { "description": "Denies the aws_policy_document command without any pre-configured scope.", "type": "string", @@ -1388,6 +1418,12 @@ "const": "deny-aws-task-log", "markdownDescription": "Denies the aws_task_log command without any pre-configured scope." }, + { + "description": "Denies the aws_workspace_status command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-workspace-status", + "markdownDescription": "Denies the aws_workspace_status command without any pre-configured scope." + }, { "description": "Denies the build_gateway_image command without any pre-configured scope.", "type": "string", diff --git a/app/src-tauri/gen/schemas/linux-schema.json b/app/src-tauri/gen/schemas/linux-schema.json index 6dbe82f..a9cf201 100644 --- a/app/src-tauri/gen/schemas/linux-schema.json +++ b/app/src-tauri/gen/schemas/linux-schema.json @@ -416,6 +416,18 @@ "const": "allow-aws-connection-sso-login", "markdownDescription": "Enables the aws_connection_sso_login command without any pre-configured scope." }, + { + "description": "Enables the aws_cost_estimate command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-cost-estimate", + "markdownDescription": "Enables the aws_cost_estimate command without any pre-configured scope." + }, + { + "description": "Enables the aws_environment_max_hours command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-environment-max-hours", + "markdownDescription": "Enables the aws_environment_max_hours command without any pre-configured scope." + }, { "description": "Enables the aws_policy_document command without any pre-configured scope.", "type": "string", @@ -434,6 +446,12 @@ "const": "allow-aws-task-log", "markdownDescription": "Enables the aws_task_log command without any pre-configured scope." }, + { + "description": "Enables the aws_workspace_status command without any pre-configured scope.", + "type": "string", + "const": "allow-aws-workspace-status", + "markdownDescription": "Enables the aws_workspace_status command without any pre-configured scope." + }, { "description": "Enables the build_gateway_image command without any pre-configured scope.", "type": "string", @@ -1370,6 +1388,18 @@ "const": "deny-aws-connection-sso-login", "markdownDescription": "Denies the aws_connection_sso_login command without any pre-configured scope." }, + { + "description": "Denies the aws_cost_estimate command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-cost-estimate", + "markdownDescription": "Denies the aws_cost_estimate command without any pre-configured scope." + }, + { + "description": "Denies the aws_environment_max_hours command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-environment-max-hours", + "markdownDescription": "Denies the aws_environment_max_hours command without any pre-configured scope." + }, { "description": "Denies the aws_policy_document command without any pre-configured scope.", "type": "string", @@ -1388,6 +1418,12 @@ "const": "deny-aws-task-log", "markdownDescription": "Denies the aws_task_log command without any pre-configured scope." }, + { + "description": "Denies the aws_workspace_status command without any pre-configured scope.", + "type": "string", + "const": "deny-aws-workspace-status", + "markdownDescription": "Denies the aws_workspace_status command without any pre-configured scope." + }, { "description": "Denies the build_gateway_image command without any pre-configured scope.", "type": "string", diff --git a/app/src-tauri/src/auth_bridge/mod.rs b/app/src-tauri/src/auth_bridge/mod.rs index 9356bc4..a7f1b95 100644 --- a/app/src-tauri/src/auth_bridge/mod.rs +++ b/app/src-tauri/src/auth_bridge/mod.rs @@ -583,7 +583,7 @@ async fn reconcile( ); continue; } - match PortForward::bind(container.clone(), port, family).await { + match PortForward::bind(container.clone(), port, port, family).await { Ok(forward) => { if st.conflicts.remove(&port).is_some() { log::info!("Auth bridge: host port {} became available", port); diff --git a/app/src-tauri/src/auth_bridge/tunnel.rs b/app/src-tauri/src/auth_bridge/tunnel.rs index 4c8ad96..e34ca53 100644 --- a/app/src-tauri/src/auth_bridge/tunnel.rs +++ b/app/src-tauri/src/auth_bridge/tunnel.rs @@ -119,7 +119,11 @@ impl Drop for AbortOnDrop { /// also awaiting the aborted task, which guarantees the socket is closed before /// the caller proceeds (important when a port is rebound right after). pub struct PortForward { + /// The host loopback port. pub port: u16, + /// The container loopback port it reaches. The auth bridge mirrors a + /// port onto the same number; a project's port mapping may not. + pub container_port: u16, pub family: PortFamily, pub bridged_at: String, /// Why `[::1]` could not be taken alongside `127.0.0.1`, if it could not. @@ -141,15 +145,40 @@ impl Drop for PortForward { } impl PortForward { - /// Bind `port` on the host loopback and start proxying into `container`. + /// Bind `host_port` on the host loopback and start proxying into + /// `container_port` on the container's loopback — the auth bridge's + /// forward, gated (see [`Gate::SignInCallback`]). /// /// The bind happens before the task is spawned, so an already-taken port is /// reported to the caller as an error rather than disappearing into a /// background task. pub async fn bind( container: ContainerTarget, - port: u16, + host_port: u16, + container_port: u16, family: PortFamily, + ) -> Result { + Self::bind_with(container, host_port, container_port, family, Gate::SignInCallback).await + } + + /// As [`bind`](Self::bind), for a project's port mapping on a host with + /// no Docker port publishing (AWS): every connection is carried as is + /// (see [`Gate::None`]). + pub async fn bind_mapping( + container: ContainerTarget, + host_port: u16, + container_port: u16, + family: PortFamily, + ) -> Result { + Self::bind_with(container, host_port, container_port, family, Gate::None).await + } + + async fn bind_with( + container: ContainerTarget, + port: u16, + container_port: u16, + family: PortFamily, + gate: Gate, ) -> Result { // SECURITY BOUNDARY: the host side binds loopback ONLY — 127.0.0.1 and // ::1, never 0.0.0.0 / ::. Everything reachable through this socket is @@ -176,8 +205,8 @@ impl PortForward { // bridge reports itself healthy — a silent failure with no // thread back to this line. log::warn!( - "Auth bridge: bound 127.0.0.1:{} but not [::1]:{} ({}) — continuing with IPv4 only; \ - a client that resolves localhost to ::1 without falling back will not reach it", + "{}: bound 127.0.0.1:{} but not [::1]:{} ({}) — continuing with IPv4 only; \ + a client that resolves localhost to ::1 without falling back will not reach it", gate.label(), port, port, e @@ -193,11 +222,12 @@ impl PortForward { } }; - let target = family.socat_target(port); - let task = tokio::spawn(accept_loop(container, port, target, v4, v6)); + let target = family.socat_target(container_port); + let task = tokio::spawn(accept_loop(container, port, target, v4, v6, gate)); Ok(Self { port, + container_port, family, bridged_at: chrono::Utc::now().to_rfc3339(), ipv6_warning, @@ -214,6 +244,30 @@ impl PortForward { } } +/// What an accepted connection must show before it is carried in. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Gate { + /// The auth bridge: a client must speak within [`FIRST_BYTE_TIMEOUT`], + /// and a cross-site sub-resource request is refused + /// ([`web_request_verdict`]). + SignInCallback, + /// A port mapping the user configured: carried as is, like Docker's own + /// port publishing (which has no gate either) — a server-speaks-first + /// protocol such as MySQL or SMTP must work, so nothing waits for the + /// client's first byte. + None, +} + +impl Gate { + /// The log prefix of a forward of this kind. + fn label(self) -> &'static str { + match self { + Gate::SignInCallback => "Auth bridge", + Gate::None => "Port mapping", + } + } +} + /// Accept on both loopback listeners until aborted. Dropping this future drops /// the listeners (freeing the port) and the `JoinSet` (aborting live tunnels). async fn accept_loop( @@ -222,6 +276,7 @@ async fn accept_loop( target: String, v4: TcpListener, v6: Option, + gate: Gate, ) { let mut conns: JoinSet<()> = JoinSet::new(); @@ -245,25 +300,35 @@ async fn accept_loop( // client side is whatever can dial loopback, so a queue is // just a slower way to run out of execs. log::warn!( - "Auth bridge: refusing connection from {} to bridged port {} — \ - {} concurrent connections already open on it", + "{}: refusing connection from {} to bridged port {} — \ + {} concurrent connections already open on it", gate.label(), peer, port, MAX_CONNECTIONS ); continue; } - log::debug!("Auth bridge: connection from {} to bridged port {}", peer, port); + log::debug!("{}: connection from {} to bridged port {}", gate.label(), peer, port); let _ = stream.set_nodelay(true); - conns.spawn(tunnel_connection( - container.clone(), - target.clone(), - stream, - port, - )); + match gate { + Gate::SignInCallback => conns.spawn(tunnel_connection( + container.clone(), + target.clone(), + stream, + port, + )), + Gate::None => conns.spawn(tunnel_labelled( + gate.label(), + container.clone(), + target.clone(), + stream, + port, + Vec::new(), + )), + }; } Err(e) => { - log::warn!("Auth bridge: accept failed on port {}: {} — stopping listener", port, e); + log::warn!("{}: accept failed on port {}: {} — stopping listener", gate.label(), port, e); return; } } @@ -520,6 +585,18 @@ pub async fn tunnel_connection_with_prelude( stream: TcpStream, port: u16, prelude: Vec, +) { + tunnel_labelled("Auth bridge", container, target, stream, port, prelude).await +} + +/// [`tunnel_connection_with_prelude`], logging under `label`. +async fn tunnel_labelled( + label: &'static str, + container: ContainerTarget, + target: String, + stream: TcpStream, + port: u16, + prelude: Vec, ) { let cmd = vec!["socat".to_string(), "-".to_string(), target.clone()]; @@ -531,7 +608,7 @@ pub async fn tunnel_connection_with_prelude( Ok(e) => e, Err(e) => { log::warn!( - "Auth bridge: failed to open tunnel exec for port {} ({}): {}", + "{}: failed to open tunnel exec for port {} ({}): {}", label, port, target, e @@ -579,7 +656,7 @@ pub async fn tunnel_connection_with_prelude( Ok(chunk) => chunk, Err(_) => { log::debug!( - "Auth bridge: bridged port {} idle for {}s — closing the tunnel", + "{}: bridged port {} idle for {}s — closing the tunnel", label, port, IDLE_TIMEOUT.as_secs() ); @@ -597,14 +674,14 @@ pub async fn tunnel_connection_with_prelude( } Ok(ExecChunk::StdErr(message)) => { log::debug!( - "Auth bridge: socat stderr for port {}: {}", + "{}: socat stderr for port {}: {}", label, port, String::from_utf8_lossy(&message).trim() ); } Ok(_) => {} Err(e) => { - log::debug!("Auth bridge: tunnel stream error on port {}: {}", port, e); + log::debug!("{}: tunnel stream error on port {}: {}", label, port, e); break; } } diff --git a/app/src-tauri/src/aws/environments.rs b/app/src-tauri/src/aws/environments.rs index 35e17d2..72d09b3 100644 --- a/app/src-tauri/src/aws/environments.rs +++ b/app/src-tauri/src/aws/environments.rs @@ -75,6 +75,10 @@ pub struct EnvironmentInfo { pub log_group: String, pub network_mode: String, pub tenancy: String, + /// Advisory lifetime cap for workspaces, in hours; 0 = none. Absent in + /// records written by module version 1. + #[serde(default)] + pub max_workspace_hours: u32, } fn field<'a>(obj: &'a Map, name: &str) -> Result<&'a Value, String> { @@ -187,6 +191,15 @@ pub fn parse_environment_record( return Err("tenancy is not strict".into()); } + let max_workspace_hours = match obj.get("max_workspace_hours") { + None => 0, + Some(v) => v + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .filter(|v| *v <= super::tofu_modules::MAX_WORKSPACE_HOURS) + .ok_or_else(|| "max_workspace_hours is not a number from 0 to 168".to_string())?, + }; + Ok(EnvironmentInfo { schema: RECORD_SCHEMA as u32, name: name.clone(), @@ -199,6 +212,7 @@ pub fn parse_environment_record( log_group: log_group.to_string(), network_mode: network_mode.to_string(), tenancy: "strict".to_string(), + max_workspace_hours, }) } diff --git a/app/src-tauri/src/aws/environments/tests.rs b/app/src-tauri/src/aws/environments/tests.rs index 4d4d22d..6b830b9 100644 --- a/app/src-tauri/src/aws/environments/tests.rs +++ b/app/src-tauri/src/aws/environments/tests.rs @@ -44,6 +44,22 @@ fn without(name: &str, field: &str) -> String { r.to_string() } +#[test] +fn the_lifetime_cap_is_read_when_present() { + for hours in [0, 8, 168] { + let rec = with("dev", "max_workspace_hours", json!(hours)); + let info = parse_environment_record("dev", &rec, ACCOUNT, REGION).unwrap(); + assert_eq!(info.max_workspace_hours, hours); + } +} + +#[test] +fn a_version_1_record_reads_as_update_available() { + use crate::aws::tofu_modules::ENVIRONMENT_MODULE_VERSION; + let v1 = parsed("dev", 1); + assert!(v1.template_version < ENVIRONMENT_MODULE_VERSION); +} + #[test] fn untrusted_environment_records_are_rejected() { let valid = parsed("dev", 1); @@ -52,6 +68,7 @@ fn untrusted_environment_records_are_rejected() { assert_eq!(valid.subnet_ids.len(), 2); assert!(valid.assign_public_ip); assert_eq!(valid.tenancy, "strict"); + assert_eq!(valid.max_workspace_hours, 0, "a v1 record has no cap"); let other_account = "999999999999"; let secret = "s3cr3t-value-never-echoed"; @@ -182,6 +199,21 @@ fn untrusted_environment_records_are_rejected() { with("dev", "template_version", json!(secret)), "template_version", ), + ( + "cap above a week", + with("dev", "max_workspace_hours", json!(169)), + "max_workspace_hours", + ), + ( + "cap not a number", + with("dev", "max_workspace_hours", json!(secret)), + "max_workspace_hours", + ), + ( + "negative cap", + with("dev", "max_workspace_hours", json!(-1)), + "max_workspace_hours", + ), ]; for (what, value, field) in cases { let err = parse_environment_record("dev", &value, ACCOUNT, REGION) diff --git a/app/src-tauri/src/aws/live_tests.rs b/app/src-tauri/src/aws/live_tests.rs index cb29d5b..10156bf 100644 --- a/app/src-tauri/src/aws/live_tests.rs +++ b/app/src-tauri/src/aws/live_tests.rs @@ -624,6 +624,35 @@ async fn an_assumed_workspace_role_checks_itself_by_simulation() { .await; } +/// The cost estimate's call (Q5), made for real: a session holding only the +/// workspace files reads the region's Fargate rates from us-east-1 (the +/// parser must find both architectures), and one holding nothing is denied. +#[tokio::test] +#[ignore] +async fn a_workspace_role_reads_fargate_prices_and_a_bare_role_cannot() { + use super::pricing::{fetch_rates, SdkPricingApi, PRICING_REGION}; + e2e(|e| async move { + let ws = e.tier_role("price", &[Tier::WorkspaceUser]).await; + let cfg = sdk_config_for_keys(&e.assume_keys(&ws).await, PRICING_REGION); + let rates = fetch_rates(&SdkPricingApi::new(&cfg), &e.region) + .await + .expect("workspace role reads prices"); + let x86 = rates.x86_64.expect("x86 rates"); + let arm = rates.arm64.expect("ARM rates"); + eprintln!("{}: x86 {x86:?}, ARM {arm:?}", e.region); + assert!(x86.vcpu_hour > 0.0 && x86.gb_hour > 0.0 && x86.storage_gb_hour > 0.0); + assert!(arm.vcpu_hour < x86.vcpu_hour, "ARM is cheaper per vCPU"); + + let bare = e.role("noprice", None, &[]).await; + let cfg = sdk_config_for_keys(&e.assume_keys(&bare).await, PRICING_REGION); + let err = fetch_rates(&SdkPricingApi::new(&cfg), &e.region) + .await + .expect_err("a role without pricing:GetProducts"); + assert!(err.contains("pricing:GetProducts"), "{err}"); + }) + .await; +} + /// The e2e profile itself (an account administrator): every check allowed. /// For an SSO profile this resolves the `/aws-reserved/sso.amazonaws.com/` /// role path through `iam:GetRole`. @@ -1477,7 +1506,7 @@ mod environment { deploy_refusal(&found, &name).expect("deploy is offered"); // Deploy, public network, as the environment admin only. - let vars = environment_vars(&name, &t.e.region, &NetworkChoice::Public).unwrap(); + let vars = environment_vars(&name, &t.e.region, &NetworkChoice::Public, 0).unwrap(); let (_, outcome, denied) = t .run( ModuleKind::Environment, @@ -1590,7 +1619,7 @@ mod environment { // Update: the recorded network, the same module version: nothing // to change. let network = network_from_record(&info, None).expect("network from record"); - let vars = environment_vars(&name, &t.e.region, &network).unwrap(); + let vars = environment_vars(&name, &t.e.region, &network, 0).unwrap(); let (_, outcome, denied) = t .run( ModuleKind::Environment, @@ -1685,7 +1714,7 @@ mod environment { let (keys, cfg, who) = t.session(&admin).await; t.ensure_bucket(&cfg, &who).await; let name = format!("e2e{}", &uuid::Uuid::new_v4().simple().to_string()[..6]); - let vars = environment_vars(&name, &t.e.region, &NetworkChoice::PrivateNat).unwrap(); + let vars = environment_vars(&name, &t.e.region, &NetworkChoice::PrivateNat, 0).unwrap(); let (_, outcome, denied) = t .run( ModuleKind::Environment, @@ -1800,9 +1829,10 @@ mod environment { for status in [aws_sdk_ecs::types::TaskDefinitionStatus::Active, aws_sdk_ecs::types::TaskDefinitionStatus::Inactive] { let mut next = None; loop { + // No `family_prefix`: ECS matches it as a whole family + // name, so the test's `triple-c--` matched nothing. let Ok(out) = ecs .list_task_definitions() - .family_prefix(prefix) .status(status.clone()) .set_next_token(next.take()) .send() @@ -1810,7 +1840,8 @@ mod environment { else { break; }; - defs.extend(out.task_definition_arns().iter().cloned()); + let ours = format!(":task-definition/{prefix}"); + defs.extend(out.task_definition_arns().iter().filter(|a| a.contains(&ours)).cloned()); next = out.next_token().map(str::to_string); if next.is_none() { break; @@ -1910,6 +1941,124 @@ mod environment { .unwrap_or_else(|err| panic!("exec `{script}`: {err}")) } + /// What [`deploy_for_workspace_user`] set up. + struct Deployed { + region: String, + /// The environment's name. + name: String, + /// The workspace user's `aws:userid`. + owner: String, + okey: String, + fs_token: String, + /// The workspace user's profile connection. + conn: HostConnection, + ws_cfg: SdkConfig, + ws: CallerIdentity, + } + + /// The workspace tests' common start: the environment (with + /// `max_workspace_hours`) deployed by the environment admin, a role + /// holding only the workspace-user files onboarded to it, the test-only + /// ECR pull policy for `image`, and that role's profile connection + /// (`AWS_CONFIG_FILE` pointed at a config file this writes). Everything + /// made is recorded in `p5` / the fixture for the guards. + async fn deploy_for_workspace_user( + t: &Env, + p5: &std::sync::Mutex, + image: &str, + max_workspace_hours: u32, + ) -> Deployed { + use crate::aws::tofu_modules::{environment_cluster_name, user_file_system_token}; + + let region = t.e.region.clone(); + let admin = t.admin().await; + let (keys, cfg, who) = t.session(&admin).await; + t.ensure_bucket(&cfg, &who).await; + t.ensure_boundary().await; + + // ── the environment, deployed by the environment admin ── + let name = format!("e2e{}", &uuid::Uuid::new_v4().simple().to_string()[..6]); + let (cluster, families) = (environment_cluster_name(&name), format!("triple-c-{name}-")); + { + let mut g = p5_lock(p5); + g.cluster = Some(cluster); + g.families.push(families); + } + let vars = environment_vars(&name, ®ion, &NetworkChoice::Public, max_workspace_hours).unwrap(); + let (_, outcome, denied) = t + .run(ModuleKind::Environment, Deployment::Environment(&name), &vars, TofuOp::Apply, t.keys_env(&keys)) + .await; + assert_ok("deploy", &outcome, &denied); + + // ── the workspace user: only the workspace files ── + let user = t.e.tier_role("wsuser", &[Tier::WorkspaceUser]).await; + let owner = validate_owner_id(&user.session_user_id()).expect("owner id"); + let okey = owner_key(®ion, &owner); + let fs_token = user_file_system_token(&name, &okey); + p5_lock(p5).fs_token = Some(fs_token.clone()); + + // Onboarded by the admin (an onboarding from an admin bundle). + let (keys, _, _) = t.session(&admin).await; + let (_, outcome, denied) = t + .run( + ModuleKind::UserOnboard, + Deployment::User { env: &name, owner_key: &okey }, + &onboarding_vars(&name, ®ion, &owner), + TofuOp::Apply, + t.keys_env(&keys), + ) + .await; + assert_ok("onboard the workspace user", &outcome, &denied); + let (_, exec_role) = user_role_names(&name, &okey); + + // Test-only: pull from the throwaway private ECR repository. + if let Some((registry, rest)) = image.split_once('/') { + if registry.contains(".dkr.ecr.") { + let repo = rest.split([':', '@']).next().unwrap(); + let doc = format!( + r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":"ecr:GetAuthorizationToken","Resource":"*"}},{{"Effect":"Allow","Action":["ecr:BatchGetImage","ecr:GetDownloadUrlForLayer","ecr:BatchCheckLayerAvailability"],"Resource":"arn:aws:ecr:{region}:{}:repository/{repo}"}}]}}"#, + t.e.account + ); + p5_lock(p5).exec_role = Some(exec_role.clone()); + ok( + "put the test-only ECR policy", + t.e.iam.put_role_policy().role_name(&exec_role).policy_name(ECR_POLICY).policy_document(doc).send().await, + ); + eprintln!("test-only: {ECR_POLICY} on {exec_role} for {repo}"); + } + } + + // The workspace user's profile connection. + let profile = format!("{}-wsuser", t.e.prefix); + let cfg_file = t.root.join(format!("{}-config", t.e.prefix)); + std::fs::write( + &cfg_file, + format!( + "[profile {profile}]\nrole_arn = {}\nsource_profile = {}\nrole_session_name = {}\n", + user.arn, + super::var("TRIPLEC_AWS_E2E_PROFILE"), + super::SESSION + ), + ) + .unwrap(); + let before = std::env::var_os("AWS_CONFIG_FILE"); + p5_lock(p5).config_file_before = Some(before); + std::env::set_var("AWS_CONFIG_FILE", &cfg_file); + let conn = HostConnection { + id: "e2e-wsuser".into(), + name: "e2e-wsuser".into(), + kind: HostKind::Aws { + auth: AwsAuth::Profile { name: profile.clone() }, + default_region: region.clone(), + }, + }; + let ws_cfg = crate::aws::sdk_config(&conn, ®ion).await.expect("workspace user config"); + let ws = caller_identity(&ws_cfg).await.expect("workspace user identity"); + assert_eq!(ws.user_id, owner, "the profile session is the onboarded owner"); + eprintln!("workspace user: {}", ws.arn); + Deployed { region, name, owner, okey, fs_token, conn, ws_cfg, ws } + } + /// Phase 5: a Fargate workspace's whole life through `ProjectHost::Aws`, /// as a role holding **only** the workspace-user files, in an /// environment the environment admin deployed and onboarded it to. @@ -1949,9 +2098,7 @@ mod environment { use crate::aws::runtime::SdkRuntimeApi; use crate::aws::tasks::{run_task_request, task_log_stream, SdkTaskApi, TaskApi}; use crate::aws::tofu_modules::{ - environment_cluster_name, log_stream_prefix, project_secret_name, task_family, - user_file_system_token, - }; +log_stream_prefix, project_secret_name, task_family}; use crate::aws::workspace::workspace_tags; use crate::host::{lifecycle::ProjectHost, tunnels}; use crate::models::app_settings::ImageSource; @@ -1966,92 +2113,8 @@ mod environment { // Boxed: the body's state machine is far larger than a test // thread's 2 MiB stack once it is moved into the timeout. let inner = Box::pin(async { - let region = t.e.region.clone(); - let admin = t.admin().await; - let (keys, cfg, who) = t.session(&admin).await; - t.ensure_bucket(&cfg, &who).await; - t.ensure_boundary().await; - - // ── the environment, deployed by the environment admin ── - let name = format!("e2e{}", &uuid::Uuid::new_v4().simple().to_string()[..6]); - let (cluster, families) = (environment_cluster_name(&name), format!("triple-c-{name}-")); - { - let mut g = p5_lock(&p5); - g.cluster = Some(cluster); - g.families.push(families); - } - let vars = environment_vars(&name, ®ion, &NetworkChoice::Public).unwrap(); - let (_, outcome, denied) = t - .run(ModuleKind::Environment, Deployment::Environment(&name), &vars, TofuOp::Apply, t.keys_env(&keys)) - .await; - assert_ok("deploy", &outcome, &denied); - - // ── the workspace user: only the workspace files ── - let user = t.e.tier_role("wsuser", &[Tier::WorkspaceUser]).await; - let owner = validate_owner_id(&user.session_user_id()).expect("owner id"); - let okey = owner_key(®ion, &owner); - let fs_token = user_file_system_token(&name, &okey); - p5_lock(&p5).fs_token = Some(fs_token.clone()); - - // Onboarded by the admin (an onboarding from an admin bundle). - let (keys, _, _) = t.session(&admin).await; - let (_, outcome, denied) = t - .run( - ModuleKind::UserOnboard, - Deployment::User { env: &name, owner_key: &okey }, - &onboarding_vars(&name, ®ion, &owner), - TofuOp::Apply, - t.keys_env(&keys), - ) - .await; - assert_ok("onboard the workspace user", &outcome, &denied); - let (_, exec_role) = user_role_names(&name, &okey); - - // Test-only: pull from the throwaway private ECR repository. - if let Some((registry, rest)) = image.split_once('/') { - if registry.contains(".dkr.ecr.") { - let repo = rest.split([':', '@']).next().unwrap(); - let doc = format!( - r#"{{"Version":"2012-10-17","Statement":[{{"Effect":"Allow","Action":"ecr:GetAuthorizationToken","Resource":"*"}},{{"Effect":"Allow","Action":["ecr:BatchGetImage","ecr:GetDownloadUrlForLayer","ecr:BatchCheckLayerAvailability"],"Resource":"arn:aws:ecr:{region}:{}:repository/{repo}"}}]}}"#, - t.e.account - ); - p5_lock(&p5).exec_role = Some(exec_role.clone()); - ok( - "put the test-only ECR policy", - t.e.iam.put_role_policy().role_name(&exec_role).policy_name(ECR_POLICY).policy_document(doc).send().await, - ); - eprintln!("test-only: {ECR_POLICY} on {exec_role} for {repo}"); - } - } - - // The workspace user's profile connection. - let profile = format!("{}-wsuser", t.e.prefix); - let cfg_file = t.root.join(format!("{}-config", t.e.prefix)); - std::fs::write( - &cfg_file, - format!( - "[profile {profile}]\nrole_arn = {}\nsource_profile = {}\nrole_session_name = {}\n", - user.arn, - super::var("TRIPLEC_AWS_E2E_PROFILE"), - super::SESSION - ), - ) - .unwrap(); - let before = std::env::var_os("AWS_CONFIG_FILE"); - p5_lock(&p5).config_file_before = Some(before); - std::env::set_var("AWS_CONFIG_FILE", &cfg_file); - let conn = HostConnection { - id: "e2e-wsuser".into(), - name: "e2e-wsuser".into(), - kind: HostKind::Aws { - auth: AwsAuth::Profile { name: profile.clone() }, - default_region: region.clone(), - }, - }; - let ws_cfg = crate::aws::sdk_config(&conn, ®ion).await.expect("workspace user config"); - let ws = caller_identity(&ws_cfg).await.expect("workspace user identity"); - assert_eq!(ws.user_id, owner, "the profile session is the onboarded owner"); - eprintln!("workspace user: {}", ws.arn); + let Deployed { region, name, owner, okey, fs_token, conn, ws_cfg, ws } = + deploy_for_workspace_user(&t, &p5, &image, 0).await; let mut settings = AppSettings::default(); settings.hosts = vec![conn]; @@ -2304,7 +2367,7 @@ mod environment { let tail1: Vec<&String> = log1.iter().filter(|l| l.contains("entrypoint: stopping") || l.contains("wip") || l.contains("WIP")).collect(); eprintln!("RESULT task 1 stop log lines: {tail1:#?}"); assert!(log1.iter().any(|l| l.contains("entrypoint: stopping (sigterm) — pushing work in progress")), "{log1:#?}"); - store.set_aws_runtime(&id, None, current(&store).aws.unwrap().access_point_id, Some(revision1.clone())).unwrap(); + store.set_aws_runtime(&id, None, current(&store).aws.unwrap().access_point_id, Some(revision1.clone()), None).unwrap(); // ── start 2, unchanged; idle stop is at its minimum ── let t3 = std::time::Instant::now(); @@ -2388,7 +2451,7 @@ mod environment { // ── remove: the task, the secret and (data discarded) the access // point; the task definition is left (R8) ── - store.set_aws_runtime(&id, None, aws2.access_point_id.clone(), aws2.task_definition_arn.clone()).unwrap(); + store.set_aws_runtime(&id, None, aws2.access_point_id.clone(), aws2.task_definition_arn.clone(), aws2.workspace_access_point_id.clone()).unwrap(); // Every step runs even when one fails (the failures are // reported together), so check them all before the result. let removed = host.remove_aws_resources(¤t(&store), &settings, true).await; @@ -2437,5 +2500,425 @@ mod environment { }) .await; } -} + // ─────────────────────────────────────────────── phase 6: one workspace, every option + + /// The keys of the project secret, as the workspace user (values are + /// never printed), and the two gateway key values for the log check. + async fn secret_keys( + ws_cfg: &SdkConfig, + secret: &str, + ) -> (Vec, serde_json::Map) { + let out = ok( + "GetSecretValue on the project's own secret, as the workspace user", + aws_sdk_secretsmanager::Client::new(ws_cfg).get_secret_value().secret_id(secret).send().await, + ); + let map: serde_json::Map = + serde_json::from_str(out.secret_string().expect("a string secret")).expect("a JSON payload"); + let mut keys: Vec = map.keys().cloned().collect(); + keys.sort(); + (keys, map) + } + + /// A free loopback port on this machine. + fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() + } + + /// `GET /` on 127.0.0.1:`port`: the status line. + async fn http_get_status(port: u16) -> String { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let mut s = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.expect("connect to the mapped port"); + s.write_all(b"GET / HTTP/1.0\r\nHost: localhost\r\n\r\n").await.unwrap(); + let mut buf = Vec::new(); + let _ = tokio::time::timeout(Duration::from_secs(30), s.read_to_end(&mut buf)).await; + String::from_utf8_lossy(&buf).lines().next().unwrap_or_default().to_string() + } + + /// Phase 6 in one project, two task starts: an environment (module v2) + /// with `max_workspace_hours = 1`, and a project with EFS storage, a + /// setup script, copy-at-connect credentials (a CA file, a git token and + /// a custom variable), a port mapping and the LLM gateway sidecar (a + /// dummy provider key). Run like the phase-5 test: + /// + /// ```sh + /// TRIPLEC_E2E_TEST=aws::live_tests::environment::a_phase6_workspace_round_trips \ + /// TRIPLEC_AWS_E2E_PROFILE=… TRIPLEC_AWS_E2E_REGION=us-west-2 scripts/aws-e2e-workspace.sh + /// ``` + /// + /// Not exercised: the lifetime cap firing (unit-tested; 60 minutes), + /// a v1 → v2 environment update (the fixture applies only the embedded + /// modules), a private clone retried after connect (no credentials). + /// About 25 Fargate task-minutes at 1 vCPU / 2 GB. + #[tokio::test] + #[ignore] + async fn a_phase6_workspace_round_trips() { + use crate::aws::runtime::SdkRuntimeApi; + use crate::aws::tasks::{task_log_stream, SdkTaskApi, TaskApi}; + use crate::aws::tofu_modules::{log_stream_prefix, project_secret_name, task_family}; + use crate::host::aws_host::{self, connect}; + use crate::host::{lifecycle::ProjectHost, port_forwards, ExecSpec}; + use crate::models::app_settings::ImageSource; + use crate::models::gateway_settings::{GatewayModel, GatewaySettings}; + use crate::models::project::{ + AwsPlacement, AwsWorkspaceConfig, Backend, EnvVar, OpenAiCompatibleConfig, PortMapping, + RepoSource, SecretsDelivery, StorageMode, + }; + use crate::models::{AppSettings, Project}; + use crate::storage::projects_store::ProjectsStore; + + let image = super::var("TRIPLEC_E2E_IMAGE"); + let ecr_repo = std::env::var("TRIPLEC_E2E_ECR_REPO").ok().filter(|r| !r.is_empty()); + env_e2e(|t| async move { + let p5 = std::sync::Mutex::new(Phase5 { ecr_repo, ..Default::default() }); + let inner = Box::pin(async { + // ── 1. the environment carries the lifetime cap ── + let Deployed { region, name, owner: _, okey, fs_token: _, conn, ws_cfg, ws } = + deploy_for_workspace_user(&t, &p5, &image, 1).await; + let env = crate::aws::runtime::read_environment(&SdkRuntimeApi::new(&ws_cfg), &name, &ws.account, ®ion) + .await + .expect("the environment record, as the workspace user"); + eprintln!( + "RESULT environment record: template_version {}, max_workspace_hours {}", + env.template_version, env.max_workspace_hours + ); + assert_eq!(env.template_version, crate::aws::tofu_modules::ENVIRONMENT_MODULE_VERSION); + assert_eq!(env.max_workspace_hours, 1); + + // Dummy values: none is a real credential; each must stay out + // of the logs and (credentials) out of the secret. + let tag = uuid::Uuid::new_v4().simple().to_string(); + let provider_key = format!("sk-e2e-provider-{tag}"); + let git_token = format!("e2e-git-token-{tag}"); + let custom_value = format!("e2e-custom-{tag}"); + let dir = tempfile::tempdir().unwrap(); + let ca = dir.path().join("e2e-ca.pem"); + let made = std::process::Command::new("openssl") + .args(["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1", "-subj", "/CN=triple-c-e2e-ca"]) + .arg("-keyout") + .arg(dir.path().join("e2e-ca.key")) + .arg("-out") + .arg(&ca) + .output() + .expect("openssl"); + assert!(made.status.success(), "openssl: {}", String::from_utf8_lossy(&made.stderr)); + + let mut settings = AppSettings::default(); + settings.hosts = vec![conn]; + settings.image_source = ImageSource::Custom; + settings.custom_image_name = Some(image.clone()); + settings.gateway = GatewaySettings { + provider: "openai".into(), + models: vec![GatewayModel { name: "e2e-model".into(), model_id: "gpt-4o-mini".into() }], + ..Default::default() + }; + + let http_port: u16 = 8099; + let host_port = free_port(); + let mut project = Project::new("e2e-phase6".into(), Vec::new()); + project.host_id = Some("e2e-wsuser".into()); + project.aws_placement = Some(AwsPlacement { region: region.clone(), environment: name.clone() }); + project.backend = Backend::OpenAiCompatible; + project.openai_compatible_config = Some(OpenAiCompatibleConfig { + base_url: "https://example.invalid".into(), + api_key: Some(format!("e2e-oc-key-{tag}")), + model_id: Some("e2e-model".into()), + haiku_model_id: None, + }); + project.ca_cert_path = Some(ca.to_string_lossy().into_owned()); + project.git_token = Some(git_token.clone()); + project.custom_env_vars = vec![EnvVar { key: "E2E_CUSTOM_TOKEN".into(), value: custom_value.clone() }]; + project.port_mappings = vec![PortMapping { host_port, container_port: http_port, protocol: "tcp".into() }]; + project.aws = Some(AwsWorkspaceConfig { + cpu: 1024, + memory_mib: 2048, + storage: StorageMode::Efs, + repos: vec![RepoSource { + url: "https://github.com/octocat/Hello-World.git".into(), + branch: None, + folder: "Hello-World".into(), + }], + wip_push_on_stop: false, + idle_stop_minutes: None, + secrets_delivery: SecretsDelivery::CopyAtConnect, + setup_script: Some( + "sudo apt-get install -y jq\njq --version\necho ok > /workspace/setup-marker\n".into(), + ), + gateway_sidecar: true, + ..Default::default() + }); + assert_eq!(crate::host::port_forwards::validate_aws_port_mappings(&project.port_mappings, true), Ok(())); + let id = project.id.clone(); + let secret_name = project_secret_name(&name, &okey, &id); + { + let mut g = p5_lock(&p5); + g.project_id = Some(id.clone()); + g.secrets.push(secret_name.clone()); + } + let store_dir = tempfile::tempdir().unwrap(); + let store = ProjectsStore::over_file_for_test(store_dir.path().join("projects.json"), vec![project.clone()]); + assert_eq!(ProjectHost::for_project(&project), ProjectHost::Aws); + let host = ProjectHost::Aws; + let progress = |m: &str| eprintln!(" progress: {m}"); + let api = SdkTaskApi::new(&ws_cfg); + let family = task_family(&name, &okey, &id); + let stream_prefix = log_stream_prefix(&okey, &id); + let current = |store: &ProjectsStore| store.get(&id).unwrap(); + let key_reader = { + let k = provider_key.clone(); + move || Ok(Some(k)) + }; + let connect_now = |target: crate::host::ContainerTarget| { + let (p, s) = (current(&store), settings.clone()); + async move { + let bundle = connect::connect_credentials(&p, &s).expect("the connect bundle"); + eprintln!(" connect bundle: {bundle:?}"); + let t0 = std::time::Instant::now(); + connect::push_connect_bundle(&target, &bundle).await.expect("push the connect bundle"); + eprintln!("RESULT copy-at-connect push: {:?}", t0.elapsed()); + } + }; + + // ── start 1 ── + let t0 = std::time::Instant::now(); + let target = aws_host::ensure_started_with(¤t(&store), &settings, &store, &progress, key_reader.clone()) + .await + .expect("start 1"); + let aws1 = current(&store).aws.unwrap(); + let task1 = aws1.task_arn.clone().unwrap(); + eprintln!("RESULT start 1 (cold, EFS + sidecar): {:?}; task {task1}", t0.elapsed()); + assert!(aws1.access_point_id.is_some() && aws1.workspace_access_point_id.is_some(), "EFS: two access points {aws1:?}"); + assert!(aws1.task_definition_arn.as_deref().unwrap().contains(&format!(":task-definition/{family}:"))); + connect_now(target.clone()).await; + + // ── 6. the secret holds no credentials; 1. the cap reached the task ── + let (keys, map) = secret_keys(&ws_cfg, &secret_name).await; + eprintln!("RESULT project secret keys (copy-at-connect + sidecar): {keys:?}"); + eprintln!("RESULT TRIPLEC_MAX_LIFETIME_MINUTES in the secret: {:?}", map.get("TRIPLEC_MAX_LIFETIME_MINUTES")); + assert_eq!(map.get("TRIPLEC_MAX_LIFETIME_MINUTES").and_then(|v| v.as_str()), Some("60")); + for k in ["TRIPLEC_FILES", "GIT_TOKEN", "E2E_CUSTOM_TOKEN", "TRIPLE_C_CUSTOM_ENV"] { + assert!(!keys.iter().any(|x| x == k), "{k} is in the copy-at-connect secret"); + } + let secret_text = serde_json::to_string(&map).unwrap(); + for (what, v) in [("git token", &git_token), ("custom value", &custom_value)] { + assert!(!secret_text.contains(v.as_str()), "the {what} is in the secret"); + } + assert_eq!(map.get("TRIPLEC_GATEWAY_API_KEY").and_then(|v| v.as_str()), Some(provider_key.as_str()), "R1: the sidecar's key stays"); + let master1 = map.get("TRIPLEC_GATEWAY_MASTER_KEY").and_then(|v| v.as_str()).expect("a master key").to_string(); + let (env_line, code) = sh( + &target, + "root", + "tr '\\0' '\\n' < /proc/1/environ | grep '^TRIPLEC_MAX_LIFETIME_MINUTES='; \ + ps -eo args | grep -c '[t]riple-c-idle-watch' || true", + ) + .await; + eprintln!("RESULT task environment (PID 1), lifetime + idle watcher count:\n{}", env_line.trim()); + assert_eq!(code, 0); + assert!(env_line.contains("TRIPLEC_MAX_LIFETIME_MINUTES=60"), "{env_line}"); + + // ── 3. clone + setup, as the app's status follower sees it ── + let settled = poll(Duration::from_secs(600), Duration::from_secs(5), || async { + let s = aws_host::workspace_status(¤t(&store)).await.ok().flatten()?; + s.settled().then_some(s) + }) + .await + .expect("clone + setup never settled"); + eprintln!("RESULT workspace status after start 1: {settled:?}"); + assert_eq!(settled.setup.state, aws_host::status::SetupState::Ok, "{settled:?}"); + assert!(settled.failed_repos().is_empty(), "{settled:?}"); + + // ── 2. EFS /workspace, Hybrid links; 6. CA installed, ~/.ssh local ── + let marker = uuid::Uuid::new_v4().to_string(); + let (fs, code) = sh( + &target, + "claude", + &format!( + "grep ' /workspace ' /proc/mounts; cat /workspace/setup-marker; \ + git -C /workspace/Hello-World log -1 --format=%H; \ + printf %s {marker} > /workspace/e2e-efs-marker && echo wrote; \ + for f in ~/.claude ~/.claude.json ~/.ssh; do printf '%s -> %s\\n' \"$f\" \"$(readlink \"$f\")\"; done; \ + test -L ~/.ssh && echo SSH-IS-LINK || echo ssh-local; \ + ls /usr/local/share/ca-certificates/; \ + for c in /usr/local/share/ca-certificates/triple-c-*.crt; do openssl x509 -in \"$c\" -noout -subject; done; \ + git config --global --get credential.helper >/dev/null && echo git-helper-set" + ), + ) + .await; + eprintln!("RESULT start 1 workspace (exit {code}):\n{}", fs.trim()); + assert!(fs.contains(" /workspace nfs"), "{fs}"); + assert!(fs.lines().any(|l| l.trim() == "ok"), "setup marker: {fs}"); + assert!(fs.contains("wrote"), "{fs}"); + assert!(fs.contains(".claude -> /mnt/triple-c-home/"), "{fs}"); + assert!(fs.contains("ssh-local"), "R6: ~/.ssh is not on EFS under copy-at-connect: {fs}"); + assert!(fs.contains("CN = triple-c-e2e-ca") || fs.contains("CN=triple-c-e2e-ca"), "CA installed: {fs}"); + + // ── 4. a port mapping ── + let exec = target + .exec_detached( + ExecSpec::new(vec!["python3".into(), "-m".into(), "http.server".into(), http_port.to_string(), "--bind".into(), "127.0.0.1".into()]) + .working_dir(Some("/tmp")) + .no_stdin(), + ) + .await + .expect("start the HTTP server"); + eprintln!(" http.server exec {exec}"); + let up = poll(Duration::from_secs(60), Duration::from_secs(2), || async { + let (_, c) = sh(&target, "claude", &format!("curl -sf -o /dev/null http://127.0.0.1:{http_port}/")).await; + (c == 0).then_some(()) + }) + .await; + assert!(up.is_some(), "the HTTP server never answered inside the workspace"); + let opened = port_forwards::open_for(&id, &target, ¤t(&store).port_mappings).await; + assert!(opened.iter().all(|r| r.error.is_none()), "{opened:?}"); + let status_line = http_get_status(host_port).await; + eprintln!("RESULT port mapping 127.0.0.1:{host_port} -> workspace :{http_port}: {status_line}"); + assert!(status_line.contains(" 200 "), "{status_line}"); + port_forwards::close(&id).await; + + // ── 5. the gateway sidecar ── + let mk_env = vec![format!("MK={master1}")]; + let health = poll(Duration::from_secs(420), Duration::from_secs(10), || async { + let (out, _) = sh(&target, "claude", "curl -s -o /dev/null -w '%{http_code}' --max-time 5 http://127.0.0.1:4000/health/liveliness").await; + (out.trim() == "200").then_some(out) + }) + .await; + eprintln!("RESULT gateway /health/liveliness from the workspace: {health:?} after {:?} from RunTask", t0.elapsed()); + assert!(health.is_some(), "the gateway sidecar never answered"); + let exec_with = |script: &'static str| { + let t = target.clone(); + let env = mk_env.clone(); + async move { + tokio::time::timeout(SH_TIMEOUT, t.exec_oneshot_as("claude", vec!["sh".into(), "-c".into(), script.into()], env)) + .await + .expect("exec timed out") + .expect("exec") + } + }; + let (models, _) = exec_with( + "curl -s -w ' HTTP%{http_code}' -H \"Authorization: Bearer $MK\" http://127.0.0.1:4000/v1/models; echo; \ + curl -s -o /dev/null -w 'no key: HTTP%{http_code}' http://127.0.0.1:4000/v1/models", + ) + .await; + eprintln!("RESULT gateway /v1/models:\n{}", models.trim()); + assert!(models.contains("e2e-model") && models.contains("HTTP200"), "{models}"); + let (chat, _) = exec_with( + "curl -s --max-time 60 -w ' HTTP%{http_code}' -H \"Authorization: Bearer $MK\" -H 'content-type: application/json' \ + -d '{\"model\":\"e2e-model\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":5}' \ + http://127.0.0.1:4000/v1/chat/completions", + ) + .await; + let chat_short: String = chat.chars().take(400).collect(); + eprintln!("RESULT failed provider call (dummy key):\n{chat_short}"); + assert!(!chat.contains(&provider_key), "the provider key came back in the response"); + assert!(!chat.contains(" HTTP200"), "a dummy key got an answer?"); + let (claude_env, _) = sh(&target, "claude", "bash -lc 'printf \"%s\\n\" \"$ANTHROPIC_BASE_URL\"; test -n \"$ANTHROPIC_AUTH_TOKEN\" && echo token-set'").await; + eprintln!("RESULT claude's environment: {}", claude_env.trim()); + + // ── 7. a cost estimate for this configuration ── + let pricing_cfg = crate::aws::sdk_config(&settings.hosts[0], crate::aws::pricing::PRICING_REGION).await.expect("pricing config"); + let rates = crate::aws::pricing::fetch_rates(&crate::aws::pricing::SdkPricingApi::new(&pricing_cfg), ®ion) + .await + .expect("fetch Fargate rates as the workspace user"); + let est = crate::aws::pricing::estimate( + current(&store).aws.as_ref().unwrap(), + &rates.for_arch(crate::models::project::Arch::X86_64).expect("x86 rates"), + ); + eprintln!("RESULT cost estimate for 1 vCPU / 2 GiB / EFS: {est:?}"); + assert!(est.usd_per_hour > 0.0 && est.efs_billed_separately); + + // ── stop 1 ── + host.stop_project(¤t(&store), &settings).await.expect("stop 1"); + let stopped = poll(Duration::from_secs(240), Duration::from_secs(5), || async { + let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task1)).await.ok()?; + let t = d.into_iter().next()?; + (t.last_status == "STOPPED").then_some(t) + }) + .await + .expect("task 1 never stopped"); + eprintln!("RESULT stop 1: code {:?}, exit {:?}, kind {:?}", stopped.stop_code, stopped.exit_code, crate::aws::tasks::classify_stop(&stopped)); + tokio::time::sleep(Duration::from_secs(20)).await; + + // ── 5. neither key in the logs ── + let task_id = task1.rsplit('/').next().unwrap(); + let gw_stream = format!("{stream_prefix}/gateway/{task_id}"); + let gw_log = api.log_tail(&env.log_group, &gw_stream, 2000).await.unwrap(); + let ws_log = api.log_tail(&env.log_group, &task_log_stream(&stream_prefix, &task1), 2000).await.unwrap(); + eprintln!("RESULT gateway log: {} lines; workspace log: {} lines", gw_log.len(), ws_log.len()); + let short = |l: &String| l.chars().take(240).collect::(); + for l in gw_log.iter().filter(|l| l.contains("rror") || l.contains("uthoriz") || l.contains("401") || l.to_lowercase().contains("header")).take(12) { + eprintln!(" gateway log: {}", short(l)); + } + let prefix8: String = provider_key.chars().take(16).collect(); + let partial = gw_log.iter().filter(|l| l.contains(&prefix8)).count(); + eprintln!("RESULT gateway log lines holding the provider key's first 16 chars (masked echo): {partial}"); + for (what, v) in [("provider key", provider_key.as_str()), ("master key", master1.as_str()), ("git token", git_token.as_str()), ("custom value", custom_value.as_str())] { + let gw = gw_log.iter().filter(|l| l.contains(v)).count(); + let wsn = ws_log.iter().filter(|l| l.contains(v)).count(); + eprintln!("RESULT {what} in logs: gateway {gw} line(s), workspace {wsn} line(s)"); + assert_eq!((gw, wsn), (0, 0), "the {what} is in the task's logs"); + } + assert!(!gw_log.is_empty(), "the gateway stream is empty: {gw_stream}"); + store.set_aws_runtime(&id, None, aws1.access_point_id.clone(), aws1.task_definition_arn.clone(), aws1.workspace_access_point_id.clone()).unwrap(); + + // ── start 2: /workspace survived ── + let t3 = std::time::Instant::now(); + let target2 = aws_host::ensure_started_with(¤t(&store), &settings, &store, &progress, key_reader.clone()) + .await + .expect("start 2"); + let aws2 = current(&store).aws.unwrap(); + let task2 = aws2.task_arn.clone().unwrap(); + eprintln!("RESULT start 2: {:?}; task {task2}", t3.elapsed()); + assert_ne!(task2, task1); + assert_eq!(aws2.workspace_access_point_id, aws1.workspace_access_point_id, "the same /workspace access point"); + connect_now(target2.clone()).await; + let (_, map2) = secret_keys(&ws_cfg, &secret_name).await; + let master2 = map2.get("TRIPLEC_GATEWAY_MASTER_KEY").and_then(|v| v.as_str()).unwrap_or_default(); + eprintln!("RESULT sidecar master key new per start: {}", master2 != master1); + assert_ne!(master2, master1.as_str()); + let settled2 = poll(Duration::from_secs(600), Duration::from_secs(5), || async { + let s = aws_host::workspace_status(¤t(&store)).await.ok().flatten()?; + s.settled().then_some(s) + }) + .await + .expect("start 2 never settled"); + eprintln!("RESULT workspace status after start 2: {settled2:?}"); + let (fs2, _) = sh(&target2, "claude", "cat /workspace/e2e-efs-marker; echo; ls /workspace; git -C /workspace/Hello-World status --short | head -3; ls /usr/local/share/ca-certificates/").await; + eprintln!("RESULT start 2 /workspace:\n{}", fs2.trim()); + assert!(fs2.contains(&marker), "the EFS file survived the stop: {fs2}"); + assert!(settled2.clone.repos.iter().any(|r| r.folder == "Hello-World" && r.state == "exists"), "{settled2:?}"); + + // ── stop 2, then remove with discard ── + host.stop_project(¤t(&store), &settings).await.expect("stop 2"); + poll(Duration::from_secs(240), Duration::from_secs(5), || async { + let d = api.describe(&env.cluster_arn, std::slice::from_ref(&task2)).await.ok()?; + (d.into_iter().next()?.last_status == "STOPPED").then_some(()) + }) + .await + .expect("task 2 never stopped"); + store.set_aws_runtime(&id, None, aws2.access_point_id.clone(), aws2.task_definition_arn.clone(), aws2.workspace_access_point_id.clone()).unwrap(); + let removed = host.remove_aws_resources(¤t(&store), &settings, true).await; + eprintln!("RESULT remove_aws_resources (discard): {:?}", removed.as_ref().map_err(|e| e.chars().take(400).collect::())); + let efs = aws_sdk_efs::Client::new(&t.e.cfg); + for ap in [aws2.access_point_id.clone().unwrap(), aws2.workspace_access_point_id.clone().unwrap()] { + let gone = efs.describe_access_points().access_point_id(&ap).send().await; + let live = gone.as_ref().map(|o| o.access_points().iter().any(|a| a.life_cycle_state() == Some(&aws_sdk_efs::types::LifeCycleState::Available))).unwrap_or(false); + eprintln!("RESULT access point {ap} after remove: available {live}"); + assert!(!live, "{ap} is still there"); + } + removed.expect("remove the project's resources"); + }); + let body = async { + if tokio::time::timeout(PHASE5_TIMEOUT, inner).await.is_err() { + panic!("the phase-6 body did not finish in {PHASE5_TIMEOUT:?}"); + } + }; + let result = std::panic::AssertUnwindSafe(body).catch_unwind().await; + let guard = std::mem::take(&mut *p5_lock(&p5)); + phase5_cleanup(&t.e, &guard).await; + if let Err(panic) = result { + std::panic::resume_unwind(panic); + } + }) + .await; + } +} diff --git a/app/src-tauri/src/aws/mod.rs b/app/src-tauri/src/aws/mod.rs index 90b011a..6dace1c 100644 --- a/app/src-tauri/src/aws/mod.rs +++ b/app/src-tauri/src/aws/mod.rs @@ -11,6 +11,7 @@ mod identity; mod live_tests; pub mod permissions; pub mod policies; +pub mod pricing; #[cfg(test)] mod policy_eval; pub mod runtime; diff --git a/app/src-tauri/src/aws/policies.rs b/app/src-tauri/src/aws/policies.rs index 10d1e64..259be0a 100644 --- a/app/src-tauri/src/aws/policies.rs +++ b/app/src-tauri/src/aws/policies.rs @@ -421,6 +421,9 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[ ), read("logs:FilterLogEvents", PROBE_LOG_GROUP, &[]), read("sts:GetCallerIdentity", "*", &[]), + // `workspace-user-tasks.json`: the hourly cost estimate (Q5). The Price + // List API has no resource-level permissions, and prices are public. + read("pricing:GetProducts", "*", &[]), ]; /// The admin tier's checks, across all its files. `tofu_modules`' tests hold @@ -1224,6 +1227,32 @@ mod tests { } } + /// The cost estimate's one call (Q5), in the second workspace file: only + /// `pricing:GetProducts`, on `*` (the API has no resource types), with no + /// other Pricing action riding along. + #[test] + fn the_workspace_tier_reads_prices_and_nothing_else_of_pricing() { + let (_, doc) = policies(Tier::WorkspaceUser) + .into_iter() + .find(|(name, _)| *name == "workspace-user-tasks.json") + .unwrap(); + let pricing: Vec = statements_of(&doc) + .into_iter() + .filter(|s| actions(s).iter().any(|a| a.starts_with("pricing:"))) + .collect(); + assert_eq!(pricing.len(), 1); + assert_eq!(actions(&pricing[0]), ["pricing:GetProducts"]); + assert_eq!(resources(&pricing[0]), ["*"]); + assert!(pricing[0].get("Condition").is_none()); + let c = ws_check("pricing:GetProducts", "*"); + assert!(!c.write); + assert!(allowed(Tier::WorkspaceUser, c, ME, SOMEONE_ELSE)); + for action in ["pricing:DescribeServices", "pricing:GetPriceListFileUrl"] { + let other = Check { action, ..*c }; + assert!(!allowed(Tier::WorkspaceUser, &other, ME, ME), "{action}"); + } + } + /// RegisterTaskDefinition with a task or execution role also authorizes /// `iam:PassRole` on each; `PassOwnTaskRoles` (owner-tagged, to ECS /// tasks, `triple-c-*` roles) must cover both and nothing else. diff --git a/app/src-tauri/src/aws/pricing.rs b/app/src-tauri/src/aws/pricing.rs new file mode 100644 index 0000000..60de75d --- /dev/null +++ b/app/src-tauri/src/aws/pricing.rs @@ -0,0 +1,405 @@ +//! The estimated hourly cost of a Fargate workspace (Q5): on-demand rates +//! from the Price List API (`pricing:GetProducts`, service `AmazonECS`, +//! served from us-east-1 only), cached on disk per region for a day. +//! +//! Everything here is best effort. A denied call, no network, a slow answer +//! or a price list we can't read all end in "no estimate" (`None`), never an +//! error: the estimate is a hint next to the settings, not something a start +//! depends on. + +use std::collections::HashMap; +use std::future::Future; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::models::project::{Arch, AwsWorkspaceConfig, StorageMode}; + +/// The Price List API's endpoint region (it also has ap-south-1 and +/// eu-central-1; any of them serves every region's prices). +pub const PRICING_REGION: &str = "us-east-1"; +pub const SERVICE_CODE: &str = "AmazonECS"; +/// How long a region's rates are used before they are fetched again. +pub const CACHE_TTL: Duration = Duration::from_secs(24 * 60 * 60); +/// The whole fetch (every page), so the command answers quickly offline. +pub const FETCH_TIMEOUT: Duration = Duration::from_secs(8); +/// After a failed fetch, the region is not asked again for this long (the +/// settings call the estimate on every change). +pub const RETRY_AFTER_FAILURE: Duration = Duration::from_secs(5 * 60); +/// Fargate includes 20 GiB of ephemeral storage; only the rest is billed. +pub const FREE_EPHEMERAL_GIB: u32 = 20; +/// The filtered list is 8 rows (one page); more pages than this is not a +/// price list we understand. +const MAX_PAGES: usize = 5; + +/// `GetProducts` filters as (type, field, value); `{region}` is the +/// workspace's region. Verified against the live API (2026-11-16): eight +/// rows per region — Linux x86 and ARM vCPU-hours and GB-hours, ephemeral +/// storage GB-hours and three Windows rows, which the parser skips. +pub const FILTERS: &[(&str, &str, &str)] = &[ + ("TERM_MATCH", "regionCode", "{region}"), + ("TERM_MATCH", "termType", "OnDemand"), + ("CONTAINS", "usagetype", "Fargate"), +]; + +/// One architecture's on-demand rates in a region, in USD. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct FargateRates { + pub vcpu_hour: f64, + pub gb_hour: f64, + pub storage_gb_hour: f64, +} + +/// A region's rates per architecture. An architecture the price list did +/// not fully cover is `None`. +#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)] +pub struct RegionRates { + pub x86_64: Option, + pub arm64: Option, +} + +impl RegionRates { + pub fn for_arch(&self, arch: Arch) -> Option { + match arch { + Arch::X86_64 => self.x86_64, + Arch::Arm64 => self.arm64, + } + } +} + +/// What the UI shows: the on-demand price per hour of the task while it +/// runs. A gateway sidecar shares the task's CPU and memory, so it adds +/// nothing; Spot isn't in the Price List API (`note_spot`: say it is +/// usually cheaper); EFS is billed per GB-month, not per hour +/// (`efs_billed_separately`). +#[derive(Debug, Clone, Copy, PartialEq, Serialize)] +pub struct HourlyEstimate { + pub usd_per_hour: f64, + pub note_spot: bool, + pub efs_billed_separately: bool, +} + +pub fn estimate(cfg: &AwsWorkspaceConfig, rates: &FargateRates) -> HourlyEstimate { + let vcpu = f64::from(cfg.cpu) / 1024.0; + let gb = f64::from(cfg.memory_mib) / 1024.0; + let billed_storage = f64::from(cfg.ephemeral_gib.saturating_sub(FREE_EPHEMERAL_GIB)); + HourlyEstimate { + usd_per_hour: vcpu * rates.vcpu_hour + + gb * rates.gb_hour + + billed_storage * rates.storage_gb_hour, + note_spot: cfg.spot, + efs_billed_separately: cfg.storage != StorageMode::Ephemeral, + } +} + +/// The rates in a `GetProducts` price list (each item one product's JSON) +/// for `region`. `None` when no architecture is complete. +pub fn parse_price_list(region: &str, items: &[String]) -> Option { + #[derive(Default)] + struct Partial { + vcpu: Option, + gb: Option, + } + let (mut x86, mut arm, mut storage) = (Partial::default(), Partial::default(), None); + for item in items { + let Ok(product) = serde_json::from_str::(item) else { + continue; + }; + let attrs = &product["product"]["attributes"]; + if attrs["regionCode"].as_str() != Some(region) { + continue; + } + if attrs["operatingSystem"] + .as_str() + .is_some_and(|os| os != "Linux") + { + continue; + } + let Some(usage) = attrs["usagetype"].as_str() else { + continue; + }; + // `USW2-Fargate-ARM-vCPU-Hours:perCPU`; us-east-1's prefix is + // `USE1-`, Ireland's `EU-`. + let Some((_, kind)) = usage.split_once("Fargate-") else { + continue; + }; + let slot = match kind { + "vCPU-Hours:perCPU" => &mut x86.vcpu, + "GB-Hours" => &mut x86.gb, + "ARM-vCPU-Hours:perCPU" => &mut arm.vcpu, + "ARM-GB-Hours" => &mut arm.gb, + "EphemeralStorage-GB-Hours" => &mut storage, + _ => continue, + }; + if slot.is_none() { + *slot = on_demand_usd(&product); + } + } + let storage = storage?; + let complete = |p: Partial| { + Some(FargateRates { + vcpu_hour: p.vcpu?, + gb_hour: p.gb?, + storage_gb_hour: storage, + }) + }; + let rates = RegionRates { + x86_64: complete(x86), + arm64: complete(arm), + }; + (rates.x86_64.is_some() || rates.arm64.is_some()).then_some(rates) +} + +/// The product's on-demand USD price per unit. A price list gives one term +/// with one dimension for these rows; anything not a sane non-negative +/// number is ignored. +fn on_demand_usd(product: &Value) -> Option { + product["terms"]["OnDemand"] + .as_object()? + .values() + .filter_map(|term| term["priceDimensions"].as_object()) + .flat_map(|dims| dims.values()) + .filter_map(|d| d["pricePerUnit"]["USD"].as_str()?.parse::().ok()) + .find(|p| p.is_finite() && (0.0..100.0).contains(p)) +} + +/// One page of `GetProducts`. +pub struct Page { + pub items: Vec, + pub next_token: Option, +} + +/// The Price List API, faked in tests. +pub trait PricingApi { + /// One page of `AmazonECS` products matching [`FILTERS`] for `region`. + fn get_products( + &self, + region: &str, + next_token: Option, + ) -> impl Future> + Send; +} + +/// The real thing: a client in [`PRICING_REGION`] from a connection's +/// `SdkConfig` (`aws::sdk_config(conn, PRICING_REGION)`). +pub struct SdkPricingApi { + client: aws_sdk_pricing::Client, +} + +impl SdkPricingApi { + pub fn new(cfg: &aws_config::SdkConfig) -> Self { + Self { + client: aws_sdk_pricing::Client::new(cfg), + } + } +} + +impl PricingApi for SdkPricingApi { + async fn get_products(&self, region: &str, next_token: Option) -> Result { + use aws_sdk_pricing::types::{Filter, FilterType}; + let mut req = self + .client + .get_products() + .service_code(SERVICE_CODE) + .format_version("aws_v1") + .max_results(100) + .set_next_token(next_token); + for (kind, field, value) in FILTERS { + let filter = Filter::builder() + .r#type(FilterType::from(*kind)) + .field(*field) + .value(value.replace("{region}", region)) + .build() + .map_err(|e| e.to_string())?; + req = req.filters(filter); + } + let out = req + .send() + .await + .map_err(|e| super::classify_sdk_error("pricing:GetProducts", &e).to_string())?; + Ok(Page { + items: out.price_list().to_vec(), + next_token: out.next_token().map(str::to_string), + }) + } +} + +/// Every page for `region`, parsed. +pub async fn fetch_rates(api: &A, region: &str) -> Result { + let mut items = Vec::new(); + let mut token = None; + for _ in 0..MAX_PAGES { + let page = api.get_products(region, token).await?; + items.extend(page.items); + token = page.next_token.filter(|t| !t.is_empty()); + if token.is_none() { + return parse_price_list(region, &items) + .ok_or_else(|| format!("no Fargate rates for {region} in the price list")); + } + } + Err(format!( + "the {region} price list has more than {MAX_PAGES} pages" + )) +} + +/// `/.json`. +#[derive(Debug, Serialize, Deserialize)] +struct CacheFile { + region: String, + /// Unix seconds. + fetched_at: u64, + rates: RegionRates, +} + +/// The per-region rate files and the memory of recent failures. +pub struct RatesCache { + dir: PathBuf, + failed_at: Mutex>, +} + +/// `/triple-c/aws-pricing/`. +pub fn default_cache_dir() -> Option { + Some(dirs::data_dir()?.join("triple-c").join("aws-pricing")) +} + +fn unix_secs(t: SystemTime) -> u64 { + t.duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs()) +} + +impl RatesCache { + pub fn new(dir: PathBuf) -> Self { + Self { + dir, + failed_at: Mutex::new(HashMap::new()), + } + } + + #[cfg(test)] + pub fn dir(&self) -> &Path { + &self.dir + } + + /// The region must already be validated (it names a file). + fn path(&self, region: &str) -> PathBuf { + self.dir.join(format!("{region}.json")) + } + + /// The cached rates and whether they are still fresh at `now`. A + /// missing, unreadable or corrupt file, or one for another region, is + /// no cache. + pub fn read(&self, region: &str, now: SystemTime) -> Option<(RegionRates, bool)> { + let text = std::fs::read_to_string(self.path(region)).ok()?; + let file: CacheFile = serde_json::from_str(&text).ok()?; + if file.region != region { + return None; + } + let now = unix_secs(now); + // A timestamp from the future (a clock change) counts as stale. + let fresh = file.fetched_at <= now && now - file.fetched_at < CACHE_TTL.as_secs(); + Some((file.rates, fresh)) + } + + pub fn write(&self, region: &str, rates: &RegionRates, now: SystemTime) -> Result<(), String> { + std::fs::create_dir_all(&self.dir).map_err(|e| e.to_string())?; + let file = CacheFile { + region: region.to_string(), + fetched_at: unix_secs(now), + rates: *rates, + }; + let text = serde_json::to_string_pretty(&file).map_err(|e| e.to_string())?; + // Write then rename, so a concurrent reader never sees half a file. + let tmp = self + .dir + .join(format!(".{region}.json.tmp-{}", std::process::id())); + std::fs::write(&tmp, text).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, self.path(region)).map_err(|e| { + let _ = std::fs::remove_file(&tmp); + e.to_string() + }) + } + + fn recently_failed(&self, region: &str, now: SystemTime) -> bool { + let map = self.failed_at.lock().unwrap_or_else(|e| e.into_inner()); + map.get(region).is_some_and(|t| { + now.duration_since(*t) + .is_ok_and(|age| age < RETRY_AFTER_FAILURE) + }) + } + + fn note_failure(&self, region: &str, now: SystemTime, failed: bool) { + let mut map = self.failed_at.lock().unwrap_or_else(|e| e.into_inner()); + if failed { + map.insert(region.to_string(), now); + } else { + map.remove(region); + } + } + + /// Fresh cached rates, else a fetch (bounded by [`FETCH_TIMEOUT`]) + /// that refreshes the cache, else the stale cache, else `None`. `api` + /// is `None` when no client could be built (the stale cache still + /// answers). A region whose fetch failed is not asked again for + /// [`RETRY_AFTER_FAILURE`]. + pub async fn rates( + &self, + api: Option<&A>, + region: &str, + now: SystemTime, + ) -> Option { + self.rates_with::(async { api }, region, now).await + } + + /// [`Self::rates`] with the client built by `api`, which is awaited only + /// when the cache can't answer, and within the same [`FETCH_TIMEOUT`] as + /// the fetch (building one reads credentials, which can hang too). + pub async fn rates_with>( + &self, + api: impl Future>, + region: &str, + now: SystemTime, + ) -> Option { + let cached = self.read(region, now); + if let Some((rates, true)) = cached { + return Some(rates); + } + let stale = cached.map(|(rates, _)| rates); + if self.recently_failed(region, now) { + return stale; + } + let fetch = async { + let api = api.await?; + Some(fetch_rates(api.borrow(), region).await) + }; + let fetched = match tokio::time::timeout(FETCH_TIMEOUT, fetch).await { + Ok(Some(r)) => r, + // No client could be built: a failure like any other (building + // one reads credentials, which can be slow), and the stale cache + // answers. + Ok(None) => { + log::info!("No Fargate rates for {region}: no Pricing client could be built"); + self.note_failure(region, now, true); + return stale; + } + Err(_) => Err(format!("timed out after {}s", FETCH_TIMEOUT.as_secs())), + }; + match fetched { + Ok(rates) => { + self.note_failure(region, now, false); + if let Err(e) = self.write(region, &rates, now) { + log::warn!("Could not cache the {region} Fargate rates: {e}"); + } + Some(rates) + } + Err(e) => { + log::info!("No Fargate rates for {region}: {e}"); + self.note_failure(region, now, true); + stale + } + } + } +} + +#[cfg(test)] +mod tests; diff --git a/app/src-tauri/src/aws/pricing/fixtures/get-products-us-west-2.json b/app/src-tauri/src/aws/pricing/fixtures/get-products-us-west-2.json new file mode 100644 index 0000000..f1f0f16 --- /dev/null +++ b/app/src-tauri/src/aws/pricing/fixtures/get-products-us-west-2.json @@ -0,0 +1,13 @@ +{ + "FormatVersion": "aws_v1", + "PriceList": [ + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"resource\":\"per vCPU per hour\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-Windows-vCPU-Hours:perCPU\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"cputype\":\"perCPU\",\"operatingSystem\":\"Windows\",\"operation\":\"\"},\"sku\":\"58AWBVRMPKQ3HVG6\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"58AWBVRMPKQ3HVG6.JRTCKXETXF\":{\"priceDimensions\":{\"58AWBVRMPKQ3HVG6.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - Windows - vCPU - US West 2 (Oregon)\",\"appliesTo\":[],\"rateCode\":\"58AWBVRMPKQ3HVG6.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0465520000\"}}},\"sku\":\"58AWBVRMPKQ3HVG6\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"resource\":\"per vCPU per hour\",\"cpuArchitecture\":\"ARM\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-ARM-vCPU-Hours:perCPU\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"cputype\":\"perCPU\",\"operation\":\"\"},\"sku\":\"5UAMYEN99PSY23D6\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"5UAMYEN99PSY23D6.JRTCKXETXF\":{\"priceDimensions\":{\"5UAMYEN99PSY23D6.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - ARM - vCPU - US West (Oregon)\",\"appliesTo\":[],\"rateCode\":\"5UAMYEN99PSY23D6.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0323800000\"}}},\"sku\":\"5UAMYEN99PSY23D6\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-vCPU-Hours:perCPU\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"cputype\":\"perCPU\",\"operation\":\"\"},\"sku\":\"EKCCQUSFCBDDTKTS\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"EKCCQUSFCBDDTKTS.JRTCKXETXF\":{\"priceDimensions\":{\"EKCCQUSFCBDDTKTS.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - vCPU - US West 2 (Oregon)\",\"appliesTo\":[],\"rateCode\":\"EKCCQUSFCBDDTKTS.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0404800000\"}}},\"sku\":\"EKCCQUSFCBDDTKTS\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"resource\":\"OS License Fee per vCPU per hour\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-Windows-OS-Hours:perCPU\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"cputype\":\"perCPU OS License Fee\",\"operatingSystem\":\"Windows\",\"operation\":\"\"},\"sku\":\"HTBGRCKVHYXUYEAC\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"HTBGRCKVHYXUYEAC.JRTCKXETXF\":{\"priceDimensions\":{\"HTBGRCKVHYXUYEAC.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - Windows - OS - US West 2 (Oregon)\",\"appliesTo\":[],\"rateCode\":\"HTBGRCKVHYXUYEAC.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0460000000\"}}},\"sku\":\"HTBGRCKVHYXUYEAC\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-GB-Hours\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"memorytype\":\"perGB\",\"operation\":\"\"},\"sku\":\"NTC2QZFJW79R5XVK\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"NTC2QZFJW79R5XVK.JRTCKXETXF\":{\"priceDimensions\":{\"NTC2QZFJW79R5XVK.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - Memory - US West 2 (Oregon)\",\"appliesTo\":[],\"rateCode\":\"NTC2QZFJW79R5XVK.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0044450000\"}}},\"sku\":\"NTC2QZFJW79R5XVK\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"resource\":\"per GB per hour\",\"cpuArchitecture\":\"ARM\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-ARM-GB-Hours\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"memorytype\":\"perGB\",\"operation\":\"\"},\"sku\":\"TAE28FJERF797NWS\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"TAE28FJERF797NWS.JRTCKXETXF\":{\"priceDimensions\":{\"TAE28FJERF797NWS.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - ARM - Memory - US West (Oregon)\",\"appliesTo\":[],\"rateCode\":\"TAE28FJERF797NWS.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0035600000\"}}},\"sku\":\"TAE28FJERF797NWS\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"usagetype\":\"USW2-Fargate-EphemeralStorage-GB-Hours\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"operation\":\"\",\"storagetype\":\"default\"},\"sku\":\"TTWDU5N74ZQ26XMP\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"TTWDU5N74ZQ26XMP.JRTCKXETXF\":{\"priceDimensions\":{\"TTWDU5N74ZQ26XMP.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"GB-Hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - Ephemeral Storage - US West (Oregon)\",\"appliesTo\":[],\"rateCode\":\"TTWDU5N74ZQ26XMP.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0001110000\"}}},\"sku\":\"TTWDU5N74ZQ26XMP\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}", + "{\"product\":{\"productFamily\":\"Compute\",\"attributes\":{\"regionCode\":\"us-west-2\",\"servicecode\":\"AmazonECS\",\"resource\":\"per GB per hour\",\"tenancy\":\"Shared\",\"usagetype\":\"USW2-Fargate-Windows-GB-Hours\",\"locationType\":\"AWS Region\",\"location\":\"US West (Oregon)\",\"servicename\":\"Amazon Elastic Container Service\",\"memorytype\":\"perGB\",\"operatingSystem\":\"Windows\",\"operation\":\"\"},\"sku\":\"ZPUB3WBJWT6K7RSF\"},\"serviceCode\":\"AmazonECS\",\"terms\":{\"OnDemand\":{\"ZPUB3WBJWT6K7RSF.JRTCKXETXF\":{\"priceDimensions\":{\"ZPUB3WBJWT6K7RSF.JRTCKXETXF.6YS6EN2CT7\":{\"unit\":\"hours\",\"endRange\":\"Inf\",\"description\":\"AWS Fargate - Windows - Memory - US West 2 (Oregon)\",\"appliesTo\":[],\"rateCode\":\"ZPUB3WBJWT6K7RSF.JRTCKXETXF.6YS6EN2CT7\",\"beginRange\":\"0\",\"pricePerUnit\":{\"USD\":\"0.0051117500\"}}},\"sku\":\"ZPUB3WBJWT6K7RSF\",\"effectiveDate\":\"2026-11-01T00:00:00Z\",\"offerTermCode\":\"JRTCKXETXF\",\"termAttributes\":{}}}},\"version\":\"20261111234623\",\"publicationDate\":\"2026-11-11T23:46:23Z\"}" + ] +} diff --git a/app/src-tauri/src/aws/pricing/tests.rs b/app/src-tauri/src/aws/pricing/tests.rs new file mode 100644 index 0000000..ad0bc82 --- /dev/null +++ b/app/src-tauri/src/aws/pricing/tests.rs @@ -0,0 +1,418 @@ +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Mutex; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use super::*; +use crate::models::project::{Arch, AwsWorkspaceConfig, StorageMode}; + +/// A real `GetProducts` answer for us-west-2 with [`FILTERS`] (recorded +/// 2026-11-16): the eight Fargate rows, Windows ones included. +const FIXTURE: &str = include_str!("fixtures/get-products-us-west-2.json"); + +fn fixture_items() -> Vec { + let v: Value = serde_json::from_str(FIXTURE).unwrap(); + v["PriceList"] + .as_array() + .unwrap() + .iter() + .map(|s| s.as_str().unwrap().to_string()) + .collect() +} + +const X86: FargateRates = FargateRates { + vcpu_hour: 0.04048, + gb_hour: 0.004445, + storage_gb_hour: 0.000111, +}; +const ARM: FargateRates = FargateRates { + vcpu_hour: 0.03238, + gb_hour: 0.00356, + storage_gb_hour: 0.000111, +}; +const RATES: RegionRates = RegionRates { + x86_64: Some(X86), + arm64: Some(ARM), +}; + +fn close(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-9 +} + +fn cfg(cpu: u32, memory_mib: u32, ephemeral_gib: u32) -> AwsWorkspaceConfig { + AwsWorkspaceConfig { + cpu, + memory_mib, + ephemeral_gib, + ..Default::default() + } +} + +// ---- estimate ---- + +#[test] +fn estimate_is_vcpus_plus_gbs_at_the_pinned_rates() { + // 1 vCPU, 4 GiB, 21 GiB disk (1 billed). + let e = estimate(&cfg(1024, 4096, 21), &X86); + assert!( + close(e.usd_per_hour, 0.04048 + 4.0 * 0.004445 + 0.000111), + "{e:?}" + ); + // 0.25 vCPU, 0.5 GiB, the free 20 GiB only. + let e = estimate(&cfg(256, 512, 20), &X86); + assert!( + close(e.usd_per_hour, 0.25 * 0.04048 + 0.5 * 0.004445), + "{e:?}" + ); + // 4 vCPU, 16 GiB on ARM, 200 GiB disk (180 billed). + let e = estimate(&cfg(4096, 16384, 200), &ARM); + assert!( + close( + e.usd_per_hour, + 4.0 * 0.03238 + 16.0 * 0.00356 + 180.0 * 0.000111 + ), + "{e:?}" + ); +} + +#[test] +fn ephemeral_storage_is_billed_only_above_twenty_gib() { + let free = estimate(&cfg(1024, 2048, 20), &X86).usd_per_hour; + let one = estimate(&cfg(1024, 2048, 21), &X86).usd_per_hour; + let fifty = estimate(&cfg(1024, 2048, 50), &X86).usd_per_hour; + assert!(close(one - free, 0.000111)); + assert!(close(fifty - free, 30.0 * 0.000111)); +} + +#[test] +fn notes_follow_spot_and_storage_and_the_sidecar_adds_nothing() { + let mut c = cfg(1024, 4096, 21); + c.storage = StorageMode::Ephemeral; + let base = estimate(&c, &X86); + assert!(!base.note_spot && !base.efs_billed_separately); + c.spot = true; + assert!(estimate(&c, &X86).note_spot); + for storage in [StorageMode::Hybrid, StorageMode::Efs] { + c.storage = storage; + assert!(estimate(&c, &X86).efs_billed_separately, "{storage:?}"); + } + c.gateway_sidecar = true; + assert!(close(estimate(&c, &X86).usd_per_hour, base.usd_per_hour)); +} + +#[test] +fn rates_are_picked_by_arch() { + assert_eq!(RATES.for_arch(Arch::X86_64), Some(X86)); + assert_eq!(RATES.for_arch(Arch::Arm64), Some(ARM)); +} + +// ---- parsing ---- + +#[test] +fn the_recorded_price_list_parses_to_x86_and_arm_rates() { + let rates = parse_price_list("us-west-2", &fixture_items()).expect("rates"); + assert_eq!(rates, RATES); +} + +#[test] +fn a_price_list_for_another_region_gives_nothing() { + assert_eq!(parse_price_list("eu-west-1", &fixture_items()), None); +} + +#[test] +fn windows_rows_never_count() { + let items: Vec = fixture_items() + .into_iter() + .filter(|s| s.contains("Windows")) + .collect(); + assert_eq!(items.len(), 3); + assert_eq!(parse_price_list("us-west-2", &items), None); +} + +#[test] +fn an_incomplete_architecture_is_none_and_storage_is_required() { + let no_arm: Vec = fixture_items() + .into_iter() + .filter(|s| !s.contains("Fargate-ARM-")) + .collect(); + let rates = parse_price_list("us-west-2", &no_arm).unwrap(); + assert_eq!(rates.x86_64, Some(X86)); + assert_eq!(rates.arm64, None); + + let no_storage: Vec = fixture_items() + .into_iter() + .filter(|s| !s.contains("EphemeralStorage")) + .collect(); + assert_eq!(parse_price_list("us-west-2", &no_storage), None); +} + +#[test] +fn garbage_and_bad_prices_are_skipped() { + let mut items = vec!["not json".to_string(), "{}".to_string()]; + // A negative x86 vCPU price ahead of the real one is ignored. + let bad = fixture_items() + .into_iter() + .find(|s| s.contains("USW2-Fargate-vCPU-Hours")) + .unwrap() + .replace("0.0404800000", "-1"); + items.push(bad); + items.extend(fixture_items()); + assert_eq!(parse_price_list("us-west-2", &items), Some(RATES)); +} + +#[test] +fn the_filters_name_the_region_on_demand_and_fargate() { + assert_eq!(PRICING_REGION, "us-east-1"); + assert_eq!(SERVICE_CODE, "AmazonECS"); + assert!(FILTERS.contains(&("TERM_MATCH", "regionCode", "{region}"))); + assert!(FILTERS.contains(&("TERM_MATCH", "termType", "OnDemand"))); + assert!(FILTERS.contains(&("CONTAINS", "usagetype", "Fargate"))); +} + +// ---- the API, faked ---- + +struct FakeApi { + pages: Mutex>>, + calls: AtomicUsize, + hang: bool, +} + +impl FakeApi { + fn answering(pages: Vec>) -> Self { + Self { + pages: Mutex::new(pages), + calls: AtomicUsize::new(0), + hang: false, + } + } + fn fixture() -> Self { + Self::answering(vec![Ok(Page { + items: fixture_items(), + next_token: None, + })]) + } + fn denied() -> Self { + Self::answering(vec![Err("Access denied: pricing:GetProducts".to_string())]) + } + fn hanging() -> Self { + Self { + hang: true, + ..Self::answering(vec![]) + } + } + fn calls(&self) -> usize { + self.calls.load(Ordering::SeqCst) + } +} + +impl PricingApi for FakeApi { + async fn get_products(&self, region: &str, _token: Option) -> Result { + assert_eq!(region, "us-west-2"); + self.calls.fetch_add(1, Ordering::SeqCst); + if self.hang { + std::future::pending::<()>().await; + } + let mut pages = self.pages.lock().unwrap(); + if pages.is_empty() { + return Err("no more pages".to_string()); + } + pages.remove(0) + } +} + +#[tokio::test] +async fn pages_are_joined() { + let items = fixture_items(); + let (a, b) = items.split_at(4); + let api = FakeApi::answering(vec![ + Ok(Page { + items: a.to_vec(), + next_token: Some("t".to_string()), + }), + Ok(Page { + items: b.to_vec(), + next_token: None, + }), + ]); + assert_eq!(fetch_rates(&api, "us-west-2").await, Ok(RATES)); + assert_eq!(api.calls(), 2); +} + +// ---- the cache ---- + +fn at(secs: u64) -> SystemTime { + UNIX_EPOCH + Duration::from_secs(secs) +} +const T0: u64 = 1_800_000_000; +const DAY: u64 = 24 * 60 * 60; + +fn cache() -> (tempfile::TempDir, RatesCache) { + let dir = tempfile::tempdir().unwrap(); + let cache = RatesCache::new(dir.path().join("aws-pricing")); + (dir, cache) +} + +#[test] +fn a_cache_file_is_fresh_for_a_day() { + let (_d, c) = cache(); + assert_eq!(c.read("us-west-2", at(T0)), None); + c.write("us-west-2", &RATES, at(T0)).unwrap(); + assert!(c.dir().join("us-west-2.json").is_file()); + assert_eq!(c.read("us-west-2", at(T0 + DAY - 1)), Some((RATES, true))); + assert_eq!(c.read("us-west-2", at(T0 + DAY)), Some((RATES, false))); + // From the future (the clock went back): stale. + assert_eq!(c.read("us-west-2", at(T0 - 10)), Some((RATES, false))); + // Another region's file is not this one's. + assert_eq!(c.read("eu-west-1", at(T0)), None); +} + +#[test] +fn a_corrupt_or_mislabelled_cache_file_is_no_cache() { + let (_d, c) = cache(); + std::fs::create_dir_all(c.dir()).unwrap(); + std::fs::write(c.dir().join("us-west-2.json"), "{ not json").unwrap(); + assert_eq!(c.read("us-west-2", at(T0)), None); + c.write("eu-west-1", &RATES, at(T0)).unwrap(); + std::fs::copy( + c.dir().join("eu-west-1.json"), + c.dir().join("us-west-2.json"), + ) + .unwrap(); + assert_eq!(c.read("us-west-2", at(T0)), None); +} + +#[tokio::test] +async fn a_fresh_cache_answers_without_a_call() { + let (_d, c) = cache(); + c.write("us-west-2", &RATES, at(T0)).unwrap(); + let api = FakeApi::denied(); + assert_eq!( + c.rates(Some(&api), "us-west-2", at(T0 + 60)).await, + Some(RATES) + ); + assert_eq!(api.calls(), 0); +} + +#[tokio::test] +async fn a_miss_fetches_and_writes_the_cache() { + let (_d, c) = cache(); + let api = FakeApi::fixture(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(T0)).await, Some(RATES)); + assert_eq!(api.calls(), 1); + assert_eq!(c.read("us-west-2", at(T0 + 1)), Some((RATES, true))); +} + +#[tokio::test] +async fn an_expired_cache_is_fetched_again() { + let (_d, c) = cache(); + let old = RegionRates { + x86_64: Some(FargateRates { + vcpu_hour: 1.0, + ..X86 + }), + arm64: None, + }; + c.write("us-west-2", &old, at(T0)).unwrap(); + let api = FakeApi::fixture(); + assert_eq!( + c.rates(Some(&api), "us-west-2", at(T0 + DAY)).await, + Some(RATES) + ); + assert_eq!(api.calls(), 1); + assert_eq!(c.read("us-west-2", at(T0 + DAY)), Some((RATES, true))); +} + +#[tokio::test] +async fn a_corrupt_cache_is_fetched_again() { + let (_d, c) = cache(); + std::fs::create_dir_all(c.dir()).unwrap(); + std::fs::write(c.dir().join("us-west-2.json"), "garbage").unwrap(); + let api = FakeApi::fixture(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(T0)).await, Some(RATES)); + assert_eq!(c.read("us-west-2", at(T0)), Some((RATES, true))); +} + +#[tokio::test] +async fn denied_is_none_and_is_not_asked_again_for_a_while() { + let (_d, c) = cache(); + let api = FakeApi::denied(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(T0)).await, None); + assert_eq!(c.rates(Some(&api), "us-west-2", at(T0 + 60)).await, None); + assert_eq!(api.calls(), 1, "a recent failure is not retried"); + let later = T0 + RETRY_AFTER_FAILURE.as_secs(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(later)).await, None); + assert_eq!(api.calls(), 2); + assert!(!c.dir().join("us-west-2.json").exists()); +} + +#[tokio::test] +async fn a_failed_refresh_falls_back_to_the_stale_cache() { + let (_d, c) = cache(); + c.write("us-west-2", &RATES, at(T0)).unwrap(); + let api = FakeApi::denied(); + assert_eq!( + c.rates(Some(&api), "us-west-2", at(T0 + 2 * DAY)).await, + Some(RATES) + ); + assert_eq!(api.calls(), 1); + // No client at all (e.g. the connection's keys are gone): stale still answers. + assert_eq!( + c.rates(None::<&FakeApi>, "us-west-2", at(T0 + 2 * DAY)) + .await, + Some(RATES) + ); +} + +#[tokio::test(start_paused = true)] +async fn a_hanging_api_times_out_to_none() { + let (_d, c) = cache(); + let api = FakeApi::hanging(); + let started = tokio::time::Instant::now(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(T0)).await, None); + assert_eq!(started.elapsed(), FETCH_TIMEOUT); + assert_eq!(api.calls(), 1); +} + +#[tokio::test(start_paused = true)] +async fn building_the_client_counts_against_the_same_timeout() { + let (_d, c) = cache(); + c.write("us-west-2", &RATES, at(T0)).unwrap(); + let started = tokio::time::Instant::now(); + // The client never gets built (credentials that hang): stale answers at + // the fetch's own bound, not later. + let r = c + .rates_with::(std::future::pending(), "us-west-2", at(T0 + 2 * DAY)) + .await; + assert_eq!(r, Some(RATES)); + assert_eq!(started.elapsed(), FETCH_TIMEOUT); + + // A fresh cache never builds a client at all. + let fresh = c + .rates_with::( + async { panic!("no client is built for a fresh cache") }, + "us-west-2", + at(T0 + 60), + ) + .await; + assert_eq!(fresh, Some(RATES)); +} + +#[tokio::test] +async fn no_client_counts_as_a_failure_and_is_not_asked_again_for_a_while() { + let (_d, c) = cache(); + let none = || async { None:: }; + assert_eq!(c.rates_with::(none(), "us-west-2", at(T0)).await, None); + // Within the back-off the client is not even built. + let r = c + .rates_with::( + async { panic!("no client is built within the back-off") }, + "us-west-2", + at(T0 + 60), + ) + .await; + assert_eq!(r, None); + // After it, a working client is asked and clears the failure. + let api = FakeApi::fixture(); + let later = T0 + RETRY_AFTER_FAILURE.as_secs(); + assert_eq!(c.rates(Some(&api), "us-west-2", at(later)).await, Some(RATES)); + assert_eq!(api.calls(), 1); +} diff --git a/app/src-tauri/src/aws/runtime.rs b/app/src-tauri/src/aws/runtime.rs index 8241292..8dc313b 100644 --- a/app/src-tauri/src/aws/runtime.rs +++ b/app/src-tauri/src/aws/runtime.rs @@ -18,7 +18,7 @@ use super::environments::{knowable, parse_environment_record, EnvironmentInfo, K use super::error::{classify_sdk_error, AwsError}; use super::tasks::{find_project_task, TaskApi, STOP_REASON}; use super::tofu_modules::{ - access_point_root, environment_cluster_name, environment_parameter_name, project_secret_name, task_family, + access_point_root, workspace_access_point_root, environment_cluster_name, environment_parameter_name, project_secret_name, task_family, user_file_system_token, user_role_names, }; use super::workspace::WorkspaceApi; @@ -234,15 +234,18 @@ pub struct RemoveRequest<'a> { /// missed it). pub stored_task_arn: Option<&'a str>, pub stored_access_point_id: Option<&'a str>, - /// Delete the EFS access point (ruling R9). The files stay on the - /// user's own file system (only their task role can read it) until - /// offboarding destroys it; a later start of the same project gets a new - /// access point onto the same directory. + /// The EFS-mode `/workspace` access point the store has (kept after a + /// switch to Hybrid or Ephemeral, Q1). + pub stored_workspace_access_point_id: Option<&'a str>, + /// Delete the EFS access points, home and `/workspace` (ruling R9). The + /// files stay on the user's own file system (only their task role can + /// read it) until offboarding destroys it; a later start of the same + /// project gets new access points onto the same directories. pub discard_data: bool, } /// Stop the project's task, delete its secret (no recovery window, R10) and, -/// with `discard_data`, delete its access point (not the files, R9). Task definition revisions +/// with `discard_data`, delete its access points (not the files, R9). Task definition revisions /// are left registered (R8). A task that can't be stopped stops the removal (nothing /// billed may be left running); the rest is attempted in full and every /// failure reported. @@ -288,20 +291,27 @@ pub async fn remove_workspace_resources = req.stored_access_point_id.map(String::from).into_iter().collect(); + let mut ids: Vec = [req.stored_access_point_id, req.stored_workspace_access_point_id] + .into_iter() + .flatten() + .map(String::from) + .collect(); let token = user_file_system_token(req.env, req.owner_key); match work.find_file_system(&token).await { Ok(Some(fs)) if fs.owner.as_deref() == Some(req.owner_user_id) => { - let root = access_point_root(req.owner_key, req.project_id); + let roots = [ + access_point_root(req.owner_key, req.project_id), + workspace_access_point_root(req.owner_key, req.project_id), + ]; match work.access_points(&fs.id).await { Ok(points) => ids.extend( points .into_iter() .filter(|a| { a.file_system_id == fs.id - && a.root_path.as_deref() == Some(root.as_str()) + && a.root_path.as_ref().is_some_and(|r| roots.contains(r)) && a.owner.as_deref() == Some(req.owner_user_id) && a.project.as_deref() == Some(req.project_id) }) diff --git a/app/src-tauri/src/aws/runtime/tests.rs b/app/src-tauri/src/aws/runtime/tests.rs index 7c9111c..dc39a8b 100644 --- a/app/src-tauri/src/aws/runtime/tests.rs +++ b/app/src-tauri/src/aws/runtime/tests.rs @@ -5,7 +5,7 @@ use aws_sdk_ecs::operation::run_task::RunTaskInput; use super::*; use crate::aws::tasks::TaskInfo; -use crate::aws::tofu_modules::owner_key; +use crate::aws::tofu_modules::{owner_key, workspace_access_point_root}; use crate::aws::workspace::{AccessPointRef, FileSystemRef, TaskDefinitionRef}; const REGION: &str = "eu-west-1"; @@ -112,6 +112,22 @@ impl WorkspaceApi for Fake { ) -> Result { unreachable!() } + async fn project_secret_value(&self, _n: &str) -> Result, AwsError> { + unreachable!() + } + async fn create_project_secret( + &self, + n: &str, + k: &str, + j: &str, + t: &[(String, String)], + ) -> Result, AwsError> { + let _ = (n, k, j, t); + unreachable!() + } + async fn delete_project_secret(&self, _n: &str) -> Result<(), AwsError> { + unreachable!() + } async fn put_project_secret( &self, _n: &str, @@ -288,6 +304,7 @@ async fn removal_stops_the_task_leaves_the_revisions_and_schedules_the_secret() project_id: PROJECT, stored_task_arn: Some(&t0), stored_access_point_id: Some("fsap-stored"), + stored_workspace_access_point_id: None, discard_data: false, }; remove_workspace_resources(&fake, &fake, &fake, &r).await.unwrap(); @@ -323,9 +340,65 @@ async fn a_failed_step_is_reported_but_the_rest_still_runs() { project_id: PROJECT, stored_task_arn: None, stored_access_point_id: Some("fsap-1"), + stored_workspace_access_point_id: None, discard_data: true, }; let e = remove_workspace_resources(&fake, &fake, &fake, &r).await.unwrap_err(); assert!(e.to_string().contains("secret"), "{e}"); assert!(fake.calls().contains(&"delete-ap fsap-1".to_string())); } + +#[tokio::test] +async fn removal_with_discard_deletes_both_access_points_and_without_keeps_both() { + let ap = |id: &str, root: String| AccessPointRef { + id: id.into(), + file_system_id: "fs-1".into(), + root_path: Some(root), + owner: Some(USER.into()), + project: Some(PROJECT.into()), + state: Some("available".into()), + }; + let points = vec![ + ap("fsap-home", access_point_root(&ok(), PROJECT)), + ap("fsap-ws", workspace_access_point_root(&ok(), PROJECT)), + AccessPointRef { + owner: Some("AROAOTHER:mallory".into()), + ..ap("fsap-foreign", workspace_access_point_root(&ok(), PROJECT)) + }, + AccessPointRef { + project: Some("another".into()), + ..ap("fsap-other-project", workspace_access_point_root(&ok(), PROJECT)) + }, + ]; + let key = ok(); + let mut r = RemoveRequest { + env: "dev", + region: REGION, + owner_user_id: USER, + owner_key: &key, + project_id: PROJECT, + stored_task_arn: None, + stored_access_point_id: Some("fsap-home"), + // Kept in the store after switching EFS -> Hybrid. + stored_workspace_access_point_id: Some("fsap-ws-stored"), + discard_data: false, + }; + let keep = Fake { access_points: points.clone(), ..Default::default() }; + remove_workspace_resources(&keep, &keep, &keep, &r).await.unwrap(); + assert!( + keep.calls().iter().all(|c| !c.starts_with("delete-ap")), + "{:?}", + keep.calls() + ); + + r.discard_data = true; + let discard = Fake { access_points: points, ..Default::default() }; + remove_workspace_resources(&discard, &discard, &discard, &r).await.unwrap(); + let mut deleted: Vec = discard + .calls() + .into_iter() + .filter_map(|c| c.strip_prefix("delete-ap ").map(String::from)) + .collect(); + deleted.sort(); + assert_eq!(deleted, vec!["fsap-home", "fsap-ws", "fsap-ws-stored"]); +} diff --git a/app/src-tauri/src/aws/tasks.rs b/app/src-tauri/src/aws/tasks.rs index b4167cb..1f69219 100644 --- a/app/src-tauri/src/aws/tasks.rs +++ b/app/src-tauri/src/aws/tasks.rs @@ -483,6 +483,11 @@ async fn stopped_error(api: &A, logs: &TaskLogs, t: &TaskInfo) -> Aw /// so an idle stop (`EssentialContainerExited`) is not mistaken for a crash. pub const IDLE_EXIT_CODE: i32 = 75; +/// The entrypoint's exit status after the environment's lifetime cap stopped +/// the workspace (`TRIPLEC_MAX_LIFETIME_MINUTES`, enforced by the in-container +/// idle watcher — advisory, see the phase 6 constraints, Q8). +pub const LIFETIME_EXIT_CODE: i32 = 76; + /// Why a task stopped, as the app reports it (spec, "Lifecycle and status"). #[derive(Debug, Clone, PartialEq, Eq)] pub enum StopKind { @@ -491,6 +496,8 @@ pub enum StopKind { Exited(Option), /// The workspace's own idle stop ([`IDLE_EXIT_CODE`]). Idle, + /// The environment's maximum workspace lifetime ([`LIFETIME_EXIT_CODE`]). + LifetimeCap, /// A Fargate Spot interruption (P8). Spot, /// Never got going: the project goes to Error with this reason. @@ -510,6 +517,9 @@ pub fn classify_stop(info: &TaskInfo) -> StopKind { ), Some("UserInitiated") => StopKind::UserInitiated, Some("EssentialContainerExited") if info.exit_code == Some(IDLE_EXIT_CODE) => StopKind::Idle, + Some("EssentialContainerExited") if info.exit_code == Some(LIFETIME_EXIT_CODE) => { + StopKind::LifetimeCap + } _ => StopKind::Exited(info.stopped_reason.clone().filter(|r| !r.trim().is_empty())), } } diff --git a/app/src-tauri/src/aws/tasks/tests.rs b/app/src-tauri/src/aws/tasks/tests.rs index fdd6eb2..31284f3 100644 --- a/app/src-tauri/src/aws/tasks/tests.rs +++ b/app/src-tauri/src/aws/tasks/tests.rs @@ -41,6 +41,7 @@ fn env_info() -> EnvironmentInfo { log_group: "/triple-c/dev".into(), network_mode: "public".into(), tenancy: "strict".into(), + max_workspace_hours: 0, } } @@ -651,6 +652,11 @@ fn classify_stop_follows_the_spec_table() { // The entrypoint's idle stop exits with its own status. let idle = TaskInfo { exit_code: Some(IDLE_EXIT_CODE), ..with(Some("EssentialContainerExited"), None) }; assert_eq!(classify_stop(&idle), StopKind::Idle); + // So does its lifetime-cap stop. + let capped = TaskInfo { exit_code: Some(LIFETIME_EXIT_CODE), ..with(Some("EssentialContainerExited"), None) }; + assert_eq!(classify_stop(&capped), StopKind::LifetimeCap); + let user_capped = TaskInfo { exit_code: Some(LIFETIME_EXIT_CODE), ..with(Some("UserInitiated"), None) }; + assert_eq!(classify_stop(&user_capped), StopKind::UserInitiated); let crashed = TaskInfo { exit_code: Some(137), ..with(Some("EssentialContainerExited"), None) }; assert_eq!(classify_stop(&crashed), StopKind::Exited(None)); // Only with that stop code: a user stop of a task that exits 75 is a user stop. diff --git a/app/src-tauri/src/aws/tofu_modules.rs b/app/src-tauri/src/aws/tofu_modules.rs index 28943c7..09ebece 100644 --- a/app/src-tauri/src/aws/tofu_modules.rs +++ b/app/src-tauri/src/aws/tofu_modules.rs @@ -15,7 +15,7 @@ use crate::models::host_connection::validate_supported_region; /// `locals.template_version` (and the `triple-c:template-version` default /// tag) of `aws/terraform/environment`. -pub const ENVIRONMENT_MODULE_VERSION: u32 = 1; +pub const ENVIRONMENT_MODULE_VERSION: u32 = 2; /// The same for the user-onboarding module. #[allow(dead_code)] // the onboarding module's version; checked against its HCL by a test pub const ONBOARD_MODULE_VERSION: u32 = 1; @@ -202,6 +202,17 @@ pub fn access_point_root(owner_key: &str, project_id: &str) -> String { format!("/triple-c/{owner_key}/{}", project_component(project_id)) } +/// The root of the project's EFS-mode `/workspace` access point (Q1): +/// `/triple-c-workspaces//`, a sibling tree of the home +/// roots (under [`access_point_root`] it would sit inside the home access +/// point). At most 100 characters. +pub fn workspace_access_point_root(owner_key: &str, project_id: &str) -> String { + format!( + "/triple-c-workspaces/{owner_key}/{}", + project_component(project_id) + ) +} + /// The container's `awslogs-stream-prefix`; ECS names the stream /// `/workspace/`. pub fn log_stream_prefix(owner_key: &str, project_id: &str) -> String { @@ -274,14 +285,23 @@ fn is_aws_id(id: &str, prefix: &str) -> bool { }) } +/// The longest lifetime cap an environment can carry, in hours (a week). +pub const MAX_WORKSPACE_HOURS: u32 = 168; + /// The environment module's `terraform.tfvars.json`. Applies the same rules /// as the module's variable validations, so a bad value fails here first. pub fn environment_vars( env: &str, region: &str, network: &NetworkChoice, + max_workspace_hours: u32, ) -> Result { let env = validate_environment_name(env)?; + if max_workspace_hours > MAX_WORKSPACE_HOURS { + return Err(format!( + "The maximum workspace lifetime is at most {MAX_WORKSPACE_HOURS} hours (0 = no cap)" + )); + } let region = validate_supported_region(region)?; let (mode, vpc_id, subnet_ids, assign_public_ip) = match network { NetworkChoice::Public => ("public", String::new(), Vec::new(), false), @@ -322,6 +342,7 @@ pub fn environment_vars( "vpc_id": vpc_id, "subnet_ids": subnet_ids, "assign_public_ip": assign_public_ip, + "max_workspace_hours": max_workspace_hours, })) } diff --git a/app/src-tauri/src/aws/tofu_modules/tests.rs b/app/src-tauri/src/aws/tofu_modules/tests.rs index 1b4cf15..0c7303f 100644 --- a/app/src-tauri/src/aws/tofu_modules/tests.rs +++ b/app/src-tauri/src/aws/tofu_modules/tests.rs @@ -7,7 +7,7 @@ use serde_json::json; use super::*; use crate::aws::policies::PERMISSIONS_BOUNDARY_NAME; -const RECORD_FIELDS: [&str; 11] = [ +const RECORD_FIELDS: [&str; 12] = [ "schema", "name", "template_version", @@ -19,9 +19,10 @@ const RECORD_FIELDS: [&str; 11] = [ "log_group", "network_mode", "tenancy", + "max_workspace_hours", ]; -const VARIABLES: [&str; 7] = [ +const VARIABLES: [&str; 8] = [ "environment_name", "region", "network_mode", @@ -29,6 +30,7 @@ const VARIABLES: [&str; 7] = [ "subnet_ids", "assign_public_ip", "log_retention_days", + "max_workspace_hours", ]; /// Every `.tf` file of `kind`, parsed and merged into one body. @@ -345,7 +347,7 @@ fn the_onboarding_completion_output_waits_for_every_resource() { #[test] fn the_module_versions_agree() { - assert_eq!(ENVIRONMENT_MODULE_VERSION, 1); + assert_eq!(ENVIRONMENT_MODULE_VERSION, 2); assert_eq!(ONBOARD_MODULE_VERSION, 1); let body = parsed(ModuleKind::Environment); let locals: Vec<_> = top_blocks(&body, "locals") @@ -591,7 +593,7 @@ fn module_files_ship_the_lock_file() { #[test] fn environment_vars_cover_every_network_mode() { - let vars = environment_vars("dev", "us-west-2", &NetworkChoice::Public).unwrap(); + let vars = environment_vars("dev", "us-west-2", &NetworkChoice::Public, 0).unwrap(); assert_eq!( vars, json!({ @@ -601,9 +603,11 @@ fn environment_vars_cover_every_network_mode() { "vpc_id": "", "subnet_ids": [], "assign_public_ip": false, + "max_workspace_hours": 0, }) ); - let vars = environment_vars("dev", "us-west-2", &NetworkChoice::PrivateNat).unwrap(); + let vars = environment_vars("dev", "us-west-2", &NetworkChoice::PrivateNat, 8).unwrap(); + assert_eq!(vars["max_workspace_hours"], 8); assert_eq!(vars["network_mode"], "private-nat"); assert_eq!(vars["subnet_ids"], json!([])); @@ -613,7 +617,8 @@ fn environment_vars_cover_every_network_mode() { assign_public_ip: true, }; let two = ["subnet-0123456789abcdef0", "subnet-89abcdef"]; - let vars = environment_vars("dev", "eu-central-1", &existing("vpc-0a1b2c3d", &two)).unwrap(); + let vars = + environment_vars("dev", "eu-central-1", &existing("vpc-0a1b2c3d", &two), 168).unwrap(); assert_eq!( vars, json!({ @@ -623,6 +628,7 @@ fn environment_vars_cover_every_network_mode() { "vpc_id": "vpc-0a1b2c3d", "subnet_ids": two, "assign_public_ip": true, + "max_workspace_hours": 168, }) ); // Every variable the app sets is one the module declares. @@ -648,13 +654,14 @@ fn environment_vars_cover_every_network_mode() { existing("vpc-0a1b2c3d", &["subnet-0123456789abcdef0", "sg-89abcdef"]), ] { assert!( - environment_vars("dev", "us-west-2", &bad).is_err(), + environment_vars("dev", "us-west-2", &bad, 0).is_err(), "{bad:?} accepted" ); } - assert!(environment_vars("Dev", "us-west-2", &NetworkChoice::Public).is_err()); - assert!(environment_vars("dev", "us-west-2;", &NetworkChoice::Public).is_err()); - assert!(environment_vars("dev", "cn-north-1", &NetworkChoice::Public).is_err()); + assert!(environment_vars("Dev", "us-west-2", &NetworkChoice::Public, 0).is_err()); + assert!(environment_vars("dev", "us-west-2;", &NetworkChoice::Public, 0).is_err()); + assert!(environment_vars("dev", "cn-north-1", &NetworkChoice::Public, 0).is_err()); + assert!(environment_vars("dev", "us-west-2", &NetworkChoice::Public, 169).is_err()); // The command layer receives the choice as tagged JSON. let parsed: NetworkChoice = serde_json::from_value(json!({ @@ -2121,3 +2128,28 @@ fn every_module_write_has_an_admin_check_and_vice_versa() { .collect(); assert!(stale.is_empty(), "APP_ONLY_WRITES is stale: {stale:?}"); } + +#[test] +fn the_lifetime_cap_maximum_is_the_same_in_rust_typescript_and_hcl() { + let max = MAX_WORKSPACE_HOURS.to_string(); + let vars = module_files(ModuleKind::Environment) + .iter() + .find(|(f, _)| *f == "variables.tf") + .unwrap() + .1; + let block = &vars[vars.find("variable \"max_workspace_hours\"").expect("the variable")..]; + let block = &block[..block.find("\n}\n").unwrap()]; + assert!( + block.contains(&format!("var.max_workspace_hours <= {max}")), + "the HCL validation's maximum: {block}" + ); + assert!(block.contains(&format!("from 0 to {max}")), "{block}"); + let ts = include_str!("../../../../src/components/settings/hosts/LifetimeCapField.tsx"); + assert!( + ts.contains(&format!("export const MAX_WORKSPACE_HOURS = {max};")), + "LifetimeCapField.tsx's MAX_WORKSPACE_HOURS" + ); + // And the record parser's message. + let envs = include_str!("../environments.rs"); + assert!(envs.contains(&format!("from 0 to {max}"))); +} diff --git a/app/src-tauri/src/aws/workspace.rs b/app/src-tauri/src/aws/workspace.rs index 482b7ce..f41fa67 100644 --- a/app/src-tauri/src/aws/workspace.rs +++ b/app/src-tauri/src/aws/workspace.rs @@ -1,5 +1,6 @@ //! A project's AWS resources, made ready before its task runs: the project -//! secret, the EFS access point (Hybrid storage) and the task definition. +//! secret, the EFS access points (Hybrid: home; EFS: home and `/workspace`) +//! and the task definition. //! //! **Everything project-shaped goes in the secret (P1).** Every workspace user //! has `ecs:Describe*` on `*`, so a task definition's `environment`, tags and @@ -43,10 +44,10 @@ use super::error::{classify_sdk_error, AwsError}; use super::identity::CallerIdentity; use super::tofu_modules::{ access_point_root, log_stream_prefix, owner_key, project_secret_name, task_family, - user_file_system_token, user_role_names, + user_file_system_token, user_role_names, workspace_access_point_root, }; use crate::host::ssm::AGENT_PORT; -use crate::models::project::{validate_aws_workspace, Arch, RepoSource, StorageMode}; +use crate::models::project::{validate_aws_workspace, Arch, RepoSource, SecretsDelivery, StorageMode}; use crate::models::Project; pub const TAG_OWNER: &str = "triple-c:owner"; @@ -59,6 +60,9 @@ pub const CONTAINER_NAME: &str = "workspace"; /// Where a Hybrid project's access point is mounted (P4). pub const HOME_MOUNT_PATH: &str = "/mnt/triple-c-home"; const HOME_VOLUME: &str = "home"; +/// Where an EFS-mode project's second access point is mounted (Q1). +pub const WORKSPACE_MOUNT_PATH: &str = "/workspace"; +const WORKSPACE_VOLUME: &str = "workspace"; /// Secrets Manager's `SecretString` limit. pub const MAX_SECRET_BYTES: usize = 65_536; /// At most this many of a family's newest revisions are described when @@ -74,6 +78,28 @@ const KEY_REPOS: &str = "TRIPLEC_REPOS"; const KEY_WIP_PUSH: &str = "TRIPLEC_WIP_PUSH"; const KEY_IDLE: &str = "TRIPLEC_IDLE_STOP_MINUTES"; const KEY_STORAGE: &str = "TRIPLEC_STORAGE"; +const KEY_SETUP_SCRIPT: &str = "TRIPLEC_SETUP_SCRIPT"; +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; @@ -113,8 +139,9 @@ fn is_env_name(key: &str) -> bool { } /// `ssh/` or `ca/`, the file name non-empty, without `/`, and -/// not `.` or `..` (R1: the entrypoint writes it under `/tmp/.host-*/`). -fn validate_file_key(key: &str) -> Result<(), String> { +/// not `.` or `..` (R1: the entrypoint writes it under `/tmp/.host-*/`; +/// copy-at-connect uploads it under `/dev/shm/triple-c/connect/*/`). +pub(crate) fn validate_file_key(key: &str) -> Result<(), String> { let file = key .strip_prefix("ssh/") .or_else(|| key.strip_prefix("ca/")) @@ -128,6 +155,94 @@ fn validate_file_key(key: &str) -> Result<(), String> { Ok(()) } +/// Payload keys that come from the project's AWS settings and its +/// environment rather than from the env pairs (phase 6). +#[derive(Debug, Clone, Copy, Default)] +pub struct PayloadExtras<'a> { + /// `AwsWorkspaceConfig::setup_script`; blank is the same as none. + pub setup_script: Option<&'a str>, + /// The environment's cap (`max_workspace_hours`), in hours; 0 = none. + pub max_workspace_hours: u32, + /// Copy-at-connect (Q2): the names of the project's custom environment + /// variables. With it, the credentials ([`is_credential_key`]) and + /// `TRIPLEC_FILES` stay out of the secret and `TRIPLEC_CREDENTIALS` is + /// `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. +const CUSTOM_ENV_FINGERPRINT: &str = "TRIPLE_C_CUSTOM_ENV"; + +/// A credential, for copy-at-connect: an API key or token Triple-C manages +/// (`SECRET_ENV_KEYS`, `GIT_TOKEN` included) or any custom variable — a +/// custom value may be a key, and nothing tells which. +pub fn is_credential_key(key: &str, custom_keys: &[String]) -> bool { + crate::docker::container::SECRET_ENV_KEYS.contains(&key) || custom_keys.iter().any(|c| c == key) +} + +/// The credential pairs of `env_pairs` ([`is_credential_key`]), in order: +/// what copy-at-connect copies in and adds to the terminals' environment. +pub fn credential_pairs(env_pairs: &[(String, String)], custom_keys: &[String]) -> Vec<(String, String)> { + env_pairs + .iter() + .filter(|(k, _)| is_credential_key(k, custom_keys)) + .cloned() + .collect() +} + +#[allow(clippy::too_many_arguments)] fn payload_map( env_pairs: &[(String, String)], agent_token: &str, @@ -136,6 +251,7 @@ fn payload_map( wip: bool, idle: Option, storage: StorageMode, + extras: PayloadExtras<'_>, ) -> Result, String> { let own = [ KEY_AGENT_TOKEN, @@ -144,6 +260,12 @@ fn payload_map( KEY_WIP_PUSH, KEY_IDLE, KEY_STORAGE, + 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 { @@ -164,6 +286,16 @@ fn payload_map( log::warn!("Ignoring the environment variable {k}: Triple-C sets it on AWS"); continue; } + // Copy-at-connect: copied in after each connect, never stored. The + // custom variables' fingerprint goes too: an unsalted hash of their + // values would let a low-entropy one be guessed offline (and nothing + // on AWS reads it; Docker uses it to notice a change). + if extras + .connect_only + .is_some_and(|custom| is_credential_key(k, custom) || k == CUSTOM_ENV_FINGERPRINT) + { + continue; + } m.insert(k.clone(), v.clone()); } let b64 = base64::engine::general_purpose::STANDARD; @@ -173,7 +305,28 @@ fn payload_map( file_map.insert(k.clone(), b64.encode(bytes)); } m.insert(KEY_AGENT_TOKEN.into(), agent_token.into()); - m.insert(KEY_FILES.into(), json(&file_map)); + // The agent token stays either way: it is how the app reaches the task. + if extras.connect_only.is_some() { + // The SSH keys and CA files arrive with the connect too. + m.insert(KEY_CREDENTIALS.into(), "connect".into()); + } else { + m.insert(KEY_FILES.into(), json(&file_map)); + } + // Ruling R1 (Task 8): the LLM gateway sidecar starts before any connect, + // 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. 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 { @@ -184,9 +337,19 @@ fn payload_map( match storage { StorageMode::Ephemeral => "ephemeral", StorageMode::Hybrid => "hybrid", + StorageMode::Efs => "efs", } .into(), ); + if let Some(script) = extras.setup_script.filter(|s| !s.trim().is_empty()) { + m.insert(KEY_SETUP_SCRIPT.into(), script.into()); + } + if extras.max_workspace_hours > 0 { + m.insert( + KEY_MAX_LIFETIME.into(), + (u64::from(extras.max_workspace_hours) * 60).to_string(), + ); + } Ok(m) } @@ -195,26 +358,71 @@ fn json(v: &T) -> String { serde_json::to_string(v).expect("plain data serialises") } +/// What a payload key is, in the size error's words. Custom variables are +/// named (names are not secret; values never appear). +fn describe_payload_key(key: &str) -> String { + match key { + KEY_SETUP_SCRIPT => "the setup script".into(), + KEY_FILES => "the SSH and CA files".into(), + KEY_REPOS => "the repository list".into(), + "CLAUDE_INSTRUCTIONS" => "the instructions".into(), + "CLAUDE_CODE_SETTINGS_JSON" => "the Claude Code settings".into(), + CUSTOM_ENV_FINGERPRINT => "the custom environment variables".into(), + k if k.starts_with("TRIPLEC_GATEWAY_") => "the LLM gateway configuration".into(), + k => format!("the environment variable {k}"), + } +} + +/// `n` bytes in KiB, rounded up (so a part is never shown as 0 KiB). +fn kib(n: usize) -> usize { + n.div_ceil(1024) +} + fn serialize_payload(m: &BTreeMap) -> Result { let json = serde_json::to_string(m).expect("a string map serialises"); if json.len() > MAX_SECRET_BYTES { + // Name what is large: the parts add up (setup script ≤ 32 KiB, + // gateway config, instructions, files…), so the total alone does not + // say what to shorten. A part's size is its serialised value. + let mut parts: Vec<(usize, &str)> = m + .iter() + .map(|(k, v)| (serde_json::to_string(v).map_or(v.len(), |j| j.len()), k.as_str())) + .collect(); + parts.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(b.1))); + let largest: Vec = parts + .iter() + .take(3) + .filter(|(n, _)| *n >= 1024) + .map(|(n, k)| format!("{} ({} KiB)", describe_payload_key(k), kib(*n))) + .collect(); + let detail = if largest.is_empty() { + String::new() + } else { + format!(" The largest parts: {}.", largest.join(", ")) + }; return Err(format!( - "The project's settings for AWS come to {} bytes, more than the 65,536 a Secrets \ - Manager secret holds. Shorten the instructions, Claude Code settings or custom \ - environment variables, or remove files from the SSH folder.", + "The project's settings for AWS come to {} KiB ({} bytes), more than the 64 KiB \ + (65,536 bytes) a Secrets Manager secret holds.{detail} Shorten the setup script, \ + instructions, Claude Code settings or custom environment variables, or remove \ + files from the SSH folder.", + kib(json.len()), json.len() )); } Ok(json) } -/// The project secret's JSON (P1, R1): every env pair, then the payload's own -/// keys (`TRIPLEC_AGENT_TOKEN`, `TRIPLEC_FILES` = `{"ssh/"|"ca/": base64}`, +/// The project secret's JSON (P1, R1): every env pair (under copy-at-connect, +/// every one but the credentials), then the payload's own keys +/// (`TRIPLEC_AGENT_TOKEN`, `TRIPLEC_FILES` = `{"ssh/"|"ca/": base64}` +/// — or, under copy-at-connect, `TRIPLEC_CREDENTIALS` = `connect` instead — /// `TRIPLEC_REPOS`, `TRIPLEC_WIP_PUSH` = `1`/`0`, `TRIPLEC_IDLE_STOP_MINUTES` -/// when on, `TRIPLEC_STORAGE` = `ephemeral`/`hybrid`), keys sorted. Fails -/// when it would exceed 65,536 bytes. +/// when on, `TRIPLEC_STORAGE` = `ephemeral`/`hybrid`/`efs`, +/// `TRIPLEC_SETUP_SCRIPT` when set, `TRIPLEC_MAX_LIFETIME_MINUTES` when the +/// environment caps it), keys sorted. Fails when it would exceed 65,536 bytes. #[cfg_attr(not(test), allow(dead_code))] -pub fn project_secret_payload( +#[allow(clippy::too_many_arguments)] +pub fn project_secret_payload_with( env_pairs: &[(String, String)], agent_token: &str, files: &[(String, Vec)], @@ -222,6 +430,7 @@ pub fn project_secret_payload( wip: bool, idle: Option, storage: StorageMode, + extras: PayloadExtras<'_>, ) -> Result { serialize_payload(&payload_map( env_pairs, @@ -231,6 +440,7 @@ pub fn project_secret_payload( wip, idle, storage, + extras, )?) } @@ -254,10 +464,15 @@ pub struct WorkspacePlan { pub secret_arn: String, /// Sorted (the payload's key order). pub secret_keys: Vec, - /// Both set for Hybrid, both `None` for Ephemeral. + /// Both set for Hybrid and EFS, both `None` for Ephemeral. pub file_system_id: Option, pub access_point_id: Option, + /// 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 @@ -327,7 +542,14 @@ pub fn task_definition_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionIn fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { const BUILT: &str = "every required field is set"; let hybrid = match (&plan.storage, &plan.file_system_id, &plan.access_point_id) { - (StorageMode::Hybrid, Some(fs), Some(ap)) => Some((fs, ap)), + (StorageMode::Hybrid | StorageMode::Efs, Some(fs), Some(ap)) => Some((fs, ap)), + _ => None, + }; + // EFS = Hybrid + `/workspace` on its own access point. Hybrid and + // Ephemeral requests are exactly what they were before EFS mode (a + // test pins their fingerprints). + let workspace = match (&plan.storage, hybrid, &plan.workspace_access_point_id) { + (StorageMode::Efs, Some((fs, _)), Some(ap)) => Some((fs, ap)), _ => None, }; @@ -345,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") @@ -391,6 +607,15 @@ fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { .build(), ); } + if workspace.is_some() { + container = container.mount_points( + MountPoint::builder() + .source_volume(WORKSPACE_VOLUME) + .container_path(WORKSPACE_MOUNT_PATH) + .read_only(false) + .build(), + ); + } let mut req = RegisterTaskDefinitionInput::builder() .family(&plan.family) @@ -421,29 +646,90 @@ fn build_request(plan: &WorkspacePlan) -> RegisterTaskDefinitionInput { .map(|(k, v)| Tag::builder().key(k).value(v).build()) .collect(), )); - if let Some((fs, ap)) = hybrid { - req = req.volumes( - Volume::builder() - .name(HOME_VOLUME) - .efs_volume_configuration( - EfsVolumeConfiguration::builder() - .file_system_id(fs) - .transit_encryption(EfsTransitEncryption::Enabled) - .authorization_config( - EfsAuthorizationConfig::builder() - .access_point_id(ap) - .iam(EfsAuthorizationConfigIam::Enabled) - .build(), - ) - .build() - .expect(BUILT), - ) - .build(), - ); + 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))) + { + req = req.volumes(efs_volume(name, fs, ap)); } 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() + .name(name) + .efs_volume_configuration( + EfsVolumeConfiguration::builder() + .file_system_id(fs) + .transit_encryption(EfsTransitEncryption::Enabled) + .authorization_config( + EfsAuthorizationConfig::builder() + .access_point_id(ap) + .iam(EfsAuthorizationConfigIam::Enabled) + .build(), + ) + .build() + .expect("every required field is set"), + ) + .build() +} + // ---------------------------------------------------------------------- API #[derive(Debug, Clone, PartialEq)] @@ -497,6 +783,23 @@ pub trait WorkspaceApi: Send + Sync { root: &str, tags: &[(String, String)], ) -> impl Future> + Send; + /// Create the secret with `json` (encrypted with `kms_key_arn`, tagged). + /// `Some(arn)` when created, `None` when it already exists. + fn create_project_secret( + &self, + name: &str, + kms_key_arn: &str, + json: &str, + tags: &[(String, String)], + ) -> impl Future, AwsError>> + Send; + /// The secret's current `SecretString`; `None` when there is no secret. + fn project_secret_value( + &self, + name: &str, + ) -> impl Future, AwsError>> + Send; + /// Delete the secret now, every version with it + /// (`ForceDeleteWithoutRecovery`); no secret is not an error. + fn delete_project_secret(&self, name: &str) -> impl Future> + Send; /// Create the secret (encrypted with `kms_key_arn`, tagged), or put a new /// value into it when it exists. Returns its ARN. fn put_project_secret( @@ -592,14 +895,17 @@ pub struct PreparedWorkspace { /// Exact `family:revision`. pub task_definition_arn: String, pub access_point_id: Option, + /// EFS storage's `/workspace` access point. + pub workspace_access_point_id: Option, /// This start's token, already in the secret. pub agent_token: String, pub secret_arn: String, } -/// Make the project's secret, access point (Hybrid) and task definition +/// Make the project's secret, access points (Hybrid, EFS) and task definition /// ready. Everything that can be checked locally — placement, sizes, the /// payload's size and names — is checked before the first write. +#[allow(clippy::too_many_arguments)] pub async fn prepare_workspace( api: &W, who: &CallerIdentity, @@ -607,7 +913,9 @@ pub async fn prepare_workspace( project: &Project, env_pairs: &[(String, String)], 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 { @@ -635,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); @@ -647,14 +979,22 @@ pub async fn prepare_workspace( cfg.wip_push_on_stop, cfg.idle_stop_minutes, cfg.storage, + PayloadExtras { + setup_script: cfg.setup_script.as_deref(), + max_workspace_hours: env.max_workspace_hours, + connect_only: (cfg.secrets_delivery == SecretsDelivery::CopyAtConnect) + .then_some(custom_env_keys), + gateway, + }, ) .map_err(other)?; let json = serialize_payload(&payload).map_err(other)?; - // Hybrid: the user's own file system, from their onboarding. - let (file_system_id, access_point_id) = match cfg.storage { - StorageMode::Ephemeral => (None, None), - StorageMode::Hybrid => { + // Hybrid and EFS: the user's own file system, from their onboarding. + let (file_system_id, access_point_id, workspace_access_point_id) = match cfg.storage { + StorageMode::Ephemeral => (None, None, None), + StorageMode::Hybrid | StorageMode::Efs => { + let mode = if cfg.storage == StorageMode::Efs { "EFS" } else { "Hybrid" }; let token = user_file_system_token(&env.name, &ok); let fs = api .find_file_system(&token) @@ -662,26 +1002,81 @@ pub async fn prepare_workspace( .filter(|fs| fs.owner.as_deref() == Some(who.user_id.as_str())) .ok_or_else(|| { other(format!( - "Your file system in environment \"{}\" was not found. Hybrid storage \ + "Your file system in environment \"{}\" was not found. {mode} storage \ needs it: ask an administrator to onboard you there, or use \ Ephemeral storage.", env.name )) })?; - let root = access_point_root(&ok, &project.id); let points = api.access_points(&fs.id).await?; - let ap = match pick_access_point(&points, &fs.id, &root, &who.user_id, &project.id) { - Some(a) => a.id.clone(), - None => api.create_access_point(&fs.id, &root, &tags).await?, + let ensure = |root: String| { + let found = pick_access_point(&points, &fs.id, &root, &who.user_id, &project.id) + .map(|a| a.id.clone()); + let (fs_id, tags) = (&fs.id, &tags); + async move { + match found { + Some(id) => Ok(id), + None => api.create_access_point(fs_id, &root, tags).await, + } + } }; - (Some(fs.id), Some(ap)) + let ap = ensure(access_point_root(&ok, &project.id)).await?; + let workspace_ap = if cfg.storage == StorageMode::Efs { + Some(ensure(workspace_access_point_root(&ok, &project.id)).await?) + } else { + None + }; + (Some(fs.id), Some(ap), workspace_ap) } }; let secret_name = project_secret_name(&env.name, &ok, &project.id); - let secret_arn = api - .put_project_secret(&secret_name, &env.kms_key_arn, &json, &tags) - .await?; + let secret_arn = match extras_custom(cfg, custom_env_keys) { + // Copy-at-connect over a secret that still holds credentials (it was + // Secrets Manager before, or a custom variable has gone): a new value + // would leave them in the secret's version history (AWSPREVIOUS), so + // the secret is deleted outright and made again (ruling R7). + // + // Created first, as for Secrets Manager: a new project has no secret, + // and reading one that doesn't exist may be refused outright (the + // read is allowed only on secrets carrying the caller's owner tag). + // Only an existing secret is read. + Some(custom) => match retry_while_pending_deletion(&secret_name, RECREATE_TIMING, || { + api.create_project_secret(&secret_name, &env.kms_key_arn, &json, &tags) + }) + .await? + { + Some(arn) => arn, + None => { + // The secret existed at the create but may be marked for + // deletion by now (another start replacing it): wait that out + // like the writes do. Once it is gone the read says `None` + // and the put below makes it again. + let old = retry_while_pending_deletion(&secret_name, RECREATE_TIMING, || { + api.project_secret_value(&secret_name) + }) + .await?; + if old.as_deref().is_some_and(|o| holds_credentials(o, &payload, custom)) { + log::info!( + "Project {}: its secret still held credentials; replacing it so no version keeps them", + project.id + ); + replace_project_secret( + api, + &secret_name, + &env.kms_key_arn, + &json, + &tags, + RECREATE_TIMING, + ) + .await? + } else { + put_secret_retrying(api, &secret_name, &env.kms_key_arn, &json, &tags).await? + } + } + }, + None => put_secret_retrying(api, &secret_name, &env.kms_key_arn, &json, &tags).await?, + }; let (task_role, exec_role) = user_role_names(&env.name, &ok); let role_arn = |name: &str| format!("arn:{partition}:iam::{}:role/{name}", who.account); @@ -702,7 +1097,9 @@ pub async fn prepare_workspace( secret_keys: payload.keys().cloned().collect(), file_system_id, 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 = @@ -728,6 +1125,7 @@ pub async fn prepare_workspace( family: plan.family, task_definition_arn, access_point_id, + workspace_access_point_id, agent_token, secret_arn, }) @@ -742,17 +1140,132 @@ const MAX_LISTED_REVISIONS: i32 = 100; /// registered (what crowding a family out can cost the caller). const MAX_REVISION_PAGES: usize = 20; +/// Copy-at-connect's custom variable names, or `None` for Secrets Manager. +fn extras_custom<'a>( + cfg: &crate::models::project::AwsWorkspaceConfig, + custom_env_keys: &'a [String], +) -> Option<&'a [String]> { + (cfg.secrets_delivery == SecretsDelivery::CopyAtConnect).then_some(custom_env_keys) +} + +/// Whether a secret's current value `old` holds anything copy-at-connect +/// keeps out: the files, the custom variables' fingerprint, a credential +/// key, or an environment variable the new payload no longer has (a custom +/// variable since removed). `TRIPLEC_*` keys are the payload's own. A value +/// that is not a JSON object counts as holding them. +pub fn holds_credentials(old: &str, new: &BTreeMap, custom: &[String]) -> bool { + 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) && !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)) + }) +} + +/// How long a replaced secret's name may stay taken by its deletion. +#[derive(Debug, Clone, Copy)] +pub struct RecreateTiming { + pub interval: std::time::Duration, + pub limit: std::time::Duration, +} + +const RECREATE_TIMING: RecreateTiming = RecreateTiming { + interval: std::time::Duration::from_secs(2), + limit: std::time::Duration::from_secs(30), +}; + +fn is_pending_deletion_error(e: &AwsError) -> bool { + matches!(e, AwsError::Other { message } if message.contains(PENDING_DELETION)) +} + +/// Run a secret write, retrying while the name is still taken by a deletion +/// AWS has not finished — a replace that timed out deleted the secret without +/// making it again, so the next start lands here. Past `timing.limit`, says +/// to try again in a minute. +async fn retry_while_pending_deletion( + name: &str, + timing: RecreateTiming, + mut write: F, +) -> Result +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let deadline = tokio::time::Instant::now() + timing.limit; + loop { + match write().await { + Err(e) if is_pending_deletion_error(&e) => { + if tokio::time::Instant::now() + timing.interval > deadline { + return Err(other(format!( + "AWS has not finished deleting this project's previous secret ({name}) \ + after {} s, so it can't be written yet. Start the project again in a \ + minute.", + timing.limit.as_secs() + ))); + } + tokio::time::sleep(timing.interval).await; + } + r => return r, + } + } +} + +async fn put_secret_retrying( + api: &W, + name: &str, + kms_key_arn: &str, + json: &str, + tags: &[(String, String)], +) -> Result { + retry_while_pending_deletion(name, RECREATE_TIMING, || { + api.put_project_secret(name, kms_key_arn, json, tags) + }) + .await +} + +/// Delete the secret with every version, then create it with `json`, +/// retrying while AWS finishes the (asynchronous) delete. +pub async fn replace_project_secret( + api: &W, + name: &str, + kms_key_arn: &str, + json: &str, + tags: &[(String, String)], + timing: RecreateTiming, +) -> Result { + api.delete_project_secret(name).await?; + retry_while_pending_deletion(name, timing, || api.put_project_secret(name, kms_key_arn, json, tags)) + .await +} + /// Secrets Manager's `InvalidRequestException` for a name whose secret is /// scheduled for deletion ("... already scheduled for deletion"). fn is_pending_deletion(message: Option<&str>) -> bool { - message.is_some_and(|m| m.contains("scheduled for deletion")) + // CreateSecret/PutSecretValue say "scheduled", GetSecretValue "marked". + message.is_some_and(|m| m.contains("scheduled for deletion") || m.contains("marked for deletion")) } +/// What [`pending_deletion_error`] says; [`is_pending_deletion_error`] looks for it. +const PENDING_DELETION: &str = "is still being deleted"; + +/// The name is taken by a deletion. Every deletion Triple-C makes is forced +/// (no recovery window) and finishes within a minute or so, so the advice is +/// to wait — never to restore the secret. fn pending_deletion_error(name: &str) -> AwsError { other(format!( - "This project's secret ({name}) is scheduled for deletion, so it can't be written. \ - Restore it in the Secrets Manager console (or wait until it is deleted) and start \ - the project again." + "This project's secret ({name}) {PENDING_DELETION}, so it can't be written yet. Start \ + the project again in a minute." )) } @@ -888,16 +1401,57 @@ impl WorkspaceApi for SdkWorkspaceApi { .ok_or_else(|| other(format!("{ACTION} returned no AccessPointId"))) } - async fn put_project_secret( + async fn project_secret_value(&self, name: &str) -> Result, AwsError> { + const ACTION: &str = "secretsmanager:GetSecretValue"; + match self.secrets.get_secret_value().secret_id(name).send().await { + Ok(out) => Ok(out.secret_string().map(str::to_string)), + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_resource_not_found_exception()) => + { + Ok(None) + } + Err(e) + if e.as_service_error().is_some_and(|s| { + s.is_invalid_request_exception() && is_pending_deletion(s.message()) + }) => + { + Err(pending_deletion_error(name)) + } + Err(e) => Err(classify_sdk_error(ACTION, &e)), + } + } + + async fn delete_project_secret(&self, name: &str) -> Result<(), AwsError> { + const ACTION: &str = "secretsmanager:DeleteSecret"; + match self + .secrets + .delete_secret() + .secret_id(name) + .force_delete_without_recovery(true) + .send() + .await + { + Ok(_) => Ok(()), + Err(e) + if e.as_service_error() + .is_some_and(|s| s.is_resource_not_found_exception()) => + { + Ok(()) + } + Err(e) => Err(classify_sdk_error(ACTION, &e)), + } + } + + async fn create_project_secret( &self, name: &str, kms_key_arn: &str, json: &str, tags: &[(String, String)], - ) -> Result { + ) -> Result, AwsError> { use aws_sdk_secretsmanager::types::Tag as SmTag; const CREATE: &str = "secretsmanager:CreateSecret"; - const PUT: &str = "secretsmanager:PutSecretValue"; let created = self .secrets .create_secret() @@ -911,43 +1465,57 @@ impl WorkspaceApi for SdkWorkspaceApi { )) .send() .await; - let arn = match created { - Ok(out) => out.arn().map(str::to_string), + match created { + Ok(out) => out + .arn() + .map(|a| Some(a.to_string())) + .ok_or_else(|| other(format!("{CREATE} returned no ARN"))), Err(e) if e.as_service_error() .is_some_and(|s| s.is_resource_exists_exception()) => { - // Only a secret tagged with the caller as owner accepts this - // (the policy), so another user's same-named secret fails - // here rather than receiving the payload. - self.secrets - .put_secret_value() - .secret_id(name) - .secret_string(json) - .send() - .await - .map_err(|e| match e.as_service_error() { - Some(s) - if s.is_invalid_request_exception() - && is_pending_deletion(s.message()) => - { - pending_deletion_error(name) - } - _ => classify_sdk_error(PUT, &e), - })? - .arn() - .map(str::to_string) + Ok(None) } Err(e) if e.as_service_error().is_some_and(|s| { s.is_invalid_request_exception() && is_pending_deletion(s.message()) }) => { - return Err(pending_deletion_error(name)); + Err(pending_deletion_error(name)) } - Err(e) => return Err(classify_sdk_error(CREATE, &e)), - }; - arn.ok_or_else(|| other(format!("{CREATE} returned no ARN"))) + Err(e) => Err(classify_sdk_error(CREATE, &e)), + } + } + + async fn put_project_secret( + &self, + name: &str, + kms_key_arn: &str, + json: &str, + tags: &[(String, String)], + ) -> Result { + const PUT: &str = "secretsmanager:PutSecretValue"; + if let Some(arn) = self.create_project_secret(name, kms_key_arn, json, tags).await? { + return Ok(arn); + } + // Only a secret tagged with the caller as owner accepts this (the + // policy), so another user's same-named secret fails here rather + // than receiving the payload. + self.secrets + .put_secret_value() + .secret_id(name) + .secret_string(json) + .send() + .await + .map_err(|e| match e.as_service_error() { + Some(s) if s.is_invalid_request_exception() && is_pending_deletion(s.message()) => { + pending_deletion_error(name) + } + _ => classify_sdk_error(PUT, &e), + })? + .arn() + .map(str::to_string) + .ok_or_else(|| other(format!("{PUT} returned no ARN"))) } async fn task_definition_revisions(&self, family: &str) -> Result, AwsError> { diff --git a/app/src-tauri/src/aws/workspace/tests.rs b/app/src-tauri/src/aws/workspace/tests.rs index 4b0bfc0..46cd135 100644 --- a/app/src-tauri/src/aws/workspace/tests.rs +++ b/app/src-tauri/src/aws/workspace/tests.rs @@ -9,7 +9,7 @@ use crate::aws::environments::EnvironmentInfo; use crate::aws::identity::CallerIdentity; use crate::aws::tofu_modules::{ access_point_root, log_stream_prefix, owner_key, project_secret_name, task_family, - user_file_system_token, + user_file_system_token, workspace_access_point_root, }; use crate::models::project::{Arch, AwsPlacement, AwsWorkspaceConfig, RepoSource, StorageMode}; use crate::models::Project; @@ -45,6 +45,7 @@ fn env_info() -> EnvironmentInfo { log_group: "/triple-c/dev".into(), network_mode: "public".into(), tenancy: "strict".into(), + max_workspace_hours: 0, } } @@ -95,9 +96,12 @@ fn sample_plan(storage: StorageMode) -> WorkspacePlan { "GIT_TOKEN".into(), "TRIPLEC_AGENT_TOKEN".into(), ], - file_system_id: (storage == StorageMode::Hybrid).then(|| "fs-0123abcd".to_string()), - access_point_id: (storage == StorageMode::Hybrid).then(|| "fsap-0123abcd".to_string()), + file_system_id: (storage != StorageMode::Ephemeral).then(|| "fs-0123abcd".to_string()), + access_point_id: (storage != StorageMode::Ephemeral).then(|| "fsap-0123abcd".to_string()), + workspace_access_point_id: (storage == StorageMode::Efs) + .then(|| "fsap-4567efab".to_string()), tags: workspace_tags(USER, PROJECT_ID, "dev"), + gateway_image: None, } } @@ -112,6 +116,7 @@ fn names_use_owner_key_and_never_contain_a_colon() { access_point_root(&ok, PROJECT_ID), log_stream_prefix(&ok, PROJECT_ID), user_file_system_token("dev", &ok), + workspace_access_point_root(&ok, PROJECT_ID), ]; for n in &names { assert!(n.contains(&ok), "{n} lacks the owner key"); @@ -124,6 +129,9 @@ fn names_use_owner_key_and_never_contain_a_colon() { assert_eq!(names[3], format!("{ok}/{PROJECT_ID}")); // The onboarding module's `creation_token` (local.name). assert_eq!(names[4], format!("triple-c-dev-{ok}")); + // A sibling of the home roots, never inside one (Q1). + assert_eq!(names[5], format!("/triple-c-workspaces/{ok}/{PROJECT_ID}")); + assert!(!names[5].starts_with(&format!("{}/", names[2]))); } #[test] @@ -143,6 +151,12 @@ fn names_sanitise_a_hostile_project_id() { !tail.is_empty() && !tail.contains('/') && tail != "." && tail != "..", "{root}" ); + let wroot = workspace_access_point_root(&ok, id); + assert_eq!( + wroot.strip_prefix(&format!("/triple-c-workspaces/{ok}/")), + Some(tail), + "{wroot}" + ); let secret = project_secret_name("dev", &ok, id); assert!(!secret.contains(':') && !secret.contains(".."), "{secret}"); assert_eq!(secret.matches('/').count(), 3, "{secret}"); @@ -150,6 +164,7 @@ fn names_sanitise_a_hostile_project_id() { let long = "x".repeat(500); assert!(task_family("abcdefghijklmnopqrst", &ok, &long).len() <= 255); assert!(access_point_root(&ok, &long).len() <= 100); + assert!(workspace_access_point_root(&ok, &long).len() <= 100); } // ------------------------------------------------------- task definition @@ -310,6 +325,84 @@ fn hybrid_mounts_the_access_point_with_iam_and_tls() { assert_eq!(mounts[0].read_only(), Some(false)); } +/// Captured before EFS mode existed: Hybrid and Ephemeral requests must not +/// change (a changed fingerprint registers a new revision for every project). +#[test] +fn hybrid_and_ephemeral_requests_are_unchanged_by_efs_mode() { + assert_eq!( + workspace_fingerprint(&sample_plan(StorageMode::Hybrid)), + "d6d00b3f3489060c40ff732be8eb8a10e723e26dd5f1ff58345e4c2a307f862d" + ); + assert_eq!( + workspace_fingerprint(&sample_plan(StorageMode::Ephemeral)), + "00f248ed315167fe7a1adc0ea5c8bcee328e8a0739a1c4f9ce9ac10270851786" + ); + // A stray workspace access point (kept after switching EFS → Hybrid) + // does not reach a Hybrid or Ephemeral request. + for storage in [StorageMode::Hybrid, StorageMode::Ephemeral] { + let mut p = sample_plan(storage); + p.workspace_access_point_id = Some("fsap-stray".into()); + assert_eq!( + workspace_fingerprint(&p), + workspace_fingerprint(&sample_plan(storage)) + ); + } +} + +#[test] +fn efs_mounts_home_and_workspace_access_points() { + let req = task_definition_request(&sample_plan(StorageMode::Efs)); + let vols = req.volumes(); + assert_eq!(vols.len(), 2); + let by_name = |n: &str| vols.iter().find(|v| v.name() == Some(n)).unwrap(); + for (name, ap) in [("home", "fsap-0123abcd"), ("workspace", "fsap-4567efab")] { + let efs = by_name(name).efs_volume_configuration().unwrap(); + assert_eq!(efs.file_system_id(), "fs-0123abcd"); + assert_eq!(efs.transit_encryption(), Some(&EfsTransitEncryption::Enabled)); + let auth = efs.authorization_config().unwrap(); + assert_eq!(auth.access_point_id(), Some(ap)); + assert_eq!(auth.iam(), Some(&EfsAuthorizationConfigIam::Enabled)); + assert!(efs.root_directory().is_none() || efs.root_directory() == Some("/")); + } + let mounts: Vec<(&str, &str, Option)> = req.container_definitions()[0] + .mount_points() + .iter() + .map(|m| { + ( + m.source_volume().unwrap(), + m.container_path().unwrap(), + m.read_only(), + ) + }) + .collect(); + assert_eq!( + mounts, + vec![ + ("home", "/mnt/triple-c-home", Some(false)), + ("workspace", "/workspace", Some(false)), + ] + ); + // Its own fingerprint, and the workspace access point is covered. + let fp = workspace_fingerprint(&sample_plan(StorageMode::Efs)); + assert_ne!(fp, workspace_fingerprint(&sample_plan(StorageMode::Hybrid))); + let mut other = sample_plan(StorageMode::Efs); + other.workspace_access_point_id = Some("fsap-other".into()); + assert_ne!(workspace_fingerprint(&other), fp); +} + +#[test] +fn efs_without_its_workspace_access_point_mounts_nothing_at_workspace() { + // Not a plan `prepare_workspace` makes; the builder must not invent one. + let mut p = sample_plan(StorageMode::Efs); + p.workspace_access_point_id = None; + let req = task_definition_request(&p); + assert!(req + .container_definitions()[0] + .mount_points() + .iter() + .all(|m| m.container_path() != Some("/workspace"))); +} + #[test] fn arm64_sets_the_runtime_platform() { let mut plan = sample_plan(StorageMode::Ephemeral); @@ -377,7 +470,7 @@ fn payload_holds_all_project_data_with_sorted_keys() { ("ca/corp.pem".to_string(), b"PEM".to_vec()), ]; let repos = project(StorageMode::Hybrid).aws.unwrap().repos; - let json = project_secret_payload( + let json = project_secret_payload_with( &env, "tok", &files, @@ -385,6 +478,7 @@ fn payload_holds_all_project_data_with_sorted_keys() { true, Some(30), StorageMode::Hybrid, + PayloadExtras::default(), ) .unwrap(); let m = payload_map(&json); @@ -433,7 +527,16 @@ fn payload_holds_all_project_data_with_sorted_keys() { #[test] fn payload_off_values() { let json = - project_secret_payload(&[], "t", &[], &[], false, None, StorageMode::Ephemeral).unwrap(); + project_secret_payload_with( + &[], + "t", + &[], + &[], + false, + None, + StorageMode::Ephemeral, + PayloadExtras::default(), + ).unwrap(); let m = payload_map(&json); assert_eq!(m["TRIPLEC_WIP_PUSH"], "0"); assert_eq!(m["TRIPLEC_STORAGE"], "ephemeral"); @@ -446,8 +549,26 @@ fn payload_off_values() { fn payload_is_independent_of_env_pair_order() { let a = pairs(&[("B", "2"), ("A", "1"), ("C", "3")]); let b = pairs(&[("C", "3"), ("A", "1"), ("B", "2")]); - let pa = project_secret_payload(&a, "t", &[], &[], true, None, StorageMode::Hybrid).unwrap(); - let pb = project_secret_payload(&b, "t", &[], &[], true, None, StorageMode::Hybrid).unwrap(); + let pa = project_secret_payload_with( + &a, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap(); + let pb = project_secret_payload_with( + &b, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap(); assert_eq!(pa, pb); } @@ -457,7 +578,16 @@ fn payload_rejects_bad_file_names() { "ssh/", "ssh/.", "ssh/..", "ssh/a/b", "other/x", "x", "ca/../k", "ssh/a:b", ] { let files = vec![(name.to_string(), b"x".to_vec())]; - let r = project_secret_payload(&[], "t", &files, &[], true, None, StorageMode::Hybrid); + let r = project_secret_payload_with( + &[], + "t", + &files, + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ); if name == "ssh/a:b" { // A colon is a fine file name; only the secret's *keys* are restricted. assert!(r.is_ok()); @@ -471,7 +601,16 @@ fn payload_rejects_bad_file_names() { fn payload_rejects_env_names_a_secret_reference_cannot_carry() { for bad in ["A:B", "", "1ABC", "A-B", "A B"] { let env = pairs(&[(bad, "SENTINEL-VALUE-7f3a")]); - let r = project_secret_payload(&env, "t", &[], &[], true, None, StorageMode::Hybrid); + let r = project_secret_payload_with( + &env, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ); assert!(r.is_err(), "{bad:?} accepted"); // The error never echoes a value. assert!(!r.unwrap_err().contains("SENTINEL-VALUE-7f3a")); @@ -489,7 +628,16 @@ fn payload_keeps_its_own_keys_over_custom_env() { ("OK", "1"), ]); let m = payload_map( - &project_secret_payload(&env, "real", &[], &[], true, None, StorageMode::Hybrid).unwrap(), + &project_secret_payload_with( + &env, + "real", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap(), ); assert_eq!(m["TRIPLEC_AGENT_TOKEN"], "real"); // The task definition's fixed environment owns these two names. @@ -505,10 +653,120 @@ fn payload_keeps_its_own_keys_over_custom_env() { fn payload_over_64_kib_fails() { let env = pairs(&[("BIG", &"x".repeat(65_536))]); let err = - project_secret_payload(&env, "t", &[], &[], true, None, StorageMode::Hybrid).unwrap_err(); + project_secret_payload_with( + &env, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap_err(); assert!(err.contains("65,536"), "{err}"); } +#[test] +fn payload_carries_setup_script_and_lifetime_when_set() { + let json = project_secret_payload_with( + &[], + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras { setup_script: Some("apt-get install -y jq\n"), max_workspace_hours: 8, ..Default::default() }, + ) + .unwrap(); + let m = payload_map(&json); + assert_eq!(m["TRIPLEC_SETUP_SCRIPT"], "apt-get install -y jq\n"); + assert_eq!(m["TRIPLEC_MAX_LIFETIME_MINUTES"], "480"); +} + +#[test] +fn payload_omits_setup_script_and_lifetime_when_unset() { + for script in [None, Some(""), Some(" \n\t")] { + let json = project_secret_payload_with( + &[], + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras { setup_script: script, ..Default::default() }, + ) + .unwrap(); + let m = payload_map(&json); + assert!(!m.contains_key("TRIPLEC_SETUP_SCRIPT"), "{script:?}"); + assert!(!m.contains_key("TRIPLEC_MAX_LIFETIME_MINUTES")); + } +} + +#[test] +fn payload_setup_script_and_lifetime_cannot_be_forged_by_custom_env() { + let env = pairs(&[("TRIPLEC_SETUP_SCRIPT", "rm -rf /"), ("TRIPLEC_MAX_LIFETIME_MINUTES", "1")]); + let m = payload_map( + &project_secret_payload_with( + &env, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap(), + ); + assert!(!m.contains_key("TRIPLEC_SETUP_SCRIPT")); + assert!(!m.contains_key("TRIPLEC_MAX_LIFETIME_MINUTES")); +} + +#[test] +fn payload_size_error_names_the_setup_script_when_it_is_the_large_part() { + let env = pairs(&[("CLAUDE_INSTRUCTIONS", &"i".repeat(20 * 1024)), ("SMALL", "x")]); + let script = "s".repeat(31 * 1024); + let files = vec![("ssh/id_rsa".to_string(), vec![b'k'; 12 * 1024])]; + let err = project_secret_payload_with( + &env, + "t", + &files, + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras { setup_script: Some(&script), ..Default::default() }, + ) + .unwrap_err(); + assert!(err.contains("65,536"), "{err}"); + // Largest first: the script, then the instructions, then the files. + let at = |needle: &str| err.find(needle).unwrap_or_else(|| panic!("{needle} missing: {err}")); + assert!(at("the setup script (32 KiB)") < at("the instructions (21 KiB)"), "{err}"); + assert!(at("the instructions") < at("the SSH and CA files (17 KiB)"), "{err}"); + assert!(!err.contains("SMALL"), "{err}"); + // Values never appear. + assert!(!err.contains("sss"), "{err}"); +} + +#[test] +fn payload_size_error_names_a_large_custom_variable_by_name_only() { + let env = pairs(&[("BIG_BLOB", &"SENTINEL".repeat(9000))]); + let err = + project_secret_payload_with( + &env, + "t", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras::default(), + ).unwrap_err(); + assert!(err.contains("the environment variable BIG_BLOB (71 KiB)"), "{err}"); + assert!(!err.contains("SENTINEL"), "{err}"); +} + #[test] fn agent_tokens_are_64_url_safe_characters_and_fresh() { let a = new_agent_token(); @@ -534,6 +792,18 @@ struct Fake { revisions: Mutex>, registered: Mutex>, describes: Mutex, + /// The secret's value before this start (`project_secret_value`). + existing_secret: Mutex>, + /// Names force-deleted. + deleted_secrets: Mutex>, + /// Calls `project_secret_value` got. + secret_reads: Mutex, + /// Puts that fail as "scheduled for deletion" before one succeeds. + pending_puts: Mutex, + /// Reads that fail as "marked for deletion" before one succeeds. + pending_reads: Mutex, + /// Calls `create_project_secret` got. + creates: Mutex, } impl Fake { @@ -579,6 +849,35 @@ impl WorkspaceApi for Fake { c.push((fs_id.into(), root.into(), tags.to_vec())); Ok(format!("fsap-new{}", c.len())) } + async fn project_secret_value(&self, name: &str) -> Result, AwsError> { + *self.secret_reads.lock().unwrap() += 1; + { + let mut pending = self.pending_reads.lock().unwrap(); + if *pending > 0 { + *pending -= 1; + return Err(pending_deletion_error(name)); + } + } + Ok(self.existing_secret.lock().unwrap().clone()) + } + async fn delete_project_secret(&self, name: &str) -> Result<(), AwsError> { + self.deleted_secrets.lock().unwrap().push(name.into()); + *self.existing_secret.lock().unwrap() = None; + Ok(()) + } + async fn create_project_secret( + &self, + name: &str, + kms_key_arn: &str, + json: &str, + tags: &[(String, String)], + ) -> Result, AwsError> { + *self.creates.lock().unwrap() += 1; + if self.existing_secret.lock().unwrap().is_some() { + return Ok(None); + } + self.put_project_secret(name, kms_key_arn, json, tags).await.map(Some) + } async fn put_project_secret( &self, name: &str, @@ -586,6 +885,13 @@ impl WorkspaceApi for Fake { json: &str, tags: &[(String, String)], ) -> Result { + { + let mut pending = self.pending_puts.lock().unwrap(); + if *pending > 0 { + *pending -= 1; + return Err(pending_deletion_error(name)); + } + } self.secrets.lock().unwrap().push(( name.into(), kms_key_arn.into(), @@ -656,7 +962,27 @@ 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] +async fn prepare_puts_the_setup_script_and_the_environments_cap_in_the_secret() { + let fake = Fake::onboarded(); + let mut p = project(StorageMode::Ephemeral); + 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, 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"); + + // No script, no cap: neither key. + let fake = Fake::onboarded(); + prepare(&fake, &project(StorageMode::Ephemeral), &[]).await.unwrap(); + let m = payload_map(&fake.secrets.lock().unwrap()[0].2); + assert!(!m.contains_key("TRIPLEC_SETUP_SCRIPT")); + assert!(!m.contains_key("TRIPLEC_MAX_LIFETIME_MINUTES")); } #[tokio::test] @@ -911,6 +1237,93 @@ async fn an_existing_access_point_is_reused() { assert_eq!(fake2.created_access_points.lock().unwrap().len(), 1); } +#[tokio::test] +async fn efs_creates_both_access_points_then_reuses_them_by_root_owner_and_project() { + let fake = Fake::onboarded(); + let ok = owner_key(REGION, USER); + let tags = workspace_tags(USER, PROJECT_ID, "dev"); + let p = project(StorageMode::Efs); + let first = prepare(&fake, &p, &[]).await.unwrap(); + let created = fake.created_access_points.lock().unwrap().clone(); + assert_eq!( + created, + vec![ + ("fs-0123abcd".to_string(), access_point_root(&ok, PROJECT_ID), tags.clone()), + ( + "fs-0123abcd".to_string(), + workspace_access_point_root(&ok, PROJECT_ID), + tags.clone() + ), + ] + ); + assert_eq!(first.access_point_id.as_deref(), Some("fsap-new1")); + assert_eq!(first.workspace_access_point_id.as_deref(), Some("fsap-new2")); + { + let reg = fake.registered.lock().unwrap(); + let aps: Vec> = reg[0] + .volumes() + .iter() + .map(|v| { + v.efs_volume_configuration() + .unwrap() + .authorization_config() + .unwrap() + .access_point_id() + }) + .collect(); + assert_eq!(aps, vec![Some("fsap-new1"), Some("fsap-new2")]); + let secrets = fake.secrets.lock().unwrap(); + assert_eq!(payload_map(&secrets[0].2)["TRIPLEC_STORAGE"], "efs"); + } + + // The second start finds both (and is not fooled by decoys: another + // owner's, another project's, the home root, one being deleted). + let good = AccessPointRef { + id: "fsap-ws".into(), + file_system_id: "fs-0123abcd".into(), + root_path: Some(workspace_access_point_root(&ok, PROJECT_ID)), + owner: Some(USER.into()), + project: Some(PROJECT_ID.into()), + state: Some("available".into()), + }; + fake.access_points.lock().unwrap().extend([ + AccessPointRef { id: "fsap-foreign".into(), owner: Some(OTHER.into()), ..good.clone() }, + AccessPointRef { + id: "fsap-other-project".into(), + project: Some("another".into()), + ..good.clone() + }, + AccessPointRef { id: "fsap-deleting".into(), state: Some("deleting".into()), ..good.clone() }, + AccessPointRef { + id: "fsap-home".into(), + root_path: Some(access_point_root(&ok, PROJECT_ID)), + ..good.clone() + }, + good, + ]); + let second = prepare(&fake, &p, &[]).await.unwrap(); + assert_eq!(fake.created_access_points.lock().unwrap().len(), 2); + assert_eq!(second.access_point_id.as_deref(), Some("fsap-home")); + assert_eq!(second.workspace_access_point_id.as_deref(), Some("fsap-ws")); +} + +#[tokio::test] +async fn hybrid_never_creates_or_returns_a_workspace_access_point() { + let fake = Fake::onboarded(); + let out = prepare(&fake, &project(StorageMode::Hybrid), &[]).await.unwrap(); + assert!(out.workspace_access_point_id.is_none()); + assert_eq!(fake.created_access_points.lock().unwrap().len(), 1); + assert_eq!(fake.registered.lock().unwrap()[0].volumes().len(), 1); +} + +#[tokio::test] +async fn efs_without_the_users_file_system_fails_before_any_write() { + let fake = Fake::default(); + let err = prepare(&fake, &project(StorageMode::Efs), &[]).await.unwrap_err(); + assert!(err.to_string().contains("EFS storage"), "{err}"); + assert_eq!(fake.writes(), 0); +} + #[tokio::test] async fn ephemeral_touches_no_file_system() { let fake = Fake::default(); // no file system at all @@ -981,7 +1394,9 @@ async fn files_travel_in_the_secret_only() { &project(StorageMode::Hybrid), &[], &files, + &[], IMAGE, + None, ) .await .unwrap(); @@ -1120,6 +1535,552 @@ fn a_secret_pending_deletion_is_recognised() { assert!(!is_pending_deletion(Some("Some other invalid request"))); assert!(!is_pending_deletion(None)); let msg = pending_deletion_error("triple-c/dev/abc/p").to_string(); - assert!(msg.contains("scheduled for deletion"), "{msg}"); + assert!(msg.contains("still being deleted") && msg.contains("again in a minute"), "{msg}"); + assert!(!msg.contains("Restore"), "{msg}"); + assert!(is_pending_deletion_error(&pending_deletion_error("n"))); assert!(msg.contains("triple-c/dev/abc/p"), "{msg}"); } + + +// ------------------------------------------------- copy-at-connect (Q2) + +#[test] +fn a_copy_at_connect_payload_keeps_settings_and_the_token_but_no_credentials() { + let env = pairs(&[ + ("ANTHROPIC_API_KEY", "sk-ant"), + ("GIT_TOKEN", "ghp_secret"), + ("AWS_SECRET_ACCESS_KEY", "aws-secret"), + ("MY_CUSTOM", "custom-value"), + ("ANTHROPIC_MODEL", "opus"), + ("CLAUDE_INSTRUCTIONS", "be nice"), + ("GIT_USER_NAME", "Dev"), + ]); + let files = vec![ + ("ssh/id_ed25519".to_string(), b"PRIVATE KEY".to_vec()), + ("ca/corp.pem".to_string(), b"PEM".to_vec()), + ]; + let repos = project(StorageMode::Hybrid).aws.unwrap().repos; + let custom = vec!["MY_CUSTOM".to_string()]; + let json = project_secret_payload_with( + &env, + "tok", + &files, + &repos, + true, + Some(30), + StorageMode::Hybrid, + PayloadExtras { + setup_script: Some("make"), + connect_only: Some(&custom), + ..Default::default() + }, + ) + .unwrap(); + for value in ["sk-ant", "ghp_secret", "aws-secret", "custom-value", "PRIVATE KEY", "UFJJVkFURSBLRVk="] { + assert!(!json.contains(value), "{value} must not be stored: {json}"); + } + let m = payload_map(&json); + assert!(!m.contains_key("TRIPLEC_FILES")); + for key in crate::docker::container::SECRET_ENV_KEYS.iter().chain(["MY_CUSTOM"].iter()) { + assert!(!m.contains_key(*key), "{key}"); + } + assert_eq!(m["TRIPLEC_CREDENTIALS"], "connect"); + // Settings and the agent token stay. + assert_eq!(m["TRIPLEC_AGENT_TOKEN"], "tok"); + assert_eq!(m["ANTHROPIC_MODEL"], "opus"); + assert_eq!(m["CLAUDE_INSTRUCTIONS"], "be nice"); + assert_eq!(m["GIT_USER_NAME"], "Dev"); + assert_eq!(m["TRIPLEC_SETUP_SCRIPT"], "make"); + assert_eq!(m["TRIPLEC_IDLE_STOP_MINUTES"], "30"); + assert!(m["TRIPLEC_REPOS"].contains("\"folder\"")); + + // Secrets Manager delivery: all of it, and no TRIPLEC_CREDENTIALS. + let m = payload_map( + &project_secret_payload_with( + &env, + "tok", + &files, + &repos, + true, + Some(30), + StorageMode::Hybrid, + PayloadExtras::default(), + ) + .unwrap(), + ); + assert_eq!(m["GIT_TOKEN"], "ghp_secret"); + assert_eq!(m["MY_CUSTOM"], "custom-value"); + assert!(m["TRIPLEC_FILES"].contains("ssh/id_ed25519")); + assert!(!m.contains_key("TRIPLEC_CREDENTIALS")); +} + +#[test] +fn credential_pairs_are_the_managed_keys_and_every_custom_variable() { + let env = pairs(&[ + ("ANTHROPIC_API_KEY", "sk"), + ("TZ", "UTC"), + ("MY_CUSTOM", "v"), + ("GIT_TOKEN", ""), + ("CLAUDE_CODE_OAUTH_TOKEN", "o"), + ]); + let got = credential_pairs(&env, &["MY_CUSTOM".to_string()]); + assert_eq!( + got, + pairs(&[("ANTHROPIC_API_KEY", "sk"), ("MY_CUSTOM", "v"), ("GIT_TOKEN", ""), ("CLAUDE_CODE_OAUTH_TOKEN", "o")]) + ); + assert!(!is_credential_key("TZ", &[])); +} + +#[tokio::test] +async fn prepare_leaves_the_credentials_out_of_a_copy_at_connect_secret() { + let fake = Fake::onboarded(); + let mut p = project(StorageMode::Hybrid); + 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, None) + .await + .unwrap(); + let m = payload_map(&fake.secrets.lock().unwrap()[0].2); + assert!(!m.contains_key("GIT_TOKEN") && !m.contains_key("MINE") && !m.contains_key("TRIPLEC_FILES")); + assert_eq!(m["TZ"], "UTC"); + assert_eq!(m["TRIPLEC_CREDENTIALS"], "connect"); + assert!(m.contains_key("TRIPLEC_AGENT_TOKEN")); +} + +fn copy_at_connect_project() -> Project { + let mut p = project(StorageMode::Hybrid); + p.aws.as_mut().unwrap().secrets_delivery = crate::models::project::SecretsDelivery::CopyAtConnect; + p +} + +#[tokio::test] +async fn switching_to_copy_at_connect_replaces_a_secret_that_held_credentials() { + // The secret from a Secrets Manager period: replaced, not overwritten. + let fake = Fake::onboarded(); + *fake.existing_secret.lock().unwrap() = + 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, None) + .await + .unwrap(); + assert_eq!(*fake.secret_reads.lock().unwrap(), 1, "read only once it exists"); + assert_eq!(fake.deleted_secrets.lock().unwrap().len(), 1); + let m = payload_map(&fake.secrets.lock().unwrap()[0].2); + assert!(!m.contains_key("GIT_TOKEN")); + + // Already clean: a plain put, nothing deleted. + let fake = Fake::onboarded(); + *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, None) + .await + .unwrap(); + assert!(fake.deleted_secrets.lock().unwrap().is_empty()); + assert_eq!(fake.secrets.lock().unwrap().len(), 1); + + // 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, None) + .await + .unwrap(); + assert_eq!(*fake.creates.lock().unwrap(), 1); + assert_eq!(*fake.secret_reads.lock().unwrap(), 0); + assert!(fake.deleted_secrets.lock().unwrap().is_empty()); + assert!(!payload_map(&fake.secrets.lock().unwrap()[0].2).contains_key("GIT_TOKEN")); + + // Secrets Manager never reads or deletes. + let fake = Fake::onboarded(); + *fake.existing_secret.lock().unwrap() = Some(r#"{"GIT_TOKEN":"x"}"#.into()); + prepare(&fake, &project(StorageMode::Hybrid), &env).await.unwrap(); + assert_eq!(*fake.secret_reads.lock().unwrap(), 0); + assert!(fake.deleted_secrets.lock().unwrap().is_empty()); +} + +#[test] +fn what_counts_as_credentials_left_in_a_secret() { + let new: BTreeMap = + [("TZ", "UTC"), ("TRIPLEC_AGENT_TOKEN", "t")].iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(); + let custom = vec!["MINE".to_string()]; + let holds = |old: &str| holds_credentials(old, &new, &custom); + assert!(holds(r#"{"TRIPLEC_FILES":"{}"}"#)); + assert!(holds(r#"{"TRIPLE_C_CUSTOM_ENV":"abc"}"#)); + assert!(holds(r#"{"ANTHROPIC_API_KEY":""}"#)); + assert!(holds(r#"{"MINE":"v"}"#)); + assert!(holds(r#"{"GONE_CUSTOM":"v","TZ":"UTC"}"#), "a variable the payload no longer has"); + assert!(holds("not json")); + assert!(!holds(r#"{"TZ":"UTC","TRIPLEC_AGENT_TOKEN":"old","TRIPLEC_SETUP_SCRIPT":"x"}"#)); +} + +#[tokio::test] +async fn a_replaced_secret_that_aws_has_not_finished_deleting_is_a_clear_error() { + let fake = Fake::onboarded(); + *fake.pending_puts.lock().unwrap() = 100; + let timing = RecreateTiming { + interval: std::time::Duration::from_millis(1), + limit: std::time::Duration::from_millis(20), + }; + let e = replace_project_secret(&fake, "n", "k", "{}", &[], timing).await.unwrap_err(); + assert!(e.to_string().contains("has not finished deleting"), "{e}"); + assert!(e.to_string().contains("Start the project again in a minute"), "{e}"); + assert!(!e.to_string().contains("Restore"), "{e}"); + assert_eq!(fake.deleted_secrets.lock().unwrap().as_slice(), ["n"]); +} + +#[tokio::test(start_paused = true)] +async fn the_start_after_a_timed_out_replace_retries_the_create() { + // The replace deleted the secret but timed out before making it again: + // the next start's create meets the deletion AWS is still finishing. + let env = pairs(&[("TZ", "UTC")]); + let fake = Fake::onboarded(); + *fake.pending_puts.lock().unwrap() = 3; + prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) + .await + .unwrap(); + assert_eq!(fake.secrets.lock().unwrap().len(), 1, "made once the name is free"); + assert!(fake.deleted_secrets.lock().unwrap().is_empty()); + + // Secrets Manager delivery retries the same way. + let fake = Fake::onboarded(); + *fake.pending_puts.lock().unwrap() = 3; + prepare(&fake, &project(StorageMode::Hybrid), &env).await.unwrap(); + assert_eq!(fake.secrets.lock().unwrap().len(), 1); + + // Still taken past the limit: try again in a minute, never "restore". + let fake = Fake::onboarded(); + *fake.pending_puts.lock().unwrap() = 1000; + let e = prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) + .await + .unwrap_err() + .to_string(); + assert!(e.contains("Start the project again in a minute"), "{e}"); + assert!(!e.contains("Restore"), "{e}"); +} + +#[tokio::test(start_paused = true)] +async fn a_copy_at_connect_read_of_a_secret_being_deleted_is_retried() { + // CreateSecret said it exists, then the read meets a deletion AWS is + // still finishing (another start replacing it): retried like the writes. + let env = pairs(&[("TZ", "UTC")]); + let fake = Fake::onboarded(); + *fake.existing_secret.lock().unwrap() = Some( + r#"{"TRIPLEC_AGENT_TOKEN":"t","TRIPLEC_CREDENTIALS":"connect","TZ":"UTC","TRIPLEC_REPOS":"[]"}"#.into(), + ); + *fake.pending_reads.lock().unwrap() = 3; + prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) + .await + .unwrap(); + assert_eq!(*fake.secret_reads.lock().unwrap(), 4); + assert_eq!(fake.secrets.lock().unwrap().len(), 1); + + // Still being deleted past the limit: try again in a minute. + let fake = Fake::onboarded(); + *fake.existing_secret.lock().unwrap() = Some(r#"{"TZ":"UTC"}"#.into()); + *fake.pending_reads.lock().unwrap() = 1000; + let e = prepare_workspace(&fake, &who(), &env_info(), ©_at_connect_project(), &env, &[], &[], IMAGE, None) + .await + .unwrap_err() + .to_string(); + assert!(e.contains("Start the project again in a minute"), "{e}"); + assert!(fake.secrets.lock().unwrap().is_empty()); +} + +#[test] +fn a_copy_at_connect_payload_drops_the_custom_variables_fingerprint() { + let env = pairs(&[("TRIPLE_C_CUSTOM_ENV", "63ce86"), ("TZ", "UTC")]); + let custom: Vec = Vec::new(); + let with = |connect_only| { + payload_map( + &project_secret_payload_with( + &env, + "tok", + &[], + &[], + true, + None, + StorageMode::Hybrid, + PayloadExtras { connect_only, ..Default::default() }, + ) + .unwrap(), + ) + }; + 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/environment_commands.rs b/app/src-tauri/src/commands/environment_commands.rs index 130530e..3edc6a5 100644 --- a/app/src-tauri/src/commands/environment_commands.rs +++ b/app/src-tauri/src/commands/environment_commands.rs @@ -178,8 +178,9 @@ pub(crate) fn network_from_record( subnet_ids: info.subnet_ids.clone(), assign_public_ip: info.assign_public_ip, }; - // The same checks as the apply's variables. - environment_vars(&info.name, "us-east-1", &choice)?; + // The same checks as the apply's variables. Only the network is + // checked here, so the lifetime cap is a valid placeholder (0). + environment_vars(&info.name, "us-east-1", &choice, 0)?; Ok(choice) } _ => Err("The environment record names an unknown network mode".into()), @@ -1034,13 +1035,20 @@ pub async fn deploy_aws_environment( region: String, name: String, network: NetworkChoice, + max_workspace_hours: Option, app: AppHandle, state: State<'_, AppState>, ) -> Result { let ctx = context(&state, &connection_id, ®ion).await?; let found = detect(&ctx).await?; deploy_refusal(&found, &name).map_err(other)?; - let vars = environment_vars(&name, &ctx.region, &network).map_err(other)?; + let vars = environment_vars( + &name, + &ctx.region, + &network, + max_workspace_hours.unwrap_or(0), + ) + .map_err(other)?; let key = DeploymentKey::Environment(name); opened(launch(app, &ctx, &key, &vars, TofuOp::Apply).await) } @@ -1052,6 +1060,7 @@ pub async fn update_aws_environment( connection_id: String, region: String, name: String, + max_workspace_hours: Option, app: AppHandle, state: State<'_, AppState>, ) -> Result { @@ -1063,7 +1072,9 @@ pub async fn update_aws_environment( .as_ref() .ok_or_else(|| other("The environment has no readable record"))?; let network = recorded_network(&ctx, info).await?; - let vars = environment_vars(&env.name, &ctx.region, &network).map_err(other)?; + // The recorded cap stays unless the caller changes it. + let hours = max_workspace_hours.unwrap_or(info.max_workspace_hours); + let vars = environment_vars(&env.name, &ctx.region, &network, hours).map_err(other)?; let key = DeploymentKey::Environment(env.name.clone()); opened(launch(app, &ctx, &key, &vars, TofuOp::Apply).await) } @@ -1077,6 +1088,7 @@ pub async fn repair_aws_environment( region: String, name: String, network: Option, + max_workspace_hours: Option, app: AppHandle, state: State<'_, AppState>, ) -> Result { @@ -1092,7 +1104,11 @@ pub async fn repair_aws_environment( )) } }; - let vars = environment_vars(&env.name, &ctx.region, &network).map_err(other)?; + // A valid record's cap stays unless the caller changes it. + let hours = max_workspace_hours + .or(env.info.as_ref().map(|i| i.max_workspace_hours)) + .unwrap_or(0); + let vars = environment_vars(&env.name, &ctx.region, &network, hours).map_err(other)?; let key = DeploymentKey::Environment(env.name.clone()); opened(launch(app, &ctx, &key, &vars, TofuOp::Apply).await) } @@ -1113,7 +1129,8 @@ pub async fn destroy_incomplete_aws_environment( let env = destroy_refusal(&found, &name).map_err(other)?; // A destroy plans the removal of everything in state whatever the // network variables say; they only have to be valid. - let vars = environment_vars(&env.name, &ctx.region, &NetworkChoice::Public).map_err(other)?; + let vars = + environment_vars(&env.name, &ctx.region, &NetworkChoice::Public, 0).map_err(other)?; let key = DeploymentKey::Environment(env.name.clone()); opened(launch(app, &ctx, &key, &vars, TofuOp::Destroy).await) } @@ -1372,6 +1389,7 @@ pub async fn save_aws_admin_bundle( environment: Option, owner_id: Option, network: Option, + max_workspace_hours: Option, window: tauri::Window, state: State<'_, AppState>, ) -> Result, AwsError> { @@ -1386,8 +1404,13 @@ pub async fn save_aws_admin_bundle( let (key, vars) = match kind { ModuleKind::Environment => { let env = need_env()?; - let vars = environment_vars(&env, ®ion_ok, &network.unwrap_or(NetworkChoice::Public)) - .map_err(other)?; + let vars = environment_vars( + &env, + ®ion_ok, + &network.unwrap_or(NetworkChoice::Public), + max_workspace_hours.unwrap_or(0), + ) + .map_err(other)?; (DeploymentKey::Environment(env), vars) } ModuleKind::UserOnboard => { diff --git a/app/src-tauri/src/commands/environment_commands/tests.rs b/app/src-tauri/src/commands/environment_commands/tests.rs index 0b0b5a1..b419554 100644 --- a/app/src-tauri/src/commands/environment_commands/tests.rs +++ b/app/src-tauri/src/commands/environment_commands/tests.rs @@ -32,6 +32,7 @@ fn info(name: &str, mode: &str, assign_public_ip: bool) -> EnvironmentInfo { log_group: format!("/triple-c/{name}"), network_mode: mode.into(), tenancy: "strict".into(), + max_workspace_hours: 0, } } @@ -165,6 +166,7 @@ fn update_reuses_the_recorded_network() { "dev", REGION, &network_from_record(&existing, Some("vpc-0123456789abcdef0")).unwrap(), + 0, ) .unwrap(); assert_eq!(vars["network_mode"], "existing"); @@ -266,7 +268,7 @@ fn bundles_contain_the_module_backend_vars_and_readme() { #[test] fn a_us_east_1_bundle_creates_its_bucket_without_a_location_constraint() { let dir = tempfile::tempdir().unwrap(); - let vars = environment_vars("dev", "us-east-1", &NetworkChoice::Public).unwrap(); + let vars = environment_vars("dev", "us-east-1", &NetworkChoice::Public, 0).unwrap(); write_bundle(dir.path(), Deployment::Environment("dev"), ACCOUNT, "us-east-1", &vars).unwrap(); let readme = fs::read_to_string(dir.path().join("README.txt")).unwrap(); assert!(readme.contains("aws s3api create-bucket"), "{readme}"); diff --git a/app/src-tauri/src/commands/host_commands.rs b/app/src-tauri/src/commands/host_commands.rs index 3c7bc66..6daa72e 100644 --- a/app/src-tauri/src/commands/host_commands.rs +++ b/app/src-tauri/src/commands/host_commands.rs @@ -2,15 +2,18 @@ //! sign-in and the permission check. use std::future::Future; +use std::sync::OnceLock; +use std::time::SystemTime; use tauri::State; use crate::aws::permissions::{check_permissions, PermissionReport, SdkPermissionApi}; use crate::aws::policies::{policy_files, Tier}; +use crate::aws::pricing::{self, HourlyEstimate, RatesCache, SdkPricingApi}; use crate::aws::{caller_identity, sdk_config, sdk_config_for_keys, AwsError, CallerIdentity}; use crate::models::{ validate_connection_name, validate_profile_name, validate_supported_region, AppSettings, AwsAuth, - HostConnection, HostKind, + AwsWorkspaceConfig, HostConnection, HostKind, }; use crate::storage::secure::{self, AwsKeys}; use crate::storage::settings_store::SettingsStore; @@ -301,6 +304,65 @@ pub fn aws_policy_document(tier: Tier) -> Vec { .collect() } +/// The cost estimate's rate cache, `/triple-c/aws-pricing/`, shared +/// by every call (it also remembers recent failures). `None` without a data +/// folder. +fn pricing_cache() -> Option<&'static RatesCache> { + static CACHE: OnceLock> = OnceLock::new(); + CACHE + .get_or_init(|| pricing::default_cache_dir().map(RatesCache::new)) + .as_ref() +} + +/// The estimated on-demand hourly cost of `config` as a Fargate task in +/// `region` (Q5). It takes the config rather than a project id because +/// Project Home's Host settings ask while the user edits, and the Overview +/// asks for the saved one; `connection_id` is the project's connection, whose +/// credentials sign the Price List call (made in us-east-1). **Never an +/// error:** a bad region, a missing connection, a denied or slow call (8 s +/// bound) or an unreadable price list is `None`, shown as "Estimate +/// unavailable". Rates are cached a day per region. +#[tauri::command] +pub async fn aws_cost_estimate( + connection_id: String, + region: String, + config: AwsWorkspaceConfig, + state: State<'_, AppState>, +) -> Result, String> { + let Some(cache) = pricing_cache() else { + return Ok(None); + }; + let settings = state.settings_store.get(); + Ok(cost_estimate(cache, &connection_id, ®ion, &config, &settings, SystemTime::now()).await) +} + +async fn cost_estimate( + cache: &RatesCache, + connection_id: &str, + region: &str, + config: &AwsWorkspaceConfig, + settings: &AppSettings, + now: SystemTime, +) -> Option { + let region = validate_supported_region(region).ok()?; + let rates = match cache.read(®ion, now) { + Some((rates, true)) => Some(rates), + _ => { + // Only now touch the connection (a keys connection reads the + // keychain); without one, a stale cache still answers. + // Built inside the fetch's 8 s bound: reading a profile's + // credentials can hang as well (an SSO or process provider). + let api = async { + let conn = aws_conn(connection_id, settings).ok()?; + let cfg = sdk_config(&conn, pricing::PRICING_REGION).await.ok()?; + Some(SdkPricingApi::new(&cfg)) + }; + cache.rates_with::(api, ®ion, now).await + } + }?; + Some(pricing::estimate(config, &rates.for_arch(config.arch)?)) +} + #[cfg(test)] mod tests { use super::*; @@ -557,4 +619,59 @@ mod tests { "workspace-user.json" ); } + + fn sample_rates() -> pricing::RegionRates { + let x86 = pricing::FargateRates { + vcpu_hour: 0.04, + gb_hour: 0.004, + storage_gb_hour: 0.0001, + }; + pricing::RegionRates { + x86_64: Some(x86), + arm64: None, + } + } + + #[tokio::test] + async fn the_cost_estimate_answers_from_a_fresh_cache_without_a_connection() { + let dir = tempfile::tempdir().unwrap(); + let cache = RatesCache::new(dir.path().to_path_buf()); + let now = SystemTime::now(); + cache.write("us-west-2", &sample_rates(), now).unwrap(); + let settings = AppSettings::default(); + let config = AwsWorkspaceConfig { + cpu: 1024, + memory_mib: 2048, + ephemeral_gib: 20, + spot: true, + ..Default::default() + }; + let e = cost_estimate(&cache, "gone", "us-west-2", &config, &settings, now) + .await + .expect("estimate"); + assert!((e.usd_per_hour - (0.04 + 2.0 * 0.004)).abs() < 1e-9); + assert!(e.note_spot && e.efs_billed_separately); + // An architecture the price list lacked has no estimate. + let arm = AwsWorkspaceConfig { + arch: crate::models::Arch::Arm64, + ..config.clone() + }; + assert_eq!(cost_estimate(&cache, "gone", "us-west-2", &arm, &settings, now).await, None); + } + + #[tokio::test] + async fn the_cost_estimate_is_none_never_an_error() { + let dir = tempfile::tempdir().unwrap(); + let cache = RatesCache::new(dir.path().to_path_buf()); + let settings = AppSettings::default(); + let config = AwsWorkspaceConfig::default(); + let now = SystemTime::now(); + // No cache and no such connection. + assert_eq!(cost_estimate(&cache, "gone", "us-west-2", &config, &settings, now).await, None); + // A region that isn't one (it would name the cache file). + cache.write("us-west-2", &sample_rates(), now).unwrap(); + for bad in ["../us-west-2", "", "us-west-2/x"] { + assert_eq!(cost_estimate(&cache, "gone", bad, &config, &settings, now).await, None); + } + } } diff --git a/app/src-tauri/src/commands/project_commands.rs b/app/src-tauri/src/commands/project_commands.rs index f54fc5d..751ee4c 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) @@ -715,7 +717,7 @@ pub async fn remove_project( // An AWS project's task and resources go first, and a failure keeps the // project: its record is the only handle on a billed task and its - // secret. Its EFS access point goes only when asked (the files stay on the + // secret. Its EFS access points go only when asked (the files stay on the // user's own file system until offboarding). if let Some(project) = state.projects_store.get(&project_id).filter(|p| p.is_aws()) { let settings = state.settings_store.get(); @@ -1061,6 +1063,7 @@ fn pending_cleanup_is_stale(recorded_at: &str, now: chrono::DateTime, ) -> Result { // Taken as raw JSON, then deserialised, for one reason: a secret field that @@ -1122,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(); @@ -1144,9 +1151,19 @@ pub async fn update_project( // lock against the record as it is *now*, so a marketplace install, a // status change or a container id landing since `stored` was read is kept // rather than written over. - state + let mappings_changed = stored.port_mappings != project.port_mappings; + let saved = state .projects_store - .update_restoring(project, restore_store_owned_fields) + .update_restoring(project, restore_store_owned_fields)?; + + // AWS (Q6): a connected workspace's forwards follow the saved mappings + // now — there is no container to recreate. Nothing when not connected. + if saved.is_aws() && mappings_changed { + if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &saved.id).await { + emit_ports_warning(&app_handle, &saved.id, &saved.name, &detail); + } + } + Ok(saved) } /// Restore onto `project` the fields whose value belongs to the store rather @@ -1191,9 +1208,30 @@ fn restore_store_owned_fields(project: &mut Project, stored: &Project) { aws.task_arn = s.and_then(|a| a.task_arn.clone()); aws.access_point_id = s.and_then(|a| a.access_point_id.clone()); aws.task_definition_arn = s.and_then(|a| a.task_definition_arn.clone()); + aws.workspace_access_point_id = s.and_then(|a| a.workspace_access_point_id.clone()); } } +/// 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( @@ -1210,6 +1248,13 @@ fn validate_aws_update( crate::models::validate_region(&place.region)?; crate::aws::tofu_modules::validate_environment_name(&place.environment)?; crate::models::validate_aws_workspace(cfg)?; + // Q6: forwarded over loopback, TCP only, never a reserved port + // (rows the save adds or edits; everything when newly on AWS). + crate::host::port_forwards::validate_aws_port_mappings_update( + stored.aws.as_ref().map(|a| (stored.port_mappings.as_slice(), a.gateway_sidecar)), + &project.port_mappings, + cfg.gateway_sidecar, + )?; } _ => { return Err( @@ -1226,7 +1271,10 @@ fn validate_aws_update( // connection's account and region; moving the project would orphan them. if moved && stored.aws.as_ref().is_some_and(|a| { - a.task_arn.is_some() || a.access_point_id.is_some() || a.task_definition_arn.is_some() + a.task_arn.is_some() + || a.access_point_id.is_some() + || a.workspace_access_point_id.is_some() + || a.task_definition_arn.is_some() }) { return Err( @@ -1459,7 +1507,7 @@ async fn start_project_container_locked( // id stored above is the tunnel's endpoint URL, which is what the death // watch reports a stopped task as. if project.is_aws() { - if let Some((task_arn, access_point_id, task_definition_arn)) = + if let Some((task_arn, access_point_id, task_definition_arn, workspace_access_point_id)) = crate::host::tunnels::runtime(&project_id) { state.projects_store.set_aws_runtime( @@ -1467,6 +1515,7 @@ async fn start_project_container_locked( Some(task_arn), access_point_id, Some(task_definition_arn), + workspace_access_point_id, )?; } } @@ -1486,11 +1535,117 @@ async fn start_project_container_locked( .await; } + // AWS (Q6): the project's port mappings become loopback forwards into + // the workspace; a mapping that can't open is a warning, the rest work. + if project.is_aws() { + if let Some(detail) = crate::host::port_forwards::open_for_project(&state.projects_store, &project_id).await { + emit_ports_warning(&app_handle, &project_id, &project.name, &detail); + } + } + + // AWS, copy-at-connect (Q2): every connect copies the credentials in, + // in the background (the clone waits for them); a failure is a warning. + if project.is_aws() { + let (handle, id, name) = (app_handle.clone(), project_id.clone(), project.name.clone()); + crate::host::aws_host::spawn_connect_push(&project, &settings, move |detail| { + emit_connect_warning(&handle, &id, &name, &detail) + }); + } + + // AWS: the start is done (Running, lock released when this returns); + // the background clone and setup script are followed by a background + // task that only reports a failure (ruling R5). Never for Docker. + if project.is_aws() { + let (handle, id, name) = (app_handle.clone(), project_id.clone(), project.name.clone()); + crate::host::aws_host::spawn_follow(&project, move |detail| { + emit_workspace_warning(&handle, &id, &name, &detail) + }); + } + project.container_id = Some(container_id); project.status = ProjectStatus::Running; Ok(project) } +/// The follower's warning channel (phase 6, Q4/R5): a started workspace +/// whose clone or setup script failed (or still ran after 35 minutes) is +/// reported as a `workspace-warning` event `{project_id, message, detail}`; +/// the frontend shows it as a warning toast. +fn emit_workspace_warning(app_handle: &tauri::AppHandle, project_id: &str, name: &str, detail: &str) { + let _ = app_handle.emit( + "workspace-warning", + serde_json::json!({ + "project_id": project_id, + "message": format!("“{name}” started, but not everything went well"), + "detail": detail, + }), + ); +} + +/// Copy-at-connect's warning (Q2): the credentials could not be copied into +/// a connected workspace. Same `workspace-warning` event as the follower's, +/// with its own `topic` so neither replaces the other's toast. +fn emit_connect_warning(app_handle: &tauri::AppHandle, project_id: &str, name: &str, detail: &str) { + let _ = app_handle.emit("workspace-warning", connect_warning_payload(project_id, name, detail)); +} + +fn connect_warning_payload(project_id: &str, name: &str, detail: &str) -> serde_json::Value { + serde_json::json!({ + "project_id": project_id, + "message": format!("“{name}”: the credentials could not be copied into the workspace"), + "detail": detail, + "topic": "connect", + }) +} + +/// Port mappings that could not be forwarded to a connected AWS workspace +/// (Q6): a busy host port, a host port mapped twice. Same `workspace-warning` +/// event, with its own `topic` so it does not replace the other warnings. +fn emit_ports_warning(app_handle: &tauri::AppHandle, project_id: &str, name: &str, detail: &str) { + let _ = app_handle.emit( + "workspace-warning", + serde_json::json!({ + "project_id": project_id, + "message": format!("“{name}”: some port mappings could not be opened"), + "detail": detail, + "topic": "ports", + }), + ); +} + +/// An AWS workspace's clone and setup-script status for Project Home +/// (background exec: never activity for idle stop). `None` for a local +/// project, a workspace with no tunnel, or an image without the reader. +#[tauri::command] +pub async fn aws_workspace_status( + project_id: String, + state: State<'_, AppState>, +) -> Result, String> { + let project = state + .projects_store + .get(&project_id) + .ok_or_else(|| format!("Project {} not found", project_id))?; + crate::host::aws_host::workspace_status(&project).await +} + +/// The lifetime cap (hours; 0 = none) of an AWS project's environment, read +/// from its record, for Host settings. `None` for a local project or when the +/// record can't be read; never an error. +#[tauri::command] +pub async fn aws_environment_max_hours( + project_id: String, + state: State<'_, AppState>, +) -> Result, String> { + let Some(project) = state.projects_store.get(&project_id) else { + return Ok(None); + }; + if !project.is_aws() { + return Ok(None); + } + let settings = state.settings_store.get(); + Ok(crate::host::aws_host::environment_max_hours(&project, &settings).await) +} + #[tauri::command] pub async fn stop_project_container( project_id: String, @@ -1518,6 +1673,9 @@ pub async fn stop_project_container( } state.projects_store.update_status(&project_id, ProjectStatus::Stopping)?; + // AWS: the background clone/setup follower ends now (it holds no lock; + // closing the tunnel would end it too). + crate::host::tunnels::cancel_follow(&project_id); // AWS: the terminals and the auth bridge close *before* the stop guard's // push, so nothing written after its snapshot is silently dropped (the @@ -1585,6 +1743,7 @@ pub async fn stop_project_container( None, a.access_point_id.clone(), a.task_definition_arn.clone(), + a.workspace_access_point_id.clone(), )?; } state.projects_store.set_container_id(&project_id, None)?; @@ -1693,24 +1852,37 @@ pub async fn remove_aws_resources( ProjectHost::for_project(&project) .remove_aws_resources(&project, &settings, discard_data) .await?; - state - .projects_store - .set_aws_runtime(&project_id, None, access_point_after_removal(&project, discard_data), None)?; + let (access_point_id, workspace_access_point_id) = + access_points_after_removal(&project, discard_data); + state.projects_store.set_aws_runtime( + &project_id, + None, + access_point_id, + None, + workspace_access_point_id, + )?; state .projects_store .get(&project_id) .ok_or_else(|| format!("Project {} not found", project_id)) } -/// The access point a removal leaves stored: kept when the saved files were -/// kept (it is still there, a later start reuses it and a later removal -/// with `discard_data` deletes it; and while it is stored the project can't -/// move away from it — [`validate_aws_update`]), gone when they were not. -fn access_point_after_removal(project: &Project, discard_data: bool) -> Option { - if discard_data { - return None; +/// The access points (home, EFS `/workspace`) a removal leaves stored: kept +/// when the saved files were kept (they are still there, a later start +/// reuses them and a later removal with `discard_data` deletes them; and +/// while one is stored the project can't move away from it — +/// [`validate_aws_update`]), gone when they were not. +fn access_points_after_removal( + project: &Project, + discard_data: bool, +) -> (Option, Option) { + match project.aws.as_ref() { + Some(a) if !discard_data => ( + a.access_point_id.clone(), + a.workspace_access_point_id.clone(), + ), + _ => (None, None), } - project.aws.as_ref().and_then(|a| a.access_point_id.clone()) } fn check_aws_resources_removable(project: &Project) -> Result<(), String> { @@ -1949,12 +2121,26 @@ pub async fn reconcile_project_statuses( /// How many AWS projects reconcile at once. const AWS_RECONCILE_CONCURRENCY: usize = 4; +/// Whether an AWS project's status must be checked against ECS at startup: +/// anything but a clean Stopped — and a Stopped one that still has a task +/// ARN (Stop clears it, so the stored ARN means a start or stop never +/// finished and a billed task may be running). +pub(crate) fn needs_aws_reconcile(p: &Project) -> bool { + match p.status { + ProjectStatus::Running | ProjectStatus::Error | ProjectStatus::Starting | ProjectStatus::Stopping => true, + ProjectStatus::Stopped => p.aws.as_ref().is_some_and(|a| a.task_arn.is_some()), + } +} + /// Reconcile every AWS project against ECS (the authority), independently of /// Docker: an app started without Docker still learns which tasks run and /// re-opens their tunnels. One bounded DescribeTasks per project, a few at a /// time; a live task's tunnel is re-opened in the background. #[tauri::command] -pub async fn reconcile_aws_projects(state: State<'_, AppState>) -> Result, String> { +pub async fn reconcile_aws_projects( + app_handle: tauri::AppHandle, + state: State<'_, AppState>, +) -> Result, String> { use futures_util::StreamExt; let projects: Vec = state.projects_store.list().into_iter().filter(|p| p.is_aws()).collect(); @@ -1972,20 +2158,32 @@ pub async fn reconcile_aws_projects(state: State<'_, AppState>) -> Result) -> Result(src: &'a str, name: &str) -> &'a str { + let start = src.find(&format!("fn {name}(")).unwrap_or_else(|| panic!("{name} missing")); + let rest = &src[start..]; + let end = rest.find("\n}\n").unwrap(); + &rest[..end] + } + + #[test] + fn the_workspace_follower_is_spawned_after_the_start_succeeds_and_only_for_aws() { + // Ruling R5: the start ends after "Connecting…" (Running, lock + // released when the command returns); the clone/setup follow runs + // in the background and never inside the start. + let src = include_str!("project_commands.rs"); + let start = fn_body(src, "start_project_container_locked"); + let running = start + .find("update_status(&project_id, ProjectStatus::Running)") + .expect("the start sets Running"); + let spawn = start.find("aws_host::spawn_follow(").expect("the start spawns the follower"); + assert!(spawn > running, "the follower is spawned only after the project is Running"); + assert_eq!(start.matches("spawn_follow(").count(), 1); + let guard = start[..spawn].rfind("if project.is_aws() {").expect("AWS-only"); + assert!(start[guard..spawn].lines().count() <= 4, "the spawn sits right in the AWS guard"); + assert!(!start.contains("follow_workspace_status"), "no follow inside the start"); + // Docker: `spawn_follow` itself also refuses a local project + // (`status::tests::a_local_project_has_no_workspace_status_and_no_follower`). + } + + #[test] + fn every_connect_of_a_copy_at_connect_project_copies_the_credentials_in() { + // Q2: a start (new task or attach) and the background re-attach at + // app start both push; a failure is a `workspace-warning`. + let src = include_str!("project_commands.rs"); + let start = fn_body(src, "start_project_container_locked"); + let running = start.find("update_status(&project_id, ProjectStatus::Running)").unwrap(); + let push = start.find("aws_host::spawn_connect_push(").expect("the start pushes"); + assert!(push > running, "only once the workspace is connected and Running"); + let guard = start[..push].rfind("if project.is_aws() {").expect("AWS-only"); + assert!(start[guard..push].lines().count() <= 4); + assert!(start[push..].starts_with("aws_host::spawn_connect_push(&project, &settings, move |detail| {\n emit_connect_warning(")); + let reconcile = fn_body(src, "reconcile_aws_projects"); + assert!(reconcile.contains("emit_connect_warning(&handle, &id, &name, &detail)")); + assert!(reconcile.contains("aws_host::reconcile(\n &project,\n &settings,\n store,\n on_connect_warning,")); + } + + #[test] + fn an_aws_project_refuses_new_udp_and_reserved_mappings_and_a_local_one_does_not() { + let hosts = vec![host("h1")]; + let udp = crate::models::PortMapping { + host_port: 5353, + container_port: 5353, + protocol: "udp".into(), + }; + let stored = aws_project(); + let mut aws = aws_project(); + aws.port_mappings = vec![udp.clone()]; + let e = validate_aws_update(&stored, &aws, &hosts).unwrap_err(); + assert!(e.contains("only TCP"), "{e}"); + // A stored UDP row does not block an unrelated save (it is skipped, + // with a warning, at connect). + assert!(validate_aws_update(&aws, &aws, &hosts).is_ok()); + // Moving a local project with one to AWS checks everything. + let (mut local, _) = stored_and_stale_payload(); + local.port_mappings = vec![udp.clone()]; + assert!(validate_aws_update(&local, &aws, &hosts).unwrap_err().contains("only TCP")); + aws.port_mappings[0].container_port = crate::host::ssm::AGENT_PORT; + aws.port_mappings[0].protocol = "tcp".into(); + assert!(validate_aws_update(&stored, &aws, &hosts).is_err()); + aws.port_mappings[0].container_port = 3000; + assert!(validate_aws_update(&stored, &aws, &hosts).is_ok()); + + // Docker publishes UDP itself: a local project is not checked. + assert!(validate_aws_update(&local, &local, &hosts).is_ok()); + } + + #[test] + fn every_connect_of_an_aws_project_opens_its_port_mappings() { + // Q6: the start (after Running), the background re-attach, and a save + // of the mappings while connected; a failure is a `workspace-warning`. + let src = include_str!("project_commands.rs"); + let start = fn_body(src, "start_project_container_locked"); + let running = start.find("update_status(&project_id, ProjectStatus::Running)").unwrap(); + let open = start + .find("port_forwards::open_for_project(&state.projects_store, &project_id)") + .expect("the start opens them"); + assert!(open > running); + let guard = start[..open].rfind("if project.is_aws() {").expect("AWS-only"); + assert!(start[guard..open].lines().count() <= 2); + assert!(start[open..].lines().nth(1).unwrap().contains("emit_ports_warning(")); + let update = fn_body(src, "update_project"); + assert!(update.contains("port_forwards::open_for_project(&state.projects_store, &saved.id)")); + let reconcile = fn_body(src, "reconcile_aws_projects"); + assert!(reconcile.contains("on_ports_warning,")); + assert!(reconcile.contains("emit_ports_warning(&ports_handle, &ports_id, &ports_name, &detail)")); + let aws_host = include_str!("../host/aws_host.rs"); + let reattached = aws_host.find("Ok(true) => {").unwrap(); + let opened = aws_host.find("port_forwards::open_for_project(&store, &project.id)").unwrap(); + let pushed = aws_host[reattached..].find("connect::apply_connect(").unwrap() + reattached; + assert!(reattached < opened && opened < pushed); + } + + #[test] + fn stop_ends_the_follower_before_it_stops_the_task() { + let src = include_str!("project_commands.rs"); + let stop = fn_body(src, "stop_project_container"); + let cancel = stop.find("tunnels::cancel_follow(&project_id)").expect("stop cancels the follower"); + let task = stop.find(".stop_project(&project, &settings)").expect("stop stops the task"); + assert!(cancel < task); + // Stop's own claim never waits on the follower: it holds none + // (`status::tests::the_follower_takes_no_project_lock`). + } + } diff --git a/app/src-tauri/src/commands/stop_guard.rs b/app/src-tauri/src/commands/stop_guard.rs index a6efb1b..122e840 100644 --- a/app/src-tauri/src/commands/stop_guard.rs +++ b/app/src-tauri/src/commands/stop_guard.rs @@ -115,13 +115,15 @@ pub async fn forget_choice(runner: Option<&R>, choice: Option Vec { vec![ "sh".into(), "-c".into(), format!( - "umask 077 && mkdir -p /run/triple-c && chmod 700 /run/triple-c && printf '%s\\n' \"$1\" > {STOP_REASON_FILE}" + "umask 077 && mkdir -p /run/triple-c && chmod 711 /run/triple-c && printf '%s\\n' \"$1\" > {STOP_REASON_FILE}" ), "sh".into(), marker.into(), diff --git a/app/src-tauri/src/commands/terminal_commands.rs b/app/src-tauri/src/commands/terminal_commands.rs index 9bbeb05..5087030 100644 --- a/app/src-tauri/src/commands/terminal_commands.rs +++ b/app/src-tauri/src/commands/terminal_commands.rs @@ -182,6 +182,10 @@ pub async fn open_terminal_session( ), }; + // AWS copy-at-connect: the credentials go into this terminal's own + // environment (never the agent's). Empty for everything else. + let env = crate::host::aws_host::terminal_env(&project, &state.settings_store.get()).await; + let output_event = format!("terminal-output-{}", session_id); let exit_event = format!("terminal-exit-{}", session_id); let app_handle_output = app_handle.clone(); @@ -193,6 +197,7 @@ pub async fn open_terminal_session( &target, &session_id, cmd, + env, move |data| { let _ = app_handle_output.emit(&output_event, data); }, diff --git a/app/src-tauri/src/container_watch.rs b/app/src-tauri/src/container_watch.rs index 0ab8399..8b11d21 100644 --- a/app/src-tauri/src/container_watch.rs +++ b/app/src-tauri/src/container_watch.rs @@ -77,7 +77,7 @@ pub struct ContainerExited<'a> { /// Why an AWS task stopped, for the UI's toast. #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct StopNote { - /// `spot`, `idle`, `failed` (the project goes to Error), `user` (someone + /// `spot`, `idle`, `lifetime`, `failed` (the project goes to Error), `user` (someone /// stopped it: no toast) or `exited` (on its own). pub kind: &'static str, /// ECS's stopped reason, or a fixed text. @@ -89,6 +89,7 @@ impl StopNote { let (kind, message) = match kind { StopKind::Spot => ("spot", Some("Spot interruption".to_string())), StopKind::Idle => ("idle", None), + StopKind::LifetimeCap => ("lifetime", None), StopKind::FailedToStart(r) => ("failed", Some(r.clone())), StopKind::UserInitiated => ("user", None), StopKind::Exited(r) => ("exited", r.clone()), @@ -276,6 +277,7 @@ pub fn spawn( None, a.access_point_id.clone(), a.task_definition_arn.clone(), + a.workspace_access_point_id.clone(), ); } let id = p.id.clone(); @@ -331,6 +333,7 @@ mod tests { let cases = [ (StopKind::Spot, "spot", Some("Spot interruption")), (StopKind::Idle, "idle", None), + (StopKind::LifetimeCap, "lifetime", None), (StopKind::FailedToStart("CannotPull".into()), "failed", Some("CannotPull")), (StopKind::UserInitiated, "user", None), (StopKind::Exited(Some("OOM".into())), "exited", Some("OOM")), diff --git a/app/src-tauri/src/docker/aws_mode_tests.rs b/app/src-tauri/src/docker/aws_mode_tests.rs index 192f733..4071414 100644 --- a/app/src-tauri/src/docker/aws_mode_tests.rs +++ b/app/src-tauri/src/docker/aws_mode_tests.rs @@ -10,9 +10,23 @@ use std::path::Path; use std::process::{Command, Output}; const ENTRYPOINT: &str = include_str!("../../../../container/entrypoint.sh"); +/// The functions `entrypoint.sh` and `triple-c-apply-connect` both source. +const LIB: &str = include_str!("../../../../container/entrypoint-lib.sh"); +const APPLY_CONNECT: &str = include_str!("../../../../container/triple-c-apply-connect"); const WIP_PUSH: &str = include_str!("../../../../container/triple-c-wip-push"); const IDLE_WATCH: &str = include_str!("../../../../container/triple-c-idle-watch"); const SCHEDULER: &str = include_str!("../../../../container/triple-c-scheduler"); +const WORKSPACE_STATUS: &str = include_str!("../../../../container/triple-c-workspace-status"); + +/// A marked block of `entrypoint.sh` or, failing that, of the library it +/// sources. +fn eblock(name: &str) -> &'static str { + if ENTRYPOINT.contains(&format!("# >>> {name}\n")) { + block(ENTRYPOINT, name) + } else { + block(LIB, name) + } +} fn block<'a>(text: &'a str, name: &str) -> &'a str { let start = text @@ -24,12 +38,13 @@ fn block<'a>(text: &'a str, name: &str) -> &'a str { &text[start..end] } -/// The aws blocks with the container user switched off: no `su claude`, no -/// chown to a user the test host may not have. +/// The aws blocks (after the library's shared settings, `aws_lib`, which the +/// entrypoint sources first) with the container user switched off: no +/// `su claude`, no chown to a user the test host may not have. fn aws_blocks(names: &[&str]) -> String { - names - .iter() - .map(|n| block(ENTRYPOINT, n).replace("triplec_run_as=claude", "triplec_run_as=")) + std::iter::once("aws_lib") + .chain(names.iter().copied()) + .map(|n| eblock(n).replace("triplec_run_as=claude", "triplec_run_as=")) .collect::>() .join("\n") } @@ -101,7 +116,8 @@ fn files_script(tmp: &Path) -> String { "{blocks}\n{agent}\n\ env -0 > \"$1/env\"\n\ printf '%s\\0' \"${{agent_env[@]}}\" > \"$1/agent_env\"\n\ - printf '%s' \"${{triplec_repos_json:-}}\" > \"$1/repos\"\n" + printf '%s' \"${{triplec_repos_json:-}}\" > \"$1/repos\"\n\ + printf '%s' \"${{triplec_setup_script:-}}\" > \"$1/setup\"\n" ) } @@ -129,6 +145,7 @@ fn aws_files_decode_to_the_host_dirs_mode_600_and_leave_the_environment() { ("TRIPLEC_HOST", "aws"), ("TRIPLEC_FILES", &files), ("TRIPLEC_REPOS", repos), + ("TRIPLEC_SETUP_SCRIPT", "echo SETUP-BODY"), ("TRIPLEC_AGENT_TOKEN", "test-token-not-real"), ], &[], @@ -178,6 +195,10 @@ fn aws_files_decode_to_the_host_dirs_mode_600_and_leave_the_environment() { assert!(!agent_env.contains(&b64("PRIVATE-KEY-BODY"))); // The repo list survives as an unexported shell variable for clone_repos. assert_eq!(fs::read_to_string(tmp.path().join("repos")).unwrap(), repos); + // So does the setup script, for aws_prepare_run to write to its file. + assert!(!env.contains("TRIPLEC_SETUP_SCRIPT=") && !env.contains("SETUP-BODY"), "{env}"); + assert!(!agent_env.contains("TRIPLEC_SETUP_SCRIPT") && !agent_env.contains("SETUP-BODY")); + assert_eq!(fs::read_to_string(tmp.path().join("setup")).unwrap(), "echo SETUP-BODY"); } #[test] @@ -273,6 +294,42 @@ fn link_persistent_home_without_the_mount_changes_nothing() { assert!(fs::symlink_metadata(home.join(".claude")).unwrap().is_dir()); } +#[test] +fn efs_storage_links_home_state_like_hybrid() { + let script = format!( + "{}\nfor m in hybrid efs ephemeral '' HYBRID efsx; do aws_storage_links_home \"$m\" && echo \"$m:yes\" || echo \"$m:no\"; done\n", + aws_blocks(&["aws_env", "aws_home"]) + ); + let out = bash(&script, &[], &[], &[]); + assert_eq!( + String::from_utf8_lossy(&out.stdout), + "hybrid:yes\nefs:yes\nephemeral:no\n:no\nHYBRID:no\nefsx:no\n" + ); + // The call site asks it, rather than testing for `hybrid` alone (an EFS + // task would otherwise get no home links at all). + let call = ENTRYPOINT + .lines() + .position(|l| l.trim_start().starts_with("link_persistent_home /home/claude")) + .unwrap(); + let above = ENTRYPOINT.lines().nth(call - 1).unwrap(); + assert_eq!( + above.trim(), + "if [ \"$triplec_aws\" = 1 ] && aws_storage_links_home \"${TRIPLEC_STORAGE:-}\"; then" + ); +} + +#[test] +fn efs_workspace_check_warns_only_when_workspace_is_not_mounted() { + let tmp = tempfile::tempdir().unwrap(); + let script = format!("{}\naws_efs_workspace_check \"$1\"; echo \"rc=$?\"\n", aws_blocks(&["aws_env", "aws_home"])); + let out = bash(&script, &[tmp.path()], &[], &[]); + assert!(text(&out).contains("is not mounted"), "{}", text(&out)); + assert!(text(&out).contains("rc=0"), "{}", text(&out)); + let out = bash(&script, &[Path::new("/proc")], &[], &[]); + assert!(!text(&out).contains("warning"), "{}", text(&out)); + assert!(text(&out).contains("rc=0"), "{}", text(&out)); +} + /// `write_claude_json` with the Hybrid mount at `/mnt`, in aws mode or not. fn write_claude_json(tmp: &Path, aws: bool) -> Output { let mnt = tmp.join("mnt"); @@ -426,6 +483,92 @@ fn clone_repos_clones_skips_existing_and_reports_failures_without_failing() { ); } +/// clone_repos over `ws` (persistent, as with EFS storage), its status in `status`. +fn clone_into(ws: &Path, status: &Path, json: &str) -> (String, String) { + fs::create_dir_all(status).unwrap(); + let script = format!("{}\nclone_repos \"$JSON\" \"$1\" \"$2\"\n", aws_blocks(&["aws_env", "aws_repos"])); + let out = bash(&script, &[ws, status], &[("JSON", json)], &[]); + assert!(out.status.success(), "{}", text(&out)); + (text(&out), fs::read_to_string(status.join("repos")).unwrap_or_default()) +} + +fn repos_json(remote: &Path, folders: &[&str]) -> String { + let items: Vec = folders + .iter() + .map(|f| format!(r#"{{"url":"{}","branch":null,"folder":"{f}"}}"#, remote.display())) + .collect(); + format!("[{}]", items.join(",")) +} + +#[test] +fn clone_repos_clones_through_scratch_and_redoes_a_clone_a_killed_task_left_there() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("workspace"); + fs::create_dir_all(&ws).unwrap(); + let remote = bare_remote(tmp.path(), "proj"); + let json = repos_json(&remote, &["a"]); + // The last task was killed mid-clone: only scratch holds it. + let scratch = ws.join(".triple-c-clone"); + fs::create_dir_all(scratch.join("a/.git")).unwrap(); + fs::write(scratch.join("a/half"), "x").unwrap(); + let (_, status) = clone_into(&ws, &tmp.path().join("s1"), &json); + assert_eq!(status, "a\tcloning\na\tcloned\n"); + assert_eq!(fs::read_to_string(ws.join("a/README")).unwrap(), "hello"); + assert!(!ws.join("a/half").exists()); + // Nothing is left in scratch after a successful run. + assert_eq!(fs::read_dir(&scratch).map(|d| d.count()).unwrap_or(0), 0); +} + +#[test] +fn clone_repos_never_deletes_a_folder_at_its_final_path() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("workspace"); + fs::create_dir_all(&ws).unwrap(); + let remote = bare_remote(tmp.path(), "proj"); + // A repository already in place, the user's work in it, and a stale + // scratch copy of the same name. + git(&ws, &["clone", "-q", remote.to_str().unwrap(), "a"]); + fs::write(ws.join("a/mine"), "work").unwrap(); + fs::create_dir_all(ws.join(".triple-c-clone/a/.git")).unwrap(); + // A folder the user made that is not a repository, and a clone that + // fails into it. + fs::create_dir_all(ws.join("notes")).unwrap(); + fs::write(ws.join("notes/todo"), "keep").unwrap(); + // An empty folder is cloned into, as `git clone` would. + fs::create_dir_all(ws.join("empty")).unwrap(); + let json = format!( + r#"[{{"url":"{r}","branch":null,"folder":"a"}}, + {{"url":"{r}","branch":null,"folder":"empty"}}, + {{"url":"{r}","branch":null,"folder":"notes"}}, + {{"url":"/nonexistent/nope.git","branch":null,"folder":"gone"}}]"#, + r = remote.display() + ); + for run in 0..3 { + let (log, status) = clone_into(&ws, &tmp.path().join(format!("s{run}")), &json); + assert!(status.starts_with("a\texists\n"), "{status}"); + assert!(status.contains("notes\tfailed\n"), "{status}: {log}"); + assert!(status.contains("gone\tfailed\n"), "{status}"); + assert_eq!(fs::read_to_string(ws.join("a/mine")).unwrap(), "work", "run {run}"); + assert_eq!(fs::read_to_string(ws.join("notes/todo")).unwrap(), "keep", "run {run}"); + assert!(!ws.join("notes/.git").exists()); + assert!(!ws.join("gone").exists(), "a failed clone writes nothing at its final path"); + assert_eq!(fs::read_to_string(ws.join("empty/README")).unwrap(), "hello"); + let want = if run == 0 { "empty\tcloning\nempty\tcloned\n" } else { "empty\texists\n" }; + assert!(status.contains(want), "{status}"); + } +} + +#[test] +fn clone_repos_refuses_the_scratch_folder_name() { + let tmp = tempfile::tempdir().unwrap(); + let ws = tmp.path().join("workspace"); + fs::create_dir_all(&ws).unwrap(); + let remote = bare_remote(tmp.path(), "proj"); + let (log, status) = clone_into(&ws, &tmp.path().join("s"), &repos_json(&remote, &[".triple-c-clone"])); + assert!(log.contains("bad folder '.triple-c-clone'"), "{log}"); + assert_eq!(status, ""); +} + /// A stand-in `ssh` that records how it was called and fails. fn fake_ssh(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf) { let log = dir.join("ssh-calls"); @@ -488,6 +631,8 @@ fn wip_push_with_clone_dir(ws: &Path, args: &[&str], clone_dir: &Path) -> Output .args(args) .env("TRIPLEC_WORKSPACE_ROOT", ws) .env("TRIPLEC_CLONE_STATUS_DIR", clone_dir) + .env("TRIPLEC_RUN_ID_FILE", tmp.join("no-run-id")) + .env("TRIPLEC_WIP_LAST_DIR", tmp.join("no-wip-last")) .env("GIT_CONFIG_NOSYSTEM", "1") .env("HOME", tmp) .output() @@ -536,7 +681,10 @@ fn wip_push_pushes_the_whole_tree_and_leaves_the_repo_as_it_was() { assert_eq!(refs.len(), 1, "{refs:?}"); let name = refs[0].trim_start_matches("refs/heads/triple-c/wip/"); assert!( - name.len() == 15 && name.as_bytes()[8] == b'-' && name.chars().filter(|c| c.is_ascii_digit()).count() == 14, + name.len() == 20 + && name.as_bytes()[8] == b'-' + && name[..15].chars().filter(|c| c.is_ascii_digit()).count() == 14 + && name.ends_with("-proj"), "{name}" ); let r = &refs[0]; @@ -634,6 +782,25 @@ fn wip_push_covers_dot_folders() { assert_eq!(wip_refs(&remote).len(), 1); } +#[test] +fn wip_push_ignores_the_clone_scratch_folder() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, _repo, remote) = workspace_with_clone(tmp.path()); + // A dirty clone left in scratch (and scratch itself made a repository): + // neither is the workspace's own. + let scratch = ws.join(".triple-c-clone"); + fs::create_dir_all(&scratch).unwrap(); + git(&scratch, &["clone", "-q", remote.to_str().unwrap(), "half"]); + fs::write(scratch.join("half/y"), "y").unwrap(); + git(&scratch, &["init", "-q"]); + let out = wip_push(&ws, &["--dry-run"]); + let dry = String::from_utf8_lossy(&out.stdout).to_string(); + assert!(!dry.contains("triple-c-clone") && !dry.contains("half"), "{dry}"); + let out = wip_push(&ws, &[]); + assert!(out.status.success(), "{}", text(&out)); + assert!(wip_refs(&remote).is_empty()); +} + #[test] fn wip_push_keeps_the_repos_ssh_command_and_adds_batch_mode() { let tmp = tempfile::tempdir().unwrap(); @@ -1063,7 +1230,7 @@ fn idle_watch_goes_back_to_watching_when_someone_comes_back_during_the_push() { #[test] fn idle_watch_keeps_a_stop_guard_marker_already_recorded() { - for marker in ["pushed", "discard"] { + for marker in ["pushed", "discard", "lifetime"] { let w = Watch::new(); fs::write(w.tmp.path().join("reason"), format!("{marker}\n")).unwrap(); let (url, mut agent) = fake_agent(w.tmp.path(), OLD_ACTIVITY); @@ -1111,6 +1278,14 @@ fn aws_stop_pushes_on_sigterm_once_and_leaves_an_idle_stop_to_the_watcher() { assert!(!log.exists(), "no second push after the watcher's"); assert!(text(&out).contains("entrypoint: stopping (idle)"), "{}", text(&out)); assert!(text(&out).contains("status=75"), "{}", text(&out)); + + // A lifetime-cap stop: the watcher already tried its push; exit 76. + fs::write(&reason, "lifetime\n").unwrap(); + let out = bash(&idle_script, &[], &[("TRIPLEC_HOST", "aws"), ("TRIPLEC_WIP_PUSH", "1")], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert!(!log.exists(), "no second push after the watcher's"); + assert!(text(&out).contains("entrypoint: stopping (lifetime)"), "{}", text(&out)); + assert!(text(&out).contains("status=76"), "{}", text(&out)); fs::remove_file(&reason).unwrap(); let out = bash(&script, &[], &[("TRIPLEC_HOST", "aws"), ("TRIPLEC_WIP_PUSH", "0")], &[]); @@ -1153,9 +1328,17 @@ fn the_idle_exit_status_is_the_one_the_app_reads() { .contains(&format!("triplec_idle_exit={}\n", crate::aws::tasks::IDLE_EXIT_CODE)), "entrypoint.sh and aws::tasks::IDLE_EXIT_CODE disagree" ); + assert!( + block(ENTRYPOINT, "aws_stop") + .contains(&format!("triplec_lifetime_exit={}\n", crate::aws::tasks::LIFETIME_EXIT_CODE)), + "entrypoint.sh and aws::tasks::LIFETIME_EXIT_CODE disagree" + ); assert!(ENTRYPOINT.contains("exit \"${triplec_exit_status:-0}\""), "stop_keepalive exits with it"); // The watcher gets the WIP setting through its scrubbed environment. assert!(block(ENTRYPOINT, "aws_stop").contains("TRIPLEC_WIP_PUSH=\"${TRIPLEC_WIP_PUSH:-0}\"")); + assert!(block(ENTRYPOINT, "aws_stop") + .contains("TRIPLEC_MAX_LIFETIME_MINUTES=\"${TRIPLEC_MAX_LIFETIME_MINUTES:-}\"")); + assert!(IDLE_WATCH.contains("printf 'lifetime\\n' > \"$reason_file\"")); } #[test] @@ -1165,7 +1348,7 @@ fn start_clone_repos_marks_done_however_the_clone_ends() { // clone_repos replaced by one that fails half-way. let script = format!( "{}\nclone_repos() {{ exit 3; }}\nstart_clone_repos '[x]' \"$1\"\nwait\n", - aws_blocks(&["aws_env", "aws_repos"]) + aws_run_blocks(tmp.path(), &["aws_env", "aws_run", "aws_repos"]) ); let out = bash(&script, &[&status], &[], &[]); assert!(out.status.success(), "{}", text(&out)); @@ -1176,18 +1359,22 @@ fn start_clone_repos_marks_done_however_the_clone_ends() { fn docker_mode_never_reaches_the_aws_blocks() { // Every new step sits behind TRIPLEC_HOST=aws; the scripts are only // started from those branches. - for name in ["aws_env", "aws_home", "aws_repos", "aws_stop"] { - let b = block(ENTRYPOINT, name); + for name in ["aws_env", "aws_run", "aws_home", "aws_repos", "aws_stop"] { + let b = eblock(name); assert!(b.contains("aws"), "{name}"); } - let outside: String = { - let mut s = ENTRYPOINT.to_string(); - for name in ["aws_env", "aws_home", "aws_repos", "aws_stop"] { - s = s.replace(block(ENTRYPOINT, name), ""); + let outside = |text: &str, names: &[&str]| { + let mut s = text.to_string(); + for name in names { + s = s.replace(block(text, name), ""); } s }; - let lines: Vec<&str> = outside.lines().collect(); + let outside_ep = outside(ENTRYPOINT, &["aws_env", "aws_run", "aws_stop"]); + // The library is sourced by Docker containers too: outside its aws + // blocks, every aws step is guarded the same way. + let outside_lib = outside(LIB, &["aws_lib", "aws_home", "aws_repos"]); + let lines: Vec<&str> = outside_ep.lines().chain(outside_lib.lines()).collect(); let calls = [ "triple-c-wip-push", "triple-c-idle-watch", @@ -1196,6 +1383,12 @@ fn docker_mode_never_reaches_the_aws_blocks() { "aws_hybrid_ssh_dir", "aws_before_stop", "start_idle_watch", + "aws_efs_workspace_check", + "aws_prepare_run", + "aws_run_setup", + "triple-c-workspace-status", + "triple-c-apply-connect", + "aws_wait_connect", ]; let guarded = |s: &str| s.contains("\"$triplec_aws\" = 1"); let mut seen = 0; @@ -1211,7 +1404,11 @@ fn docker_mode_never_reaches_the_aws_blocks() { "unguarded call outside the aws blocks: {line}" ); } - assert_eq!(seen, 5, "the call sites: Hybrid link, Hybrid ~/.ssh, clone, idle watch, stop"); + assert_eq!( + seen, 7, + "the call sites: run record + setup file, Hybrid/EFS link, EFS /workspace check, Hybrid ~/.ssh \ + (in merge_host_ssh), clone (+ setup), idle watch, stop" + ); // Clones start in the background *after* the agent: the app gives a // starting task's agent only seconds to answer. let pos = |needle: &str| { @@ -1228,9 +1425,1244 @@ fn docker_mode_never_reaches_the_aws_blocks() { assert!(trap < pos("start_clone_repos"), "the trap must precede the clone"); assert!(trap < pos("start_idle_watch"), "the trap must precede the idle watcher"); assert!(pos("stop_keepalive()") < trap); - assert!(block(ENTRYPOINT, "aws_repos").contains(") &"), "start_clone_repos backgrounds the clone"); + assert!(eblock("aws_repos").contains(") &"), "start_clone_repos backgrounds the clone"); // And the snapshot-sensitive variables are gone before the agent's // environment snapshot is taken. assert!(ENTRYPOINT.find("unset TRIPLEC_FILES").unwrap() < ENTRYPOINT.find("# >>> agent_token").unwrap()); assert!(ENTRYPOINT.find("unset TRIPLEC_REPOS").unwrap() < ENTRYPOINT.find("# >>> agent_token").unwrap()); + assert!( + ENTRYPOINT.find("unset TRIPLEC_SETUP_SCRIPT").unwrap() < ENTRYPOINT.find("# >>> agent_token").unwrap() + ); + // The run record is made after the agent-token block (its children must + // not inherit TRIPLEC_AGENT_TOKEN) and before anything that can push. + let prepare = ENTRYPOINT.find("then aws_prepare_run; fi").expect("aws_prepare_run call"); + assert!(prepare > ENTRYPOINT.find("# <<< agent_token").unwrap()); + assert!(prepare < ENTRYPOINT.find("trap stop_keepalive TERM INT HUP").unwrap()); + assert!(prepare < ENTRYPOINT.find("\nstart_agent\n").unwrap()); + // The setup runs in the clone's background chain, never in the agent's way. + assert!(eblock("aws_repos").contains("aws_run_setup")); +} + +// ------------------------------------------- run record and setup script + +/// The named blocks with the run and setup dirs moved into `tmp` (`run`, +/// `setup`) and the container user switched off. +fn aws_run_blocks(tmp: &Path, names: &[&str]) -> String { + aws_blocks(names) + .replace( + "triplec_run_dir=/run/triple-c\n", + &format!("triplec_run_dir='{}'\n", tmp.join("run").display()), + ) + .replace( + "triplec_setup_dir=/run/triple-c-setup\n", + &format!("triplec_setup_dir='{}'\n", tmp.join("setup").display()), + ) +} + +/// A one-shot fake ECS task metadata endpoint answering `/task` with `body`. +fn fake_metadata(body: &str) -> (String, std::process::Child) { + let server = r#" +import http.server, sys, socketserver +body = sys.argv[1].encode() +class H(http.server.BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(200 if self.path == "/v4/x/task" else 404) + self.end_headers() + if self.path == "/v4/x/task": self.wfile.write(body) + def log_message(self, *a): pass +s = socketserver.TCPServer(("127.0.0.1", 0), H) +print(s.server_address[1], flush=True) +s.serve_forever() +"#; + let mut child = Command::new("python3") + .arg("-I") + .arg("-c") + .arg(server) + .arg(body) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let mut line = String::new(); + use std::io::BufRead; + std::io::BufReader::new(child.stdout.take().unwrap()).read_line(&mut line).unwrap(); + (format!("http://127.0.0.1:{}/v4/x", line.trim()), child) +} + +fn is_run_id(s: &str, suffix: &str) -> bool { + let b = s.as_bytes(); + s.len() == 16 + suffix.len() + && b[8] == b'-' + && b[15] == b'-' + && s[..8].chars().chain(s[9..15].chars()).all(|c| c.is_ascii_digit()) + && &s[16..] == suffix +} + +#[test] +fn aws_prepare_run_records_the_run_and_writes_the_setup_script() { + let tmp = tempfile::tempdir().unwrap(); + let script = format!( + "{}\ntriplec_setup_script=\"$SETUP\"\naws_prepare_run\n", + aws_run_blocks(tmp.path(), &["aws_env", "aws_run"]) + ); + let before = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + let out = bash(&script, &[], &[("SETUP", "echo hi\n")], &["ECS_CONTAINER_METADATA_URI_V4", "TRIPLEC_HOST"]); + assert!(out.status.success(), "{}", text(&out)); + let run = tmp.path().join("run"); + let setup = tmp.path().join("setup"); + let id = fs::read_to_string(run.join("run-id")).unwrap(); + assert!(is_run_id(id.trim_end(), "local"), "{id:?}"); + let epoch: u64 = fs::read_to_string(run.join("start-epoch")).unwrap().trim().parse().unwrap(); + assert!(epoch >= before && epoch <= before + 5); + assert_eq!(mode(&run), 0o711, "claude may read the run id, not list the dir"); + assert_eq!(mode(&run.join("run-id")), 0o644); + assert_eq!(mode(&run.join("wip-last")), 0o700); + assert_eq!(mode(&setup), 0o755); + assert_eq!(fs::read_to_string(setup.join("script")).unwrap(), "echo hi\n"); + assert_eq!(mode(&setup.join("script")), 0o644); + assert_eq!(fs::read_to_string(setup.join("status")).unwrap(), "running\n"); + assert_eq!(fs::read_to_string(setup.join("log")).unwrap(), ""); + + // No script: nothing for the setup to run, no status (state `none`). + let out = bash(&script, &[], &[("SETUP", "")], &["ECS_CONTAINER_METADATA_URI_V4"]); + assert!(out.status.success(), "{}", text(&out)); + assert!(setup.is_dir() && !setup.join("script").exists() && !setup.join("status").exists()); + + // On ECS the run id carries the task id's first 8 characters. + let (url, mut meta) = fake_metadata( + r#"{"TaskARN":"arn:aws:ecs:eu-west-1:123456789012:task/triple-c/0123abcd4567ef890123abcd4567ef89"}"#, + ); + let out = bash(&script, &[], &[("SETUP", ""), ("ECS_CONTAINER_METADATA_URI_V4", &url)], &[]); + meta.kill().ok(); + assert!(out.status.success(), "{}", text(&out)); + let id = fs::read_to_string(run.join("run-id")).unwrap(); + assert!(is_run_id(id.trim_end(), "0123abcd"), "{id:?}"); + // An answer that is not a task id, or none at all, falls back to `local`. + let (bad_url, mut bad_meta) = fake_metadata(r#"{"TaskARN":"arn:aws:ecs:x:1:task/c/a-b"}"#); + for uri in [bad_url.as_str(), "http://127.0.0.1:9/v4"] { + let out = bash(&script, &[], &[("SETUP", ""), ("ECS_CONTAINER_METADATA_URI_V4", uri)], &[]); + assert!(out.status.success(), "{}", text(&out)); + let id = fs::read_to_string(run.join("run-id")).unwrap(); + assert!(is_run_id(id.trim_end(), "local"), "{uri}: {id:?}"); + } + bad_meta.kill().ok(); +} + +/// Runs `start_clone_repos` with `setup_script` (and a clone that takes a +/// moment), as the entrypoint would; `_triplec_as_user` records its argv. +fn run_setup(tmp: &Path, setup_script: &str, timeout: &str) -> Output { + let blocks = aws_run_blocks(tmp, &["aws_env", "aws_run", "aws_repos"]) + .replace("triplec_setup_timeout=1800\n", &format!("triplec_setup_timeout={timeout}\n")); + let script = format!( + "{blocks}\n\ + _triplec_as_user() {{ printf '%s\\n' \"$*\" >> \"$CALLS\"; \"$@\"; }}\n\ + clone_repos() {{ sleep 1; echo cloned > \"$3/marker\"; }}\n\ + triplec_setup_script=\"$SETUP\"\n\ + aws_prepare_run\n\ + start_clone_repos '[]' \"$STATUS\"\n\ + wait\n" + ); + bash( + &script, + &[], + &[ + ("SETUP", setup_script), + ("CALLS", tmp.join("calls").to_str().unwrap()), + ("STATUS", tmp.join("clone").to_str().unwrap()), + ], + &["ECS_CONTAINER_METADATA_URI_V4"], + ) +} + +#[test] +fn the_setup_script_runs_after_the_clone_as_the_user_with_no_stdin() { + let tmp = tempfile::tempdir().unwrap(); + let clone = tmp.path().join("clone"); + let body = format!( + "echo started\nreadlink /proc/self/fd/0\n\ + if [ -e '{c}/done' ] && [ -e '{c}/marker' ]; then echo clone-was-done; fi\n", + c = clone.display() + ); + let out = run_setup(tmp.path(), &body, "1800"); + assert!(out.status.success(), "{}", text(&out)); + let setup = tmp.path().join("setup"); + let log = fs::read_to_string(setup.join("log")).unwrap(); + assert_eq!(log, "started\n/dev/null\nclone-was-done\n"); + assert_eq!(fs::read_to_string(setup.join("status")).unwrap(), "ok\n"); + let calls = fs::read_to_string(tmp.path().join("calls")).unwrap(); + assert_eq!( + calls, + format!("timeout -k 10 1800 bash -e {}/script\n", setup.display()), + "as the user, bounded, under bash -e" + ); + assert!(text(&out).contains("entrypoint: setup script ok"), "{}", text(&out)); +} + +#[test] +fn the_setup_script_fails_under_bash_e_and_a_hang_is_killed_as_failed_124() { + let tmp = tempfile::tempdir().unwrap(); + let out = run_setup(tmp.path(), "echo one\nfalse\necho never\n", "1800"); + assert!(out.status.success(), "a failed setup never fails the start: {}", text(&out)); + let setup = tmp.path().join("setup"); + assert_eq!(fs::read_to_string(setup.join("status")).unwrap(), "failed 1\n"); + assert_eq!(fs::read_to_string(setup.join("log")).unwrap(), "one\n"); + + let tmp = tempfile::tempdir().unwrap(); + let started = std::time::Instant::now(); + let out = run_setup(tmp.path(), "echo waiting\nsleep 60\n", "1"); + assert!(out.status.success(), "{}", text(&out)); + assert!(started.elapsed() < std::time::Duration::from_secs(20), "the hang was killed"); + let setup = tmp.path().join("setup"); + assert_eq!(fs::read_to_string(setup.join("status")).unwrap(), "failed 124\n"); +} + +#[test] +fn no_setup_script_means_no_setup_run() { + let tmp = tempfile::tempdir().unwrap(); + let out = run_setup(tmp.path(), "", "1800"); + assert!(out.status.success(), "{}", text(&out)); + assert!(!tmp.path().join("calls").exists(), "nothing ran as the user"); + assert!(!tmp.path().join("setup/status").exists()); + // The clone status is still made, and ends `done`, with no repos at all. + assert!(tmp.path().join("clone/done").exists()); +} + +#[test] +fn idle_watch_check_counts_a_running_setup_as_busy() { + let w = Watch::new(); + let (url, mut agent) = fake_agent(w.tmp.path(), OLD_ACTIVITY); + let setup = w.tmp.path().join("setup"); + fs::create_dir_all(&setup).unwrap(); + fs::write(setup.join("status"), "running\n").unwrap(); + let check = || w.cmd(&url, 0).env("TRIPLEC_SETUP_STATUS_DIR", &setup).arg("--check").output().unwrap(); + let busy = check(); + fs::write(setup.join("status"), "failed 124\n").unwrap(); + let failed = check(); + fs::write(setup.join("status"), "ok\n").unwrap(); + let ok = check(); + agent.kill().ok(); + assert_eq!(busy.status.code(), Some(1), "{}", text(&busy)); + assert_eq!(failed.status.code(), Some(0), "{}", text(&failed)); + assert_eq!(ok.status.code(), Some(0), "{}", text(&ok)); +} + +// ----------------------------------------------------------- lifetime cap + +impl Watch { + /// A watcher for the lifetime cap alone (no idle stop), its run started + /// `age_secs` ago. + fn lifetime_cmd(&self, signal_pid: u32, minutes: &str, age_secs: u64) -> Command { + let p = self.tmp.path(); + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_secs(); + fs::write(p.join("start-epoch"), format!("{}\n", now - age_secs)).unwrap(); + // An agent that never answers: the idle check alone would never stop it. + let mut c = self.cmd("http://127.0.0.1:9", signal_pid); + c.env_remove("TRIPLEC_IDLE_STOP_MINUTES") + .env("TRIPLEC_MAX_LIFETIME_MINUTES", minutes) + .env("TRIPLEC_START_EPOCH_FILE", p.join("start-epoch")); + c + } +} + +#[test] +fn lifetime_cap_pushes_then_stops_with_its_marker_even_when_the_push_fails() { + let w = Watch::new(); + w.dirty(); + fs::write(w.tmp.path().join("push_rc"), "1").unwrap(); + let mut target = fake_entrypoint(w.tmp.path()); + let mut cmd = w.lifetime_cmd(target.id(), "1", 61); + cmd.env("TRIPLEC_WIP_PUSH", "1"); + let out = run_watch_for(cmd, 20).expect("it stops at the cap"); + target.wait().unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(w.pushes(), "--reason lifetime\n", "one push, best effort"); + assert!(text(&out).contains("stopping anyway"), "{}", text(&out)); + assert_eq!(fs::read_to_string(w.tmp.path().join("got")).unwrap().trim(), "term"); + assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), "lifetime"); +} + +#[test] +fn lifetime_cap_with_the_wip_push_off_stops_without_pushing() { + let w = Watch::new(); + w.dirty(); + let mut target = fake_entrypoint(w.tmp.path()); + let mut cmd = w.lifetime_cmd(target.id(), "1", 120); + cmd.env("TRIPLEC_WIP_PUSH", "0"); + let out = run_watch_for(cmd, 20).expect("it stops at the cap"); + target.wait().unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(w.pushes(), ""); + assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), "lifetime"); +} + +#[test] +fn lifetime_cap_not_reached_keeps_the_workspace_up() { + let w = Watch::new(); + let mut target = fake_entrypoint(w.tmp.path()); + let ran = run_watch_for(w.lifetime_cmd(target.id(), "60", 30), 3); + target.kill().ok(); + target.wait().ok(); + assert!(ran.is_none(), "{:?}", ran.map(|o| text(&o))); + assert!(!w.tmp.path().join("got").exists()); + // Neither an idle stop nor a cap: nothing to watch, refused. + let none = w.cmd("http://127.0.0.1:9", target.id()).env_remove("TRIPLEC_IDLE_STOP_MINUTES").output().unwrap(); + assert_eq!(none.status.code(), Some(2), "{}", text(&none)); + let zero = w.lifetime_cmd(target.id(), "0", 30).output().unwrap(); + assert_eq!(zero.status.code(), Some(2), "0 is no cap: {}", text(&zero)); + let zeros = w.lifetime_cmd(target.id(), "00", 30).output().unwrap(); + assert_eq!(zeros.status.code(), Some(2), "00 is no cap either: {}", text(&zeros)); +} + +#[test] +fn lifetime_cap_leaves_a_stop_guard_decision_alone() { + for marker in ["pushed", "discard"] { + let w = Watch::new(); + w.dirty(); + fs::write(w.tmp.path().join("reason"), format!("{marker}\n")).unwrap(); + let mut target = fake_entrypoint(w.tmp.path()); + let mut cmd = w.lifetime_cmd(target.id(), "1", 120); + cmd.env("TRIPLEC_WIP_PUSH", "1"); + let out = run_watch_for(cmd, 20).expect("it signals"); + target.wait().unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(w.pushes(), "", "{marker}: the app already decided"); + assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), marker); + } +} + +// ------------------------------------------------------- WIP branch per run + +fn wip_push_in_run(ws: &Path, run_id: Option<&str>) -> Output { + let tmp = ws.parent().unwrap(); + let run = tmp.join("run"); + fs::create_dir_all(run.join("wip-last")).unwrap(); + match run_id { + Some(id) => fs::write(run.join("run-id"), format!("{id}\n")).unwrap(), + None => { + let _ = fs::remove_file(run.join("run-id")); + } + } + let script = write_script(tmp, "triple-c-wip-push", WIP_PUSH); + Command::new("bash") + .arg(script) + .args(["--reason", "lifetime"]) + .env("TRIPLEC_WORKSPACE_ROOT", ws) + .env("TRIPLEC_CLONE_STATUS_DIR", tmp.join("no-clone-status")) + .env("TRIPLEC_RUN_ID_FILE", run.join("run-id")) + .env("TRIPLEC_WIP_LAST_DIR", run.join("wip-last")) + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("HOME", tmp) + .output() + .unwrap() +} + +#[test] +fn wip_pushes_in_one_run_update_one_branch_and_skip_an_unchanged_tree() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, repo, remote) = workspace_with_clone(tmp.path()); + let run_id = "20261115-093000-0123abcd"; + fs::write(repo.join("a.txt"), "one").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let branch = format!("refs/heads/triple-c/wip/{run_id}-proj"); + assert_eq!(wip_refs(&remote), [branch.clone()]); + let first = git(&remote, &["rev-parse", &branch]); + assert_eq!(git(&remote, &["show", &format!("{branch}:a.txt")]), "one"); + let last = tmp.path().join("run/wip-last/proj"); + assert_eq!( + fs::read_to_string(&last).unwrap(), + format!("{} origin\n", git(&remote, &["rev-parse", &format!("{branch}^{{tree}}")])) + ); + + // Nothing changed: skipped, the branch stays where it was. + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + assert!(text(&out).contains("unchanged since the last push"), "{}", text(&out)); + assert_eq!(git(&remote, &["rev-parse", &branch]), first); + + // A change: the same branch moves (forced — the WIP commit is not a + // descendant of the last one), still one branch for the run. + fs::write(repo.join("a.txt"), "two").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(wip_refs(&remote), [branch.clone()]); + assert_ne!(git(&remote, &["rev-parse", &branch]), first); + assert_eq!(git(&remote, &["show", &format!("{branch}:a.txt")]), "two"); + assert_eq!(git(&remote, &["log", "-1", "--format=%s", &branch]).contains("(lifetime)"), true); + + // A failed push records nothing, so the next one tries again. + fs::write(repo.join("a.txt"), "three").unwrap(); + let before = fs::read_to_string(&last).unwrap(); + let saved = tmp.path().join("origin.git.away"); + fs::rename(&remote, &saved).unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(!out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(&last).unwrap(), before); + fs::rename(&saved, &remote).unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(git(&remote, &["show", &format!("{branch}:a.txt")]), "three"); +} + +#[test] +fn wip_push_without_a_usable_run_id_keeps_the_per_push_stamp() { + for run_id in [None, Some("../../evil"), Some("not a run id")] { + let tmp = tempfile::tempdir().unwrap(); + let (ws, repo, remote) = workspace_with_clone(tmp.path()); + fs::write(repo.join("a.txt"), "one").unwrap(); + let out = wip_push_in_run(&ws, run_id); + assert!(out.status.success(), "{}", text(&out)); + let refs = wip_refs(&remote); + assert_eq!(refs.len(), 1, "{refs:?}"); + let name = refs[0].trim_start_matches("refs/heads/triple-c/wip/"); + assert!(name.len() == 20 && name.as_bytes()[8] == b'-' && name.ends_with("-proj"), "{run_id:?}: {name}"); + } +} + +// ------------------------------------------------------- workspace status + +fn workspace_status(clone: &Path, setup: &Path) -> serde_json::Value { + let tmp = clone.parent().unwrap(); + let script = write_script(tmp, "triple-c-workspace-status", WORKSPACE_STATUS); + let out = Command::new("python3") + .arg("-I") + .arg(script) + .env("TRIPLEC_CLONE_STATUS_DIR", clone) + .env("TRIPLEC_SETUP_STATUS_DIR", setup) + .output() + .unwrap(); + assert!(out.status.success(), "{}", text(&out)); + let stdout = String::from_utf8(out.stdout).unwrap(); + assert_eq!(stdout.lines().count(), 1, "one JSON object on one line: {stdout}"); + serde_json::from_str(&stdout).unwrap() +} + +#[test] +fn workspace_status_reports_clone_and_setup_and_survives_missing_files() { + let tmp = tempfile::tempdir().unwrap(); + let clone = tmp.path().join("clone"); + let setup = tmp.path().join("setup"); + // Nothing yet: the clone has not started, no setup. + assert_eq!( + workspace_status(&clone, &setup), + serde_json::json!({"clone": {"done": false, "repos": []}, + "setup": {"state": "none", "code": null, "tail": []}}) + ); + + fs::create_dir_all(&clone).unwrap(); + fs::write(clone.join("repos"), "api\tcloning\napi\tcloned\nweb\tcloning\n").unwrap(); + fs::create_dir_all(&setup).unwrap(); + fs::write(setup.join("status"), "running\n").unwrap(); + let v = workspace_status(&clone, &setup); + assert_eq!( + v["clone"], + serde_json::json!({"done": false, "repos": [ + {"folder": "api", "state": "cloned"}, {"folder": "web", "state": "cloning"}]}) + ); + assert_eq!(v["setup"], serde_json::json!({"state": "running", "code": null, "tail": []})); + + fs::write(clone.join("repos"), "api\tcloning\napi\tcloned\nweb\tcloning\nweb\tfailed\n").unwrap(); + fs::write(clone.join("done"), "").unwrap(); + let lines: String = (1..=25).map(|i| format!("line {i}\n")).collect(); + fs::write(setup.join("log"), format!("{lines}partial \u{e9}\u{ff}")).unwrap(); + fs::write(setup.join("status"), "ok\n").unwrap(); + let v = workspace_status(&clone, &setup); + assert_eq!(v["clone"]["done"], true); + assert_eq!(v["clone"]["repos"][1], serde_json::json!({"folder": "web", "state": "failed"})); + assert_eq!(v["setup"]["state"], "ok"); + assert_eq!(v["setup"]["code"], 0); + let tail: Vec = + v["setup"]["tail"].as_array().unwrap().iter().map(|l| l.as_str().unwrap().to_string()).collect(); + assert_eq!(tail.len(), 20); + assert_eq!(tail[0], "line 7"); + assert!(tail[19].starts_with("partial \u{e9}"), "{:?}", tail[19]); + + fs::write(setup.join("status"), "failed 124\n").unwrap(); + let v = workspace_status(&clone, &setup); + assert_eq!((v["setup"]["state"].as_str(), v["setup"]["code"].as_i64()), (Some("failed"), Some(124))); + // Garbled status: a failure with no code, never a crash. + fs::write(setup.join("status"), "what\n").unwrap(); + let v = workspace_status(&clone, &setup); + assert_eq!(v["setup"], serde_json::json!({"state": "failed", "code": null, "tail": v["setup"]["tail"]})); + // An unreadable log is an empty tail. + fs::remove_file(setup.join("log")).unwrap(); + fs::create_dir(setup.join("log")).unwrap(); + assert_eq!(workspace_status(&clone, &setup)["setup"]["tail"], serde_json::json!([])); +} + +#[test] +fn lifetime_cap_reads_leading_zeros_as_decimal() { + // `08` is 8 minutes, not a bad octal number. + let w = Watch::new(); + let mut target = fake_entrypoint(w.tmp.path()); + let out = run_watch_for(w.lifetime_cmd(target.id(), "08", 8 * 60 + 1), 20).expect("it stops at 8 minutes"); + target.wait().unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(w.tmp.path().join("reason")).unwrap().trim(), "lifetime"); + let w = Watch::new(); + let mut target = fake_entrypoint(w.tmp.path()); + let ran = run_watch_for(w.lifetime_cmd(target.id(), "08", 7 * 60), 3); + target.kill().ok(); + target.wait().ok(); + assert!(ran.is_none(), "7 of 8 minutes: {:?}", ran.map(|o| text(&o))); +} + +#[test] +fn a_setup_chain_that_dies_early_records_failed_so_the_idle_stop_is_not_blocked() { + // The chain ends abnormally while the status still says `running`. + let tmp = tempfile::tempdir().unwrap(); + let blocks = aws_run_blocks(tmp.path(), &["aws_env", "aws_run", "aws_repos"]); + let script = format!( + "{blocks}\n\ + aws_run_setup() {{ exit 9; }}\n\ + triplec_setup_script='echo hi'\n\ + aws_prepare_run\n\ + start_clone_repos '[]' \"$STATUS\"\n\ + wait\n" + ); + let out = bash(&script, &[], &[("STATUS", tmp.path().join("clone").to_str().unwrap())], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "failed\n"); + + // Killed (TERM) while the clone is still running: `done` and `failed`. + let tmp = tempfile::tempdir().unwrap(); + let blocks = aws_run_blocks(tmp.path(), &["aws_env", "aws_run", "aws_repos"]); + let pid = tmp.path().join("inner.pid"); + let script = format!( + "{blocks}\n\ + clone_repos() {{ sleep 30 >/dev/null 2>&1 & s=$!; echo \"$BASHPID $s\" > '{p}'; wait $s; }}\n\ + triplec_setup_script='echo hi'\n\ + aws_prepare_run\n\ + start_clone_repos '[]' \"$STATUS\"\n\ + chain=$!\n\ + while [ ! -s '{p}' ]; do sleep 0.1; done\n\ + kill -TERM \"$chain\" $(cat '{p}')\n\ + wait\n", + p = pid.display() + ); + let started = std::time::Instant::now(); + let out = bash(&script, &[], &[("STATUS", tmp.path().join("clone").to_str().unwrap())], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert!(started.elapsed() < std::time::Duration::from_secs(20)); + assert!(tmp.path().join("clone/done").exists()); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "failed\n"); + // A finished setup's status is left alone by the trap. + let tmp = tempfile::tempdir().unwrap(); + let out = run_setup(tmp.path(), "true\n", "1800"); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(tmp.path().join("setup/status")).unwrap(), "ok\n"); +} + +#[test] +fn each_folder_in_a_run_has_its_own_wip_branch_even_on_one_remote() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, api, remote) = workspace_with_clone(tmp.path()); + // A second clone of the same bare remote, under a folder name git refs + // cannot carry as is. + git(&ws, &["clone", "-q", remote.to_str().unwrap(), "we b@x"]); + let web = ws.join("we b@x"); + git(&web, &["config", "user.name", "Dev"]); + git(&web, &["config", "user.email", "dev@example.invalid"]); + let run_id = "20261115-093000-0123abcd"; + fs::write(api.join("a.txt"), "api-1").unwrap(); + fs::write(web.join("a.txt"), "web-1").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let api_ref = format!("refs/heads/triple-c/wip/{run_id}-proj"); + // Sanitised, so with the first 8 hex of sha256("we b@x"). + let web_ref = format!("refs/heads/triple-c/wip/{run_id}-we_b_x-7d2e374f"); + let mut refs = wip_refs(&remote); + refs.sort(); + assert_eq!(refs, [api_ref.clone(), web_ref.clone()]); + assert_eq!(git(&remote, &["show", &format!("{api_ref}:a.txt")]), "api-1"); + assert_eq!(git(&remote, &["show", &format!("{web_ref}:a.txt")]), "web-1"); + let web_first = git(&remote, &["rev-parse", &web_ref]); + + // A second push changes only api: its branch moves, web's is skipped. + fs::write(api.join("a.txt"), "api-2").unwrap(); + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + assert!(text(&out).contains("we b@x: unchanged since the last push"), "{}", text(&out)); + assert_eq!(git(&remote, &["show", &format!("{api_ref}:a.txt")]), "api-2"); + assert_eq!(git(&remote, &["rev-parse", &web_ref]), web_first); + assert_eq!(wip_refs(&remote).len(), 2); +} + +#[test] +fn a_folder_name_no_ref_can_carry_falls_back_to_a_hash() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, _, remote) = workspace_with_clone(tmp.path()); + git(&ws, &["clone", "-q", remote.to_str().unwrap(), "a..b.lock"]); + let repo = ws.join("a..b.lock"); + git(&repo, &["config", "user.name", "Dev"]); + git(&repo, &["config", "user.email", "dev@example.invalid"]); + fs::write(repo.join("x"), "x").unwrap(); + let run_id = "20261115-093000-local"; + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let refs = wip_refs(&remote); + assert_eq!(refs.len(), 1, "{refs:?}"); + let suffix = refs[0].strip_prefix(&format!("refs/heads/triple-c/wip/{run_id}-")).unwrap(); + assert!(suffix.len() == 12 && suffix.chars().all(|c| c.is_ascii_hexdigit()), "{suffix}"); +} + +#[test] +fn folders_that_sanitise_to_the_same_name_get_different_wip_branches() { + let tmp = tempfile::tempdir().unwrap(); + let (ws, _, remote) = workspace_with_clone(tmp.path()); + for folder in ["a b", "a_b"] { + git(&ws, &["clone", "-q", remote.to_str().unwrap(), folder]); + let repo = ws.join(folder); + git(&repo, &["config", "user.name", "Dev"]); + git(&repo, &["config", "user.email", "dev@example.invalid"]); + fs::write(repo.join("x"), folder).unwrap(); + } + let run_id = "20261115-093000-local"; + let out = wip_push_in_run(&ws, Some(run_id)); + assert!(out.status.success(), "{}", text(&out)); + let mut refs = wip_refs(&remote); + refs.sort(); + let base = format!("refs/heads/triple-c/wip/{run_id}-"); + // Exact names keep their folder; the changed one gets a hash of the raw name. + assert!(refs.iter().any(|r| *r == format!("{base}a_b")), "{refs:?}"); + let spaced: Vec<_> = refs.iter().filter_map(|r| r.strip_prefix(&format!("{base}a_b-"))).collect(); + assert_eq!(spaced.len(), 1, "{refs:?}"); + assert!(spaced[0].len() == 8 && spaced[0].chars().all(|c| c.is_ascii_hexdigit()), "{refs:?}"); + assert_eq!(refs.len(), 2, "{refs:?}"); +} + +// ------------------------------------------------- copy-at-connect (phase 6 Q2) + +#[test] +fn sourcing_the_library_only_defines_functions() { + // Docker parity: the entrypoint sources it first thing, so it must run + // nothing — no output, no files, no environment changes. + let tmp = tempfile::tempdir().unwrap(); + let lib = tmp.path().join("lib.sh"); + fs::write(&lib, LIB).unwrap(); + let out = Command::new("env") + .args(["-i", "PATH=/usr/bin:/bin", "bash", "-c"]) + .arg(". \"$1\" && env && echo --- && declare -F | awk '{print $3}'") + .arg("t") + .arg(&lib) + .current_dir(tmp.path()) + .output() + .unwrap(); + assert!(out.status.success(), "{}", text(&out)); + assert!(out.stderr.is_empty(), "{}", text(&out)); + let stdout = String::from_utf8_lossy(&out.stdout); + let (env, funcs) = stdout.split_once("---\n").unwrap(); + assert!(!env.contains("triplec_") && !env.contains("CA_"), "nothing exported: {env}"); + for f in [ + "_triplec_as_user", + "link_persistent_home", + "aws_hybrid_ssh_dir", + "install_corporate_ca", + "sync_host_ssh", + "merge_host_ssh", + "install_git_credentials", + "clone_repos", + "aws_wait_connect", + "start_clone_repos", + ] { + assert!(funcs.lines().any(|l| l == f), "{f} missing: {funcs}"); + } + assert_eq!(fs::read_dir(tmp.path()).unwrap().count(), 1, "sourcing made no files"); +} + +#[test] +fn the_entrypoint_sources_the_library_first_and_calls_the_moved_steps_in_order() { + let path = "/usr/local/lib/triple-c/entrypoint-lib.sh"; + let source = ENTRYPOINT.find(&format!(". {path}")).expect("sources the library"); + assert!(source < ENTRYPOINT.find("# >>> aws_env").unwrap(), "before any block uses it"); + let docker = include_str!("../../../../container/Dockerfile"); + assert!(docker.contains(&format!("COPY entrypoint-lib.sh {path}"))); + assert!(docker.contains("COPY triple-c-apply-connect /usr/local/bin/triple-c-apply-connect")); + assert!(APPLY_CONNECT.contains(&format!("lib={path}\n"))); + // The steps run where the inline code ran: CA, then the SSH merge, then + // the git credential helper, all before the clone starts. + let at = |needle: &str| { + ENTRYPOINT + .lines() + .position(|l| l.trim_start() == needle) + .unwrap_or_else(|| panic!("{needle}")) + }; + let ca = at("install_corporate_ca"); + let ssh = at("merge_host_ssh /tmp/.host-ssh"); + let git = at("install_git_credentials \"$GIT_TOKEN\""); + assert!(at("link_persistent_home /home/claude \"$triplec_home_mnt\" claude:claude") < ca); + assert!(ca < ssh && ssh < git && git < at("start_clone_repos \"$triplec_repos_json\" /run/triple-c-clone")); + // Each block lives in exactly one file. + for name in ["aws_lib", "aws_home", "ca_install", "sync_host_ssh", "merge_host_ssh", "git_credentials", "aws_repos"] { + assert!(LIB.contains(&format!("# >>> {name}\n")), "{name}"); + assert!(!ENTRYPOINT.contains(&format!("# >>> {name}\n")), "{name}"); + } +} + +#[test] +fn the_git_credential_helper_is_written_as_before() { + let tmp = tempfile::tempdir().unwrap(); + let home = tmp.path().join("home"); + fs::create_dir_all(&home).unwrap(); + let script = format!( + "{}\ninstall_git_credentials \"$TOKEN\"\n", + aws_blocks(&["git_credentials"]) + .replace("/home/claude", home.to_str().unwrap()) + .replace("chown claude:claude", ": chown") + ); + let out = bash(&script, &[], &[("TOKEN", "tok-123")], &[]); + assert!(out.status.success(), "{}", text(&out)); + let cred = home.join(".git-credentials"); + assert_eq!( + fs::read_to_string(&cred).unwrap(), + "https://oauth2:tok-123@github.com\nhttps://oauth2:tok-123@gitlab.com\nhttps://oauth2:tok-123@bitbucket.org\n" + ); + assert_eq!(mode(&cred), 0o600); + let helper = Command::new("git") + .args(["config", "--file"]) + .arg(home.join(".gitconfig")) + .args(["--get", "credential.helper"]) + .output() + .unwrap(); + assert_eq!( + String::from_utf8_lossy(&helper.stdout).trim(), + format!("store --file={}", cred.display()) + ); +} + +#[test] +fn merge_host_ssh_merges_and_fixes_modes_and_refuses_a_foreign_link_on_aws() { + let tmp = tempfile::tempdir().unwrap(); + let (home, mnt) = hybrid_dirs(tmp.path()); + let src = tmp.path().join("src"); + fs::create_dir_all(&src).unwrap(); + fs::write(src.join("id_ed25519"), "KEY").unwrap(); + fs::write(src.join("id_ed25519.pub"), "PUB").unwrap(); + fs::write(src.join("config"), "Host *\n").unwrap(); + let run = |aws: &str| { + let script = format!( + "{}\ntriplec_aws={aws}\nmerge_host_ssh \"$1\"\n", + aws_blocks(&["aws_home", "sync_host_ssh", "merge_host_ssh"]) + .replace("/home/claude", home.to_str().unwrap()) + .replace("triplec_home_mnt=/mnt/triple-c-home", &format!("triplec_home_mnt='{}'", mnt.display())) + .replace("chown -R claude:claude", ": chown") + ); + bash(&script, &[&src], &[], &[]) + }; + // Docker (and AWS without a link): ~/.ssh itself. + let out = run("0"); + assert!(out.status.success(), "{}", text(&out)); + let ssh = home.join(".ssh"); + assert_eq!(fs::read_to_string(ssh.join("id_ed25519")).unwrap(), "KEY"); + assert_eq!(mode(&ssh), 0o700); + assert_eq!(mode(&ssh.join("id_ed25519")), 0o600); + assert_eq!(mode(&ssh.join("id_ed25519.pub")), 0o644); + assert_eq!(mode(&ssh.join("config")), 0o600); + + // AWS Hybrid: through the link Triple-C made, into the mount. + fs::remove_dir_all(&ssh).unwrap(); + fs::create_dir_all(mnt.join(".ssh")).unwrap(); + std::os::unix::fs::symlink(mnt.join(".ssh"), &ssh).unwrap(); + let out = run("1"); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(mnt.join(".ssh/id_ed25519")).unwrap(), "KEY"); + + // Any other link: nothing merged. + let elsewhere = tmp.path().join("elsewhere"); + fs::create_dir_all(&elsewhere).unwrap(); + fs::remove_file(&ssh).unwrap(); + std::os::unix::fs::symlink(&elsewhere, &ssh).unwrap(); + let out = run("1"); + assert!(text(&out).contains("symlink Triple-C did not make"), "{}", text(&out)); + assert_eq!(fs::read_dir(&elsewhere).unwrap().count(), 0); +} + +/// `start_clone_repos` under copy-at-connect, with `clone_repos` stubbed to +/// record when it ran. +fn connect_clone(tmp: &Path, marker: bool) -> (Output, std::time::Duration) { + let run = tmp.join("run"); + fs::create_dir_all(&run).unwrap(); + if marker { + fs::write(run.join("connected"), "").unwrap(); + } + let script = format!( + "{}\ntriplec_connect=1\n\ + clone_repos() {{ echo cloned > \"$3/marker\"; }}\n\ + aws_run_setup() {{ :; }}\n\ + start_clone_repos '[{{\"url\":\"u\",\"branch\":null,\"folder\":\"f\"}}]' \"$1\"\nwait\n", + aws_run_blocks(tmp, &["aws_env", "aws_run", "aws_repos"]) + .replace("triplec_connect_wait=300\n", "triplec_connect_wait=2\n") + ); + let started = std::time::Instant::now(); + let out = bash(&script, &[&tmp.join("status")], &[], &[]); + (out, started.elapsed()) +} + +#[test] +fn under_copy_at_connect_the_clone_waits_for_the_connect_then_goes_ahead_without() { + // Connected already: clones at once, with nothing to retry later. + let tmp = tempfile::tempdir().unwrap(); + let (out, took) = connect_clone(tmp.path(), true); + assert!(out.status.success(), "{}", text(&out)); + let status = tmp.path().join("status"); + assert!(status.join("marker").exists() && status.join("done").exists()); + assert!(!status.join("no-credentials").exists()); + assert!(took < std::time::Duration::from_secs(2), "{took:?}"); + + // Never connected: waits out the limit, clones anyway, says so. + let tmp = tempfile::tempdir().unwrap(); + let (out, took) = connect_clone(tmp.path(), false); + assert!(out.status.success(), "{}", text(&out)); + let status = tmp.path().join("status"); + assert!(status.join("marker").exists() && status.join("done").exists()); + assert!(status.join("no-credentials").exists()); + assert!(took >= std::time::Duration::from_secs(2), "{took:?}"); + assert!(text(&out).contains("going ahead without the project's credentials"), "{}", text(&out)); +} + +/// Copy-at-connect with no repositories: `start_clone_repos` with a setup +/// script (or none), the connect arriving after a second; the stubbed setup +/// records whether the connect had happened when it ran. +fn connect_setup(tmp: &Path, setup_script: &str) -> (Output, std::time::Duration) { + let script = format!( + "{} +triplec_connect=1 + triplec_setup_script=\"$SETUP\" + aws_prepare_run + aws_run_setup() {{ if [ -e \"$triplec_run_dir/connected\" ]; then echo after > \"$OUT/setup-ran\"; else echo before > \"$OUT/setup-ran\"; fi; }} + ( sleep 1; : > \"$triplec_run_dir/connected\" ) & + start_clone_repos '[]' \"$1/status\" +wait +", + aws_run_blocks(tmp, &["aws_env", "aws_run", "aws_repos"]) + .replace("triplec_connect_wait=300\n", "triplec_connect_wait=10\n") + ); + let started = std::time::Instant::now(); + let out = bash( + &script, + &[tmp], + &[("SETUP", setup_script), ("OUT", tmp.to_str().unwrap())], + &["ECS_CONTAINER_METADATA_URI_V4"], + ); + (out, started.elapsed()) +} + +#[test] +fn under_copy_at_connect_a_setup_script_waits_for_the_connect_even_with_no_repos() { + let tmp = tempfile::tempdir().unwrap(); + let (out, took) = connect_setup(tmp.path(), "echo hi\n"); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(tmp.path().join("setup-ran")).unwrap(), "after\n", "{}", text(&out)); + assert!(took >= std::time::Duration::from_secs(1), "{took:?}"); + assert!(!tmp.path().join("status/no-credentials").exists()); + + // No repositories and no setup script: nothing waits for the connect. + let tmp = tempfile::tempdir().unwrap(); + let (out, took) = connect_setup(tmp.path(), ""); + assert!(out.status.success(), "{}", text(&out)); + assert!(tmp.path().join("status/done").exists()); + assert!(took < std::time::Duration::from_secs(3), "{took:?}"); +} + +/// A workspace for `triple-c-apply-connect`: its script and library with every +/// path moved into `tmp`, the user switched off, `update-ca-certificates` +/// faked and certutil skipped. +struct Connect { + root: std::path::PathBuf, + script: std::path::PathBuf, + path_env: String, +} + +impl Connect { + fn new(tmp: &Path) -> Self { + let p = |s: &str| tmp.join(s); + for d in ["shm", "run", "home", "ws", "clone", "store", "bin", "lib"] { + fs::create_dir_all(p(d)).unwrap(); + } + let lib = LIB + .replace("triplec_run_as=claude", "triplec_run_as=") + .replace("triplec_run_dir=/run/triple-c\n", &format!("triplec_run_dir='{}'\n", p("run").display())) + .replace("\"/usr/local/share/ca-certificates\"", &format!("'{}'", p("store").display())) + .replace("\"/var/lib/triple-c/ca.stamp\"", &format!("'{}'", p("lib/ca.stamp").display())) + .replace("\"/etc/ssl/certs/ca-certificates.crt\"", &format!("'{}'", p("lib/bundle").display())) + .replace("if ! command -v certutil >/dev/null 2>&1; then", "if true; then") + .replace("/home/claude", p("home").to_str().unwrap()) + .replace("chown -R claude:claude", ": chown") + .replace("chown claude:claude", ": chown"); + fs::write(p("lib.sh"), lib).unwrap(); + fs::write(p("log"), "").unwrap(); + // The system bundle update-ca-certificates would have made. + fs::write(p("lib/bundle"), PEM).unwrap(); + let script = APPLY_CONNECT + .replace("lib=/usr/local/lib/triple-c/entrypoint-lib.sh\n", &format!("lib='{}'\n", p("lib.sh").display())) + .replace("shm=/dev/shm/triple-c\n", &format!("shm='{}'\n", p("shm").display())) + .replace("stage=/dev/shm/triple-c/connect\n", &format!("stage='{}'\n", p("shm/connect").display())) + .replace("ca_dir=/dev/shm/triple-c/connect-ca\n", &format!("ca_dir='{}'\n", p("shm/connect-ca").display())) + .replace("clone_status=/run/triple-c-clone\n", &format!("clone_status='{}'\n", p("clone").display())) + .replace("workspace=/workspace\n", &format!("workspace='{}'\n", p("ws").display())) + .replace("retry_wait=2400\n", "retry_wait=20\n") + .replace("log_to=/proc/1/fd/1\n", &format!("log_to='{}'\n", p("log").display())) + .replace("ssh_tmp_dir=/tmp\n", &format!("ssh_tmp_dir='{}'\n", tmp.display())); + let script_path = write_script(tmp, "apply-connect", &script); + write_script(&p("bin"), "update-ca-certificates", "#!/bin/sh\necho ran >> \"$(dirname \"$0\")/../update-calls\"\n"); + let path_env = format!("{}:{}", p("bin").display(), std::env::var("PATH").unwrap_or_default()); + Connect { root: tmp.to_path_buf(), script: script_path, path_env } + } + + fn run(&self, args: &[&str]) -> Output { + Command::new("bash") + .arg(&self.script) + .args(args) + .env("PATH", &self.path_env) + .env_remove("GIT_TOKEN") + .output() + .unwrap() + } + + fn p(&self, s: &str) -> std::path::PathBuf { + self.root.join(s) + } + + /// `--prepare`: this connect's nonce (its dir is `shm/connect/`). + fn prepare(&self) -> String { + let out = self.run(&["--prepare"]); + assert!(out.status.success(), "{}", text(&out)); + let nonce = String::from_utf8_lossy(&out.stdout).trim().to_string(); + assert!(nonce.len() == 16 && nonce.chars().all(|c| c.is_ascii_hexdigit()), "{nonce:?}"); + nonce + } + + /// What the app uploads for one connect: `files` (`ssh/x`, `ca/y`) and + /// `connect.env`. + fn stage(&self, nonce: &str, files: &[(&str, &str)], env: &str) { + for (k, v) in files { + fs::write(self.p(&format!("shm/connect/{nonce}/{k}")), v).unwrap(); + } + fs::write(self.p(&format!("shm/connect/{nonce}/connect.env")), env).unwrap(); + } + + /// A whole connect: prepare, stage, apply. + fn connect(&self, files: &[(&str, &str)], env: &str) -> Output { + let nonce = self.prepare(); + self.stage(&nonce, files, env); + self.run(&[&nonce]) + } + + /// Waits for the background re-clone to finish (`done` back). + fn wait_done(&self) { + for _ in 0..200 { + if self.p("clone/done").exists() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + panic!("the re-clone never finished: {}", fs::read_to_string(self.p("log")).unwrap()); + } +} + +const PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----\n"; + +#[test] +fn apply_connect_installs_the_ca_merges_ssh_writes_git_credentials_and_retries_only_failed_clones() { + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + let remote = bare_remote(tmp.path(), "remote"); + + // A connect's own staging dir; one an abandoned connect left long ago is + // cleared, a recent one (a connect in flight) is not. + fs::create_dir_all(c.p("shm/connect/0000000000000old")).unwrap(); + fs::create_dir_all(c.p("shm/connect/00000000000recent")).unwrap(); + assert!(Command::new("touch").args(["-d", "1 hour ago"]).arg(c.p("shm/connect/0000000000000old")).status().unwrap().success()); + let nonce = c.prepare(); + for d in ["shm/connect".to_string(), format!("shm/connect/{nonce}"), format!("shm/connect/{nonce}/ssh"), format!("shm/connect/{nonce}/ca")] { + assert_eq!(mode(&c.p(&d)), 0o700, "{d}"); + } + assert!(!c.p("shm/connect/0000000000000old").exists()); + assert!(c.p("shm/connect/00000000000recent").exists()); + + // What the app uploads. + let token = "ghp_secret-value"; + let env = format!("ANTHROPIC_API_KEY={}\nGIT_TOKEN={}\n", b64("sk-other"), b64(token)); + c.stage(&nonce, &[("ssh/id_ed25519", "KEY"), ("ca/corp.pem", PEM)], &env); + // The first clone is done: `ok` cloned, `bad` failed (no credentials then). + git(tmp.path(), &["clone", "-q", remote.to_str().unwrap(), c.p("ws/ok").to_str().unwrap()]); + fs::write(c.p("clone/repos"), "ok\tcloning\nok\tcloned\nbad\tcloning\nbad\tfailed\n").unwrap(); + fs::write(c.p("clone/done"), "").unwrap(); + fs::write( + c.p("run/repos.json"), + format!( + r#"[{{"url":"{r}","branch":null,"folder":"ok"}},{{"url":"{r}","branch":"dev","folder":"bad"}}]"#, + r = remote.display() + ), + ) + .unwrap(); + + let out = c.run(&[&nonce]); + let log = text(&out); + assert!(out.status.success(), "{log}"); + assert!(log.contains("credentials applied"), "{log}"); + assert!(!c.p(&format!("shm/connect/{nonce}")).exists(), "the apply removes its staging"); + assert!(!log.contains(token) && !log.contains("sk-other"), "no value is printed: {log}"); + + // CA, as the entrypoint installs it. + assert_eq!(fs::read_to_string(c.p("store/triple-c-corp.crt")).unwrap(), PEM); + assert_eq!(fs::read_to_string(c.p("update-calls")).unwrap(), "ran\n"); + // SSH merged into ~/.ssh. + assert_eq!(fs::read_to_string(c.p("home/.ssh/id_ed25519")).unwrap(), "KEY"); + assert_eq!(mode(&c.p("home/.ssh/id_ed25519")), 0o600); + // The git credential helper. + let cred = fs::read_to_string(c.p("home/.git-credentials")).unwrap(); + assert!(cred.contains(&format!("https://oauth2:{token}@github.com")), "{cred}"); + // The marker the waiting clone starts on. + assert!(c.p("run/connected").exists()); + + // Only `bad` is cloned again, in the background. + c.wait_done(); + let repos = fs::read_to_string(c.p("clone/repos")).unwrap(); + assert_eq!( + repos, + "ok\tcloning\nok\tcloned\nbad\tcloning\nbad\tfailed\nbad\tcloning\nbad\tcloned\n", + "{}", + fs::read_to_string(c.p("log")).unwrap() + ); + assert_eq!(git(&c.p("ws/bad"), &["rev-parse", "--abbrev-ref", "HEAD"]), "dev"); + let clone_log = fs::read_to_string(c.p("log")).unwrap(); + assert!(clone_log.contains("cloning again with the project's credentials: bad"), "{clone_log}"); + assert!(!clone_log.contains(token), "{clone_log}"); + + // A new connect with the same credentials: nothing failed, nothing + // re-cloned, same state, the CA not reinstalled. + let out = c.connect(&[("ssh/id_ed25519", "KEY"), ("ca/corp.pem", PEM)], &env); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(c.p("clone/repos")).unwrap(), repos); + assert!(c.p("clone/done").exists()); + assert_eq!(fs::read_to_string(c.p("home/.git-credentials")).unwrap(), cred); + assert_eq!(fs::read_to_string(c.p("home/.ssh/id_ed25519")).unwrap(), "KEY"); + assert_eq!(fs::read_to_string(c.p("update-calls")).unwrap(), "ran\n", "the CA stamp skips a reinstall"); +} + +#[test] +fn a_connect_that_takes_over_from_a_waiting_retry_does_not_lose_done() { + // Connect 1 arrives while a clone that started without credentials is + // still running: its retry waits for `done`. The clone finishes and + // connect 2 arrives before the waiter's next look: connect 2 removes + // `done` and retries at once. The waiter used to hold the retry lock + // while it waited, so connect 2's retry queued behind it and the waiter + // never saw `done` again (stalled for the whole retry_wait). + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + // A long poll, so connect 2 lands in the gap deterministically. + let script = fs::read_to_string(&c.script).unwrap().replace(" sleep 2\n", " sleep 6\n"); + fs::write(&c.script, script).unwrap(); + let remote = bare_remote(tmp.path(), "remote"); + fs::write(c.p("run/repos.json"), format!(r#"[{{"url":"{}","branch":null,"folder":"bad"}}]"#, remote.display())).unwrap(); + fs::write(c.p("clone/repos"), "bad\tcloning\nbad\tfailed\n").unwrap(); + fs::write(c.p("clone/no-credentials"), "").unwrap(); + let env = format!("GIT_TOKEN={}\n", b64("ghp_fake-fixture")); + + let out = c.connect(&[], &env); + assert!(out.status.success(), "{}", text(&out)); + std::thread::sleep(std::time::Duration::from_millis(500)); + // The first clone ends; connect 2 comes before the waiter looks again. + fs::write(c.p("clone/done"), "").unwrap(); + let started = std::time::Instant::now(); + let out = c.connect(&[], &env); + assert!(out.status.success(), "{}", text(&out)); + + // Connect 2's retry runs straight away and writes `done`. + while !c.p("clone/done").exists() { + assert!( + started.elapsed() < std::time::Duration::from_secs(5), + "`done` was lost: {}", + fs::read_to_string(c.p("log")).unwrap() + ); + std::thread::sleep(std::time::Duration::from_millis(100)); + } + // The waiter wakes, sees another retry took over, and clones nothing. + std::thread::sleep(std::time::Duration::from_secs(7)); + assert!(c.p("clone/done").exists()); + assert_eq!( + fs::read_to_string(c.p("clone/repos")).unwrap(), + "bad\tcloning\nbad\tfailed\nbad\tcloning\nbad\tcloned\n", + "{}", + fs::read_to_string(c.p("log")).unwrap() + ); + assert!(!c.p("clone/no-credentials").exists()); +} + +#[test] +fn a_failed_ca_move_keeps_the_ca_installed_before() { + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + let out = c.connect(&[("ca/corp.pem", PEM)], ""); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(c.p("shm/connect-ca/corp.pem")).unwrap(), PEM); + + // Every move of a staged `ca` dir fails: the old files stay in place and + // stay installed. + let pem2 = "-----BEGIN CERTIFICATE-----\nMIIC\n-----END CERTIFICATE-----\n"; + write_script( + &c.p("bin"), + "mv", + "#!/bin/sh\nfor a; do case \"$a\" in */ca) exit 1 ;; esac; done\nexec /usr/bin/mv \"$@\"\n", + ); + let out = c.connect(&[("ca/corp.pem", pem2)], ""); + assert!(out.status.success(), "{}", text(&out)); + assert!(text(&out).contains("keeping the ones from before"), "{}", text(&out)); + assert_eq!(fs::read_to_string(c.p("shm/connect-ca/corp.pem")).unwrap(), PEM); + assert_eq!(fs::read_to_string(c.p("store/triple-c-corp.crt")).unwrap(), PEM); + + // With the moves working again the new files are swapped in, nothing left over. + fs::remove_file(c.p("bin/mv")).unwrap(); + let out = c.connect(&[("ca/corp.pem", pem2)], ""); + assert!(out.status.success(), "{}", text(&out)); + assert_eq!(fs::read_to_string(c.p("shm/connect-ca/corp.pem")).unwrap(), pem2); + assert_eq!(fs::read_to_string(c.p("store/triple-c-corp.crt")).unwrap(), pem2); + assert!(!c.p("shm/connect-ca.new").exists() && !c.p("shm/connect-ca.old").exists()); + + // A connect with no CA removes it. + let out = c.connect(&[], ""); + assert!(out.status.success(), "{}", text(&out)); + assert!(!c.p("shm/connect-ca").exists()); + assert!(!c.p("store/triple-c-corp.crt").exists()); +} + +#[test] +fn apply_connect_with_nothing_configured_changes_nothing_and_leaves_a_waiting_clone_alone() { + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + let nonce = c.prepare(); + // The first clone is still waiting for this connect: no `done`, no + // `no-credentials`. + fs::write(c.p("run/repos.json"), "[]").unwrap(); + let out = c.run(&[&nonce]); + let log = text(&out); + assert!(out.status.success(), "{log}"); + assert!(!log.contains("warning"), "{log}"); + assert!(!c.p("home/.ssh").exists() && !c.p("home/.git-credentials").exists()); + assert!(!c.p("update-calls").exists()); + assert!(c.p("run/connected").exists()); + assert!(!c.p("clone/done").exists(), "nothing retried"); + assert_eq!(fs::read_to_string(c.p("log")).unwrap(), ""); +} + +#[test] +fn apply_connect_retries_a_clone_that_started_without_credentials_once_it_is_done() { + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + let remote = bare_remote(tmp.path(), "remote"); + let nonce = c.prepare(); + fs::write( + c.p("run/repos.json"), + format!(r#"[{{"url":"{}","branch":null,"folder":"late"}}]"#, remote.display()), + ) + .unwrap(); + // Still cloning without credentials (the wait timed out). + fs::write(c.p("clone/no-credentials"), "").unwrap(); + fs::write(c.p("clone/repos"), "late\tcloning\n").unwrap(); + let out = c.run(&[&nonce]); + assert!(out.status.success(), "{}", text(&out)); + std::thread::sleep(std::time::Duration::from_millis(500)); + assert!(!c.p("ws/late").exists(), "nothing until the running clone is done"); + // That clone ends, failed. + fs::write(c.p("clone/repos"), "late\tcloning\nlate\tfailed\n").unwrap(); + fs::write(c.p("clone/done"), "").unwrap(); + for _ in 0..200 { + if fs::read_to_string(c.p("clone/repos")).unwrap().ends_with("late\tcloned\n") && c.p("clone/done").exists() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + assert!( + fs::read_to_string(c.p("clone/repos")).unwrap().ends_with("late\tcloning\nlate\tcloned\n"), + "{}", + fs::read_to_string(c.p("log")).unwrap() + ); + assert!(c.p("ws/late/README").exists()); + assert!(!c.p("clone/no-credentials").exists()); +} + +#[test] +fn a_running_re_clone_never_holds_the_apply_lock_and_prepare_waits_for_an_apply() { + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + // A re-clone that takes a while. + let mut lib = fs::read_to_string(c.p("lib.sh")).unwrap(); + lib.push_str("\nclone_repos() { sleep 6; }\n"); + fs::write(c.p("lib.sh"), lib).unwrap(); + let nonce = c.prepare(); + fs::write(c.p("run/repos.json"), r#"[{"url":"x","branch":null,"folder":"bad"}]"#).unwrap(); + fs::write(c.p("clone/repos"), "bad\tcloning\nbad\tfailed\n").unwrap(); + fs::write(c.p("clone/done"), "").unwrap(); + assert!(c.run(&[&nonce]).status.success()); + assert!(!c.p("clone/done").exists(), "the re-clone is running"); + // The next connect goes straight through. + let started = std::time::Instant::now(); + let out = c.connect(&[], ""); + assert!(out.status.success(), "{}", text(&out)); + assert!(!text(&out).contains("another apply"), "{}", text(&out)); + assert!(started.elapsed() < std::time::Duration::from_secs(4), "{:?}", started.elapsed()); + c.wait_done(); + + // An apply in progress (the lock held) holds a prepare back. + let lock = c.p("shm/apply-connect.lock"); + let mut holder = Command::new("flock").arg(&lock).args(["sleep", "2"]).spawn().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(300)); + let started = std::time::Instant::now(); + assert!(c.run(&["--prepare"]).status.success()); + assert!(started.elapsed() >= std::time::Duration::from_millis(1200), "{:?}", started.elapsed()); + holder.wait().unwrap(); +} + +#[test] +fn under_copy_at_connect_hybrid_keeps_ssh_off_efs() { + let tmp = tempfile::tempdir().unwrap(); + let (home, mnt) = hybrid_dirs(tmp.path()); + fs::create_dir_all(home.join(".ssh")).unwrap(); + fs::create_dir_all(home.join(".claude")).unwrap(); + let src = tmp.path().join("src"); + fs::create_dir_all(&src).unwrap(); + fs::write(src.join("id_ed25519"), "KEY").unwrap(); + let script = format!( + "{}\ntriplec_aws=1\ntriplec_connect=1\nlink_persistent_home \"$1\" \"$2\" \"\"\nmerge_host_ssh \"$3\"\n", + aws_blocks(&["aws_home", "sync_host_ssh", "merge_host_ssh"]) + .replace("/home/claude", home.to_str().unwrap()) + .replace("triplec_home_mnt=/mnt/triple-c-home", &format!("triplec_home_mnt='{}'", mnt.display())) + .replace("chown -R claude:claude", ": chown") + ); + let out = bash(&script, &[&home, &mnt, &src], &[], &[]); + assert!(out.status.success(), "{}", text(&out)); + assert!(text(&out).contains("~/.ssh does not"), "{}", text(&out)); + assert!(fs::symlink_metadata(home.join(".claude")).unwrap().file_type().is_symlink()); + let ssh = fs::symlink_metadata(home.join(".ssh")).unwrap(); + assert!(ssh.is_dir() && !ssh.file_type().is_symlink(), "~/.ssh is a local directory"); + assert_eq!(fs::read_to_string(home.join(".ssh/id_ed25519")).unwrap(), "KEY"); + assert!(!mnt.join(".ssh").exists(), "nothing written to EFS"); +} + +#[test] +fn two_connects_at_once_never_mix_their_files() { + // Two machines connecting at the same moment: both prepare, then both + // upload, then both apply. Each applies its own set; the later wins. + let tmp = tempfile::tempdir().unwrap(); + let c = Connect::new(tmp.path()); + let a = c.prepare(); + let b = c.prepare(); + assert_ne!(a, b); + c.stage(&a, &[("ssh/id_a", "A"), ("ssh/config", "Host a\n")], &format!("GIT_TOKEN={}\n", b64("tok-a"))); + c.stage(&b, &[("ssh/id_b", "B"), ("ssh/config", "Host b\n")], &format!("GIT_TOKEN={}\n", b64("tok-b"))); + for n in [&a, &b] { + let out = c.run(&[n]); + assert!(out.status.success(), "{}", text(&out)); + } + assert_eq!(fs::read_to_string(c.p("home/.ssh/config")).unwrap(), "Host b\n"); + let cred = fs::read_to_string(c.p("home/.git-credentials")).unwrap_or_else(|e| panic!("{e}: {:?}", fs::read_dir(c.p("home")).unwrap().map(|e| e.unwrap().file_name()).collect::>())); + assert!(cred.contains("tok-b"), "{cred}"); + // B's set as a whole: A's key, merged first, is dropped again by the + // merge's own bookkeeping (B no longer provides it). + assert_eq!(fs::read_to_string(c.p("home/.ssh/id_b")).unwrap(), "B"); + assert!(!c.p("home/.ssh/id_a").exists()); + assert_eq!(fs::read_dir(c.p("shm/connect")).unwrap().count(), 0, "both staging dirs gone"); + // A nonce that is not one, or not prepared, is refused. + assert_eq!(c.run(&["../../etc"]).status.code(), Some(2)); + assert_eq!(c.run(&[&a]).status.code(), Some(1)); } diff --git a/app/src-tauri/src/docker/ca_certs.rs b/app/src-tauri/src/docker/ca_certs.rs index 58b1da7..e0e0618 100644 --- a/app/src-tauri/src/docker/ca_certs.rs +++ b/app/src-tauri/src/docker/ca_certs.rs @@ -108,7 +108,8 @@ fn sha256_hex(input: &str) -> String { /// loops that walk the store, and leading dots are stripped so a hidden file /// does not stay hidden. /// -/// `entrypoint.sh` reimplements exactly this in a few lines of shell (it has to +/// `entrypoint-lib.sh` (`ca_normalise_name`, sourced by `entrypoint.sh`) +/// reimplements exactly this in a few lines of shell (it has to /// rename the files inside the container); the two must agree, which is what /// the unit tests below pin down. pub fn container_cert_name(file_name: &str) -> String { 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/docker/image.rs b/app/src-tauri/src/docker/image.rs index 31f05be..6eab194 100644 --- a/app/src-tauri/src/docker/image.rs +++ b/app/src-tauri/src/docker/image.rs @@ -10,6 +10,10 @@ use crate::models::container_config; const DOCKERFILE: &str = include_str!("../../../../container/Dockerfile"); const ENTRYPOINT: &str = include_str!("../../../../container/entrypoint.sh"); +/// Sourced by the entrypoint and by `triple-c-apply-connect`; holds the +/// `sync_host_ssh` block the tests below run. +const ENTRYPOINT_LIB: &str = include_str!("../../../../container/entrypoint-lib.sh"); +const APPLY_CONNECT: &str = include_str!("../../../../container/triple-c-apply-connect"); const SCHEDULER: &str = include_str!("../../../../container/triple-c-scheduler"); const TASK_RUNNER: &str = include_str!("../../../../container/triple-c-task-runner"); const OSC52_CLIPBOARD: &str = include_str!("../../../../container/osc52-clipboard"); @@ -19,6 +23,7 @@ const TRIPLE_C_OPEN: &str = include_str!("../../../../container/triple-c-open"); const PLAYWRIGHT_HEAL: &str = include_str!("../../../../container/triple-c-playwright-heal"); const WIP_PUSH: &str = include_str!("../../../../container/triple-c-wip-push"); const IDLE_WATCH: &str = include_str!("../../../../container/triple-c-idle-watch"); +const WORKSPACE_STATUS: &str = include_str!("../../../../container/triple-c-workspace-status"); static MISSION_CONTROL_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/mission-control"); static SKILLS_DIR: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../container/skills"); @@ -240,6 +245,8 @@ fn create_build_context() -> Result, std::io::Error> { append_file_to_archive(&mut archive, "Dockerfile", DOCKERFILE.as_bytes(), 0o644)?; append_file_to_archive(&mut archive, "entrypoint.sh", ENTRYPOINT.as_bytes(), 0o755)?; + append_file_to_archive(&mut archive, "entrypoint-lib.sh", ENTRYPOINT_LIB.as_bytes(), 0o644)?; + append_file_to_archive(&mut archive, "triple-c-apply-connect", APPLY_CONNECT.as_bytes(), 0o755)?; append_file_to_archive(&mut archive, "triple-c-scheduler", SCHEDULER.as_bytes(), 0o755)?; append_file_to_archive(&mut archive, "triple-c-task-runner", TASK_RUNNER.as_bytes(), 0o755)?; append_file_to_archive(&mut archive, "osc52-clipboard", OSC52_CLIPBOARD.as_bytes(), 0o755)?; @@ -249,6 +256,12 @@ fn create_build_context() -> Result, std::io::Error> { append_file_to_archive(&mut archive, "triple-c-playwright-heal", PLAYWRIGHT_HEAL.as_bytes(), 0o755)?; append_file_to_archive(&mut archive, "triple-c-wip-push", WIP_PUSH.as_bytes(), 0o755)?; append_file_to_archive(&mut archive, "triple-c-idle-watch", IDLE_WATCH.as_bytes(), 0o755)?; + append_file_to_archive( + &mut archive, + "triple-c-workspace-status", + WORKSPACE_STATUS.as_bytes(), + 0o755, + )?; append_embedded_dir(&mut archive, &MISSION_CONTROL_DIR, "mission-control")?; append_embedded_dir(&mut archive, &SKILLS_DIR, "skills")?; @@ -305,17 +318,18 @@ mod build_context_tests { #[cfg(all(test, unix))] mod tests { - use super::ENTRYPOINT; + use super::ENTRYPOINT_LIB; use std::fs; use std::path::Path; use std::process::Command; - /// The `sync_host_ssh` function from `entrypoint.sh`, cut out between its - /// markers so it can be run against temp dirs instead of the real ~/.ssh. + /// The `sync_host_ssh` function from `entrypoint-lib.sh` (which + /// `entrypoint.sh` sources), cut out between its markers so it can be run + /// against temp dirs instead of the real ~/.ssh. fn sync_fn() -> &'static str { - let start = ENTRYPOINT.find("# >>> sync_host_ssh").expect("start marker"); - let end = ENTRYPOINT.find("# <<< sync_host_ssh").expect("end marker"); - &ENTRYPOINT[start..end] + let start = ENTRYPOINT_LIB.find("# >>> sync_host_ssh").expect("start marker"); + let end = ENTRYPOINT_LIB.find("# <<< sync_host_ssh").expect("end marker"); + &ENTRYPOINT_LIB[start..end] } fn sync(src: &Path, dest: &Path) -> String { diff --git a/app/src-tauri/src/docker/workspace_env.rs b/app/src-tauri/src/docker/workspace_env.rs index 046eb76..998b182 100644 --- a/app/src-tauri/src/docker/workspace_env.rs +++ b/app/src-tauri/src/docker/workspace_env.rs @@ -420,6 +420,20 @@ pub(crate) fn workspace_env( } +/// The names of the custom variables [`workspace_env`] emits for `project` +/// (global + per-project, trimmed, reserved names skipped): the ones +/// copy-at-connect treats as credentials. +pub(crate) fn custom_env_keys(project: &Project, global_custom_env_vars: &[EnvVar]) -> Vec { + let mut keys: Vec = merge_custom_env_vars(global_custom_env_vars, &project.custom_env_vars) + .iter() + .map(|e| e.key.trim().to_string()) + .filter(|k| !k.is_empty() && !is_reserved_env_key(k)) + .collect(); + keys.sort(); + keys.dedup(); + keys +} + /// [`workspace_env`] with its inputs resolved from `settings` exactly as /// `create_container` resolves them (the CA from disk, the shared Claude /// token from the keychain), for a host that does not create a Docker @@ -428,11 +442,25 @@ pub(crate) fn workspace_env_from_settings( project: &Project, settings: &crate::models::AppSettings, ) -> Result { - let shared_claude = super::container::shared_claude_auth(project); let effective_ca_path = resolve_with_global(project.ca_cert_path.as_deref(), settings.ca_cert_path.as_deref()); let resolved_ca = ca_certs::resolve(effective_ca_path)?; - let pairs = workspace_env( + let pairs = workspace_env_with_ca(project, settings, resolved_ca.as_ref()); + Ok((pairs, resolved_ca)) +} + +/// [`workspace_env`] resolved from `settings` like +/// [`workspace_env_from_settings`] but with the CA given (`None`: no CA +/// variables) — so nothing is read from disk. The keychain is (the shared +/// Claude token). Copy-at-connect's terminal environment uses it: the +/// credential pairs never depend on the CA. +pub(crate) fn workspace_env_with_ca( + project: &Project, + settings: &crate::models::AppSettings, + resolved_ca: Option<&ResolvedCa>, +) -> Vec<(String, String)> { + let shared_claude = super::container::shared_claude_auth(project); + workspace_env( project, &WorkspaceEnvInputs { global_aws: &settings.global_aws, @@ -445,11 +473,10 @@ pub(crate) fn workspace_env_from_settings( global_claude_code_settings: settings.global_claude_code_settings.as_ref(), default_git_user_name: settings.default_git_user_name.as_deref(), default_git_user_email: settings.default_git_user_email.as_deref(), - resolved_ca: resolved_ca.as_ref(), + resolved_ca, shared_claude_token: shared_claude.as_ref().map(|(token, _)| token.as_str()), }, - ); - Ok((pairs, resolved_ca)) + ) } #[cfg(test)] diff --git a/app/src-tauri/src/host/aws_host.rs b/app/src-tauri/src/host/aws_host.rs index 061cd10..5d55760 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; @@ -81,6 +84,11 @@ const WATCH_CALL_TIMEOUT: Duration = Duration::from_secs(60); /// reported as failed; the SDK's own bound is per call. const STOP_TIMEOUT: Duration = Duration::from_secs(45); +pub mod connect; +pub mod status; +pub use connect::{spawn_connect_push, terminal_env}; +pub use status::{spawn_follow, workspace_status, WorkspaceStatus}; + fn s(e: E) -> String { e.to_string() } @@ -146,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> { @@ -345,7 +402,13 @@ pub struct StartInputs<'a> { pub who: &'a CallerIdentity, pub env_pairs: &'a [(String, String)], pub files: &'a [(String, Vec)], + /// 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`]). Called only when the start prepares a new task: + /// attaching to a running one never needs the provider key or models. + pub gateway: &'a (dyn Fn() -> Result, String> + Send + Sync), pub wait: WaitTiming, pub access_point_wait: PollTiming, /// Called as soon as the project has a task (found, or RunTask @@ -362,6 +425,8 @@ pub struct TaskRecord { pub task_arn: String, pub access_point_id: Option, pub task_definition_arn: Option, + /// EFS storage's `/workspace` access point. + pub workspace_access_point_id: Option, } /// A connected task. @@ -373,6 +438,8 @@ pub struct Started { /// The access point the task mounts (Hybrid). `None` when an existing /// task was attached to: the store's value stands. pub access_point_id: Option, + /// The `/workspace` access point (EFS), like `access_point_id`. + pub workspace_access_point_id: Option, /// This start ran the task (rather than attaching to a running one). pub created: bool, } @@ -433,13 +500,14 @@ pub async fn start_core t, Err(e) => return Err(with_log_tail(tasks, &logs, &task.arn, e.to_string()).await), }; - (task, token, None, false) + (task, token, None, None, false) } else { progress(PROGRESS_PREPARING); + let sidecar = (inp.gateway)()?; let prepared = prepare_workspace( work, inp.who, @@ -457,11 +526,16 @@ pub async fn start_core Result<(Strin Ok((host_id.to_string(), region, sdk)) } +/// The lifetime cap, in hours (0 = none), of the environment `project` runs +/// in, from its record (Q8: Host settings show it). `None` when it can't be +/// read — offline, denied, slow, or the environment is gone. +pub async fn environment_max_hours(project: &Project, settings: &AppSettings) -> Option { + let placement = project.aws_placement.as_ref()?; + let read = async { + let (_, region, sdk) = project_sdk(project, settings).await.ok()?; + let who = caller_identity(&sdk).await.ok()?; + read_environment(&SdkRuntimeApi::new(&sdk), &placement.environment, &who.account, ®ion) + .await + .ok() + }; + let info = tokio::time::timeout(std::time::Duration::from_secs(10), read).await.ok()??; + Some(info.max_workspace_hours) +} + /// `ProjectHost::Aws::ensure_started`. pub async fn ensure_started( project: &Project, settings: &AppSettings, store: &ProjectsStore, progress: &(dyn Fn(&str) + Send + Sync), +) -> Result { + ensure_started_with( + project, + settings, + store, + progress, + crate::storage::secure::get_gateway_api_key, + ) + .await +} + +/// [`ensure_started`] with the gateway sidecar's provider key read by +/// `read_gateway_key` instead of the keychain (the live tests have none). +pub async fn ensure_started_with( + project: &Project, + settings: &AppSettings, + store: &ProjectsStore, + progress: &(dyn Fn(&str) + Send + Sync), + read_gateway_key: impl FnOnce() -> Result, String> + Send, ) -> Result { // A background re-attach (after a restart) may be opening a tunnel: // cancel it, this start attaches itself. Its tunnel, if it gets one, is @@ -569,6 +687,7 @@ pub async fn ensure_started( // Already connected and answering: nothing to do. if let Some(ep) = tunnels::get_endpoint(&project.id) { if matches!(agent::is_running(&ep).await, Ok(true)) { + tunnels::mark_attached(&project.id); return Ok(ContainerTarget::Agent(ep)); } tunnels::close(&project.id).await; @@ -582,6 +701,17 @@ pub async fn ensure_started( .as_deref() .or(settings.default_ssh_key_path.as_deref()); let files = workspace_files(ssh, ca.as_ref())?; + let custom_env_keys = + crate::docker::workspace_env::custom_env_keys(project, &settings.global_custom_env_vars); + // Read lazily: only a start that prepares a new task needs it (an attach + // must work with the provider key gone from the keychain). + let read_gateway_key = std::sync::Mutex::new(Some(read_gateway_key)); + let sidecar = || { + gateway_sidecar(project, settings, || match read_gateway_key.lock().unwrap().take() { + Some(read) => read(), + None => Ok(None), + }) + }; let (connection_id, region, sdk) = project_sdk(project, settings).await?; let who = caller_identity(&sdk).await.map_err(s)?; @@ -596,7 +726,9 @@ pub async fn ensure_started( who: &who, env_pairs: &env_pairs, files: &files, + custom_env_keys: &custom_env_keys, image: &image, + gateway: &sidecar, wait: WaitTiming::default(), access_point_wait: PollTiming::default(), on_task: &on_task, @@ -615,6 +747,9 @@ pub async fn ensure_started( let access_point_id = started .access_point_id .or_else(|| project.aws.as_ref().and_then(|a| a.access_point_id.clone())); + let workspace_access_point_id = started + .workspace_access_point_id + .or_else(|| project.aws.as_ref().and_then(|a| a.workspace_access_point_id.clone())); let ecs = ecs_task(&started.task)?; if let Some(old) = tunnels::register( &project.id, @@ -628,7 +763,9 @@ pub async fn ensure_started( forward: started.forward, endpoint: endpoint.clone(), access_point_id, + workspace_access_point_id, task_definition_arn: started.task.task_definition_arn.clone(), + created: started.created, }, ) { old.forward.close().await; @@ -651,12 +788,14 @@ pub fn record_task(store: &ProjectsStore, project_id: &str, rec: Option<&TaskRec Some(r.task_arn.clone()), r.access_point_id.clone().or(stored.access_point_id), r.task_definition_arn.clone().or(stored.task_definition_arn), + r.workspace_access_point_id.clone().or(stored.workspace_access_point_id), ), None => store.set_aws_runtime( project_id, None, stored.access_point_id, stored.task_definition_arn, + stored.workspace_access_point_id, ), }; if let Err(e) = res { @@ -808,6 +947,7 @@ async fn task_arn_or_find( /// the stored task ARN, else whatever live task the project has (a crash /// between RunTask and the store write). Closes the tunnel. pub async fn stop_project(project: &Project, settings: &AppSettings) -> Result<(), String> { + tunnels::cancel_follow(&project.id); if let Some(ep) = tunnels::get_endpoint(&project.id) { if let Some(res) = stop_endpoint(&ep).await { return res; @@ -841,6 +981,7 @@ pub async fn remove_resources( settings: &AppSettings, discard_data: bool, ) -> Result<(), String> { + tunnels::cancel_follow(&project.id); let (_, region, sdk) = project_sdk(project, settings).await?; let who = caller_identity(&sdk).await.map_err(s)?; let ok = owner_key(®ion, &who.user_id); @@ -858,6 +999,8 @@ pub async fn remove_resources( project_id: &project.id, stored_task_arn: aws.and_then(|a| a.task_arn.as_deref()), stored_access_point_id: aws.and_then(|a| a.access_point_id.as_deref()), + stored_workspace_access_point_id: aws + .and_then(|a| a.workspace_access_point_id.as_deref()), discard_data, }, ) @@ -972,6 +1115,7 @@ pub async fn reconcile_project( task_arn: t.arn.clone(), access_point_id: None, task_definition_arn: Some(t.task_definition_arn.clone()), + workspace_access_point_id: None, }), ); } @@ -985,8 +1129,17 @@ pub async fn reconcile_project( /// `reconcile_project_statuses` for an AWS project: decide, and when the /// task is live re-open its tunnel in the background (terminals wait for -/// it through [`tunnels::wait_endpoint`]). Never blocks on the tunnel. -pub async fn reconcile(project: &Project, settings: &AppSettings, store: Arc) { +/// it through [`tunnels::wait_endpoint`]), then — copy-at-connect — copy the +/// credentials in, calling `on_connect_warning` if that fails — after +/// opening its port mappings (`on_ports_warning` for any that fail). Never +/// blocks on the tunnel. +pub async fn reconcile( + project: &Project, + settings: &AppSettings, + store: Arc, + on_connect_warning: impl FnOnce(String) + Send + 'static, + on_ports_warning: impl FnOnce(String) + Send + 'static, +) { let (connection_id, region, sdk) = match project_sdk(project, settings).await { Ok(v) => v, Err(e) => { @@ -1006,12 +1159,29 @@ pub async fn reconcile(project: &Project, settings: &AppSettings, store: Arc { let generation = tunnels::begin_reattach(&project.id); - let project = project.clone(); + let (project, settings) = (project.clone(), settings.clone()); tauri::async_runtime::spawn(async move { let ctx = Reattach { generation, connection_id, region, sdk, who }; - if let Err(e) = reattach(&project, *task, ctx, &store).await { - log::warn!("Project {}: could not re-open the tunnel to its task: {e}", project.id); - tunnels::end_reattach(&project.id, generation); + match reattach(&project, *task, ctx, &store).await { + // Re-attached: a connect like any other (Q2). + Ok(true) => { + // Q6: the port mappings' forwards, before the + // (slower) credential copy. + if let Some(detail) = super::port_forwards::open_for_project(&store, &project.id).await { + on_ports_warning(detail); + } + if let Err(e) = connect::apply_connect(&project, &settings).await { + log::warn!("Project {}: could not copy the credentials in: {e}", project.id); + if tunnels::get_endpoint(&project.id).is_some() { + on_connect_warning(e); + } + } + } + Ok(false) => {} + Err(e) => { + log::warn!("Project {}: could not re-open the tunnel to its task: {e}", project.id); + tunnels::end_reattach(&project.id, generation); + } } }); } @@ -1040,13 +1210,14 @@ pub fn reattach_still_wanted(store: &ProjectsStore, project_id: &str, task_arn: }) } -/// Re-open the tunnel to a live task found at startup. +/// Re-open the tunnel to a live task found at startup. `Ok(true)` once it +/// is registered; `Ok(false)` when it was no longer wanted. async fn reattach( project: &Project, task: TaskInfo, ctx: Reattach, store: &ProjectsStore, -) -> Result<(), String> { +) -> Result { let placement = project.aws_placement.as_ref().ok_or("no placement")?; let ok = owner_key(&ctx.region, &ctx.who.user_id); let rt = SdkRuntimeApi::new(&ctx.sdk); @@ -1070,13 +1241,18 @@ async fn reattach( forward, endpoint: endpoint.clone(), access_point_id: project.aws.as_ref().and_then(|a| a.access_point_id.clone()), + workspace_access_point_id: project + .aws + .as_ref() + .and_then(|a| a.workspace_access_point_id.clone()), task_definition_arn: task.task_definition_arn.clone(), + created: false, }; if !reattach_still_wanted(store, &project.id, &task.arn) { tunnel.forward.close().await; tunnels::end_reattach(&project.id, ctx.generation); log::info!("Project {}: stopped or removed while re-attaching; tunnel closed", project.id); - return Ok(()); + return Ok(false); } match tunnels::register_if_current(&project.id, ctx.generation, tunnel) { Ok(old) => { @@ -1087,13 +1263,13 @@ async fn reattach( Err(tunnel) => { tunnel.forward.close().await; log::info!("Project {}: stopped or removed while re-attaching; tunnel closed", project.id); - return Ok(()); + return Ok(false); } } // The local port is new, so the stored target id is too. store.set_container_id(&project.id, Some(endpoint.base_url.to_string()))?; log::info!("Project {}: tunnel to task {} re-opened", project.id, task.arn); - Ok(()) + Ok(true) } // ─────────────────────────────────────────────────────────────── watch diff --git a/app/src-tauri/src/host/aws_host/connect.rs b/app/src-tauri/src/host/aws_host/connect.rs new file mode 100644 index 0000000..7431841 --- /dev/null +++ b/app/src-tauri/src/host/aws_host/connect.rs @@ -0,0 +1,299 @@ +//! Copy-at-connect (phase 6, ruling Q2): an AWS project whose credentials +//! are "copied when you connect" keeps them out of its Secrets Manager +//! secret (`aws::workspace`, `PayloadExtras::connect_only`) and brings them +//! in after every connect instead — a start, an attach, the background +//! re-attach when the app starts. +//! +//! The credentials are [`ConnectBundle`]: the SSH and CA files (the same +//! [`workspace_files`](super::workspace_files) the secret would carry) and +//! the credential environment pairs (`SECRET_ENV_KEYS` and every custom +//! variable, `aws::workspace::credential_pairs`). [`push_connect_bundle`] +//! uploads them through the agent, as root, into this connect's own root-only +//! staging dir on the task's `/dev/shm` tmpfs and runs `triple-c-apply-connect +//! ` (container), which +//! installs the CA, merges the SSH files, writes the git credential helper +//! and re-clones what failed. The terminals the app opens get the pairs in +//! their own `ExecSpec.env` ([`terminal_env`]); nothing puts them into the +//! agent's environment, so other execs, cron jobs and the scheduler never +//! see them. **Values are never logged**: errors carry names and the +//! script's own (value-free) output only. + +use std::time::Duration; + +use zeroize::Zeroizing; + +use super::super::{tunnels, ContainerTarget}; +use crate::aws::workspace::{credential_pairs, validate_file_key}; +use crate::models::project::SecretsDelivery; +use crate::models::{AppSettings, Project}; + +/// The in-container half (container/triple-c-apply-connect). +pub const APPLY_CONNECT: &str = "/usr/local/bin/triple-c-apply-connect"; +/// Staging (root 0700, on the tmpfs the entrypoint made for the agent +/// token): each connect gets `/` with `ssh/`, `ca/` and `connect.env`. +pub const CONNECT_STAGE: &str = "/dev/shm/triple-c/connect"; +pub const CONNECT_ENV_FILE: &str = "connect.env"; +/// Every staged file is root 0600. +const STAGED_MODE: u32 = 0o600; +/// The whole push (a few uploads and two execs through the tunnel). +pub const PUSH_TIMEOUT: Duration = Duration::from_secs(120); +/// The most of the script's output a warning carries. +const OUTPUT_TAIL_LINES: usize = 10; + +/// A credential value, zeroed when dropped (the settings export's +/// precedent). It narrows, not closes, the window: the values were read from +/// the keychain into a `Project`, and the copies an `ExecSpec` or an upload +/// body needs are plain buffers owned by those layers. +pub type SecretBytes = Zeroizing>; +pub type SecretString = Zeroizing; + +/// What copy-at-connect copies in. +#[derive(Clone, Default)] +pub struct ConnectBundle { + /// `ssh/` / `ca/`, as in the secret's `TRIPLEC_FILES`. + pub files: Vec<(String, SecretBytes)>, + /// The credential environment pairs. + pub env: Vec<(String, SecretString)>, +} + +/// Names only: a bundle holds keys and tokens. +impl std::fmt::Debug for ConnectBundle { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("ConnectBundle") + .field("files", &self.files.iter().map(|(k, _)| k.as_str()).collect::>()) + .field("env", &self.env.iter().map(|(k, _)| k.as_str()).collect::>()) + .finish() + } +} + +/// Whether `project` copies its credentials in at connect. +pub fn copies_at_connect(project: &Project) -> bool { + project.is_aws() + && project + .aws + .as_ref() + .is_some_and(|a| a.secrets_delivery == SecretsDelivery::CopyAtConnect) +} + +/// The bundle for `project`, whose keychain secrets must already be loaded +/// (`load_secrets_for_project`): the same sources the secret would use. +pub fn connect_credentials(project: &Project, settings: &AppSettings) -> Result { + let (_, ca) = super::aws_env(project, settings)?; + let ssh = project + .ssh_key_path + .as_deref() + .or(settings.default_ssh_key_path.as_deref()); + let files = super::workspace_files(ssh, ca.as_ref())? + .into_iter() + .map(|(k, v)| (k, Zeroizing::new(v))) + .collect(); + Ok(ConnectBundle { files, env: connect_env(project, settings) }) +} + +/// Only the credential pairs of `project` (secrets loaded): no file is read, +/// so a missing SSH or CA file never keeps the API keys from a terminal. +pub fn connect_env(project: &Project, settings: &AppSettings) -> Vec<(String, SecretString)> { + 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() +} + +/// `project` as the store holds it, with its keychain secrets read in. +fn with_secrets(project: &Project) -> Project { + let mut p = project.clone(); + crate::commands::project_commands::load_secrets_for_project(&mut p); + p +} + +/// `connect.env`: one `KEY=` line per pair, so a value +/// with a newline or `=` reads back whole and nothing has to be quoted. +pub fn connect_env_file(env: &[(String, SecretString)]) -> SecretBytes { + use base64::Engine; + let b64 = base64::engine::general_purpose::STANDARD; + let mut out = Zeroizing::new(String::new()); + for (k, v) in env { + out.push_str(k); + out.push('='); + b64.encode_string(v.as_bytes(), &mut out); + out.push('\n'); + } + Zeroizing::new(out.as_bytes().to_vec()) +} + +/// `KEY=VALUE` strings for an `ExecSpec`. +pub fn exec_env(env: &[(String, SecretString)]) -> Vec { + env.iter().map(|(k, v)| format!("{k}={}", v.as_str())).collect() +} + +/// What a push needs from the container: root execs and root uploads. +pub trait ConnectTarget: Send + Sync { + fn exec_root( + &self, + cmd: Vec, + ) -> impl std::future::Future> + Send; + fn upload_root( + &self, + dir: &str, + name: &str, + data: &[u8], + mode: u32, + ) -> impl std::future::Future> + Send; +} + +impl ConnectTarget for ContainerTarget { + async fn exec_root(&self, cmd: Vec) -> Result<(String, i64), String> { + self.exec_oneshot_as("root", cmd, Vec::new()).await + } + async fn upload_root(&self, dir: &str, name: &str, data: &[u8], mode: u32) -> Result<(), String> { + self.upload_bytes_with_ids(dir, name, data, mode, (0, 0)).await.map(|_| ()) + } +} + +fn tail(output: &str) -> String { + let lines: Vec<&str> = output.lines().filter(|l| !l.trim().is_empty()).collect(); + lines[lines.len().saturating_sub(OUTPUT_TAIL_LINES)..].join("\n") +} + +async fn run_apply(t: &T, args: &[&str]) -> Result { + let mut cmd = vec![APPLY_CONNECT.to_string()]; + cmd.extend(args.iter().map(|a| a.to_string())); + let (out, code) = t.exec_root(cmd).await?; + match code { + 0 => Ok(out), + // `exec` of a missing file: an image from before copy-at-connect. + 126 | 127 => Err( + "This workspace's image has no triple-c-apply-connect (it predates copying \ + credentials at connect); use a newer image, or store the credentials in AWS" + .into(), + ), + _ => Err(format!("triple-c-apply-connect failed ({code}):\n{}", tail(&out))), + } +} + +/// `--prepare`'s answer: this connect's nonce, 16 hex digits on the last line. +pub(crate) fn parse_nonce(out: &str) -> Result { + let last = out.lines().rev().map(str::trim).find(|l| !l.is_empty()).unwrap_or_default(); + if last.len() == 16 && last.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) { + Ok(last.to_string()) + } else { + Err(format!("triple-c-apply-connect --prepare gave no connect id:\n{}", tail(out))) + } +} + +/// Upload `bundle` and apply it (see the module docs): `--prepare` (which +/// names this connect's own staging dir), the files and `connect.env` (root +/// 0600) into that dir, then the apply of exactly that dir — so two +/// connects at once (two machines) never mix their files. +pub async fn push_connect_bundle(t: &T, bundle: &ConnectBundle) -> Result<(), String> { + let nonce = parse_nonce(&run_apply(t, &["--prepare"]).await?)?; + let dir = format!("{CONNECT_STAGE}/{nonce}"); + for (key, data) in &bundle.files { + validate_file_key(key)?; + let (kind, name) = key.split_once('/').expect("validated"); + t.upload_root(&format!("{dir}/{kind}"), name, data, STAGED_MODE) + .await + .map_err(|e| format!("Could not copy {key} into the workspace: {e}"))?; + } + t.upload_root(&dir, CONNECT_ENV_FILE, &connect_env_file(&bundle.env), STAGED_MODE) + .await + .map_err(|e| format!("Could not copy the credential variables into the workspace: {e}"))?; + let out = run_apply(t, &[&nonce]).await?; + for line in out.lines().filter(|l| l.contains("warning")) { + log::warn!("{line}"); + } + Ok(()) +} + +/// Copy `project`'s credentials into its connected workspace. `Ok(false)` +/// when there is nothing to do (not copy-at-connect, or no tunnel). +pub async fn apply_connect(project: &Project, settings: &AppSettings) -> Result { + if !copies_at_connect(project) { + return Ok(false); + } + let Some(ep) = tunnels::get_endpoint(&project.id) else { + return Ok(false); + }; + let (p, s) = (project.clone(), settings.clone()); + let bundle = tokio::task::spawn_blocking(move || connect_credentials(&with_secrets(&p), &s)) + .await + .map_err(|e| format!("Could not gather the credentials: {e}"))??; + let target = ContainerTarget::Agent(ep); + tokio::time::timeout(PUSH_TIMEOUT, push_connect_bundle(&target, &bundle)) + .await + .map_err(|_| format!("Copying the credentials took more than {} s", PUSH_TIMEOUT.as_secs()))??; + log::info!( + "Project {}: credentials copied into the workspace ({} file(s), {} variable(s))", + project.id, + bundle.files.len(), + bundle.env.len() + ); + Ok(true) +} + +/// After a connect: [`apply_connect`] in the background, `on_warning` on a +/// failure while the workspace is still connected (a Stop meanwhile is not +/// worth a warning). `false` (nothing spawned) unless the project copies at +/// connect and is connected. +pub fn spawn_connect_push( + project: &Project, + settings: &AppSettings, + on_warning: impl FnOnce(String) + Send + 'static, +) -> bool { + if !copies_at_connect(project) || tunnels::get_endpoint(&project.id).is_none() { + return false; + } + let (project, settings) = (project.clone(), settings.clone()); + tauri::async_runtime::spawn(async move { + if let Err(e) = apply_connect(&project, &settings).await { + log::warn!("Project {}: could not copy the credentials in: {e}", project.id); + if tunnels::get_endpoint(&project.id).is_some() { + on_warning(e); + } + } + }); + true +} + +/// The environment a terminal the app opens adds to its exec: the +/// credential pairs for a copy-at-connect project, nothing otherwise (they +/// are already in the task's environment). Only the pairs ([`connect_env`]: +/// no SSH or CA file is read); the keychain is read off the async runtime. +pub async fn terminal_env(project: &Project, settings: &AppSettings) -> Vec { + if !copies_at_connect(project) { + return Vec::new(); + } + let (p, s) = (project.clone(), settings.clone()); + let gathered = tokio::task::spawn_blocking(move || connect_env(&with_secrets(&p), &s)) + .await + .map_err(|e| format!("could not gather them: {e}")); + terminal_env_with(project, || gathered) +} + +/// [`terminal_env`] over a given source of the pairs. +pub fn terminal_env_with( + project: &Project, + credentials: impl FnOnce() -> Result, String>, +) -> Vec { + if !copies_at_connect(project) { + return Vec::new(); + } + match credentials() { + Ok(env) => exec_env(&env), + Err(e) => { + log::warn!( + "Project {}: the terminal opens without the project's credentials: {e}", + project.id + ); + Vec::new() + } + } +} diff --git a/app/src-tauri/src/host/aws_host/status.rs b/app/src-tauri/src/host/aws_host/status.rs new file mode 100644 index 0000000..2c52a18 --- /dev/null +++ b/app/src-tauri/src/host/aws_host/status.rs @@ -0,0 +1,455 @@ +//! An AWS workspace's clone and setup script, as the start follows them and +//! Project Home shows them (phase 6, Q4). +//! +//! The entrypoint clones in the background and then runs the setup script; +//! `triple-c-workspace-status` (container) prints both as one JSON line, +//! mirrored by [`WorkspaceStatus`]. +//! +//! **The start does not wait for them** (ruling R5, amending Q4): it ends +//! after "Connecting…" as in phase 5 — project Running, project lock +//! released, terminals and Stop usable. [`spawn_follow`] then follows in the +//! background: a read through the agent every [`FOLLOW_INTERVAL`] as a +//! **background** exec (never activity for idle stop), a log line only when +//! it changes, until the clone is done and no setup runs, [`FOLLOW_LIMIT`] +//! passes, the agent is gone (tunnel dropped, task died, image without the +//! script) or its token is cancelled (`tunnels::cancel_follow` on Stop and +//! Remove; any tunnel close; app exit). Its only output is the final warning +//! ([`follow_warning`]); Project Home's Overview card polls the status itself +//! while the project is Running, so progress shows there. + +use std::future::Future; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use tokio_util::sync::CancellationToken; + +use super::super::{tunnels, ContainerTarget}; +use crate::models::Project; + +/// The in-container status reader (Task 4). +pub const STATUS_SCRIPT: &str = "/usr/local/bin/triple-c-workspace-status"; +pub const FOLLOW_INTERVAL: Duration = Duration::from_secs(2); +/// The setup script's own timeout is 30 minutes, after the clone. +pub const FOLLOW_LIMIT: Duration = Duration::from_secs(35 * 60); +/// One status read through the agent. +const READ_TIMEOUT: Duration = Duration::from_secs(20); +/// Reads failing in a row before the follow gives up (quietly). +const MAX_READ_FAILURES: u32 = 5; +/// The script prints at most ~20 KB (20 tail lines of ≤ 1000 characters). +const STATUS_OUTPUT_LIMIT: usize = 256 * 1024; +/// A setup log line shown as progress is cut to this many characters. +const MAX_PROGRESS_LINE: usize = 200; +/// Setup log lines a warning carries. +const WARNING_TAIL_LINES: usize = 10; + +pub const PROGRESS_CLONING: &str = "Cloning repos…"; +pub const PROGRESS_SETUP: &str = "Running setup script…"; + +// ──────────────────────────────────────────────────────────────── model + +/// `triple-c-workspace-status`'s JSON. Unknown fields are ignored and +/// missing ones default, so an older or newer image never breaks a read. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct WorkspaceStatus { + pub clone: CloneStatus, + pub setup: SetupStatus, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct CloneStatus { + /// Every repo has been tried. + pub done: bool, + /// The repos tried so far, in order. + pub repos: Vec, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct RepoProgress { + pub folder: String, + /// `cloning`, `cloned`, `failed` or `exists`. + pub state: String, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct SetupStatus { + pub state: SetupState, + /// The script's exit code: 0 when `ok`, the code when `failed` (if known). + pub code: Option, + /// The setup log's last lines. + pub tail: Vec, +} + +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum SetupState { + /// No setup script. + #[default] + None, + Running, + Ok, + /// Also any state this app does not know. + #[serde(other)] + Failed, +} + +impl RepoProgress { + fn finished(&self) -> bool { + matches!(self.state.as_str(), "cloned" | "failed" | "exists") + } +} + +impl WorkspaceStatus { + /// Nothing more will change: the clone is done and no setup is running. + pub fn settled(&self) -> bool { + self.clone.done && self.setup.state != SetupState::Running + } + + pub fn failed_repos(&self) -> Vec<&str> { + self.clone + .repos + .iter() + .filter(|r| r.state == "failed") + .map(|r| r.folder.as_str()) + .collect() + } + + /// The start's progress line for this state (`None` once settled). + /// `total` is how many repos the project configures; the status only + /// lists the ones started so far. + pub fn progress_line(&self, total: usize) -> Option { + if !self.clone.done { + let n = total.max(self.clone.repos.len()); + if n == 0 { + return Some(PROGRESS_CLONING.into()); + } + let finished = self.clone.repos.iter().filter(|r| r.finished()).count(); + return Some(format!("{PROGRESS_CLONING} ({}/{n})", (finished + 1).min(n))); + } + (self.setup.state == SetupState::Running).then(|| PROGRESS_SETUP.into()) + } + + /// The setup log's last non-blank line, cleaned for a progress line. + fn last_log_line(&self) -> Option { + self.setup + .tail + .iter() + .rev() + .map(|l| clean_line(l)) + .find(|l| !l.is_empty()) + } + + /// What went wrong, for the user; `None` when nothing did. + pub fn problems(&self) -> Option { + let mut parts = Vec::new(); + let failed = self.failed_repos(); + if !failed.is_empty() { + parts.push(format!( + "Cloning failed for {}: {}. The workspace started without {}.", + if failed.len() == 1 { "a repo" } else { "some repos" }, + failed.join(", "), + if failed.len() == 1 { "it" } else { "them" }, + )); + } + if self.setup.state == SetupState::Failed { + let code = self.setup.code.map(|c| format!(" (exit {c})")).unwrap_or_default(); + let mut s = format!("The setup script failed{code}."); + let tail: Vec<&String> = self.setup.tail.iter().rev().take(WARNING_TAIL_LINES).collect(); + if !tail.is_empty() { + s.push_str("\nLast lines:\n"); + s.push_str( + &tail.into_iter().rev().map(String::as_str).collect::>().join("\n"), + ); + } + parts.push(s); + } + (!parts.is_empty()).then(|| parts.join("\n\n")) + } +} + +/// One line of the setup log as a progress message: control characters +/// dropped, trimmed, at most [`MAX_PROGRESS_LINE`] characters. +fn clean_line(line: &str) -> String { + let cleaned: String = line + .chars() + .map(|c| if c == '\t' { ' ' } else { c }) + .filter(|c| !c.is_control()) + .collect(); + let t = cleaned.trim(); + if t.chars().count() > MAX_PROGRESS_LINE { + let mut s: String = t.chars().take(MAX_PROGRESS_LINE - 1).collect(); + s.push('…'); + s + } else { + t.to_string() + } +} + +/// Parse the script's output: its last non-blank line is the JSON (anything +/// before it — a stray warning — is ignored). +pub fn parse_status(output: &str) -> Result { + let line = output + .lines() + .rev() + .find(|l| !l.trim().is_empty()) + .ok_or("The workspace status was empty")?; + serde_json::from_str(line.trim()).map_err(|e| format!("The workspace status could not be read: {e}")) +} + +// ───────────────────────────────────────────────────────────── reading + +/// One read of the status. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StatusRead { + Status(WorkspaceStatus), + /// No agent to ask (tunnel gone), or an image without the script. + Gone, + /// A read that failed; may be retried. + Failed(String), +} + +pub trait StatusSource: Send + Sync { + fn read(&self) -> impl Future + Send; +} + +/// The command that runs the script; exit 127 when the image predates it. +fn status_command() -> Vec { + vec![ + "sh".into(), + "-c".into(), + format!("[ -x {STATUS_SCRIPT} ] || exit 127; exec {STATUS_SCRIPT}"), + ] +} + +/// Read the status through `target`, as a background exec. +pub async fn read_status(target: &ContainerTarget) -> StatusRead { + let res = tokio::time::timeout( + READ_TIMEOUT, + target.exec_oneshot_background("claude", status_command(), STATUS_OUTPUT_LIMIT), + ) + .await; + match res { + Err(_) => StatusRead::Failed("The workspace status read timed out".into()), + Ok(Err(e)) => StatusRead::Failed(e), + Ok(Ok((out, 0))) => match parse_status(&out) { + Ok(s) => StatusRead::Status(s), + Err(e) => StatusRead::Failed(e), + }, + Ok(Ok((_, 126 | 127))) => StatusRead::Gone, + Ok(Ok((_, code))) => StatusRead::Failed(format!("The workspace status exited with {code}")), + } +} + +/// The project's registered tunnel, looked up on every read: a stop or a +/// dropped tunnel unregisters it, and the follow then ends. +struct TunnelStatusSource<'a> { + project_id: &'a str, +} + +impl StatusSource for TunnelStatusSource<'_> { + async fn read(&self) -> StatusRead { + match tunnels::get_endpoint(self.project_id) { + Some(ep) => read_status(&ContainerTarget::Agent(ep)).await, + None => StatusRead::Gone, + } + } +} + +/// The status of an AWS project's workspace for Project Home: `None` for a +/// local project, one with no tunnel, or an image without the script. +pub async fn workspace_status(project: &Project) -> Result, String> { + if !project.is_aws() { + return Ok(None); + } + match (TunnelStatusSource { project_id: &project.id }).read().await { + StatusRead::Status(s) => Ok(Some(s)), + StatusRead::Gone => Ok(None), + StatusRead::Failed(e) => Err(e), + } +} + +// ──────────────────────────────────────────────────────────── following + +#[derive(Debug, Clone, Copy)] +pub struct FollowTiming { + pub interval: Duration, + pub limit: Duration, +} + +impl Default for FollowTiming { + fn default() -> Self { + Self { interval: FOLLOW_INTERVAL, limit: FOLLOW_LIMIT } + } +} + +/// How a follow ended. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FollowEnd { + Settled { + status: WorkspaceStatus, + /// The very first read was already settled: nothing happened in + /// this follow (an attach to a workspace that finished long ago). + first_read: bool, + }, + /// [`FollowTiming::limit`] passed; the last status read, if any. + TimedOut(Option), + /// The agent went away, kept failing, or the follow was cancelled: + /// nothing to say. + Lost, +} + +/// Follow `src` until it settles, the limit passes, it is lost or `cancel` +/// fires, calling `progress` with each new progress line and each new setup +/// log line. +pub async fn follow_workspace_status( + src: &S, + total_repos: usize, + timing: FollowTiming, + cancel: &CancellationToken, + progress: &(dyn Fn(&str) + Send + Sync), +) -> FollowEnd { + tokio::select! { + biased; + _ = cancel.cancelled() => FollowEnd::Lost, + end = follow_inner(src, total_repos, timing, progress) => end, + } +} + +async fn follow_inner( + src: &S, + total_repos: usize, + timing: FollowTiming, + progress: &(dyn Fn(&str) + Send + Sync), +) -> FollowEnd { + let deadline = tokio::time::Instant::now() + timing.limit; + let mut last_line: Option = None; + let mut last_log: Option = None; + let mut last_status: Option = None; + let mut failures = 0u32; + let mut reads = 0u32; + loop { + match src.read().await { + StatusRead::Status(s) => { + failures = 0; + reads += 1; + if s.settled() { + return FollowEnd::Settled { status: s, first_read: reads == 1 }; + } + if let Some(line) = s.progress_line(total_repos) { + if last_line.as_deref() != Some(line.as_str()) { + progress(&line); + last_line = Some(line); + } + } + if s.setup.state == SetupState::Running { + if let Some(log) = s.last_log_line() { + if last_log.as_deref() != Some(log.as_str()) { + progress(&log); + last_log = Some(log); + } + } + } + last_status = Some(s); + } + StatusRead::Gone => return FollowEnd::Lost, + StatusRead::Failed(e) => { + failures += 1; + log::debug!("Workspace status read failed ({failures}): {e}"); + if failures >= MAX_READ_FAILURES { + log::info!("Stopped following the workspace's start: {e}"); + return FollowEnd::Lost; + } + } + } + if tokio::time::Instant::now() + timing.interval > deadline { + return FollowEnd::TimedOut(last_status); + } + tokio::time::sleep(timing.interval).await; + } +} + +/// What the user is told after a follow; `None` when all went well, the +/// follow was lost, or the workspace had settled before this start — +/// a failure is reported only when this follow saw it happen, or the +/// task is one this start ran (`created`). Project Home still shows an old +/// failure on demand. +pub fn follow_warning(end: &FollowEnd, limit: Duration, created: bool) -> Option { + match end { + FollowEnd::Settled { status, first_read } => { + if *first_read && !created { + None + } else { + status.problems() + } + } + FollowEnd::TimedOut(s) => { + let what = match s { + Some(s) if !s.clone.done => "still cloning its repos", + _ => "still running its setup script", + }; + let mut msg = format!( + "The workspace is {what} after {} minutes. It is running; Project Home shows the \ + progress.", + limit.as_secs() / 60 + ); + if let Some(p) = s.as_ref().and_then(WorkspaceStatus::problems) { + msg.push_str("\n\n"); + msg.push_str(&p); + } + Some(msg) + } + FollowEnd::Lost => None, + } +} + +/// The follow of one project's workspace. `follower` is its registration +/// with the tunnel registry (`tunnels::begin_follow`), made by the caller +/// before the follow is spawned so registrations keep the order of the starts +/// (a quick Stop→Start can't leave the old follower registered last). +/// `on_warning` gets the warning, if any. +pub async fn run_follow( + src: &S, + project_id: &str, + follower: (u64, CancellationToken), + total_repos: usize, + created: bool, + timing: FollowTiming, + on_warning: impl FnOnce(String), +) { + let (id, cancel) = follower; + let log_line = |m: &str| log::debug!("Project {project_id}: {m}"); + let end = follow_workspace_status(src, total_repos, timing, &cancel, &log_line).await; + tunnels::end_follow(project_id, id); + if let Some(w) = follow_warning(&end, timing.limit, created) { + on_warning(w); + } +} + +/// After a successful start of an AWS project: follow its clone and setup +/// script in the background (see the module docs). `false` (nothing +/// spawned) for a local project or one with no tunnel. +pub fn spawn_follow( + project: &Project, + on_warning: impl FnOnce(String) + Send + 'static, +) -> bool { + if !project.is_aws() || tunnels::get_endpoint(&project.id).is_none() { + return false; + } + let project_id = project.id.clone(); + let total = project.aws.as_ref().map_or(0, |a| a.repos.len()); + let created = tunnels::ran_task(&project_id); + // Registered now, not in the spawned task: see `run_follow`. + let follower = tunnels::begin_follow(&project_id); + tauri::async_runtime::spawn(async move { + let src = TunnelStatusSource { project_id: &project_id }; + run_follow(&src, &project_id, follower, total, created, FollowTiming::default(), on_warning) + .await; + }); + true +} + +#[cfg(test)] +mod tests; diff --git a/app/src-tauri/src/host/aws_host/status/tests.rs b/app/src-tauri/src/host/aws_host/status/tests.rs new file mode 100644 index 0000000..25a280f --- /dev/null +++ b/app/src-tauri/src/host/aws_host/status/tests.rs @@ -0,0 +1,285 @@ +use std::sync::Mutex; + +use super::*; +use crate::host::tunnels; + +/// Returns its scripted reads in order, then repeats the last one. +struct Scripted { + reads: Mutex>, + count: Mutex, +} + +impl Scripted { + fn new(reads: Vec) -> Self { + Self { reads: Mutex::new(reads), count: Mutex::new(0) } + } + fn count(&self) -> usize { + *self.count.lock().unwrap() + } +} + +impl StatusSource for Scripted { + async fn read(&self) -> StatusRead { + *self.count.lock().unwrap() += 1; + let mut r = self.reads.lock().unwrap(); + if r.len() > 1 { + r.remove(0) + } else { + r[0].clone() + } + } +} + +fn st(json: &str) -> StatusRead { + StatusRead::Status(parse_status(json).unwrap()) +} + +async fn follow(src: &Scripted, total: usize) -> (FollowEnd, Vec) { + let lines = Mutex::new(Vec::new()); + let progress = |m: &str| lines.lock().unwrap().push(m.to_string()); + let cancel = CancellationToken::new(); + let end = follow_workspace_status(src, total, FollowTiming::default(), &cancel, &progress).await; + (end, lines.into_inner().unwrap()) +} + +const NOT_STARTED: &str = r#"{"clone":{"done":false,"repos":[]},"setup":{"state":"running","code":null,"tail":[]}}"#; +const CLONING_1: &str = r#"{"clone":{"done":false,"repos":[{"folder":"a","state":"cloning"}]},"setup":{"state":"running","code":null,"tail":[]}}"#; +const CLONING_2: &str = r#"{"clone":{"done":false,"repos":[{"folder":"a","state":"cloned"},{"folder":"b","state":"cloning"}]},"setup":{"state":"running","code":null,"tail":[]}}"#; +const SETUP_1: &str = r#"{"clone":{"done":true,"repos":[{"folder":"a","state":"cloned"},{"folder":"b","state":"failed"}]},"setup":{"state":"running","code":null,"tail":["Reading package lists...",""," Setting up jq "]}}"#; +const SETUP_2: &str = r#"{"clone":{"done":true,"repos":[{"folder":"a","state":"cloned"},{"folder":"b","state":"failed"}]},"setup":{"state":"running","code":null,"tail":["Setting up jq","done"]}}"#; +const SETUP_FAILED: &str = r#"{"clone":{"done":true,"repos":[{"folder":"a","state":"cloned"},{"folder":"b","state":"failed"}]},"setup":{"state":"failed","code":2,"tail":["Setting up jq","E: oops"]}}"#; +const ALL_OK: &str = r#"{"clone":{"done":true,"repos":[{"folder":"a","state":"cloned"}]},"setup":{"state":"none","code":null,"tail":[]}}"#; + +#[tokio::test(start_paused = true)] +async fn follow_emits_each_change_once_and_stops_when_settled() { + let src = Scripted::new(vec![ + st(NOT_STARTED), + st(CLONING_1), + st(CLONING_1), + st(CLONING_2), + st(SETUP_1), + st(SETUP_1), + st(SETUP_2), + st(SETUP_FAILED), + ]); + let started = tokio::time::Instant::now(); + let (end, lines) = follow(&src, 2).await; + assert_eq!( + lines, + [ + "Cloning repos… (1/2)", + "Cloning repos… (2/2)", + "Running setup script…", + "Setting up jq", + "done", + ] + ); + assert_eq!(src.count(), 8); + // Seven waits of 2 s between eight reads. + assert_eq!(started.elapsed(), FOLLOW_INTERVAL * 7); + let FollowEnd::Settled { status: s, first_read: false } = &end else { panic!("{end:?}") }; + // Seen failing in this follow: reported even on an attach. + let w = follow_warning(&end, FOLLOW_LIMIT, false).unwrap(); + assert!(w.contains("Cloning failed for a repo: b."), "{w}"); + assert!(w.contains("The setup script failed (exit 2)."), "{w}"); + assert!(w.ends_with("Last lines:\nSetting up jq\nE: oops"), "{w}"); + assert_eq!(s.failed_repos(), ["b"]); +} + +#[tokio::test(start_paused = true)] +async fn a_workspace_already_settled_ends_at_once_without_a_warning() { + let src = Scripted::new(vec![st(ALL_OK)]); + let started = tokio::time::Instant::now(); + let (end, lines) = follow(&src, 1).await; + assert!(lines.is_empty()); + assert_eq!(started.elapsed(), std::time::Duration::ZERO); + assert_eq!(follow_warning(&end, FOLLOW_LIMIT, true), None); +} + +#[tokio::test(start_paused = true)] +async fn an_old_failure_warns_only_for_a_task_this_start_ran() { + let src = Scripted::new(vec![st(SETUP_FAILED)]); + let (end, lines) = follow(&src, 2).await; + assert!(lines.is_empty()); + assert!(matches!(end, FollowEnd::Settled { first_read: true, .. }), "{end:?}"); + // Attached to a workspace that failed long ago: no toast. + assert_eq!(follow_warning(&end, FOLLOW_LIMIT, false), None); + // This start ran the task and it failed before the first read. + let w = follow_warning(&end, FOLLOW_LIMIT, true).unwrap(); + assert!(w.contains("The setup script failed (exit 2)."), "{w}"); +} + +#[tokio::test(start_paused = true)] +async fn follow_times_out_after_35_minutes() { + let src = Scripted::new(vec![st(CLONING_1)]); + let started = tokio::time::Instant::now(); + let (end, lines) = follow(&src, 3).await; + assert_eq!(lines, ["Cloning repos… (1/3)"]); + assert!(matches!(end, FollowEnd::TimedOut(Some(_))), "{end:?}"); + assert!(started.elapsed() <= FOLLOW_LIMIT); + assert!(started.elapsed() > FOLLOW_LIMIT - FOLLOW_INTERVAL * 2); + let w = follow_warning(&end, FOLLOW_LIMIT, false).unwrap(); + assert!(w.contains("still cloning its repos after 35 minutes"), "{w}"); +} + +#[tokio::test(start_paused = true)] +async fn a_timed_out_setup_says_so_and_carries_any_clone_failure() { + let src = Scripted::new(vec![st(SETUP_2)]); + let (end, _) = follow(&src, 2).await; + let w = follow_warning(&end, FOLLOW_LIMIT, false).unwrap(); + assert!(w.contains("still running its setup script"), "{w}"); + assert!(w.contains("Cloning failed for a repo: b."), "{w}"); +} + +#[tokio::test(start_paused = true)] +async fn a_lost_agent_ends_the_follow_quietly() { + let src = Scripted::new(vec![st(CLONING_1), StatusRead::Gone]); + let (end, lines) = follow(&src, 1).await; + assert_eq!(end, FollowEnd::Lost); + assert_eq!(lines, ["Cloning repos… (1/1)"]); + assert_eq!(follow_warning(&end, FOLLOW_LIMIT, false), None); +} + +#[tokio::test(start_paused = true)] +async fn failing_reads_are_retried_then_give_up_quietly() { + let fail = || StatusRead::Failed("tunnel hiccup".into()); + // Four failures, then a good read: the count resets. + let src = Scripted::new(vec![fail(), fail(), fail(), fail(), st(ALL_OK)]); + assert!(matches!(follow(&src, 1).await.0, FollowEnd::Settled { .. })); + let src = Scripted::new(vec![fail()]); + let (end, _) = follow(&src, 1).await; + assert_eq!(end, FollowEnd::Lost); + assert_eq!(src.count(), MAX_READ_FAILURES as usize); +} + +#[test] +fn status_parses_the_scripts_output_and_tolerates_drift() { + let s = parse_status(&format!("a stray warning\n{SETUP_FAILED}\n\n")).unwrap(); + assert_eq!(s.setup.state, SetupState::Failed); + assert_eq!(s.setup.code, Some(2)); + assert!(s.clone.done); + // Unknown fields and states, missing fields. + let s = parse_status(r#"{"clone":{"done":true,"extra":1},"setup":{"state":"paused"},"new":{}}"#) + .unwrap(); + assert!(s.clone.repos.is_empty()); + assert_eq!(s.setup.state, SetupState::Failed); + assert_eq!(parse_status("{}").unwrap(), WorkspaceStatus::default()); + assert!(parse_status("").is_err()); + assert!(parse_status("not json").is_err()); +} + +#[test] +fn progress_lines_count_repos_and_clean_log_lines() { + let s = parse_status(NOT_STARTED).unwrap(); + assert_eq!(s.progress_line(0).as_deref(), Some("Cloning repos…")); + assert_eq!(s.progress_line(3).as_deref(), Some("Cloning repos… (1/3)")); + let s = parse_status(ALL_OK).unwrap(); + assert!(s.settled()); + assert_eq!(s.progress_line(1), None); + let mut s = parse_status(SETUP_2).unwrap(); + s.setup.tail = vec![format!("\x1b[31m{}\x1b[0m", "x".repeat(500))]; + let l = s.last_log_line().unwrap(); + assert_eq!(l.chars().count(), MAX_PROGRESS_LINE); + assert!(l.starts_with("[31mxxx") && l.ends_with('…'), "{l}"); + assert!(!l.contains('\x1b')); +} + +#[test] +fn status_serialises_in_the_scripts_shape() { + let s = parse_status(SETUP_FAILED).unwrap(); + let v = serde_json::to_value(&s).unwrap(); + assert_eq!(v, serde_json::from_str::(SETUP_FAILED).unwrap()); +} + +#[test] +fn the_status_command_reports_a_missing_script_as_127() { + let cmd = status_command(); + assert_eq!(cmd[..2], ["sh", "-c"]); + assert!(cmd[2].contains("|| exit 127") && cmd[2].contains(STATUS_SCRIPT)); +} + +#[tokio::test] +async fn a_local_project_has_no_workspace_status_and_no_follower() { + let p = Project::new("p".into(), vec![]); + assert_eq!(workspace_status(&p).await, Ok(None)); + assert!(!spawn_follow(&p, |_| panic!("no warning for Docker"))); + assert!(!tunnels::is_following(&p.id)); +} + +/// Never answers: a follow in progress until something ends it. +struct Hang; +impl StatusSource for Hang { + async fn read(&self) -> StatusRead { + std::future::pending().await + } +} + +#[tokio::test(start_paused = true)] +async fn stop_ends_a_follow_in_progress_without_a_warning() { + let id = "follow-stop-test"; + let task = tokio::spawn(async move { + let warned = std::sync::Arc::new(Mutex::new(false)); + let w = warned.clone(); + let follower = tunnels::begin_follow(id); + run_follow(&Hang, id, follower, 1, true, FollowTiming::default(), move |_| { + *w.lock().unwrap() = true + }) + .await; + let v = *warned.lock().unwrap(); + v + }); + tokio::time::sleep(FOLLOW_INTERVAL * 3).await; + assert!(tunnels::is_following(id)); + // What Stop and Remove call (`stop_project_container`, `stop_project`, + // `remove_resources`); closing the tunnel does the same. + tunnels::cancel_follow(id); + let warned = tokio::time::timeout(std::time::Duration::from_secs(1), task) + .await + .expect("the follow ends at once") + .unwrap(); + assert!(!warned); + assert!(!tunnels::is_following(id)); +} + +#[tokio::test(start_paused = true)] +async fn a_new_follow_replaces_the_old_one() { + let id = "follow-replace-test"; + let follower = tunnels::begin_follow(id); + let first = tokio::spawn(run_follow(&Hang, id, follower, 1, true, FollowTiming::default(), |_| {})); + tokio::time::sleep(FOLLOW_INTERVAL).await; + let (_, second) = tunnels::begin_follow(id); + tokio::time::timeout(std::time::Duration::from_secs(1), first).await.unwrap().unwrap(); + // The old follower's end does not unregister the new one. + assert!(tunnels::is_following(id)); + assert!(!second.is_cancelled()); + tunnels::cancel_follow(id); + assert!(second.is_cancelled()); +} + +#[tokio::test(start_paused = true)] +async fn followers_registered_in_start_order_win_in_that_order_however_they_are_scheduled() { + // A quick Stop→Start: the old start's follower is registered first, the + // new one second, but the new one's task happens to run first. + let id = "follow-order-test"; + let old = tunnels::begin_follow(id); + let new = tunnels::begin_follow(id); + let new_token = new.1.clone(); + let new_task = tokio::spawn(run_follow(&Hang, id, new, 1, true, FollowTiming::default(), |_| {})); + tokio::time::sleep(FOLLOW_INTERVAL).await; + let old_task = tokio::spawn(run_follow(&Hang, id, old, 1, true, FollowTiming::default(), |_| {})); + // The old one was cancelled at registration: it ends at once and leaves + // the new one registered and running. + tokio::time::timeout(std::time::Duration::from_secs(1), old_task).await.unwrap().unwrap(); + assert!(tunnels::is_following(id)); + assert!(!new_token.is_cancelled()); + assert!(!new_task.is_finished()); + tunnels::cancel_follow(id); + tokio::time::timeout(std::time::Duration::from_secs(1), new_task).await.unwrap().unwrap(); +} + +#[test] +fn the_follower_takes_no_project_lock() { + // Stop must never wait for it (ruling R5). + let src = include_str!("../status.rs"); + assert!(!src.contains("project_lock")); +} diff --git a/app/src-tauri/src/host/aws_host/tests.rs b/app/src-tauri/src/host/aws_host/tests.rs index 220934e..48c19f0 100644 --- a/app/src-tauri/src/host/aws_host/tests.rs +++ b/app/src-tauri/src/host/aws_host/tests.rs @@ -155,11 +155,26 @@ impl WorkspaceApi for Fake { async fn create_access_point( &self, _fs: &str, - _root: &str, + root: &str, _tags: &[(String, String)], ) -> Result { self.log("create-ap"); - Ok("fsap-new".into()) + Ok(if root.starts_with("/triple-c-workspaces/") { "fsap-ws" } else { "fsap-new" }.into()) + } + async fn project_secret_value(&self, _name: &str) -> Result, AwsError> { + Ok(None) + } + async fn create_project_secret( + &self, + n: &str, + k: &str, + j: &str, + t: &[(String, String)], + ) -> Result, AwsError> { + self.put_project_secret(n, k, j, t).await.map(Some) + } + async fn delete_project_secret(&self, _name: &str) -> Result<(), AwsError> { + Ok(()) } async fn put_project_secret( &self, @@ -247,6 +262,10 @@ impl Connector for Fake { } } +fn no_gateway() -> Result, String> { + Ok(None) +} + fn inputs<'a>( p: &'a Project, who: &'a CallerIdentity, @@ -258,7 +277,9 @@ fn inputs<'a>( who, env_pairs: &[], files: &[], + custom_env_keys: &[], image: REGISTRY_IMAGE, + gateway: &no_gateway, wait: WaitTiming { interval: Duration::from_millis(1), timeout: Duration::from_millis(30), @@ -309,6 +330,76 @@ async fn a_first_start_prepares_runs_waits_and_connects_in_that_order() { ); } +#[tokio::test] +async fn an_efs_start_waits_for_both_access_points_and_records_them() { + let p = aws_project(StorageMode::Efs); + let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), ..Default::default() }; + let w = who(); + let records = Mutex::new(Vec::new()); + let on_task = |r: Option<&TaskRecord>| records.lock().unwrap().push(r.cloned()); + let started = start_core(&fake, &fake, &fake, &fake, &inputs(&p, &w, &on_task), &|_| {}) + .await + .unwrap(); + assert_eq!(started.access_point_id.as_deref(), Some("fsap-new")); + assert_eq!(started.workspace_access_point_id.as_deref(), Some("fsap-ws")); + let calls = fake.calls(); + let pos = |c: &str| calls.iter().position(|x| x == c).unwrap_or_else(|| panic!("{c}: {calls:?}")); + assert!(pos("ap-state fsap-new") < pos("run"), "{calls:?}"); + assert!(pos("ap-state fsap-ws") < pos("run"), "{calls:?}"); + let recs = records.into_inner().unwrap(); + let rec = recs[0].as_ref().unwrap(); + assert_eq!(rec.access_point_id.as_deref(), Some("fsap-new")); + assert_eq!(rec.workspace_access_point_id.as_deref(), Some("fsap-ws")); + + // Hybrid waits for one and records none for /workspace. + let p = aws_project(StorageMode::Hybrid); + let fake = Fake { run: Some(task(&p, "new", "RUNNING", true)), ..Default::default() }; + let records = Mutex::new(Vec::new()); + let on_task = |r: Option<&TaskRecord>| records.lock().unwrap().push(r.cloned()); + let started = start_core(&fake, &fake, &fake, &fake, &inputs(&p, &w, &on_task), &|_| {}) + .await + .unwrap(); + assert_eq!(started.workspace_access_point_id, None); + assert!(!fake.called("ap-state fsap-ws")); + assert_eq!(records.into_inner().unwrap()[0].as_ref().unwrap().workspace_access_point_id, None); +} + +#[test] +fn switching_efs_to_hybrid_keeps_the_stored_workspace_access_point() { + let mut p = aws_project(StorageMode::Hybrid); + p.aws.as_mut().unwrap().workspace_access_point_id = Some("fsap-ws".into()); + let (_d, store) = store_with(&p); + // A Hybrid start knows no /workspace access point: the stored one stays. + record_task( + &store, + &p.id, + Some(&TaskRecord { + task_arn: "arn:t".into(), + access_point_id: Some("fsap-home".into()), + task_definition_arn: None, + workspace_access_point_id: None, + }), + ); + let a = store.get(&p.id).unwrap().aws.unwrap(); + assert_eq!(a.workspace_access_point_id.as_deref(), Some("fsap-ws")); + record_task(&store, &p.id, None); + let a = store.get(&p.id).unwrap().aws.unwrap(); + assert_eq!(a.workspace_access_point_id.as_deref(), Some("fsap-ws")); + // An EFS start records its own. + record_task( + &store, + &p.id, + Some(&TaskRecord { + task_arn: "arn:t2".into(), + access_point_id: None, + task_definition_arn: None, + workspace_access_point_id: Some("fsap-ws2".into()), + }), + ); + let a = store.get(&p.id).unwrap().aws.unwrap(); + assert_eq!(a.workspace_access_point_id.as_deref(), Some("fsap-ws2")); +} + #[tokio::test] async fn a_running_task_is_attached_with_its_own_token_and_nothing_is_rewritten() { let p = aws_project(StorageMode::Hybrid); @@ -327,6 +418,35 @@ async fn a_running_task_is_attached_with_its_own_token_and_nothing_is_rewritten( assert_eq!(steps, vec![PROGRESS_READING, PROGRESS_WAITING, PROGRESS_CONNECTING]); } +/// A gateway payload that cannot be built: the provider key is gone. +fn missing_gateway_key() -> Result, String> { + Err("The LLM gateway sidecar needs the provider API key".into()) +} + +#[tokio::test] +async fn attaching_to_a_running_task_never_builds_the_gateway_payload() { + let mut p = aws_project(StorageMode::Hybrid); + p.aws.as_mut().unwrap().gateway_sidecar = true; + let live = task(&p, "live", "RUNNING", true); + let fake = Fake { + listed: Mutex::new(vec![vec![live.arn.clone()]]), + ..Default::default() + } + .with_task(live); + let w = who(); + let on_task = |_: Option<&TaskRecord>| {}; + let inp = StartInputs { gateway: &missing_gateway_key, ..inputs(&p, &w, &on_task) }; + let started = start_core(&fake, &fake, &fake, &fake, &inp, &|_| {}).await.unwrap(); + assert!(!started.created); + + // A start that prepares a new task does need it, and fails before RunTask. + let fake = Fake::default(); + let inp = StartInputs { gateway: &missing_gateway_key, ..inputs(&p, &w, &on_task) }; + let e = start_core(&fake, &fake, &fake, &fake, &inp, &|_| {}).await.err().unwrap(); + assert!(e.contains("provider API key"), "{e}"); + assert!(!fake.called("run")); +} + #[tokio::test] async fn losing_the_run_race_is_a_clear_error_and_nothing_is_stopped() { let p = aws_project(StorageMode::Ephemeral); @@ -666,7 +786,12 @@ fn a_start_records_its_task_and_keeps_the_stored_handles_it_does_not_know() { record_task( &store, &p.id, - Some(&TaskRecord { task_arn: "arn:t".into(), access_point_id: None, task_definition_arn: Some("arn:td:2".into()) }), + Some(&TaskRecord { + task_arn: "arn:t".into(), + access_point_id: None, + task_definition_arn: Some("arn:td:2".into()), + workspace_access_point_id: None, + }), ); let a = store.get(&p.id).unwrap().aws.unwrap(); assert_eq!((a.task_arn.as_deref(), a.access_point_id.as_deref(), a.task_definition_arn.as_deref()), @@ -720,7 +845,12 @@ fn the_log_task_is_the_stored_one_else_the_last_one_a_start_saw() { record_task( &store, &p.id, - Some(&TaskRecord { task_arn: "arn:first".into(), access_point_id: None, task_definition_arn: None }), + Some(&TaskRecord { + task_arn: "arn:first".into(), + access_point_id: None, + task_definition_arn: None, + workspace_access_point_id: None, + }), ); record_task(&store, &p.id, None); assert_eq!(log_task_arn(&p).as_deref(), Some("arn:first"), "a cleared ARN still has a log"); @@ -795,3 +925,319 @@ async fn an_unattached_aws_project_gets_a_target_id_no_tunnel_can_have() { let local = Project::new("l".into(), Vec::new()); assert_eq!(unattached_container_id(&local), None); } + +#[tokio::test] +async fn a_persisted_starting_aws_project_with_a_task_arn_is_reconciled_against_ecs_on_load() { + use crate::commands::project_commands::needs_aws_reconcile; + use crate::storage::projects_store::settle_stale_statuses; + + // The app quit mid-start: Starting, the task's ARN already recorded. + let mut p = aws_project(StorageMode::Hybrid); + p.status = ProjectStatus::Starting; + p.aws.as_mut().unwrap().task_arn = Some(task_arn("mid")); + let mut docker = Project::new("local".into(), vec![]); + docker.status = ProjectStatus::Starting; + + let mut loaded = vec![p.clone(), docker]; + assert!(settle_stale_statuses(&mut loaded)); + // Not Stopped (that would hide a billed task): Error, ARN kept. + assert_eq!(loaded[0].status, ProjectStatus::Error); + assert_eq!(loaded[0].aws.as_ref().unwrap().task_arn, Some(task_arn("mid"))); + assert_eq!(loaded[1].status, ProjectStatus::Stopped, "Docker is unchanged"); + assert!(needs_aws_reconcile(&loaded[0])); + + // ECS says it runs: Running. + let p = loaded[0].clone(); + let fake = Fake::default().with_task(task(&p, "mid", "RUNNING", true)); + let (_d, store) = store_with(&p); + assert!(matches!(reconcile_project(&fake, &store, &p, &find(&p)).await.unwrap(), Reconciled::Live(_))); + assert_eq!(store.get(&p.id).unwrap().status, ProjectStatus::Running); + // ECS says it is gone: Stopped, ARN cleared. + let (_d, store) = store_with(&p); + assert_eq!(reconcile_project(&Fake::default(), &store, &p, &find(&p)).await.unwrap(), Reconciled::Gone); + let after = store.get(&p.id).unwrap(); + assert_eq!(after.status, ProjectStatus::Stopped); + assert_eq!(after.aws.unwrap().task_arn, None); +} + +#[test] +fn a_stopped_aws_project_is_reconciled_only_when_it_still_has_a_task_arn() { + use crate::commands::project_commands::needs_aws_reconcile; + let mut p = aws_project(StorageMode::Hybrid); + p.status = ProjectStatus::Stopped; + assert!(!needs_aws_reconcile(&p), "a clean stop clears the ARN"); + p.aws.as_mut().unwrap().task_arn = Some(task_arn("left")); + assert!(needs_aws_reconcile(&p)); + for s in [ProjectStatus::Running, ProjectStatus::Error, ProjectStatus::Starting, ProjectStatus::Stopping] { + p.status = s; + p.aws.as_mut().unwrap().task_arn = None; + assert!(needs_aws_reconcile(&p)); + } +} + +// ──────────────────────────────────────────── copy-at-connect (Q2) + +mod copy_at_connect { + use super::*; + use crate::host::aws_host::connect::*; + use crate::models::project::SecretsDelivery; + use crate::models::EnvVar; + + fn connect_project(delivery: SecretsDelivery) -> Project { + let mut p = aws_project(StorageMode::Hybrid); + p.aws.as_mut().unwrap().secrets_delivery = delivery; + p + } + + /// `(dir, name, data, mode)`. + type Upload = (String, String, Vec, u32); + + #[derive(Default)] + struct FakeTarget { + calls: Mutex>, + uploads: Mutex>, + apply_result: Mutex>, + } + + impl ConnectTarget for FakeTarget { + async fn exec_root(&self, cmd: Vec) -> Result<(String, i64), String> { + self.calls.lock().unwrap().push(format!("exec {}", cmd.join(" "))); + if cmd.get(1).map(String::as_str) == Some("--prepare") { + return Ok(("0123456789abcdef\n".into(), 0)); + } + if let Some(r) = self.apply_result.lock().unwrap().clone() { + return Ok(r); + } + Ok(("triple-c-apply-connect: credentials applied\n".into(), 0)) + } + async fn upload_root(&self, dir: &str, name: &str, data: &[u8], mode: u32) -> Result<(), String> { + self.calls.lock().unwrap().push(format!("upload {dir}/{name}")); + self.uploads.lock().unwrap().push((dir.into(), name.into(), data.to_vec(), mode)); + Ok(()) + } + } + + fn bundle() -> ConnectBundle { + ConnectBundle { + files: vec![ + ("ssh/id_ed25519".into(), b"PRIVATE".to_vec().into()), + ("ca/corp.crt".into(), b"PEM".to_vec().into()), + ], + env: vec![ + ("GIT_TOKEN".into(), String::from("ghp_x").into()), + ("MULTI".into(), String::from("a=b\nc").into()), + ], + } + } + + #[tokio::test] + async fn a_push_prepares_uploads_root_only_then_applies() { + let t = FakeTarget::default(); + push_connect_bundle(&t, &bundle()).await.unwrap(); + assert_eq!( + *t.calls.lock().unwrap(), + vec![ + "exec /usr/local/bin/triple-c-apply-connect --prepare", + "upload /dev/shm/triple-c/connect/0123456789abcdef/ssh/id_ed25519", + "upload /dev/shm/triple-c/connect/0123456789abcdef/ca/corp.crt", + "upload /dev/shm/triple-c/connect/0123456789abcdef/connect.env", + "exec /usr/local/bin/triple-c-apply-connect 0123456789abcdef", + ] + ); + let uploads = t.uploads.lock().unwrap(); + assert!(uploads.iter().all(|u| u.3 == 0o600), "every staged file is 0600"); + assert_eq!(uploads[0].2, b"PRIVATE"); + // KEY= lines: a newline or `=` in a value reads back whole. + assert_eq!( + String::from_utf8(uploads[2].2.clone()).unwrap(), + "GIT_TOKEN=Z2hwX3g=\nMULTI=YT1iCmM=\n" + ); + } + + #[tokio::test] + async fn a_failed_apply_reports_its_output_and_an_old_image_says_so() { + let t = FakeTarget::default(); + *t.apply_result.lock().unwrap() = Some(("line\ntriple-c-apply-connect: /x is missing\n".into(), 1)); + let e = push_connect_bundle(&t, &bundle()).await.unwrap_err(); + assert!(e.contains("failed (1)") && e.contains("/x is missing"), "{e}"); + assert!(!e.contains("ghp_x")); + + let t = FakeTarget::default(); + *t.apply_result.lock().unwrap() = Some(("not found".into(), 127)); + let e = push_connect_bundle(&t, &bundle()).await.unwrap_err(); + assert!(e.contains("predates copying credentials"), "{e}"); + + // A bad file key is refused before anything is uploaded under it. + let t = FakeTarget::default(); + let bad = ConnectBundle { files: vec![("ssh/../x".into(), Vec::new().into())], env: vec![] }; + assert!(push_connect_bundle(&t, &bad).await.is_err()); + assert!(t.uploads.lock().unwrap().is_empty()); + } + + #[test] + fn only_a_well_formed_connect_id_is_used_as_a_path() { + assert_eq!(parse_nonce("noise\n0123456789abcdef\n").unwrap(), "0123456789abcdef"); + for bad in ["", "../../etc/passwd", "0123456789ABCDEF", "0123456789abcde", "0123456789abcdef0"] { + assert!(parse_nonce(bad).is_err(), "{bad}"); + } + } + + #[test] + fn a_bundle_never_shows_its_values() { + let shown = format!("{:?}", bundle()); + assert!(shown.contains("GIT_TOKEN") && shown.contains("ssh/id_ed25519"), "{shown}"); + assert!(!shown.contains("ghp_x") && !shown.contains("PRIVATE"), "{shown}"); + } + + #[test] + fn the_bundle_is_the_ssh_and_ca_files_and_the_credential_variables() { + let base = tempfile::tempdir().unwrap(); + let ssh = base.path().join("ssh"); + std::fs::create_dir(&ssh).unwrap(); + std::fs::write(ssh.join("id_ed25519"), b"KEY").unwrap(); + let mut p = connect_project(SecretsDelivery::CopyAtConnect); + p.ssh_key_path = Some(ssh.to_str().unwrap().into()); + p.git_token = Some("ghp_tok".into()); + p.custom_env_vars = vec![EnvVar { key: "MY_KEY".into(), value: "v1".into() }]; + let settings = AppSettings { + global_custom_env_vars: vec![EnvVar { key: "GLOBAL_KEY".into(), value: "g".into() }], + ..Default::default() + }; + let b = connect_credentials(&p, &settings).unwrap(); + assert_eq!(b.files.len(), 1); + assert_eq!((b.files[0].0.as_str(), b.files[0].1.as_slice()), ("ssh/id_ed25519", &b"KEY"[..])); + let env: HashMap = b.env.iter().map(|(k, v)| (k.clone(), v.to_string())).collect(); + assert_eq!(env["GIT_TOKEN"], "ghp_tok"); + assert_eq!(env["MY_KEY"], "v1"); + assert_eq!(env["GLOBAL_KEY"], "g"); + assert!(!env.contains_key("TZ") && !env.contains_key("CLAUDE_CODE_SETTINGS_JSON")); + assert!(b.env.iter().all(|(k, _)| crate::aws::workspace::is_credential_key( + k, + &["MY_KEY".to_string(), "GLOBAL_KEY".to_string()] + ))); + } + + #[test] + fn a_terminal_gets_the_api_keys_even_when_a_file_is_unreadable() { + let mut p = connect_project(SecretsDelivery::CopyAtConnect); + p.ssh_key_path = Some("/nonexistent/ssh-dir".into()); + p.ca_cert_path = Some("/nonexistent/ca.pem".into()); + p.git_token = Some("ghp_tok".into()); + let settings = AppSettings::default(); + assert!(connect_credentials(&p, &settings).is_err(), "the push needs the files"); + let env: HashMap = + connect_env(&p, &settings).into_iter().map(|(k, v)| (k, v.to_string())).collect(); + assert_eq!(env["GIT_TOKEN"], "ghp_tok"); + } + + #[test] + fn a_copy_at_connect_terminal_carries_the_credentials_and_a_secrets_manager_one_does_not() { + let creds = || Ok(bundle().env); + let p = connect_project(SecretsDelivery::CopyAtConnect); + let spec = crate::host::sessions::session_spec( + vec!["bash".into(), "-l".into()], + true, + terminal_env_with(&p, creds), + ); + assert_eq!(spec.env, vec!["GIT_TOKEN=ghp_x".to_string(), "MULTI=a=b\nc".to_string()]); + assert!(spec.tty && spec.user == "claude"); + assert_eq!(spec.working_dir.as_deref(), Some("/workspace")); + + let p = connect_project(SecretsDelivery::SecretsManager); + let env = terminal_env_with(&p, || panic!("not gathered for Secrets Manager")); + assert!(crate::host::sessions::session_spec(vec!["bash".into()], true, env).env.is_empty()); + + // A local project never; a failure opens the terminal without them. + let mut local = connect_project(SecretsDelivery::CopyAtConnect); + local.host_id = None; + assert!(terminal_env_with(&local, || panic!("local")).is_empty()); + let p = connect_project(SecretsDelivery::CopyAtConnect); + assert!(terminal_env_with(&p, || Err("no CA file".into())).is_empty()); + } + + #[test] + fn only_a_connected_copy_at_connect_project_gets_a_push() { + let p = connect_project(SecretsDelivery::SecretsManager); + assert!(!copies_at_connect(&p)); + assert!(!spawn_connect_push(&p, &AppSettings::default(), |_| panic!("no push"))); + let p = connect_project(SecretsDelivery::CopyAtConnect); + assert!(copies_at_connect(&p)); + // 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-tauri/src/host/lifecycle.rs b/app/src-tauri/src/host/lifecycle.rs index df81e45..f1fdd5f 100644 --- a/app/src-tauri/src/host/lifecycle.rs +++ b/app/src-tauri/src/host/lifecycle.rs @@ -132,7 +132,7 @@ impl ProjectHost { /// AWS: stop the task and remove the project's resources — task /// definition revisions, the secret (deleted at once) and, only - /// with `discard_data`, the EFS access point (not its files). Docker: nothing (its state + /// with `discard_data`, the EFS access points, home and EFS-mode `/workspace` (not their files). Docker: nothing (its state /// goes with [`Self::discard_project_state`]). pub async fn remove_aws_resources( &self, diff --git a/app/src-tauri/src/host/mod.rs b/app/src-tauri/src/host/mod.rs index 6882030..45c049c 100644 --- a/app/src-tauri/src/host/mod.rs +++ b/app/src-tauri/src/host/mod.rs @@ -30,6 +30,7 @@ pub mod agent; pub mod aws_host; pub mod lifecycle; +pub mod port_forwards; pub mod sessions; pub mod ssm; pub mod tunnels; diff --git a/app/src-tauri/src/host/port_forwards.rs b/app/src-tauri/src/host/port_forwards.rs new file mode 100644 index 0000000..4cb0b77 --- /dev/null +++ b/app/src-tauri/src/host/port_forwards.rs @@ -0,0 +1,390 @@ +//! A project's port mappings on a host with no Docker port publishing (AWS). +//! +//! Docker publishes a mapping itself (`0.0.0.0:` → the container's +//! network interface). A Fargate task has no such thing, so each TCP mapping +//! becomes a host **loopback** listener (`127.0.0.1` and `::1`, never a +//! wildcard) carried into the task over `socat` on an attached exec — the +//! auth bridge's [`PortForward`], which works through the agent like any +//! other exec (constraints Q6). Nothing is published beyond this machine, +//! and the UI says so. +//! +//! ## Two differences from Docker, both deliberate +//! +//! * **It reaches the workspace's loopback, not its network interface** +//! (`socat … TCP:127.0.0.1:` inside the task). So a mapping can +//! reach a service that bound loopback precisely to be private — which is +//! why the agent's port, the browser view's range and (when the project +//! runs it) the gateway sidecar's [`GATEWAY_SIDECAR_PORT`] are refused. +//! * **No gate** ([`PortForward::bind_mapping`]): unlike the auth bridge, a +//! client need not speak first and an HTTP request is not checked for a +//! cross-site origin — Docker's publishing has neither, and a +//! server-speaks-first protocol (MySQL, SMTP) must work. What a mapping +//! exposes is what the user chose to expose, to this machine only. +//! +//! The tunnel's bounds still apply: 16 concurrent connections per mapping, +//! and a connection the workspace sends nothing on for 600 s is closed. +//! +//! ## Lifetime +//! +//! One set per project, opened after every connect (the start, and the +//! background re-attach after an app restart) and on a save of the mappings +//! while connected. Opens are serialised per project and re-read the stored +//! mappings under that lock, so the last save wins; an open keeps the +//! forwards it already has for an unchanged mapping (with their live +//! connections) and rebinds everything when the tunnel changed. The set is +//! closed with the project's tunnel — `tunnels::close`, `close_if_task` (the +//! task died) and `close_all` (app exit) call [`close`] / [`close_all`] — so +//! Stop, Remove, a task death and exit need nothing of their own. +//! +//! ## Idle stop +//! +//! An open listener costs the workspace nothing: no agent request is made +//! until a client connects. A connection is an attach, which counts as +//! activity while bytes flow — a client using a mapping keeps the workspace +//! from its idle stop; one connected but silent does not. + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; + +use crate::auth_bridge::proc_net::PortFamily; +use crate::auth_bridge::tunnel::PortForward; +use crate::auth_bridge::{RESERVED_CONTAINER_PORTS, RESERVED_HOST_PORTS}; +use crate::models::PortMapping; +use crate::storage::projects_store::ProjectsStore; + +use super::ContainerTarget; + +/// What became of one mapping: `error` is `None` when its forward is open. +#[derive(Debug, Clone, PartialEq)] +pub struct PortForwardResult { + pub mapping: PortMapping, + pub error: Option, +} + +/// The container port the gateway sidecar (Task 8, `gateway_sidecar`) +/// listens on, on the workspace's loopback. +pub const GATEWAY_SIDECAR_PORT: u16 = 4000; + +/// A project's open forwards and the target (tunnel endpoint) they lead to. +struct OpenSet { + target_id: String, + forwards: Vec, +} + +type Registry = HashMap; + +fn registry() -> &'static Mutex { + static R: std::sync::OnceLock> = std::sync::OnceLock::new(); + R.get_or_init(Default::default) +} + +fn lock() -> std::sync::MutexGuard<'static, Registry> { + registry().lock().unwrap_or_else(|e| e.into_inner()) +} + +/// The per-project lock every open and close holds, so two opens (a save on +/// every blur, a save during a start's open) never interleave. +fn project_lock(project_id: &str) -> Arc> { + static L: std::sync::OnceLock>>>> = + std::sync::OnceLock::new(); + L.get_or_init(Default::default) + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(project_id.to_string()) + .or_default() + .clone() +} + +/// Why one mapping can't be forwarded to an AWS workspace, if it can't. +/// `None` when it is fine. +fn mapping_problem(m: &PortMapping, gateway_sidecar: bool) -> Option { + if !m.protocol.eq_ignore_ascii_case("tcp") { + return Some(format!( + "{} → {} ({}): only TCP ports can be forwarded to an AWS workspace", + m.host_port, + m.container_port, + m.protocol.to_ascii_uppercase() + )); + } + if RESERVED_CONTAINER_PORTS.contains(&m.container_port) { + return Some(format!( + "Container port {} is reserved for the browser view ({}–{})", + m.container_port, + RESERVED_CONTAINER_PORTS.start(), + RESERVED_CONTAINER_PORTS.end() + )); + } + if m.container_port == super::ssm::AGENT_PORT { + return Some(format!( + "Container port {} is the workspace agent's own port", + super::ssm::AGENT_PORT + )); + } + if gateway_sidecar && m.container_port == GATEWAY_SIDECAR_PORT { + return Some(format!( + "Container port {GATEWAY_SIDECAR_PORT} is the gateway sidecar's, which holds the \ + model provider's key" + )); + } + if RESERVED_HOST_PORTS.contains(&m.host_port) { + return Some(format!( + "Host port {} is reserved for the browser view ({}–{})", + m.host_port, + RESERVED_HOST_PORTS.start(), + RESERVED_HOST_PORTS.end() + )); + } + None +} + +/// A row the editor saved before both its ports were typed (the editor +/// saves on blur): nothing to check or forward yet, and nothing to say. +fn incomplete(m: &PortMapping) -> bool { + m.host_port == 0 || m.container_port == 0 +} + +/// An AWS project's port mappings, checked in full: TCP only, no reserved +/// port (the browser view's two ranges, the agent's port, the gateway +/// sidecar's when it runs), and no host port twice. The first problem, +/// worded for the user. +pub fn validate_aws_port_mappings(mappings: &[PortMapping], gateway_sidecar: bool) -> Result<(), String> { + validate_changed(mappings, gateway_sidecar, |_| true) +} + +/// [`validate_aws_port_mappings`] on a save, against what is stored: +/// `stored` is `None` when the project was not on AWS before (everything is +/// checked). Otherwise only rows the save adds or edits are — a stored row +/// this check would refuse (a UDP mapping kept from before) does not block +/// every unrelated save; it is skipped, with a warning, at each connect. +/// Turning the gateway sidecar on checks everything again. +pub fn validate_aws_port_mappings_update( + stored: Option<(&[PortMapping], bool)>, + mappings: &[PortMapping], + gateway_sidecar: bool, +) -> Result<(), String> { + match stored { + Some((old, old_gateway)) if old_gateway == gateway_sidecar => { + validate_changed(mappings, gateway_sidecar, |m| !old.contains(m)) + } + _ => validate_aws_port_mappings(mappings, gateway_sidecar), + } +} + +fn validate_changed( + mappings: &[PortMapping], + gateway_sidecar: bool, + changed: impl Fn(&PortMapping) -> bool, +) -> Result<(), String> { + let mut seen: HashMap = HashMap::new(); + for m in mappings.iter().filter(|m| !incomplete(m)) { + let is_changed = changed(m); + if is_changed { + if let Some(problem) = mapping_problem(m, gateway_sidecar) { + return Err(problem); + } + } + match seen.get(&m.host_port) { + Some(&other_changed) if is_changed || other_changed => { + return Err(format!("Host port {} is mapped twice", m.host_port)) + } + Some(_) => {} + None => { + seen.insert(m.host_port, is_changed); + } + } + } + Ok(()) +} + +/// Whether `target` is still the project's connected workspace. +fn still_connected(project_id: &str, target: &ContainerTarget) -> bool { + match target { + ContainerTarget::Agent(ep) => { + super::tunnels::get_endpoint(project_id).is_some_and(|e| e.base_url == ep.base_url) + } + ContainerTarget::Docker { .. } => false, + } +} + +/// Open `mappings` for `project_id` into `target` (its connected workspace). +/// See [`open_latest`]; the gateway sidecar is taken as off. Test helper. +#[cfg(test)] +pub async fn open_for( + project_id: &str, + target: &ContainerTarget, + mappings: &[PortMapping], +) -> Vec { + let mappings = mappings.to_vec(); + open_latest(project_id, target, move || Some((mappings, false))).await +} + +/// Open the project's mappings into `target`, replacing the set it had. +/// `read` gives the mappings and whether the gateway sidecar runs, and is +/// called **under the project's lock** — so the last of several overlapping +/// opens applies what is stored last. `None` from it closes the set. +/// +/// One result per mapping, in order: a refused mapping, a host port mapped +/// twice or a busy host port is an error for that mapping only, and the +/// others still open. A mapping already open into the same target is kept, +/// live connections and all. If the project's tunnel is no longer `target` +/// once they are bound (a Stop or a newer connect raced this), nothing is +/// kept. +pub async fn open_latest( + project_id: &str, + target: &ContainerTarget, + read: impl FnOnce() -> Option<(Vec, bool)> + Send, +) -> Vec { + let plock = project_lock(project_id); + let _held = plock.lock().await; + let Some((mappings, gateway_sidecar)) = read() else { + close_unlocked(project_id).await; + return Vec::new(); + }; + + // What can be forwarded, in order; the first row wins a host port. + let mut results: Vec = Vec::new(); + let mut wanted: Vec<(usize, u16, u16)> = Vec::new(); + let mut taken = HashSet::new(); + for m in mappings.iter().filter(|m| !incomplete(m)) { + let error = if let Some(problem) = mapping_problem(m, gateway_sidecar) { + Some(problem) + } else if !taken.insert(m.host_port) { + Some(format!( + "{} → {}: host port {} is already used by another mapping", + m.host_port, m.container_port, m.host_port + )) + } else { + wanted.push((results.len(), m.host_port, m.container_port)); + None + }; + results.push(PortForwardResult { mapping: m.clone(), error }); + } + + // Keep what is already open into this target and still wanted; free + // every other host port first, so a changed mapping can rebind it. + let previous = lock().remove(project_id); + let mut kept: HashMap<(u16, u16), PortForward> = HashMap::new(); + let mut dropped = Vec::new(); + if let Some(prev) = previous { + let same_target = prev.target_id == target.id(); + for f in prev.forwards { + let key = (f.port, f.container_port); + if same_target && wanted.iter().any(|&(_, h, c)| (h, c) == key) { + kept.insert(key, f); + } else { + dropped.push(f); + } + } + } + shutdown_all(dropped).await; + + let mut opened = Vec::new(); + for (i, host_port, container_port) in wanted { + if let Some(f) = kept.remove(&(host_port, container_port)) { + opened.push(f); + continue; + } + match PortForward::bind_mapping(target.clone(), host_port, container_port, PortFamily::V4).await { + Ok(fwd) => { + if let Some(w) = &fwd.ipv6_warning { + log::warn!("Project {project_id}: port mapping {host_port}: {w}"); + } + log::info!( + "Project {project_id}: forwarding localhost:{host_port} → workspace port {container_port}" + ); + opened.push(fwd); + } + Err(e) => { + results[i].error = Some(if e.kind() == std::io::ErrorKind::AddrInUse { + format!( + "{host_port} → {container_port}: host port {host_port} is already in use on this machine" + ) + } else { + format!("{host_port} → {container_port}: could not listen on host port {host_port}: {e}") + }); + } + } + } + + lock().insert( + project_id.to_string(), + OpenSet { target_id: target.id().to_string(), forwards: opened }, + ); + // Checked *after* the set is registered: a tunnel close that ran before + // this sees it gone here; one that runs after removes it itself. + if !still_connected(project_id, target) { + close_unlocked(project_id).await; + for r in results.iter_mut().filter(|r| r.error.is_none()) { + r.error = Some("the workspace disconnected".into()); + } + } + results +} + +async fn shutdown_all(set: Vec) { + futures_util::future::join_all(set.into_iter().map(|mut f| async move { f.shutdown().await })) + .await; +} + +/// Close the project's forwards (its ports are free when this returns). +/// Waits for an open in progress. +pub async fn close(project_id: &str) { + let plock = project_lock(project_id); + let _held = plock.lock().await; + close_unlocked(project_id).await; +} + +async fn close_unlocked(project_id: &str) { + let set = lock().remove(project_id); + if let Some(set) = set { + shutdown_all(set.forwards).await; + } +} + +/// Close every project's forwards. The shutdown path's step (via +/// `tunnels::close_all`). An open in progress finds the tunnel gone and +/// closes its own set. +pub async fn close_all() { + let all: Vec = lock().drain().flat_map(|(_, v)| v.forwards).collect(); + shutdown_all(all).await; +} + +/// After a connect (or a save of the mappings while connected): open an +/// AWS project's mappings, **as stored when the open runs**, into its +/// connected workspace. The warning detail for the mappings that failed, if +/// any did; `None` as well for a local project (Docker publishes its own) or +/// a workspace that is not (or no longer) connected. +pub async fn open_for_project(store: &ProjectsStore, project_id: &str) -> Option { + let project = store.get(project_id).filter(|p| p.is_aws())?; + let target = ContainerTarget::Agent(super::tunnels::get_endpoint(&project.id)?); + let results = open_latest(project_id, &target, || { + store.get(project_id).filter(|p| p.is_aws()).map(|p| { + let gateway = p.aws.as_ref().is_some_and(|a| a.gateway_sidecar); + (p.port_mappings, gateway) + }) + }) + .await; + if !still_connected(project_id, &target) { + return None; + } + failure_detail(&results) +} + +/// The host ports open for the project. +#[cfg(test)] +pub fn open_ports(project_id: &str) -> Vec { + let mut ports: Vec = + lock().get(project_id).map(|v| v.forwards.iter().map(|f| f.port).collect()).unwrap_or_default(); + ports.sort_unstable(); + ports +} + +/// The `workspace-warning` detail for the mappings that failed, if any did. +pub fn failure_detail(results: &[PortForwardResult]) -> Option { + let lines: Vec<&str> = results.iter().filter_map(|r| r.error.as_deref()).collect(); + (!lines.is_empty()).then(|| lines.join("\n")) +} + +#[cfg(test)] +#[path = "port_forwards/tests.rs"] +mod tests; diff --git a/app/src-tauri/src/host/port_forwards/tests.rs b/app/src-tauri/src/host/port_forwards/tests.rs new file mode 100644 index 0000000..599e496 --- /dev/null +++ b/app/src-tauri/src/host/port_forwards/tests.rs @@ -0,0 +1,396 @@ +//! Port mappings against real loopback sockets and a **fake** agent that +//! answers `/v1/attach` by echoing stdin back as stdout — the socat it was +//! asked to run is recorded, never run. + +use super::*; +use crate::storage::projects_store::ProjectsStore; +use crate::host::agent::AgentEndpoint; +use crate::host::tunnels; +use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade}; +use axum::extract::State; +use axum::response::Response; +use axum::routing::get; +use axum::Router; +use futures_util::SinkExt; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +#[derive(Default)] +struct Fake { + /// Every request the agent saw, of any kind. + requests: AtomicUsize, + /// The command of each attach. + cmds: std::sync::Mutex>>, +} + +async fn attach_ws(State(f): State>, ws: WebSocketUpgrade) -> Response { + f.requests.fetch_add(1, Ordering::SeqCst); + ws.on_upgrade(move |socket| echo(f, socket)) +} + +async fn echo(f: Arc, mut ws: WebSocket) { + let Some(Ok(WsMessage::Text(hello))) = ws.recv().await else { return }; + let hello: serde_json::Value = serde_json::from_str(hello.as_str()).unwrap(); + let cmd = hello["cmd"] + .as_array() + .unwrap() + .iter() + .map(|v| v.as_str().unwrap().to_string()) + .collect(); + f.cmds.lock().unwrap().push(cmd); + let _ = ws.send(WsMessage::Text(r#"{"type":"started","exec_id":"a1"}"#.into())).await; + while let Some(Ok(msg)) = ws.recv().await { + match msg { + WsMessage::Binary(b) => { + let mut out = vec![1u8]; + out.extend_from_slice(&b); + if ws.send(WsMessage::Binary(out.into())).await.is_err() { + return; + } + } + WsMessage::Text(t) if t.as_str().contains("close_stdin") => break, + _ => {} + } + } + let _ = ws.send(WsMessage::Text(r#"{"type":"exit","code":0}"#.into())).await; + let _ = ws.close().await; +} + +async fn counted(State(f): State>) -> &'static str { + f.requests.fetch_add(1, Ordering::SeqCst); + "{}" +} + +/// A fake agent, registered as `project_id`'s connected tunnel; its target. +async fn connected_agent(project_id: &str) -> (ContainerTarget, Arc, Arc) { + let fake = Arc::new(Fake::default()); + let app = Router::new() + .route("/v1/attach", get(attach_ws)) + .fallback(counted) + .with_state(fake.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let port = listener.local_addr().unwrap().port(); + tokio::spawn(async move { + axum::serve(listener, app).await.unwrap(); + }); + let closes = Arc::new(AtomicUsize::new(0)); + tunnels::register(project_id, tunnels::tests::fake_tunnel(port, closes.clone())); + (ContainerTarget::Agent(AgentEndpoint::loopback(port, "tok")), fake, closes) +} + +fn pid(tag: &str) -> String { + format!("port-forwards-test-{tag}-{}", uuid::Uuid::new_v4()) +} + +/// A host port nothing listens on right now. +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +fn tcp(host_port: u16, container_port: u16) -> PortMapping { + PortMapping { host_port, container_port, protocol: "tcp".into() } +} + +async fn round_trip(port: u16, msg: &[u8]) -> Vec { + let mut c = TcpStream::connect(("127.0.0.1", port)).await.expect("connect"); + c.write_all(msg).await.unwrap(); + let mut buf = vec![0u8; msg.len()]; + tokio::time::timeout(std::time::Duration::from_secs(5), c.read_exact(&mut buf)) + .await + .expect("echo in time") + .expect("echo"); + buf +} + +fn port_is_free(port: u16) -> bool { + std::net::TcpListener::bind(("127.0.0.1", port)).is_ok() +} + +#[tokio::test] +async fn a_busy_host_port_fails_its_mapping_alone_and_the_other_forwards() { + let p = pid("busy"); + let (target, fake, _) = connected_agent(&p).await; + let busy = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let busy_port = busy.local_addr().unwrap().port(); + let free = free_port(); + + let results = open_for(&p, &target, &[tcp(busy_port, 3000), tcp(free, 5432)]).await; + + assert_eq!(results.len(), 2); + let e = results[0].error.as_deref().expect("the busy port fails"); + assert!(e.contains("already in use"), "{e}"); + assert!(results[1].error.is_none(), "{:?}", results[1].error); + assert_eq!(failure_detail(&results).as_deref(), Some(e)); + assert_eq!(open_ports(&p), vec![free]); + + // Bytes go through the agent's attach, to the *container* port. + assert_eq!(round_trip(free, b"ping").await, b"ping"); + assert_eq!( + fake.cmds.lock().unwrap().as_slice(), + [vec!["socat".to_string(), "-".into(), "TCP:127.0.0.1:5432".into()]] + ); + + // Stop / Remove / task death all close the tunnel: the mappings go too. + tunnels::close(&p).await; + assert!(open_ports(&p).is_empty()); + assert!(port_is_free(free)); +} + +#[tokio::test] +async fn a_server_speaks_first_protocol_is_not_held_back() { + // Unlike the auth bridge, a mapping forwards a client that has said + // nothing yet (MySQL, SMTP): the attach opens on connect. + let p = pid("silent"); + let (target, fake, _) = connected_agent(&p).await; + let port = free_port(); + assert!(open_for(&p, &target, &[tcp(port, 3306)]).await[0].error.is_none()); + let _client = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3); + while fake.cmds.lock().unwrap().is_empty() { + assert!(tokio::time::Instant::now() < deadline, "no attach for a silent client"); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + tunnels::close(&p).await; +} + +#[tokio::test] +async fn an_open_listener_with_no_connection_makes_no_agent_request() { + // So it can never count as activity and keep a workspace from its idle stop. + let p = pid("idle"); + let (target, fake, _) = connected_agent(&p).await; + let port = free_port(); + assert!(open_for(&p, &target, &[tcp(port, 8080)]).await[0].error.is_none()); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + assert_eq!(fake.requests.load(Ordering::SeqCst), 0); + tunnels::close(&p).await; +} + +#[tokio::test] +async fn udp_reserved_and_duplicate_mappings_are_refused_per_mapping() { + let p = pid("refused"); + let (target, _, _) = connected_agent(&p).await; + let ok = free_port(); + let udp = PortMapping { host_port: free_port(), container_port: 53, protocol: "udp".into() }; + let results = open_for( + &p, + &target, + &[ + udp, + tcp(ok, 8080), + tcp(ok, 9090), + tcp(free_port(), *RESERVED_CONTAINER_PORTS.start()), + tcp(free_port(), crate::host::ssm::AGENT_PORT), + tcp(*RESERVED_HOST_PORTS.start(), 8080), + tcp(0, 0), + ], + ) + .await; + let errors: Vec> = results.iter().map(|r| r.error.as_deref()).collect(); + assert_eq!(errors.len(), 6, "an unfinished row is skipped: {errors:?}"); + assert!(errors[0].unwrap().contains("only TCP"), "{errors:?}"); + assert!(errors[1].is_none()); + assert!(errors[2].unwrap().contains("another mapping"), "{errors:?}"); + assert!(errors[3].unwrap().contains("browser view"), "{errors:?}"); + assert!(errors[4].unwrap().contains("agent"), "{errors:?}"); + assert!(errors[5].unwrap().contains("browser view"), "{errors:?}"); + assert_eq!(open_ports(&p), vec![ok]); + tunnels::close(&p).await; +} + +#[tokio::test] +async fn a_reconnect_replaces_the_set_on_the_same_host_ports() { + let p = pid("replace"); + let (target, _, _) = connected_agent(&p).await; + let port = free_port(); + assert!(open_for(&p, &target, &[tcp(port, 8080)]).await[0].error.is_none()); + // A background re-attach registers a new tunnel and opens again. + let (target2, fake2, _) = connected_agent(&p).await; + let again = open_for(&p, &target2, &[tcp(port, 8080)]).await; + assert!(again[0].error.is_none(), "{:?}", again[0].error); + assert_eq!(round_trip(port, b"hi").await, b"hi"); + assert_eq!(fake2.cmds.lock().unwrap().len(), 1, "the new set reaches the new tunnel"); + tunnels::close(&p).await; + assert!(port_is_free(port)); +} + +#[tokio::test] +async fn nothing_is_kept_when_the_workspace_is_no_longer_connected() { + let p = pid("gone"); + let (target, _, _) = connected_agent(&p).await; + tunnels::close(&p).await; // a Stop raced the connect + let port = free_port(); + let results = open_for(&p, &target, &[tcp(port, 8080)]).await; + assert!(results[0].error.as_deref().unwrap().contains("disconnected")); + assert!(open_ports(&p).is_empty()); + assert!(port_is_free(port)); +} + +#[tokio::test] +async fn a_task_death_closes_the_mappings_but_a_stale_report_does_not() { + let p = pid("death"); + let (target, _, _) = connected_agent(&p).await; + let port = free_port(); + open_for(&p, &target, &[tcp(port, 8080)]).await; + tunnels::close_if_task(&p, "arn:some-older-task").await; + assert_eq!(open_ports(&p), vec![port]); + let ContainerTarget::Agent(ep) = &target else { unreachable!() }; + let (_, _, _, arn) = tunnels::task_of(ep).unwrap(); + tunnels::close_if_task(&p, &arn).await; + assert!(open_ports(&p).is_empty()); + assert!(port_is_free(port)); +} + +#[test] +fn an_aws_project_saves_only_tcp_unreserved_unique_mappings() { + let v = |m: &[PortMapping]| validate_aws_port_mappings(m, false); + assert!(v(&[tcp(3000, 3000), tcp(8081, 8080), tcp(0, 0), tcp(5000, 0), tcp(4001, 4000)]).is_ok()); + let udp = PortMapping { host_port: 5353, container_port: 5353, protocol: "udp".into() }; + let e = v(&[udp]).unwrap_err(); + assert!(e.contains("only TCP") && e.contains("UDP"), "{e}"); + assert!(v(&[tcp(3000, 3000), tcp(3000, 4000)]).unwrap_err().contains("mapped twice")); + assert!(v(&[tcp(4000, 39321)]).is_err()); + assert!(v(&[tcp(4000, 47900)]).is_err()); + assert!(v(&[tcp(47820, 4000)]).is_err()); +} + +#[test] +fn the_gateway_sidecars_port_is_refused_while_the_project_runs_it() { + // A mapping reaches the workspace's *loopback*, where the sidecar holds + // the provider key behind 127.0.0.1:4000. + let m = [tcp(4001, GATEWAY_SIDECAR_PORT)]; + assert!(validate_aws_port_mappings(&m, false).is_ok()); + let e = validate_aws_port_mappings(&m, true).unwrap_err(); + assert!(e.contains("gateway sidecar"), "{e}"); + // Turning the sidecar on re-checks rows that were already stored. + assert!(validate_aws_port_mappings_update(Some((&m, false)), &m, true).is_err()); + assert!(validate_aws_port_mappings_update(Some((&m, false)), &m, false).is_ok()); +} + +#[test] +fn a_stored_row_that_would_be_refused_does_not_block_other_saves() { + let udp = PortMapping { host_port: 5353, container_port: 5353, protocol: "udp".into() }; + let stored = vec![udp.clone(), tcp(3000, 3000)]; + // Unchanged, plus a new valid row: fine. + let saved = vec![udp.clone(), tcp(3000, 3000), tcp(8080, 8080)]; + assert!(validate_aws_port_mappings_update(Some((&stored, false)), &saved, false).is_ok()); + // A new UDP row, or an edit to one, is refused. + let edited = PortMapping { host_port: 5354, ..udp.clone() }; + let e = validate_aws_port_mappings_update(Some((&stored, false)), &[edited, tcp(3000, 3000)], false); + assert!(e.unwrap_err().contains("only TCP")); + // A new row taking a stored row's host port is refused. + let dup = vec![udp.clone(), tcp(3000, 3000), tcp(3000, 4000)]; + assert!(validate_aws_port_mappings_update(Some((&stored, false)), &dup, false) + .unwrap_err() + .contains("mapped twice")); + // Newly on AWS: everything is checked. + assert!(validate_aws_port_mappings_update(None, &stored, false).is_err()); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn overlapping_opens_converge_on_the_last_stored_set_without_false_errors() { + // The editor saves on every blur; each save opens. Each open re-reads + // the stored mappings under the project's lock, so overlapping opens + // neither fight over a host port nor leave an older save's set behind. + let p = pid("concurrent"); + let (target, _, _) = connected_agent(&p).await; + let (a, b, c) = (free_port(), free_port(), free_port()); + let sets = [ + vec![tcp(a, 8080), tcp(b, 8081)], + vec![tcp(b, 8081), tcp(c, 8082)], + vec![tcp(a, 8085), tcp(c, 8082)], + vec![tcp(b, 8090), tcp(c, 8082)], + ]; + let stored = Arc::new(std::sync::Mutex::new(sets[0].clone())); + let go = Arc::new(tokio::sync::Barrier::new(8)); + let mut opens = Vec::new(); + for i in 0..8 { + let (p2, t2, s2, go2) = (p.clone(), target.clone(), stored.clone(), go.clone()); + let mine = sets[i % sets.len()].clone(); + opens.push(tokio::spawn(async move { + go2.wait().await; + open_latest(&p2, &t2, move || { + let mut s = s2.lock().unwrap(); + *s = mine; // this save lands, then its open reads the store + Some((s.clone(), false)) + }) + .await + })); + } + for o in opens { + let results = o.await.unwrap(); + assert!(results.iter().all(|r| r.error.is_none()), "{results:?}"); + } + let last = stored.lock().unwrap().clone(); + let mut want: Vec = last.iter().map(|m| m.host_port).collect(); + want.sort_unstable(); + assert_eq!(open_ports(&p), want, "the registry holds the last stored set"); + tunnels::close(&p).await; +} + +#[tokio::test] +async fn a_save_keeps_unchanged_forwards_and_their_live_connections() { + let p = pid("diff"); + let (target, fake, _) = connected_agent(&p).await; + let (a, b) = (free_port(), free_port()); + open_for(&p, &target, &[tcp(a, 8080)]).await; + let mut client = TcpStream::connect(("127.0.0.1", a)).await.unwrap(); + client.write_all(b"one").await.unwrap(); + let mut buf = [0u8; 3]; + client.read_exact(&mut buf).await.unwrap(); + + let r = open_for(&p, &target, &[tcp(a, 8080), tcp(b, 8081)]).await; + assert!(r.iter().all(|r| r.error.is_none()), "{r:?}"); + // The same connection still carries bytes: its forward was kept. + client.write_all(b"two").await.unwrap(); + client.read_exact(&mut buf).await.unwrap(); + assert_eq!(&buf, b"two"); + assert_eq!(fake.cmds.lock().unwrap().len(), 1, "no new attach for the kept connection"); + + // A changed container port rebinds the same host port. + let r = open_for(&p, &target, &[tcp(a, 9090)]).await; + assert!(r[0].error.is_none(), "{:?}", r[0].error); + assert_eq!(round_trip(a, b"x").await, b"x"); + assert_eq!(fake.cmds.lock().unwrap().last().unwrap()[2], "TCP:127.0.0.1:9090"); + assert!(port_is_free(b)); + tunnels::close(&p).await; +} + +#[tokio::test] +async fn a_stored_project_is_read_when_the_open_runs() { + let p = pid("store"); + let dir = tempfile::tempdir().unwrap(); + let mut project = crate::models::Project::new("x".into(), vec![]); + project.id = p.clone(); + project.host_id = Some("h1".into()); + project.aws_placement = + Some(crate::models::AwsPlacement { region: "us-west-2".into(), environment: "dev".into() }); + project.aws = Some(Default::default()); + let (port, busy) = (free_port(), std::net::TcpListener::bind("127.0.0.1:0").unwrap()); + let busy_port = busy.local_addr().unwrap().port(); + project.port_mappings = vec![tcp(port, 8080), tcp(busy_port, 8081)]; + let store = ProjectsStore::over_file_for_test(dir.path().join("projects.json"), vec![project]); + assert_eq!(open_for_project(&store, &p).await, None, "not connected: nothing, no warning"); + let (_target, _, _) = connected_agent(&p).await; + let warning = open_for_project(&store, &p).await.expect("the busy port is reported"); + assert!(warning.contains(&busy_port.to_string()) && warning.contains("already in use"), "{warning}"); + assert_eq!(open_ports(&p), vec![port]); + tunnels::close(&p).await; +} + +#[tokio::test] +async fn the_auth_bridges_forward_still_waits_for_a_client_to_speak() { + // The generalised `PortForward::bind` keeps the bridge's gate: a silent + // client costs no attach (contrast `a_server_speaks_first_protocol_…`). + let p = pid("bridge"); + let (target, fake, _) = connected_agent(&p).await; + let port = free_port(); + let mut fwd = PortForward::bind(target, port, port, PortFamily::V4).await.unwrap(); + assert_eq!((fwd.port, fwd.container_port), (port, port)); + let _client = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + assert_eq!(fake.requests.load(Ordering::SeqCst), 0); + fwd.shutdown().await; + tunnels::close(&p).await; +} diff --git a/app/src-tauri/src/host/sessions.rs b/app/src-tauri/src/host/sessions.rs index 38e977e..56baa9c 100644 --- a/app/src-tauri/src/host/sessions.rs +++ b/app/src-tauri/src/host/sessions.rs @@ -9,7 +9,13 @@ use std::sync::Arc; use tokio::io::AsyncWriteExt; use tokio::sync::{mpsc, Mutex}; -use super::{AttachedExec, ContainerTarget}; +use super::{AttachedExec, ContainerTarget, ExecSpec}; + +/// A session's exec: as `claude` in `/workspace` (what `attach_exec` runs), +/// with `env` added. Values in `env` are never logged. +pub fn session_spec(cmd: Vec, tty: bool, env: Vec) -> ExecSpec { + ExecSpec::new(cmd).tty(tty).env(env) +} pub struct ExecSession { pub exec_id: String, @@ -46,18 +52,22 @@ impl ExecSessionManager { } } + /// A terminal: a tty exec of `cmd` with `env` added to the container's + /// environment (an AWS copy-at-connect project's credentials, + /// `aws_host::terminal_env`; empty otherwise). pub async fn create_session( &self, target: &ContainerTarget, session_id: &str, cmd: Vec, + env: Vec, on_output: F, on_exit: Box, ) -> Result<(), String> where F: Fn(Vec) + Send + 'static, { - self.create_session_with_tty(target, session_id, cmd, true, on_output, on_exit) + self.create_session_spec(target, session_id, session_spec(cmd, true, env), on_output, on_exit) .await } @@ -70,6 +80,21 @@ impl ExecSessionManager { on_output: F, on_exit: Box, ) -> Result<(), String> + where + F: Fn(Vec) + Send + 'static, + { + self.create_session_spec(target, session_id, session_spec(cmd, tty, Vec::new()), on_output, on_exit) + .await + } + + async fn create_session_spec( + &self, + target: &ContainerTarget, + session_id: &str, + spec: ExecSpec, + on_output: F, + on_exit: Box, + ) -> Result<(), String> where F: Fn(Vec) + Send + 'static, { @@ -77,7 +102,7 @@ impl ExecSessionManager { exec_id, mut output, mut input, - } = target.attach_exec(cmd, tty).await?; + } = target.attach(spec).await?; let (input_tx, mut input_rx) = mpsc::unbounded_channel::>(); let (shutdown_tx, mut shutdown_rx) = mpsc::channel::<()>(1); diff --git a/app/src-tauri/src/host/tunnels.rs b/app/src-tauri/src/host/tunnels.rs index 99d4106..923be83 100644 --- a/app/src-tauri/src/host/tunnels.rs +++ b/app/src-tauri/src/host/tunnels.rs @@ -18,6 +18,7 @@ use std::time::Duration; use aws_config::SdkConfig; use futures_util::future::BoxFuture; use tokio::sync::watch; +use tokio_util::sync::CancellationToken; use super::agent::AgentEndpoint; use crate::aws::tasks::StopKind; @@ -51,6 +52,11 @@ pub struct LiveTunnel { /// Runtime handles for the store (`set_aws_runtime`). pub access_point_id: Option, pub task_definition_arn: String, + /// EFS storage's `/workspace` access point. + pub workspace_access_point_id: Option, + /// The start that opened this tunnel ran the task (rather than + /// attaching to one already running, or re-attaching after a restart). + pub created: bool, } /// Where an endpoint's task is: `(connection, region, cluster, task ARN)`. @@ -68,6 +74,12 @@ struct Registry { /// start's own tunnel) and [`cancel_reattach`]: a background re-attach /// that began under an older generation must never register. generation: HashMap, + /// The background clone/setup follower per project (`aws_host::status`), + /// with the id [`begin_follow`] gave it. Cancelled by a new follower, + /// [`cancel_follow`] (Stop, Remove), and whenever the tunnel is taken + /// out or every tunnel closed. + followers: HashMap, + next_follower: u64, } fn registry() -> &'static Mutex { @@ -123,13 +135,15 @@ pub fn get_endpoint(project_id: &str) -> Option { lock().live.get(project_id).map(|t| t.endpoint.clone()) } -/// `(task ARN, access point id, task definition ARN)` of the project's tunnel. -pub fn runtime(project_id: &str) -> Option<(String, Option, String)> { +/// `(task ARN, access point id, task definition ARN, workspace access point +/// id)` of the project's tunnel. +pub fn runtime(project_id: &str) -> Option<(String, Option, String, Option)> { lock().live.get(project_id).map(|t| { ( t.task_arn.clone(), t.access_point_id.clone(), t.task_definition_arn.clone(), + t.workspace_access_point_id.clone(), ) }) } @@ -200,13 +214,67 @@ pub async fn close_if_task(project_id: &str, task_arn: &str) { take(&mut r, project_id) }; notify(); + // The project's port mappings lead into that task: they go with it. + super::port_forwards::close(project_id).await; if let Some(t) = taken { t.forward.close().await; } } +/// Whether the project's registered tunnel came from a start that ran its +/// task (see [`LiveTunnel::created`]). +pub fn ran_task(project_id: &str) -> bool { + lock().live.get(project_id).is_some_and(|t| t.created) +} + +/// A later start found the tunnel already up: it ran no task itself. +pub fn mark_attached(project_id: &str) { + if let Some(t) = lock().live.get_mut(project_id) { + t.created = false; + } +} + +/// Register a background follower for `project_id`, cancelling the one +/// before it. Returns its id (for [`end_follow`]) and its token. +pub fn begin_follow(project_id: &str) -> (u64, CancellationToken) { + let mut r = lock(); + r.next_follower += 1; + let id = r.next_follower; + let token = CancellationToken::new(); + if let Some((_, old)) = r.followers.insert(project_id.to_string(), (id, token.clone())) { + old.cancel(); + } + (id, token) +} + +/// A follower finished: forget it, unless a newer one has replaced it. +pub fn end_follow(project_id: &str, id: u64) { + let mut r = lock(); + if r.followers.get(project_id).is_some_and(|(i, _)| *i == id) { + r.followers.remove(project_id); + } +} + +/// End the project's follower, if one runs (Stop, Remove). +pub fn cancel_follow(project_id: &str) { + cancel_follow_locked(&mut lock(), project_id); +} + +fn cancel_follow_locked(r: &mut Registry, project_id: &str) { + if let Some((_, t)) = r.followers.remove(project_id) { + t.cancel(); + } +} + +/// Whether a follower runs for the project. +#[cfg(test)] +pub fn is_following(project_id: &str) -> bool { + lock().followers.contains_key(project_id) +} + /// Under the lock: invalidate a re-attach in flight and take the tunnel out. fn take(r: &mut Registry, project_id: &str) -> Option { + cancel_follow_locked(r, project_id); r.pending.remove(project_id); *r.generation.entry(project_id.to_string()).or_default() += 1; let t = r.live.remove(project_id); @@ -239,11 +307,12 @@ pub fn end_reattach(project_id: &str, generation: u64) { notify(); } -/// Take the project's tunnel out and close it, and invalidate a background -/// re-attach in flight. +/// Take the project's tunnel out and close it (and its port mappings' +/// forwards), and invalidate a background re-attach in flight. pub async fn close(project_id: &str) { let taken = take(&mut lock(), project_id); notify(); + super::port_forwards::close(project_id).await; if let Some(t) = taken { t.forward.close().await; } @@ -255,12 +324,16 @@ pub async fn close_all() { let mut r = lock(); r.pending.clear(); r.stopped.clear(); + for (_, (_, t)) in r.followers.drain() { + t.cancel(); + } for g in r.generation.values_mut() { *g += 1; } r.live.drain().map(|(_, t)| t).collect() }; notify(); + super::port_forwards::close_all().await; futures_util::future::join_all(all.into_iter().map(|t| t.forward.close())).await; } @@ -334,6 +407,8 @@ pub(crate) mod tests { endpoint: AgentEndpoint::loopback(port, "tok"), access_point_id: Some("fsap-1".into()), task_definition_arn: "arn:td:1".into(), + workspace_access_point_id: None, + created: true, } } @@ -359,6 +434,21 @@ pub(crate) mod tests { assert!(get_endpoint(&p).is_none() && task_of(&ep).is_none()); } + #[tokio::test] + async fn closing_the_tunnel_ends_its_follower_and_an_attach_clears_created() { + let closes = Arc::new(AtomicUsize::new(0)); + let p = pid("follow"); + register(&p, fake_tunnel(61009, closes.clone())); + assert!(ran_task(&p)); + mark_attached(&p); + assert!(!ran_task(&p)); + let (_, token) = begin_follow(&p); + assert!(is_following(&p) && !token.is_cancelled()); + close(&p).await; + assert!(token.is_cancelled()); + assert!(!is_following(&p)); + } + #[tokio::test] async fn re_registering_hands_back_the_old_tunnel_and_clears_a_stale_stop() { let closes = Arc::new(AtomicUsize::new(0)); diff --git a/app/src-tauri/src/lib.rs b/app/src-tauri/src/lib.rs index 452e96a..0a77116 100644 --- a/app/src-tauri/src/lib.rs +++ b/app/src-tauri/src/lib.rs @@ -553,6 +553,8 @@ pub fn run() { commands::project_commands::stop_project_container, commands::project_commands::check_unsaved_work, commands::project_commands::aws_task_log, + commands::project_commands::aws_workspace_status, + commands::project_commands::aws_environment_max_hours, commands::project_commands::remove_aws_resources, commands::project_commands::rebuild_project_container, commands::project_commands::reconcile_project_statuses, @@ -631,6 +633,7 @@ pub fn run() { commands::host_commands::aws_connection_sso_login, commands::host_commands::check_aws_permissions, commands::host_commands::aws_policy_document, + commands::host_commands::aws_cost_estimate, commands::environment_commands::detect_aws_environments, commands::environment_commands::deploy_aws_environment, commands::environment_commands::update_aws_environment, diff --git a/app/src-tauri/src/models/project.rs b/app/src-tauri/src/models/project.rs index 9835397..7890deb 100644 --- a/app/src-tauri/src/models/project.rs +++ b/app/src-tauri/src/models/project.rs @@ -486,6 +486,19 @@ pub enum StorageMode { Ephemeral, #[default] Hybrid, + /// Hybrid plus `/workspace` on EFS (a second access point). + Efs, +} + +/// How an AWS project's credentials and files reach the workspace. +#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)] +#[serde(rename_all = "snake_case")] +pub enum SecretsDelivery { + /// In the project's Secrets Manager secret. + #[default] + SecretsManager, + /// Kept out of the secret; the app copies them in after each connect. + CopyAtConnect, } /// One git repository cloned into the workspace. `branch: None` means the @@ -536,8 +549,22 @@ pub struct AwsWorkspaceConfig { pub access_point_id: Option, #[serde(default)] pub task_definition_arn: Option, + /// Store-owned like `access_point_id`: the EFS-mode `/workspace` access point. + #[serde(default)] + pub workspace_access_point_id: Option, + #[serde(default)] + pub secrets_delivery: SecretsDelivery, + /// Run after the clone, as `claude` (AWS only). + #[serde(default)] + pub setup_script: Option, + /// Run the LiteLLM gateway as a sidecar container. + #[serde(default)] + pub gateway_sidecar: bool, } +/// Largest setup script, in bytes. +pub const MAX_SETUP_SCRIPT_BYTES: usize = 32_768; + impl Default for AwsWorkspaceConfig { fn default() -> Self { Self { @@ -553,6 +580,10 @@ impl Default for AwsWorkspaceConfig { task_arn: None, access_point_id: None, task_definition_arn: None, + workspace_access_point_id: None, + secrets_delivery: SecretsDelivery::default(), + setup_script: None, + gateway_sidecar: false, } } } @@ -706,6 +737,21 @@ pub fn validate_aws_workspace(cfg: &AwsWorkspaceConfig) -> Result<(), String> { return Err(format!("Repository folder \"{}\" is used twice", r.folder)); } } + if let Some(script) = &cfg.setup_script { + if script.len() > MAX_SETUP_SCRIPT_BYTES { + return Err(format!( + "The setup script is {} bytes; the limit is {}", + script.len(), + MAX_SETUP_SCRIPT_BYTES + )); + } + if script.contains('\0') { + return Err("The setup script must not contain NUL characters".into()); + } + } + if cfg.gateway_sidecar && (cfg.cpu < 1024 || cfg.memory_mib < 2048) { + return Err("The LLM gateway sidecar needs at least 1 vCPU (1024) and 2 GiB (2048 MiB)".into()); + } Ok(()) } @@ -1342,6 +1388,44 @@ mod tests { assert!(!off.wip_push_on_stop); } + #[test] + fn phase6_fields_default_for_old_json_and_efs_round_trips() { + let c: AwsWorkspaceConfig = serde_json::from_str(r#"{"storage":"hybrid","cpu":512}"#).unwrap(); + assert_eq!(c.secrets_delivery, SecretsDelivery::SecretsManager); + assert!(!c.gateway_sidecar && c.setup_script.is_none() && c.workspace_access_point_id.is_none()); + let e: AwsWorkspaceConfig = serde_json::from_str(r#"{"storage":"efs","secrets_delivery":"copy_at_connect"}"#).unwrap(); + assert_eq!(e.storage, StorageMode::Efs); + assert_eq!(e.secrets_delivery, SecretsDelivery::CopyAtConnect); + assert_eq!(serde_json::to_string(&StorageMode::Efs).unwrap(), "\"efs\""); + assert_eq!(serde_json::to_string(&SecretsDelivery::CopyAtConnect).unwrap(), "\"copy_at_connect\""); + let back: AwsWorkspaceConfig = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap(); + assert_eq!(back, e); + } + + #[test] + fn setup_script_limits() { + let mut c = AwsWorkspaceConfig::default(); + c.setup_script = Some("a".repeat(MAX_SETUP_SCRIPT_BYTES)); + assert!(validate_aws_workspace(&c).is_ok()); + c.setup_script = Some("a".repeat(MAX_SETUP_SCRIPT_BYTES + 1)); + assert!(validate_aws_workspace(&c).unwrap_err().contains("limit")); + c.setup_script = Some("echo\0hi".into()); + assert!(validate_aws_workspace(&c).unwrap_err().contains("NUL")); + } + + #[test] + fn gateway_sidecar_needs_one_vcpu_and_two_gib() { + let mut c = cfg(512, 2048); + c.gateway_sidecar = true; + assert!(validate_aws_workspace(&c).is_err()); + c = cfg(1024, 2048); + c.gateway_sidecar = true; + assert!(validate_aws_workspace(&c).is_ok()); + c = cfg(256, 2048); + c.gateway_sidecar = true; + assert!(validate_aws_workspace(&c).is_err()); + } + #[test] fn enums_serialize_snake_case_and_is_aws_follows_host_id() { assert_eq!(serde_json::to_string(&Arch::Arm64).unwrap(), "\"arm64\""); diff --git a/app/src-tauri/src/storage/projects_store.rs b/app/src-tauri/src/storage/projects_store.rs index e141a3b..99aa688 100644 --- a/app/src-tauri/src/storage/projects_store.rs +++ b/app/src-tauri/src/storage/projects_store.rs @@ -93,6 +93,46 @@ fn record_corrupt_load(file_path: &Path, now: &chrono::DateTime) { } } +/// The load's rewrite of stale transient statuses; `true` when it changed +/// any. +pub(crate) fn settle_stale_statuses(projects: &mut [Project]) -> bool { + // Reconcile stale transient statuses: on a cold app start no Docker + // operations can be in flight, so Starting/Stopping are always stale. + // Running/Error are left as-is and reconciled against Docker later + // via the reconcile_project_statuses command. + // + // An AWS project goes to **Error**, not Stopped: an app that quit + // mid-start (or mid-stop) may have left a billed task running, with + // or without its ARN recorded yet. Error is what a failed start that + // left a task already uses; `reconcile_aws_projects` then asks ECS + // (by ARN, else by the project's tags) and settles it Running or + // Stopped. Stopped would hide the live task. + let mut changed = false; + for p in projects.iter_mut() { + match p.status { + crate::models::ProjectStatus::Starting | crate::models::ProjectStatus::Stopping => { + let to = if p.is_aws() { + crate::models::ProjectStatus::Error + } else { + crate::models::ProjectStatus::Stopped + }; + log::warn!( + "Reconciling stale '{}' status for project '{}' ({}) → {:?}", + serde_json::to_string(&p.status).unwrap_or_default().trim_matches('"'), + p.name, + p.id, + to + ); + p.status = to; + p.updated_at = chrono::Utc::now().to_rfc3339(); + changed = true; + } + _ => {} + } + } + changed +} + pub struct ProjectsStore { projects: Mutex>, file_path: PathBuf, @@ -155,28 +195,8 @@ impl ProjectsStore { (Vec::new(), false) }; - // Reconcile stale transient statuses: on a cold app start no Docker - // operations can be in flight, so Starting/Stopping are always stale. - // Running/Error are left as-is and reconciled against Docker later - // via the reconcile_project_statuses command. let mut projects = projects; - let mut needs_save = needs_save; - for p in projects.iter_mut() { - match p.status { - crate::models::ProjectStatus::Starting | crate::models::ProjectStatus::Stopping => { - log::warn!( - "Reconciling stale '{}' status for project '{}' ({}) → Stopped", - serde_json::to_string(&p.status).unwrap_or_default().trim_matches('"'), - p.name, - p.id - ); - p.status = crate::models::ProjectStatus::Stopped; - p.updated_at = chrono::Utc::now().to_rfc3339(); - needs_save = true; - } - _ => {} - } - } + let needs_save = settle_stale_statuses(&mut projects) || needs_save; let store = Self { projects: Mutex::new(projects), @@ -448,6 +468,7 @@ impl ProjectsStore { task_arn: Option, access_point_id: Option, task_definition_arn: Option, + workspace_access_point_id: Option, ) -> Result<(), String> { let mut projects = self.lock(); let p = projects @@ -461,6 +482,7 @@ impl ProjectsStore { aws.task_arn = task_arn; aws.access_point_id = access_point_id; aws.task_definition_arn = task_definition_arn; + aws.workspace_access_point_id = workspace_access_point_id; p.updated_at = chrono::Utc::now().to_rfc3339(); self.save(&projects)?; Ok(()) @@ -885,7 +907,7 @@ mod tests { let store = store_over(&dir, vec![aws, local]); store - .set_aws_runtime(&aid, Some("t".into()), Some("ap".into()), Some("td".into())) + .set_aws_runtime(&aid, Some("t".into()), Some("ap".into()), Some("td".into()), Some("wap".into())) .unwrap(); let a = store.get(&aid).unwrap().aws.unwrap(); assert_eq!( @@ -896,10 +918,10 @@ mod tests { serde_json::from_str(&fs::read_to_string(dir.join("projects.json")).unwrap()).unwrap(); assert_eq!(on_disk[0].aws.as_ref().unwrap().task_arn.as_deref(), Some("t")); - store.set_aws_runtime(&aid, None, None, None).unwrap(); + store.set_aws_runtime(&aid, None, None, None, None).unwrap(); assert!(store.get(&aid).unwrap().aws.unwrap().task_arn.is_none()); - assert!(store.set_aws_runtime(&lid, None, None, None).is_err()); - assert!(store.set_aws_runtime("nope", None, None, None).is_err()); + assert!(store.set_aws_runtime(&lid, None, None, None, None).is_err()); + assert!(store.set_aws_runtime("nope", None, None, None, None).is_err()); fs::remove_dir_all(&dir).ok(); } } diff --git a/app/src-tauri/src/web_terminal/ws_handler.rs b/app/src-tauri/src/web_terminal/ws_handler.rs index df85e36..56d9542 100644 --- a/app/src-tauri/src/web_terminal/ws_handler.rs +++ b/app/src-tauri/src/web_terminal/ws_handler.rs @@ -304,6 +304,10 @@ async fn handle_open( _ => build_terminal_cmd(&project, &state.settings_store), }; + // AWS copy-at-connect: the credentials go into this terminal's own + // environment (never the agent's). Empty for everything else. + let env = crate::host::aws_host::terminal_env(&project, &state.settings_store.get()).await; + let session_id = uuid::Uuid::new_v4().to_string(); let project_name = project.name.clone(); @@ -332,6 +336,7 @@ async fn handle_open( &container, &session_id, cmd, + env, on_output, on_exit, ) diff --git a/app/src/App.tsx b/app/src/App.tsx index 2d0aea7..8a89ecc 100644 --- a/app/src/App.tsx +++ b/app/src/App.tsx @@ -23,6 +23,7 @@ import { useContainerProgress } from "./hooks/useContainerProgress"; import { useKeyboardShortcuts } from "./hooks/useKeyboardShortcuts"; import { useMarketplaceSyncToasts } from "./hooks/useMarketplace"; import { useProjectStatusEvents } from "./hooks/useProjectStatusEvents"; +import { useWorkspaceWarnings } from "./hooks/useWorkspaceWarnings"; import MarketplaceView from "./components/marketplace/MarketplaceView"; import { useAppState, isHomeTab, tabKeyId, homeTabKey, MARKETPLACE_TAB_KEY } from "./store/appState"; import { reconcileAwsProjects, reconcileProjectStatuses } from "./lib/tauri-commands"; @@ -77,6 +78,7 @@ export default function App() { useKeyboardShortcuts(); useMarketplaceSyncToasts(); useProjectStatusEvents(); + useWorkspaceWarnings(); // Initialize on mount useEffect(() => { diff --git a/app/src/components/projects/ConfirmRemoveModal.test.tsx b/app/src/components/projects/ConfirmRemoveModal.test.tsx index e5b66d8..10eaa76 100644 --- a/app/src/components/projects/ConfirmRemoveModal.test.tsx +++ b/app/src/components/projects/ConfirmRemoveModal.test.tsx @@ -14,6 +14,14 @@ describe("ConfirmRemoveModal", () => { expect(onConfirm.mock.calls).toEqual([[{ discardData: false }], [{ discardData: true }]]); }); + it("says both access points go when the workspace kept /workspace on EFS", () => { + render( + , + ); + expect(screen.getByRole("checkbox", { name: /file-system access points/ })).toBeInTheDocument(); + expect(screen.getByText(/\/workspace/)).toBeInTheDocument(); + }); + it("offers no access-point choice for an Ephemeral AWS workspace", () => { const onConfirm = vi.fn(); render(); diff --git a/app/src/components/projects/ConfirmRemoveModal.tsx b/app/src/components/projects/ConfirmRemoveModal.tsx index df16a78..9c2d8dc 100644 --- a/app/src/components/projects/ConfirmRemoveModal.tsx +++ b/app/src/components/projects/ConfirmRemoveModal.tsx @@ -8,6 +8,8 @@ interface Props { aws?: boolean; /** AWS: the workspace may have an EFS access point (offers removing it). */ savedFiles?: boolean; + /** AWS: `/workspace` may be on EFS too (EFS storage, now or before). */ + workspaceFiles?: boolean; onConfirm: (opts: { discardData: boolean }) => void; onCancel: () => void; } @@ -19,6 +21,7 @@ export default function ConfirmRemoveModal({ projectName, aws = false, savedFiles = false, + workspaceFiles = false, onConfirm, onCancel, }: Props) { @@ -61,11 +64,12 @@ export default function ConfirmRemoveModal({ onChange={(e) => setDiscardData(e.target.checked)} /> - Also remove the workspace’s file-system access point + Also remove the workspace’s file-system access points - The saved files themselves (Claude login, history, SSH keys) stay on your own - EFS file system, readable only by your workspace role, until an administrator - offboards you. + The saved files themselves (Claude login, history, SSH keys + {workspaceFiles ? ", and the /workspace files" : ""}) stay on your own EFS file + system, readable only by your workspace role, until an administrator offboards + you. diff --git a/app/src/components/projects/PortMappingsEditor.tsx b/app/src/components/projects/PortMappingsEditor.tsx index d807f6b..c425040 100644 --- a/app/src/components/projects/PortMappingsEditor.tsx +++ b/app/src/components/projects/PortMappingsEditor.tsx @@ -7,6 +7,8 @@ interface Props { portMappings: PortMapping[]; disabled: boolean; disabledReason?: string; + /** AWS: only TCP is forwarded (UDP is refused on save). */ + tcpOnly?: boolean; onSave: (mappings: PortMapping[]) => Promise; } @@ -14,6 +16,7 @@ export default function PortMappingsEditor({ portMappings: initial, disabled, disabledReason, + tcpOnly = false, onSave, }: Props) { const [mappings, setMappings] = useState(initial); @@ -93,7 +96,7 @@ export default function PortMappingsEditor({ className={`w-[22%] ${selectClass}`} > - + {(!tcpOnly || pm.protocol === "udp") && }