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 8506f7e..4cf67d3 100644 --- a/app/src-tauri/src/aws/live_tests.rs +++ b/app/src-tauri/src/aws/live_tests.rs @@ -1477,7 +1477,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 +1590,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 +1685,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, @@ -1980,7 +1980,7 @@ mod environment { g.cluster = Some(cluster); g.families.push(families); } - let vars = environment_vars(&name, ®ion, &NetworkChoice::Public).unwrap(); + let vars = environment_vars(&name, ®ion, &NetworkChoice::Public, 0).unwrap(); let (_, outcome, denied) = t .run(ModuleKind::Environment, Deployment::Environment(&name), &vars, TofuOp::Apply, t.keys_env(&keys)) .await; diff --git a/app/src-tauri/src/aws/tasks/tests.rs b/app/src-tauri/src/aws/tasks/tests.rs index fdd6eb2..bdeb743 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, } } diff --git a/app/src-tauri/src/aws/tofu_modules.rs b/app/src-tauri/src/aws/tofu_modules.rs index 28943c7..8528206 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; @@ -274,14 +274,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 +331,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..a3ae211 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!({ diff --git a/app/src-tauri/src/aws/workspace/tests.rs b/app/src-tauri/src/aws/workspace/tests.rs index 4b0bfc0..1d83fc1 100644 --- a/app/src-tauri/src/aws/workspace/tests.rs +++ b/app/src-tauri/src/aws/workspace/tests.rs @@ -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, } } diff --git a/app/src-tauri/src/commands/environment_commands.rs b/app/src-tauri/src/commands/environment_commands.rs index 130530e..f480890 100644 --- a/app/src-tauri/src/commands/environment_commands.rs +++ b/app/src-tauri/src/commands/environment_commands.rs @@ -179,7 +179,7 @@ pub(crate) fn network_from_record( assign_public_ip: info.assign_public_ip, }; // The same checks as the apply's variables. - environment_vars(&info.name, "us-east-1", &choice)?; + environment_vars(&info.name, "us-east-1", &choice, 0)?; Ok(choice) } _ => Err("The environment record names an unknown network mode".into()), @@ -1034,13 +1034,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 +1059,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 +1071,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 +1087,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 +1103,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 +1128,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 +1388,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 +1403,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/components/settings/hosts/AdminBundleModal.test.tsx b/app/src/components/settings/hosts/AdminBundleModal.test.tsx index de5e1f5..00228c4 100644 --- a/app/src/components/settings/hosts/AdminBundleModal.test.tsx +++ b/app/src/components/settings/hosts/AdminBundleModal.test.tsx @@ -57,10 +57,21 @@ describe("AdminBundleModal", () => { environment: "team", ownerId: null, network: { mode: "private-nat" }, + maxWorkspaceHours: 0, }), ); }); + it("an environment bundle carries the lifetime cap", async () => { + invoke.mockResolvedValue("/tmp/env"); + render(); + fireEvent.change(screen.getByLabelText("Maximum workspace lifetime (hours, 0 = none)"), { target: { value: "24" } }); + fireEvent.click(screen.getByRole("button", { name: "Save bundle to folder…" })); + await waitFor(() => + expect(invoke).toHaveBeenCalledWith("save_aws_admin_bundle", expect.objectContaining({ maxWorkspaceHours: 24 })), + ); + }); + it("shows a save failure through the AWS error copy", async () => { invoke.mockRejectedValue({ kind: "sso_expired", profile: "prod-sso" }); render(); diff --git a/app/src/components/settings/hosts/AdminBundleModal.tsx b/app/src/components/settings/hosts/AdminBundleModal.tsx index 2707669..e6b372f 100644 --- a/app/src/components/settings/hosts/AdminBundleModal.tsx +++ b/app/src/components/settings/hosts/AdminBundleModal.tsx @@ -5,6 +5,7 @@ import type { AwsError, ModuleKind, NetworkChoice } from "../../../lib/types"; import Button from "../../ui/Button"; import Field, { inputClass } from "../../ui/Field"; import Modal from "../../ui/Modal"; +import LifetimeCapField, { parseCapHours } from "./LifetimeCapField"; import NetworkFields from "./NetworkFields"; import { DEFAULT_NETWORK, environmentNameError, networkFromDraft, type NetworkDraft } from "./environmentFormat"; @@ -48,6 +49,7 @@ export default function AdminBundleModal({ const askEnvironment = kind === "environment" && !environment; const [name, setName] = useState("main"); const [draft, setDraft] = useState(DEFAULT_NETWORK); + const [capText, setCapText] = useState("0"); const [saving, setSaving] = useState(false); const [saved, setSaved] = useState(null); const [error, setError] = useState(null); @@ -55,7 +57,8 @@ export default function AdminBundleModal({ const nameError = askEnvironment ? environmentNameError(name) : null; const picked = askEnvironment ? networkFromDraft(draft) : null; - const ready = !nameError && (!picked || "network" in picked); + const capHours = parseCapHours(capText); + const ready = !nameError && (!picked || "network" in picked) && (!askEnvironment || capHours !== null); const save = async () => { setSaving(true); @@ -65,6 +68,7 @@ export default function AdminBundleModal({ environment: askEnvironment ? name : environment, ownerId, network: picked && "network" in picked ? picked.network : network, + ...(askEnvironment && capHours !== null ? { maxWorkspaceHours: capHours } : {}), }); if (folder) { setSaved(folder); @@ -127,6 +131,7 @@ export default function AdminBundleModal({ {(id) => setName(e.target.value)} />} + )} @@ -568,12 +571,21 @@ export default function EnvironmentsPanel({ setDeployOpen(false); setRepairOf(null); }} - onDeploy={(name, network) => - repairOf ? repair(current.region, name, network) : deploy(current.region, name, network) + onDeploy={(name, network, hours) => + repairOf ? repair(current.region, name, network, hours) : deploy(current.region, name, network, hours) } onDetect={() => void detect()} /> )} + {updateOf && ( + setUpdateOf(null)} + onUpdate={(hours) => update(updateOf.region, updateOf.name, hours)} + /> + )} {destroyOf && ( void; +}) { + const bad = parseCapHours(value) === null; + return ( + + {(id) => ( + onChange(e.target.value)} + /> + )} + + ); +} diff --git a/app/src/components/settings/hosts/UpdateEnvironmentModal.tsx b/app/src/components/settings/hosts/UpdateEnvironmentModal.tsx new file mode 100644 index 0000000..965f609 --- /dev/null +++ b/app/src/components/settings/hosts/UpdateEnvironmentModal.tsx @@ -0,0 +1,69 @@ +import { useState } from "react"; +import { awsErrorMessage } from "../../../lib/aws-error"; +import type { AwsError } from "../../../lib/types"; +import Button from "../../ui/Button"; +import Modal from "../../ui/Modal"; +import LifetimeCapField, { parseCapHours } from "./LifetimeCapField"; + +/** + * Update an environment to the app's module version. The lifetime cap is + * pre-filled from the environment's record, so an update keeps it unless + * the admin changes it. + */ +export default function UpdateEnvironmentModal({ + name, + region, + currentHours, + onClose, + onUpdate, +}: { + name: string; + region: string; + /** The cap in the environment's record (0 = none). */ + currentHours: number; + onClose: () => void; + /** Starts the run; resolves to the command's error, or null once started. */ + onUpdate: (hours: number) => Promise; +}) { + const [text, setText] = useState(String(currentHours)); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(null); + const hours = parseCapHours(text); + + const submit = async () => { + if (hours === null) return; + setSubmitting(true); + setError(null); + const err = await onUpdate(hours); + setSubmitting(false); + if (err) setError(err); + else onClose(); + }; + + return ( + + + + + } + > +
+ + {error && ( +

+ {awsErrorMessage(error)} +

+ )} +
+
+ ); +} diff --git a/app/src/components/settings/hosts/testkit.ts b/app/src/components/settings/hosts/testkit.ts index 0612e22..72c1329 100644 --- a/app/src/components/settings/hosts/testkit.ts +++ b/app/src/components/settings/hosts/testkit.ts @@ -40,6 +40,7 @@ export function info(name = "dev"): EnvironmentInfo { log_group: `/triple-c/${name}`, network_mode: "public", tenancy: "strict", + max_workspace_hours: 0, }; } diff --git a/app/src/lib/tauri-commands.ts b/app/src/lib/tauri-commands.ts index 273fe3e..63bb211 100644 --- a/app/src/lib/tauri-commands.ts +++ b/app/src/lib/tauri-commands.ts @@ -109,13 +109,35 @@ export const awsPolicyDocument = (tier: Tier) => // after a reload) replays the whole log under a new op id. export const detectAwsEnvironments = (connectionId: string, region: string) => invoke("detect_aws_environments", { connectionId, region }); -export const deployAwsEnvironment = (connectionId: string, region: string, name: string, network: NetworkChoice) => - invoke("deploy_aws_environment", { connectionId, region, name, network }); -export const updateAwsEnvironment = (connectionId: string, region: string, name: string) => - invoke("update_aws_environment", { connectionId, region, name }); -/** `network` is required only when the environment has no record. */ -export const repairAwsEnvironment = (connectionId: string, region: string, name: string, network?: NetworkChoice) => - invoke("repair_aws_environment", { connectionId, region, name, network: network ?? null }); +export const deployAwsEnvironment = ( + connectionId: string, + region: string, + name: string, + network: NetworkChoice, + maxWorkspaceHours = 0, +) => invoke("deploy_aws_environment", { connectionId, region, name, network, maxWorkspaceHours }); +/** Omit `maxWorkspaceHours` to keep the environment's recorded cap. */ +export const updateAwsEnvironment = (connectionId: string, region: string, name: string, maxWorkspaceHours?: number) => + invoke( + "update_aws_environment", + maxWorkspaceHours === undefined + ? { connectionId, region, name } + : { connectionId, region, name, maxWorkspaceHours }, + ); +/** `network` is required only when the environment has no record; a record's cap is kept unless `maxWorkspaceHours` is given. */ +export const repairAwsEnvironment = ( + connectionId: string, + region: string, + name: string, + network?: NetworkChoice, + maxWorkspaceHours?: number, +) => + invoke( + "repair_aws_environment", + maxWorkspaceHours === undefined + ? { connectionId, region, name, network: network ?? null } + : { connectionId, region, name, network: network ?? null, maxWorkspaceHours }, + ); export const destroyIncompleteAwsEnvironment = (connectionId: string, region: string, name: string) => invoke("destroy_incomplete_aws_environment", { connectionId, region, name }); export const unlockAwsState = (connectionId: string, region: string, stateKey: string) => @@ -136,7 +158,7 @@ export const saveAwsAdminBundle = ( connectionId: string, region: string, kind: ModuleKind, - options: { environment?: string; ownerId?: string; network?: NetworkChoice } = {}, + options: { environment?: string; ownerId?: string; network?: NetworkChoice; maxWorkspaceHours?: number } = {}, ) => invoke("save_aws_admin_bundle", { connectionId, @@ -145,6 +167,7 @@ export const saveAwsAdminBundle = ( environment: options.environment ?? null, ownerId: options.ownerId ?? null, network: options.network ?? null, + ...(options.maxWorkspaceHours === undefined ? {} : { maxWorkspaceHours: options.maxWorkspaceHours }), }); /** Check a corporate CA path and report what would be installed. Never * rejects for a bad path — the reason comes back in `error`. */ diff --git a/app/src/lib/types.ts b/app/src/lib/types.ts index 2c52b22..b5015b8 100644 --- a/app/src/lib/types.ts +++ b/app/src/lib/types.ts @@ -1299,6 +1299,8 @@ export interface EnvironmentInfo { log_group: string; network_mode: "public" | "private-nat" | "existing"; tenancy: string; + /** Advisory workspace lifetime cap in hours; 0 = none (absent in v1 records). */ + max_workspace_hours: number; } /** A held state lock. `who`/`created`/`operation` are sanitized untrusted text. */ diff --git a/aws/README.md b/aws/README.md index 76d65a6..5dd838f 100644 --- a/aws/README.md +++ b/aws/README.md @@ -283,7 +283,7 @@ it is unpacked), and an admin can run the very same files by hand from a bundle. | Module | Creates | State key | |---|---|---| | `terraform/permissions-boundary` | the account's `triple-c-permissions-boundary` policy (an account administrator applies it; the admin tier cannot) | `boundary/terraform.tfstate` | -| `terraform/environment` | what every user shares: ECS cluster (Fargate, Fargate Spot), the tasks security group (no inbound rules), KMS key and alias, log group `/triple-c/`, the network (`network_mode`: `public`, `private-nat`, `existing`) and, last, the record `/triple-c/environments/` | `environments//terraform.tfstate` | +| `terraform/environment` | what every user shares: ECS cluster (Fargate, Fargate Spot), the tasks security group (no inbound rules), KMS key and alias, log group `/triple-c/`, the network (`network_mode`: `public`, `private-nat`, `existing`) and, last, the record `/triple-c/environments/` (which carries the advisory `max_workspace_hours` lifetime cap, 0 = none, at most 168) | `environments//terraform.tfstate` | | `terraform/user-onboard` | one user's task and execution roles (with the boundary) and their own EFS file system, its `-efs` security group, two mount targets and a file-system policy that admits only their task role | `users///terraform.tfstate` | The **owner key** is the first 12 hex characters of `sha256(":")`; it names @@ -540,7 +540,7 @@ progress events) is not exercised. | EFS file-system policy naming a just-created role | ✓ no invalid-principal error in any onboarding apply (two applies, each created in 4 s, right after the role; whether the provider retried internally is not visible without its debug log); no module change. If it ever fails, applying the onboarding again completes it | | NAT address on destroy | ✗→fixed: the provider disassociates the address before releasing it, after the NAT gateway (and the association) are gone, and EC2 authorizes that call against the literal `*/*`. `DisassociateGoneAddresses` allows exactly `arn:aws:ec2:*:*:${*}/${*}`; CloudTrail shows the retried call reaching `InvalidAssociationID.NotFound` | | Conditional unlock | ✓ on the versioned state bucket, `DeleteObject` with `If-Match` and a mismatched ETag gets 412 (the app's "lock changed" answer) and leaves the lock; with the current ETag it deletes it. A fresh foreign lock scans as Deploying with its `Who` | -| Update | ✓ re-applying with the network read back from the record: "0 added, 0 changed, 0 destroyed" | +| Update | ✓ re-applying with the network and lifetime cap read back from the record: "0 added, 0 changed, 0 destroyed" | | After `tofu destroy` | ✗→fixed (app): the state object stays, empty, so a destroyed environment kept scanning as Incomplete (and a removed onboarding as Joined). Detection now reads small state objects (up to 2 KiB, at most 200 per scan) and treats one with no resources as absent; a read that fails counts as a deployment | | Cleanup | ✓ nothing `triple-c` left in us-west-2 (roles, policies, log groups, clusters, VPCs, subnets, gateways, NAT gateways, addresses, security groups, file systems, parameters, aliases, buckets); five environment KMS keys pending deletion (7 days); the boundary, which the account did not have, deleted again | diff --git a/aws/terraform/environment/main.tf b/aws/terraform/environment/main.tf index 9399947..9885c7a 100644 --- a/aws/terraform/environment/main.tf +++ b/aws/terraform/environment/main.tf @@ -3,7 +3,7 @@ locals { # ENVIRONMENT_MODULE_VERSION in app/src-tauri/src/aws/tofu_modules.rs. - template_version = 1 + template_version = 2 name = "triple-c-${var.environment_name}" } @@ -110,17 +110,18 @@ resource "aws_ssm_parameter" "environment" { type = "String" tier = "Standard" value = jsonencode({ - schema = 1 - name = var.environment_name - template_version = local.template_version - cluster_arn = aws_ecs_cluster.this.arn - security_group_id = aws_security_group.tasks.id - subnet_ids = local.task_subnet_ids - assign_public_ip = local.assign_public_ip - kms_key_arn = aws_kms_key.this.arn - log_group = aws_cloudwatch_log_group.this.name - network_mode = var.network_mode - tenancy = "strict" + schema = 1 + name = var.environment_name + template_version = local.template_version + cluster_arn = aws_ecs_cluster.this.arn + security_group_id = aws_security_group.tasks.id + subnet_ids = local.task_subnet_ids + assign_public_ip = local.assign_public_ip + kms_key_arn = aws_kms_key.this.arn + log_group = aws_cloudwatch_log_group.this.name + network_mode = var.network_mode + tenancy = "strict" + max_workspace_hours = var.max_workspace_hours }) depends_on = [ diff --git a/aws/terraform/environment/variables.tf b/aws/terraform/environment/variables.tf index 7e50ba7..3ec77bd 100644 --- a/aws/terraform/environment/variables.tf +++ b/aws/terraform/environment/variables.tf @@ -94,3 +94,14 @@ variable "log_retention_days" { error_message = "log_retention_days must be a CloudWatch Logs retention value (1, 3, 5, 7, 14, 30, 60, 90, ...)." } } + +variable "max_workspace_hours" { + description = "Advisory cap on how long one workspace task may run, in hours (0 = no cap, at most 168). The app reads it from the environment record and enforces it inside the workspace." + type = number + default = 0 + + validation { + condition = var.max_workspace_hours == floor(var.max_workspace_hours) && var.max_workspace_hours >= 0 && var.max_workspace_hours <= 168 + error_message = "max_workspace_hours must be a whole number from 0 to 168." + } +}