diff --git a/app/src-tauri/src/aws/tofu_modules/tests.rs b/app/src-tauri/src/aws/tofu_modules/tests.rs index fc6ec0b..1f07ffb 100644 --- a/app/src-tauri/src/aws/tofu_modules/tests.rs +++ b/app/src-tauri/src/aws/tofu_modules/tests.rs @@ -242,14 +242,8 @@ fn same_user_and_environment_in_two_regions_do_not_collide() { assert_ne!(wt, et); assert_ne!(we, ee); assert_ne!( - state_key(Deployment::User { - env: "dev", - owner_key: &west - }), - state_key(Deployment::User { - env: "dev", - owner_key: &east - }) + state_key(Deployment::User { env: "dev", owner_key: &west }), + state_key(Deployment::User { env: "dev", owner_key: &east }) ); } @@ -367,10 +361,7 @@ fn an_existing_network_is_checked_before_anything_is_built() { let lookup = lookups[0]; assert_eq!(label(lookup, 1), Some("existing")); let count = render(attr(&lookup.body, "count").expect("count")); - assert!( - count.contains("var.network_mode") && count.contains("\"existing\""), - "{count}" - ); + assert!(count.contains("var.network_mode") && count.contains("\"existing\""), "{count}"); assert!(count.contains('2'), "{count}"); let id = render(attr(&lookup.body, "id").expect("id")); assert!(id.contains("var.subnet_ids[count.index]"), "{id}"); @@ -405,10 +396,7 @@ fn the_onboarding_completion_output_waits_for_every_resource() { let mut n = 0; for r in top_blocks(&body, "resource") { let addr = format!("{}.{}", label(r, 0).unwrap(), label(r, 1).unwrap()); - assert!( - deps.contains(&addr), - "onboarding_complete doesn't wait for {addr}: {deps}" - ); + assert!(deps.contains(&addr), "onboarding_complete doesn't wait for {addr}: {deps}"); n += 1; } assert!(n >= 9, "only {n} resources"); @@ -2604,9 +2592,7 @@ fn the_lifetime_cap_maximum_is_the_same_in_rust_typescript_and_hcl() { .find(|(f, _)| *f == "variables.tf") .unwrap() .1; - let block = &vars[vars - .find("variable \"max_workspace_hours\"") - .expect("the variable")..]; + let block = &vars[vars.find("variable \"max_workspace_hours\"").expect("the variable")..]; let block = &block[..block.find("\n}\n").unwrap()]; assert!( block.contains(&format!("var.max_workspace_hours <= {max}")), @@ -2895,7 +2881,7 @@ fn the_ami_is_the_ecs_optimized_one_for_the_architecture() { /// The launch template: the variable's type, IMDSv2 at one hop, an /// encrypted 50 GiB gp3 root volume, the environment's tasks group named in /// the template, the instance profile, the agent pointed at the user's -/// cluster with task IMDS blocked, and the default tags on what a launch +/// cluster with task roles for bridge tasks, and the default tags on what a launch /// creates. Never a default-version change (no `ModifyLaunchTemplate`). #[test] fn the_launch_template_is_pinned() { @@ -2979,17 +2965,18 @@ fn the_launch_template_is_pinned() { "#!/bin/bash", ">>/etc/ecs/ecs.config", "ECS_CLUSTER=${aws_ecs_cluster.ec2[0].name}\n", - "ECS_AWSVPC_BLOCK_IMDS=true\n", + // Bridge tasks (R2) get task-role credentials from the agent's + // endpoint; IMDS stays out of their reach at hop limit 1. + "ECS_ENABLE_TASK_IAM_ROLE=true\n", ] { assert!( user_data.contains(needle), "{needle:?} missing from {user_data}" ); } - assert!( - !user_data.contains("ECS_ENABLE_TASK_ENI"), - "no trunking (E3)" - ); + // Bridge networking: no task ENIs, and no awsvpc-only settings. + assert!(!user_data.contains("ECS_ENABLE_TASK_ENI"), "{user_data}"); + assert!(!user_data.contains("AWSVPC"), "{user_data}"); let specs: BTreeSet = top_blocks(b, "tag_specifications") .map(|t| { diff --git a/app/src-tauri/src/commands/environment_commands.rs b/app/src-tauri/src/commands/environment_commands.rs index dd7484f..79162c8 100644 --- a/app/src-tauri/src/commands/environment_commands.rs +++ b/app/src-tauri/src/commands/environment_commands.rs @@ -47,7 +47,8 @@ use crate::aws::tofu::{ }; use crate::aws::tofu_modules::{ boundary_vars, environment_vars, module_files, onboarding_vars, owner_key, state_bucket_name, - state_key, validate_environment_name, Deployment, ModuleKind, NetworkChoice, + state_key, user_ec2_stem, user_record_parameter_name, validate_ec2_user_tag, + validate_environment_name, Deployment, ModuleKind, NetworkChoice, }; use crate::aws::{caller_identity, sdk_config, AwsError, CallerIdentity}; use crate::models::{validate_supported_region, AwsAuth, HostConnection, HostKind}; @@ -415,7 +416,43 @@ const README: &str = "README.txt"; const BACKEND: &str = "backend.hcl"; const TFVARS: &str = "terraform.tfvars.json"; -fn bundle_readme(d: Deployment, account: &str, region: &str, bucket: &str, key: &str) -> String { +/// The onboarding bundle's EC2 step: before applying with EC2 capacity, the +/// admin checks that the per-user names are free or already this user's +/// (the module can't: a name taken by someone else's onboarding would be +/// adopted by neither, and a collision only fails at create). `user_tag` is +/// the bundle's `ec2_user_tag` when set and valid; otherwise the commands +/// show `` for the admin to fill in. +fn ec2_collision_step(env: &str, owner_key: &str, region: &str, user_tag: Option<&str>) -> String { + let stem = user_ec2_stem(env, user_tag.unwrap_or("")); + let record = user_record_parameter_name(env, owner_key); + format!( + " +EC2 capacity (only if ec2_instance_type is set) +------------------------------------------------ +ec2_user_tag must be the value of the user's triple-c-user principal tag. +BEFORE tofu apply, check that the per-user EC2 names are not already in use +by another onboarding. Run: + + aws ecs describe-clusters --region {region} --clusters {stem} --query 'clusters[?status==`ACTIVE`].clusterName' --output text + aws autoscaling describe-auto-scaling-groups --region {region} --auto-scaling-group-names {stem} --query 'AutoScalingGroups[].AutoScalingGroupName' --output text + aws ssm get-parameter --region {region} --name {record} --query Parameter.Value --output text + +If either of the first two prints {stem}, apply ONLY if the third (this +user's record) succeeds and its cluster_arn ends in cluster/{stem}; +otherwise the name belongs to someone else's onboarding: stop and choose +the correct ec2_user_tag. (The app runs the same check before applying.) +" + ) +} + +fn bundle_readme( + d: Deployment, + account: &str, + region: &str, + bucket: &str, + key: &str, + vars: &Value, +) -> String { let what = match d { Deployment::Environment(env) => format!( "the Triple-C environment \"{env}\" (ECS cluster, security group, KMS key, log \ @@ -442,6 +479,15 @@ fn bundle_readme(d: Deployment, account: &str, region: &str, bucket: &str, key: format!(r#"{{"LocationConstraint":"{region}",{tags}}}"#) }; let policy = state_bucket_policy(bucket); + let ec2_step = match d { + Deployment::User { env, owner_key } => { + let tag = vars["ec2_user_tag"] + .as_str() + .filter(|t| validate_ec2_user_tag(t).is_ok()); + ec2_collision_step(env, owner_key, region, tag) + } + _ => String::new(), + }; let credentials = match d { Deployment::Boundary => format!( "- Credentials of an account administrator for account {account} WITHOUT @@ -498,7 +544,7 @@ From this folder: (With Terraform: terraform init -backend-config=backend.hcl, then terraform apply.) - +{ec2_step} 3. Remove --------- From this folder, after tofu init: @@ -529,7 +575,7 @@ fn bundle_files( let json = serde_json::to_string_pretty(vars) .map_err(|e| format!("Could not encode the module variables: {e}"))?; files.push((TFVARS.into(), json + "\n")); - files.push((README.into(), bundle_readme(d, account, ®ion, &bucket, &key))); + files.push((README.into(), bundle_readme(d, account, ®ion, &bucket, &key, vars))); Ok(files) } diff --git a/app/src-tauri/src/commands/environment_commands/tests.rs b/app/src-tauri/src/commands/environment_commands/tests.rs index b7829c7..ad7553e 100644 --- a/app/src-tauri/src/commands/environment_commands/tests.rs +++ b/app/src-tauri/src/commands/environment_commands/tests.rs @@ -253,6 +253,38 @@ fn bundles_contain_the_module_backend_vars_and_readme() { } assert!(!readme.contains("put-bucket-tagging"), "a later tag can't satisfy the create"); + // The EC2 name-collision check (the app does it too, Task 4): the + // exact per-user names, and this user's record to compare against. + let record = format!("/triple-c/users/dev/{ok}"); + for needle in [ + "BEFORE tofu apply", + &format!("aws ecs describe-clusters --region {REGION} --clusters triple-c-dev--u-"), + &format!( + "aws autoscaling describe-auto-scaling-groups --region {REGION} \ + --auto-scaling-group-names triple-c-dev--u-" + ), + &format!("aws ssm get-parameter --region {REGION} --name {record}"), + "cluster/triple-c-dev--u-", + ] { + assert!(readme.contains(needle), "README lacks {needle:?}:\n{readme}"); + } + // With a tag in the variables, the commands name it. + let mut tagged = vars.clone(); + tagged["ec2_instance_type"] = "m7i.large".into(); + tagged["ec2_user_tag"] = "alice".into(); + let other = tempfile::tempdir().unwrap(); + write_bundle(other.path(), d, ACCOUNT, REGION, &tagged).unwrap(); + let readme_tagged = fs::read_to_string(other.path().join("README.txt")).unwrap(); + assert!(readme_tagged.contains("--clusters triple-c-dev--u-alice "), "{readme_tagged}"); + assert!(readme_tagged.contains("--auto-scaling-group-names triple-c-dev--u-alice ")); + assert!(!readme_tagged.contains("")); + // Not in the other bundles. + let env_dir = tempfile::tempdir().unwrap(); + let env_vars = environment_vars("dev", REGION, &NetworkChoice::Public, 0).unwrap(); + write_bundle(env_dir.path(), Deployment::Environment("dev"), ACCOUNT, REGION, &env_vars).unwrap(); + let env_readme = fs::read_to_string(env_dir.path().join("README.txt")).unwrap(); + assert!(!env_readme.contains("EC2 capacity"), "{env_readme}"); + // Writing again over our own files is fine... write_bundle(dir.path(), d, ACCOUNT, REGION, &vars).unwrap(); // ...but an unrelated file (or folder) means the wrong folder. diff --git a/aws/terraform/user-onboard/ec2.tf b/aws/terraform/user-onboard/ec2.tf index 30d2578..b29b55e 100644 --- a/aws/terraform/user-onboard/ec2.tf +++ b/aws/terraform/user-onboard/ec2.tf @@ -159,7 +159,8 @@ resource "aws_launch_template" "ec2" { # The environment's tasks group (outbound only), named in the template so # the admin policy sees it as a launch-template resource. A public IP only # where the environment's tasks get one: in a public-subnet environment - # the agent reaches ECS through the internet gateway. + # the agent, and bridge-network tasks through the instance, reach out + # through the internet gateway. network_interfaces { device_index = 0 security_groups = [local.env.security_group_id] @@ -167,8 +168,9 @@ resource "aws_launch_template" "ec2" { delete_on_termination = true } - # IMDSv2 only, one hop: the agent (host network) reaches it, bridge - # containers don't, and awsvpc tasks are blocked by the agent below. + # IMDSv2 only, one hop: the agent (host network) reaches it, while + # bridge-network containers are one hop further and their token request + # never comes back, so they can't take the instance role's credentials. metadata_options { http_endpoint = "enabled" http_tokens = "required" @@ -191,7 +193,7 @@ resource "aws_launch_template" "ec2" { #!/bin/bash cat >>/etc/ecs/ecs.config <<'EOF' ECS_CLUSTER=${aws_ecs_cluster.ec2[0].name} - ECS_AWSVPC_BLOCK_IMDS=true + ECS_ENABLE_TASK_IAM_ROLE=true EOF EOT )