From fc985ce480b62e82af4a0190cb94e232e51324c0 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 7 Nov 2026 12:44:44 -0500 Subject: [PATCH 1/2] Quiet log findings resolve again: the log analyzer may use the log reader On an install in the same account as the logs it reads, the permissions boundary let only the gateway and worker take on CoderHelmLogReader. The log analyzer, its main user, was refused (AccessDenied in a permissions boundary) on every run, so no finding was refreshed or resolved, and the page kept promising a resolve date that had passed. - Boundary: the log analyzer's role (now tagged coderhelm:role=log-analyzer) may take on the read roles here; its own role policy keeps it to the log reader. One statement, so the boundary stays under IAM's size limit. IAM simulator fixtures regenerated for the boundary and runtime verdicts; the access check verifies the analyzer's real role can't take on the data-source role. - One quiet-period rule: the page's resolve date is worked out exactly as the sweep does (quiet_days_for in Rust and Python, checked against shared cases), instead of a stored value that was missing or stale. - A passed date is never a promise: the page says the next check resolves it, or that checks are failing and why, with a banner per account. - A query that fails holds only the log groups it covered; quiet findings in the other groups still resolve. - The analyzer reads nanosecond times on every Python version. - The native simulator script resolves a parameter that points at a parent role. --- infra/lib/access.ts | 23 +- infra/lib/log-analyzer-stack.ts | 7 + infra/lib/worker-stack.ts | 2 +- infra/scripts/deploy-role-sim.py | 10 +- infra/test/access.test.ts | 19 +- infra/test/deploy-role-sim.test.ts | 5 +- infra/test/fixtures/deploy-role-sim.json | 9 +- infra/test/fixtures/native-sim.json | 9 +- infra/test/native-sim.test.ts | 5 +- lambda/log-analyzer/attribution.py | 6 +- lambda/log-analyzer/handler.py | 44 ++- lambda/tests/test_log_attribution.py | 2 +- lambda/tests/test_log_dedup.py | 54 +++ selfhost/check-access.mjs | 24 +- selfhost/launch/check-access.test.mjs | 34 +- services/common/src/log_findings.rs | 344 +++++++++++++++++- .../tests/fixtures/quiet_days_cases.json | 15 + services/gateway/src/routes/log_findings.rs | 39 +- 18 files changed, 575 insertions(+), 76 deletions(-) create mode 100644 services/common/tests/fixtures/quiet_days_cases.json diff --git a/infra/lib/access.ts b/infra/lib/access.ts index 07dda71e1..23ebfbf19 100644 --- a/infra/lib/access.ts +++ b/infra/lib/access.ts @@ -137,6 +137,18 @@ export const OWN_READ_ROLES = ["CoderHelmLogReader", "CoderhelmReadOnly"]; */ export const RUNTIME_ROLE_TAG = "coderhelm:role"; export const RUNTIME_ROLES = ["gateway", "worker"]; +/** + * The log analyzer's tag value (infra/lib/log-analyzer-stack.ts). It reads + * logs through the log reader here: without it a same-account install never + * analyzes its logs, and no finding ever resolves. The boundary lets it take + * on CoderHelm's read roles like the gateway and worker (one statement keeps + * the boundary under IAM's 6,144 characters); its own role policy allows + * sts:AssumeRole on CoderHelmLogReader only, so it never takes on the + * data-source role (selfhost/check-access.mjs checks both together). + */ +export const LOG_ANALYZER_ROLE = "log-analyzer"; +/** Every tag value the boundary lets take on the read roles in this account. */ +export const READ_ROLE_CALLERS = [...RUNTIME_ROLES, LOG_ANALYZER_ROLE]; /** STS actions on a role in this account: all denied, except sts:AssumeRole on the read roles above. */ const ROLE_SESSION_ACTIONS = ["sts:AssumeRole", "sts:AssumeRoleWithWebIdentity", "sts:AssumeRoleWithSAML", "sts:TagSession", "sts:SetSourceIdentity"]; @@ -331,14 +343,15 @@ export function guardrails(n: AccessNames, otherBoundaries: string[] = []): Stat Resource: a.ownReadRoles, }, { - // And only by the gateway's and the worker's roles (their tag; a role - // without it is refused). Each read role's trust policy still requires - // the team's external id. - Sid: "ReadRolesHereOnlyGatewayAndWorker", + // And only by CoderHelm's own functions that read through them (their + // tag; a role without it is refused): the gateway, the worker and the + // log analyzer. Each read role's trust policy still requires the + // team's external id. + Sid: "ReadRolesHereOnlyCoderHelmRuntime", Effect: "Deny", Action: "sts:AssumeRole", Resource: a.ownReadRoles, - Condition: { StringNotEquals: { [`aws:PrincipalTag/${RUNTIME_ROLE_TAG}`]: RUNTIME_ROLES } }, + Condition: { StringNotEquals: { [`aws:PrincipalTag/${RUNTIME_ROLE_TAG}`]: READ_ROLE_CALLERS } }, }, { // That tag is set and removed only by CloudFormation through the diff --git a/infra/lib/log-analyzer-stack.ts b/infra/lib/log-analyzer-stack.ts index 250551023..abff8082a 100644 --- a/infra/lib/log-analyzer-stack.ts +++ b/infra/lib/log-analyzer-stack.ts @@ -10,6 +10,7 @@ import * as s3 from "aws-cdk-lib/aws-s3"; import * as s3deploy from "aws-cdk-lib/aws-s3-deployment"; import * as sqs from "aws-cdk-lib/aws-sqs"; import { Construct } from "constructs"; +import { LOG_ANALYZER_ROLE, RUNTIME_ROLE_TAG } from "./access"; import { ResolvedConfig } from "./config"; import { repoPath } from "./paths"; import { modelProviderEnvironment, modelPolicyStatements } from "./service-env"; @@ -120,6 +121,12 @@ export class LogAnalyzerStack extends cdk.Stack { }) ); + // On a hardened install in the same account as the logs it reads, the + // boundary lets this tag take on the read roles there + // (infra/lib/access.ts READ_ROLE_CALLERS); the statement above keeps it + // to the log reader. + cdk.Tags.of(analyzerFunction.role!).add(RUNTIME_ROLE_TAG, LOG_ANALYZER_ROLE); + // --- EventBridge Schedule: every 6 hours --- new events.Rule(this, "AnalyzerSchedule", { ruleName: `${prefix}-log-analyzer-schedule`, diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index f9b3ba539..b6f2d207d 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -210,7 +210,7 @@ export class WorkerStack extends cdk.Stack { ); // On a hardened install the boundary lets only the gateway's and the // worker's roles take on these two roles in the install's own account - // (infra/lib/access.ts, ReadRolesHereOnlyGatewayAndWorker): this tag + // (infra/lib/access.ts, ReadRolesHereOnlyCoderHelmRuntime): this tag // says which they are. cdk.Tags.of(this.workerFunction.role!).add(RUNTIME_ROLE_TAG, "worker"); // MCP servers: read their settings; write back a remote server's renewed diff --git a/infra/scripts/deploy-role-sim.py b/infra/scripts/deploy-role-sim.py index 806e37252..31d9a1f6f 100644 --- a/infra/scripts/deploy-role-sim.py +++ b/infra/scripts/deploy-role-sim.py @@ -15,7 +15,8 @@ 4. Simulates what the boundary leaves the install's functions in its own account (`runtime`): sts actions on CoderHelm's two read roles, on lookalike names, the CDK bootstrap, the deploy role and the install's own - roles, by the gateway's and worker's roles (their coderhelm:role tag), by + roles, by the gateway's, worker's and log analyzer's roles (their + coderhelm:role tag), by another role and by an untagged one; and who may set that tag. The identity policy allows all of it, so only the boundary decides. 5. Writes infra/test/fixtures/deploy-role-sim.json, which @@ -665,6 +666,13 @@ def grouped(simulated): for (const [p, v] of Object.entries(rel.parent.Resources[part].Properties.Parameters)) { const g = v["Fn::GetAtt"]; if (!g) continue; + if (!rel.children[g[0]]) { + // A parent resource, not a part: its role's ARN (the auto-update role). + const r = rel.parent.Resources[g[0]]; + if (!r || r.Type !== "AWS::IAM::Role" || g[1] !== "Arn") throw new Error("unresolved GetAtt " + JSON.stringify(g)); + imports[part + "/" + p] = "arn:aws:iam::" + ACCT + ":role/" + resolveValue(r.Properties.RoleName, { values }); + continue; + } const exp = rel.children[g[0]].Outputs[g[1].replace("Outputs.", "")].Export.Name; imports[part + "/" + p] = resolveValue(exp, { values }); } diff --git a/infra/test/access.test.ts b/infra/test/access.test.ts index c1e890add..01b71e35f 100644 --- a/infra/test/access.test.ts +++ b/infra/test/access.test.ts @@ -14,7 +14,7 @@ import * as path from "node:path"; import * as cdk from "aws-cdk-lib"; import { buildApp } from "../lib/app"; import { resolveConfig, ResolvedConfig, CoderhelmConfig } from "../lib/config"; -import { AccessNames, accessNames, boundaryPolicy, BOUNDARY_SERVICES, OWN_READ_ROLES, RUNTIME_ROLE_TAG, RUNTIME_ROLES, deployPolicy, INSTALL_TAG, PolicyDocument, Statement, WINDOW_EXPIRES, WINDOW_USER_ID, windowPolicy, windowPolicyParts } from "../lib/access"; +import { AccessNames, accessNames, boundaryPolicy, BOUNDARY_SERVICES, LOG_ANALYZER_ROLE, OWN_READ_ROLES, READ_ROLE_CALLERS, RUNTIME_ROLE_TAG, RUNTIME_ROLES, deployPolicy, INSTALL_TAG, PolicyDocument, Statement, WINDOW_EXPIRES, WINDOW_USER_ID, windowPolicy, windowPolicyParts } from "../lib/access"; import { allowed, glob, list, Request } from "./iam-eval"; import { installName } from "../lib/hardening"; import { buildSpecSha256, canonicalJson, updateBuildSpecObject, UPDATE_BUILD_VARIABLES } from "../lib/updates-stack"; @@ -123,15 +123,20 @@ test("boundary: even a role whose own policy allows everything stays inside it", // An install in the same AWS account as the data it reads takes on // CoderHelm's own read roles there. The boundary allows exactly that: only // sts:AssumeRole, only on those two names, only by the gateway's and the -// worker's roles (their coderhelm:role tag). -test("boundary: in its own account, only the gateway and worker may assume only CoderHelm's two read roles", () => { +// worker's roles, plus the log analyzer's on the log reader alone (their +// coderhelm:role tag). Without the analyzer's exception a same-account +// install never analyzes its logs, so no finding ever resolves. +test("boundary: in its own account, only the gateway, worker and log analyzer may assume only CoderHelm's read roles", () => { const sts: PolicyDocument = { Version: "2012-10-17", Statement: [{ Sid: "AllSts", Effect: "Allow", Action: "sts:*", Resource: "*" }] }; const can = (action: string, resource: string, tag?: string) => allowed([sts], BOUNDARY, { action, resource, context: { "aws:ResourceAccount": resource.split(":")[4], ...(tag ? { [`aws:PrincipalTag/${RUNTIME_ROLE_TAG}`]: tag } : {}) } }); for (const r of ["CoderHelmLogReader", "CoderhelmReadOnly"]) { for (const t of RUNTIME_ROLES) assert.ok(can("sts:AssumeRole", role(r), t), `${t} may assume ${r} here`); + // The log analyzer too (its own role policy keeps it to the log reader). + assert.ok(can("sts:AssumeRole", role(r), LOG_ANALYZER_ROLE), `log-analyzer may assume ${r} here`); // Any other caller: another function's role, a build, an untagged role, a lookalike tag value. - for (const t of ["log-analyzer", "update-build", "Gateway", "gateway-x", "", undefined]) assert.ok(!can("sts:AssumeRole", role(r), t), `${t ?? "no tag"} may not assume ${r}`); + for (const t of ["update-build", "Gateway", "gateway-x", "Log-Analyzer", "log-analyzer-x", "", undefined]) assert.ok(!can("sts:AssumeRole", role(r), t), `${t ?? "no tag"} may not assume ${r}`); + for (const a of ["sts:TagSession", "sts:SetSourceIdentity", "sts:AssumeRoleWithWebIdentity"]) assert.ok(!can(a, role(r), LOG_ANALYZER_ROLE), `log-analyzer: ${a} on ${r}`); // Only AssumeRole: no other STS action on them, even from the gateway. for (const a of ["sts:TagSession", "sts:SetSourceIdentity", "sts:AssumeRoleWithWebIdentity", "sts:AssumeRoleWithSAML"]) assert.ok(!can(a, role(r), "gateway"), `${a} on ${r}`); } @@ -141,7 +146,7 @@ test("boundary: in its own account, only the gateway and worker may assume only "CoderhelmReadOnly-2", "CoderhelmReadOnlyAdmin", "CoderHelmLogReaderAdmin", "team/CoderhelmReadOnly", "coderhelmreadonly", "CoderHelmReadOnly", "cdk-hnb659fds-cfn-exec-role-111122223333-us-west-2", n.deployRoleName, "coderhelm-prod-ServiceRole-ab12cd34", "coderhelm-prod-update-build", "OrganizationAccountAccessRole", ]) { - for (const t of RUNTIME_ROLES) { + for (const t of [...RUNTIME_ROLES, LOG_ANALYZER_ROLE]) { for (const a of ["sts:AssumeRole", "sts:TagSession", "sts:SetSourceIdentity", "sts:AssumeRoleWithWebIdentity"]) assert.ok(!can(a, role(r), t), `${t}: ${a} on ${r}`); } } @@ -188,7 +193,9 @@ test("boundary: the read role names are the ones CoderHelm's own template and se tagged[tag.Value] = fn?.Properties.FunctionName; } } - assert.deepEqual(tagged, { gateway: "coderhelm-prod-gateway", worker: "coderhelm-prod-worker" }); + assert.deepEqual(tagged, { gateway: "coderhelm-prod-gateway", worker: "coderhelm-prod-worker", "log-analyzer": "coderhelm-prod-log-analyzer" }); + // Each tag the boundary lets in is one a CoderHelm function carries. + for (const c of READ_ROLE_CALLERS) assert.ok(c in tagged, c); }); test("boundary: allows every action every synthesized CoderHelm role is given", () => { diff --git a/infra/test/deploy-role-sim.test.ts b/infra/test/deploy-role-sim.test.ts index 67782d4a8..06c6a5ad4 100644 --- a/infra/test/deploy-role-sim.test.ts +++ b/infra/test/deploy-role-sim.test.ts @@ -96,7 +96,7 @@ test("the deploy role may make every call CloudFormation makes for a self-host i // (infra/lib/access.ts, NoOtherRolesHere and the read-role exception), as // AWS's simulator saw it: an identity policy allowing every sts action and // role tag, so the boundary alone decides. -test("own-account roles: the evaluator gives the simulator's verdict, and only the gateway and worker may assume only the two read roles", () => { +test("own-account roles: the evaluator gives the simulator's verdict, and only the gateway, worker and log analyzer may assume only the two read roles", () => { const { identity, rows } = FIXTURE.runtime; const { boundary } = FIXTURE.policies; const wrong = rows.flatMap((r) => Object.entries(r.actions).filter(([action, v]) => decision([identity], boundary, { action, resource: r.resource, context: r.context }) !== v).map(([a]) => `${a} on ${r.resource} as ${r.caller}`)); @@ -117,6 +117,9 @@ test("own-account roles: the evaluator gives the simulator's verdict, and only t "deploy role: iam:UntagRole on 111122223333:role/coderhelm-prod-ServiceRole-ab12cd34 tags other", "gateway: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", "gateway: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", + // The log analyzer reads logs here; its own role policy keeps it to the log reader. + "log-analyzer: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", + "log-analyzer: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", "untagged: sts:AssumeRole on 999988887777:role/CoderHelmLogReader", "worker: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", "worker: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", diff --git a/infra/test/fixtures/deploy-role-sim.json b/infra/test/fixtures/deploy-role-sim.json index 45ca19e3c..4f1486f6e 100644 --- a/infra/test/fixtures/deploy-role-sim.json +++ b/infra/test/fixtures/deploy-role-sim.json @@ -700,7 +700,7 @@ ] }, { - "Sid": "ReadRolesHereOnlyGatewayAndWorker", + "Sid": "ReadRolesHereOnlyCoderHelmRuntime", "Effect": "Deny", "Action": "sts:AssumeRole", "Resource": [ @@ -711,7 +711,8 @@ "StringNotEquals": { "aws:PrincipalTag/coderhelm:role": [ "gateway", - "worker" + "worker", + "log-analyzer" ] } } @@ -1348,12 +1349,12 @@ "rows": [ {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "worker", "context": {"aws:PrincipalTag/coderhelm:role": "worker", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, - {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, + {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "lookalike tag", "context": {"aws:PrincipalTag/coderhelm:role": "Gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "untagged", "context": {"aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "worker", "context": {"aws:PrincipalTag/coderhelm:role": "worker", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, - {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, + {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "lookalike tag", "context": {"aws:PrincipalTag/coderhelm:role": "Gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "untagged", "context": {"aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly-2"}, diff --git a/infra/test/fixtures/native-sim.json b/infra/test/fixtures/native-sim.json index 25077063b..db070a3a2 100644 --- a/infra/test/fixtures/native-sim.json +++ b/infra/test/fixtures/native-sim.json @@ -744,7 +744,7 @@ ] }, { - "Sid": "ReadRolesHereOnlyGatewayAndWorker", + "Sid": "ReadRolesHereOnlyCoderHelmRuntime", "Effect": "Deny", "Action": "sts:AssumeRole", "Resource": [ @@ -755,7 +755,8 @@ "StringNotEquals": { "aws:PrincipalTag/coderhelm:role": [ "gateway", - "worker" + "worker", + "log-analyzer" ] } } @@ -1458,12 +1459,12 @@ "rows": [ {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "worker", "context": {"aws:PrincipalTag/coderhelm:role": "worker", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, - {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, + {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "lookalike tag", "context": {"aws:PrincipalTag/coderhelm:role": "Gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "untagged", "context": {"aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderHelmLogReader"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "worker", "context": {"aws:PrincipalTag/coderhelm:role": "worker", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, - {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, + {"actions": {"sts:AssumeRole": "allowed", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "log-analyzer", "context": {"aws:PrincipalTag/coderhelm:role": "log-analyzer", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "lookalike tag", "context": {"aws:PrincipalTag/coderhelm:role": "Gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "untagged", "context": {"aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly"}, {"actions": {"sts:AssumeRole": "explicitDeny", "sts:AssumeRoleWithSAML": "explicitDeny", "sts:AssumeRoleWithWebIdentity": "explicitDeny", "sts:SetSourceIdentity": "explicitDeny", "sts:TagSession": "explicitDeny"}, "caller": "gateway", "context": {"aws:PrincipalTag/coderhelm:role": "gateway", "aws:ResourceAccount": "111122223333"}, "resource": "arn:aws:iam::111122223333:role/CoderhelmReadOnly-2"}, diff --git a/infra/test/native-sim.test.ts b/infra/test/native-sim.test.ts index 4e8062da9..93251ac77 100644 --- a/infra/test/native-sim.test.ts +++ b/infra/test/native-sim.test.ts @@ -115,11 +115,14 @@ test("the helper may do what it needs and nothing on another install's or anyone assert.notEqual(row("secretsmanager:DeleteSecret", ":secret:coderhelm/other/secrets-AbCdEf")?.simulator, "allowed"); }); -test("runtime roles: only the gateway and worker may take on the two read roles in the install's own account", () => { +test("runtime roles: only the gateway, worker and log analyzer may take on the two read roles in the install's own account", () => { const allowed = (F.runtime.rows as any[]).flatMap((r) => Object.entries(r.actions).filter(([a, v]) => v === "allowed" && a.startsWith("sts:")).map(([a]) => `${r.caller}: ${a} on ${r.resource.split(":").slice(4).join(":")}`)).sort(); assert.deepEqual(allowed, [ "gateway: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", "gateway: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", + // The log analyzer reads logs here; its own role policy keeps it to the log reader. + "log-analyzer: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", + "log-analyzer: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", "untagged: sts:AssumeRole on 999988887777:role/CoderHelmLogReader", "worker: sts:AssumeRole on 111122223333:role/CoderHelmLogReader", "worker: sts:AssumeRole on 111122223333:role/CoderhelmReadOnly", diff --git a/lambda/log-analyzer/attribution.py b/lambda/log-analyzer/attribution.py index 996ffbe35..0fbd9ca6d 100644 --- a/lambda/log-analyzer/attribution.py +++ b/lambda/log-analyzer/attribution.py @@ -24,6 +24,7 @@ import json import logging +import re import time from datetime import datetime, timezone @@ -74,8 +75,11 @@ def parse_ts(value): return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc) except ValueError: pass + # The gateway writes nanoseconds (9 digits); fromisoformat before 3.13 + # takes at most 6, so the rest is dropped (sub-microsecond, never used). + text = re.sub(r"(\.\d{6})\d+", r"\1", text.replace("Z", "+00:00")) try: - t = datetime.fromisoformat(text.replace("Z", "+00:00")) + t = datetime.fromisoformat(text) except ValueError: return None return t if t.tzinfo else t.replace(tzinfo=timezone.utc) diff --git a/lambda/log-analyzer/handler.py b/lambda/log-analyzer/handler.py index 8b032ff52..f7ef9e1c8 100644 --- a/lambda/log-analyzer/handler.py +++ b/lambda/log-analyzer/handler.py @@ -308,9 +308,11 @@ def analyze_connection(conn): start, end = lookback_window() # Run queries and collect results. A query that fails is not "no errors": - # when any fails, nothing is auto-resolved this run. + # nothing in the log groups it covered is auto-resolved this run (the + # other groups were read in full, so their quiet findings still resolve). batches = [] any_query_failed = False + failed_groups = set() for query_def in INSIGHTS_QUERIES: matching_groups = filter_log_groups(log_groups, query_def.get("log_group_pattern")) if not matching_groups: @@ -321,6 +323,7 @@ def analyze_connection(conn): results = run_insights_query(cw_logs, batch, query_def["query"], start, end) if results is None: any_query_failed = True + failed_groups.update(batch) continue if results: batches.append( @@ -339,11 +342,12 @@ def analyze_connection(conn): if not batches: record_connection_success(team_id, account_id) if any_query_failed: - logger.warning(f"{team_id}/{account_id}: queries failed and none returned rows, skipping resolution") - return 0 - logger.info(f"No errors found for {team_id}/{account_id}") - # Every query ran and found nothing: the findings are no longer erroring. - resolve_stale_recommendations(team_id, existing, set()) + logger.warning(f"{team_id}/{account_id}: queries failed for {len(failed_groups)} log group(s); resolving only in the others") + else: + logger.info(f"No errors found for {team_id}/{account_id}") + # Every query that ran found nothing: those groups' findings are no + # longer erroring. + resolve_stale_recommendations(team_id, existing, set(), skip_groups=failed_groups) return 0 # One entry per log group and message, each with its own counts and times. @@ -374,8 +378,6 @@ def analyze_connection(conn): # Credit each finding to the log groups whose lines match it, checked one # group at a time; then make its words match that evidence. candidates, check_failed = attribute_recommendations(cw_logs, recommendations, evidence, start, end) - if check_failed: - any_query_failed = True attribution.guard_texts( candidates, log_groups, lambda prompt: ask_model(prompt, api_key, team_id) ) @@ -388,10 +390,13 @@ def analyze_connection(conn): if is_new or cand.get("seen_again"): new_recs.append(cand) - # Resolve findings that stopped appearing for the quiet period — only - # after a complete run. - if not any_query_failed: - resolve_stale_recommendations(team_id, existing, seen_ids) + # Resolve findings that stopped appearing for the quiet period, in every + # log group this run read in full. A failed attribution check can't tell + # which group a line was in, so then nothing is resolved. + if check_failed: + logger.warning(f"{team_id}/{account_id}: an attribution check failed, skipping resolution") + else: + resolve_stale_recommendations(team_id, existing, seen_ids, skip_groups=failed_groups) notify_new_recommendations(team_id, account_id, new_recs) logger.info(f"{team_id}/{account_id}: {len(new_recs)} new recommendations") @@ -742,15 +747,18 @@ def list_recent_findings(team_id, account_id, now=None): return items -def resolve_stale_recommendations(team_id, existing, seen_ids, now=None): - """Mark open findings resolved when this complete run didn't see them and - they have been quiet for their quiet period (lifecycle.quiet_days_for). - One missed run never resolves a finding. Open findings also carry their - quiet period (`quiet_days`) so the page can say when one resolves.""" +def resolve_stale_recommendations(team_id, existing, seen_ids, now=None, skip_groups=()): + """Mark open findings resolved when this run read their log group in full, + didn't see them, and they have been quiet for their quiet period + (lifecycle.quiet_days_for). One missed run never resolves a finding, and a + group whose query failed (`skip_groups`) resolves nothing. Open findings + also carry their quiet period (`quiet_days`) so the page can say when one + resolves.""" now_dt = now or datetime.now(timezone.utc) now_iso = now_dt.isoformat() resolved_count = 0 - stale = lifecycle.stale(existing, seen_ids, now_dt) + skip = set(skip_groups or ()) + stale = [i for i in lifecycle.stale(existing, seen_ids, now_dt) if i.get("source_log_group") not in skip] stale_ids = {i.get("rec_id") for i in stale} for item in stale: days = lifecycle.quiet_days_for(item) diff --git a/lambda/tests/test_log_attribution.py b/lambda/tests/test_log_attribution.py index 5a62b2996..e5427f18b 100644 --- a/lambda/tests/test_log_attribution.py +++ b/lambda/tests/test_log_attribution.py @@ -182,7 +182,7 @@ def ask(prompt, _key, _team=None): logs_client_for=lambda _c: cw, list_recent_findings=lambda *_a: [], record_connection_success=lambda *_a: None, - resolve_stale_recommendations=lambda *_a: None, + resolve_stale_recommendations=lambda *_a, **_k: None, notify_new_recommendations=lambda *_a: None, ask_model=ask, aws_insights_table=table, diff --git a/lambda/tests/test_log_dedup.py b/lambda/tests/test_log_dedup.py index 590b72b1a..d433f1a9b 100644 --- a/lambda/tests/test_log_dedup.py +++ b/lambda/tests/test_log_dedup.py @@ -14,6 +14,8 @@ import merge_duplicates as M +QUIET_CASES = __import__("pathlib").Path(__file__).resolve().parents[2] / "services/common/tests/fixtures/quiet_days_cases.json" + A, F, L = h.attribution, h.fingerprint, h.lifecycle WEB = "/ecs/prod-shop-web" @@ -290,6 +292,58 @@ def test_seen_again_after_an_auto_resolve_reopens(self): self.assertEqual(L.quiet_days_for(item), 6) self.assertEqual(L.stale([item], set()), []) + def test_the_quiet_period_matches_the_page_on_every_shared_case(self): + # services/common/src/log_findings.rs runs the same cases, so the date + # the page shows is the one this sweep uses. + cases = json.load(open(QUIET_CASES))["cases"] + self.assertGreater(len(cases), 5) + for c in cases: + item = {k: c[k] for k in ("daily_lines", "last_resolved_at", "reopened_at") if c[k]} + self.assertEqual(L.quiet_days_for(item), c["quiet_days"], c["name"]) + + def test_an_acknowledged_finding_that_came_back_resolves_after_twice_its_silence(self): + # Resolved after one burst, back 4 days later, acknowledged, then + # quiet: it resolves 8 days after its last line, not 3. + item = {"rec_id": "e1", "sk": "REC#e1", "status": "pending", "source_log_group": WEB, + "acknowledged_at": "2026-11-03T06:44:39.346874173+00:00", + "daily_lines": [{"day": "2026-10-31", "lines": 6296}], + "last_resolved_at": "2026-10-27T03:48:40.472966+00:00", + "reopened_at": "2026-10-31T03:48:51.255562+00:00", + "last_seen_at": "2026-10-31T03:38:10.248+00:00"} + self.assertEqual(L.quiet_days_for(item), 8) + at = lambda t: datetime.fromisoformat(t) + self.assertEqual(L.stale([item], set(), at("2026-11-08T03:00:00+00:00")), []) + self.assertEqual(L.stale([item], set(), at("2026-11-08T03:39:00+00:00")), [item]) + + def test_a_failed_query_holds_only_the_groups_it_covered(self): + old = iso_ago(days=20) + web = {"rec_id": "w", "sk": "REC#w", "status": "pending", "source_log_group": WEB, "last_seen_at": old} + api = {"rec_id": "a", "sk": "REC#a", "status": "pending", "source_log_group": API, "last_seen_at": old} + t = Table() + with Patch(aws_insights_table=t, emit_event=lambda *_a, **_k: None): + h.resolve_stale_recommendations("TEAM#t", [web, api], set(), skip_groups={API}) + resolves = [u["Key"]["sk"] for u in t.updates if ":s" in u["ExpressionAttributeValues"]] + self.assertEqual(resolves, ["REC#w"]) + + def test_a_query_that_fails_every_run_no_longer_holds_every_finding_open(self): + # One group's query keeps failing; the other groups' quiet findings + # still resolve on a run that read them in full. + old = iso_ago(days=20) + web = {"rec_id": "w", "sk": "REC#w", "status": "pending", "source_log_group": WEB, "last_seen_at": old, + "source_account_id": ACCOUNT} + calls = [] + def query(cw, groups, q, start=None, end=None): + calls.append(list(groups)) + return None if API in groups else [] + t = Table() + with Patch(aws_insights_table=t, emit_event=lambda *_a, **_k: None, get_team_api_key=lambda _t: "k", + logs_client_for=lambda _c: object(), log_groups_for=lambda _c, _l: [WEB], + run_insights_query=query, list_recent_findings=lambda *_a, **_k: [web], + record_connection_success=lambda *_a: None): + h.analyze_connection({"team_id": "TEAM#t", "account_id": ACCOUNT}) + self.assertTrue(calls) + self.assertEqual([u["Key"]["sk"] for u in t.updates if ":s" in u["ExpressionAttributeValues"]], ["REC#w"]) + def test_history_adds_new_lines_per_day(self): hist = L.add_history([], "2026-10-25", 5) hist = L.add_history(hist, "2026-10-25", 2) diff --git a/selfhost/check-access.mjs b/selfhost/check-access.mjs index 4eccd0af4..a7d54b310 100644 --- a/selfhost/check-access.mjs +++ b/selfhost/check-access.mjs @@ -93,7 +93,8 @@ const noBoundary = []; const admin = []; const star = []; // The tag that lets a role take on CoderHelm's read roles in this account -// (infra/lib/access.ts RUNTIME_ROLE_TAG): only the gateway's and worker's. +// (infra/lib/access.ts RUNTIME_ROLE_TAG): only the gateway's, the worker's +// and the log analyzer's (the log reader only). const RUNTIME_TAG = "coderhelm:role"; const runtimeTagged = new Map(); for (const r of roles) { @@ -277,7 +278,8 @@ try { for (const r of others) for (const a of ["sts:AssumeRole", "sts:TagSession"]) if (decide(a, roleArn(r), tag) === "allowed") broader.push(`${tag}: ${a} on ${r}`); for (const r of READ_ROLES) for (const a of ["sts:TagSession", "sts:SetSourceIdentity", "sts:AssumeRoleWithWebIdentity"]) if (decide(a, roleArn(r), tag) === "allowed") broader.push(`${tag}: ${a} on ${r}`); } - for (const r of READ_ROLES) for (const tag of [null, "log-analyzer"]) if (decide("sts:AssumeRole", roleArn(r), tag) === "allowed") broader.push(`${tag ? `role tagged ${tag}` : "an untagged role"}: sts:AssumeRole on ${r}`); + for (const r of READ_ROLES) if (decide("sts:AssumeRole", roleArn(r), null) === "allowed") broader.push(`an untagged role: sts:AssumeRole on ${r}`); + for (const r of others) if (decide("sts:AssumeRole", roleArn(r), "log-analyzer") === "allowed") broader.push(`log-analyzer: sts:AssumeRole on ${r}`); const hasException = READ_ROLES.some((r) => ["gateway", "worker"].some((tag) => decide("sts:AssumeRole", roleArn(r), tag) === "allowed")); if (hasException) { for (const a of ["iam:TagRole", "iam:UntagRole", "iam:CreateRole"]) { @@ -291,11 +293,12 @@ try { check("the boundary: no other role in this account can be assumed (only CoderHelm's two read roles, by the gateway and worker)", false, e.message); } -// Only the gateway's and the worker's roles carry the tag, and they can -// take on the read roles (the policy simulator, with the role's own tag). -// The functions' roles, found in their stacks (GatewayServiceRole..., WorkerServiceRole...). +// Only the gateway's, the worker's and the log analyzer's roles carry the +// tag, and they can take on the read roles (the policy simulator, with the +// role's own tag). The functions' roles, found in their stacks +// (GatewayServiceRole..., WorkerServiceRole..., LogAnalyzerServiceRole...). const runtime = {}; -for (const [f, stack, id] of [["gateway", "api", "GatewayServiceRole"], ["worker", "worker", "WorkerServiceRole"]]) { +for (const [f, stack, id] of [["gateway", "api", "GatewayServiceRole"], ["worker", "worker", "WorkerServiceRole"], ["log-analyzer", "log-analyzer", "LogAnalyzerServiceRole"]]) { try { const res = aws("cloudformation", "describe-stack-resources", "--stack-name", `${prefix}-${stack}`).StackResources ?? []; runtime[f] = res.find((r) => r.ResourceType === "AWS::IAM::Role" && r.LogicalResourceId.startsWith(id))?.PhysicalResourceId ?? null; @@ -304,7 +307,7 @@ for (const [f, stack, id] of [["gateway", "api", "GatewayServiceRole"], ["worker } } const wrongTag = [...runtimeTagged].filter(([name, v]) => !(runtime[v] === name)).map(([name, v]) => `${name} (${RUNTIME_TAG}=${v})`); -check(`only the gateway's and worker's roles carry ${RUNTIME_TAG}`, wrongTag.length === 0, wrongTag.join(", ") || [...runtimeTagged].map(([name, v]) => `${v}: ${name}`).join(", ") || "no role carries it yet (a release from before it)"); +check(`only the gateway's, worker's and log analyzer's roles carry ${RUNTIME_TAG}`, wrongTag.length === 0, wrongTag.join(", ") || [...runtimeTagged].map(([name, v]) => `${v}: ${name}`).join(", ") || "no role carries it yet (a release from before it)"); try { const notes = []; const broader = []; @@ -315,10 +318,13 @@ try { "--context-entries", ctxEntry("aws:ResourceAccount", account), ...(tag ? [ctxEntry(`aws:PrincipalTag/${RUNTIME_TAG}`, tag)] : [])).EvaluationResults?.[0]?.EvalDecision; notes.push(`${f}: ${READ_ROLES.map((r) => `${r} ${sim(r)}`).join(", ")}`); for (const r of [`cdk-hnb659fds-deploy-role-${account}-${region}`, deployRole, "CoderhelmReadOnly-2"]) if (sim(r) === "allowed") broader.push(`${f}: sts:AssumeRole on ${r}`); + // The log analyzer reads logs only: its own role policy keeps it to the + // log reader, never the data-source role. + if (f === "log-analyzer" && sim("CoderhelmReadOnly") === "allowed") broader.push("log-analyzer: sts:AssumeRole on CoderhelmReadOnly"); } - check("the gateway and worker roles: only the read roles in this account (policy simulator)", broader.length === 0, broader.join(", ") || notes.join("; ")); + check("the gateway, worker and log analyzer roles: only the read roles in this account (policy simulator)", broader.length === 0, broader.join(", ") || notes.join("; ")); } catch (e) { - check("the gateway and worker roles: only the read roles in this account (policy simulator)", false, e.message); + check("the gateway, worker and log analyzer roles: only the read roles in this account (policy simulator)", false, e.message); } // CoderHelm's read roles in this account, when they exist: the boundary diff --git a/selfhost/launch/check-access.test.mjs b/selfhost/launch/check-access.test.mjs index 1a70632fd..9bb9d2d57 100644 --- a/selfhost/launch/check-access.test.mjs +++ b/selfhost/launch/check-access.test.mjs @@ -27,10 +27,13 @@ function healthy() { "coderhelm-prod-ServiceRole-ab12cd34": role("coderhelm-prod-ServiceRole-ab12cd34"), "coderhelm-prod-ServiceRole-0000aaaa": role("coderhelm-prod-ServiceRole-0000aaaa", { Tags: [{ Key: "coderhelm:role", Value: "gateway" }] }), "coderhelm-prod-ServiceRole-1111bbbb": role("coderhelm-prod-ServiceRole-1111bbbb", { Tags: [{ Key: "coderhelm:role", Value: "worker" }] }), + "coderhelm-prod-ServiceRole-2222cccc": role("coderhelm-prod-ServiceRole-2222cccc", { Tags: [{ Key: "coderhelm:role", Value: "log-analyzer" }] }), }, - functions: { "coderhelm-prod-gateway": "coderhelm-prod-ServiceRole-0000aaaa", "coderhelm-prod-worker": "coderhelm-prod-ServiceRole-1111bbbb" }, + functions: { "coderhelm-prod-gateway": "coderhelm-prod-ServiceRole-0000aaaa", "coderhelm-prod-worker": "coderhelm-prod-ServiceRole-1111bbbb", "coderhelm-prod-log-analyzer": "coderhelm-prod-ServiceRole-2222cccc" }, // What the boundary allows in this account, as "||" (the simulator's answer). - boundaryAllows: ["gateway", "worker"].flatMap((t) => ["CoderHelmLogReader", "CoderhelmReadOnly"].map((r) => `${t}|sts:AssumeRole|${r}`)), + boundaryAllows: ["gateway", "worker", "log-analyzer"].flatMap((t) => ["CoderHelmLogReader", "CoderhelmReadOnly"].map((r) => `${t}|sts:AssumeRole|${r}`)), + // What each function's own role policy allows (the simulator with role and boundary together). + roleDenies: { "coderhelm-prod-ServiceRole-2222cccc": ["CoderhelmReadOnly"] }, attached: { "coderhelm-prod-ServiceRole-ab12cd34": [{ PolicyArn: "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole" }] }, inline: { "coderhelm-prod-update-build": { idle: { Statement: [{ Effect: "Allow", Action: "lambda:InvokeFunction", Resource: "arn:aws:lambda:x" }] } } }, stacks: [{ StackName: "coderhelm-prod-api", RoleARN: DEPLOY, StackStatus: "UPDATE_COMPLETE" }, { StackName: "other-app", RoleARN: "arn:aws:iam::1:role/x", StackStatus: "CREATE_COMPLETE" }], @@ -72,8 +75,8 @@ if (k === "cloudformation describe-stacks") out({ Stacks: s.stacks }); if (k === "iam get-policy") out({ Policy: { DefaultVersionId: "v3" } }); if (k === "iam get-policy-version") out({ PolicyVersion: { Document: { Version: "2012-10-17", Statement: [] } } }); if (k === "cloudformation describe-stack-resources") { - const st = arg("--stack-name"), f = st === "coderhelm-prod-api" ? "coderhelm-prod-gateway" : st === "coderhelm-prod-worker" ? "coderhelm-prod-worker" : null; - const id = st === "coderhelm-prod-api" ? "GatewayServiceRole162DEA77" : "WorkerServiceRole8543584E"; + const st = arg("--stack-name"), f = st === "coderhelm-prod-api" ? "coderhelm-prod-gateway" : st === "coderhelm-prod-worker" ? "coderhelm-prod-worker" : st === "coderhelm-prod-log-analyzer" ? "coderhelm-prod-log-analyzer" : null; + const id = st === "coderhelm-prod-api" ? "GatewayServiceRole162DEA77" : st === "coderhelm-prod-log-analyzer" ? "LogAnalyzerServiceRole0D2C1A3B" : "WorkerServiceRole8543584E"; out({ StackResources: f && (s.functions || {})[f] ? [{ ResourceType: "AWS::IAM::Role", LogicalResourceId: "OtherServiceRole1", PhysicalResourceId: "coderhelm-prod-ServiceRole-ab12cd34" }, { ResourceType: "AWS::IAM::Role", LogicalResourceId: id, PhysicalResourceId: s.functions[f] }] : [] }); } if (k === "iam simulate-custom-policy") { @@ -92,7 +95,8 @@ if (k === "iam simulate-principal-policy") { let d = "implicitDeny"; const all = a.join(" "); const tagged = all.match(/aws:PrincipalTag[/]coderhelm:role,ContextKeyValues=([^,]+)/); - if (action === "sts:AssumeRole" && tagged) d = s.boundaryAllows.includes(tagged[1] + "|sts:AssumeRole|" + arg("--resource-arns").split(":role/").pop()) ? "allowed" : "explicitDeny"; + const target = (arg("--resource-arns") || "").split(":role/").pop(); + if (action === "sts:AssumeRole" && tagged) d = ((s.roleDenies || {})[who.split(":role/").pop()] || []).includes(target) ? "implicitDeny" : s.boundaryAllows.includes(tagged[1] + "|sts:AssumeRole|" + target) ? "allowed" : "explicitDeny"; else if (who.includes("deploy")) d = s.deployDecisions[action] || ((action === "lambda:UpdateFunctionCode" && all.includes("function:coderhelm-prod-")) || (action === "iam:CreateRole" && all.includes("role/coderhelm-prod-check") && all.includes("iam:PermissionsBoundary")) ? "allowed" : "implicitDeny"); else if (s.allowedForBuilds.includes(action)) d = "allowed"; out({ EvaluationResults: [{ EvalActionName: action, EvalDecision: d }] }); @@ -121,8 +125,10 @@ test("a hardened install passes every row, and the check only reads", () => { assert.match(row(out, "coderhelm-prod-installer-1a2b3c4d: no deploy window while idle"), /^PASS/); assert.match(row(out, "refused IAM users"), /^PASS/); assert.match(row(out, "no other role in this account can be assumed"), /^PASS.*expected exception: the gateway and worker may assume CoderHelmLogReader and CoderhelmReadOnly/); - assert.match(row(out, "only the gateway's and worker's roles carry coderhelm:role"), /^PASS.*gateway: coderhelm-prod-ServiceRole-0000aaaa/); - assert.match(row(out, "the gateway and worker roles: only the read roles"), /^PASS.*gateway: CoderHelmLogReader allowed, CoderhelmReadOnly allowed/); + assert.match(row(out, "only the gateway's, worker's and log analyzer's roles carry coderhelm:role"), /^PASS.*gateway: coderhelm-prod-ServiceRole-0000aaaa/); + assert.match(row(out, "the gateway, worker and log analyzer roles: only the read roles"), /^PASS.*gateway: CoderHelmLogReader allowed, CoderhelmReadOnly allowed/); + // The log analyzer reads logs through the log reader, and nothing else. + assert.match(row(out, "the gateway, worker and log analyzer roles: only the read roles"), /log-analyzer: CoderHelmLogReader allowed, CoderhelmReadOnly implicitDeny/); assert.match(row(out, "read roles in this account only read"), /^PASS.*none in this account/); for (const c of calls) assert.match(c, /^(sts get-caller-identity|ssm get-parameter|iam (list-|get-|simulate-principal-policy|simulate-custom-policy)|cloudformation describe-stack(s|-resources)|codebuild (list-|batch-get-))/, `read-only: ${c}`); assert.doesNotMatch(out, /^FAIL/m, out); @@ -201,12 +207,12 @@ test("a boundary from before the read-role exception passes and says so", () => for (const r of Object.values(s.roles)) delete r.Tags; const { code, out } = check(s); assert.match(row(out, "no other role in this account can be assumed"), /^PASS.*no exception/); - assert.match(row(out, "only the gateway's and worker's roles carry coderhelm:role"), /^PASS.*no role carries it yet/); + assert.match(row(out, "only the gateway's, worker's and log analyzer's roles carry coderhelm:role"), /^PASS.*no role carries it yet/); assert.equal(code, 0, out); }); test("a boundary that lets the gateway assume another role here, or more than AssumeRole, or an untagged role in, fails", () => { - for (const extra of ["gateway|sts:AssumeRole|coderhelm-prod-deploy-1a2b3c4d", "worker|sts:AssumeRole|CoderhelmReadOnly-2", "gateway|sts:TagSession|CoderhelmReadOnly", "|sts:AssumeRole|CoderHelmLogReader", "log-analyzer|sts:AssumeRole|CoderhelmReadOnly"]) { + for (const extra of ["gateway|sts:AssumeRole|coderhelm-prod-deploy-1a2b3c4d", "worker|sts:AssumeRole|CoderhelmReadOnly-2", "gateway|sts:TagSession|CoderhelmReadOnly", "|sts:AssumeRole|CoderHelmLogReader", "log-analyzer|sts:AssumeRole|coderhelm-prod-deploy-1a2b3c4d"]) { const s = healthy(); s.boundaryAllows.push(extra); const { code, out } = check(s); @@ -220,7 +226,7 @@ test("another role carrying the gateway or worker tag fails", () => { s.roles["coderhelm-prod-ServiceRole-ab12cd34"].Tags = [{ Key: "Coderhelm:Role", Value: "worker" }]; const { code, out } = check(s); assert.equal(code, 1); - assert.match(row(out, "only the gateway's and worker's roles carry coderhelm:role"), /^FAIL.*ServiceRole-ab12cd34/); + assert.match(row(out, "only the gateway's, worker's and log analyzer's roles carry coderhelm:role"), /^FAIL.*ServiceRole-ab12cd34/); }); test("a boundary with the exception but without the tag guard fails", () => { @@ -253,3 +259,11 @@ test("read roles here: one that only reads with an external id passes; no extern assert.match(row(r.out, "read roles in this account only read"), new RegExp("^FAIL.*" + why.source), String(why)); } }); + +test("a log analyzer role that may take on the data-source role fails", () => { + const s = healthy(); + s.roleDenies = {}; + const { code, out } = check(s); + assert.equal(code, 1); + assert.match(row(out, "the gateway, worker and log analyzer roles: only the read roles"), /^FAIL.*log-analyzer: sts:AssumeRole on CoderhelmReadOnly/); +}); diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index 9496b0594..f7686157e 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -136,6 +136,13 @@ impl Severity { /// The analyzer's quiet period for a burst that stopped /// (lambda/log-analyzer/lifecycle.py DEFAULT_QUIET_DAYS). pub const DEFAULT_QUIET_DAYS: u64 = 3; +/// The shortest and longest quiet period (lifecycle.py MIN_QUIET_DAYS, +/// MAX_QUIET_DAYS). +pub const MIN_QUIET_DAYS: u64 = 1; +pub const MAX_QUIET_DAYS: u64 = 14; +/// How often the analyzer runs (its EventBridge schedule), so a finding past +/// its quiet period resolves within this long once analysis works. +pub const ANALYSIS_EVERY_HOURS: u64 = 6; /// One finding as stored. #[derive(Debug, Clone, Default, PartialEq)] @@ -192,9 +199,15 @@ pub struct Finding { /// N days"); empty while open. pub resolved_at: String, pub resolved_reason: String, - /// Days without a matching line before the analyzer resolves it - /// (lifecycle.quiet_days_for); missing on older items. + /// Days without a matching line before the analyzer resolves it, as the + /// analyzer last wrote it; missing on older items and stale while the + /// analyzer can't run. [`Finding::quiet_days`] works it out from the same + /// inputs the analyzer uses instead. pub quiet_days: Option, + /// Matching lines per day (`[{day, lines}]`), oldest first. + pub daily_lines: Vec, + /// When it was last resolved before its latest reopen (empty if never). + pub last_resolved_at: String, } impl Finding { @@ -254,6 +267,8 @@ impl Finding { resolved_at: s(item, "resolved_at"), resolved_reason: s(item, "resolved_reason"), quiet_days: n(item, "quiet_days"), + daily_lines: counted(item, "daily_lines", "day"), + last_resolved_at: s(item, "last_resolved_at"), }) } @@ -273,12 +288,11 @@ impl Finding { .to_string() } - /// The quiet period this finding resolves after: its own, or the - /// analyzer's default for a burst that stopped. + /// The quiet period this finding resolves after, worked out exactly as + /// the analyzer's resolve sweep does (lifecycle.quiet_days_for), so the + /// date the page shows is the date the sweep uses. pub fn quiet_days(&self) -> u64 { - self.quiet_days - .filter(|d| *d > 0) - .unwrap_or(DEFAULT_QUIET_DAYS) + quiet_days_for(&self.daily_lines, &self.last_resolved_at, &self.reopened_at) } /// When an open finding resolves on its own if no new line comes @@ -309,6 +323,159 @@ impl Finding { } } +/// When a time string parses (RFC 3339, or the analyzer's +/// "YYYY-MM-DD HH:MM:SS[.f]" in UTC). +fn parse_time(v: &str) -> Option> { + let v = v.trim(); + if v.is_empty() { + return None; + } + if let Ok(t) = DateTime::parse_from_rfc3339(v) { + return Some(t.with_timezone(&Utc)); + } + ["%Y-%m-%d %H:%M:%S%.f", "%Y-%m-%d %H:%M:%S"] + .iter() + .find_map(|f| chrono::NaiveDateTime::parse_from_str(v, f).ok()) + .map(|t| t.and_utc()) +} + +/// Pure: how long a finding must go without a matching line before it is +/// resolved. The same rule as lambda/log-analyzer/lifecycle.py +/// `quiet_days_for` (both are checked against +/// services/common/tests/fixtures/quiet_days_cases.json): +/// - a burst that stopped (lines on one run of consecutive days, or no +/// daily history): [`DEFAULT_QUIET_DAYS`]; +/// - an error that keeps coming back: twice the longest silence it came back +/// from (gaps between days with lines, and the time from a resolve to the +/// reopen); +/// - never less than [`MIN_QUIET_DAYS`] nor more than [`MAX_QUIET_DAYS`]. +pub fn quiet_days_for(daily_lines: &[Counted], last_resolved_at: &str, reopened_at: &str) -> u64 { + let mut days: Vec = daily_lines + .iter() + .filter(|d| d.lines > 0) + .filter_map(|d| chrono::NaiveDate::parse_from_str(d.name.trim(), "%Y-%m-%d").ok()) + .collect(); + days.sort(); + let mut gaps: Vec = days + .windows(2) + .map(|w| (w[1] - w[0]).num_days()) + .filter(|g| *g > 1) + .map(|g| g as u64) + .collect(); + if let (Some(resolved), Some(back)) = (parse_time(last_resolved_at), parse_time(reopened_at)) { + if back > resolved { + let d = ((back - resolved).num_milliseconds() as f64 / 86_400_000.0).round_ties_even(); + gaps.push((d as u64).max(1)); + } + } + let quiet = gaps + .iter() + .max() + .map(|g| g * 2) + .unwrap_or(DEFAULT_QUIET_DAYS); + quiet.clamp(MIN_QUIET_DAYS, MAX_QUIET_DAYS) +} + +/// How the log analyzer is doing for one AWS account, from its connection +/// item (`last_analyzed_at` on a complete run; `last_error`/`last_error_at` +/// while runs fail, cleared by the next one that works). +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Analysis { + pub last_ok_at: String, + pub error: String, + pub error_at: String, +} + +impl Analysis { + pub fn from_item(item: &Item) -> Analysis { + Analysis { + last_ok_at: s(item, "last_analyzed_at"), + error: s(item, "last_error"), + error_at: s(item, "last_error_at"), + } + } + + /// Whether its latest run failed (an error newer than the last run that + /// worked). + pub fn failing(&self) -> bool { + match (parse_time(&self.error_at), parse_time(&self.last_ok_at)) { + (Some(e), Some(ok)) => e > ok, + (Some(_), None) => true, + _ => false, + } + } + + /// The failure in plain words, for the page. + pub fn reason(&self) -> String { + analysis_reason(&self.error) + } +} + +/// Pure: an analyzer error as a person reads it. +pub fn analysis_reason(error: &str) -> String { + let e = error.trim(); + if e.contains("AssumeRole") && e.contains("permissions boundary") { + return "this install's permissions boundary stops CoderHelm from reading your AWS logs \ + through the log reader role (fixed by updating CoderHelm)" + .into(); + } + if e.contains("AssumeRole") && (e.contains("AccessDenied") || e.contains("not authorized")) { + return "CoderHelm can't use the log reader role to read your AWS logs (access denied); \ + check the role's trust policy and external id" + .into(); + } + if e.is_empty() { + return "the last check of your AWS logs failed".into(); + } + let first = e.lines().next().unwrap_or(e); + let mut out: String = first.chars().take(160).collect(); + if first.chars().count() > 160 { + out.push_str("..."); + } + out +} + +/// When an open finding resolves on its own, as the page can promise it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(tag = "state", rename_all = "snake_case")] +pub enum ResolveState { + /// Quiet until `at`; resolves then unless seen again. + Scheduled { at: String }, + /// Its quiet period has ended: the next analyzer run resolves it + /// (within [`ANALYSIS_EVERY_HOURS`]). + Due { at: String }, + /// Its quiet period has ended, but the analyzer has failed since + /// `analysis_ok_at` (empty: never worked), so nothing can resolve it + /// until that is fixed. + Blocked { + at: String, + analysis_ok_at: String, + reason: String, + }, +} + +/// Pure: what the page says about an open finding's resolve date. A date +/// that has passed is never shown as a promise. +pub fn resolve_state( + f: &Finding, + analysis: Option<&Analysis>, + now: DateTime, +) -> Option { + let at = f.resolves_at()?; + let when = parse_time(&at)?; + if when > now { + return Some(ResolveState::Scheduled { at }); + } + match analysis.filter(|a| a.failing()) { + Some(a) => Some(ResolveState::Blocked { + at, + analysis_ok_at: a.last_ok_at.clone(), + reason: a.reason(), + }), + None => Some(ResolveState::Due { at }), + } +} + /// Pure: the ticket id of fix runs for a fingerprint (stable across findings). pub fn ticket_id(fingerprint: &str) -> String { format!( @@ -1670,10 +1837,12 @@ mod tests { last_seen_at: "2026-10-31T03:38:10Z".into(), ..Default::default() }; - // An older item without a quiet period gets the analyzer's default. + // A burst that stopped (no history) gets the analyzer's default. assert_eq!(f.quiet_days(), DEFAULT_QUIET_DAYS); assert_eq!(f.resolves_at().as_deref(), Some("2026-11-03T03:38:10Z")); - f.quiet_days = Some(8); + // Back 4 days after it was resolved: twice that. + f.last_resolved_at = "2026-10-27T03:48:40.472966+00:00".into(); + f.reopened_at = "2026-10-31T03:48:51.255562+00:00".into(); assert_eq!(f.resolves_at().as_deref(), Some("2026-11-08T03:38:10Z")); f.status = "resolved".into(); assert_eq!(f.resolves_at(), None); @@ -1684,6 +1853,163 @@ mod tests { use super::*; use std::sync::Mutex; + /// The incident: resolved after its first burst, back 4 days later, + /// acknowledged, then quiet. The stored item has no `quiet_days` (the + /// analyzer couldn't run to write one), and the analyzer has failed every + /// run since. + fn came_back_and_acknowledged() -> Finding { + Finding { + status: "pending".into(), + acknowledged_at: "2026-11-03T06:44:39.346874173+00:00".into(), + last_seen_at: "2026-10-31T03:38:10.248+00:00".into(), + last_resolved_at: "2026-10-27T03:48:40.472966+00:00".into(), + reopened_at: "2026-10-31T03:48:51.255562+00:00".into(), + reopen_count: 1, + daily_lines: vec![Counted { + name: "2026-10-31".into(), + lines: 6296, + }], + ..Default::default() + } + } + + fn at(t: &str) -> DateTime { + DateTime::parse_from_rfc3339(t).unwrap().with_timezone(&Utc) + } + + #[test] + fn the_quiet_period_matches_the_analyzer_on_every_shared_case() { + // lambda/tests/test_log_dedup.py runs the same cases against the + // analyzer's quiet_days_for, so the page's date is the sweep's. + let raw = include_str!("../tests/fixtures/quiet_days_cases.json"); + let doc: serde_json::Value = serde_json::from_str(raw).unwrap(); + let cases = doc["cases"].as_array().unwrap(); + assert!(cases.len() > 5); + for c in cases { + let daily: Vec = c["daily_lines"] + .as_array() + .unwrap() + .iter() + .map(|d| Counted { + name: d["day"].as_str().unwrap().into(), + lines: d["lines"].as_u64().unwrap(), + }) + .collect(); + let got = quiet_days_for( + &daily, + c["last_resolved_at"].as_str().unwrap(), + c["reopened_at"].as_str().unwrap(), + ); + assert_eq!(got, c["quiet_days"].as_u64().unwrap(), "{}", c["name"]); + } + } + + #[test] + fn a_stale_stored_quiet_period_never_moves_the_date() { + // The page used the stored value (missing: 3 days, Nov 3) while the + // sweep used 8 (Nov 8). Now both work it out the same way. + let mut f = came_back_and_acknowledged(); + assert_eq!(f.quiet_days(), 8); + f.quiet_days = Some(3); + assert_eq!(f.quiet_days(), 8); + assert_eq!(f.resolves_at().as_deref(), Some("2026-11-08T03:38:10Z")); + } + + #[test] + fn a_resolve_date_still_ahead_is_a_plain_date() { + let f = came_back_and_acknowledged(); + let ok = Analysis { + last_ok_at: "2026-11-07T15:26:49Z".into(), + ..Default::default() + }; + assert_eq!( + resolve_state(&f, Some(&ok), at("2026-11-07T16:00:00Z")), + Some(ResolveState::Scheduled { + at: "2026-11-08T03:38:10Z".into() + }) + ); + } + + #[test] + fn a_passed_date_with_analysis_failing_says_why_it_has_not_resolved() { + let f = came_back_and_acknowledged(); + let failing = Analysis { + last_ok_at: "2026-11-02T21:48:40.182316+00:00".into(), + error: "An error occurred (AccessDenied) when calling the AssumeRole operation: User: \ + arn:aws:sts::111122223333:assumed-role/x/coderhelm-prod-log-analyzer is not \ + authorized to perform: sts:AssumeRole on resource: \ + arn:aws:iam::111122223333:role/CoderHelmLogReader with an explicit deny in a \ + permissions boundary: arn:aws:iam::111122223333:policy/coderhelm-prod-boundary-stack" + .into(), + error_at: "2026-11-09T09:26:49.056528+00:00".into(), + }; + assert!(failing.failing()); + match resolve_state(&f, Some(&failing), at("2026-11-09T10:00:00Z")) { + Some(ResolveState::Blocked { + at, + analysis_ok_at, + reason, + }) => { + assert_eq!(at, "2026-11-08T03:38:10Z"); + assert_eq!(analysis_ok_at, "2026-11-02T21:48:40.182316+00:00"); + assert!(reason.contains("permissions boundary"), "{reason}"); + assert!(!reason.contains("arn:aws"), "{reason}"); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn a_passed_date_with_analysis_working_resolves_at_the_next_run() { + let f = came_back_and_acknowledged(); + // An error from before the last run that worked is history, not a failure. + let recovered = Analysis { + last_ok_at: "2026-11-09T09:26:49Z".into(), + error: "AccessDenied".into(), + error_at: "2026-11-09T03:26:49Z".into(), + }; + assert!(!recovered.failing()); + assert_eq!( + resolve_state(&f, Some(&recovered), at("2026-11-09T10:00:00Z")), + Some(ResolveState::Due { + at: "2026-11-08T03:38:10Z".into() + }) + ); + // No connection item at all: the next run decides. + assert_eq!( + resolve_state(&f, None, at("2026-11-09T10:00:00Z")), + Some(ResolveState::Due { + at: "2026-11-08T03:38:10Z".into() + }) + ); + } + + #[test] + fn a_finding_that_is_not_open_has_no_resolve_state() { + let mut f = came_back_and_acknowledged(); + f.status = "resolved".into(); + assert_eq!(resolve_state(&f, None, at("2026-11-09T10:00:00Z")), None); + } + + #[test] + fn analysis_errors_read_in_plain_words() { + assert!(analysis_reason("An error occurred (AccessDenied) when calling the AssumeRole operation: not authorized") + .contains("can't use the log reader role")); + assert_eq!(analysis_reason(""), "the last check of your AWS logs failed"); + let long = "x".repeat(400); + assert!(analysis_reason(&long).chars().count() <= 163); + assert_eq!(analysis_reason("Throttled\ntraceback..."), "Throttled"); + } + + #[test] + fn the_analyzer_and_gateway_time_formats_both_parse() { + assert!(parse_time("2026-10-25 14:03:11.123").is_some()); + assert!(parse_time("2026-11-03T06:44:39.346874173+00:00").is_some()); + assert!(parse_time("2026-10-31T03:38:10Z").is_some()); + assert!(parse_time("").is_none()); + assert!(parse_time("soon").is_none()); + } + const TEAM: &str = "TEAM#acme"; fn t(s: &str) -> DateTime { diff --git a/services/common/tests/fixtures/quiet_days_cases.json b/services/common/tests/fixtures/quiet_days_cases.json new file mode 100644 index 000000000..7fa58ddc2 --- /dev/null +++ b/services/common/tests/fixtures/quiet_days_cases.json @@ -0,0 +1,15 @@ +{ + "about": "How long a log finding must be quiet before it resolves. lambda/log-analyzer/lifecycle.py quiet_days_for (the resolve sweep) and services/common/src/log_findings.rs quiet_days_for (the date the page shows) both run every case, so the page never promises a date the sweep won't use.", + "cases": [ + { "name": "no history: a burst that stopped", "daily_lines": [], "last_resolved_at": "", "reopened_at": "", "quiet_days": 3 }, + { "name": "one run of consecutive days", "daily_lines": [{ "day": "2026-10-01", "lines": 40 }, { "day": "2026-10-02", "lines": 9 }, { "day": "2026-10-03", "lines": 1 }], "last_resolved_at": "", "reopened_at": "", "quiet_days": 3 }, + { "name": "back every 4 days", "daily_lines": [{ "day": "2026-10-01", "lines": 5 }, { "day": "2026-10-05", "lines": 5 }, { "day": "2026-10-09", "lines": 5 }], "last_resolved_at": "", "reopened_at": "", "quiet_days": 8 }, + { "name": "days without lines are no sighting", "daily_lines": [{ "day": "2026-10-01", "lines": 5 }, { "day": "2026-10-03", "lines": 0 }, { "day": "2026-10-02", "lines": 2 }], "last_resolved_at": "", "reopened_at": "", "quiet_days": 3 }, + { "name": "resolved, then back 4 days later (one day of history)", "daily_lines": [{ "day": "2026-10-31", "lines": 6296 }], "last_resolved_at": "2026-10-27T03:48:40.472966+00:00", "reopened_at": "2026-10-31T03:48:51.255562+00:00", "quiet_days": 8 }, + { "name": "back the same day it resolved", "daily_lines": [], "last_resolved_at": "2026-10-27T03:00:00+00:00", "reopened_at": "2026-10-27T10:00:00+00:00", "quiet_days": 2 }, + { "name": "a half day rounds to even", "daily_lines": [], "last_resolved_at": "2026-10-20T00:00:00+00:00", "reopened_at": "2026-10-22T12:00:00+00:00", "quiet_days": 4 }, + { "name": "reopen time before the resolve is ignored", "daily_lines": [], "last_resolved_at": "2026-10-27T03:00:00+00:00", "reopened_at": "2026-10-20T03:00:00+00:00", "quiet_days": 3 }, + { "name": "a rare error is capped", "daily_lines": [{ "day": "2026-09-01", "lines": 1 }, { "day": "2026-09-21", "lines": 1 }], "last_resolved_at": "", "reopened_at": "", "quiet_days": 14 }, + { "name": "Z and nanosecond times", "daily_lines": [], "last_resolved_at": "2026-10-27T03:48:40Z", "reopened_at": "2026-11-02T03:48:40.123456789Z", "quiet_days": 12 } + ] +} diff --git a/services/gateway/src/routes/log_findings.rs b/services/gateway/src/routes/log_findings.rs index 4fbb293a2..3b901d208 100644 --- a/services/gateway/src/routes/log_findings.rs +++ b/services/gateway/src/routes/log_findings.rs @@ -62,8 +62,15 @@ fn role(claims: &Claims, level: u8) -> Result<(), Reply> { .map_err(|c| fail(c, "forbidden", "Your role can't do this.")) } -/// `account → region` of the team's AWS connections. -async fn connections(state: &AppState, team_id: &str) -> Result, Reply> { +/// One AWS connection as the findings page needs it: its region, and how the +/// log analyzer is doing there. +struct Conn { + region: String, + analysis: lf::Analysis, +} + +/// `account → connection` of the team's AWS connections. +async fn connections(state: &AppState, team_id: &str) -> Result, Reply> { let out = state .dynamo .query() @@ -84,7 +91,13 @@ async fn connections(state: &AppState, team_id: &str) -> Result>(), }))) } From 54377be25d645ed5b3c71e19606d432e52dedc73 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sat, 7 Nov 2026 13:08:50 -0500 Subject: [PATCH 2/2] Format the analysis reason test --- services/common/src/log_findings.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/common/src/log_findings.rs b/services/common/src/log_findings.rs index f7686157e..9db8f6cc8 100644 --- a/services/common/src/log_findings.rs +++ b/services/common/src/log_findings.rs @@ -1995,7 +1995,10 @@ mod tests { fn analysis_errors_read_in_plain_words() { assert!(analysis_reason("An error occurred (AccessDenied) when calling the AssumeRole operation: not authorized") .contains("can't use the log reader role")); - assert_eq!(analysis_reason(""), "the last check of your AWS logs failed"); + assert_eq!( + analysis_reason(""), + "the last check of your AWS logs failed" + ); let long = "x".repeat(400); assert!(analysis_reason(&long).chars().count() <= 163); assert_eq!(analysis_reason("Throttled\ntraceback..."), "Throttled");