feat(aws): environments can cap workspace lifetime

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
shadowdaoandClaude Sonnet 5.5 committed 2026-11-15 21:33:54 -08:00
1 parent 34a6edd413
commit cbaf6209fd
23 files changed
+383 -68

No files matched your search

+14
View File
@@ -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<String, Value>, 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,
})
}
@@ -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)
+4 -4
View File
@@ -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, &region, &NetworkChoice::Public).unwrap();
let vars = environment_vars(&name, &region, &NetworkChoice::Public, 0).unwrap();
let (_, outcome, denied) = t
.run(ModuleKind::Environment, Deployment::Environment(&name), &vars, TofuOp::Apply, t.keys_env(&keys))
.await;
+1
View File
@@ -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,
}
}
+11 -1
View File
@@ -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<serde_json::Value, String> {
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,
}))
}
+17 -10
View File
@@ -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!({
+1
View File
@@ -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,
}
}
@@ -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<u32>,
app: AppHandle,
state: State<'_, AppState>,
) -> Result<String, AwsError> {
let ctx = context(&state, &connection_id, &region).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<u32>,
app: AppHandle,
state: State<'_, AppState>,
) -> Result<String, AwsError> {
@@ -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<NetworkChoice>,
max_workspace_hours: Option<u32>,
app: AppHandle,
state: State<'_, AppState>,
) -> Result<String, AwsError> {
@@ -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<String>,
owner_id: Option<String>,
network: Option<NetworkChoice>,
max_workspace_hours: Option<u32>,
window: tauri::Window,
state: State<'_, AppState>,
) -> Result<Option<String>, 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, &region_ok, &network.unwrap_or(NetworkChoice::Public))
.map_err(other)?;
let vars = environment_vars(
&env,
&region_ok,
&network.unwrap_or(NetworkChoice::Public),
max_workspace_hours.unwrap_or(0),
)
.map_err(other)?;
(DeploymentKey::Environment(env), vars)
}
ModuleKind::UserOnboard => {
@@ -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}");
@@ -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(<AdminBundleModal connectionId="h1" region="eu-west-1" kind="environment" onClose={vi.fn()} />);
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(<AdminBundleModal connectionId="h1" region="eu-west-1" kind="permissions_boundary" onClose={vi.fn()} />);
@@ -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<NetworkDraft>(DEFAULT_NETWORK);
const [capText, setCapText] = useState("0");
const [saving, setSaving] = useState(false);
const [saved, setSaved] = useState<string | null>(null);
const [error, setError] = useState<AwsError | null>(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) => <input id={id} className={inputClass} value={name} onChange={(e) => setName(e.target.value)} />}
</Field>
<NetworkFields value={draft} onChange={setDraft} error={picked && "error" in picked ? picked.error : null} />
<LifetimeCapField value={capText} onChange={setCapText} />
</div>
)}
<Button size="md" variant="primary" onClick={save} disabled={saving || !ready}>
@@ -55,7 +55,7 @@ describe("DeployEnvironmentModal", () => {
fireEvent.click(screen.getByRole("radio", { name: "Public" }));
expect(screen.getByLabelText("Name")).toHaveValue("main");
fireEvent.click(screen.getByRole("button", { name: "Deploy" }));
expect(props.onDeploy).toHaveBeenCalledWith("main", { mode: "public" });
expect(props.onDeploy).toHaveBeenCalledWith("main", { mode: "public" }, 0);
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
});
@@ -71,7 +71,7 @@ describe("DeployEnvironmentModal", () => {
fireEvent.change(screen.getByLabelText("Name"), { target: { value: "team-2" } });
expect(deploy).toBeEnabled();
fireEvent.click(deploy);
expect(props.onDeploy).toHaveBeenCalledWith("team-2", { mode: "public" });
expect(props.onDeploy).toHaveBeenCalledWith("team-2", { mode: "public" }, 0);
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
});
@@ -92,7 +92,24 @@ describe("DeployEnvironmentModal", () => {
vpc_id: "vpc-0123abcd",
subnet_ids: ["subnet-0123abcd", "subnet-4567abcd"],
assign_public_ip: true,
});
}, 0);
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
});
it("carries the maximum workspace lifetime and refuses more than a week", async () => {
const props = renderModal();
const cap = screen.getByLabelText("Maximum workspace lifetime (hours, 0 = none)");
expect(cap).toHaveValue("0");
const deploy = screen.getByRole("button", { name: "Deploy" });
for (const bad of ["169", "-1", "1.5", "", "abc"]) {
fireEvent.change(cap, { target: { value: bad } });
expect(deploy).toBeDisabled();
}
fireEvent.change(cap, { target: { value: "168" } });
expect(deploy).toBeEnabled();
fireEvent.change(cap, { target: { value: "12" } });
fireEvent.click(deploy);
expect(props.onDeploy).toHaveBeenCalledWith("main", { mode: "public" }, 12);
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
});
@@ -177,7 +194,7 @@ describe("DeployEnvironmentModal", () => {
expect(screen.getByText(/different network than the one it was deployed with replaces/)).toBeInTheDocument();
fireEvent.click(screen.getByRole("radio", { name: "Private + NAT" }));
fireEvent.click(screen.getByRole("button", { name: "Repair" }));
expect(props.onDeploy).toHaveBeenCalledWith("dev", { mode: "private-nat" });
expect(props.onDeploy).toHaveBeenCalledWith("dev", { mode: "private-nat" }, 0);
await waitFor(() => expect(props.onClose).toHaveBeenCalled());
});
});
@@ -7,6 +7,7 @@ import Field, { inputClass } from "../../ui/Field";
import Modal from "../../ui/Modal";
import AdminBundleModal from "./AdminBundleModal";
import DeployProgress, { runKey, useDeployRuns } from "./DeployProgress";
import LifetimeCapField, { parseCapHours } from "./LifetimeCapField";
import NetworkFields from "./NetworkFields";
import {
BOUNDARY_STATE_KEY,
@@ -37,11 +38,12 @@ export default function DeployEnvironmentModal({
repair?: string;
onClose: () => void;
/** Starts the run; resolves to the command's error, or null once started. */
onDeploy: (name: string, network: NetworkChoice) => Promise<AwsError | null>;
onDeploy: (name: string, network: NetworkChoice, maxWorkspaceHours: number) => Promise<AwsError | null>;
onDetect: () => void;
}) {
const [name, setName] = useState("main");
const [draft, setDraft] = useState<NetworkDraft>(DEFAULT_NETWORK);
const [capText, setCapText] = useState("0");
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<AwsError | null>(null);
const [boundaryDone, setBoundaryDone] = useState(false);
@@ -73,7 +75,8 @@ export default function DeployEnvironmentModal({
: environmentNameError(name) ??
(scan.environments.some((e) => e.name === name) ? `An environment named ${name} already exists here.` : null);
const picked = networkFromDraft(draft);
const ready = !nameError && "network" in picked && !submitting;
const capHours = parseCapHours(capText);
const ready = !nameError && "network" in picked && capHours !== null && !submitting;
const createBoundary = async () => {
setBoundaryError(null);
@@ -85,10 +88,10 @@ export default function DeployEnvironmentModal({
};
const submit = async () => {
if (!("network" in picked)) return;
if (!("network" in picked) || capHours === null) return;
setSubmitting(true);
setError(null);
const err = await onDeploy(target, picked.network);
const err = await onDeploy(target, picked.network, capHours);
setSubmitting(false);
if (err) setError(err);
else onClose();
@@ -171,6 +174,7 @@ export default function DeployEnvironmentModal({
</Field>
)}
<NetworkFields value={draft} onChange={setDraft} error={"error" in picked ? picked.error : null} />
<LifetimeCapField value={capText} onChange={setCapText} />
<p className="text-xs text-[var(--text-secondary)] leading-snug">
First deploy downloads OpenTofu (~30 MB) and the AWS provider (~150 MB).
</p>
@@ -2,7 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import EnvironmentsPanel from "./EnvironmentsPanel";
import type { DeployProgress, EnvironmentScan } from "../../../lib/types";
import { conn, env, progress, scan, tofuEvent } from "./testkit";
import { conn, env, info, progress, scan, tofuEvent } from "./testkit";
const invoke = vi.fn();
vi.mock("@tauri-apps/api/core", () => ({
@@ -301,6 +301,29 @@ describe("EnvironmentsPanel", () => {
);
});
it("Update pre-fills the environment's recorded cap and sends what is shown", async () => {
backend(
() => scan({ environments: [env({ state: { state: "update_available" }, actions: ["join", "update"], info: { ...info("dev"), max_workspace_hours: 24 }, onboarding: { state: "joined" } })] }),
async (cmd) => {
if (cmd === "update_aws_environment") return "u1";
throw new Error(`unexpected ${cmd}`);
},
);
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Update dev" }));
const dialog = screen.getByRole("dialog", { name: "Update dev" });
const cap = within(dialog).getByLabelText("Maximum workspace lifetime (hours, 0 = none)");
expect(cap).toHaveValue("24");
fireEvent.change(cap, { target: { value: "200" } });
expect(within(dialog).getByRole("button", { name: "Update" })).toBeDisabled();
fireEvent.change(cap, { target: { value: "24" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Update" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev", maxWorkspaceHours: 24 }),
);
});
it("shows a failed run's errors in full", async () => {
backend(
() => scan({ environments: [env({ state: { state: "update_available" }, actions: ["join", "update"], onboarding: { state: "joined" } })] }),
@@ -312,7 +335,8 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Update dev" }));
await waitFor(() => expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Update dev" })).getByRole("button", { name: "Update" }));
await waitFor(() => expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "eu-west-1", name: "dev", maxWorkspaceHours: 0 }));
const long = "Error: creating IAM Role (triple-c-dev-task): AccessDenied: User is not authorized to perform iam:CreateRole\n with aws_iam_role.task";
emit(progress({ op_id: "u1", events: [tofuEvent(long, { level: "error", kind: "diagnostic" })] }));
emit(progress({ op_id: "u1", events: [], done: true, cancellable: false, result: { ok: false, exit_code: 1, summary: "Apply failed" } }));
@@ -362,8 +386,9 @@ describe("EnvironmentsPanel", () => {
resolveUs(scan({ region: "us-east-1", environments: [env({ state: { state: "update_available" }, actions: ["update"], onboarding: { state: "joined" } })] })),
);
fireEvent.click(await screen.findByRole("button", { name: "Update dev" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Update dev" })).getByRole("button", { name: "Update" }));
await waitFor(() =>
expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "us-east-1", name: "dev" }),
expect(invoke).toHaveBeenCalledWith("update_aws_environment", { connectionId: "h1", region: "us-east-1", name: "dev", maxWorkspaceHours: 0 }),
);
expect(await screen.findByText("Running")).toBeInTheDocument();
});
@@ -402,6 +427,7 @@ describe("EnvironmentsPanel", () => {
render(<EnvironmentsPanel connection={conn} tier="environment_admin" />);
await open();
fireEvent.click(await screen.findByRole("button", { name: "Update dev" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Update dev" })).getByRole("button", { name: "Update" }));
expect(await screen.findByText(/Finished: No changes\./)).toBeInTheDocument();
expect(screen.getByText("Refreshing state")).toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Cancel deployment" })).toBeNull();
@@ -27,6 +27,7 @@ import Field, { inputClass, selectClass } from "../../ui/Field";
import Modal from "../../ui/Modal";
import StatusIndicator from "../../ui/StatusIndicator";
import AdminBundleModal from "./AdminBundleModal";
import UpdateEnvironmentModal from "./UpdateEnvironmentModal";
import DeployEnvironmentModal from "./DeployEnvironmentModal";
import DeployProgress, { runKey, useDeployRuns, type DeployRun } from "./DeployProgress";
import PolicyFiles from "./PolicyFiles";
@@ -133,6 +134,7 @@ export default function EnvironmentsPanel({
const [waiting, setWaiting] = useState<Set<string>>(new Set());
const [deployOpen, setDeployOpen] = useState(false);
const [repairOf, setRepairOf] = useState<string | null>(null);
const [updateOf, setUpdateOf] = useState<{ name: string; region: string; hours: number } | null>(null);
const [destroyOf, setDestroyOf] = useState<{ name: string; region: string } | null>(null);
/** An Unlock waiting for its typed confirmation: an environment's lock or the caller's onboarding's. */
const [unlockOf, setUnlockOf] = useState<{
@@ -225,13 +227,18 @@ export default function EnvironmentsPanel({
const current = scan && scan.region === region ? scan : null;
const stale = detecting || !current;
const deploy = (runRegion: string, name: string, network: NetworkChoice) =>
const deploy = (runRegion: string, name: string, network: NetworkChoice, hours: number) =>
launch(runRegion, name, environmentStateKey(name), `Deploy of ${name}`, () =>
deployAwsEnvironment(connection.id, runRegion, name, network),
deployAwsEnvironment(connection.id, runRegion, name, network, hours),
);
const repair = (runRegion: string, name: string, network?: NetworkChoice) =>
// Without `hours`, the environment's recorded cap is kept.
const repair = (runRegion: string, name: string, network?: NetworkChoice, hours?: number) =>
launch(runRegion, name, environmentStateKey(name), `Repair of ${name}`, () =>
repairAwsEnvironment(connection.id, runRegion, name, network),
repairAwsEnvironment(connection.id, runRegion, name, network, hours),
);
const update = (runRegion: string, name: string, hours: number) =>
launch(runRegion, name, environmentStateKey(name), `Update of ${name}`, () =>
updateAwsEnvironment(connection.id, runRegion, name, hours),
);
const join = (found: EnvironmentScan, e: DetectedEnvironment) => {
@@ -422,11 +429,7 @@ export default function EnvironmentsPanel({
size="sm"
disabled={busy}
aria-label={`Update ${e.name}`}
onClick={() =>
void launch(at, e.name, environmentStateKey(e.name), `Update of ${e.name}`, () =>
updateAwsEnvironment(connection.id, at, e.name),
)
}
onClick={() => setUpdateOf({ name: e.name, region: at, hours: e.info?.max_workspace_hours ?? 0 })}
>
Update
</Button>
@@ -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 && (
<UpdateEnvironmentModal
name={updateOf.name}
region={updateOf.region}
currentHours={updateOf.hours}
onClose={() => setUpdateOf(null)}
onUpdate={(hours) => update(updateOf.region, updateOf.name, hours)}
/>
)}
{destroyOf && (
<TypedConfirmModal
title={`Destroy ${destroyOf.name}`}
@@ -0,0 +1,44 @@
import Field, { inputClass } from "../../ui/Field";
/** The longest cap the environment module accepts (`MAX_WORKSPACE_HOURS` in `aws/tofu_modules.rs`). */
export const MAX_WORKSPACE_HOURS = 168;
/** The hours in `text`, or null when it isn't a whole number from 0 to 168. */
export function parseCapHours(text: string): number | null {
if (!/^\d{1,3}$/.test(text.trim())) return null;
const n = Number(text);
return n <= MAX_WORKSPACE_HOURS ? n : null;
}
/** "Maximum workspace lifetime (hours, 0 = none)": the environment's advisory cap. */
export default function LifetimeCapField({
value,
onChange,
}: {
value: string;
onChange: (text: string) => void;
}) {
const bad = parseCapHours(value) === null;
return (
<Field
label="Maximum workspace lifetime (hours, 0 = none)"
hint={
bad
? `Enter a whole number of hours from 0 to ${MAX_WORKSPACE_HOURS}.`
: "A workspace stops once it has run this long (after a best-effort WIP push). Advisory: it is enforced inside the workspace, which its user controls."
}
>
{(id) => (
<input
id={id}
type="text"
inputMode="numeric"
className={inputClass}
value={value}
aria-invalid={bad}
onChange={(e) => onChange(e.target.value)}
/>
)}
</Field>
);
}
@@ -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<AwsError | null>;
}) {
const [text, setText] = useState(String(currentHours));
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<AwsError | null>(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 (
<Modal
title={`Update ${name}`}
description={`In ${region}.`}
onClose={onClose}
footer={
<>
<Button size="md" onClick={onClose}>
Cancel
</Button>
<Button size="md" variant="primary" onClick={submit} disabled={hours === null || submitting}>
{submitting ? "Updating…" : "Update"}
</Button>
</>
}
>
<div className="space-y-4">
<LifetimeCapField value={text} onChange={setText} />
{error && (
<p role="alert" className="text-xs text-[var(--error)] leading-snug">
{awsErrorMessage(error)}
</p>
)}
</div>
</Modal>
);
}
@@ -40,6 +40,7 @@ export function info(name = "dev"): EnvironmentInfo {
log_group: `/triple-c/${name}`,
network_mode: "public",
tenancy: "strict",
max_workspace_hours: 0,
};
}
+31 -8
View File
@@ -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<EnvironmentScan>("detect_aws_environments", { connectionId, region });
export const deployAwsEnvironment = (connectionId: string, region: string, name: string, network: NetworkChoice) =>
invoke<string>("deploy_aws_environment", { connectionId, region, name, network });
export const updateAwsEnvironment = (connectionId: string, region: string, name: string) =>
invoke<string>("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<string>("repair_aws_environment", { connectionId, region, name, network: network ?? null });
export const deployAwsEnvironment = (
connectionId: string,
region: string,
name: string,
network: NetworkChoice,
maxWorkspaceHours = 0,
) => invoke<string>("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<string>(
"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<string>(
"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<string>("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<string | null>("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`. */
+2
View File
@@ -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. */
+2 -2
View File
@@ -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/<env>`, the network (`network_mode`: `public`, `private-nat`, `existing`) and, last, the record `/triple-c/environments/<env>` | `environments/<env>/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/<env>`, the network (`network_mode`: `public`, `private-nat`, `existing`) and, last, the record `/triple-c/environments/<env>` (which carries the advisory `max_workspace_hours` lifetime cap, 0 = none, at most 168) | `environments/<env>/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/<env>/<owner key>/terraform.tfstate` |
The **owner key** is the first 12 hex characters of `sha256("<region>:<aws:userid>")`; 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 |
+13 -12
View File
@@ -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 = [
+11
View File
@@ -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."
}
}