From 8b8ca42e0d97442af84e575551af7142dce77e99 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 10 Nov 2026 12:01:57 -0500 Subject: [PATCH 1/3] Fix Security Hub findings at the source of every install The chat stream's function URL takes only calls CloudFront signs (AWS_IAM and origin access control) on a single-origin install; the gateway reads the stream token from x-coderhelm-stream-token, else a bearer token. Every bucket is TLS-only with a lifecycle, and the data, dashboard and sandbox buckets and the distribution write access logs to a new log bucket. Every table has point-in-time recovery and deletion protection, the user pool has deletion protection and a password policy that needs a symbol, the MCP proxy runs on Node.js 22, SES sends only over TLS, and viewers on a domain need TLSv1.2_2025. docs/self-host/security.md lists each control and the ones accepted, with why. --- docs/self-host/security.md | 49 +++++- docs/self-host/uninstall.md | 1 + infra/lib/api-stack.ts | 10 +- infra/lib/app.ts | 5 + infra/lib/config.ts | 3 + infra/lib/database-stack.ts | 27 +++- infra/lib/email-stack.ts | 2 + infra/lib/mail-relay.ts | 2 + infra/lib/native/parent.ts | 15 +- infra/lib/storage-stack.ts | 74 +++++++++ infra/lib/streaming-stack.ts | 8 +- infra/lib/web-stack.ts | 42 ++++- infra/lib/worker-stack.ts | 5 +- infra/test/hybrid.test.ts | 3 +- infra/test/security-hub.test.ts | 228 +++++++++++++++++++++++++++ installer/lib/uninstall.mjs | 2 +- lambda/mcp-proxy/package.json | 2 +- services/gateway/src/auth/jwt.rs | 55 +++++++ services/gateway/src/routes/auth.rs | 22 ++- services/gateway/src/routes/brain.rs | 5 +- services/gateway/src/routes/plans.rs | 14 +- 21 files changed, 537 insertions(+), 37 deletions(-) create mode 100644 infra/test/security-hub.test.ts diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 7a5b5ffb9..2d1e48c91 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -15,8 +15,8 @@ order: 11 | From | To | How | |---|---|---| -| People | CloudFront (your hostname) | HTTPS only, TLS 1.2+, HSTS | -| CloudFront | HTTP API, streaming function URL, dashboard bucket | HTTPS; the bucket is private and only CloudFront can read it | +| People | CloudFront (your hostname) | HTTPS only, TLS 1.2+ (CloudFront's `TLSv1.2_2025` policy on your own domain), HSTS | +| CloudFront | HTTP API, streaming function URL, dashboard bucket | HTTPS; the bucket is private and only CloudFront can read it; the streaming function URL takes only calls CloudFront signs (origin access control) | | GitHub, Jira | `/webhooks/*` | Signed payloads, checked before use | | Functions | GitHub, Anthropic, Bedrock, the services teams connect | HTTPS from Lambda (no VPC) | @@ -276,6 +276,51 @@ CoderHelm **cannot** see: your code at rest, your runs, plans, reviews, memory, - Messages from CoderHelm carry CoderHelm's own signature (Ed25519, key in AWS KMS), checked with public keys pinned in your signed release once a release pins them: a leaked relay key alone can't make an install accept a message. See hybrid.md, "How an install knows a message is from CoderHelm". The answers of the OAuth sign-in broker (Notion and the other OAuth integrations) are not signed yet; HTTPS and the install's client secret protect them. - Install requests carry no one-time number, so someone who could break HTTPS could repeat one within its 5 minutes. They would already see the same traffic, tokens included. +## Security Hub + +AWS Security Hub checks an install against AWS's best practices. This is what each check finds on an install, and why. + +### What an install sets + +| Control | What the stacks set | +|---|---| +| Lambda.1, CloudFront.16 | The chat stream's function URL takes only calls signed with AWS credentials (`AWS_IAM`), and only the install's CloudFront may call it: origin access control signs every request, and the function's policy allows `cloudfront.amazonaws.com` for that one distribution. The function still checks the person's short-lived stream token on every request. Because CloudFront's signature is the `Authorization` header, the dashboard sends the token in `x-coderhelm-stream-token`, and sends the body's SHA-256 in `x-amz-content-sha256`, which Lambda requires of a signed POST. Responses still stream. | +| S3.5 | Every bucket refuses requests without TLS, the release bucket included. | +| S3.9 | The data, dashboard and sandbox buckets write server access logs to the install's log bucket, `coderhelm--logs-`, under `s3//`. | +| S3.13 | Every bucket has a lifecycle: access logs expire after 90 days, sandbox tarballs after a day, old versions of data after 30 days, and unfinished uploads after a day. | +| CloudFront.5 | The distribution writes standard logs to the log bucket, under `cloudfront/`. | +| CloudFront.15 | On your own domain, viewers need TLS 1.2 with modern ciphers, or TLS 1.3 (`TLSv1.2_2025`). | +| DynamoDB.2, DynamoDB.6 | Every table has point-in-time recovery and deletion protection. On a Launch Stack install, deletion protection follows **KeepDataOnDelete**, so an uninstall that deletes the data can delete the tables. | +| Cognito.3, Cognito.6 | Passwords need 8 characters with an upper-case and a lower-case letter, a digit and a symbol. Temporary passwords last 7 days. The user pool has deletion protection, which follows **KeepDataOnDelete** like the tables. | +| Lambda.2 | Every function runs on a supported runtime (the MCP proxy on Node.js 22). | +| SES.3 | The install's SES configuration set sends only over TLS: a receiving server that can't do TLS gets no mail. | + +The log bucket uses SSE-S3 and has ACLs enabled with the bucket owner preferred: S3 log delivery can't write to an SSE-KMS bucket, and CloudFront's standard logging writes with an ACL. The install still owns every object, and the bucket blocks all public access. It is deleted with the stack: writes are refused first, then it is emptied. + +### Accepted, and why + +Mark these as accepted in Security Hub (workflow status **Suppressed**, with the reason below). + +| Control | Resource | Why it stays | +|---|---|---| +| APIGateway.9 | The HTTP API's `$default` stage | Every request to the API comes through the install's CloudFront, whose standard logs record each one (CloudFront.5). Access logs on the stage itself need `logs:CreateLogDelivery` and `logs:PutResourcePolicy` on all resources, which the install's deploy role deliberately doesn't have, so an update could never turn them on. | +| CloudFront.4 | The distribution | Origin failover needs a second copy of each origin in another region. The API and the functions run in one region, and failover covers only GET, HEAD and OPTIONS. | +| CloudFront.6 | The distribution | AWS WAF is billed per web ACL, per rule and per request, and the boundary doesn't let an install create one. Every API route checks a session, a signed webhook or a stream token, and the HTTP API throttles each stage. Attach your own web ACL to the distribution if your account requires one. | +| CloudFront.17 | The distribution | Trusted key groups are for signed URLs and cookies. CoderHelm serves nothing private through CloudFront that way: the dashboard is public static files, and everything else checks its own session or signature. | +| CloudFront.15 | A distribution without your own domain | CloudFront's default certificate (`*.cloudfront.net`) allows only its own TLS policy. Add your own domain to get `TLSv1.2_2025`. | +| S3.15 | Every bucket | Object Lock would stop CoderHelm deleting what it must: data a team removes, a release's old files, the sandbox's tarballs, the dashboard's old build, and everything on uninstall with **KeepDataOnDelete** `false`. | +| S3.17 | The dashboard, release, sandbox and log buckets | They use SSE-S3 on purpose. The dashboard is public static files that CloudFront reads; the release bucket holds the signed release's public files, each checked against its sha256; the sandbox holds tarballs that live for a day; S3 log delivery can't write to an SSE-KMS bucket. The data bucket uses the install's KMS key. | +| S3.20 | Every bucket | Only the account's root user can turn on MFA delete, from the CLI with the root user's MFA device. A template can't. | +| S3.9 | The release bucket and the log bucket | The release bucket is made before every other part (it holds their templates), so before the log bucket exists. Only the install helper may write to it (its bucket policy), and CloudTrail records each write. A log bucket that logged to itself would log forever. | +| Cognito.1, Cognito.4 | The user pool | Threat protection needs Cognito's Plus tier, billed for every monthly active user. The gateway rate-limits sign-in attempts itself. Turn it on in the console if your account requires it. | +| Cognito.5 | The user pool | Two-factor is optional, with an authenticator app. An admin can require it for everyone (the **RequireTwoFactor** launch parameter, or **Settings, Sign-in**), and CoderHelm enforces that at sign-in. Requiring it in Cognito would force it on every install, including those that chose not to. | +| KMS.2 | The roles `coderhelm--deploy-stack` and `coderhelm--install-helper` | Both allow `kms:Decrypt` only on keys tagged `coderhelm:install = coderhelm-` (the install's own keys), but Security Hub reads only the resource, not the condition. The deploy role creates those keys, so their ids can't be known when its policy is written, and no update can change that role (see [Updates and the deploy role](#updates-and-the-deploy-role)). The helper is made before the part that makes the keys, for the same reason. | +| SecretsManager.1 | `coderhelm//secrets` | It holds the GitHub App's keys, which only GitHub can issue, and the session signing key: rotating that key signs everyone out. | +| SecretsManager.1 | `coderhelm-readonly-*` | You create these for a data source: a read-only database user of yours. Rotate them with your database's own rotation. | +| CloudFormation.3 | `coderhelm-`, `coderhelm--access`, `CoderHelmLogReader*` | Uninstalling is deleting the stack. To protect it, turn termination protection on: `aws cloudformation update-termination-protection --enable-termination-protection --stack-name coderhelm-`. Updates still apply. Turn it off with `--no-enable-termination-protection` before you uninstall. | +| CloudFormation.4 | `coderhelm--access`, `CoderHelmLogReader*` | An AWS admin creates these with their own permissions, because they write IAM roles and policies. A service role would need the same IAM permissions. The main stack `coderhelm-` has its service role, the deploy role. | +| KMS.3 | Keys of an install already uninstalled | An uninstall with **KeepDataOnDelete** `false` schedules the install's keys for deletion after 7 days, on purpose. The finding goes away when they are deleted. | + ## Reporting a problem Report security issues privately, never in a public issue: email [support@coderhelm.com](mailto:support@coderhelm.com?subject=Security%20report) with "Security report" in the subject. The [Security](https://docs.coderhelm.com/security/) page says what to include. diff --git a/docs/self-host/uninstall.md b/docs/self-host/uninstall.md index 755caf93f..9eeed9d82 100644 --- a/docs/self-host/uninstall.md +++ b/docs/self-host/uninstall.md @@ -35,6 +35,7 @@ The stack parameter **KeepDataOnDelete** does the same from AWS. It is `true` un | CoderHelm's functions, roles, queues, API, CloudFront, dashboard, schedules, alarms, the permissions boundary, the install helper | deleted | deleted | | The release bucket (`coderhelm--release-`) and the install guide's progress bucket | emptied and deleted | emptied and deleted | | Log groups the stack declares (every function's) | deleted | deleted | +| The access log bucket (`coderhelm--logs-`: S3 and CloudFront access logs, 90 days) | writes stopped, emptied and deleted | writes stopped, emptied and deleted | | Certificates the updater requested for your own domain | deleted | deleted | | DNS records you added for the domain (the certificate's validation CNAME and the address CNAME) | kept: CoderHelm never changes your DNS. The uninstall's log names them so you can remove them | kept, the same | | DynamoDB tables | kept | deleted | diff --git a/infra/lib/api-stack.ts b/infra/lib/api-stack.ts index 84163fa54..f53e0c31a 100644 --- a/infra/lib/api-stack.ts +++ b/infra/lib/api-stack.ts @@ -88,7 +88,9 @@ export class ApiStack extends cdk.Stack { requireUppercase: true, requireLowercase: true, requireDigits: true, - requireSymbols: false, + // The gateway checks the same before it calls Cognito (routes/auth.rs password_fits). + requireSymbols: true, + tempPasswordValidity: cdk.Duration.days(7), }, mfa: cognito.Mfa.OPTIONAL, mfaSecondFactor: { sms: false, otp: true }, @@ -105,6 +107,10 @@ export class ApiStack extends cdk.Stack { : {}), }) : cognito.UserPoolEmail.withCognito(), + // Deleting the pool takes turning this off first: the uninstaller and a + // native install's helper do (KeepDataOnDelete=false); a native install + // follows KeepDataOnDelete (native/package.ts). + deletionProtection: cfg.retainData, removalPolicy: cfg.retainData ? cdk.RemovalPolicy.RETAIN : cdk.RemovalPolicy.DESTROY, @@ -802,7 +808,7 @@ export class ApiStack extends cdk.Stack { this.mcpProxyFunction = new lambda.Function(this, "McpProxy", { functionName: `${prefix}-mcp-proxy`, - runtime: lambda.Runtime.NODEJS_20_X, + runtime: lambda.Runtime.NODEJS_22_X, architecture: lambda.Architecture.ARM_64, handler: "handler.handler", // MCP_PROXY_DIR: a prebuilt proxy (release artifact) instead of a local build. diff --git a/infra/lib/app.ts b/infra/lib/app.ts index b83a6b065..4bdb1b979 100644 --- a/infra/lib/app.ts +++ b/infra/lib/app.ts @@ -79,6 +79,9 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig, opts: { accessStack? : undefined, }); + // The sandbox bucket logs into the storage stack's log bucket (by name). + worker.addDependency(storage); + // --- Streaming (SSE via Lambda Function URL + Web Adapter) --- // Created before email and log analyzer so a single-origin web stack can // sit between them (those two link to the dashboard URL it creates). @@ -110,6 +113,8 @@ export function buildApp(app: cdk.App, cfg: ResolvedConfig, opts: { accessStack? streamingFunctionUrl: streaming.functionUrl, crossRegionReferences: false, }); + // Its dashboard bucket and distribution log into the storage stack's log bucket (by name). + web.addDependency(storage); } /** The dashboard's URL: static when known, else the web stack's CloudFront URL. */ diff --git a/infra/lib/config.ts b/infra/lib/config.ts index 614631765..7f5adaca1 100644 --- a/infra/lib/config.ts +++ b/infra/lib/config.ts @@ -339,6 +339,8 @@ export interface ResolvedConfig { /** Data bucket name. */ dataBucketName: string; sandboxBucketName: string; + /** The access log bucket: S3 server access logs and CloudFront's logs (storage-stack.ts). */ + logBucketName: string; cognitoDomainPrefix: string; /** * A native release (infra/lib/native): one set of templates for every @@ -742,6 +744,7 @@ export function resolveConfig(cfg: CoderhelmConfig, opts: { skipValidation?: boo : null, dataBucketName: `${prefix}-data${suffix}`, sandboxBucketName: `${prefix}-sandbox${suffix}`, + logBucketName: `${prefix}-logs${suffix}`, cognitoDomainPrefix: `${prefix}${suffix}`, }; } diff --git a/infra/lib/database-stack.ts b/infra/lib/database-stack.ts index 2213d29be..ce907f376 100644 --- a/infra/lib/database-stack.ts +++ b/infra/lib/database-stack.ts @@ -467,6 +467,9 @@ export class DatabaseStack extends cdk.Stack { encryption: dynamodb.TableEncryptionV2.customerManagedKey( this.encryptionKey ), + pointInTimeRecoverySpecification: { + pointInTimeRecoveryEnabled: true, + }, deletionProtection: isProd, removalPolicy: isProd ? cdk.RemovalPolicy.RETAIN @@ -529,7 +532,15 @@ export class DatabaseStack extends cdk.Stack { encryption: dynamodb.TableEncryptionV2.customerManagedKey( this.encryptionKey ), - removalPolicy: cdk.RemovalPolicy.DESTROY, + pointInTimeRecoverySpecification: { + pointInTimeRecoveryEnabled: true, + }, + // Run history: deleting it is a person's choice (KeepDataOnDelete + // on a native install, retainData otherwise), like every other table. + deletionProtection: isProd, + removalPolicy: isProd + ? cdk.RemovalPolicy.RETAIN + : cdk.RemovalPolicy.DESTROY, timeToLiveAttribute: "ttl", }); @@ -546,7 +557,15 @@ export class DatabaseStack extends cdk.Stack { encryption: dynamodb.TableEncryptionV2.customerManagedKey( this.encryptionKey ), - removalPolicy: cdk.RemovalPolicy.DESTROY, + pointInTimeRecoverySpecification: { + pointInTimeRecoveryEnabled: true, + }, + // Run history: deleting it is a person's choice (KeepDataOnDelete + // on a native install, retainData otherwise), like every other table. + deletionProtection: isProd, + removalPolicy: isProd + ? cdk.RemovalPolicy.RETAIN + : cdk.RemovalPolicy.DESTROY, timeToLiveAttribute: "ttl", }); @@ -596,6 +615,10 @@ export class DatabaseStack extends cdk.Stack { partitionKey: { name: "pk", type: dynamodb.AttributeType.STRING }, sortKey: { name: "sk", type: dynamodb.AttributeType.STRING }, billing: dynamodb.Billing.onDemand(), + pointInTimeRecoverySpecification: { + pointInTimeRecoveryEnabled: true, + }, + deletionProtection: isProd, removalPolicy: cdk.RemovalPolicy.RETAIN, }); new cdk.CfnOutput(this, "BillingTableName", { diff --git a/infra/lib/email-stack.ts b/infra/lib/email-stack.ts index 8b18142c8..0577c0d51 100644 --- a/infra/lib/email-stack.ts +++ b/infra/lib/email-stack.ts @@ -40,6 +40,8 @@ export class EmailStack extends cdk.Stack { configurationSetName: `${prefix}-emails`, reputationMetrics: true, sendingEnabled: true, + // Never in the clear: a receiving server without TLS gets no mail. + tlsPolicy: ses.ConfigurationSetTlsPolicy.REQUIRE, }); // A self-hosted install counts its own email by kind (Deliveries): every // send, delivery, bounce, complaint and rejection goes to its worker diff --git a/infra/lib/mail-relay.ts b/infra/lib/mail-relay.ts index 5700ace3d..40035d617 100644 --- a/infra/lib/mail-relay.ts +++ b/infra/lib/mail-relay.ts @@ -88,6 +88,8 @@ export class MailRelay extends Construct { reputationMetrics: true, sendingEnabled: true, suppressionReasons: ses.SuppressionReasons.BOUNCES_AND_COMPLAINTS, + // Never in the clear: a receiving server without TLS gets no mail. + tlsPolicy: ses.ConfigurationSetTlsPolicy.REQUIRE, }); configSet.addEventDestination("BouncesAndComplaints", { destination: ses.EventDestination.snsTopic(this.topic), diff --git a/infra/lib/native/parent.ts b/infra/lib/native/parent.ts index 272f52b40..3074e16f5 100644 --- a/infra/lib/native/parent.ts +++ b/infra/lib/native/parent.ts @@ -323,9 +323,16 @@ export function buildParent(input: ParentInput): Json { R.DeployBoundary = pinned.DeployBoundary; R.AssetsBucket = { Type: "AWS::S3::Bucket", - Properties: { BucketName: sub(ASSETS_BUCKET_NAME), ...s3Secure, Tags: [{ Key: INSTALL_TAG, Value: sub("coderhelm-${Stage}") }] }, + Properties: { + BucketName: sub(ASSETS_BUCKET_NAME), + ...s3Secure, + // The helper copies each file whole; nothing should keep half an upload. + LifecycleConfiguration: { Rules: [{ Id: "abort-uploads", Status: "Enabled", AbortIncompleteMultipartUpload: { DaysAfterInitiation: 1 } }] }, + Tags: [{ Key: INSTALL_TAG, Value: sub("coderhelm-${Stage}") }], + }, }; - // Only the helper may write or delete the release files (it checks each one). + // Only the helper may write or delete the release files (it checks each one), + // and only over TLS. R.AssetsBucketPolicy = { Type: "AWS::S3::BucketPolicy", Properties: { @@ -337,6 +344,10 @@ export function buildParent(input: ParentInput): Json { Action: ["s3:PutObject", "s3:DeleteObject", "s3:DeleteObjectVersion", "s3:PutObjectAcl"], Resource: { "Fn::Sub": "${AssetsBucket.Arn}/*" }, Condition: { ArnNotEquals: { "aws:PrincipalArn": { "Fn::GetAtt": ["HelperRole", "Arn"] } } }, + }, { + Sid: "TlsOnly", Effect: "Deny", Principal: "*", Action: "s3:*", + Resource: [{ "Fn::GetAtt": ["AssetsBucket", "Arn"] }, { "Fn::Sub": "${AssetsBucket.Arn}/*" }], + Condition: { Bool: { "aws:SecureTransport": "false" } }, }], }, }, diff --git a/infra/lib/storage-stack.ts b/infra/lib/storage-stack.ts index c2b615e30..e15166b02 100644 --- a/infra/lib/storage-stack.ts +++ b/infra/lib/storage-stack.ts @@ -1,6 +1,7 @@ import * as cdk from "aws-cdk-lib"; import * as s3 from "aws-cdk-lib/aws-s3"; import * as kms from "aws-cdk-lib/aws-kms"; +import * as iam from "aws-cdk-lib/aws-iam"; import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { hostedKeyPolicy, KEY_PENDING_WINDOW } from "./key-policy"; @@ -10,12 +11,81 @@ interface StorageStackProps extends cdk.StackProps { cfg: ResolvedConfig; } +/** How long access logs are kept. */ +export const ACCESS_LOG_DAYS = 90; + +/** + * The install's access log bucket, by name: the stacks that log into it + * (web, worker) depend on the storage stack instead of importing it, so no + * export ties them together. + */ +export function logBucketOf(scope: Construct, cfg: ResolvedConfig): s3.IBucket { + return s3.Bucket.fromBucketAttributes(scope, "AccessLogBucket", { + bucketName: cfg.logBucketName, + // CloudFront's standard logging names its bucket this way (bucket.s3.amazonaws.com). + bucketRegionalDomainName: `${cfg.logBucketName}.s3.${cdk.Aws.URL_SUFFIX}`, + }); +} + +/** + * Turns on S3 server access logging for `bucket`, into the install's log + * bucket under `s3//`. Set on the bucket itself (not CDK's + * serverAccessLogsBucket, which would grant log delivery with an ACL): the + * log bucket's policy lets S3's log delivery write for this install's buckets. + */ +export function logAccessTo(bucket: s3.Bucket, cfg: ResolvedConfig, name: string): void { + (bucket.node.defaultChild as s3.CfnBucket).loggingConfiguration = { + destinationBucketName: cfg.logBucketName, + logFilePrefix: `s3/${name}/`, + }; +} + export class StorageStack extends cdk.Stack { public readonly bucket: s3.Bucket; + /** Where the install's buckets and its CloudFront distribution write their access logs. */ + public readonly logBucket: s3.Bucket; constructor(scope: Construct, id: string, props: StorageStackProps) { super(scope, id, props); + // Access logs: S3 server access logs of the install's buckets (s3//) + // and the web distribution's standard logs (cloudfront/). SSE-S3, since + // log delivery can't write to an SSE-KMS bucket; ACLs on, since + // CloudFront's standard logging writes with one (BucketOwnerPreferred: + // the install owns every object). Logs are operational, not data: the + // bucket goes with the stack, writes denied first and then emptied + // (autoDeleteObjects), so a late log delivery can't stop the delete. + this.logBucket = new s3.Bucket(this, "LogBucket", { + bucketName: props.cfg.logBucketName, + encryption: s3.BucketEncryption.S3_MANAGED, + blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, + objectOwnership: s3.ObjectOwnership.BUCKET_OWNER_PREFERRED, + enforceSSL: true, + removalPolicy: cdk.RemovalPolicy.DESTROY, + autoDeleteObjects: true, + lifecycleRules: [ + { + id: "expire-access-logs", + expiration: cdk.Duration.days(ACCESS_LOG_DAYS), + abortIncompleteMultipartUploadAfter: cdk.Duration.days(1), + }, + ], + }); + // S3 log delivery for this install's own buckets only (the other stacks + // name the bucket rather than import it, so CDK can't add this for them). + this.logBucket.addToResourcePolicy( + new iam.PolicyStatement({ + sid: "S3ServerAccessLogsFromThisInstall", + principals: [new iam.ServicePrincipal("logging.s3.amazonaws.com")], + actions: ["s3:PutObject"], + resources: [this.logBucket.arnForObjects("s3/*")], + conditions: { + StringEquals: { "aws:SourceAccount": this.account }, + ArnLike: { "aws:SourceArn": `arn:${this.partition}:s3:::${props.cfg.prefix}-*` }, + }, + }) + ); + const encryptionKey = new kms.Key(this, "BucketKey", { alias: `${props.cfg.prefix}-s3`, description: "Coderhelm S3 encryption key", @@ -75,6 +145,10 @@ export class StorageStack extends cdk.Stack { ], }); + logAccessTo(this.bucket, props.cfg, "data"); + this.bucket.node.addDependency(this.logBucket); + new cdk.CfnOutput(this, "BucketName", { value: this.bucket.bucketName }); + new cdk.CfnOutput(this, "LogBucketName", { value: this.logBucket.bucketName }); } } diff --git a/infra/lib/streaming-stack.ts b/infra/lib/streaming-stack.ts index 7baad5615..2fd0fcd72 100644 --- a/infra/lib/streaming-stack.ts +++ b/infra/lib/streaming-stack.ts @@ -185,8 +185,14 @@ export class StreamingStack extends cdk.Stack { // --- Function URL with Response Streaming --- + // Single-origin: the install's CloudFront is the only way in. The URL + // takes only calls signed with AWS credentials, and CloudFront signs each + // one (origin access control, web-stack.ts); the function still checks the + // member's stream token on every request. The split layout (CoderHelm's + // own deployment) answers browsers on the URL itself, so its URL stays + // open and the token is the only check. const functionUrl = this.streamingFunction.addFunctionUrl({ - authType: lambda.FunctionUrlAuthType.NONE, + authType: cfg.layout === "single-origin" ? lambda.FunctionUrlAuthType.AWS_IAM : lambda.FunctionUrlAuthType.NONE, invokeMode: lambda.InvokeMode.RESPONSE_STREAM, // Cross-origin only in the split layout (single-origin forwards the // stream from the dashboard's own hostname). diff --git a/infra/lib/web-stack.ts b/infra/lib/web-stack.ts index 74c6be936..46a862387 100644 --- a/infra/lib/web-stack.ts +++ b/infra/lib/web-stack.ts @@ -4,7 +4,8 @@ * One CloudFront distribution serves the dashboard from S3 and forwards the * service paths to their backends, all on one hostname: * - * /api/plans/chat/stream /api/brain/stream → the streaming function URL (SSE) + * /api/plans/chat/stream /api/brain/stream → the streaming function URL (SSE), + * signed by CloudFront (origin access control; the URL takes only signed calls) * /api/* /auth/* /webhooks/* /email/* /integrations/* /mcp /oauth/* → the HTTP API * everything else → the dashboard (static export in S3) * @@ -29,6 +30,7 @@ import * as ssm from "aws-cdk-lib/aws-ssm"; import { Construct } from "constructs"; import { ResolvedConfig } from "./config"; import { releaseStamp } from "./release"; +import { logAccessTo, logBucketOf } from "./storage-stack"; /** * Paths the HTTP API serves (each also matches its sub-paths). Includes the @@ -56,6 +58,12 @@ export const STREAM_PATH = "/api/plans/chat/stream"; /** Chat's answer stream: answers that read code run past the HTTP API's 30-second limit. */ export const BRAIN_STREAM_PATH = "/api/brain/stream"; +/** + * The lowest TLS version and ciphers viewers may use: CloudFront's newest + * TLS 1.2 policy (TLS 1.2 with AES-GCM and ChaCha20 only, and TLS 1.3). + */ +export const VIEWER_TLS_POLICY = cloudfront.SecurityPolicyProtocol.TLS_V1_2_2025; + /** Hashed build files: cached for a year. */ const ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable"; /** Pages and the runtime config: revalidated on every visit. */ @@ -162,7 +170,10 @@ export class WebStack extends cdk.Stack { // The build is re-uploaded on every deploy, so it never needs keeping. removalPolicy: cdk.RemovalPolicy.DESTROY, autoDeleteObjects: true, + lifecycleRules: [{ id: "abort-uploads", abortIncompleteMultipartUploadAfter: cdk.Duration.days(1) }], }); + // Into the storage stack's log bucket (this stack depends on it: app.ts). + logAccessTo(bucket, cfg, "dashboard"); // --- Certificate and DNS (custom domain only) --- let certificate: acm.ICertificate | undefined; @@ -178,10 +189,13 @@ export class WebStack extends cdk.Stack { protocolPolicy: cloudfront.OriginProtocolPolicy.HTTPS_ONLY, originSslProtocols: [cloudfront.OriginSslPolicy.TLS_V1_2], }); - const streamDomain = cdk.Fn.select(2, cdk.Fn.split("/", props.streamingFunctionUrl.url)); - const streamOrigin = new origins.HttpOrigin(streamDomain, { - protocolPolicy: cloudfront.OriginProtocolPolicy.HTTPS_ONLY, - originSslProtocols: [cloudfront.OriginSslPolicy.TLS_V1_2], + // The chat streams: the function URL takes only calls signed with AWS + // credentials (AWS_IAM, streaming-stack.ts), and CloudFront signs each one + // through origin access control. The dashboard sends the stream token in + // its own header (CloudFront's signature is the Authorization header) and + // the body's SHA-256 in x-amz-content-sha256, which Lambda requires of a + // signed POST. Response streaming passes through as before. + const streamOrigin = origins.FunctionUrlOrigin.withOriginAccessControl(props.streamingFunctionUrl, { readTimeout: cdk.Duration.seconds(60), }); const passThrough: Omit = { @@ -231,7 +245,11 @@ export class WebStack extends cdk.Stack { ...(domain && certificate ? { domainNames: [domain.hostname], certificate } : {}), defaultRootObject: "index.html", httpVersion: cloudfront.HttpVersion.HTTP2_AND_3, - minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021, + minimumProtocolVersion: VIEWER_TLS_POLICY, + // Standard logs, kept 90 days in the storage stack's log bucket. + enableLogging: true, + logBucket: logBucketOf(this, cfg), + logFilePrefix: "cloudfront/", defaultBehavior: { // List too, so a file that isn't there is a 404 (not S3's 403), // which the error response below turns into the install's own page. @@ -257,6 +275,16 @@ export class WebStack extends cdk.Stack { ], }); + // Origin access control signs the stream's calls as CloudFront; Lambda + // needs both of these for a function URL (FunctionUrlOrigin adds the first). + new lambda.CfnPermission(this, "StreamInvokeFromDistribution", { + action: "lambda:InvokeFunction", + functionName: props.streamingFunctionUrl.functionArn, + principal: "cloudfront.amazonaws.com", + sourceArn: `arn:${this.partition}:cloudfront::${this.account}:distribution/${this.distribution.distributionId}`, + invokedViaFunctionUrl: true, + }); + let hostname = domain ? domain.hostname : this.distribution.distributionDomainName; if (cfg.native) hostname = this.nativeDomain(this.distribution); this.publicUrl = `https://${hostname}`; @@ -369,7 +397,7 @@ export class WebStack extends cdk.Stack { "DistributionConfig.ViewerCertificate", cdk.Fn.conditionIf( has.logicalId, - { AcmCertificateArn: cert.valueAsString, SslSupportMethod: "sni-only", MinimumProtocolVersion: "TLSv1.2_2021" }, + { AcmCertificateArn: cert.valueAsString, SslSupportMethod: "sni-only", MinimumProtocolVersion: VIEWER_TLS_POLICY }, cdk.Aws.NO_VALUE, ), ); diff --git a/infra/lib/worker-stack.ts b/infra/lib/worker-stack.ts index 8b4846a13..77ef22561 100644 --- a/infra/lib/worker-stack.ts +++ b/infra/lib/worker-stack.ts @@ -19,6 +19,7 @@ import { repoPath } from "./paths"; import { grantOwnAccountRead } from "./own-account-read"; import * as path from "path"; import { relaySendStatement } from "./mail-relay"; +import { logAccessTo } from "./storage-stack"; import { serviceEnvironment, modelPolicyStatements, publicUrlReadStatement, weeklySummaryScheduled } from "./service-env"; interface WorkerStackProps extends cdk.StackProps { @@ -372,8 +373,10 @@ export class WorkerStack extends cdk.Stack { // Source tarballs are transient: the worker uploads one per commit per // run and reuses it for every check of that commit; this expiry is // what removes them. - lifecycleRules: [{ expiration: cdk.Duration.days(1) }], + lifecycleRules: [{ expiration: cdk.Duration.days(1), abortIncompleteMultipartUploadAfter: cdk.Duration.days(1) }], }); + // Into the storage stack's log bucket (this stack depends on it: app.ts). + logAccessTo(sandboxBucket, cfg, "sandbox"); const sandboxProject = new codebuild.Project(this, "SandboxProject", { projectName: `${prefix}-sandbox`, diff --git a/infra/test/hybrid.test.ts b/infra/test/hybrid.test.ts index 1da5d18ea..a5d932a5b 100644 --- a/infra/test/hybrid.test.ts +++ b/infra/test/hybrid.test.ts @@ -163,7 +163,8 @@ test("hosted CORS trusts exact origins only, never a coderhelm.com wildcard", () test("relay bodies held for retries are gone after two days", () => { const storage = hosted()["coderhelm-prod-storage"]; - const bucket = Object.values(storage.findResources("AWS::S3::Bucket"))[0] as any; + // The data bucket (the storage stack also has the access log bucket). + const bucket = Object.values(storage.findResources("AWS::S3::Bucket")).find((b: any) => JSON.stringify(b.Properties.BucketName).includes("-data")) as any; const rule = bucket.Properties.LifecycleConfiguration.Rules.find((r: any) => r.Prefix === "relay/"); assert.equal(rule.ExpirationInDays, 2); }); diff --git a/infra/test/security-hub.test.ts b/infra/test/security-hub.test.ts new file mode 100644 index 000000000..854bd557d --- /dev/null +++ b/infra/test/security-hub.test.ts @@ -0,0 +1,228 @@ +// What AWS Security Hub checks on an install, as the templates set it +// (docs/self-host/security.md, "Security Hub"): the chat stream behind +// CloudFront only, access logs, TLS everywhere, tables and the user pool +// protected from deletion, supported runtimes. Self-host (CLI) and native +// templates both; the hosted deployment where it shares the stack. +// +// npm test + +import { test } from "node:test"; +import * as assert from "node:assert/strict"; +import * as cdk from "aws-cdk-lib"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { Template } from "aws-cdk-lib/assertions"; +import { buildApp } from "../lib/app"; +import { loadConfigFile, resolveConfig, ResolvedConfig } from "../lib/config"; +import { buildNative } from "../lib/native/build"; +import { ACCESS_LOG_DAYS } from "../lib/storage-stack"; + +const INFRA = path.join(__dirname, "..", ".."); +const STUBS = fs.mkdtempSync(path.join(os.tmpdir(), "chsec-")); +for (const d of ["gateway", "worker", "mcp"]) { + fs.mkdirSync(path.join(STUBS, d), { recursive: true }); + fs.writeFileSync(path.join(STUBS, d, d === "mcp" ? "handler.js" : "bootstrap"), "stub"); +} +const DASH = path.join(STUBS, "dash"); +fs.mkdirSync(path.join(DASH, "_next"), { recursive: true }); +fs.writeFileSync(path.join(DASH, "index.html"), ""); +fs.writeFileSync(path.join(DASH, "_next", "a.js"), "x"); +process.env.GATEWAY_ZIP = path.join(STUBS, "gateway"); +process.env.WORKER_ZIP = path.join(STUBS, "worker"); +process.env.MCP_PROXY_DIR = path.join(STUBS, "mcp"); + +function synth(cfg: ResolvedConfig, context: Record = {}): Record { + const app = new cdk.App({ outdir: fs.mkdtempSync(path.join(os.tmpdir(), "chsecout-")), context }); + buildApp(app, cfg); + const out: Record = {}; + for (const s of app.node.children) if (s instanceof cdk.Stack) out[s.stackName] = Template.fromStack(s).toJSON(); + return out; +} + +const selfHost = synth(resolveConfig({ + account: "111122223333", + region: "us-west-2", + stage: "prod", + email: { from: "coderhelm@example.org" }, + admins: ["owner@example.org"], + integrations: { googleSignIn: false, sandbox: true, logAnalyzer: true, weeklySummary: false }, +})); +const hosted = synth( + loadConfigFile(path.join(INFRA, "config", "hosted.prod.json"), { CDK_DEFAULT_ACCOUNT: "654654210434" }), + { "hosted-zone:account=654654210434:domainName=coderhelm.com:region=us-east-1": { Id: "/hostedzone/ZTEST000001", Name: "coderhelm.com." } }, +); +const rel = buildNative("v9.8.7", fs.mkdtempSync(path.join(os.tmpdir(), "chsecrel-")), { dashboardDir: DASH, commit: "0123456789abcdef0123456789abcdef01234567", releasedAt: "2026-11-01T12:00:00Z" }); +const native: Record = { parent: rel.parent, ...rel.children }; + +type R = { id: string; where: string; r: any }; +function resources(templates: Record, type: string): R[] { + const out: R[] = []; + for (const [where, t] of Object.entries(templates)) { + for (const [id, r] of Object.entries(t.Resources ?? {})) if (r.Type === type) out.push({ id, where, r }); + } + return out; +} +const one = (rs: R[], what: string): R => { + assert.equal(rs.length, 1, `${what}: ${rs.map((x) => `${x.where}.${x.id}`).join(", ")}`); + return rs[0]; +}; +const named = (rs: R[], part: string): R => one(rs.filter((x) => JSON.stringify(x.r.Properties?.BucketName ?? x.r.Properties?.TableName ?? "").includes(part)), part); + +const INSTALLS: [string, Record][] = [["self-host", selfHost], ["native", native]]; + +test("Lambda.1: the chat stream's function URL takes only signed calls; CloudFront signs them (OAC)", () => { + for (const [name, t] of INSTALLS) { + const url = one(resources(t, "AWS::Lambda::Url"), `${name} function URL`); + assert.equal(url.r.Properties.AuthType, "AWS_IAM", name); + assert.equal(url.r.Properties.InvokeMode, "RESPONSE_STREAM", name); + const perms = resources(t, "AWS::Lambda::Permission").map((p) => p.r.Properties); + // Nothing lets the public in (the URL's old FunctionUrlAuthType NONE grants). + for (const p of perms) assert.notEqual(p.Principal, "*", `${name}: a public permission ${JSON.stringify(p)}`); + const cf = perms.filter((p) => p.Principal === "cloudfront.amazonaws.com"); + assert.deepEqual(cf.map((p) => p.Action).sort(), ["lambda:InvokeFunction", "lambda:InvokeFunctionUrl"], name); + for (const p of cf) assert.match(JSON.stringify(p.SourceArn), /:distribution\//, `${name}: scoped to the distribution`); + assert.equal(cf.find((p) => p.Action === "lambda:InvokeFunction")!.InvokedViaFunctionUrl, true, name); + + const oac = resources(t, "AWS::CloudFront::OriginAccessControl").map((x) => x.r.Properties.OriginAccessControlConfig); + assert.ok(oac.some((c) => c.OriginAccessControlOriginType === "lambda" && c.SigningBehavior === "always" && c.SigningProtocol === "sigv4"), name); + const dist = one(resources(t, "AWS::CloudFront::Distribution"), `${name} distribution`).r.Properties.DistributionConfig; + const lambdaOrigin = dist.Origins.find((o: any) => JSON.stringify(o.DomainName).includes("Fn::Split")); + assert.ok(lambdaOrigin?.OriginAccessControlId, `${name}: the stream origin uses OAC`); + for (const p of ["/api/plans/chat/stream", "/api/brain/stream"]) { + const b = dist.CacheBehaviors.find((x: any) => x.PathPattern === p); + assert.deepEqual(b.TargetOriginId, lambdaOrigin.Id, p); + assert.ok(b.AllowedMethods.includes("POST"), p); + // No caching; every viewer header (the stream token, x-amz-content-sha256), cookie and query string reaches it. + assert.equal(b.CachePolicyId, "4135ea2d-6df8-44a3-9df3-4b5a84be39ad", p); + assert.equal(b.OriginRequestPolicyId, "b689b0a8-53d0-40ab-baf2-68738e2966ac", p); + } + } + // CoderHelm's own deployment answers browsers on its stream URL directly: unchanged. + const h = one(resources(hosted, "AWS::Lambda::Url"), "hosted function URL"); + assert.equal(h.r.Properties.AuthType, "NONE"); +}); + +test("S3.5, S3.9, S3.13: every bucket TLS-only with a lifecycle; every bucket but the log bucket logs into it", () => { + for (const [name, t] of INSTALLS) { + const buckets = resources(t, "AWS::S3::Bucket"); + const policies = resources(t, "AWS::S3::BucketPolicy"); + for (const b of buckets) { + const label = `${name} ${b.where}.${b.id}`; + const pol = policies.find((p) => p.where === b.where && JSON.stringify(p.r.Properties.Bucket) === JSON.stringify({ Ref: b.id })); + assert.ok(pol, `${label}: no bucket policy`); + assert.ok(pol!.r.Properties.PolicyDocument.Statement.some((s: any) => s.Effect === "Deny" && s.Condition?.Bool?.["aws:SecureTransport"] === "false"), `${label}: not TLS-only`); + assert.ok(b.r.Properties.LifecycleConfiguration?.Rules?.length, `${label}: no lifecycle`); + const logs = JSON.stringify(b.r.Properties.BucketName ?? "").includes("-logs"); + if (logs) assert.equal(b.r.Properties.LoggingConfiguration, undefined, label); + // The release bucket (native parent) is made before any part, so before the log bucket. + else if (b.where !== "parent") assert.match(JSON.stringify(b.r.Properties.LoggingConfiguration), /-logs.*"LogFilePrefix":"s3\/[a-z]+\/"/, `${label}: no access logs`); + } + } +}); + +test("the log bucket: SSE-S3, private, logs kept 90 days, removed with the stack (writes denied, then emptied)", () => { + for (const [name, t] of [...INSTALLS, ["hosted", hosted] as [string, Record]]) { + const b = named(resources(t, "AWS::S3::Bucket"), "-logs"); + assert.equal(b.where.endsWith("storage") || b.where === "Storage", true, `${name}: in the storage stack`); + const p = b.r.Properties; + assert.equal(p.BucketEncryption.ServerSideEncryptionConfiguration[0].ServerSideEncryptionByDefault.SSEAlgorithm, "AES256"); + assert.deepEqual(p.PublicAccessBlockConfiguration, { BlockPublicAcls: true, BlockPublicPolicy: true, IgnorePublicAcls: true, RestrictPublicBuckets: true }); + // CloudFront's standard logs write with an ACL; the install still owns every object. + assert.equal(p.OwnershipControls.Rules[0].ObjectOwnership, "BucketOwnerPreferred"); + assert.equal(p.AccessControl, undefined, "no ACL grant of its own"); + assert.equal(p.LifecycleConfiguration.Rules[0].ExpirationInDays, ACCESS_LOG_DAYS); + assert.equal(b.r.DeletionPolicy, "Delete", `${name}: logs aren't kept data`); + assert.ok(resources(t, "Custom::S3AutoDeleteObjects").some((x) => x.where === b.where && JSON.stringify(x.r.Properties.BucketName) === JSON.stringify({ Ref: b.id })), name); + const pol = resources(t, "AWS::S3::BucketPolicy").find((x) => x.where === b.where && JSON.stringify(x.r.Properties.Bucket) === JSON.stringify({ Ref: b.id }))!; + const delivery = pol.r.Properties.PolicyDocument.Statement.find((s: any) => s.Sid === "S3ServerAccessLogsFromThisInstall"); + assert.deepEqual(delivery.Principal, { Service: "logging.s3.amazonaws.com" }); + assert.ok(delivery.Condition.StringEquals["aws:SourceAccount"]); + assert.match(JSON.stringify(delivery.Condition.ArnLike["aws:SourceArn"]), /:s3:::coderhelm-(prod|\$\{Stage\})-\*/); + } + // Native: a part that logs into it depends on the storage part. + for (const part of ["Web", "Worker"]) { + const r = rel.parent.Resources[part]; + assert.ok(r.DependsOn.includes("Storage") || JSON.stringify(r.Properties.Parameters).includes('"Storage"'), part); + } +}); + +test("the release bucket (native parent): TLS-only, a lifecycle, only the helper writes", () => { + const R = rel.parent.Resources; + const st = R.AssetsBucketPolicy.Properties.PolicyDocument.Statement; + assert.equal(st[0].Sid, "OnlyTheHelperWritesReleaseFiles"); + assert.deepEqual(st[1].Condition, { Bool: { "aws:SecureTransport": "false" } }); + assert.equal(st[1].Effect, "Deny"); + assert.deepEqual(R.AssetsBucket.Properties.LifecycleConfiguration.Rules[0].AbortIncompleteMultipartUpload, { DaysAfterInitiation: 1 }); +}); + +test("CloudFront.5, CloudFront.15: standard logs to the log bucket; the newest TLS policy on a domain", () => { + for (const [name, t] of INSTALLS) { + const d = one(resources(t, "AWS::CloudFront::Distribution"), name).r.Properties.DistributionConfig; + assert.equal(d.Logging.Prefix, "cloudfront/", name); + assert.match(JSON.stringify(d.Logging.Bucket), /-logs-.*\.s3\./, name); + assert.match(JSON.stringify(d.ViewerCertificate ?? {}), /TLSv1\.2_2025|^\{\}$/, name); + } + // Native: the domain's certificate, when there is one. + assert.match(JSON.stringify(native.Web.Resources.Distribution830FAC52.Properties.DistributionConfig.ViewerCertificate), /"MinimumProtocolVersion":"TLSv1.2_2025"/); + const withDomain = synth(resolveConfig({ + account: "111122223333", region: "us-east-1", stage: "prod", email: { from: "coderhelm@example.org" }, admins: ["owner@example.org"], + domain: { hostname: "coderhelm.example.org", certificateArn: "arn:aws:acm:us-east-1:111122223333:certificate/00000000-0000-0000-0000-000000000000" }, + } as any)); + const vc = one(resources(withDomain, "AWS::CloudFront::Distribution"), "domain").r.Properties.DistributionConfig.ViewerCertificate; + assert.equal(vc.MinimumProtocolVersion, "TLSv1.2_2025"); +}); + +test("DynamoDB.2, DynamoDB.6: every table has point-in-time recovery and deletion protection", () => { + for (const [name, t] of [["self-host", selfHost], ["hosted", hosted]] as [string, Record][]) { + const tables = resources(t, "AWS::DynamoDB::GlobalTable"); + assert.ok(tables.length >= 20, `${name}: ${tables.length} tables`); + for (const x of tables) { + const rep = x.r.Properties.Replicas[0]; + assert.equal(rep.PointInTimeRecoverySpecification?.PointInTimeRecoveryEnabled, true, `${name} ${x.id}: PITR`); + assert.equal(rep.DeletionProtectionEnabled, true, `${name} ${x.id}: deletion protection`); + } + } + // Native: deletion protection follows KeepDataOnDelete (the uninstall turns it off with it). + for (const x of resources(native, "AWS::DynamoDB::GlobalTable")) { + const rep = x.r.Properties.Replicas[0]; + assert.equal(rep.PointInTimeRecoverySpecification?.PointInTimeRecoveryEnabled, true, x.id); + assert.deepEqual(rep.DeletionProtectionEnabled, { "Fn::If": ["NativeKeepData", true, false] }, x.id); + } +}); + +test("Cognito.3, Cognito.6: a strong password policy and deletion protection on the user pool", () => { + for (const [name, t] of [...INSTALLS, ["hosted", hosted] as [string, Record]]) { + const p = one(resources(t, "AWS::Cognito::UserPool"), name).r.Properties; + assert.deepEqual(p.Policies.PasswordPolicy, { + MinimumLength: 8, RequireLowercase: true, RequireUppercase: true, RequireNumbers: true, RequireSymbols: true, TemporaryPasswordValidityDays: 7, + }, name); + // Optional TOTP: an admin can require two-factor for everyone (Settings, Sign-in). + assert.equal(p.MfaConfiguration, "OPTIONAL", name); + assert.deepEqual(p.EnabledMfas, ["SOFTWARE_TOKEN_MFA"], name); + if (name === "native") assert.deepEqual(p.DeletionProtection, { "Fn::If": ["NativeKeepData", "ACTIVE", "INACTIVE"] }); + else assert.equal(p.DeletionProtection, "ACTIVE", name); + } +}); + +test("Lambda.2: every function on a supported runtime (no Node.js 20 or older)", () => { + for (const [name, t] of [...INSTALLS, ["hosted", hosted] as [string, Record]]) { + for (const f of resources(t, "AWS::Lambda::Function")) { + const rt = f.r.Properties.Runtime; + if (rt === undefined) continue; + assert.doesNotMatch(String(rt), /^nodejs(1\d|20)\.x$|^python3\.(\d|1[01])$/, `${name} ${f.where}.${f.id}: ${rt}`); + } + const proxy = resources(t, "AWS::Lambda::Function").find((f) => JSON.stringify(f.r.Properties.FunctionName ?? "").includes("-mcp-proxy"))!; + assert.equal(proxy.r.Properties.Runtime, "nodejs22.x", name); + } + assert.match(fs.readFileSync(path.join(INFRA, "..", "lambda", "mcp-proxy", "package.json"), "utf8"), /--target=node22/); +}); + +test("SES.3: email is only sent over TLS", () => { + for (const [name, t] of [...INSTALLS, ["hosted", hosted] as [string, Record]]) { + const sets = resources(t, "AWS::SES::ConfigurationSet"); + assert.ok(sets.length >= 1, name); + // The install's own set; on hosted, the mail relay's too. + for (const c of sets) assert.equal(c.r.Properties.DeliveryOptions?.TlsPolicy, "REQUIRE", `${name} ${c.where}.${c.id}`); + } +}); diff --git a/installer/lib/uninstall.mjs b/installer/lib/uninstall.mjs index a55cd27a9..9450d1d6f 100644 --- a/installer/lib/uninstall.mjs +++ b/installer/lib/uninstall.mjs @@ -185,7 +185,7 @@ export async function discover(ctx, base, { mode = "keep", installStatus = "", o const bucketNames = new Set(buckets.map((b) => b.Name)); // S3 names carry no region: the stacks' own buckets only when they are in this region. const want = [...inv.ids.map((id) => [`${P}-assets-${id}-${A}`, "bucket"])]; - for (const [name, kind] of [[`${P}-dashboard-${A}`, "bucket"], [`${P}-sandbox-${A}`, "bucket"], [`${P}-data-${A}`, "data bucket"]]) { + for (const [name, kind] of [[`${P}-dashboard-${A}`, "bucket"], [`${P}-sandbox-${A}`, "bucket"], [`${P}-logs-${A}`, "bucket"], [`${P}-data-${A}`, "data bucket"]]) { if (!bucketNames.has(name)) continue; const loc = await aws.read("s3api", "get-bucket-location", ["--bucket", name]); if ((loc?.LocationConstraint || "us-east-1") === region) want.push([name, kind]); diff --git a/lambda/mcp-proxy/package.json b/lambda/mcp-proxy/package.json index 85898fce1..529f1dcb1 100644 --- a/lambda/mcp-proxy/package.json +++ b/lambda/mcp-proxy/package.json @@ -4,7 +4,7 @@ "private": true, "type": "module", "scripts": { - "build": "esbuild handler.mjs --bundle --platform=node --target=node20 --outfile=dist/handler.mjs --format=esm --external:@aws-sdk/* --banner:js=\"import{createRequire}from'module';const require=createRequire(import.meta.url);\"", + "build": "esbuild handler.mjs --bundle --platform=node --target=node22 --outfile=dist/handler.mjs --format=esm --external:@aws-sdk/* --banner:js=\"import{createRequire}from'module';const require=createRequire(import.meta.url);\"", "package": "npm run build && cd dist && zip -r ../mcp-proxy.zip ." }, "dependencies": { diff --git a/services/gateway/src/auth/jwt.rs b/services/gateway/src/auth/jwt.rs index c725cec43..46c25a02c 100644 --- a/services/gateway/src/auth/jwt.rs +++ b/services/gateway/src/auth/jwt.rs @@ -224,10 +224,65 @@ pub fn validate_token(token: &str, secret: &str) -> Result Option<&str> { + if let Some(t) = headers + .get(STREAM_TOKEN_HEADER) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|t| !t.is_empty()) + { + return Some(t); + } + headers + .get(axum::http::header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) + .filter(|t| !t.is_empty()) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_stream_token_comes_from_its_header_or_a_bearer_authorization() { + use axum::http::{HeaderMap, HeaderValue}; + let mut h = HeaderMap::new(); + assert_eq!(stream_token(&h), None); + h.insert("authorization", HeaderValue::from_static("Bearer abc")); + assert_eq!(stream_token(&h), Some("abc")); + // Through CloudFront the Authorization header is CloudFront's own + // signature: the token is in its header, which wins. + h.insert( + "authorization", + HeaderValue::from_static( + "AWS4-HMAC-SHA256 Credential=AKIA/20261110/us-east-1/lambda/aws4_request", + ), + ); + assert_eq!(stream_token(&h), None); + h.insert(STREAM_TOKEN_HEADER, HeaderValue::from_static("xyz")); + assert_eq!(stream_token(&h), Some("xyz")); + // An empty header doesn't hide a bearer token. + let mut e = HeaderMap::new(); + e.insert(STREAM_TOKEN_HEADER, HeaderValue::from_static("")); + e.insert("authorization", HeaderValue::from_static("Bearer abc")); + assert_eq!(stream_token(&e), Some("abc")); + e.insert("authorization", HeaderValue::from_static("Bearer ")); + assert_eq!(stream_token(&e), None); + } + #[test] fn test_roundtrip_jwt() { let secret = "test-jwt-secret-at-least-32-chars!"; diff --git a/services/gateway/src/routes/auth.rs b/services/gateway/src/routes/auth.rs index c4d8c3cb2..dc4f6f954 100644 --- a/services/gateway/src/routes/auth.rs +++ b/services/gateway/src/routes/auth.rs @@ -265,13 +265,19 @@ pub async fn signup( const WEAK_PASSWORD: &str = "Password must contain at least 8 characters, including uppercase, lowercase, a number, and a special character"; -/// The user pool's password rules (infra: at least 8 characters, an upper-case and a -/// lower-case letter, and a digit). +/// The characters Cognito counts as special in a password (its password policy). +const PASSWORD_SYMBOLS: &str = "^$*.[]{}()?\"!@#%&/\\,><':;|_~`=+-"; + +/// The user pool's password rules (infra/lib/api-stack.ts: at least 8 characters, an +/// upper-case and a lower-case letter, a digit and a symbol). pub fn password_fits(p: &str) -> bool { + let inner = p.trim(); p.chars().count() >= 8 && p.chars().any(|c| c.is_uppercase()) && p.chars().any(|c| c.is_lowercase()) && p.chars().any(|c| c.is_ascii_digit()) + // A space counts too, but not a leading or trailing one (Cognito's rule). + && (p.chars().any(|c| PASSWORD_SYMBOLS.contains(c)) || inner.contains(' ')) } /// A self-hosted install's sign-up answer, the same for every email: invited or allowed (a @@ -3536,8 +3542,16 @@ mod forgot_tests { #[test] fn passwords_are_checked_before_anyone_is_looked_up() { - assert!(password_fits("Acme2026x")); - for p in ["acme2026x", "ACME2026X", "AcmeAcmeX", "Ac2"] { + assert!(password_fits("Acme2026x!")); + assert!(password_fits("Acme 2026x")); + for p in [ + "acme2026x!", + "ACME2026X!", + "AcmeAcmeX!", + "Ac2!", + "Acme2026x", + " Acme2026x ", + ] { assert!(!password_fits(p), "{p}"); } } diff --git a/services/gateway/src/routes/brain.rs b/services/gateway/src/routes/brain.rs index b95926db2..4887c2d10 100644 --- a/services/gateway/src/routes/brain.rs +++ b/services/gateway/src/routes/brain.rs @@ -1924,10 +1924,7 @@ pub async fn brain_stream( >, (StatusCode, Json), > { - let token = headers - .get("authorization") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.strip_prefix("Bearer ")) + let token = crate::auth::jwt::stream_token(&headers) .ok_or_else(|| fail(StatusCode::UNAUTHORIZED, "Sign in again."))?; let mut claims = crate::auth::jwt::validate_scoped_token( token, diff --git a/services/gateway/src/routes/plans.rs b/services/gateway/src/routes/plans.rs index b0b9041bf..74914feb0 100644 --- a/services/gateway/src/routes/plans.rs +++ b/services/gateway/src/routes/plans.rs @@ -3555,15 +3555,11 @@ pub async fn plan_chat_stream( >, StatusCode, > { - // Validate Bearer token (issued by /api/plans/chat/token) - let token = headers - .get("authorization") - .and_then(|v| v.to_str().ok()) - .and_then(|v| v.strip_prefix("Bearer ")) - .ok_or_else(|| { - warn!("plan_chat_stream: missing or invalid Authorization header"); - StatusCode::UNAUTHORIZED - })?; + // The token issued by /api/plans/chat/token (auth::jwt::stream_token). + let token = crate::auth::jwt::stream_token(&headers).ok_or_else(|| { + warn!("plan_chat_stream: no stream token"); + StatusCode::UNAUTHORIZED + })?; let claims = crate::auth::jwt::validate_token(token, &state.secrets.jwt_secret).map_err(|e| { From 277fbbf3adfa19d551c8b1bdaed9362900d8aa80 Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 10 Nov 2026 12:03:07 -0500 Subject: [PATCH 2/3] Ship the dashboard that streams through the signed CloudFront path CoderHelm/coderhelm a95516a sends the stream token in its own header and the body's SHA-256, which the AWS_IAM function URL behind origin access control needs. --- selfhost/versions.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/selfhost/versions.json b/selfhost/versions.json index 80651b70c..55f390e27 100644 --- a/selfhost/versions.json +++ b/selfhost/versions.json @@ -1,4 +1,4 @@ { "about": "The dashboard commit each platform release ships: a full 40-character commit SHA of CoderHelm/coderhelm, never a branch or tag (scripts/check-dashboard-ref.mjs fails CI and the release otherwise). The release workflow builds exactly this commit (dashboard/) into dashboard.tar.gz. Move it with scripts/bump-dashboard.sh in a reviewed PR, in the same PR as any API change the dashboard needs.", - "dashboardRef": "1a354aed30a52e0a8039738b95279822f64471d1" + "dashboardRef": "a95516ade4dc72708a16dcd00db66c0fa159ea1f" } From 21879b28160d0c8736eac2ec069463c7bfd8f04b Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Tue, 10 Nov 2026 12:07:27 -0500 Subject: [PATCH 3/3] Write CloudFront's standard logs only where CloudFront delivers them Legacy standard logging delivers to no bucket in an opt-in region, and turning it on there would fail the update. A native release's one template decides by its region (a condition); any other install at synth. --- docs/self-host/security.md | 2 +- infra/lib/web-stack.ts | 45 ++++++++++++++++++++++++++++++--- infra/test/security-hub.test.ts | 23 ++++++++++++----- 3 files changed, 59 insertions(+), 11 deletions(-) diff --git a/docs/self-host/security.md b/docs/self-host/security.md index 2d1e48c91..3bc174888 100644 --- a/docs/self-host/security.md +++ b/docs/self-host/security.md @@ -288,7 +288,7 @@ AWS Security Hub checks an install against AWS's best practices. This is what ea | S3.5 | Every bucket refuses requests without TLS, the release bucket included. | | S3.9 | The data, dashboard and sandbox buckets write server access logs to the install's log bucket, `coderhelm--logs-`, under `s3//`. | | S3.13 | Every bucket has a lifecycle: access logs expire after 90 days, sandbox tarballs after a day, old versions of data after 30 days, and unfinished uploads after a day. | -| CloudFront.5 | The distribution writes standard logs to the log bucket, under `cloudfront/`. | +| CloudFront.5 | The distribution writes standard logs to the log bucket, under `cloudfront/`, in every region AWS enables by default. CloudFront delivers no standard logs to a bucket in an opt-in region (Cape Town, Hong Kong, Milan, Spain, Zurich, Tel Aviv, the UAE, Bahrain, Hyderabad, Jakarta, Melbourne, Calgary, Mexico and newer), so an install there has the S3 access logs only. | | CloudFront.15 | On your own domain, viewers need TLS 1.2 with modern ciphers, or TLS 1.3 (`TLSv1.2_2025`). | | DynamoDB.2, DynamoDB.6 | Every table has point-in-time recovery and deletion protection. On a Launch Stack install, deletion protection follows **KeepDataOnDelete**, so an uninstall that deletes the data can delete the tables. | | Cognito.3, Cognito.6 | Passwords need 8 characters with an upper-case and a lower-case letter, a digit and a symbol. Temporary passwords last 7 days. The user pool has deletion protection, which follows **KeepDataOnDelete** like the tables. | diff --git a/infra/lib/web-stack.ts b/infra/lib/web-stack.ts index 46a862387..f8b0294f1 100644 --- a/infra/lib/web-stack.ts +++ b/infra/lib/web-stack.ts @@ -64,6 +64,17 @@ export const BRAIN_STREAM_PATH = "/api/brain/stream"; */ export const VIEWER_TLS_POLICY = cloudfront.SecurityPolicyProtocol.TLS_V1_2_2025; +/** + * The regions CloudFront's standard logs (legacy, to S3) can be delivered to: + * every region enabled by default. It delivers none to a bucket in an opt-in + * region, so an install there has no CloudFront logs (S3 access logs still). + */ +export const CLOUDFRONT_LOG_REGIONS = [ + "us-east-1", "us-east-2", "us-west-1", "us-west-2", "ca-central-1", "sa-east-1", + "eu-west-1", "eu-west-2", "eu-west-3", "eu-central-1", "eu-north-1", + "ap-northeast-1", "ap-northeast-2", "ap-northeast-3", "ap-southeast-1", "ap-southeast-2", "ap-south-1", +]; + /** Hashed build files: cached for a year. */ const ASSET_CACHE_CONTROL = "public, max-age=31536000, immutable"; /** Pages and the runtime config: revalidated on every visit. */ @@ -246,10 +257,6 @@ export class WebStack extends cdk.Stack { defaultRootObject: "index.html", httpVersion: cloudfront.HttpVersion.HTTP2_AND_3, minimumProtocolVersion: VIEWER_TLS_POLICY, - // Standard logs, kept 90 days in the storage stack's log bucket. - enableLogging: true, - logBucket: logBucketOf(this, cfg), - logFilePrefix: "cloudfront/", defaultBehavior: { // List too, so a file that isn't there is a 404 (not S3's 403), // which the error response below turns into the install's own page. @@ -275,6 +282,8 @@ export class WebStack extends cdk.Stack { ], }); + this.standardLogs(cfg); + // Origin access control signs the stream's calls as CloudFront; Lambda // needs both of these for a function URL (FunctionUrlOrigin adds the first). new lambda.CfnPermission(this, "StreamInvokeFromDistribution", { @@ -370,6 +379,34 @@ export class WebStack extends cdk.Stack { } } + /** + * Standard logs into the storage stack's log bucket (`cloudfront/`, kept + * 90 days), where CloudFront can deliver them: a native release's one + * template decides by its region (a condition), any other install at synth. + */ + private standardLogs(cfg: ResolvedConfig): void { + const logging = { + Bucket: logBucketOf(this, cfg).bucketRegionalDomainName, + IncludeCookies: false, + Prefix: "cloudfront/", + }; + const cfn = this.distribution.node.defaultChild as cloudfront.CfnDistribution; + if (cfg.native) { + const eq = (r: string) => cdk.Fn.conditionEquals(cdk.Aws.REGION, r); + const half = Math.ceil(CLOUDFRONT_LOG_REGIONS.length / 2); + const supported = new cdk.CfnCondition(this, "CloudFrontLogsRegion", { + // Fn::Or takes at most 10. + expression: cdk.Fn.conditionOr( + cdk.Fn.conditionOr(...CLOUDFRONT_LOG_REGIONS.slice(0, half).map(eq)), + cdk.Fn.conditionOr(...CLOUDFRONT_LOG_REGIONS.slice(half).map(eq)), + ), + }); + cfn.addPropertyOverride("DistributionConfig.Logging", cdk.Fn.conditionIf(supported.logicalId, logging, cdk.Aws.NO_VALUE)); + } else if (CLOUDFRONT_LOG_REGIONS.includes(cfg.region)) { + cfn.addPropertyOverride("DistributionConfig.Logging", logging); + } + } + /** * A native release's own domain: stack parameters, not a redeploy. The * updater requests the certificate (Settings, System, or the Hostname diff --git a/infra/test/security-hub.test.ts b/infra/test/security-hub.test.ts index 854bd557d..f62ad72f8 100644 --- a/infra/test/security-hub.test.ts +++ b/infra/test/security-hub.test.ts @@ -17,6 +17,7 @@ import { buildApp } from "../lib/app"; import { loadConfigFile, resolveConfig, ResolvedConfig } from "../lib/config"; import { buildNative } from "../lib/native/build"; import { ACCESS_LOG_DAYS } from "../lib/storage-stack"; +import { CLOUDFRONT_LOG_REGIONS } from "../lib/web-stack"; const INFRA = path.join(__dirname, "..", ".."); const STUBS = fs.mkdtempSync(path.join(os.tmpdir(), "chsec-")); @@ -157,12 +158,22 @@ test("the release bucket (native parent): TLS-only, a lifecycle, only the helper }); test("CloudFront.5, CloudFront.15: standard logs to the log bucket; the newest TLS policy on a domain", () => { - for (const [name, t] of INSTALLS) { - const d = one(resources(t, "AWS::CloudFront::Distribution"), name).r.Properties.DistributionConfig; - assert.equal(d.Logging.Prefix, "cloudfront/", name); - assert.match(JSON.stringify(d.Logging.Bucket), /-logs-.*\.s3\./, name); - assert.match(JSON.stringify(d.ViewerCertificate ?? {}), /TLSv1\.2_2025|^\{\}$/, name); - } + const self = one(resources(selfHost, "AWS::CloudFront::Distribution"), "self-host").r.Properties.DistributionConfig; + assert.deepEqual(self.Logging.Prefix, "cloudfront/"); + assert.equal(self.Logging.IncludeCookies, false); + assert.match(JSON.stringify(self.Logging.Bucket), /coderhelm-prod-logs-111122223333\.s3\./); + // Native: one template for every region, and CloudFront delivers no standard + // logs to a bucket in an opt-in region, so the region decides. + const nd = native.Web.Resources.Distribution830FAC52.Properties.DistributionConfig; + assert.equal(nd.Logging["Fn::If"][0], "CloudFrontLogsRegion"); + assert.equal(nd.Logging["Fn::If"][1].Prefix, "cloudfront/"); + assert.deepEqual(nd.Logging["Fn::If"][2], { Ref: "AWS::NoValue" }); + const regions = JSON.stringify(native.Web.Conditions.CloudFrontLogsRegion).match(/"(?:[a-z]+-)+\d"/g)!.map((r) => JSON.parse(r)).sort(); + assert.deepEqual(regions, [...CLOUDFRONT_LOG_REGIONS].sort()); + for (const r of ["af-south-1", "il-central-1", "eu-south-2", "me-central-1", "ap-east-1", "mx-central-1"]) assert.ok(!regions.includes(r), r); + // A self-host install in an opt-in region: no standard logs (the update would fail). + const optIn = synth(resolveConfig({ account: "111122223333", region: "eu-south-2", stage: "prod", email: { from: "coderhelm@example.org" }, admins: ["owner@example.org"] })); + assert.equal(one(resources(optIn, "AWS::CloudFront::Distribution"), "opt-in").r.Properties.DistributionConfig.Logging, undefined); // Native: the domain's certificate, when there is one. assert.match(JSON.stringify(native.Web.Resources.Distribution830FAC52.Properties.DistributionConfig.ViewerCertificate), /"MinimumProtocolVersion":"TLSv1.2_2025"/); const withDomain = synth(resolveConfig({