fix(aws): EC2-safe SG descriptions, deny other EFS principals, format-check the record
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f061ddb9a4
commit
31c0a918e6
3 files changed
+162
-5
No files matched your search
@@ -912,7 +912,28 @@ fn the_users_file_system_admits_only_their_task_role_through_an_access_point() {
|
||||
);
|
||||
assert_eq!(allows[0]["Resource"], fs_arn);
|
||||
assert!(allows[0].get("Condition").is_none() || allows[0]["Condition"].is_null());
|
||||
assert_eq!(stmts.len(), 3, "{stmts:?}");
|
||||
let deny_others = stmts
|
||||
.iter()
|
||||
.find(|s| s["Sid"] == "DenyAllButOwnersTaskRole")
|
||||
.expect("a deny for every principal but the task role");
|
||||
assert_eq!(
|
||||
deny_others,
|
||||
&json!({
|
||||
"Sid": "DenyAllButOwnersTaskRole",
|
||||
"Effect": "Deny",
|
||||
"Principal": { "AWS": "*" },
|
||||
"Action": [
|
||||
"elasticfilesystem:ClientMount",
|
||||
"elasticfilesystem:ClientWrite",
|
||||
"elasticfilesystem:ClientRootAccess",
|
||||
],
|
||||
"Resource": fs_arn,
|
||||
"Condition": {
|
||||
"ArnNotEquals": { "aws:PrincipalArn": "${aws_iam_role.task.arn}" }
|
||||
},
|
||||
})
|
||||
);
|
||||
assert_eq!(stmts.len(), 4, "{stmts:?}");
|
||||
|
||||
// The task role may mount this file system and no other.
|
||||
let efs: Vec<_> = role_policies(&body, "task")
|
||||
@@ -990,8 +1011,8 @@ fn the_environment_security_group_gains_no_ingress() {
|
||||
assert_eq!(text.matches("local.env.security_group_id").count(), 1);
|
||||
assert_eq!(
|
||||
text.matches("security_group_id").count(),
|
||||
2,
|
||||
"the rule and the efs group output"
|
||||
4,
|
||||
"the rule, the record check and its message, and the efs group output"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1203,3 +1224,107 @@ fn boundary_vars_carry_the_shipped_boundary() {
|
||||
Some(&Expression::String("boundary".into()))
|
||||
);
|
||||
}
|
||||
|
||||
/// EC2 accepts only these characters in a security group's or rule's
|
||||
/// description; the provider checks only the length, so a stray apostrophe
|
||||
/// passes `tofu validate` and fails `CreateSecurityGroup`.
|
||||
fn is_ec2_description(text: &str) -> bool {
|
||||
text.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || " ._-:/()#,@[]+=&;{}!$*".contains(c))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn security_group_descriptions_use_only_ec2_characters() {
|
||||
assert!(is_ec2_description(
|
||||
"Triple-C ${var.environment_name}: NFS (tcp)"
|
||||
));
|
||||
assert!(!is_ec2_description("the environment's tasks"));
|
||||
|
||||
for kind in [ModuleKind::Environment, ModuleKind::UserOnboard] {
|
||||
let body = parsed(kind);
|
||||
let mut seen = 0;
|
||||
for ty in [
|
||||
"aws_security_group",
|
||||
"aws_security_group_rule",
|
||||
"aws_vpc_security_group_ingress_rule",
|
||||
"aws_vpc_security_group_egress_rule",
|
||||
] {
|
||||
for res in resources(&body, ty) {
|
||||
let mut bodies = vec![&res.body];
|
||||
bodies.extend(
|
||||
res.body
|
||||
.blocks()
|
||||
.filter(|b| matches!(b.identifier.as_str(), "ingress" | "egress"))
|
||||
.map(|b| &b.body),
|
||||
);
|
||||
for b in bodies {
|
||||
if let Some(d) = attr(b, "description") {
|
||||
let text = template_text(d);
|
||||
assert!(
|
||||
is_ec2_description(&text),
|
||||
"{kind:?} {:?}: description {text:?} has characters EC2 rejects",
|
||||
res.labels
|
||||
);
|
||||
seen += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(seen >= 2, "{kind:?}: only {seen} descriptions checked");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_record_is_format_checked_before_use() {
|
||||
let body = parsed(ModuleKind::UserOnboard);
|
||||
let param = top_blocks(&body, "data")
|
||||
.find(|b| label(b, 0) == Some("aws_ssm_parameter"))
|
||||
.unwrap();
|
||||
let lifecycle = top_blocks(¶m.body, "lifecycle")
|
||||
.next()
|
||||
.expect("lifecycle");
|
||||
let conditions: String = top_blocks(&lifecycle.body, "postcondition")
|
||||
.map(|p| render(attr(&p.body, "condition").expect("condition")))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
for needle in [
|
||||
"jsondecode(self.insecure_value).schema == 1",
|
||||
"jsondecode(self.insecure_value).name == var.environment_name",
|
||||
"jsondecode(self.insecure_value).tenancy == \"strict\"",
|
||||
"length(jsondecode(self.insecure_value).subnet_ids) == 2",
|
||||
"\"^arn:aws[a-z-]*:kms:${var.region}:${data.aws_caller_identity.current.account_id}:key/[0-9a-f-]+$\"",
|
||||
"jsondecode(self.insecure_value).kms_key_arn",
|
||||
"jsondecode(self.insecure_value).log_group == \"/triple-c/${var.environment_name}\"",
|
||||
"\"^sg-[0-9a-f]{8,17}$\"",
|
||||
"jsondecode(self.insecure_value).security_group_id",
|
||||
"\"^subnet-[0-9a-f]{8,17}$\"",
|
||||
// Every subnet, not just the first.
|
||||
"alltrue([for s in jsondecode(self.insecure_value).subnet_ids",
|
||||
] {
|
||||
assert!(
|
||||
conditions.contains(needle),
|
||||
"the record postconditions do not check {needle}:\n{conditions}"
|
||||
);
|
||||
}
|
||||
|
||||
// Every record field the module reads is one the postconditions check.
|
||||
let text = tf_text(ModuleKind::UserOnboard);
|
||||
let mut used = BTreeSet::new();
|
||||
for (i, _) in text.match_indices("local.env.") {
|
||||
let rest = &text[i + "local.env.".len()..];
|
||||
let end = rest
|
||||
.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
|
||||
.unwrap_or(rest.len());
|
||||
used.insert(rest[..end].to_string());
|
||||
}
|
||||
assert!(
|
||||
used.contains("kms_key_arn") && used.contains("subnet_ids"),
|
||||
"{used:?}"
|
||||
);
|
||||
for field in &used {
|
||||
assert!(
|
||||
conditions.contains(&format!("jsondecode(self.insecure_value).{field}")),
|
||||
"local.env.{field} is used but never checked"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -18,13 +18,15 @@ resource "aws_efs_file_system" "this" {
|
||||
}
|
||||
|
||||
# Admits NFS from the environment's task group, which itself gains nothing.
|
||||
# EC2 descriptions allow only a-zA-Z0-9, spaces and ._-:/()#,@[]+=&;{}!$*
|
||||
# (no apostrophes); the provider does not check, CreateSecurityGroup does.
|
||||
resource "aws_security_group" "efs" {
|
||||
name = "${local.name}-efs"
|
||||
description = "Triple-C ${var.environment_name}: NFS to one user's file system"
|
||||
description = "Triple-C ${var.environment_name}: NFS to the file system of ${var.owner_key}"
|
||||
vpc_id = data.aws_subnet.task[0].vpc_id
|
||||
|
||||
ingress {
|
||||
description = "NFS from the environment's tasks"
|
||||
description = "NFS from the environment task group"
|
||||
from_port = 2049
|
||||
to_port = 2049
|
||||
protocol = "tcp"
|
||||
@@ -79,6 +81,20 @@ resource "aws_efs_file_system_policy" "this" {
|
||||
Resource = aws_efs_file_system.this.arn
|
||||
Condition = { Null = { "elasticfilesystem:AccessPointArn" = "true" } }
|
||||
},
|
||||
{
|
||||
# Same-account access needs an identity OR a resource policy, so the
|
||||
# Allow below is not enough by itself: refuse every other principal.
|
||||
Sid = "DenyAllButOwnersTaskRole"
|
||||
Effect = "Deny"
|
||||
Principal = { AWS = "*" }
|
||||
Action = [
|
||||
"elasticfilesystem:ClientMount",
|
||||
"elasticfilesystem:ClientWrite",
|
||||
"elasticfilesystem:ClientRootAccess",
|
||||
]
|
||||
Resource = aws_efs_file_system.this.arn
|
||||
Condition = { ArnNotEquals = { "aws:PrincipalArn" = aws_iam_role.task.arn } }
|
||||
},
|
||||
{
|
||||
Sid = "OwnersTaskRoleOnly"
|
||||
Effect = "Allow"
|
||||
|
||||
@@ -42,6 +42,8 @@ data "aws_ssm_parameter" "environment" {
|
||||
name = "/triple-c/environments/${var.environment_name}"
|
||||
with_decryption = false
|
||||
|
||||
# The record is untrusted input that feeds IAM policies and the network:
|
||||
# every field this module uses is format-checked before anything is built.
|
||||
lifecycle {
|
||||
postcondition {
|
||||
condition = try(
|
||||
@@ -53,5 +55,19 @@ data "aws_ssm_parameter" "environment" {
|
||||
)
|
||||
error_message = "The environment record is missing or not a schema-1 strict-tenancy record with two subnets; deploy (or update) the environment first."
|
||||
}
|
||||
|
||||
postcondition {
|
||||
condition = try(
|
||||
can(regex(
|
||||
"^arn:aws[a-z-]*:kms:${var.region}:${data.aws_caller_identity.current.account_id}:key/[0-9a-f-]+$",
|
||||
jsondecode(self.insecure_value).kms_key_arn
|
||||
))
|
||||
&& jsondecode(self.insecure_value).log_group == "/triple-c/${var.environment_name}"
|
||||
&& can(regex("^sg-[0-9a-f]{8,17}$", jsondecode(self.insecure_value).security_group_id))
|
||||
&& alltrue([for s in jsondecode(self.insecure_value).subnet_ids : can(regex("^subnet-[0-9a-f]{8,17}$", s))]),
|
||||
false
|
||||
)
|
||||
error_message = "The environment record has a malformed kms_key_arn (not a key in this region and account), log_group (not /triple-c/<environment>), security_group_id or subnet id."
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user