Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/incidents.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ pipeline still calls it there.
| bk. `bk_owns_the_outside_work` | A run with its pull request open ended waiting on people and its ticket comment handed over work CoderHelm could do: reading workflow runs, a lint, page checks (all failing on one 400 because a page check written as the confirm "query" was sent to the CMS's GROQ API), the production release (a tag after one approval), a review look, and a step number the ticket never showed; it opened on a raw Jira account id and counted nothing as handed over. | Each outside step's action comes from its own words; a failed attempt reaches a person only for a permission or credential in its own cause; a tool failure is diagnosed and reported once and its steps take another way; the release is one approval; a run waits on a person only with a gate-approved item and nothing it can still do; every comment, description, chat message and outside report passes the sink check; replies show names, never account ids; the team's history replays with no doable item reaching a person. |
| bl. `bl_description_final_review` | A pull request description showed six checks as "still running when this was written" in its results and never changed them, asked a person for deploy credentials or to run the staging deploy in a repository that deploys staging from a label CoderHelm adds, said the file to read first and the way back twice each, closed its review focus with "nothing is out of the ordinary", named a page by its raw id beside its name, and listed still-running and did-not-run checks on one line. The repository's template only guided the first draft. A run could also end as needing an outside change instead of delivering the code. | Every description passes a final review in the one save (`common::pr_review`): a running check reads Running and is never a result, and the stamp keeps the description rebuilt until the checks end; nothing the gate does not let through reaches a person, and a staging deploy the repository lets CoderHelm start (a dispatchable workflow, or a job a pull request label starts) is CoderHelm's step: the gate is told it can deploy, and the executor adds the label or dispatches, waits for the run and records its end; nothing is said twice; no filler; no raw id beside a name; running and did-not-run are said apart. The repository's template is the visible structure, filled with CoderHelm's content (`common::pr_template`). A plan with code is implemented and its pull request opened whatever outside work it needs, a person's feedback that part of the fix is outside the code keeps the code and its open pull request with the outside part attached, and the run ends delivered with only person-only items listed once under Needed from you. |
| bm. `bm_teams_never_cross` | An audit of every event path found four keys that named a shared thing instead of the team: any team admin could point a Slack workspace at their own team and take another team's slash commands; the run page's GitHub check reads were cached by repository name, so a same-named repository was served another installation's cached checks; model-written replies were cached by Jira ticket key and comment id, which two Jira sites can share; and run events were keyed by run id with no team on the row. | Every inbound route resolves its team from something only that team holds (a signed installation, a per-team token or secret, a claim no other team can overwrite) and drops an event no team owns. A Slack workspace or Teams webhook is claimed by one team at a time (`common::plugins::flag::claim_chat`) and routes only while that team still names it. Every process-wide cache is keyed by the credential or team that read it, and a reply is reused only for the exact prompt it was written from. Every run event row names its team and reads keep only the asking team's rows (`common::run_events`). Source scans fail on a new inbound route, a new cache or a direct events table access that does not say how it stays in its team. |
| bn. `bn_infra_list_follows_aws` | Security, Infrastructure kept ten rows while AWS had moved on: an RDS instance deleted two days before still showed two pending actions, a Lambda function on a retired runtime came from a Terraform module nothing called, five rows already fixed kept their Runbook and Fix PR buttons, an older CVE row and the engine patch to the same version stood as two rows, and a serverless platform update and an operating system update on each instance AWS listed never appeared. The read kept every resource for three days and the match took them all as running. | Each read says which kinds it saw in full; what a full read no longer lists is dropped and its findings close as removed, with the time; a failed or partial read drops and closes nothing. The same move on one database is one item. Every pending action is an item, applied by CoderHelm after one approval when it has no code change, and a version change on a resource in code is a pull request whichever source raised it. Closed items offer nothing to do. Opening the page refreshes a read older than five minutes, at most once per team in that time. |

## Adding a case

Expand Down
27 changes: 27 additions & 0 deletions infra/cfn/coderhelm-log-reader-update.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Description: >
named in SyncKnowledgeBases. With InfrastructureVulnerabilities "on" it
also reads, read-only, which versions your EC2, EKS, RDS, ElastiCache and
OpenSearch resources run, for matching against security advisories.
With ApplyMaintenance "on" it may also apply a pending RDS or Aurora
maintenance action that a person approved in CoderHelm.
It only adds: to drop a permission an older release granted, update the
CoderHelmLogReader stack itself with the current role template.
Created from the dashboard's Update link; you can delete older
Expand Down Expand Up @@ -85,6 +87,17 @@ Parameters:
"on" lets CoderHelm read this account's AWS Health events through the
Health API (read-only), which needs AWS Business Support or higher.

ApplyMaintenance:
Type: String
Default: "off"
AllowedValues: ["off", "on"]
Description: >
"on" lets CoderHelm apply a pending RDS or Aurora maintenance action
(an operating system update, an engine patch or upgrade, a serverless
platform update) that a person approved in CoderHelm, through AWS's
own ApplyPendingMaintenanceAction, only on this account's database
clusters and instances. Nothing is applied without that approval.

Conditions:
ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]]
ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"]
Expand All @@ -94,6 +107,7 @@ Conditions:
ReadsInfrastructure: !Equals [!Ref InfrastructureVulnerabilities, "on"]
ReadsInspector: !Equals [!Ref InspectorFindings, "on"]
ReadsHealth: !Equals [!Ref HealthEvents, "on"]
AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"]

Resources:
CoderHelmReadOnlyUpdate:
Expand Down Expand Up @@ -331,6 +345,19 @@ Resources:
- "inspector2:BatchGetAccountStatus"
Resource: "*"
- !Ref AWS::NoValue
# Applying a pending RDS or Aurora maintenance action, only when
# ApplyMaintenance is "on", and only after a person approved that
# action in CoderHelm. Only this account's clusters and instances.
- !If
- AppliesMaintenance
- Sid: ApplyApprovedMaintenance
Effect: Allow
Action:
- "rds:ApplyPendingMaintenanceAction"
Resource:
- !Sub "arn:aws:rds:*:${AWS::AccountId}:cluster:*"
- !Sub "arn:aws:rds:*:${AWS::AccountId}:db:*"
- !Ref AWS::NoValue
# AWS Health events, only when HealthEvents is "on" (the Health API needs
# Business Support or higher). Read-only.
- !If
Expand Down
33 changes: 32 additions & 1 deletion infra/cfn/coderhelm-log-reader.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ Description: >
Only when you name them in SyncKnowledgeBases, it may also copy your chosen Coderhelm
knowledge bases into those Bedrock knowledge bases. With
InfrastructureVulnerabilities "on" it also reads, read-only, which versions
your EC2, EKS, RDS, ElastiCache and OpenSearch resources run.
your EC2, EKS, RDS, ElastiCache and OpenSearch resources run. With
ApplyMaintenance "on" it may also apply a pending RDS or Aurora
maintenance action that a person approved in CoderHelm.
This role uses an External ID to prevent confused deputy attacks.

Parameters:
Expand Down Expand Up @@ -95,6 +97,17 @@ Parameters:
"on" lets CoderHelm read this account's AWS Health events through the
Health API (read-only), which needs AWS Business Support or higher.

ApplyMaintenance:
Type: String
Default: "off"
AllowedValues: ["off", "on"]
Description: >
"on" lets CoderHelm apply a pending RDS or Aurora maintenance action
(an operating system update, an engine patch or upgrade, a serverless
platform update) that a person approved in CoderHelm, through AWS's
own ApplyPendingMaintenanceAction, only on this account's database
clusters and instances. Nothing is applied without that approval.

Conditions:
ReadsKnowledgeBases: !Not [!Equals [!Ref KnowledgeBases, ""]]
ReadsEveryKnowledgeBase: !Equals [!Ref KnowledgeBases, "all"]
Expand All @@ -104,6 +117,7 @@ Conditions:
ReadsInfrastructure: !Equals [!Ref InfrastructureVulnerabilities, "on"]
ReadsInspector: !Equals [!Ref InspectorFindings, "on"]
ReadsHealth: !Equals [!Ref HealthEvents, "on"]
AppliesMaintenance: !Equals [!Ref ApplyMaintenance, "on"]

Resources:
CoderHelmLogReaderRole:
Expand Down Expand Up @@ -405,6 +419,23 @@ Resources:
- "inspector2:BatchGetAccountStatus"
Resource: "*"
- !Ref AWS::NoValue
# Applying a pending RDS or Aurora maintenance action, only when
# ApplyMaintenance is "on", and only after a person approved that
# action in CoderHelm. Only this account's clusters and instances.
- !If
- AppliesMaintenance
- PolicyName: ApplyApprovedMaintenance
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: ApplyApprovedMaintenance
Effect: Allow
Action:
- "rds:ApplyPendingMaintenanceAction"
Resource:
- !Sub "arn:aws:rds:*:${AWS::AccountId}:cluster:*"
- !Sub "arn:aws:rds:*:${AWS::AccountId}:db:*"
- !Ref AWS::NoValue
- !If
- ReadsHealth
- PolicyName: HealthEventsReadOnly
Expand Down
2 changes: 2 additions & 0 deletions infra/lib/own-account-read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ const OWN_CONDITIONS: Record<string, boolean> = {
ReadsImportBuckets: false,
SyncsKnowledgeBases: false,
SyncsEveryKnowledgeBase: false,
// The install's own role only reads: it never applies database maintenance.
AppliesMaintenance: false,
};

/**
Expand Down
4 changes: 3 additions & 1 deletion infra/test/synth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,9 @@ test("self-host: the gateway and worker read the install's own account with this
};
// Inspector and Health are switches (off by default) like infrastructure
// vulnerabilities (on by default): their statements are there, each behind its condition.
const abilities = ["imports", "sync"].reduce(without, all);
// Applying approved database maintenance is a write a team grants its own
// CoderHelmLogReader role; the install's own role only reads.
const abilities = ["imports", "sync", "maintenance"].reduce(without, all);
const needed = [...new Set([...abilities.matchAll(/"([a-z0-9-]+:[A-Za-z]+)"/g)].map((m) => m[1]))];
assert.ok(needed.length > 20, `${needed.length} actions`);
for (const [stack, fn] of [
Expand Down
11 changes: 11 additions & 0 deletions services/common/src/infra_vuln/actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,15 @@ pub fn target_in(description: &str) -> String {
.unwrap_or_default()
}

/// The platform version a serverless update names (`Upgrade to platform
/// version 4`), as `platform version 4`; empty when it names none.
pub fn platform_in(description: &str) -> String {
re(r"(?i)platform version (\d+(?:\.\d+)*)")
.captures(description)
.map(|c| format!("platform version {}", &c[1]))
.unwrap_or_default()
}

/// The part of an engine version that names its major version.
fn major_of(engine: &str, version: &str) -> String {
if let Some(a) = version.split("mysql_aurora.").nth(1) {
Expand Down Expand Up @@ -434,6 +443,8 @@ pub fn reconcile(engine: &str, running: &str, lines: &[Line]) -> Vec<Pending> {
let meaning = meaning_of(&l.action, scope, engine);
let target = if matches!(meaning, Meaning::EngineUpgrade | Meaning::EnginePatch) {
target_in(&l.description)
} else if meaning == Meaning::ServerlessPlatform {
platform_in(&l.description)
} else {
String::new()
};
Expand Down
135 changes: 135 additions & 0 deletions services/common/src/infra_vuln/inventory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,141 @@ pub enum Kind {
ContainerImage,
}

/// Every kind, in declaration order.
pub const ALL_KINDS: &[Kind] = &[
Kind::Ec2Instance,
Kind::AutoScalingGroup,
Kind::EksNodegroup,
Kind::EksCluster,
Kind::EcsFargateService,
Kind::LambdaFunction,
Kind::RdsInstance,
Kind::RdsCluster,
Kind::ElasticacheGroup,
Kind::OpensearchDomain,
Kind::ContainerImage,
];

/// What one account and region's latest read saw in full, from its summary
/// row: only these kinds may close a finding or drop a resource.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct KindsRead {
pub account: String,
pub region: String,
pub read_at: String,
/// Kinds every call answered for, every page read.
pub complete: Vec<Kind>,
}

/// Every account and region's latest full reads.
#[derive(Debug, Clone, Default)]
pub struct Coverage {
pub reads: Vec<KindsRead>,
}

impl Coverage {
/// The latest read of this account and region saw every resource of
/// this kind.
pub fn complete(&self, account: &str, region: &str, kind: Kind) -> bool {
self.reads
.iter()
.any(|r| r.account == account && r.region == region && r.complete.contains(&kind))
}

/// When the account and region was last read, empty when never.
pub fn read_at(&self, account: &str, region: &str) -> &str {
self.reads
.iter()
.find(|r| r.account == account && r.region == region)
.map(|r| r.read_at.as_str())
.unwrap_or("")
}
}

/// The resources a new read replaces: stored rows of this account and
/// region that the read did not return, of a kind the read saw in full.
/// Rows of a kind the read did not see in full are kept (a failed or
/// partial read removes nothing). Returns their sort keys.
pub fn gone(stored: &[Resource], fresh: &[Resource], complete: &[Kind]) -> Vec<String> {
let seen: std::collections::BTreeSet<String> = fresh.iter().map(Resource::sk).collect();
let mut out: Vec<String> = stored
.iter()
.filter(|r| complete.contains(&r.kind))
.map(Resource::sk)
.filter(|sk| !seen.contains(sk))
.collect();
out.sort();
out.dedup();
out
}

/// Terraform module folders nothing calls: the `.tf` files read hold no
/// provider, backend or `terraform` block there and no `module` block
/// anywhere names the folder as its `source`. What is declared in them is
/// never applied, so it is not something that runs. A folder is kept when
/// unsure (a remote source that ends in its name, a root with no
/// provider block of its own).
pub fn uncalled_modules(files: &[(&str, &str, &str)]) -> std::collections::BTreeSet<String> {
use std::collections::{BTreeMap, BTreeSet};
let dir_of = |p: &str| {
p.rsplit_once('/')
.map(|(d, _)| d.to_string())
.unwrap_or_default()
};
let source = re(r#"(?m)^\s*source\s*=\s*"([^"]+)""#);
let root = re(r#"(?m)^\s*(provider\s+"|terraform\s*\{|backend\s+")"#);
// (repo, dir) of each .tf file, and whether one of its files is a root.
let mut dirs: BTreeMap<(String, String), bool> = BTreeMap::new();
let mut called: BTreeSet<(String, String)> = BTreeSet::new();
let mut remote_tails: BTreeSet<String> = BTreeSet::new();
for (repo, path, content) in files {
if !path.ends_with(".tf") {
continue;
}
let d = dir_of(path);
let is_root = root.is_match(content);
let e = dirs.entry((repo.to_string(), d.clone())).or_insert(false);
*e |= is_root;
for c in source.captures_iter(content) {
let src = c[1].to_string();
if src.starts_with("./") || src.starts_with("../") {
let mut parts: Vec<&str> = if d.is_empty() {
Vec::new()
} else {
d.split('/').collect()
};
for seg in src.split('/') {
match seg {
"." | "" => {}
".." => {
parts.pop();
}
s => parts.push(s),
}
}
called.insert((repo.to_string(), parts.join("/")));
} else if let Some(tail) = src
.split("//")
.last()
.and_then(|t| t.split('?').next())
.and_then(|t| t.trim_end_matches('/').rsplit('/').next())
{
remote_tails.insert(tail.to_string());
}
}
}
dirs.into_iter()
.filter(|((repo, d), is_root)| {
!is_root
&& d.split('/').any(|s| s == "modules")
&& !called.contains(&(repo.clone(), d.clone()))
&& !remote_tails.contains(d.rsplit('/').next().unwrap_or(""))
})
.map(|((repo, d), _)| format!("{repo}:{d}"))
.collect()
}

impl Kind {
pub fn label(self) -> &'static str {
match self {
Expand Down
Loading
Loading