diff --git a/CLAUDE.md b/CLAUDE.md index 21feaa6..ae7a67b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -312,14 +312,17 @@ docker exec stdout → tokio task → emit("terminal-output-{sessionId}") → li `identity.rs` is `GetCallerIdentity` and the principal to simulate (an assumed role's ARN is recovered with `iam:GetRole`, because SSO roles have an `/aws-reserved/…` path the session ARN lacks); `error.rs` classifies SDK errors (SSO expired, access denied naming the action, …); - `policies.rs` embeds `aws/policies/*.json` (the two tier policies and the permissions boundary) - and the table of checks the simulator is asked; `permissions.rs` runs it + `policies.rs` embeds `aws/policies/*.json` (the tier policies — the admin tier spans several + files, `policy_files` lists them — and the permissions boundary) and the table of checks the + simulator is asked; `permissions.rs` runs it (`SimulatePrincipalPolicy`, adaptive retries — it throttles — or read-only probes when the caller can't simulate itself; a probed run never claims the admin tier). `policies.rs`'s tests are the drift guard: every allowed action has a check, every check is allowed by a small IAM - evaluator, owner-scoped checks are denied for someone else, admin destruction is tag-scoped, - the boundary fences hold, every Resource is an ARN and every policy fits a 6,144-character - managed policy. **Change a policy JSON, its checks and `aws/README.md` together.** The evaluator + evaluator (`policy_eval.rs`, test-only; `tofu_modules/tests.rs` also asks it whether the admin + tier allows every call `MODULE_CALLS` lists for the Terraform modules), owner-scoped checks are + denied for someone else, admin destruction is tag-scoped, the boundary fences hold, every + Resource is an ARN and every policy fits a 6,144-character managed policy. **Change a policy + JSON, its checks and `aws/README.md` together.** The evaluator is not IAM: `live_tests.rs` (ignored; `TRIPLEC_AWS_E2E_PROFILE`, `TRIPLEC_AWS_E2E_REGION`, admin credentials for a disposable account; `cargo test aws::live_tests -- --ignored --test-threads=1`) runs the check and real calls against throwaway `triple-c-e2e-*` roles, diff --git a/app/src-tauri/Cargo.lock b/app/src-tauri/Cargo.lock index 3b5a9e6..08fed18 100644 --- a/app/src-tauri/Cargo.lock +++ b/app/src-tauri/Cargo.lock @@ -366,32 +366,6 @@ dependencies = [ "uuid", ] -[[package]] -name = "aws-sdk-cloudformation" -version = "1.139.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b77def03a5fb2442348afdd6ecd0eafbfa117243865cc78e899beb26edf7fb6d" -dependencies = [ - "arc-swap", - "aws-credential-types", - "aws-runtime", - "aws-smithy-async", - "aws-smithy-http", - "aws-smithy-json", - "aws-smithy-observability", - "aws-smithy-query", - "aws-smithy-runtime", - "aws-smithy-runtime-api", - "aws-smithy-schema", - "aws-smithy-types", - "aws-smithy-xml", - "aws-types", - "fastrand", - "http", - "regex-lite", - "tracing", -] - [[package]] name = "aws-sdk-ecs" version = "1.159.0" @@ -7301,7 +7275,6 @@ dependencies = [ "aws-config", "aws-credential-types", "aws-runtime", - "aws-sdk-cloudformation", "aws-sdk-ecs", "aws-sdk-iam", "aws-sdk-kms", diff --git a/app/src-tauri/Cargo.toml b/app/src-tauri/Cargo.toml index c12a00e..b2b29b9 100644 --- a/app/src-tauri/Cargo.toml +++ b/app/src-tauri/Cargo.toml @@ -64,7 +64,6 @@ aws-sdk-ssm = { version = "1.137.0", default-features = false, features = ["defa aws-sdk-ecs = { version = "1.159.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } aws-sdk-sts = { version = "1.126.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } aws-sdk-iam = { version = "1.136.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } -aws-sdk-cloudformation = { version = "1.139.0", default-features = false, features = ["default-https-client", "rt-tokio", "behavior-version-latest"] } aws-sdk-secretsmanager = { version = "1.128.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). diff --git a/app/src-tauri/src/aws/live_tests.rs b/app/src-tauri/src/aws/live_tests.rs index 9c5b92b..9385318 100644 --- a/app/src-tauri/src/aws/live_tests.rs +++ b/app/src-tauri/src/aws/live_tests.rs @@ -39,7 +39,7 @@ use super::permissions::{ SdkPermissionApi, Summary, Verdict, }; use super::policies::{ - checks, permissions_boundary_json, policy_json, Placeholders, Tier, PERMISSIONS_BOUNDARY_NAME, + checks, permissions_boundary_json, policy_files, Placeholders, Tier, PERMISSIONS_BOUNDARY_NAME, }; use super::{caller_identity, sdk_config, sdk_config_for_keys, CallerIdentity}; use crate::models::host_connection::{AwsAuth, HostConnection, HostKind}; @@ -276,10 +276,12 @@ impl E2e { Tier::WorkspaceUser => "workspace", Tier::EnvironmentAdmin => "admin", }; - let arn = self - .managed_policy(&format!("{suffix}-{name}"), policy_json(tier)) - .await; - self.attach(&role, &arn).await; + for (i, (_, json)) in policy_files(tier).iter().enumerate() { + let arn = self + .managed_policy(&format!("{suffix}-{name}{i}"), json) + .await; + self.attach(&role, &arn).await; + } } role } @@ -555,7 +557,7 @@ async fn a_role_with_no_policy_checks_as_insufficient_and_lists_every_action() { async fn a_role_without_simulate_permission_falls_back_to_probes() { e2e(|e| async move { let mut doc: serde_json::Value = - serde_json::from_str(policy_json(Tier::WorkspaceUser)).unwrap(); + serde_json::from_str(policy_files(Tier::WorkspaceUser)[0].1).unwrap(); doc["Statement"] .as_array_mut() .unwrap() @@ -578,7 +580,6 @@ async fn a_role_without_simulate_permission_falls_back_to_probes() { for probed in [ "ecs:ListClusters", "ssm:GetParametersByPath", - "cloudformation:DescribeStacks", "secretsmanager:ListSecrets", ] { assert_eq!(verdict(probed), Verdict::Allowed, "{probed}"); diff --git a/app/src-tauri/src/aws/mod.rs b/app/src-tauri/src/aws/mod.rs index f51e5ee..27134e3 100644 --- a/app/src-tauri/src/aws/mod.rs +++ b/app/src-tauri/src/aws/mod.rs @@ -10,6 +10,8 @@ mod identity; mod live_tests; pub mod permissions; pub mod policies; +#[cfg(test)] +mod policy_eval; pub mod tofu_modules; pub use connection::{sdk_config, sdk_config_for_keys}; diff --git a/app/src-tauri/src/aws/permissions.rs b/app/src-tauri/src/aws/permissions.rs index 52e9f81..6f6c314 100644 --- a/app/src-tauri/src/aws/permissions.rs +++ b/app/src-tauri/src/aws/permissions.rs @@ -74,15 +74,13 @@ pub fn simulation_request(check: &Check, p: &Placeholders, user_id: &str) -> Sim pub enum Probe { EcsListClusters, SsmGetParametersByPath, - CfnDescribeStacks, SecretsListSecrets, } impl Probe { - const ALL: [Probe; 4] = [ + const ALL: [Probe; 3] = [ Probe::EcsListClusters, Probe::SsmGetParametersByPath, - Probe::CfnDescribeStacks, Probe::SecretsListSecrets, ]; @@ -91,7 +89,6 @@ impl Probe { match action.split_once(':')?.0 { "ecs" => Some(Probe::EcsListClusters), "ssm" => Some(Probe::SsmGetParametersByPath), - "cloudformation" => Some(Probe::CfnDescribeStacks), "secretsmanager" => Some(Probe::SecretsListSecrets), _ => None, } @@ -101,7 +98,6 @@ impl Probe { match self { Probe::EcsListClusters => "ecs:ListClusters", Probe::SsmGetParametersByPath => "ssm:GetParametersByPath", - Probe::CfnDescribeStacks => "cloudformation:DescribeStacks", Probe::SecretsListSecrets => "secretsmanager:ListSecrets", } } @@ -130,7 +126,6 @@ pub struct SdkPermissionApi { iam: aws_sdk_iam::Client, ecs: aws_sdk_ecs::Client, ssm: aws_sdk_ssm::Client, - cfn: aws_sdk_cloudformation::Client, secrets: aws_sdk_secretsmanager::Client, } @@ -147,7 +142,6 @@ impl SdkPermissionApi { iam: aws_sdk_iam::Client::from_conf(iam), ecs: aws_sdk_ecs::Client::new(cfg), ssm: aws_sdk_ssm::Client::new(cfg), - cfn: aws_sdk_cloudformation::Client::new(cfg), secrets: aws_sdk_secretsmanager::Client::new(cfg), } } @@ -213,13 +207,6 @@ impl PermissionApi for SdkPermissionApi { .await .map(drop) .map_err(|e| classify(&e)), - Probe::CfnDescribeStacks => self - .cfn - .describe_stacks() - .send() - .await - .map(drop) - .map_err(|e| classify(&e)), Probe::SecretsListSecrets => self .secrets .list_secrets() @@ -515,7 +502,7 @@ async fn simulate_all( )) } -/// Per-tier outcomes from the four probes. `denied` is the action whose +/// Per-tier outcomes from the three probes. `denied` is the action whose /// denial forced probing; the caller's own-principal checks of it are /// `Denied`. async fn probe_all( diff --git a/app/src-tauri/src/aws/permissions/tests.rs b/app/src-tauri/src/aws/permissions/tests.rs index 182bb08..8a883da 100644 --- a/app/src-tauri/src/aws/permissions/tests.rs +++ b/app/src-tauri/src/aws/permissions/tests.rs @@ -17,10 +17,9 @@ fn identity() -> CallerIdentity { } } -const ALL_PROBES: [Probe; 4] = [ +const ALL_PROBES: [Probe; 3] = [ Probe::EcsListClusters, Probe::SsmGetParametersByPath, - Probe::CfnDescribeStacks, Probe::SecretsListSecrets, ]; @@ -214,15 +213,11 @@ fn a_missing_action_reports_insufficient_and_names_it() { #[test] fn an_admin_gap_still_reports_workspace_user() { let mut api = FakeApi::allowing(&[Tier::WorkspaceUser, Tier::EnvironmentAdmin]); - api.allow.remove("cloudformation:CreateStack"); + api.allow.remove("ec2:CreateVpc"); let report = run(&api); assert_eq!(report.summary, Summary::WorkspaceUser); assert_eq!( - verdict( - &report, - Tier::EnvironmentAdmin, - "cloudformation:CreateStack" - ), + verdict(&report, Tier::EnvironmentAdmin, "ec2:CreateVpc"), Verdict::Denied ); } @@ -407,10 +402,6 @@ fn a_denied_simulation_falls_back_to_probes_and_marks_writes_unverified() { verdict(&report, ws, "ssm:GetParametersByPath"), Verdict::Allowed ); - assert_eq!( - verdict(&report, ws, "cloudformation:DescribeStacks"), - Verdict::Allowed - ); assert_eq!( verdict(&report, ws, "secretsmanager:ListSecrets"), Verdict::Allowed @@ -446,7 +437,7 @@ fn a_denied_get_role_falls_back_to_probes() { m => panic!("expected Probed, got {m:?}"), } assert!(api.simulated().is_empty()); - assert_eq!(api.probed.lock().unwrap().len(), 4); + assert_eq!(api.probed.lock().unwrap().len(), ALL_PROBES.len()); // Denied on the caller's own role: direct evidence. assert_eq!( verdict(&report, Tier::WorkspaceUser, "iam:GetRole"), @@ -487,14 +478,10 @@ fn a_probed_run_never_claims_environment_admin() { #[test] fn throttled_simulations_block_the_tier_and_carry_notes() { let mut api = FakeApi::allowing(&[Tier::WorkspaceUser, Tier::EnvironmentAdmin]); - api.simulate_errors = vec![("cloudformation:CreateStack", throttled())]; + api.simulate_errors = vec![("ec2:CreateVpc", throttled())]; let report = run(&api); assert_eq!(report.method, Method::Simulated); - let r = row( - &report, - Tier::EnvironmentAdmin, - "cloudformation:CreateStack", - ); + let r = row(&report, Tier::EnvironmentAdmin, "ec2:CreateVpc"); assert_eq!(r.verdict, Verdict::Unverified); assert!(r.note.as_deref().unwrap().contains("Throttling"), "{r:?}"); // Allowed rows carry no note. @@ -548,7 +535,7 @@ fn credential_errors_anywhere_are_errors() { // From a probe. let mut api = FakeApi::allowing(&[Tier::WorkspaceUser]); api.get_role_denied = true; - api.probes_ok.remove(&Probe::CfnDescribeStacks); + api.probes_ok.remove(&Probe::SecretsListSecrets); api.probe_error = Some(AwsError::KeysMissing); assert_eq!( try_run(&api, &identity()).unwrap_err(), @@ -630,3 +617,14 @@ fn check_permissions_is_send() { } let _ = with::; } + +/// D8: CloudFormation left the policies, so nothing probes it either. +#[test] +fn no_probe_is_cloudformation() { + assert_eq!(Probe::ALL, ALL_PROBES); + for p in Probe::ALL { + assert!(!p.action().starts_with("cloudformation:"), "{p:?}"); + assert_eq!(Probe::for_action(p.action()), Some(p)); + } + assert_eq!(Probe::for_action("cloudformation:DescribeStacks"), None); +} diff --git a/app/src-tauri/src/aws/policies.rs b/app/src-tauri/src/aws/policies.rs index 583915a..d76ef6d 100644 --- a/app/src-tauri/src/aws/policies.rs +++ b/app/src-tauri/src/aws/policies.rs @@ -19,11 +19,26 @@ pub enum Tier { WorkspaceUser, } -/// The policy document an admin attaches for `tier`. -pub fn policy_json(tier: Tier) -> &'static str { +/// The policy documents an admin attaches for `tier`, as (file name under +/// `aws/policies/`, contents). Every file of a tier is required: the admin +/// tier is split across files only because a managed policy holds 6,144 +/// characters (D7). +pub fn policy_files(tier: Tier) -> &'static [(&'static str, &'static str)] { match tier { - Tier::EnvironmentAdmin => include_str!("../../../../aws/policies/environment-admin.json"), - Tier::WorkspaceUser => include_str!("../../../../aws/policies/workspace-user.json"), + Tier::EnvironmentAdmin => &[ + ( + "environment-admin.json", + include_str!("../../../../aws/policies/environment-admin.json"), + ), + ( + "environment-admin-network.json", + include_str!("../../../../aws/policies/environment-admin-network.json"), + ), + ], + Tier::WorkspaceUser => &[( + "workspace-user.json", + include_str!("../../../../aws/policies/workspace-user.json"), + )], } } @@ -125,6 +140,10 @@ const COMPONENT_REQUESTED: Context = &[("aws:RequestTag/triple-c:component", Literal("environment"))]; const COMPONENT_RESOURCE_TAG: &str = "aws:ResourceTag/triple-c:component"; const COMPONENT_TAGGED: Context = &[(COMPONENT_RESOURCE_TAG, Literal("environment"))]; +/// A call a service makes on the caller's behalf. +const VIA_AWS_SERVICE: Context = &[("aws:ViaAWSService", Literal("true"))]; +/// The state bucket is created tagged `triple-c:component=state`. +const STATE_REQUESTED: Context = &[("aws:RequestTag/triple-c:component", Literal("state"))]; const PROBE_CLUSTER: &str = "arn:aws:ecs:{region}:{account}:cluster/triple-c-probe"; const PROBE_TASK: &str = @@ -139,7 +158,6 @@ const PROBE_ALIAS: &str = "arn:aws:kms:{region}:{account}:alias/triple-c-probe"; const PROBE_LOG_GROUP: &str = "arn:aws:logs:{region}:{account}:log-group:/triple-c/probe"; const PROBE_PARAMETER: &str = "arn:aws:ssm:{region}:{account}:parameter/triple-c/environments/probe"; -const PROBE_STACK: &str = "arn:aws:cloudformation:{region}:{account}:stack/triple-c-probe/00000000-0000-0000-0000-000000000000"; const PROBE_FILE_SYSTEM: &str = "arn:aws:elasticfilesystem:{region}:{account}:file-system/fs-00000000"; const PROBE_ACCESS_POINT: &str = @@ -148,6 +166,22 @@ const PROBE_SECURITY_GROUP: &str = "arn:aws:ec2:{region}:{account}:security-group/sg-00000000000000000"; const PROBE_VPC: &str = "arn:aws:ec2:{region}:{account}:vpc/vpc-00000000000000000"; const PROBE_SESSION: &str = "arn:aws:ssm:{region}:{account}:session/probe-0123456789abcdef0"; +const PROBE_SUBNET: &str = "arn:aws:ec2:{region}:{account}:subnet/subnet-00000000000000000"; +const PROBE_INTERNET_GATEWAY: &str = + "arn:aws:ec2:{region}:{account}:internet-gateway/igw-00000000000000000"; +const PROBE_ROUTE_TABLE: &str = "arn:aws:ec2:{region}:{account}:route-table/rtb-00000000000000000"; +const PROBE_ELASTIC_IP: &str = + "arn:aws:ec2:{region}:{account}:elastic-ip/eipalloc-00000000000000000"; +const PROBE_NAT_GATEWAY: &str = "arn:aws:ec2:{region}:{account}:natgateway/nat-00000000000000000"; +const PROBE_NETWORK_INTERFACE: &str = + "arn:aws:ec2:{region}:{account}:network-interface/eni-00000000000000000"; +const PROBE_SECURITY_GROUP_RULE: &str = + "arn:aws:ec2:{region}:{account}:security-group-rule/sgr-00000000000000000"; +/// [`super::tofu_modules::state_bucket_name`]'s bucket. +const PROBE_STATE_BUCKET: &str = "arn:aws:s3:::triple-c-tfstate-{account}-{region}"; +const PROBE_STATE_OBJECT: &str = + "arn:aws:s3:::triple-c-tfstate-{account}-{region}/environments/probe/terraform.tfstate"; +const PROBE_BOUNDARY: &str = "arn:aws:iam::{account}:policy/triple-c-permissions-boundary"; const fn write(action: &'static str, resource: &'static str, context: Context) -> Check { Check { @@ -255,13 +289,15 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[ PROBE_SECRET, &[(OWNER_RESOURCE_TAG, OwnerId)], ), - // Only on the environment's (component-tagged) file system. + // Only on the user's own file system: Triple-C's (component-tagged by + // their onboarding module) and tagged with their owner ID (D2). write( "elasticfilesystem:CreateAccessPoint", PROBE_FILE_SYSTEM, &[ (OWNER_REQUEST_TAG, OwnerId), - (COMPONENT_RESOURCE_TAG, Literal("environment")), + (OWNER_RESOURCE_TAG, OwnerId), + (COMPONENT_RESOURCE_TAG, Literal("user-onboarding")), ], ), write( @@ -320,8 +356,6 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[ read("ecs:DescribeClusters", PROBE_CLUSTER, &[]), read("ecs:ListClusters", "*", &[]), read("ssm:GetParametersByPath", PROBE_PARAMETER, &[]), - read("cloudformation:DescribeStacks", "*", &[]), - read("cloudformation:ListStacks", "*", &[]), read("secretsmanager:ListSecrets", "*", &[]), read("elasticfilesystem:DescribeAccessPoints", "*", &[]), read( @@ -333,10 +367,10 @@ const WORKSPACE_USER_CHECKS: &[Check] = &[ read("sts:GetCallerIdentity", "*", &[]), ]; +/// The admin tier's checks, across all its files. `tofu_modules`' tests hold +/// the per-resource table these are drawn from. const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ - write("cloudformation:CreateStack", PROBE_STACK, &[]), - write("cloudformation:UpdateStack", PROBE_STACK, &[]), - write("cloudformation:DeleteStack", PROBE_STACK, &[]), + // Roles: bounded writes, by name. write("iam:CreateRole", PROBE_ROLE, WITH_BOUNDARY), write("iam:PutRolePolicy", PROBE_ROLE, WITH_BOUNDARY), write("iam:DeleteRolePolicy", PROBE_ROLE, WITH_BOUNDARY), @@ -344,7 +378,14 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ write("iam:DetachRolePolicy", PROBE_ROLE, WITH_BOUNDARY), write("iam:DeleteRole", PROBE_ROLE, &[]), write("iam:TagRole", PROBE_ROLE, &[]), + write("iam:UntagRole", PROBE_ROLE, &[]), + write("iam:UpdateRole", PROBE_ROLE, &[]), + write("iam:UpdateRoleDescription", PROBE_ROLE, &[]), read("iam:GetRole", PROBE_ROLE, &[]), + read("iam:GetRolePolicy", PROBE_ROLE, &[]), + read("iam:ListRolePolicies", PROBE_ROLE, &[]), + read("iam:ListAttachedRolePolicies", PROBE_ROLE, &[]), + read("iam:ListInstanceProfilesForRole", PROBE_ROLE, &[]), write( "iam:PassRole", PROBE_ROLE, @@ -352,9 +393,21 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ ), read("iam:GetRole", "{principal}", OWN_PRINCIPAL), read("iam:SimulatePrincipalPolicy", "{principal}", OWN_PRINCIPAL), - write("ecs:CreateCluster", PROBE_CLUSTER, &[]), + // Detection reads the boundary policy. + read("iam:GetPolicy", PROBE_BOUNDARY, &[]), + // ECS, by name. + write("ecs:CreateCluster", PROBE_CLUSTER, COMPONENT_REQUESTED), write("ecs:DeleteCluster", PROBE_CLUSTER, &[]), + write("ecs:UpdateCluster", PROBE_CLUSTER, &[]), write("ecs:PutClusterCapacityProviders", PROBE_CLUSTER, &[]), + write( + "ecs:TagResource", + PROBE_CLUSTER, + &[("ecs:CreateAction", Literal("CreateCluster"))], + ), + write("ecs:UntagResource", PROBE_CLUSTER, &[]), + read("ecs:DescribeClusters", PROBE_CLUSTER, &[]), + read("ecs:ListTagsForResource", PROBE_CLUSTER, &[]), write( "ecs:CreateCapacityProvider", "arn:aws:ecs:{region}:{account}:capacity-provider/triple-c-probe", @@ -367,19 +420,104 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ ), write("ecs:RegisterTaskDefinition", "*", &[]), write("ecs:DeregisterTaskDefinition", "*", &[]), - // CreateSecurityGroup is authorized against the new group and the VPC. + // The network (environment-admin-network.json). Creates carry the + // component request tag and are authorized against the new resource and + // its parents; tags go on only through the creating call. + write("ec2:CreateVpc", PROBE_VPC, COMPONENT_REQUESTED), + write("ec2:CreateSubnet", PROBE_SUBNET, COMPONENT_REQUESTED), + write("ec2:CreateSubnet", PROBE_VPC, COMPONENT_REQUESTED), + write( + "ec2:CreateInternetGateway", + PROBE_INTERNET_GATEWAY, + COMPONENT_REQUESTED, + ), + write( + "ec2:CreateRouteTable", + PROBE_ROUTE_TABLE, + COMPONENT_REQUESTED, + ), + write("ec2:CreateRouteTable", PROBE_VPC, COMPONENT_REQUESTED), + write("ec2:AllocateAddress", PROBE_ELASTIC_IP, COMPONENT_REQUESTED), + write( + "ec2:CreateNatGateway", + PROBE_NAT_GATEWAY, + COMPONENT_REQUESTED, + ), + write("ec2:CreateNatGateway", PROBE_SUBNET, COMPONENT_REQUESTED), + write( + "ec2:CreateNatGateway", + PROBE_ELASTIC_IP, + COMPONENT_REQUESTED, + ), write( "ec2:CreateSecurityGroup", PROBE_SECURITY_GROUP, COMPONENT_REQUESTED, ), - write("ec2:CreateSecurityGroup", PROBE_VPC, &[]), + write("ec2:CreateSecurityGroup", PROBE_VPC, COMPONENT_REQUESTED), write( "ec2:CreateTags", PROBE_SECURITY_GROUP, &[("ec2:CreateAction", Literal("CreateSecurityGroup"))], ), + write( + "ec2:CreateTags", + PROBE_VPC, + &[("ec2:CreateAction", Literal("CreateVpc"))], + ), + write( + "ec2:CreateTags", + PROBE_NAT_GATEWAY, + &[("ec2:CreateAction", Literal("CreateNatGateway"))], + ), + // Changes and deletes need the component tag on the resource. write("ec2:CreateTags", PROBE_SECURITY_GROUP, COMPONENT_TAGGED), + write("ec2:DeleteTags", PROBE_SUBNET, COMPONENT_TAGGED), + write("ec2:ModifyVpcAttribute", PROBE_VPC, COMPONENT_TAGGED), + write("ec2:DeleteVpc", PROBE_VPC, COMPONENT_TAGGED), + write("ec2:ModifySubnetAttribute", PROBE_SUBNET, COMPONENT_TAGGED), + write("ec2:DeleteSubnet", PROBE_SUBNET, COMPONENT_TAGGED), + write( + "ec2:AttachInternetGateway", + PROBE_INTERNET_GATEWAY, + COMPONENT_TAGGED, + ), + write("ec2:AttachInternetGateway", PROBE_VPC, COMPONENT_TAGGED), + write( + "ec2:DetachInternetGateway", + PROBE_INTERNET_GATEWAY, + COMPONENT_TAGGED, + ), + write( + "ec2:DeleteInternetGateway", + PROBE_INTERNET_GATEWAY, + COMPONENT_TAGGED, + ), + write("ec2:DeleteRouteTable", PROBE_ROUTE_TABLE, COMPONENT_TAGGED), + // Routes and associations can't be tagged: their route table (and + // subnet) can. + write("ec2:CreateRoute", PROBE_ROUTE_TABLE, COMPONENT_TAGGED), + write("ec2:ReplaceRoute", PROBE_ROUTE_TABLE, COMPONENT_TAGGED), + write("ec2:DeleteRoute", PROBE_ROUTE_TABLE, COMPONENT_TAGGED), + write( + "ec2:AssociateRouteTable", + PROBE_ROUTE_TABLE, + COMPONENT_TAGGED, + ), + write("ec2:AssociateRouteTable", PROBE_SUBNET, COMPONENT_TAGGED), + write( + "ec2:ReplaceRouteTableAssociation", + PROBE_ROUTE_TABLE, + COMPONENT_TAGGED, + ), + write( + "ec2:DisassociateRouteTable", + PROBE_ROUTE_TABLE, + COMPONENT_TAGGED, + ), + write("ec2:DisassociateRouteTable", PROBE_SUBNET, COMPONENT_TAGGED), + write("ec2:ReleaseAddress", PROBE_ELASTIC_IP, COMPONENT_TAGGED), + write("ec2:DeleteNatGateway", PROBE_NAT_GATEWAY, COMPONENT_TAGGED), write( "ec2:DeleteSecurityGroup", PROBE_SECURITY_GROUP, @@ -390,14 +528,55 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ PROBE_SECURITY_GROUP, COMPONENT_TAGGED, ), + // Authorizing also names the new (untagged) rule. + write( + "ec2:AuthorizeSecurityGroupIngress", + PROBE_SECURITY_GROUP_RULE, + &[], + ), + write( + "ec2:AuthorizeSecurityGroupEgress", + PROBE_SECURITY_GROUP, + COMPONENT_TAGGED, + ), + write( + "ec2:AuthorizeSecurityGroupEgress", + PROBE_SECURITY_GROUP_RULE, + &[], + ), write( "ec2:RevokeSecurityGroupIngress", PROBE_SECURITY_GROUP, COMPONENT_TAGGED, ), + // The provider revokes AWS's default egress rule after creating a group. + write( + "ec2:RevokeSecurityGroupEgress", + PROBE_SECURITY_GROUP, + COMPONENT_TAGGED, + ), + write( + "ec2:UpdateSecurityGroupRuleDescriptionsIngress", + PROBE_SECURITY_GROUP, + COMPONENT_TAGGED, + ), + // EFS creates and deletes a mount target's interface with the caller's + // EC2 permissions. + write( + "ec2:CreateNetworkInterface", + PROBE_NETWORK_INTERFACE, + VIA_AWS_SERVICE, + ), + write("ec2:CreateNetworkInterface", PROBE_SUBNET, VIA_AWS_SERVICE), + write( + "ec2:DeleteNetworkInterface", + PROBE_NETWORK_INTERFACE, + VIA_AWS_SERVICE, + ), read("ec2:DescribeSecurityGroups", "*", &[]), - // CreateFileSystem has no resource type: IAM authorizes it against `*` - // (verified live; a `file-system/*` Resource never matches). + read("ec2:DescribeVpcs", "*", &[]), + // EFS. CreateFileSystem has no resource type: IAM authorizes it against + // `*` (verified live; a `file-system/*` Resource never matches). write( "elasticfilesystem:CreateFileSystem", "*", @@ -416,11 +595,26 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ PROBE_FILE_SYSTEM, COMPONENT_TAGGED, ), + write( + "elasticfilesystem:UntagResource", + PROBE_FILE_SYSTEM, + COMPONENT_TAGGED, + ), write( "elasticfilesystem:DeleteFileSystem", PROBE_FILE_SYSTEM, COMPONENT_TAGGED, ), + write( + "elasticfilesystem:UpdateFileSystem", + PROBE_FILE_SYSTEM, + COMPONENT_TAGGED, + ), + write( + "elasticfilesystem:PutLifecycleConfiguration", + PROBE_FILE_SYSTEM, + COMPONENT_TAGGED, + ), write( "elasticfilesystem:CreateMountTarget", PROBE_FILE_SYSTEM, @@ -431,23 +625,60 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ PROBE_FILE_SYSTEM, COMPONENT_TAGGED, ), + write( + "elasticfilesystem:ModifyMountTargetSecurityGroups", + PROBE_FILE_SYSTEM, + COMPONENT_TAGGED, + ), write( "elasticfilesystem:PutFileSystemPolicy", PROBE_FILE_SYSTEM, COMPONENT_TAGGED, ), + write( + "elasticfilesystem:DeleteFileSystemPolicy", + PROBE_FILE_SYSTEM, + COMPONENT_TAGGED, + ), + read( + "elasticfilesystem:DescribeFileSystems", + PROBE_FILE_SYSTEM, + &[], + ), + read( + "elasticfilesystem:ListTagsForResource", + PROBE_FILE_SYSTEM, + &[], + ), + // KMS. write("kms:CreateKey", "*", COMPONENT_REQUESTED), write("kms:ScheduleKeyDeletion", PROBE_KEY, COMPONENT_TAGGED), write("kms:PutKeyPolicy", PROBE_KEY, COMPONENT_TAGGED), + write("kms:EnableKeyRotation", PROBE_KEY, COMPONENT_TAGGED), + write("kms:UpdateKeyDescription", PROBE_KEY, COMPONENT_TAGGED), write("kms:TagResource", PROBE_KEY, COMPONENT_TAGGED), + write("kms:UntagResource", PROBE_KEY, COMPONENT_TAGGED), // An alias call is authorized against both the alias and the key. write("kms:CreateAlias", PROBE_ALIAS, &[]), write("kms:CreateAlias", PROBE_KEY, COMPONENT_TAGGED), + write("kms:UpdateAlias", PROBE_ALIAS, &[]), + write("kms:UpdateAlias", PROBE_KEY, COMPONENT_TAGGED), write("kms:DeleteAlias", PROBE_ALIAS, &[]), write("kms:DeleteAlias", PROBE_KEY, COMPONENT_TAGGED), - write("logs:CreateLogGroup", PROBE_LOG_GROUP, &[]), + read("kms:DescribeKey", PROBE_KEY, &[]), + read("kms:GetKeyPolicy", PROBE_KEY, &[]), + read("kms:GetKeyRotationStatus", PROBE_KEY, &[]), + read("kms:ListResourceTags", PROBE_KEY, &[]), + read("kms:ListAliases", "*", &[]), + // Logs, SSM, ECR, by name. + write("logs:CreateLogGroup", PROBE_LOG_GROUP, COMPONENT_REQUESTED), + write("logs:TagResource", PROBE_LOG_GROUP, COMPONENT_REQUESTED), + write("logs:UntagResource", PROBE_LOG_GROUP, &[]), write("logs:DeleteLogGroup", PROBE_LOG_GROUP, &[]), write("logs:PutRetentionPolicy", PROBE_LOG_GROUP, &[]), + write("logs:DeleteRetentionPolicy", PROBE_LOG_GROUP, &[]), + read("logs:ListTagsForResource", PROBE_LOG_GROUP, &[]), + read("logs:DescribeLogGroups", "*", &[]), write( "ecr:CreateRepository", "arn:aws:ecr:{region}:{account}:repository/triple-c/probe", @@ -459,96 +690,63 @@ const ENVIRONMENT_ADMIN_CHECKS: &[Check] = &[ &[], ), write("ecr:CreatePullThroughCacheRule", "*", &[]), - write("ssm:PutParameter", PROBE_PARAMETER, &[]), + write("ssm:PutParameter", PROBE_PARAMETER, COMPONENT_REQUESTED), + write( + "ssm:AddTagsToResource", + PROBE_PARAMETER, + COMPONENT_REQUESTED, + ), + write("ssm:RemoveTagsFromResource", PROBE_PARAMETER, &[]), write("ssm:DeleteParameter", PROBE_PARAMETER, &[]), + read("ssm:GetParameter", PROBE_PARAMETER, &[]), + read("ssm:ListTagsForResource", PROBE_PARAMETER, &[]), + read("ssm:DescribeParameters", "*", &[]), + read("sts:GetCallerIdentity", "*", &[]), + // The state bucket (the app creates it; OpenTofu's S3 backend reads and + // writes the state and lock objects). + write("s3:CreateBucket", PROBE_STATE_BUCKET, STATE_REQUESTED), + write("s3:PutBucketVersioning", PROBE_STATE_BUCKET, &[]), + write("s3:PutEncryptionConfiguration", PROBE_STATE_BUCKET, &[]), + write("s3:PutBucketPublicAccessBlock", PROBE_STATE_BUCKET, &[]), + write("s3:PutBucketTagging", PROBE_STATE_BUCKET, &[]), + write("s3:PutBucketPolicy", PROBE_STATE_BUCKET, &[]), + read("s3:GetBucketVersioning", PROBE_STATE_BUCKET, &[]), + read("s3:ListBucket", PROBE_STATE_BUCKET, &[]), + read("s3:GetObject", PROBE_STATE_OBJECT, &[]), + write("s3:PutObject", PROBE_STATE_OBJECT, &[]), + write("s3:DeleteObject", PROBE_STATE_OBJECT, &[]), ]; #[cfg(test)] mod tests { use super::*; + use crate::aws::policy_eval::{ + actions, conditions_hold, effect, evaluate_in, glob, matching, parse, rendered, resources, + sid, statements_of, strings, Request, ME, SOMEONE_ELSE, + }; use serde_json::Value; use std::collections::BTreeSet; - const AT: Placeholders = Placeholders { - region: "us-west-2", - account: "111122223333", - principal: "arn:aws:iam::111122223333:role/aws-reserved/sso.amazonaws.com/us-west-2/AWSReservedSSO_Dev_0123456789abcdef", - }; - const ME: &str = "AROAEXAMPLEME:alice@example.com"; - const SOMEONE_ELSE: &str = "AROAEXAMPLEOTHER:bob@example.com"; - const TIERS: [Tier; 2] = [Tier::WorkspaceUser, Tier::EnvironmentAdmin]; - /// IAM wildcard match: `*` is any run of characters (including `:` and - /// `/`), `?` is exactly one. - fn glob(pattern: &str, text: &str) -> bool { - let p: Vec = pattern.chars().collect(); - let t: Vec = text.chars().collect(); - let (mut pi, mut ti) = (0, 0); - let (mut star, mut mark) = (None, 0); - while ti < t.len() { - if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { - pi += 1; - ti += 1; - } else if pi < p.len() && p[pi] == '*' { - star = Some(pi); - mark = ti; - pi += 1; - } else if let Some(s) = star { - pi = s + 1; - mark += 1; - ti = mark; - } else { - return false; - } - } - while pi < p.len() && p[pi] == '*' { - pi += 1; - } - pi == p.len() - } - - #[test] - fn glob_behaves_like_iam_wildcards() { - assert!(glob("ecs:Describe*", "ecs:DescribeClusters")); - assert!(!glob("ecs:Describe*", "ecs:ListClusters")); - assert!(glob( - "arn:aws:ecs:*:*:task/triple-c-*/*", - "arn:aws:ecs:us-west-2:1:task/triple-c-x/abc" - )); - assert!(!glob( - "arn:aws:ecs:*:*:task/triple-c-*/*", - "arn:aws:ecs:us-west-2:1:task/other/abc" - )); - assert!(glob("a?c", "abc")); - assert!(!glob("a?c", "ac")); - } - - fn parse(name: &str, json: &str) -> Value { - serde_json::from_str(json).unwrap_or_else(|e| panic!("{name} is not JSON: {e}")) - } - - fn policy(tier: Tier) -> Value { - parse(&format!("{tier:?} policy"), policy_json(tier)) + /// Every file of `tier`, parsed: (file name, document). + fn policies(tier: Tier) -> Vec<(&'static str, Value)> { + policy_files(tier) + .iter() + .map(|(name, json)| (*name, parse(name, json))) + .collect() } fn boundary() -> Value { parse("permissions boundary", permissions_boundary_json()) } - fn statements_of(doc: &Value) -> Vec { - doc["Statement"] - .as_array() - .expect("policy has no Statement array") - .clone() - } - + /// The statements of every file of `tier`, which IAM evaluates together. fn statements(tier: Tier) -> Vec { - statements_of(&policy(tier)) - } - - fn effect(stmt: &Value) -> &str { - stmt["Effect"].as_str().unwrap_or("") + policies(tier) + .iter() + .flat_map(|(_, doc)| statements_of(doc)) + .collect() } fn allows(tier: Tier) -> Vec { @@ -565,185 +763,10 @@ mod tests { .collect() } - /// `Action` / `Resource` / condition values: a string or an array of them. - fn strings(v: &Value) -> Vec { - match v { - Value::String(s) => vec![s.clone()], - Value::Array(a) => a - .iter() - .map(|x| x.as_str().expect("expected a string").to_string()) - .collect(), - other => panic!("expected a string or array, got {other}"), - } - } - - fn actions(stmt: &Value) -> Vec { - strings(&stmt["Action"]) - } - - fn resources(stmt: &Value) -> Vec { - strings(&stmt["Resource"]) - } - - fn sid(stmt: &Value) -> &str { - stmt["Sid"].as_str().unwrap_or("") - } - - fn rendered(check: &Check) -> String { - render(check.resource, &AT) - } - - /// The request: who calls, and whose the resource / request tag is. - #[derive(Clone, Copy)] - struct Request<'a> { - check: &'a Check, - /// `${aws:userid}` of the caller. - caller: &'a str, - /// What `OwnerId` context entries carry. - owner: &'a str, - } - - impl Request<'_> { - fn context_value(&self, key: &str) -> Option { - self.context_values(key).into_iter().next() - } - - /// All values of a (possibly multi-valued) key. - fn context_values(&self, key: &str) -> Vec { - self.check - .context - .iter() - .filter(|(k, _)| *k == key) - .map(|(_, v)| match v { - ContextValue::OwnerId => self.owner.to_string(), - ContextValue::Literal(l) => render(l, &AT), - }) - .collect() - } - - /// Resolves `${…}` policy variables the way the simulator does: from - /// the request context. An unresolvable variable makes the string - /// match nothing (`None`). - fn resolve(&self, s: &str) -> Option { - let mut out = String::new(); - let mut rest = s; - while let Some(start) = rest.find("${") { - out.push_str(&rest[..start]); - let end = rest[start..].find('}').expect("unterminated ${") + start; - let name = &rest[start + 2..end]; - let value = if name == "aws:userid" { - Some(self.caller.to_string()) - } else { - self.context_value(name) - }; - out.push_str(&value?); - rest = &rest[end + 1..]; - } - out.push_str(rest); - Some(out) - } - } - - /// Statements that name the action and one of whose resources matches - /// the rendered resource. - fn matching<'s>(stmts: &'s [Value], req: &Request) -> Vec<&'s Value> { - let resource = rendered(req.check); - stmts - .iter() - .filter(|s| actions(s).iter().any(|a| glob(a, req.check.action))) - .filter(|s| { - resources(s) - .iter() - .filter_map(|r| req.resolve(r)) - .any(|r| glob(&r, &resource)) - }) - .collect() - } - - /// A deliberately small IAM condition evaluator: the operators the - /// shipped policies use, and nothing else (an unknown operator fails the - /// test rather than being ignored). - fn conditions_hold(stmt: &Value, req: &Request) -> bool { - let Some(cond) = stmt.get("Condition") else { - return true; - }; - let cond = cond.as_object().expect("Condition is an object"); - cond.iter().all(|(op, entries)| { - let entries = entries.as_object().expect("condition block is an object"); - // ForAllValues: every value of the (multi-valued) key matches - // one of the policy's values. Vacuously true when the key is - // absent, which is why statements pair it with a required key. - if let Some(base) = op.strip_prefix("ForAllValues:") { - assert_eq!( - base, - "StringEquals", - "{}: unsupported ForAllValues operator", - sid(stmt) - ); - return entries.iter().all(|(key, want)| { - let allowed: Vec = strings(want) - .iter() - .filter_map(|p| req.resolve(p)) - .collect(); - req.context_values(key).iter().all(|v| allowed.contains(v)) - }); - } - if op == "Null" { - return entries.iter().all(|(key, want)| { - let absent = req.context_value(key).is_none(); - match want.as_str() { - Some("true") => absent, - Some("false") => !absent, - _ => panic!("{}: Null takes \"true\" or \"false\"", sid(stmt)), - } - }); - } - let (base, if_exists) = match op.strip_suffix("IfExists") { - Some(b) => (b, true), - None => (op.as_str(), false), - }; - // A negated operator holds when the key is absent, and - // otherwise when no value matches. - let (matches, negated): (fn(&str, &str) -> bool, bool) = match base { - "StringEquals" => (|p, v| p == v, false), - "StringLike" | "ArnLike" => (glob, false), - "StringNotEquals" => (|p, v| p == v, true), - "StringNotLike" => (glob, true), - other => panic!("{}: unsupported condition operator {other}", sid(stmt)), - }; - entries - .iter() - .all(|(key, want)| match req.context_value(key) { - None => if_exists || negated, - Some(value) => { - let any = strings(want) - .iter() - .filter_map(|p| req.resolve(p)) - .any(|p| matches(&p, &value)); - any != negated - } - }) - }) - } - fn evaluate(tier: Tier, req: Request) -> bool { evaluate_in(&statements(tier), req) } - /// Allowed by some Allow and by no Deny among `stmts`. - fn evaluate_in(stmts: &[Value], req: Request) -> bool { - let applies = |s: &&Value| conditions_hold(s, &req); - let allowed = matching(stmts, &req) - .into_iter() - .filter(|s| effect(s) == "Allow") - .any(|s| applies(&s)); - let denied = matching(stmts, &req) - .into_iter() - .filter(|s| effect(s) == "Deny") - .any(|s| applies(&s)); - allowed && !denied - } - fn allowed(tier: Tier, check: &Check, caller: &str, owner: &str) -> bool { evaluate( tier, @@ -787,7 +810,9 @@ mod tests { #[test] fn policies_are_valid_iam_json() { for tier in TIERS { - validate_document(&format!("{tier:?}"), &policy(tier)); + for (name, doc) in policies(tier) { + validate_document(name, &doc); + } assert!(!allows(tier).is_empty(), "{tier:?} allows nothing"); } validate_document("permissions boundary", &boundary()); @@ -868,6 +893,11 @@ mod tests { "file-system/", OWNER_REQUEST_TAG, ), + ( + "elasticfilesystem:CreateAccessPoint", + "file-system/", + OWNER_RESOURCE_TAG, + ), ( "elasticfilesystem:TagResource", "access-point/", @@ -1127,14 +1157,8 @@ mod tests { /// live: "Resource ${aws:PrincipalArn} must be in ARN format or \"*\""). #[test] fn every_resource_is_an_arn_or_star() { - let docs = [ - ("workspace-user", policy(Tier::WorkspaceUser)), - ("environment-admin", policy(Tier::EnvironmentAdmin)), - ( - "permissions-boundary", - serde_json::from_str(permissions_boundary_json()).unwrap(), - ), - ]; + let mut docs: Vec<(&str, Value)> = TIERS.into_iter().flat_map(policies).collect(); + docs.push(("permissions-boundary.json", boundary())); for (name, doc) in &docs { for s in statements_of(doc) { for r in resources(&s) { @@ -1150,16 +1174,17 @@ mod tests { /// A customer managed policy may hold 6,144 characters, not counting /// whitespace (verified live: the workspace policy is close). An - /// environment admin needs both tier policies, which together exceed a - /// role's 10,240-character inline budget, so they ship as managed - /// policies. + /// environment admin needs every file of both tiers, which together + /// exceed a role's 10,240-character inline budget, so they ship as + /// managed policies, the admin tier in several (D7). #[test] fn every_policy_fits_a_managed_policy() { - for (name, text) in [ - ("workspace-user", policy_json(Tier::WorkspaceUser)), - ("environment-admin", policy_json(Tier::EnvironmentAdmin)), - ("permissions-boundary", permissions_boundary_json()), - ] { + let mut files: Vec<(&str, &str)> = TIERS + .into_iter() + .flat_map(|t| policy_files(t).iter().copied()) + .collect(); + files.push(("permissions-boundary.json", permissions_boundary_json())); + for (name, text) in files { let size = text.chars().filter(|c| !c.is_whitespace()).count(); assert!( size <= 6144, @@ -1522,28 +1547,195 @@ mod tests { assert!(allowed(tier, create, ME, ME)); } + /// Strict tenancy (D2): each user has their own file system, tagged + /// with their owner ID by their onboarding module, and may create access + /// points only there. #[test] - fn access_points_only_on_the_environments_file_system() { + fn access_points_only_on_the_users_own_file_system() { let c = checks(Tier::WorkspaceUser) .iter() .find(|c| c.action == "elasticfilesystem:CreateAccessPoint") .unwrap(); + assert!(allowed(Tier::WorkspaceUser, c, ME, ME)); let foreign_fs = Check { context: &[(OWNER_REQUEST_TAG, OwnerId)], ..*c }; assert!(!allowed(Tier::WorkspaceUser, &foreign_fs, ME, ME)); + // Someone else's onboarding file system, with my owner tag requested. + let someone_elses_fs = Check { + context: &[ + (OWNER_REQUEST_TAG, OwnerId), + (OWNER_RESOURCE_TAG, Literal(SOMEONE_ELSE)), + (COMPONENT_RESOURCE_TAG, Literal("user-onboarding")), + ], + ..*c + }; + assert!(!allowed(Tier::WorkspaceUser, &someone_elses_fs, ME, ME)); + // An owner-tagged file system that isn't Triple-C's. + let not_triple_c = Check { + context: &[(OWNER_REQUEST_TAG, OwnerId), (OWNER_RESOURCE_TAG, OwnerId)], + ..*c + }; + assert!(!allowed(Tier::WorkspaceUser, ¬_triple_c, ME, ME)); + } + + #[test] + fn the_admin_tier_spans_its_files() { + let names = |t: Tier| policy_files(t).iter().map(|(n, _)| *n).collect::>(); + assert_eq!( + names(Tier::EnvironmentAdmin), + ["environment-admin.json", "environment-admin-network.json"] + ); + assert_eq!(names(Tier::WorkspaceUser), ["workspace-user.json"]); + } + + /// D8: CloudFormation leaves the policies, the checks and the probes. + #[test] + fn no_policy_mentions_cloudformation() { + let mut texts: Vec<(&str, &str)> = TIERS + .into_iter() + .flat_map(|t| policy_files(t).iter().copied()) + .collect(); + texts.push(("permissions-boundary.json", permissions_boundary_json())); + for (name, text) in texts { + assert!( + !text.to_ascii_lowercase().contains("cloudformation"), + "{name} mentions CloudFormation" + ); + } + for tier in TIERS { + for c in checks(tier) { + assert!( + !c.action.starts_with("cloudformation:") + && !c.resource.contains("cloudformation"), + "{tier:?}: check {} on {}", + c.action, + c.resource + ); + } + } + } + + /// The network the admin creates is tag-scoped like everything else: an + /// untagged VPC, subnet, gateway or route table is someone else's, and + /// the only bucket the admin may touch is the state bucket. + #[test] + fn the_admin_still_cannot_touch_untagged_resources() { + let tier = Tier::EnvironmentAdmin; + for (action, resource) in [ + ("ec2:DeleteVpc", PROBE_VPC), + ("ec2:ModifyVpcAttribute", PROBE_VPC), + ("ec2:DeleteSubnet", PROBE_SUBNET), + ("ec2:DeleteInternetGateway", PROBE_INTERNET_GATEWAY), + ("ec2:DetachInternetGateway", PROBE_INTERNET_GATEWAY), + ("ec2:DeleteRouteTable", PROBE_ROUTE_TABLE), + ("ec2:CreateRoute", PROBE_ROUTE_TABLE), + ("ec2:DeleteRoute", PROBE_ROUTE_TABLE), + ("ec2:AssociateRouteTable", PROBE_ROUTE_TABLE), + ("ec2:DeleteNatGateway", PROBE_NAT_GATEWAY), + ("ec2:ReleaseAddress", PROBE_ELASTIC_IP), + ("ec2:DeleteSecurityGroup", PROBE_SECURITY_GROUP), + ("ec2:CreateTags", PROBE_VPC), + ("ec2:DeleteTags", PROBE_SUBNET), + ] { + let tagged = write(action, resource, COMPONENT_TAGGED); + assert!( + allowed(tier, &tagged, ME, ME), + "{action} on a tagged {resource}" + ); + let untagged = write(action, resource, &[]); + assert!( + !allowed(tier, &untagged, ME, ME), + "{action} on an untagged {resource}" + ); + } + // Creates need the component request tag. + for (action, resource) in [ + ("ec2:CreateVpc", PROBE_VPC), + ("ec2:CreateSubnet", PROBE_SUBNET), + ("ec2:CreateInternetGateway", PROBE_INTERNET_GATEWAY), + ("ec2:CreateRouteTable", PROBE_ROUTE_TABLE), + ("ec2:AllocateAddress", PROBE_ELASTIC_IP), + ("ec2:CreateNatGateway", PROBE_NAT_GATEWAY), + ] { + assert!( + allowed(tier, &write(action, resource, COMPONENT_REQUESTED), ME, ME), + "{action}" + ); + assert!( + !allowed(tier, &write(action, resource, &[]), ME, ME), + "untagged {action}" + ); + } + // Tags go on at create only through the creating call. + let tag_at = |create: &'static str| -> Check { + let ctx: Context = + Box::leak(vec![("ec2:CreateAction", Literal(create))].into_boxed_slice()); + write("ec2:CreateTags", PROBE_VPC, ctx) + }; + assert!(allowed(tier, &tag_at("CreateVpc"), ME, ME)); + assert!(!allowed(tier, &tag_at("RunInstances"), ME, ME)); + // A mount target's interface is EFS's doing, never a direct call. + for action in ["ec2:CreateNetworkInterface", "ec2:DeleteNetworkInterface"] { + assert!( + !allowed(tier, &write(action, PROBE_NETWORK_INTERFACE, &[]), ME, ME), + "{action}" + ); + } + // No bucket may be deleted, and only the state bucket is managed. + const OTHER_BUCKET: &str = "arn:aws:s3:::someone-elses-bucket"; + for bucket in [PROBE_STATE_BUCKET, OTHER_BUCKET] { + for context in [&[][..], COMPONENT_TAGGED] { + assert!( + !allowed(tier, &write("s3:DeleteBucket", bucket, context), ME, ME), + "s3:DeleteBucket on {bucket}" + ); + } + } + for action in [ + "s3:PutBucketPolicy", + "s3:PutBucketVersioning", + "s3:PutEncryptionConfiguration", + "s3:PutBucketPublicAccessBlock", + "s3:PutBucketTagging", + ] { + assert!( + allowed(tier, &write(action, PROBE_STATE_BUCKET, &[]), ME, ME), + "{action}" + ); + assert!( + !allowed(tier, &write(action, OTHER_BUCKET, &[]), ME, ME), + "{action}" + ); + } + for action in ["s3:PutObject", "s3:DeleteObject", "s3:GetObject"] { + let check = Check { + write: action != "s3:GetObject", + ..write(action, "arn:aws:s3:::someone-elses-bucket/key", &[]) + }; + assert!(!allowed(tier, &check, ME, ME), "{action}"); + } + assert!(allowed( + tier, + &write("s3:CreateBucket", PROBE_STATE_BUCKET, STATE_REQUESTED), + ME, + ME + )); + assert!(!allowed( + tier, + &write("s3:CreateBucket", PROBE_STATE_BUCKET, &[]), + ME, + ME + )); + assert!(!allowed( + tier, + &write("s3:CreateBucket", OTHER_BUCKET, STATE_REQUESTED), + ME, + ME + )); } - const CFN_WRITES: &[&str] = &[ - "cloudformation:CreateStack", - "cloudformation:UpdateStack", - "cloudformation:CreateChangeSet", - ]; - const WITH_SERVICE_ROLE: Context = &[( - "cloudformation:RoleArn", - Literal("arn:aws:iam::{account}:role/AnyServiceRole"), - )]; const OTHER_BOUNDARY: Context = &[ ( "iam:PermissionsBoundary", @@ -1552,19 +1744,6 @@ mod tests { ("aws:PrincipalAccount", Literal("{account}")), ]; - #[test] - fn triple_c_stacks_cannot_use_a_service_role() { - for action in CFN_WRITES { - let with_role = write(action, PROBE_STACK, WITH_SERVICE_ROLE); - assert!( - !allowed(Tier::EnvironmentAdmin, &with_role, ME, ME), - "{action} allowed with a CloudFormation service role" - ); - let plain = write(action, PROBE_STACK, &[]); - assert!(allowed(Tier::EnvironmentAdmin, &plain, ME, ME), "{action}"); - } - } - /// True if some Deny statement in `tier` applies to `check`. fn explicitly_denied(tier: Tier, check: &Check) -> bool { let stmts = denies(tier); @@ -1634,11 +1813,6 @@ mod tests { } } } - // A stack deployed with a service role would act outside the - // boundary. - for action in CFN_WRITES { - assert!(denied(&write(action, PROBE_STACK, WITH_SERVICE_ROLE))); - } } const ALLOWED_TAG_KEYS: [&str; 3] = @@ -1766,39 +1940,6 @@ mod tests { } } - #[test] - fn for_all_values_is_vacuous_on_an_absent_key() { - let stmt: Value = serde_json::json!({ - "Sid": "T", "Effect": "Allow", "Action": "x:Y", "Resource": "*", - "Condition": { "ForAllValues:StringEquals": { "aws:TagKeys": ["a", "b"] } } - }); - let check = |context| Check { - action: "x:Y", - resource: "*", - context, - write: true, - }; - let holds = |c: &Check| { - conditions_hold( - &stmt, - &Request { - check: c, - caller: ME, - owner: ME, - }, - ) - }; - assert!(holds(&check(&[]))); - assert!(holds(&check(&[ - ("aws:TagKeys", Literal("a")), - ("aws:TagKeys", Literal("b")) - ]))); - assert!(!holds(&check(&[ - ("aws:TagKeys", Literal("a")), - ("aws:TagKeys", Literal("c")) - ]))); - } - /// A key whose *key policy* grants account principals through Secrets /// Manager (the AWS-managed `aws/secretsmanager` key, or any such customer /// key) needs no identity-policy Allow, so only an explicit Deny keeps a diff --git a/app/src-tauri/src/aws/policy_eval.rs b/app/src-tauri/src/aws/policy_eval.rs new file mode 100644 index 0000000..2eccb56 --- /dev/null +++ b/app/src-tauri/src/aws/policy_eval.rs @@ -0,0 +1,320 @@ +//! The test-only IAM evaluator the policy drift guards use (moved here from +//! `policies.rs` so the Terraform-module tests can ask it too). It is +//! deliberately small: the operators the shipped policies use and nothing +//! else; an unknown operator fails the test rather than being ignored. It is +//! not IAM -- `live_tests.rs` and the live runs are the proof. + +use serde_json::Value; + +use super::policies::{render, Check, ContextValue, Placeholders}; + +pub(crate) const AT: Placeholders = Placeholders { + region: "us-west-2", + account: "111122223333", + principal: "arn:aws:iam::111122223333:role/aws-reserved/sso.amazonaws.com/us-west-2/AWSReservedSSO_Dev_0123456789abcdef", +}; +pub(crate) const ME: &str = "AROAEXAMPLEME:alice@example.com"; +pub(crate) const SOMEONE_ELSE: &str = "AROAEXAMPLEOTHER:bob@example.com"; + +/// IAM wildcard match: `*` is any run of characters (including `:` and +/// `/`), `?` is exactly one. +pub(crate) fn glob(pattern: &str, text: &str) -> bool { + let p: Vec = pattern.chars().collect(); + let t: Vec = text.chars().collect(); + let (mut pi, mut ti) = (0, 0); + let (mut star, mut mark) = (None, 0); + while ti < t.len() { + if pi < p.len() && (p[pi] == '?' || p[pi] == t[ti]) { + pi += 1; + ti += 1; + } else if pi < p.len() && p[pi] == '*' { + star = Some(pi); + mark = ti; + pi += 1; + } else if let Some(s) = star { + pi = s + 1; + mark += 1; + ti = mark; + } else { + return false; + } + } + while pi < p.len() && p[pi] == '*' { + pi += 1; + } + pi == p.len() +} + +pub(crate) fn parse(name: &str, json: &str) -> Value { + serde_json::from_str(json).unwrap_or_else(|e| panic!("{name} is not JSON: {e}")) +} + +pub(crate) fn statements_of(doc: &Value) -> Vec { + doc["Statement"] + .as_array() + .expect("policy has no Statement array") + .clone() +} + +pub(crate) fn effect(stmt: &Value) -> &str { + stmt["Effect"].as_str().unwrap_or("") +} + +/// `Action` / `Resource` / condition values: a string or an array of them. +pub(crate) fn strings(v: &Value) -> Vec { + match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a + .iter() + .map(|x| x.as_str().expect("expected a string").to_string()) + .collect(), + other => panic!("expected a string or array, got {other}"), + } +} + +pub(crate) fn actions(stmt: &Value) -> Vec { + strings(&stmt["Action"]) +} + +pub(crate) fn resources(stmt: &Value) -> Vec { + strings(&stmt["Resource"]) +} + +pub(crate) fn sid(stmt: &Value) -> &str { + stmt["Sid"].as_str().unwrap_or("") +} + +pub(crate) fn rendered(check: &Check) -> String { + render(check.resource, &AT) +} + +/// The request: who calls, and whose the resource / request tag is. +#[derive(Clone, Copy)] +pub(crate) struct Request<'a> { + pub check: &'a Check, + /// `${aws:userid}` of the caller. + pub caller: &'a str, + /// What `OwnerId` context entries carry. + pub owner: &'a str, +} + +impl Request<'_> { + pub(crate) fn context_value(&self, key: &str) -> Option { + self.context_values(key).into_iter().next() + } + + /// All values of a (possibly multi-valued) key. + pub(crate) fn context_values(&self, key: &str) -> Vec { + self.check + .context + .iter() + .filter(|(k, _)| *k == key) + .map(|(_, v)| match v { + ContextValue::OwnerId => self.owner.to_string(), + ContextValue::Literal(l) => render(l, &AT), + }) + .collect() + } + + /// Resolves `${…}` policy variables the way the simulator does: from + /// the request context. An unresolvable variable makes the string + /// match nothing (`None`). + pub(crate) fn resolve(&self, s: &str) -> Option { + let mut out = String::new(); + let mut rest = s; + while let Some(start) = rest.find("${") { + out.push_str(&rest[..start]); + let end = rest[start..].find('}').expect("unterminated ${") + start; + let name = &rest[start + 2..end]; + let value = if name == "aws:userid" { + Some(self.caller.to_string()) + } else { + self.context_value(name) + }; + out.push_str(&value?); + rest = &rest[end + 1..]; + } + out.push_str(rest); + Some(out) + } +} + +/// Statements that name the action and one of whose resources matches +/// the rendered resource. +pub(crate) fn matching<'s>(stmts: &'s [Value], req: &Request) -> Vec<&'s Value> { + let resource = rendered(req.check); + stmts + .iter() + .filter(|s| actions(s).iter().any(|a| glob(a, req.check.action))) + .filter(|s| { + resources(s) + .iter() + .filter_map(|r| req.resolve(r)) + .any(|r| glob(&r, &resource)) + }) + .collect() +} + +/// A deliberately small IAM condition evaluator: the operators the +/// shipped policies use, and nothing else (an unknown operator fails the +/// test rather than being ignored). +pub(crate) fn conditions_hold(stmt: &Value, req: &Request) -> bool { + let Some(cond) = stmt.get("Condition") else { + return true; + }; + let cond = cond.as_object().expect("Condition is an object"); + cond.iter().all(|(op, entries)| { + let entries = entries.as_object().expect("condition block is an object"); + // ForAllValues: every value of the (multi-valued) key matches + // one of the policy's values. Vacuously true when the key is + // absent, which is why statements pair it with a required key. + if let Some(base) = op.strip_prefix("ForAllValues:") { + assert_eq!( + base, + "StringEquals", + "{}: unsupported ForAllValues operator", + sid(stmt) + ); + return entries.iter().all(|(key, want)| { + let allowed: Vec = strings(want) + .iter() + .filter_map(|p| req.resolve(p)) + .collect(); + req.context_values(key).iter().all(|v| allowed.contains(v)) + }); + } + if op == "Null" { + return entries.iter().all(|(key, want)| { + let absent = req.context_value(key).is_none(); + match want.as_str() { + Some("true") => absent, + Some("false") => !absent, + _ => panic!("{}: Null takes \"true\" or \"false\"", sid(stmt)), + } + }); + } + let (base, if_exists) = match op.strip_suffix("IfExists") { + Some(b) => (b, true), + None => (op.as_str(), false), + }; + // A negated operator holds when the key is absent, and + // otherwise when no value matches. + let (matches, negated): (fn(&str, &str) -> bool, bool) = match base { + "StringEquals" => (|p, v| p == v, false), + // A boolean key's value is the string "true" or "false". + "Bool" => (|p, v| p == v, false), + "StringLike" | "ArnLike" => (glob, false), + "StringNotEquals" => (|p, v| p == v, true), + "StringNotLike" => (glob, true), + other => panic!("{}: unsupported condition operator {other}", sid(stmt)), + }; + entries + .iter() + .all(|(key, want)| match req.context_value(key) { + None => if_exists || negated, + Some(value) => { + let any = strings(want) + .iter() + .filter_map(|p| req.resolve(p)) + .any(|p| matches(&p, &value)); + any != negated + } + }) + }) +} + +/// Allowed by some Allow and by no Deny among `stmts`. +pub(crate) fn evaluate_in(stmts: &[Value], req: Request) -> bool { + let applies = |s: &&Value| conditions_hold(s, &req); + let allowed = matching(stmts, &req) + .into_iter() + .filter(|s| effect(s) == "Allow") + .any(|s| applies(&s)); + let denied = matching(stmts, &req) + .into_iter() + .filter(|s| effect(s) == "Deny") + .any(|s| applies(&s)); + allowed && !denied +} + +#[cfg(test)] +mod tests { + use super::*; + use ContextValue::Literal; + + #[test] + fn glob_behaves_like_iam_wildcards() { + assert!(glob("ecs:Describe*", "ecs:DescribeClusters")); + assert!(!glob("ecs:Describe*", "ecs:ListClusters")); + assert!(glob( + "arn:aws:ecs:*:*:task/triple-c-*/*", + "arn:aws:ecs:us-west-2:1:task/triple-c-x/abc" + )); + assert!(!glob( + "arn:aws:ecs:*:*:task/triple-c-*/*", + "arn:aws:ecs:us-west-2:1:task/other/abc" + )); + assert!(glob("a?c", "abc")); + assert!(!glob("a?c", "ac")); + } + + #[test] + fn for_all_values_is_vacuous_on_an_absent_key() { + let stmt: Value = serde_json::json!({ + "Sid": "T", "Effect": "Allow", "Action": "x:Y", "Resource": "*", + "Condition": { "ForAllValues:StringEquals": { "aws:TagKeys": ["a", "b"] } } + }); + let check = |context| Check { + action: "x:Y", + resource: "*", + context, + write: true, + }; + let holds = |c: &Check| { + conditions_hold( + &stmt, + &Request { + check: c, + caller: ME, + owner: ME, + }, + ) + }; + assert!(holds(&check(&[]))); + assert!(holds(&check(&[ + ("aws:TagKeys", Literal("a")), + ("aws:TagKeys", Literal("b")) + ]))); + assert!(!holds(&check(&[ + ("aws:TagKeys", Literal("a")), + ("aws:TagKeys", Literal("c")) + ]))); + } + + #[test] + fn bool_compares_the_values_string() { + let stmt: Value = serde_json::json!({ + "Sid": "T", "Effect": "Allow", "Action": "x:Y", "Resource": "*", + "Condition": { "Bool": { "aws:ViaAWSService": "true" } } + }); + let holds = |context| { + let c = Check { + action: "x:Y", + resource: "*", + context, + write: true, + }; + conditions_hold( + &stmt, + &Request { + check: &c, + caller: ME, + owner: ME, + }, + ) + }; + assert!(holds(&[("aws:ViaAWSService", Literal("true"))])); + assert!(!holds(&[("aws:ViaAWSService", Literal("false"))])); + assert!(!holds(&[])); + } +} diff --git a/app/src-tauri/src/aws/tofu_modules/tests.rs b/app/src-tauri/src/aws/tofu_modules/tests.rs index 4d6fd8b..a3adfa2 100644 --- a/app/src-tauri/src/aws/tofu_modules/tests.rs +++ b/app/src-tauri/src/aws/tofu_modules/tests.rs @@ -1328,3 +1328,623 @@ fn the_record_is_format_checked_before_use() { ); } } + +// --------------------------------------------------------------------------- +// What the admin tier must allow for the modules to apply. +// +// MODULE_CALLS maps every Terraform resource type (and data source, and the +// S3 backend) the environment and onboarding modules use to the IAM actions +// the AWS provider calls to create, read (refresh), tag, update and delete +// it, each with the resource it is authorized against and the context IAM +// sees. It is the hypothesis: Task 8's live run is the proof, and an action +// it shows missing is added here, to the policy, to the check table +// (`policies.rs`) and to `aws/README.md` together. + +use crate::aws::policies::{permissions_boundary_json, policy_files, Check, ContextValue, Tier}; +use crate::aws::policy_eval as eval; + +type Context = &'static [(&'static str, ContextValue)]; + +const fn call(action: &'static str, resource: &'static str, context: Context) -> Check { + Check { + action, + resource, + context, + write: true, + } +} + +// The resources the modules create for environment `probe` and the user +// whose owner key is `0123456789ab`, named as Task 1 names them (pinned to +// the naming functions by `the_module_call_table_uses_the_shared_names`). +const ENV: &str = "probe"; +const OWNER_KEY: &str = "0123456789ab"; +const CLUSTER: &str = "arn:aws:ecs:{region}:{account}:cluster/triple-c-probe"; +const KEY: &str = "arn:aws:kms:{region}:{account}:key/00000000-0000-0000-0000-000000000000"; +const ALIAS: &str = "arn:aws:kms:{region}:{account}:alias/triple-c-probe"; +const LOG_GROUP: &str = "arn:aws:logs:{region}:{account}:log-group:/triple-c/probe"; +const PARAMETER: &str = "arn:aws:ssm:{region}:{account}:parameter/triple-c/environments/probe"; +const VPC: &str = "arn:aws:ec2:{region}:{account}:vpc/vpc-00000000000000000"; +const SUBNET: &str = "arn:aws:ec2:{region}:{account}:subnet/subnet-00000000000000000"; +const IGW: &str = "arn:aws:ec2:{region}:{account}:internet-gateway/igw-00000000000000000"; +const RTB: &str = "arn:aws:ec2:{region}:{account}:route-table/rtb-00000000000000000"; +const EIP: &str = "arn:aws:ec2:{region}:{account}:elastic-ip/eipalloc-00000000000000000"; +const NAT: &str = "arn:aws:ec2:{region}:{account}:natgateway/nat-00000000000000000"; +const SG: &str = "arn:aws:ec2:{region}:{account}:security-group/sg-00000000000000000"; +const SG_RULE: &str = "arn:aws:ec2:{region}:{account}:security-group-rule/sgr-00000000000000000"; +const ENI: &str = "arn:aws:ec2:{region}:{account}:network-interface/eni-00000000000000000"; +const FS: &str = "arn:aws:elasticfilesystem:{region}:{account}:file-system/fs-00000000"; +const TASK_ROLE: &str = "arn:aws:iam::{account}:role/triple-c-probe-0123456789ab-task"; +const EXEC_ROLE: &str = "arn:aws:iam::{account}:role/triple-c-probe-0123456789ab-exec"; +const STATE_BUCKET: &str = "arn:aws:s3:::triple-c-tfstate-{account}-{region}"; +const ENV_STATE: &str = + "arn:aws:s3:::triple-c-tfstate-{account}-{region}/environments/probe/terraform.tfstate"; +const ENV_LOCK: &str = + "arn:aws:s3:::triple-c-tfstate-{account}-{region}/environments/probe/terraform.tfstate.tflock"; +const USER_STATE: &str = + "arn:aws:s3:::triple-c-tfstate-{account}-{region}/users/probe/0123456789ab/terraform.tfstate"; +const USER_LOCK: &str = "arn:aws:s3:::triple-c-tfstate-{account}-{region}/users/probe/0123456789ab/terraform.tfstate.tflock"; + +use ContextValue::Literal; + +const REQUEST_COMPONENT: &str = "aws:RequestTag/triple-c:component"; +const RESOURCE_COMPONENT: &str = "aws:ResourceTag/triple-c:component"; +/// Created by the environment module: default_tags put the component tag on +/// the create request. +const ENV_CREATE: Context = &[(REQUEST_COMPONENT, Literal("environment"))]; +/// An environment-module resource after creation. +const ENV_TAGGED: Context = &[(RESOURCE_COMPONENT, Literal("environment"))]; +const USER_CREATE: Context = &[(REQUEST_COMPONENT, Literal("user-onboarding"))]; +const USER_TAGGED: Context = &[(RESOURCE_COMPONENT, Literal("user-onboarding"))]; +/// Role writes name the boundary the module sets. +const BOUNDED: Context = &[ + ( + "iam:PermissionsBoundary", + Literal("arn:aws:iam::{account}:policy/triple-c-permissions-boundary"), + ), + ("aws:PrincipalAccount", Literal("{account}")), +]; +/// A call EFS makes on the caller's behalf (a mount target's interface). +const VIA_SERVICE: Context = &[("aws:ViaAWSService", Literal("true"))]; +const NONE: Context = &[]; + +macro_rules! created_by { + ($action:literal) => { + &[("ec2:CreateAction", Literal($action))] + }; +} + +/// The S3 backend's calls on one deployment's state and lock objects. +const BACKEND: &[Check] = &[ + call("s3:ListBucket", STATE_BUCKET, NONE), + call("s3:GetObject", ENV_STATE, NONE), + call("s3:PutObject", ENV_STATE, NONE), + call("s3:GetObject", ENV_LOCK, NONE), + call("s3:PutObject", ENV_LOCK, NONE), + call("s3:DeleteObject", ENV_LOCK, NONE), + call("s3:GetObject", USER_STATE, NONE), + call("s3:PutObject", USER_STATE, NONE), + call("s3:PutObject", USER_LOCK, NONE), + call("s3:DeleteObject", USER_LOCK, NONE), +]; + +const MODULE_CALLS: &[(&str, &[Check])] = &[ + ( + "aws_ecs_cluster", + &[ + call("ecs:CreateCluster", CLUSTER, ENV_CREATE), + call( + "ecs:TagResource", + CLUSTER, + &[("ecs:CreateAction", Literal("CreateCluster"))], + ), + call("ecs:DescribeClusters", CLUSTER, NONE), + call("ecs:ListTagsForResource", CLUSTER, NONE), + call("ecs:UpdateCluster", CLUSTER, ENV_TAGGED), + call("ecs:TagResource", CLUSTER, ENV_TAGGED), + call("ecs:UntagResource", CLUSTER, ENV_TAGGED), + call("ecs:DeleteCluster", CLUSTER, ENV_TAGGED), + ], + ), + ( + // Untaggable: authorized against the (named) cluster. + "aws_ecs_cluster_capacity_providers", + &[ + call("ecs:PutClusterCapacityProviders", CLUSTER, ENV_TAGGED), + call("ecs:DescribeClusters", CLUSTER, NONE), + ], + ), + ( + // Both modules' groups. The provider revokes AWS's default egress + // rule after creating (both groups declare their own egress), and + // authorizes rules one call per direction, against the group and the + // new (untagged) rule. + "aws_security_group", + &[ + call("ec2:CreateSecurityGroup", SG, ENV_CREATE), + call("ec2:CreateSecurityGroup", VPC, ENV_CREATE), + call("ec2:CreateTags", SG, created_by!("CreateSecurityGroup")), + call("ec2:DescribeSecurityGroups", "*", NONE), + call("ec2:DescribeSecurityGroupRules", "*", NONE), + call("ec2:RevokeSecurityGroupEgress", SG, USER_TAGGED), + call("ec2:RevokeSecurityGroupEgress", SG, ENV_TAGGED), + call("ec2:AuthorizeSecurityGroupEgress", SG, ENV_TAGGED), + call("ec2:AuthorizeSecurityGroupEgress", SG_RULE, NONE), + call("ec2:AuthorizeSecurityGroupIngress", SG, USER_TAGGED), + call("ec2:AuthorizeSecurityGroupIngress", SG_RULE, NONE), + call("ec2:RevokeSecurityGroupIngress", SG, ENV_TAGGED), + call( + "ec2:UpdateSecurityGroupRuleDescriptionsIngress", + SG, + USER_TAGGED, + ), + call( + "ec2:UpdateSecurityGroupRuleDescriptionsEgress", + SG, + ENV_TAGGED, + ), + call("ec2:CreateTags", SG, ENV_TAGGED), + call("ec2:DeleteTags", SG, ENV_TAGGED), + call("ec2:DescribeNetworkInterfaces", "*", NONE), + call("ec2:DeleteSecurityGroup", SG, ENV_TAGGED), + call("ec2:DeleteSecurityGroup", SG, USER_TAGGED), + ], + ), + ( + // Tag-on-create authorizes kms:TagResource against the new key with + // its request tags (verified live in phase 3). + "aws_kms_key", + &[ + call("kms:CreateKey", "*", ENV_CREATE), + call("kms:TagResource", KEY, ENV_TAGGED), + call("kms:DescribeKey", KEY, NONE), + call("kms:GetKeyPolicy", KEY, NONE), + call("kms:GetKeyRotationStatus", KEY, NONE), + call("kms:ListResourceTags", KEY, NONE), + call("kms:EnableKeyRotation", KEY, ENV_TAGGED), + call("kms:PutKeyPolicy", KEY, ENV_TAGGED), + call("kms:UpdateKeyDescription", KEY, ENV_TAGGED), + call("kms:UntagResource", KEY, ENV_TAGGED), + call("kms:ScheduleKeyDeletion", KEY, ENV_TAGGED), + ], + ), + ( + // Untaggable: authorized against the alias (by name) and the key. + "aws_kms_alias", + &[ + call("kms:CreateAlias", ALIAS, NONE), + call("kms:CreateAlias", KEY, ENV_TAGGED), + call("kms:ListAliases", "*", NONE), + call("kms:UpdateAlias", ALIAS, NONE), + call("kms:UpdateAlias", KEY, ENV_TAGGED), + call("kms:DeleteAlias", ALIAS, NONE), + call("kms:DeleteAlias", KEY, ENV_TAGGED), + ], + ), + ( + "aws_cloudwatch_log_group", + &[ + call("logs:CreateLogGroup", LOG_GROUP, ENV_CREATE), + call("logs:TagResource", LOG_GROUP, ENV_CREATE), + call("logs:PutRetentionPolicy", LOG_GROUP, NONE), + call("logs:DescribeLogGroups", "*", NONE), + call("logs:ListTagsForResource", LOG_GROUP, NONE), + call("logs:UntagResource", LOG_GROUP, NONE), + call("logs:DeleteRetentionPolicy", LOG_GROUP, NONE), + call("logs:DeleteLogGroup", LOG_GROUP, NONE), + ], + ), + ( + "aws_ssm_parameter", + &[ + call("ssm:PutParameter", PARAMETER, ENV_CREATE), + call("ssm:AddTagsToResource", PARAMETER, ENV_CREATE), + call("ssm:GetParameter", PARAMETER, NONE), + call("ssm:DescribeParameters", "*", NONE), + call("ssm:ListTagsForResource", PARAMETER, NONE), + call("ssm:RemoveTagsFromResource", PARAMETER, NONE), + call("ssm:DeleteParameter", PARAMETER, NONE), + ], + ), + ( + // enable_dns_hostnames is set after CreateVpc; reads include the + // default ACL, route table and security group. + "aws_vpc", + &[ + call("ec2:CreateVpc", VPC, ENV_CREATE), + call("ec2:CreateTags", VPC, created_by!("CreateVpc")), + call("ec2:DescribeVpcs", "*", NONE), + call("ec2:DescribeVpcAttribute", "*", NONE), + call("ec2:DescribeNetworkAcls", "*", NONE), + call("ec2:DescribeRouteTables", "*", NONE), + call("ec2:ModifyVpcAttribute", VPC, ENV_TAGGED), + call("ec2:CreateTags", VPC, ENV_TAGGED), + call("ec2:DeleteTags", VPC, ENV_TAGGED), + call("ec2:DeleteVpc", VPC, ENV_TAGGED), + ], + ), + ( + "aws_internet_gateway", + &[ + call("ec2:CreateInternetGateway", IGW, ENV_CREATE), + call("ec2:CreateTags", IGW, created_by!("CreateInternetGateway")), + call("ec2:AttachInternetGateway", IGW, ENV_TAGGED), + call("ec2:AttachInternetGateway", VPC, ENV_TAGGED), + call("ec2:DescribeInternetGateways", "*", NONE), + call("ec2:CreateTags", IGW, ENV_TAGGED), + call("ec2:DetachInternetGateway", IGW, ENV_TAGGED), + call("ec2:DetachInternetGateway", VPC, ENV_TAGGED), + call("ec2:DeleteInternetGateway", IGW, ENV_TAGGED), + ], + ), + ( + // Deleting waits for the subnet's interfaces to go. + "aws_subnet", + &[ + call("ec2:CreateSubnet", SUBNET, ENV_CREATE), + call("ec2:CreateSubnet", VPC, ENV_CREATE), + call("ec2:CreateTags", SUBNET, created_by!("CreateSubnet")), + call("ec2:DescribeSubnets", "*", NONE), + call("ec2:ModifySubnetAttribute", SUBNET, ENV_TAGGED), + call("ec2:CreateTags", SUBNET, ENV_TAGGED), + call("ec2:DeleteTags", SUBNET, ENV_TAGGED), + call("ec2:DescribeNetworkInterfaces", "*", NONE), + call("ec2:DeleteSubnet", SUBNET, ENV_TAGGED), + ], + ), + ( + "aws_route_table", + &[ + call("ec2:CreateRouteTable", RTB, ENV_CREATE), + call("ec2:CreateRouteTable", VPC, ENV_CREATE), + call("ec2:CreateTags", RTB, created_by!("CreateRouteTable")), + call("ec2:DescribeRouteTables", "*", NONE), + call("ec2:CreateTags", RTB, ENV_TAGGED), + call("ec2:DeleteRouteTable", RTB, ENV_TAGGED), + ], + ), + ( + // Untaggable: authorized against the route table. + "aws_route", + &[ + call("ec2:CreateRoute", RTB, ENV_TAGGED), + call("ec2:DescribeRouteTables", "*", NONE), + call("ec2:ReplaceRoute", RTB, ENV_TAGGED), + call("ec2:DeleteRoute", RTB, ENV_TAGGED), + ], + ), + ( + // Untaggable: authorized against the route table and the subnet. + "aws_route_table_association", + &[ + call("ec2:AssociateRouteTable", RTB, ENV_TAGGED), + call("ec2:AssociateRouteTable", SUBNET, ENV_TAGGED), + call("ec2:DescribeRouteTables", "*", NONE), + call("ec2:ReplaceRouteTableAssociation", RTB, ENV_TAGGED), + call("ec2:ReplaceRouteTableAssociation", SUBNET, ENV_TAGGED), + call("ec2:DisassociateRouteTable", RTB, ENV_TAGGED), + call("ec2:DisassociateRouteTable", SUBNET, ENV_TAGGED), + ], + ), + ( + "aws_eip", + &[ + call("ec2:AllocateAddress", EIP, ENV_CREATE), + call("ec2:CreateTags", EIP, created_by!("AllocateAddress")), + call("ec2:DescribeAddresses", "*", NONE), + call("ec2:DescribeAddressesAttribute", "*", NONE), + call("ec2:CreateTags", EIP, ENV_TAGGED), + call("ec2:ReleaseAddress", EIP, ENV_TAGGED), + ], + ), + ( + // Authorized against the gateway, its subnet, its address and the VPC. + "aws_nat_gateway", + &[ + call("ec2:CreateNatGateway", NAT, ENV_CREATE), + call("ec2:CreateNatGateway", SUBNET, ENV_CREATE), + call("ec2:CreateNatGateway", EIP, ENV_CREATE), + call("ec2:CreateNatGateway", VPC, ENV_CREATE), + call("ec2:CreateTags", NAT, created_by!("CreateNatGateway")), + call("ec2:DescribeNatGateways", "*", NONE), + call("ec2:CreateTags", NAT, ENV_TAGGED), + call("ec2:DeleteNatGateway", NAT, ENV_TAGGED), + ], + ), + ( + "aws_efs_file_system", + &[ + call("elasticfilesystem:CreateFileSystem", "*", USER_CREATE), + call( + "elasticfilesystem:TagResource", + FS, + &[( + "elasticfilesystem:CreateAction", + Literal("CreateFileSystem"), + )], + ), + call("elasticfilesystem:DescribeFileSystems", FS, NONE), + call("elasticfilesystem:DescribeLifecycleConfiguration", FS, NONE), + call("elasticfilesystem:ListTagsForResource", FS, NONE), + call("elasticfilesystem:UpdateFileSystem", FS, USER_TAGGED), + call( + "elasticfilesystem:PutLifecycleConfiguration", + FS, + USER_TAGGED, + ), + call("elasticfilesystem:TagResource", FS, USER_TAGGED), + call("elasticfilesystem:UntagResource", FS, USER_TAGGED), + call("elasticfilesystem:DeleteFileSystem", FS, USER_TAGGED), + ], + ), + ( + // Untaggable here (the module sets no tags on it). EFS creates and + // deletes the mount target's interface with the caller's EC2 + // permissions (CreateMountTarget / DeleteMountTarget API reference). + "aws_efs_mount_target", + &[ + call("elasticfilesystem:CreateMountTarget", FS, USER_TAGGED), + call("ec2:DescribeSubnets", "*", NONE), + call("ec2:DescribeNetworkInterfaces", "*", NONE), + call("ec2:CreateNetworkInterface", ENI, VIA_SERVICE), + call("ec2:CreateNetworkInterface", SUBNET, VIA_SERVICE), + call("ec2:CreateNetworkInterface", SG, VIA_SERVICE), + call("elasticfilesystem:DescribeMountTargets", FS, NONE), + call( + "elasticfilesystem:DescribeMountTargetSecurityGroups", + FS, + NONE, + ), + call( + "elasticfilesystem:ModifyMountTargetSecurityGroups", + FS, + USER_TAGGED, + ), + call("elasticfilesystem:DeleteMountTarget", FS, USER_TAGGED), + call("ec2:DeleteNetworkInterface", ENI, VIA_SERVICE), + ], + ), + ( + // Untaggable: authorized against the file system. + "aws_efs_file_system_policy", + &[ + call("elasticfilesystem:PutFileSystemPolicy", FS, USER_TAGGED), + call("elasticfilesystem:DescribeFileSystemPolicy", FS, NONE), + call("elasticfilesystem:DeleteFileSystemPolicy", FS, USER_TAGGED), + ], + ), + ( + // Deleting a role first lists (and removes) its instance profiles + // and inline policies. + "aws_iam_role", + &[ + call("iam:CreateRole", TASK_ROLE, BOUNDED), + call("iam:CreateRole", EXEC_ROLE, BOUNDED), + call("iam:TagRole", TASK_ROLE, NONE), + call("iam:GetRole", TASK_ROLE, NONE), + call("iam:ListRolePolicies", TASK_ROLE, NONE), + call("iam:ListAttachedRolePolicies", TASK_ROLE, NONE), + call("iam:ListInstanceProfilesForRole", TASK_ROLE, NONE), + call("iam:UpdateRole", TASK_ROLE, NONE), + call("iam:UpdateRoleDescription", TASK_ROLE, NONE), + call("iam:UntagRole", TASK_ROLE, NONE), + call("iam:DeleteRole", EXEC_ROLE, NONE), + ], + ), + ( + // Untaggable: authorized against the role. + "aws_iam_role_policy", + &[ + call("iam:PutRolePolicy", TASK_ROLE, BOUNDED), + call("iam:GetRolePolicy", TASK_ROLE, NONE), + call("iam:DeleteRolePolicy", EXEC_ROLE, BOUNDED), + ], + ), + ( + "data.aws_caller_identity", + &[call("sts:GetCallerIdentity", "*", NONE)], + ), + ("data.aws_partition", &[]), + ( + "data.aws_availability_zones", + &[call("ec2:DescribeAvailabilityZones", "*", NONE)], + ), + ( + "data.aws_ssm_parameter", + &[call("ssm:GetParameter", PARAMETER, NONE)], + ), + ("data.aws_subnet", &[call("ec2:DescribeSubnets", "*", NONE)]), + ("backend.s3", BACKEND), +]; + +/// `resource.` and `data.` of the environment and onboarding +/// modules, and `backend.s3`. +fn module_types() -> BTreeSet { + let mut types = BTreeSet::new(); + for kind in [ModuleKind::Environment, ModuleKind::UserOnboard] { + let body = parsed(kind); + for b in top_blocks(&body, "resource") { + types.insert(label(b, 0).unwrap().to_string()); + } + for b in top_blocks(&body, "data") { + types.insert(format!("data.{}", label(b, 0).unwrap())); + } + for t in top_blocks(&body, "terraform") { + for backend in top_blocks(&t.body, "backend") { + types.insert(format!("backend.{}", label(backend, 0).unwrap())); + } + } + } + types +} + +#[test] +fn the_module_call_table_covers_every_type_the_modules_use() { + let table: BTreeSet = MODULE_CALLS.iter().map(|(t, _)| t.to_string()).collect(); + assert_eq!( + table.len(), + MODULE_CALLS.len(), + "a type appears twice in MODULE_CALLS" + ); + assert_eq!(module_types(), table); +} + +#[test] +fn the_module_call_table_uses_the_shared_names() { + let (task, exec) = user_role_names(ENV, OWNER_KEY); + assert!(TASK_ROLE.ends_with(&format!("role/{task}"))); + assert!(EXEC_ROLE.ends_with(&format!("role/{exec}"))); + assert!(PARAMETER.ends_with(&format!("parameter{}", environment_parameter_name(ENV)))); + assert!(LOG_GROUP.ends_with(&format!("log-group:/triple-c/{ENV}"))); + assert!(CLUSTER.ends_with(&format!("cluster/triple-c-{ENV}"))); + assert!(ALIAS.ends_with(&format!("alias/triple-c-{ENV}"))); + let bucket = state_bucket_name("{account}", "{region}"); + assert_eq!(STATE_BUCKET, format!("arn:aws:s3:::{bucket}")); + let env_key = state_key(Deployment::Environment(ENV)); + let user_key = state_key(Deployment::User { + env: ENV, + owner_key: OWNER_KEY, + }); + assert_eq!(ENV_STATE, format!("{STATE_BUCKET}/{env_key}")); + assert_eq!(ENV_LOCK, format!("{STATE_BUCKET}/{env_key}.tflock")); + assert_eq!(USER_STATE, format!("{STATE_BUCKET}/{user_key}")); + assert_eq!(USER_LOCK, format!("{STATE_BUCKET}/{user_key}.tflock")); +} + +fn tier_statements(tiers: &[Tier]) -> Vec { + tiers + .iter() + .flat_map(|t| policy_files(*t).iter()) + .flat_map(|(name, json)| eval::statements_of(&eval::parse(name, json))) + .collect() +} + +fn allowed_by(stmts: &[serde_json::Value], check: &Check) -> bool { + eval::evaluate_in( + stmts, + eval::Request { + check, + caller: eval::ME, + owner: eval::ME, + }, + ) +} + +/// Every call of every module resource is allowed by the admin tier's +/// files alone, and still allowed with the workspace tier (whose Denies an +/// admin also carries) attached as well. +#[test] +fn the_admin_tier_can_apply_every_module_resource() { + let admin = tier_statements(&[Tier::EnvironmentAdmin]); + let both = tier_statements(&[Tier::EnvironmentAdmin, Tier::WorkspaceUser]); + let mut missing = Vec::new(); + for (ty, calls) in MODULE_CALLS { + for c in *calls { + for (which, stmts) in [("admin", &admin), ("admin + workspace", &both)] { + if !allowed_by(stmts, c) { + missing.push(format!( + "{ty}: {} on {} with {:?} ({which})", + c.action, + eval::rendered(c), + c.context + )); + } + } + } + } + assert!(missing.is_empty(), "not allowed:\n{}", missing.join("\n")); +} + +/// The sample values the onboarding module's role policies are rendered +/// with: (template text, value). +const ONBOARD_SAMPLES: &[(&str, &str)] = &[ + ("${local.partition}", "aws"), + ("${data.aws_partition.current.partition}", "aws"), + ("${local.account}", "111122223333"), + ( + "${data.aws_caller_identity.current.account_id}", + "111122223333", + ), + ("${var.region}", "us-west-2"), + ("${var.owner_id}", "AROAEXAMPLEME:alice@example.com"), + ("${local.env.log_group}", "/triple-c/probe"), + ( + "${local.env.kms_key_arn}", + "arn:aws:kms:us-west-2:111122223333:key/00000000-0000-0000-0000-000000000000", + ), + ( + "${aws_efs_file_system.this.arn}", + "arn:aws:elasticfilesystem:us-west-2:111122223333:file-system/fs-00000000", + ), +]; + +fn leak(s: String) -> &'static str { + Box::leak(s.into_boxed_str()) +} + +/// Every action a per-user role's policies grant, on every resource they +/// name, is within the permissions boundary: the boundary, not the module, +/// is the ceiling, so a module change can't widen a role past it unseen. +/// Each request carries what the role's own statement requires (its +/// `StringEquals` conditions) and the component tag every Triple-C key and +/// file system has. +#[test] +fn every_onboarding_role_stays_inside_the_boundary() { + let body = parsed(ModuleKind::UserOnboard); + let boundary = eval::statements_of(&eval::parse( + "permissions-boundary.json", + permissions_boundary_json(), + )); + let render_sample = |text: &str| { + let mut out = expand_locals(&body, text); + for (from, to) in ONBOARD_SAMPLES { + out = out.replace(from, to); + } + assert!(!out.contains("${"), "unrendered {out}"); + out + }; + let mut seen = 0; + for policy in resources(&body, "aws_iam_role_policy") { + for stmt in statements(&jsonencoded(policy, "policy")) { + assert_eq!(stmt["Effect"], "Allow", "{:?}", policy.labels); + for key in stmt.as_object().unwrap().keys() { + assert!( + ["Sid", "Effect", "Action", "Resource", "Condition"].contains(&key.as_str()), + "{:?}: {key}", + policy.labels + ); + } + let mut context: Vec<(&'static str, ContextValue)> = + vec![(RESOURCE_COMPONENT, Literal("user-onboarding"))]; + if let Some(cond) = stmt.get("Condition") { + for (op, entries) in cond.as_object().unwrap() { + assert_eq!(op, "StringEquals", "{:?}: unexpected {op}", policy.labels); + for (k, v) in entries.as_object().unwrap() { + context.push(( + leak(k.clone()), + Literal(leak(render_sample(v.as_str().unwrap()))), + )); + } + } + } + let context: Context = Box::leak(context.into_boxed_slice()); + for action in actions(&stmt) { + for resource in eval::strings(&stmt["Resource"]) { + let check = call( + leak(action.clone()), + leak(render_sample(&resource)), + context, + ); + assert!( + allowed_by(&boundary, &check), + "{:?}: {action} on {} with {context:?} is outside the boundary", + policy.labels, + check.resource + ); + seen += 1; + } + } + } + } + assert!(seen >= 15, "only {seen} role grants checked"); +} diff --git a/app/src-tauri/src/commands/host_commands.rs b/app/src-tauri/src/commands/host_commands.rs index a099795..03e1cd4 100644 --- a/app/src-tauri/src/commands/host_commands.rs +++ b/app/src-tauri/src/commands/host_commands.rs @@ -6,7 +6,7 @@ use std::future::Future; use tauri::State; use crate::aws::permissions::{check_permissions, PermissionReport, SdkPermissionApi}; -use crate::aws::policies::{policy_json, Tier}; +use crate::aws::policies::{policy_files, Tier}; 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, @@ -281,9 +281,24 @@ pub async fn check_aws_permissions( check_permissions(&api, &identity, ®ion).await } +/// One policy file of a tier: its file name under `aws/policies/` and its +/// JSON, verbatim. +#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)] +pub struct PolicyFile { + pub name: String, + pub json: String, +} + +/// Every policy file `tier` needs, in order; all of them are required (D7). #[tauri::command] -pub fn aws_policy_document(tier: Tier) -> String { - policy_json(tier).to_string() +pub fn aws_policy_document(tier: Tier) -> Vec { + policy_files(tier) + .iter() + .map(|(name, json)| PolicyFile { + name: name.to_string(), + json: json.to_string(), + }) + .collect() } #[cfg(test)] @@ -522,4 +537,21 @@ mod tests { } assert!(validated("Prod", "eu-west-1").is_ok()); } + + #[test] + fn the_policy_document_is_every_file_of_the_tier() { + let admin = aws_policy_document(Tier::EnvironmentAdmin); + let names: Vec<&str> = admin.iter().map(|f| f.name.as_str()).collect(); + assert_eq!(names, ["environment-admin.json", "environment-admin-network.json"]); + for f in &admin { + serde_json::from_str::(&f.json).expect("policy JSON"); + } + let ws = aws_policy_document(Tier::WorkspaceUser); + assert_eq!(ws.len(), 1); + assert_eq!(ws[0].name, "workspace-user.json"); + assert_eq!( + serde_json::to_value(&ws[0]).unwrap()["name"], + "workspace-user.json" + ); + } } diff --git a/app/src/components/settings/HostsSettings.test.tsx b/app/src/components/settings/HostsSettings.test.tsx index 75444fb..7a1c0fa 100644 --- a/app/src/components/settings/HostsSettings.test.tsx +++ b/app/src/components/settings/HostsSettings.test.tsx @@ -140,11 +140,18 @@ describe("HostsSettings", () => { expect(screen.getByLabelText("Secret access key")).toHaveValue(""); }); - it("check shows Insufficient with the denied actions and the copy-policy buttons", async () => { - invoke.mockImplementation(async (cmd: string) => { + it("check shows Insufficient with the denied actions and every policy file to copy", async () => { + const adminFiles = [ + { name: "environment-admin.json", json: '{"Statement":"admin"}' }, + { name: "environment-admin-network.json", json: '{"Statement":"network"}' }, + ]; + invoke.mockImplementation(async (cmd: string, args?: { tier: string }) => { if (cmd === "list_aws_profiles") return []; if (cmd === "check_aws_permissions") return report({}); - if (cmd === "aws_policy_document") return '{"Version":"2012-10-17"}'; + if (cmd === "aws_policy_document") + return args?.tier === "environment_admin" + ? adminFiles + : [{ name: "workspace-user.json", json: '{"Version":"2012-10-17"}' }]; throw new Error(`unexpected ${cmd}`); }); const writeText = vi.fn().mockResolvedValue(undefined); @@ -154,10 +161,22 @@ describe("HostsSettings", () => { expect(await screen.findByText("Insufficient")).toBeInTheDocument(); expect(screen.getByText("ecs:RunTask")).toBeInTheDocument(); expect(screen.getByText(/SCPs or session policies/)).toBeInTheDocument(); - fireEvent.click(screen.getByRole("button", { name: "Copy workspace-user policy" })); + + fireEvent.click(screen.getByRole("button", { name: "Show workspace-user policy" })); + fireEvent.click(await screen.findByRole("button", { name: "Copy workspace-user.json" })); await waitFor(() => expect(writeText).toHaveBeenCalledWith('{"Version":"2012-10-17"}')); expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "workspace_user" }); - expect(screen.getByRole("button", { name: "Copy admin policy" })).toBeInTheDocument(); + expect(screen.getByText("workspace-user.json copied to clipboard.")).toBeInTheDocument(); + + // The admin tier is every one of its files, each shown and copied on its own. + fireEvent.click(screen.getByRole("button", { name: "Show admin policies" })); + expect(await screen.findByText(/Attach all 2 files/)).toBeInTheDocument(); + for (const f of adminFiles) { + expect(screen.getByText(f.json)).toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: `Copy ${f.name}` })); + await waitFor(() => expect(writeText).toHaveBeenCalledWith(f.json)); + } + expect(invoke).toHaveBeenCalledWith("aws_policy_document", { tier: "environment_admin" }); }); it("shows a neutral Incomplete badge when the only blockers are failed checks", async () => { @@ -301,14 +320,27 @@ describe("HostsSettings", () => { invoke.mockImplementation(async (cmd: string) => { if (cmd === "list_aws_profiles") return []; if (cmd === "check_aws_permissions") return report({}); - if (cmd === "aws_policy_document") return "{}"; + if (cmd === "aws_policy_document") return [{ name: "environment-admin.json", json: "{}" }]; throw new Error(`unexpected ${cmd}`); }); Object.assign(navigator, { clipboard: { writeText: vi.fn().mockRejectedValue(new Error("denied")) } }); render(); fireEvent.click(screen.getByRole("button", { name: "Check Prod" })); - fireEvent.click(await screen.findByRole("button", { name: "Copy admin policy" })); - expect(await screen.findByText(/Could not copy the policy: denied/)).toBeInTheDocument(); + fireEvent.click(await screen.findByRole("button", { name: "Show admin policies" })); + fireEvent.click(await screen.findByRole("button", { name: "Copy environment-admin.json" })); + expect(await screen.findByText(/Could not copy environment-admin.json: denied/)).toBeInTheDocument(); + }); + + it("shows a message when the policy files can't be loaded", async () => { + invoke.mockImplementation(async (cmd: string) => { + if (cmd === "list_aws_profiles") return []; + if (cmd === "check_aws_permissions") return report({}); + throw new Error("boom"); + }); + render(); + fireEvent.click(screen.getByRole("button", { name: "Check Prod" })); + fireEvent.click(await screen.findByRole("button", { name: "Show admin policies" })); + expect(await screen.findByText(/Could not load the policy: boom/)).toBeInTheDocument(); }); it.each([ diff --git a/app/src/components/settings/HostsSettings.tsx b/app/src/components/settings/HostsSettings.tsx index 5cd885a..d18babb 100644 --- a/app/src/components/settings/HostsSettings.tsx +++ b/app/src/components/settings/HostsSettings.tsx @@ -17,6 +17,7 @@ import type { HostConnection, PermissionReport, PermissionSummary, + PolicyFile, Tier, } from "../../lib/types"; import Button from "../ui/Button"; @@ -93,6 +94,70 @@ function ErrorLine({ ); } +/** A tier's policy files, loaded on demand: each one shown and copied on its own. */ +function PolicyFiles({ + tier, + label, + onCopy, +}: { + tier: Tier; + label: string; + onCopy: (file: PolicyFile) => void; +}) { + const [files, setFiles] = useState(null); + const [error, setError] = useState(null); + + const load = async () => { + setError(null); + try { + setFiles(await awsPolicyDocument(tier)); + } catch (e) { + setError(`Could not load the policy: ${awsErrorMessage(toAwsError(e))}`); + } + }; + + if (!files) { + return ( +
+ + {error && ( +

+ {error} +

+ )} +
+ ); + } + return ( +
+

+ {tier === "workspace_user" ? "Workspace user" : "Environment admin"}:{" "} + {files.length === 1 + ? "attach this file as a customer managed policy." + : `Attach all ${files.length} files, each as its own customer managed policy.`} +

+ {files.map((f) => ( +
+
+ {f.name} + +
+
+ Show JSON +
+              {f.json}
+            
+
+
+ ))} +
+ ); +} + function PermissionReportView({ report }: { report: PermissionReport }) { const [copyNote, setCopyNote] = useState(null); const probed = typeof report.method === "object"; @@ -121,12 +186,12 @@ function PermissionReportView({ report }: { report: PermissionReport }) { t.results.some((r) => r.verdict === "denied" && OWN_PRINCIPAL_ACTIONS.includes(r.action)), ); - const copy = async (tier: Tier) => { + const copy = async (file: PolicyFile) => { try { - await navigator.clipboard.writeText(await awsPolicyDocument(tier)); - setCopyNote("Policy copied to clipboard."); + await navigator.clipboard.writeText(file.json); + setCopyNote(`${file.name} copied to clipboard.`); } catch (e) { - setCopyNote(`Could not copy the policy: ${awsErrorMessage(toAwsError(e))}`); + setCopyNote(`Could not copy ${file.name}: ${awsErrorMessage(toAwsError(e))}`); } }; @@ -181,14 +246,8 @@ function PermissionReportView({ report }: { report: PermissionReport }) { ))} -
- - -
+ + {copyNote && (

{copyNote} diff --git a/app/src/lib/tauri-commands.ts b/app/src/lib/tauri-commands.ts index 9bada24..b03b9bd 100644 --- a/app/src/lib/tauri-commands.ts +++ b/app/src/lib/tauri-commands.ts @@ -1,5 +1,5 @@ import { invoke } from "@tauri-apps/api/core"; -import type { Project, ProjectPath, 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, Tier } from "./types"; +import type { Project, ProjectPath, 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 } from "./types"; // Docker export const checkDocker = () => invoke("check_docker"); @@ -76,8 +76,9 @@ export const awsConnectionSsoLogin = (id: string) => /** `region` omitted: the connection's default region. */ export const checkAwsPermissions = (id: string, region?: string) => invoke("check_aws_permissions", { id, region: region ?? null }); +/** Every policy file `tier` needs, in order: attach all of them. */ export const awsPolicyDocument = (tier: Tier) => - invoke("aws_policy_document", { tier }); + invoke("aws_policy_document", { tier }); /** Check a corporate CA path and report what would be installed. Never * rejects for a bad path — the reason comes back in `error`. */ export const inspectCaCertPath = (path: string) => diff --git a/app/src/lib/types.ts b/app/src/lib/types.ts index 87b93e3..21b7051 100644 --- a/app/src/lib/types.ts +++ b/app/src/lib/types.ts @@ -1158,6 +1158,12 @@ export interface CallerIdentity { export type Tier = "environment_admin" | "workspace_user"; +/** One policy file of a tier (`aws/policies/`); a tier needs all of its files. */ +export interface PolicyFile { + name: string; + json: string; +} + export type Verdict = "allowed" | "denied" | "unverified"; export interface ActionResult { diff --git a/aws/README.md b/aws/README.md index 573bebd..1ff9017 100644 --- a/aws/README.md +++ b/aws/README.md @@ -7,11 +7,14 @@ tier the signed-in identity has under **Settings → Hosts → Check**. | File | What it is | |---|---| | `policies/workspace-user.json` | The **workspace user** tier: create, start, stop, connect to and delete **their own** workspaces in an existing environment | -| `policies/environment-admin.json` | The **environment admin** tier: deploy, update and delete the environment stack, and onboard users | +| `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 | -An environment admin needs **both** tier files. The admin policy adds environment management on -top of everything a workspace user can do. Explicit Deny statements in either file apply to anyone +The admin tier is **two** files, because one managed policy holds only 6,144 characters; both are +required, and the app's **Copy** lists every file of a tier. An environment admin attaches all three +tier files (the workspace user's and both admin files): the admin files add environment management +on top of everything a workspace user can do. Explicit Deny statements in any file apply to anyone who has it attached. ## Workspace user @@ -42,7 +45,7 @@ following: is needed because the AWS-managed `aws/secretsmanager` key, or any customer key whose key policy grants account principals directly, needs no identity-policy Allow; without the Deny such a `CreateSecret` succeeds. Keeping every user secret on the environment key keeps it - under the key policy the environment stack controls. (The permissions boundary does *not* + under the key policy the environment module controls. (The permissions boundary does *not* stop a task role decrypting an `aws/secretsmanager` secret: that key's policy grants the caller directly.) - Every `TagResource` on a secret must carry `triple-c:owner = ${aws:userid}` in the request, @@ -50,8 +53,10 @@ following: - A secret tagged `triple-c:component` belongs to the environment. A workspace user can never tag, untag, overwrite or delete one; an explicit Deny enforces this. - **Manage their own access points.** They can create and delete EFS access points tagged with - their owner ID, and only on the environment's file system, which is the one tagged - `triple-c:component`. + their owner ID, and create them only on **their own** file system: one tagged + `triple-c:component` (their onboarding module tags it `user-onboarding`) *and* + `triple-c:owner = ${aws:userid}`. Each user has their own file system (strict tenancy), so + another user's file system is refused even though it is Triple-C's. - **Set only the ordinary tag keys.** Every request that tags something may set only `triple-c:owner`, `triple-c:project` and `triple-c:environment` (`aws:TagKeys`). This applies to `RunTask`, the ECS and EFS tag-on-create calls, `CreateSecret`, and secret `TagResource`. A @@ -71,20 +76,65 @@ 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 environment information.** This covers ECS, CloudFormation stacks, the `/triple-c/*` SSM - parameters, the secret list, EFS, and the `/triple-c/*` log groups. Listing is not a secret; the - app filters by owner for display. +- **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 + a record: the OpenTofu state bucket is admin-only. ## Environment admin -The admin tier manages `triple-c-*` CloudFormation stacks and the resources they create: +The admin tier applies (and destroys) the OpenTofu modules in `terraform/` with the admin's own +credentials: the provider calls AWS as the admin, so the policy must allow every call it makes, +and nothing runs with more than the admin holds. It covers: -- `triple-c-*` IAM roles; -- ECS clusters, capacity providers and task definitions; -- security groups, EFS file systems and KMS keys; +- the per-account state bucket `triple-c-tfstate--` (created by the app, tagged + `triple-c:component=state`, then read and written by OpenTofu's S3 backend, lock files included); +- `triple-c-*` IAM roles, and reading the `triple-c-permissions-boundary` policy; +- ECS clusters (and capacity providers and task definitions); +- the network: VPCs, subnets, an internet gateway, route tables and routes, an Elastic IP and NAT + gateway, security groups and their rules (`environment-admin-network.json`); +- EFS file systems, mount targets and file-system policies, and KMS keys and aliases; - `/triple-c/*` log groups and `/triple-c/*` SSM parameters; - ECR repositories and pull-through cache rules. +### What each module resource needs + +`app/src-tauri/src/aws/tofu_modules/tests.rs` (`MODULE_CALLS`) maps every resource type, data +source and the S3 backend the modules use to the IAM actions the AWS provider calls to create, +read, tag, update and delete it, and a test evaluates each against the admin files. It is the +**hypothesis**; a live apply and destroy is the proof, and any action that shows missing is added +to the table, the policy, the check table in `policies.rs` and this list together. + +| Resource | Actions (authorized against) | +|---|---| +| `aws_ecs_cluster` | `ecs:CreateCluster`, `TagResource` (at create), `DescribeClusters`, `ListTagsForResource`, `UpdateCluster`, `UntagResource`, `DeleteCluster` (cluster `triple-c-*`) | +| `aws_ecs_cluster_capacity_providers` | `ecs:PutClusterCapacityProviders`, `DescribeClusters` (the cluster; untaggable) | +| `aws_security_group` | `ec2:CreateSecurityGroup` (group and VPC, request tag), `CreateTags` (at create), `RevokeSecurityGroupEgress` (AWS's default rule), `Authorize`/`RevokeSecurityGroupIngress`/`Egress` and `UpdateSecurityGroupRuleDescriptions*` (tagged group; new rules: `security-group-rule/*`), `CreateTags`/`DeleteTags`, `DeleteSecurityGroup` (tagged), `Describe*` | +| `aws_kms_key` | `kms:CreateKey` (request tag), `TagResource`, `DescribeKey`, `GetKeyPolicy`, `GetKeyRotationStatus`, `ListResourceTags`, `EnableKeyRotation`, `PutKeyPolicy`, `UpdateKeyDescription`, `UntagResource`, `ScheduleKeyDeletion` (tagged key) | +| `aws_kms_alias` | `kms:CreateAlias`/`UpdateAlias`/`DeleteAlias` (alias `triple-c-*` and the tagged key; untaggable), `ListAliases` | +| `aws_cloudwatch_log_group` | `logs:CreateLogGroup`, `TagResource`, `PutRetentionPolicy`, `ListTagsForResource`, `UntagResource`, `DeleteRetentionPolicy`, `DeleteLogGroup` (`/triple-c/*`), `DescribeLogGroups` (`*`) | +| `aws_ssm_parameter` | `ssm:PutParameter`, `AddTagsToResource`, `GetParameter`, `ListTagsForResource`, `RemoveTagsFromResource`, `DeleteParameter` (`/triple-c/*`), `DescribeParameters` (`*`) | +| `aws_vpc` | `ec2:CreateVpc` (request tag), `CreateTags` (at create), `ModifyVpcAttribute` (DNS hostnames), `CreateTags`/`DeleteTags`, `DeleteVpc` (tagged), `Describe*` | +| `aws_internet_gateway` | `ec2:CreateInternetGateway`, `CreateTags` (at create), `Attach`/`DetachInternetGateway` (tagged gateway and VPC), `DeleteInternetGateway`, `Describe*` | +| `aws_subnet` | `ec2:CreateSubnet` (subnet and VPC, request tag), `CreateTags` (at create), `ModifySubnetAttribute`, `DeleteSubnet` (tagged), `Describe*` | +| `aws_route_table` | `ec2:CreateRouteTable` (table and VPC, request tag), `CreateTags` (at create), `DeleteRouteTable` (tagged), `Describe*` | +| `aws_route` | `ec2:CreateRoute`, `ReplaceRoute`, `DeleteRoute` (the tagged route table; untaggable) | +| `aws_route_table_association` | `ec2:AssociateRouteTable`, `ReplaceRouteTableAssociation`, `DisassociateRouteTable` (the tagged route table and subnet; untaggable) | +| `aws_eip` | `ec2:AllocateAddress` (request tag), `CreateTags` (at create), `ReleaseAddress` (tagged), `Describe*` | +| `aws_nat_gateway` | `ec2:CreateNatGateway` (gateway, subnet, address and VPC, request tag), `CreateTags` (at create), `DeleteNatGateway` (tagged), `Describe*` | +| `aws_efs_file_system` | `elasticfilesystem:CreateFileSystem` (`*`, request tag), `TagResource` (at create), `UpdateFileSystem`, `PutLifecycleConfiguration`, `TagResource`/`UntagResource`, `DeleteFileSystem` (tagged), `Describe*`, `ListTagsForResource` | +| `aws_efs_mount_target` | `elasticfilesystem:CreateMountTarget`, `ModifyMountTargetSecurityGroups`, `DeleteMountTarget` (the tagged file system; untaggable), and the interface EFS makes with the caller's permissions: `ec2:CreateNetworkInterface`, `ec2:DeleteNetworkInterface` (only with `aws:ViaAWSService`) | +| `aws_efs_file_system_policy` | `elasticfilesystem:PutFileSystemPolicy`, `DeleteFileSystemPolicy` (the tagged file system; untaggable), `DescribeFileSystemPolicy` | +| `aws_iam_role` | `iam:CreateRole` (with the boundary), `TagRole`, `UntagRole`, `GetRole`, `ListRolePolicies`, `ListAttachedRolePolicies`, `ListInstanceProfilesForRole`, `UpdateRole`, `UpdateRoleDescription`, `DeleteRole` (`triple-c-*`) | +| `aws_iam_role_policy` | `iam:PutRolePolicy`, `DeleteRolePolicy` (with the boundary), `GetRolePolicy` (the role; untaggable) | +| data sources | `sts:GetCallerIdentity`, `ec2:DescribeAvailabilityZones`, `ec2:DescribeSubnets`, `ssm:GetParameter` | +| S3 backend | `s3:ListBucket` (the state bucket), `GetObject`/`PutObject`/`DeleteObject` (`triple-c-tfstate-*/*`, the `.tflock` objects included) | + +The app also creates the state bucket: `s3:CreateBucket` with a `triple-c:component` request tag, +then `PutBucketVersioning`, `PutEncryptionConfiguration`, `PutBucketPublicAccessBlock`, +`PutBucketTagging`, `PutBucketPolicy`, `GetBucket*` and `ListBucket`, all on +`triple-c-tfstate-*` only. No bucket can be deleted. + It is fenced in the following ways. **Roles are bounded.** The admin can create a `triple-c-*` role, or change its policies, only when @@ -96,9 +146,9 @@ the role carries the `triple-c-permissions-boundary` managed policy as its permi - ECS Exec channels; - reading `triple-c/*` secrets; - decrypting only through Secrets Manager, and only with environment (component-tagged) keys; - - mounting and writing only environment (component-tagged) file systems; whether that excludes - root access depends on access points fixing the POSIX user and root directory, which is only - true once phase 6 enforces them (see "Enforced access-point roots" under Phase 6 gaps); + - mounting and writing only Triple-C (component-tagged) file systems, which are each user's own + (tagged `user-onboarding` by their onboarding module); the file system's own policy admits + only its owner's task role, through an access point; - `sts:GetCallerIdentity`; - invoking Bedrock models. - The boundary grants nothing in IAM. @@ -110,13 +160,16 @@ the role carries the `triple-c-permissions-boundary` managed policy as its permi Without these fences an admin could create a role with any permissions and become an account administrator. -**No CloudFormation service roles.** The admin cannot create or update a `triple-c-*` stack, or -create a change set for one, with a service role (`RoleARN`). - -**Destruction is tag-scoped.** Security groups, EFS file systems and KMS keys can be created only -with a `triple-c:component` tag. They can be changed or deleted only if they carry that tag. -Tagging is allowed only as part of the creating call, or on a resource that is already -Triple-C's. +**Destruction is tag-scoped.** VPCs, subnets, internet gateways, route tables, Elastic IPs, NAT +gateways, security groups, EFS file systems and KMS keys can be created only with a +`triple-c:component` tag (the modules' `default_tags` put it on every create request). They can be +changed or deleted only if they carry that tag. Tagging is allowed only as part of the creating +call (`ec2:CreateAction`, `elasticfilesystem:CreateAction`), or on a resource that is already +Triple-C's. Resources that cannot carry a tag are authorized through one that does: routes and +route-table associations through the route table (and subnet), mount targets and the file-system +policy through the file system, KMS aliases through the key, role policies through the +(boundary-carrying) role. Clusters, log groups, parameters, roles and the state bucket are scoped +by name (`triple-c-*`, `/triple-c/*`, `triple-c-tfstate-*`). **What is not scoped.** The scoping above does not cover every action. These actions apply account-wide: @@ -128,28 +181,35 @@ account-wide: pull-through cache rules for any prefix. This cannot delete or overwrite anything. - `elasticfilesystem:CreateFileSystem` on `*` (no resource type), still only with a `triple-c:component` request tag. -- `ec2:CreateSecurityGroup` in any VPC (the new group itself must be tagged), and `ec2:Describe*`. -- `cloudformation:*` on `triple-c-*` stacks. Whatever a template creates is limited by the actions - above, because CloudFormation runs with the caller's own permissions (see the invariants below). +- Security groups, subnets, route tables and NAT gateways can be created in **any** VPC or subnet, + as long as the new resource is tagged: the request tag, not the parent's tag, is what the create + statement checks (an `existing`-network environment's VPC is the user's own and untagged). +- `ec2:AuthorizeSecurityGroupIngress`/`Egress` on `security-group-rule/*`: authorizing names the + new, untagged rule as well as the group, and the group must still be tagged. +- `ec2:CreateNetworkInterface` and `ec2:DeleteNetworkInterface` on `*`, but only when an AWS + service makes the call for the admin (`aws:ViaAWSService`): EFS creates and deletes a mount + target's interface with the caller's EC2 permissions. +- Reads on `*`: `ec2:Describe*`, `elasticfilesystem:Describe*`, the KMS key reads and + `ListAliases`, `logs:DescribeLogGroups` and `ssm:DescribeParameters`. +- `s3:PutBucketPolicy` on the state bucket: an admin could open their own account's state bucket to + others. The state holds no secrets (the modules create none), but it maps the account's + Triple-C resources. -## Invariants the templates must keep (phase 4) +## Invariants the modules must keep (phase 4) -The policies rely on the following. Phase 4's templates must establish them, and phase 4's -detection should flag any environment that breaks them. +The policies rely on the following. The modules in `terraform/` establish them (their tests pin +it), and detection should flag any environment that breaks them. 1. **Every `triple-c-*` role carries `triple-c-permissions-boundary`.** The admin tier cannot create one without it. A role created some other way, such as by an account administrator or by hand, must still have the boundary. Detection should flag a `triple-c-*` role that has no boundary. -2. **`triple-c-*` stacks are never deployed with a CloudFormation service role.** `UpdateStack` - and change sets on a stack that already has a service role reuse it without `iam:PassRole`, - and that role is not under the boundary. The admin tier denies setting `RoleARN`. Detection - should flag a `triple-c-*` stack whose `RoleARN` is set. -3. **Every environment-level `triple-c/*` secret carries `triple-c:component`.** A secret with +2. **Every environment-level `triple-c/*` secret carries `triple-c:component`.** A secret with neither an owner tag nor a component tag could be claimed by any workspace user. -4. **Every environment KMS key and EFS file system carries `triple-c:component`.** The boundary - and the admin tier both rely on this tag. -5. **User secrets use the environment key.** The app must pass the environment KMS key's ARN as +3. **Every environment KMS key and EFS file system carries `triple-c:component`,** and every + user's file system also carries `triple-c:owner`. The boundary, the admin tier and the + workspace user's access-point rule rely on these tags. +4. **User secrets use the environment key.** The app must pass the environment KMS key's ARN as `KmsKeyId` when it creates a secret. The workspace policy explicitly denies Secrets Manager encryption with any key that lacks `triple-c:component`, including `aws/secretsmanager`. @@ -164,19 +224,21 @@ aws iam create-policy --policy-name triple-c-permissions-boundary \ ``` Create the policy **without a path**. The admin policy expects exactly -`arn:aws:iam:::policy/triple-c-permissions-boundary`. Phase 4 decides how the app offers -this step; one option is to list it with the environment stack's prerequisites. +`arn:aws:iam:::policy/triple-c-permissions-boundary`. The `terraform/permissions-boundary` +module creates the same policy, applied by an account administrator; the admin tier can read it +(`iam:GetPolicy`, which detection uses) but never create or change it. ## Attaching the tier policies Create each file as a **customer managed policy** and attach it. In the console, go to **IAM → Policies → Create policy → JSON**, paste the file, and attach the policy to a user, group or role. Inline policies do not fit: a role's inline policies share 10,240 characters and an -environment admin needs both tiers (about 11,500), and a user's share 2,048. A managed policy may -hold 6,144 characters, not counting whitespace; the workspace policy is about 6,110 (roughly 30 -characters of headroom, so phase 4 must split `workspace-user.json` into two policies before -adding anything to it), and a unit test (`every_policy_fits_a_managed_policy`) fails before it -outgrows that. For IAM Identity Center, add the files as inline policies on the permission set +environment admin needs every tier file (about 14,500), 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), `environment-admin.json` about 6,080 (60) and +`environment-admin-network.json` about 2,370; 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 +the app then lists with the others. For IAM Identity Center, add the files as inline policies on the permission set (the "up to 32,768 characters" limit is unverified) or reference the managed policies. With the CLI: @@ -193,20 +255,20 @@ aws iam attach-user-policy --user-name \ **Phase 4** - **Per-user execution roles.** A workspace user can pass only roles tagged with their own owner - ID. Each user's onboarding stack must therefore create their execution role as well as their - task role. The alternative is a separate statement that allows the environment's shared - execution role. -- **The admin's full deploy permissions.** Deploying needs the following, added with the same - boundary and tag scoping once the templates exist: - - tag-on-create permissions for ECS, CloudWatch Logs, SSM and ECR; - - autoscaling and instance-profile actions for EC2 capacity; - - `cloudformation:ValidateTemplate`; - - whatever else the templates create. + ID, so each user's onboarding module creates their execution role as well as their task role + (done: `terraform/user-onboard/iam.tf`). +- **The admin's deploy permissions are a hypothesis until a live apply.** The module table above + is derived from the provider's behaviour and the Service Authorization Reference, not yet from a + real `tofu apply`/`destroy`. In particular unverified: whether tag-on-create needs + `logs:TagResource` / `ssm:AddTagsToResource` / `ecs:TagResource` as listed, whether EFS's + interface calls carry `aws:ViaAWSService`, and whether `s3:CreateBucket` honours + `aws:RequestTag`. A trust-policy change on a role (`iam:UpdateAssumeRolePolicy`) is never + allowed, so a module version that changes a role's trust must replace the role. - **Admin access to user data.** The admin can retag `triple-c-*` roles (`iam:TagRole`). The - boundary also allows every `triple-c/*` secret and every environment file system. As a result, - isolating users *from the admin* depends on the onboarding template's per-user policies, not on + boundary also allows every `triple-c/*` secret and every Triple-C file system. As a result, + isolating users *from the admin* depends on the onboarding module's per-user policies, not on IAM fences. -- **The workspace tier's secret Deny also applies to admins.** If the environment stack ever +- **The workspace tier's secret Deny also applies to admins.** If the environment module ever manages component-tagged secrets through the admin's credentials, that Deny will block `PutSecretValue`/`DeleteSecret` for them. @@ -219,11 +281,10 @@ aws iam attach-user-policy --user-name \ **Phase 6** -- **Enforced access-point roots.** A workspace user creates their own access points. The - `RootDirectory` and `PosixUser` must be enforced, so that an access point rooted at `/` cannot - read other users' data. Two ways to do this: an EFS file-system policy that pins each access - point to its owner's task role, or access points created by the onboarding stack rather than by - the user. +- **Access-point roots.** A workspace user creates their own access points, only on their own file + system (strict tenancy: one file system per user, whose policy admits only their task role). An + access point rooted at `/` therefore reaches only that user's own data. Pinning `RootDirectory` + and `PosixUser` is still worth doing if file systems are ever shared again. ## Live verification (2026-11-14) @@ -268,11 +329,14 @@ ends (keys are scheduled for deletion, 7 days). One test creates the real | Secret ownership | ✓ another owner's or a component-tagged secret cannot be written, deleted or claimed; `triple-c:component` cannot be set. An untagged `triple-c/*` secret *can* be claimed (invariant 3) | | `aws:TagKeys` | ✓ for `CreateSecret` and secret `TagResource`. `RunTask` (including `aws:ecs:*` and propagated tags), `CreateAccessPoint`, ECS/EFS tag-on-create: — need phase 4/5/6 resources | | Boundary and key tags | ✓ a role under the boundary decrypts through Secrets Manager with a component-tagged key and is refused with an untagged customer key, so KMS supplies the key's `aws:ResourceTag` | -| `cloudformation:RoleArn` | ✓ present when `RoleARN` is given; the Deny fires. The admin tier cannot pass any role to CloudFormation anyway (`PassRole` is only to ECS tasks and EC2) | +| `cloudformation:RoleArn` | ✓ (phase 3) present when `RoleARN` is given; the Deny fired. CloudFormation has since left the policies (phase 4, D8), and the Deny with it | | Task definition / pull-through scoping | ✓ both authorize against `*`; they cannot be narrowed | Still open for the phases that create the resources: `RunTask`'s tag keys and `iam:PassRole`'s `iam:ResourceTag` on a real run, the owner tag on a real task for `StopTask`/`ExecuteCommand`/ `StartSession`, session ownership for an SSO-started session, and the EFS and security-group-rule points above. The simulator does not apply session policies, so the first real create is the final -check. +check. The phase-4 additions (the network, the state bucket, the module table above, the +owner-scoped `CreateAccessPoint`) are verified by Task 8's live apply and destroy; until then they +are unit-tested only. (Checked with the simulator: a `Bool` condition matches a context entry sent +as a string, which is how the permission check sends `aws:ViaAWSService`.) diff --git a/aws/policies/environment-admin-network.json b/aws/policies/environment-admin-network.json new file mode 100644 index 0000000..93c5ffd --- /dev/null +++ b/aws/policies/environment-admin-network.json @@ -0,0 +1,139 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "CreateTaggedNetwork", + "Effect": "Allow", + "Action": [ + "ec2:CreateVpc", + "ec2:CreateSubnet", + "ec2:CreateInternetGateway", + "ec2:CreateRouteTable", + "ec2:AllocateAddress", + "ec2:CreateNatGateway", + "ec2:CreateSecurityGroup" + ], + "Resource": [ + "arn:aws:ec2:*:*:vpc/*", + "arn:aws:ec2:*:*:subnet/*", + "arn:aws:ec2:*:*:internet-gateway/*", + "arn:aws:ec2:*:*:route-table/*", + "arn:aws:ec2:*:*:elastic-ip/*", + "arn:aws:ec2:*:*:natgateway/*", + "arn:aws:ec2:*:*:security-group/*" + ], + "Condition": { + "Null": { + "aws:RequestTag/triple-c:component": "false" + } + } + }, + { + "Sid": "TagNetworkAtCreate", + "Effect": "Allow", + "Action": [ + "ec2:CreateTags" + ], + "Resource": [ + "arn:aws:ec2:*:*:vpc/*", + "arn:aws:ec2:*:*:subnet/*", + "arn:aws:ec2:*:*:internet-gateway/*", + "arn:aws:ec2:*:*:route-table/*", + "arn:aws:ec2:*:*:elastic-ip/*", + "arn:aws:ec2:*:*:natgateway/*", + "arn:aws:ec2:*:*:security-group/*" + ], + "Condition": { + "StringEquals": { + "ec2:CreateAction": [ + "CreateVpc", + "CreateSubnet", + "CreateInternetGateway", + "CreateRouteTable", + "AllocateAddress", + "CreateNatGateway", + "CreateSecurityGroup" + ] + } + } + }, + { + "Sid": "ManageTripleCNetwork", + "Effect": "Allow", + "Action": [ + "ec2:DeleteVpc", + "ec2:ModifyVpcAttribute", + "ec2:DeleteSubnet", + "ec2:ModifySubnetAttribute", + "ec2:AttachInternetGateway", + "ec2:DetachInternetGateway", + "ec2:DeleteInternetGateway", + "ec2:DeleteRouteTable", + "ec2:CreateRoute", + "ec2:ReplaceRoute", + "ec2:DeleteRoute", + "ec2:AssociateRouteTable", + "ec2:ReplaceRouteTableAssociation", + "ec2:DisassociateRouteTable", + "ec2:ReleaseAddress", + "ec2:DeleteNatGateway", + "ec2:DeleteSecurityGroup", + "ec2:AuthorizeSecurityGroup*", + "ec2:RevokeSecurityGroup*", + "ec2:UpdateSecurityGroupRuleDescriptions*", + "ec2:CreateTags", + "ec2:DeleteTags" + ], + "Resource": [ + "arn:aws:ec2:*:*:vpc/*", + "arn:aws:ec2:*:*:subnet/*", + "arn:aws:ec2:*:*:internet-gateway/*", + "arn:aws:ec2:*:*:route-table/*", + "arn:aws:ec2:*:*:elastic-ip/*", + "arn:aws:ec2:*:*:natgateway/*", + "arn:aws:ec2:*:*:security-group/*" + ], + "Condition": { + "Null": { + "aws:ResourceTag/triple-c:component": "false" + } + } + }, + { + "Sid": "AuthorizeNewSecurityGroupRules", + "Effect": "Allow", + "Action": [ + "ec2:AuthorizeSecurityGroup*" + ], + "Resource": [ + "arn:aws:ec2:*:*:security-group-rule/*" + ] + }, + { + "Sid": "MountTargetInterfacesThroughEfs", + "Effect": "Allow", + "Action": [ + "ec2:CreateNetworkInterface", + "ec2:DeleteNetworkInterface" + ], + "Resource": [ + "*" + ], + "Condition": { + "Bool": { + "aws:ViaAWSService": "true" + } + } + }, + { + "Sid": "DescribeEc2", + "Effect": "Allow", + "Action": [ + "ec2:Describe*" + ], + "Resource": [ + "*" + ] + } + ] +} diff --git a/aws/policies/environment-admin.json b/aws/policies/environment-admin.json index d6cfbde..d743bae 100644 --- a/aws/policies/environment-admin.json +++ b/aws/policies/environment-admin.json @@ -1,16 +1,6 @@ { "Version": "2012-10-17", "Statement": [ - { - "Sid": "ManageEnvironmentStacks", - "Effect": "Allow", - "Action": [ - "cloudformation:*" - ], - "Resource": [ - "arn:aws:cloudformation:*:*:stack/triple-c-*/*" - ] - }, { "Sid": "ManageBoundedTripleCRoles", "Effect": "Allow", @@ -31,12 +21,19 @@ } }, { - "Sid": "TagReadAndDeleteTripleCRoles", + "Sid": "ManageAndReadTripleCRoles", "Effect": "Allow", "Action": [ "iam:DeleteRole", "iam:TagRole", - "iam:GetRole" + "iam:UntagRole", + "iam:UpdateRole", + "iam:UpdateRoleDescription", + "iam:GetRole", + "iam:GetRolePolicy", + "iam:ListRolePolicies", + "iam:ListAttachedRolePolicies", + "iam:ListInstanceProfilesForRole" ], "Resource": [ "arn:aws:iam::*:role/triple-c-*" @@ -98,23 +95,6 @@ } } }, - { - "Sid": "NoServiceRoleForTripleCStacks", - "Effect": "Deny", - "Action": [ - "cloudformation:CreateStack", - "cloudformation:UpdateStack", - "cloudformation:CreateChangeSet" - ], - "Resource": [ - "arn:aws:cloudformation:*:*:stack/triple-c-*/*" - ], - "Condition": { - "Null": { - "cloudformation:RoleArn": "false" - } - } - }, { "Sid": "InspectOwnPrincipal", "Effect": "Allow", @@ -129,13 +109,28 @@ "arn:aws:iam::*:user/*/${aws:username}" ] }, + { + "Sid": "ReadTheBoundary", + "Effect": "Allow", + "Action": [ + "iam:GetPolicy" + ], + "Resource": [ + "arn:aws:iam::*:policy/triple-c-permissions-boundary" + ] + }, { "Sid": "ManageClusters", "Effect": "Allow", "Action": [ "ecs:CreateCluster", "ecs:DeleteCluster", - "ecs:PutClusterCapacityProviders" + "ecs:UpdateCluster", + "ecs:PutClusterCapacityProviders", + "ecs:DescribeClusters", + "ecs:TagResource", + "ecs:UntagResource", + "ecs:ListTagsForResource" ], "Resource": [ "arn:aws:ecs:*:*:cluster/triple-c-*" @@ -163,74 +158,6 @@ "*" ] }, - { - "Sid": "CreateTaggedSecurityGroups", - "Effect": "Allow", - "Action": [ - "ec2:CreateSecurityGroup" - ], - "Resource": [ - "arn:aws:ec2:*:*:security-group/*" - ], - "Condition": { - "Null": { - "aws:RequestTag/triple-c:component": "false" - } - } - }, - { - "Sid": "CreateSecurityGroupsInVpcs", - "Effect": "Allow", - "Action": [ - "ec2:CreateSecurityGroup" - ], - "Resource": [ - "arn:aws:ec2:*:*:vpc/*" - ] - }, - { - "Sid": "TagSecurityGroupsAtCreate", - "Effect": "Allow", - "Action": [ - "ec2:CreateTags" - ], - "Resource": [ - "arn:aws:ec2:*:*:security-group/*" - ], - "Condition": { - "StringEquals": { - "ec2:CreateAction": "CreateSecurityGroup" - } - } - }, - { - "Sid": "ManageTripleCSecurityGroups", - "Effect": "Allow", - "Action": [ - "ec2:DeleteSecurityGroup", - "ec2:AuthorizeSecurityGroup*", - "ec2:RevokeSecurityGroup*", - "ec2:CreateTags" - ], - "Resource": [ - "arn:aws:ec2:*:*:security-group/*" - ], - "Condition": { - "Null": { - "aws:ResourceTag/triple-c:component": "false" - } - } - }, - { - "Sid": "DescribeEc2", - "Effect": "Allow", - "Action": [ - "ec2:Describe*" - ], - "Resource": [ - "*" - ] - }, { "Sid": "CreateTaggedFileSystems", "Effect": "Allow", @@ -266,10 +193,15 @@ "Effect": "Allow", "Action": [ "elasticfilesystem:DeleteFileSystem", + "elasticfilesystem:UpdateFileSystem", + "elasticfilesystem:PutLifecycleConfiguration", "elasticfilesystem:CreateMountTarget", "elasticfilesystem:DeleteMountTarget", + "elasticfilesystem:ModifyMountTargetSecurityGroups", "elasticfilesystem:PutFileSystemPolicy", - "elasticfilesystem:TagResource" + "elasticfilesystem:DeleteFileSystemPolicy", + "elasticfilesystem:TagResource", + "elasticfilesystem:UntagResource" ], "Resource": [ "arn:aws:elasticfilesystem:*:*:file-system/*" @@ -301,8 +233,12 @@ "Action": [ "kms:ScheduleKeyDeletion", "kms:PutKeyPolicy", + "kms:EnableKeyRotation", + "kms:UpdateKeyDescription", "kms:TagResource", + "kms:UntagResource", "kms:CreateAlias", + "kms:UpdateAlias", "kms:DeleteAlias" ], "Resource": [ @@ -319,6 +255,7 @@ "Effect": "Allow", "Action": [ "kms:CreateAlias", + "kms:UpdateAlias", "kms:DeleteAlias" ], "Resource": [ @@ -331,7 +268,11 @@ "Action": [ "logs:CreateLogGroup", "logs:DeleteLogGroup", - "logs:PutRetentionPolicy" + "logs:PutRetentionPolicy", + "logs:DeleteRetentionPolicy", + "logs:TagResource", + "logs:UntagResource", + "logs:ListTagsForResource" ], "Resource": [ "arn:aws:logs:*:*:log-group:/triple-c/*" @@ -364,11 +305,77 @@ "Effect": "Allow", "Action": [ "ssm:PutParameter", - "ssm:DeleteParameter" + "ssm:DeleteParameter", + "ssm:GetParameter*", + "ssm:AddTagsToResource", + "ssm:RemoveTagsFromResource", + "ssm:ListTagsForResource" ], "Resource": [ "arn:aws:ssm:*:*:parameter/triple-c/*" ] + }, + { + "Sid": "ReadWhatTheModulesRefresh", + "Effect": "Allow", + "Action": [ + "kms:DescribeKey", + "kms:GetKeyPolicy", + "kms:GetKeyRotationStatus", + "kms:ListResourceTags", + "kms:ListAliases", + "logs:DescribeLogGroups", + "ssm:DescribeParameters", + "elasticfilesystem:Describe*", + "elasticfilesystem:ListTagsForResource", + "sts:GetCallerIdentity" + ], + "Resource": [ + "*" + ] + }, + { + "Sid": "CreateTheStateBucket", + "Effect": "Allow", + "Action": [ + "s3:CreateBucket" + ], + "Resource": [ + "arn:aws:s3:::triple-c-tfstate-*" + ], + "Condition": { + "Null": { + "aws:RequestTag/triple-c:component": "false" + } + } + }, + { + "Sid": "ManageTheStateBucket", + "Effect": "Allow", + "Action": [ + "s3:PutBucketVersioning", + "s3:PutEncryptionConfiguration", + "s3:PutBucketPublicAccessBlock", + "s3:PutBucketTagging", + "s3:PutBucketPolicy", + "s3:GetBucket*", + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::triple-c-tfstate-*" + ] + }, + { + "Sid": "ReadAndWriteState", + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:DeleteObject" + ], + "Resource": [ + "arn:aws:s3:::triple-c-tfstate-*/*" + ] } ] } diff --git a/aws/policies/workspace-user.json b/aws/policies/workspace-user.json index 00426f7..230c11d 100644 --- a/aws/policies/workspace-user.json +++ b/aws/policies/workspace-user.json @@ -232,7 +232,8 @@ ], "Condition": { "StringEquals": { - "aws:RequestTag/triple-c:owner": "${aws:userid}" + "aws:RequestTag/triple-c:owner": "${aws:userid}", + "aws:ResourceTag/triple-c:owner": "${aws:userid}" }, "Null": { "aws:ResourceTag/triple-c:component": "false" @@ -344,17 +345,6 @@ "arn:aws:ssm:*:*:parameter/triple-c/*" ] }, - { - "Sid": "ReadStacks", - "Effect": "Allow", - "Action": [ - "cloudformation:DescribeStacks", - "cloudformation:ListStacks" - ], - "Resource": [ - "*" - ] - }, { "Sid": "ListSecrets", "Effect": "Allow",