feat(aws): estimated hourly cost per workspace

Q5: aws/pricing.rs reads on-demand Fargate rates (x86 and ARM vCPU-hours,
GB-hours, ephemeral storage GB-hours) from the Price List API in us-east-1
(AmazonECS; regionCode, termType=OnDemand, usagetype CONTAINS Fargate),
caches them per region for 24 h under <data_dir>/triple-c/aws-pricing/,
and estimates a config's hourly cost (ephemeral storage billed above
20 GiB; the gateway sidecar adds nothing). aws_cost_estimate(connection_id,
region, config) never errors: denied, offline or slow (8 s) is None,
shown as "Estimate unavailable"; a failed region is not re-asked for
5 minutes and a stale cache still answers.

pricing:GetProducts on * joins workspace-user-tasks.json with its check,
a policy test, the README and a live test (passed). HostSection shows the
estimate while configuring, Overview while running, with the Spot and EFS
notes. Fixture: a recorded us-west-2 GetProducts answer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Opus 5.5 committed 2026-11-16 10:14:06 -08:00
1 parent 2857b4ae7d
commit 904547b2f1
25 files changed
+1309 -6

No files matched your search

+4
View File
@@ -380,6 +380,10 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li
and under copy-at-connect that token stays in the secret too (R1; terminals don't override it).
Log streams: `<prefix>/gateway/<task-id>` (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 `<data_dir>/triple-c/aws-pricing/<region>.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/<env>` record, owner key — `sha256("<region>:<aws:userid>")`,
+26
View File
@@ -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",
+2
View File
@@ -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.
+1
View File
@@ -70,6 +70,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",
+1 -1
View File
@@ -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-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 cLine truncated
{"__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-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 cLine truncated
+1 -1
View File
@@ -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 fielLine truncated
{"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 fielLine truncated
@@ -416,6 +416,12 @@
"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_policy_document command without any pre-configured scope.",
"type": "string",
@@ -1376,6 +1382,12 @@
"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_policy_document command without any pre-configured scope.",
"type": "string",
@@ -416,6 +416,12 @@
"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_policy_document command without any pre-configured scope.",
"type": "string",
@@ -1376,6 +1382,12 @@
"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_policy_document command without any pre-configured scope.",
"type": "string",
+29
View File
@@ -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`.
+1
View File
@@ -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;
+29
View File
@@ -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<Value> = 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.
+384
View File
@@ -0,0 +1,384 @@
//! 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<FargateRates>,
pub arm64: Option<FargateRates>,
}
impl RegionRates {
pub fn for_arch(&self, arch: Arch) -> Option<FargateRates> {
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<RegionRates> {
#[derive(Default)]
struct Partial {
vcpu: Option<f64>,
gb: Option<f64>,
}
let (mut x86, mut arm, mut storage) = (Partial::default(), Partial::default(), None);
for item in items {
let Ok(product) = serde_json::from_str::<Value>(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<f64> {
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::<f64>().ok())
.find(|p| p.is_finite() && (0.0..100.0).contains(p))
}
/// One page of `GetProducts`.
pub struct Page {
pub items: Vec<String>,
pub next_token: Option<String>,
}
/// 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<String>,
) -> impl Future<Output = Result<Page, String>> + 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<String>) -> Result<Page, String> {
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<A: PricingApi>(api: &A, region: &str) -> Result<RegionRates, String> {
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"
))
}
/// `<dir>/<region>.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<HashMap<String, SystemTime>>,
}
/// `<data dir>/triple-c/aws-pricing/`.
pub fn default_cache_dir() -> Option<PathBuf> {
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<A: PricingApi>(
&self,
api: Option<&A>,
region: &str,
now: SystemTime,
) -> Option<RegionRates> {
let cached = self.read(region, now);
if let Some((rates, true)) = cached {
return Some(rates);
}
let stale = cached.map(|(rates, _)| rates);
let Some(api) = api else {
return stale;
};
if self.recently_failed(region, now) {
return stale;
}
let fetched = match tokio::time::timeout(FETCH_TIMEOUT, fetch_rates(api, region)).await {
Ok(r) => r,
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;
@@ -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\"}"
]
}
+373
View File
@@ -0,0 +1,373 @@
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<String> {
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<String> = 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<String> = 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<String> = 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<Vec<Result<Page, String>>>,
calls: AtomicUsize,
hang: bool,
}
impl FakeApi {
fn answering(pages: Vec<Result<Page, String>>) -> 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<String>) -> Result<Page, String> {
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);
}
+118 -1
View File
@@ -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<PolicyFile> {
.collect()
}
/// The cost estimate's rate cache, `<data dir>/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<Option<RatesCache>> = 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<Option<HourlyEstimate>, String> {
let Some(cache) = pricing_cache() else {
return Ok(None);
};
let settings = state.settings_store.get();
Ok(cost_estimate(cache, &connection_id, &region, &config, &settings, SystemTime::now()).await)
}
async fn cost_estimate(
cache: &RatesCache,
connection_id: &str,
region: &str,
config: &AwsWorkspaceConfig,
settings: &AppSettings,
now: SystemTime,
) -> Option<HourlyEstimate> {
let region = validate_supported_region(region).ok()?;
let rates = match cache.read(&region, now) {
Some((rates, true)) => Some(rates),
_ => {
// Only now touch the connection (a keys connection reads the
// keychain); without one, a stale cache still answers.
let api = match aws_conn(connection_id, settings) {
Ok(conn) => sdk_config(&conn, pricing::PRICING_REGION)
.await
.ok()
.map(|cfg| SdkPricingApi::new(&cfg)),
Err(_) => None,
};
cache.rates(api.as_ref(), &region, 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);
}
}
}
+1
View File
@@ -632,6 +632,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,
@@ -0,0 +1,116 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { act, render, screen } from "@testing-library/react";
import type { AwsWorkspaceConfig, HourlyEstimate } from "../../../lib/types";
import { defaultAwsWorkspace } from "../../../lib/awsWorkspace";
const awsCostEstimate =
vi.fn<(id: string, region: string, config: AwsWorkspaceConfig) => Promise<HourlyEstimate | null>>();
vi.mock("../../../lib/tauri-commands", () => ({
awsCostEstimate: (id: string, region: string, config: AwsWorkspaceConfig) =>
awsCostEstimate(id, region, config),
}));
import AwsCostEstimate, { ESTIMATE_DEBOUNCE_MS, formatHourly } from "./AwsCostEstimate";
const config = (over: Partial<AwsWorkspaceConfig> = {}): AwsWorkspaceConfig => ({
...defaultAwsWorkspace(),
storage: "ephemeral",
...over,
});
async function settle() {
await act(async () => {
vi.advanceTimersByTime(ESTIMATE_DEBOUNCE_MS);
});
await act(async () => {});
}
beforeEach(() => {
vi.useFakeTimers();
awsCostEstimate.mockReset();
});
afterEach(() => vi.useRealTimers());
describe("AwsCostEstimate", () => {
it("formats small and larger figures", () => {
expect(formatHourly(0.05826)).toBe("$0.058");
expect(formatHourly(0.2468)).toBe("$0.25");
expect(formatHourly(2.5)).toBe("$2.50");
});
it("shows the on-demand hourly figure for the connection, region and config", async () => {
awsCostEstimate.mockResolvedValue({
usd_per_hour: 0.05826,
note_spot: false,
efs_billed_separately: false,
});
const c = config();
render(<AwsCostEstimate connectionId="c1" region="us-west-2" config={c} />);
expect(screen.getByText("Estimating…")).toBeInTheDocument();
await settle();
expect(awsCostEstimate).toHaveBeenCalledWith("c1", "us-west-2", c);
expect(screen.getByText("≈ $0.058/hour")).toBeInTheDocument();
expect(screen.queryByText(/Spot/)).toBeNull();
expect(screen.queryByText(/EFS/)).toBeNull();
});
it("notes Spot, EFS and the gateway sidecar", async () => {
awsCostEstimate.mockResolvedValue({
usd_per_hour: 0.05,
note_spot: true,
efs_billed_separately: true,
});
render(
<AwsCostEstimate
connectionId="c1"
region="us-west-2"
config={config({ spot: true, storage: "hybrid", gateway_sidecar: true })}
/>,
);
await settle();
expect(
screen.getByText("≈ $0.050/hour (on-demand; Spot is usually up to 70% cheaper)"),
).toBeInTheDocument();
expect(screen.getByText(/EFS storage is billed separately/)).toBeInTheDocument();
expect(screen.getByText(/gateway sidecar shares the task's CPU and memory/)).toBeInTheDocument();
});
it("says the estimate is unavailable for null or a failed call, never an error", async () => {
awsCostEstimate.mockResolvedValueOnce(null);
const { unmount } = render(<AwsCostEstimate connectionId="c1" region="us-west-2" config={config()} />);
await settle();
expect(screen.getByText("Estimate unavailable")).toBeInTheDocument();
unmount();
awsCostEstimate.mockRejectedValueOnce("boom");
render(<AwsCostEstimate connectionId="c1" region="us-west-2" config={config()} />);
await settle();
expect(screen.getByText("Estimate unavailable")).toBeInTheDocument();
});
it("without a connection or region it does not ask", async () => {
render(<AwsCostEstimate connectionId={null} region="us-west-2" config={config()} />);
await settle();
expect(awsCostEstimate).not.toHaveBeenCalled();
expect(screen.getByText("Estimate unavailable")).toBeInTheDocument();
});
it("asks once per settled change of a cost field, not for unrelated edits", async () => {
awsCostEstimate.mockResolvedValue({ usd_per_hour: 0.1, note_spot: false, efs_billed_separately: false });
const { rerender } = render(<AwsCostEstimate connectionId="c1" region="us-west-2" config={config()} />);
await settle();
expect(awsCostEstimate).toHaveBeenCalledTimes(1);
// An unrelated field: no new call.
rerender(<AwsCostEstimate connectionId="c1" region="us-west-2" config={config({ setup_script: "x" })} />);
await settle();
expect(awsCostEstimate).toHaveBeenCalledTimes(1);
// Two quick CPU changes: one call, with the last.
rerender(<AwsCostEstimate connectionId="c1" region="us-west-2" config={config({ cpu: 2048 })} />);
rerender(
<AwsCostEstimate connectionId="c1" region="us-west-2" config={config({ cpu: 4096, memory_mib: 8192 })} />,
);
await settle();
expect(awsCostEstimate).toHaveBeenCalledTimes(2);
expect(awsCostEstimate.mock.calls[1][2].cpu).toBe(4096);
});
});
@@ -0,0 +1,78 @@
import { useEffect, useState } from "react";
import type { AwsWorkspaceConfig, HourlyEstimate } from "../../../lib/types";
import { awsCostEstimate } from "../../../lib/tauri-commands";
/** Edits settle this long before the estimate is asked for again. */
export const ESTIMATE_DEBOUNCE_MS = 400;
/** "$0.058" below ten cents (two decimals would round most tasks to $0.05/$0.06), "$0.25" above. */
export function formatHourly(usd: number): string {
return `$${usd.toFixed(usd < 0.1 ? 3 : 2)}`;
}
interface Props {
/** The project's connection; null when it was removed. */
connectionId: string | null;
region: string | null | undefined;
config: AwsWorkspaceConfig;
}
type State = { kind: "loading" } | { kind: "done"; estimate: HourlyEstimate | null };
/**
* The estimated on-demand cost per hour of an AWS project's Fargate task (Q5), from the Price
* List API through `aws_cost_estimate` (cached a day per region). Best effort: a denied call, no
* network or no connection reads "Estimate unavailable" — never an error toast, and nothing waits
* on it. Re-asked only when a field that changes the price changes, after edits settle.
*/
export default function AwsCostEstimate({ connectionId, region, config }: Props) {
const [state, setState] = useState<State>({ kind: "loading" });
const { cpu, memory_mib, arch, ephemeral_gib, spot, storage } = config;
// Only what the backend prices or notes; the rest of the config is sent but changes nothing.
const key = JSON.stringify([connectionId, region, cpu, memory_mib, arch, ephemeral_gib, spot, storage]);
useEffect(() => {
if (!connectionId || !region) {
setState({ kind: "done", estimate: null });
return;
}
let cancelled = false;
setState({ kind: "loading" });
const timer = setTimeout(() => {
awsCostEstimate(connectionId, region, config)
.catch(() => null)
.then((estimate) => {
if (!cancelled) setState({ kind: "done", estimate });
});
}, ESTIMATE_DEBOUNCE_MS);
return () => {
cancelled = true;
clearTimeout(timer);
};
// `key` covers every field of `config` the estimate depends on.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key]);
const estimate = state.kind === "done" ? state.estimate : null;
return (
<div className="space-y-0.5 text-xs">
<p className="text-[var(--text-primary)]">
{state.kind === "loading"
? "Estimating…"
: estimate
? `≈ ${formatHourly(estimate.usd_per_hour)}/hour${
estimate.note_spot ? " (on-demand; Spot is usually up to 70% cheaper)" : ""
}`
: "Estimate unavailable"}
</p>
{estimate && (
<p className="text-[var(--text-secondary)]">
While the task runs; nothing while it is stopped.
{estimate.efs_billed_separately && " EFS storage is billed separately."}
{config.gateway_sidecar &&
" The gateway sidecar shares the task's CPU and memory, so it adds nothing."}
</p>
)}
</div>
);
}
@@ -13,6 +13,7 @@ import PermissionModeControl, {
import CapabilityTiles from "./CapabilityTiles";
import ContainerMigrationBanner from "./ContainerMigrationBanner";
import AwsWorkspaceStatusCard from "./AwsWorkspaceStatusCard";
import AwsCostEstimate from "./AwsCostEstimate";
import { isAwsProject } from "../../../lib/awsWorkspace";
import type { ContainerMigration } from "../../../hooks/useContainerMigration";
import SaveIndicator from "../../ui/SaveIndicator";
@@ -138,6 +139,23 @@ export default function OverviewTab({
failed, …). Polls only while Running and visible. */}
{isAwsProject(project) && <AwsWorkspaceStatusCard project={project} />}
{/* AWS, while running: what the task costs per hour (Q5). */}
{isAwsProject(project) && project.status === "running" && project.aws && (
<section
aria-label="Estimated cost"
className="p-3 border rounded-[var(--radius-panel)] bg-[var(--bg-secondary)] border-[var(--border-color)] space-y-1"
>
<h2 className="text-[11px] font-semibold uppercase tracking-wide text-[var(--text-secondary)]">
Estimated cost
</h2>
<AwsCostEstimate
connectionId={project.host_id}
region={project.aws_placement?.region}
config={project.aws}
/>
</section>
)}
{/* A container missing socat and bwrap is a capability statement, so the
out-of-date warning sits directly above the capability inventory. */}
<ContainerMigrationBanner
@@ -11,12 +11,14 @@ import { useAppState } from "../../../../store/appState";
const OFF_BRIDGE: AuthBridgeStatus = { enabled: false, active_ports: [], conflicts: [] };
const removeAwsResources = vi.fn();
const awsCostEstimate = vi.fn(async (..._args: unknown[]) => null as unknown);
vi.mock("../../../../lib/tauri-commands", () => ({
getAuthBridgeStatus: vi.fn(async () => OFF_BRIDGE),
setAuthBridgeEnabled: vi.fn(),
inspectCaCertPath: vi.fn(async () => null),
removeAwsResources: (id: string, discard: boolean) => removeAwsResources(id, discard),
awsCostEstimate: (...args: unknown[]) => awsCostEstimate(...args),
}));
vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => {}) }));
vi.mock("@tauri-apps/plugin-dialog", () => ({ open: vi.fn(async () => null) }));
@@ -220,6 +222,35 @@ describe("HostSection", () => {
const renderHost = (p: Project = awsProject(), disabled = false) =>
render(<HostSection project={p} save={save} disabled={disabled} />);
it("shows the estimated hourly cost for the project's connection and region", async () => {
awsCostEstimate.mockResolvedValueOnce({
usd_per_hour: 0.05,
note_spot: true,
efs_billed_separately: true,
});
useAppState.setState({
appSettings: { hosts: [{ id: "c1", name: "lab" }] } as unknown as AppSettings,
});
const p = awsProject();
p.aws = { ...p.aws!, spot: true };
renderHost(p);
const card = screen.getByRole("region", { name: "Estimated cost" });
await waitFor(() =>
expect(within(card).getByText(/≈ \$0\.050\/hour \(on-demand; Spot is usually up to 70% cheaper\)/)).toBeInTheDocument(),
);
expect(awsCostEstimate).toHaveBeenCalledWith("c1", "eu-west-1", p.aws);
expect(within(card).getByText(/EFS storage is billed separately/)).toBeInTheDocument();
useAppState.setState({ appSettings: null });
});
it("says the estimate is unavailable when the connection is gone", async () => {
useAppState.setState({ appSettings: null });
renderHost();
const card = screen.getByRole("region", { name: "Estimated cost" });
await waitFor(() => expect(within(card).getByText("Estimate unavailable")).toBeInTheDocument());
expect(awsCostEstimate).not.toHaveBeenCalled();
});
it("offers no CPU below 1 vCPU while the gateway sidecar is on", () => {
const p = awsProject();
p.aws = { ...p.aws!, gateway_sidecar: true };
@@ -27,6 +27,7 @@ import Toggle from "../../../ui/Toggle";
import SegmentedControl from "../../../ui/SegmentedControl";
import Field, { ConfigGroup, SwitchRow, inputClass, selectClass } from "../../../ui/Field";
import RepoListEditor from "../../RepoListEditor";
import AwsCostEstimate from "../AwsCostEstimate";
interface Props {
project: Project;
@@ -297,6 +298,19 @@ export default function HostSection({ project, save, disabled }: Props) {
}
/>
<section aria-label="Estimated cost">
<h3 className="text-[13px] font-medium text-[var(--text-primary)]">Estimated cost</h3>
<p className="mt-0.5 mb-1 text-xs text-[var(--text-secondary)] leading-snug">
The on-demand Fargate price in this region for the CPU, memory, architecture and disk
above.
</p>
<AwsCostEstimate
connectionId={connection ? connection.id : null}
region={project.aws_placement?.region}
config={aws}
/>
</section>
<SwitchRow
label="Stop when idle"
hint={
+6 -1
View File
@@ -1,5 +1,5 @@
import { invoke } from "@tauri-apps/api/core";
import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, WorkspaceStatus, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
import type { Project, ProjectPath, NewProjectHost, RemoveProjectOptions, WipChoice, UnsavedWork, WorkspaceStatus, ProjectRemovalReport, ProjectResetOutcome, ContainerInfo, AppSettings, SettingsImportPreview, SettingsImportOutcome, UpdateInfo, ImageUpdateInfo, FileEntry, FileContents, WebTerminalInfo, SttStatus, GatewayStatus, InstallOptions, ClaudeSession, ContainerCapabilities, ScheduledTask, ScheduledTaskInput, SchedulerNotification, AuthBridgeStatus, BrowserViewStatus, BrowserViewPopoutState, BrowserPageState, PlaywrightDetection, BrowserSetupOutcome, BrowserInstallTarget, ContainerStaleness, MigrationOptions, MigrationReport, MigrationState, ClearTokenOutcome, CaCertInfo, UploadOutcome, Note, ViewerFile, ViewerPoll, ViewerSaved, ViewerState, FileDiff, InstallScope, ItemUpdate, Marketplace, MarketplaceAccount, MarketplaceItemRef, MarketplaceSnapshot, ProjectSyncResult, SyncReport, HostConnection, CallerIdentity, PermissionReport, PolicyFile, HourlyEstimate, AwsWorkspaceConfig, Tier, EnvironmentScan, NetworkChoice, ModuleKind } from "./types";
// Docker
export const checkDocker = () => invoke<boolean>("check_docker");
@@ -105,6 +105,11 @@ export const checkAwsPermissions = (id: string, region?: string) =>
/** Every policy file `tier` needs, in order: attach all of them. */
export const awsPolicyDocument = (tier: Tier) =>
invoke<PolicyFile[]>("aws_policy_document", { tier });
/** The estimated hourly cost of `config` on Fargate in `region`, signed with the project's
* connection. Never rejects for AWS reasons: `null` means "Estimate unavailable" (denied, offline,
* no connection). Rates are cached a day on disk. */
export const awsCostEstimate = (connectionId: string, region: string, config: AwsWorkspaceConfig) =>
invoke<HourlyEstimate | null>("aws_cost_estimate", { connectionId, region, config });
// AWS environments (OpenTofu). Reject with an `AwsError`. Starting commands (and follow) resolve
// to an op id; progress arrives on the `AWS_DEPLOY_PROGRESS_EVENT` event (`DeployProgress`, in
+10
View File
@@ -1268,6 +1268,16 @@ export interface PolicyFile {
json: string;
}
/** `aws::pricing::HourlyEstimate`: the on-demand price of an AWS project's
* Fargate task per hour while it runs (a gateway sidecar adds nothing). */
export interface HourlyEstimate {
usd_per_hour: number;
/** Spot is on: the Price List has no Spot rates, so say it is usually cheaper. */
note_spot: boolean;
/** Hybrid or EFS storage: EFS is billed per GB-month, not in this figure. */
efs_billed_separately: boolean;
}
export type Verdict = "allowed" | "denied" | "unverified";
export interface ActionResult {
+19 -2
View File
@@ -7,7 +7,7 @@ tier the signed-in identity has under **Settings → Hosts → Check**.
| File | What it is |
|---|---|
| `policies/workspace-user.json` | The **workspace user** tier, part 1: create, start, stop, connect to and delete **their own** workspaces in an existing environment |
| `policies/workspace-user-tasks.json` | The **workspace user** tier, part 2: register and tag **their own** ECS task definitions, and read **their own** secrets (`workspace-user.json` has no room left) |
| `policies/workspace-user-tasks.json` | The **workspace user** tier, part 2: register and tag **their own** ECS task definitions, read **their own** secrets, and read Fargate prices for the cost estimate (`workspace-user.json` has no room left) |
| `policies/environment-admin.json` | The **environment admin** tier, part 1: apply and destroy the environment and onboarding modules (`terraform/`) with OpenTofu, and keep their state |
| `policies/environment-admin-network.json` | The **environment admin** tier, part 2: the network those modules create (VPC, subnets, gateways, routes, security groups) |
| `policies/permissions-boundary.json` | The **permissions boundary** every Triple-C role must carry. It is never attached to a person |
@@ -117,6 +117,12 @@ following:
roles, add those roles' ARNs or path prefixes (for example `arn:aws:iam::*:role/engineers/*`)
to `InspectOwnPrincipal` in both tier policies. Everything matched there can be read and
simulated by every holder of the policy, so keep it to the sign-in roles.
- **Read Fargate prices** (`workspace-user-tasks.json`, `ReadFargatePrices`). `pricing:GetProducts`
on `*`: the Price List API has no resource types or condition keys, and prices are public. The
app asks it (in us-east-1, service `AmazonECS`) for the workspace region's on-demand Fargate
vCPU, memory and ephemeral-storage rates, caches them for a day and shows an estimated hourly
cost in the project's Host settings and Overview. Without this permission the estimate reads
"Estimate unavailable"; nothing else depends on it.
- **Read environment information.** This covers ECS, the `/triple-c/*` SSM parameters (the
environment records), the secret list, EFS, and the `/triple-c/*` log groups. Listing is not a
secret; the app filters by owner for display. A workspace user sees only environments that have
@@ -395,7 +401,7 @@ Create each file as a **customer managed policy** and attach it. In the console,
or role. Inline policies do not fit: a role's inline policies share 10,240 characters and an
environment admin needs every tier file (about 16,400), and a user's share 2,048. A managed policy
may hold 6,144 characters, not counting whitespace. Without whitespace, `workspace-user.json` is
about 6,040 (roughly 100 characters of headroom), `workspace-user-tasks.json` about 1,200,
about 6,040 (roughly 100 characters of headroom), `workspace-user-tasks.json` about 1,290,
`environment-admin.json` about 5,800 (340)
and `environment-admin-network.json` about 3,340; a unit test (`every_policy_fits_a_managed_policy`)
fails before any file outgrows the limit. A tier that outgrows its files gains another file, which
@@ -601,3 +607,14 @@ and the secret and removes the ECR policy; then the fixture destroys the modules
| A revision per configuration | turning idle stop on adds a secret key, so the next start registers a new revision (by design) |
| Removal (R8) | ✓ final run: `remove_aws_resources` succeeds; the secret is scheduled for deletion, the access point deleted, the revision left ACTIVE. Since R10 the secret is deleted without a recovery window (the test now asserts it is gone) |
| Cleanup | ✓ nothing `triple-c` left in us-west-2; environment KMS keys pending deletion |
### Phase 6: the cost estimate's price reads (2026-11-16)
`cargo test aws::live_tests::a_ -- --ignored --test-threads=1` (the four permission-check tests
plus `a_workspace_role_reads_fargate_prices_and_a_bare_role_cannot`), us-west-2, all passed.
| Point | Result |
|---|---|
| `pricing:GetProducts` on `*` (`ReadFargatePrices`) | ✓ a role holding only the workspace files reads us-west-2's rates from the us-east-1 endpoint (`AmazonECS`; `TERM_MATCH regionCode`, `TERM_MATCH termType=OnDemand`, `CONTAINS usagetype=Fargate`: eight rows, one page). x86 $0.04048/vCPU-h, $0.004445/GB-h; ARM $0.03238, $0.00356; ephemeral storage $0.000111/GB-h |
| Without the permission | ✓ a role with no policy is denied (`AccessDeniedException` naming `pricing:GetProducts`); the app shows "Estimate unavailable" |
| The permission check | ✓ the simulator allows the new check for the workspace tier and denies it for a role with no policy |
+10
View File
@@ -61,6 +61,16 @@
}
}
},
{
"Sid": "ReadFargatePrices",
"Effect": "Allow",
"Action": [
"pricing:GetProducts"
],
"Resource": [
"*"
]
},
{
"Sid": "NeverReadEnvironmentSecrets",
"Effect": "Deny",