From 48c74c1f62d5c4145d94c1b610b00b8e9348f58e Mon Sep 17 00:00:00 2001 From: OllieJC Date: Thu, 22 Oct 2026 00:34:21 +0100 Subject: [PATCH 1/3] Add self-contained SOCA Lambda@Edge MVP and deployment generator --- .dockerignore | 9 + .github/dependabot.yml | 21 + .github/workflows/ci.yml | 53 +++ .github/workflows/codeql.yml | 27 ++ .gitignore | 11 + AGENTS.md | 6 + Dockerfile | 13 + README.md | 125 +++++- SECURITY.md | 8 + cloudformation/README.md | 15 + cloudformation/template.yaml | 95 +++++ demo/provider.mjs | 57 +++ demo/server.mjs | 54 +++ docs/requirements.md | 54 +++ docs/security.md | 88 ++++ examples/config.json | 12 + examples/terraform/.terraform.lock.hcl | 26 ++ examples/terraform/README.md | 19 + examples/terraform/main.tf | 148 +++++++ examples/terraform/outputs.tf | 22 + examples/terraform/variables.tf | 33 ++ generator/cli.mjs | 42 ++ generator/package.mjs | 72 ++++ package-lock.json | 533 +++++++++++++++++++++++++ package.json | 23 ++ src/config.mjs | 121 ++++++ src/network.mjs | 55 +++ src/runtime.mjs | 281 +++++++++++++ terraform/.terraform.lock.hcl | 26 ++ terraform/README.md | 25 ++ terraform/main.tf | 69 ++++ terraform/outputs.tf | 9 + terraform/variables.tf | 37 ++ tests/demo.test.mjs | 30 ++ tests/helpers.mjs | 38 ++ tests/network.test.mjs | 52 +++ tests/package.test.mjs | 108 +++++ tests/runtime.test.mjs | 175 ++++++++ 38 files changed, 2590 insertions(+), 2 deletions(-) create mode 100644 .dockerignore create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/codeql.yml create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 Dockerfile create mode 100644 SECURITY.md create mode 100644 cloudformation/README.md create mode 100644 cloudformation/template.yaml create mode 100644 demo/provider.mjs create mode 100644 demo/server.mjs create mode 100644 docs/requirements.md create mode 100644 docs/security.md create mode 100644 examples/config.json create mode 100644 examples/terraform/.terraform.lock.hcl create mode 100644 examples/terraform/README.md create mode 100644 examples/terraform/main.tf create mode 100644 examples/terraform/outputs.tf create mode 100644 examples/terraform/variables.tf create mode 100644 generator/cli.mjs create mode 100644 generator/package.mjs create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 src/config.mjs create mode 100644 src/network.mjs create mode 100644 src/runtime.mjs create mode 100644 terraform/.terraform.lock.hcl create mode 100644 terraform/README.md create mode 100644 terraform/main.tf create mode 100644 terraform/outputs.tf create mode 100644 terraform/variables.tf create mode 100644 tests/demo.test.mjs create mode 100644 tests/helpers.mjs create mode 100644 tests/network.test.mjs create mode 100644 tests/package.test.mjs create mode 100644 tests/runtime.test.mjs diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..0ff25c1 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,9 @@ +.git +node_modules +.soca +dist +*.zip +*.pem +*.key +**/.terraform +**/*.tfstate* diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..a210b00 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,21 @@ +version: 2 +updates: + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + groups: + dependencies: + patterns: ['*'] + - package-ecosystem: terraform + directories: [/terraform, /examples/terraform] + schedule: + interval: weekly + - package-ecosystem: docker + directory: / + schedule: + interval: weekly + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..815af0c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,53 @@ +name: CI +on: + pull_request: + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +jobs: + runtime: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: '24' + cache: npm + - run: npm ci --ignore-scripts + - run: npm run check && npm test + - run: npm audit --audit-level=high + - name: Emit dependency SBOM without deployment material + run: npm sbom --omit=dev --sbom-format=cyclonedx > sbom.json + - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: dependency-sbom + path: sbom.json + retention-days: 7 + infrastructure: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: hashicorp/setup-terraform@dfe3c3f87815947d99a8997f908cb6525fc44e9e # v4 + with: + terraform_version: '1.16.0' + - run: terraform fmt -recursive -check + - run: terraform -chdir=terraform init -backend=false -lockfile=readonly && terraform -chdir=terraform validate + - run: terraform -chdir=examples/terraform init -backend=false -lockfile=readonly && terraform -chdir=examples/terraform validate + - run: pipx run --spec cfn-lint==1.58.0 cfn-lint cloudformation/template.yaml + demo-container: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: docker build -t soca-edge-demo . + - run: docker run --rm --network=none soca-edge-demo npm test diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..129d3a2 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,27 @@ +name: CodeQL +on: + pull_request: + push: + branches: [main] + schedule: + - cron: '37 4 * * 4' + workflow_dispatch: +permissions: + contents: read +jobs: + analyse: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + contents: read + security-events: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: github/codeql-action/init@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + languages: javascript-typescript,actions + build-mode: none + queries: security-extended + - uses: github/codeql-action/analyze@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8037767 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +node_modules/ +.soca/ +dist/ +*.zip +*.pem +*.key +*.tfstate* +.terraform/ +*.tfplan +coverage/ +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..0fe8cbe --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,6 @@ +# Repository guidance + +- Keep the implementation small. Use British English and no em dash in prose. +- Never commit deployment keys, generated ZIPs, session cookies or real tokens. +- Run `npm test`, `npm run check` and `git diff --check` before committing. +- Preserve fail-closed behaviour and disclose SOCA requirement gaps in `docs/requirements.md`. diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..6921261 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM docker.io/library/node:24-bookworm-slim@sha256:2dd9a4f758e173b65fee15388f7706af6fb01ef50cf7a2c0538711d67a6981ae +RUN apt-get update && apt-get install -y --no-install-recommends openssl && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --ignore-scripts && npm cache clean --force +COPY src/ ./src/ +COPY generator/ ./generator/ +COPY demo/ ./demo/ +COPY tests/ ./tests/ +COPY LICENSE ./LICENSE +USER node +EXPOSE 8443 +CMD ["npm", "run", "demo"] diff --git a/README.md b/README.md index 91b33cd..abfccdc 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,123 @@ -# cloudfront-soca-plugin -SOCA authentication for private S3 content using a self-contained Lambda@Edge deployment package +# CloudFront SOCA plugin + +An MVP SOCA/OIDC gate for private S3 static content. One Lambda@Edge viewer-request +handler checks access before CloudFront serves cached objects. A local generator +packages JavaScript, configuration, ES256 keys and AES-256-GCM session keys into a +private ZIP. No runtime KMS, database, Secrets Manager, Parameter Store or AWS SDK. +Sign-in contacts the trusted identity provider; authenticated content requests use +local cryptography only. There are no local user accounts or admin UI. + +**Alpha:** ES256, one issuer, static GET/HEAD content and stateless sessions. +Sessions default to **43,200 seconds (12 hours)**. Sign-in is disabled by default +and admission denies everyone until an allow rule is supplied. See the +[requirements and verification gaps](docs/requirements.md) before deployment. + +## Package + +Use Node.js 24 and npm. Licence: AGPL-3.0-only. + +```sh +npm ci --ignore-scripts +mkdir -p .soca +cp examples/config.json .soca/config.json +npm run soca -- init .soca/keys.json +# Edit origin, issuer, allow rules and paths in .soca/config.json. +npm run soca -- preview .soca/config.json .soca/keys.json +npm run soca -- build .soca/config.json .soca/keys.json .soca/deployment-v1.zip +``` + +Keep the key file across rebuilds. `init` and `build` refuse to overwrite files. +The ZIP contains `index.mjs`, private `deployment.json` and the licence; dependencies +are bundled. No generator or simulator runs inside Lambda. Identical source, +configuration and keys produce identical ZIPs. + +Generated ZIPs **contain private keys**. Keep them in private deployment storage, +never Git, public releases, CI artefacts or the content bucket. Key files and ZIPs +are created with mode `0600`. Anyone allowed to download Lambda code or the source +ZIP can extract the keys. This is the chosen exportable-key model. + +## Deploy + +- [Terraform module](terraform/README.md) publishes a numbered Lambda version. +- [CloudFormation template](cloudformation/README.md) deploys the function from a + private, versioned S3 ZIP. Use it directly or as a nested stack, the practical + equivalent of a reusable Terraform module. +- [Complete Terraform example](examples/terraform/README.md) adds private S3, OAC + and CloudFront, with a disabled distribution for safe hostname bootstrap. + +Deploy in `us-east-1`, Node.js 24, x86_64, handler `index.handler`. Associate the +numbered version with **viewer-request on every relevant cache behaviour**, with +`include_body=false`. Lambda@Edge has no custom runtime environment variables; +configuration is fixed in the ZIP. Source is in [src/](src/). + +First publish an `enabled=false` package for the real HTTPS origin and run: + +```sh +npm run soca -- check .soca/config.json .soca/keys.json +``` + +This checks exact public documents and provider capabilities. It does **not** test +login or authorise activation. Verify a real allowed and denied login on a separate +staging distribution with `enabled=true` before deploying that configuration with +production content. There is no candidate-only operator login or enforced +activation evidence yet. See F-20 in the assessment. + +For content caching, exclude cookies, query strings and viewer identity headers +from cache keys and S3 forwarding, as in the example. All admitted users receive +the same static objects. Do not use this cache configuration for personalised +responses. Avoid access logs that retain callback query strings or cookies. + +## Configuration + +All settings/defaults are in [src/config.mjs](src/config.mjs). File values override +defaults; `SOCA_SESSION_TTL_SECONDS` overrides the file **at generator time**. +It has no runtime effect. Unknown settings fail validation. + +| Setting | Meaning/default | +| --- | --- | +| `origin` | Required canonical public HTTPS origin, no trailing slash; never inferred from headers. | +| `issuer` | Exact trusted issuer; default `https://auth.resoauth.cloud`. | +| `enabled` | `false`: metadata stays public; protected content and login return 503. | +| `session_ttl_seconds` | Absolute lifetime, `43200`; integer range 1 to 604800. | +| `transaction_ttl_seconds` | `300`; integer range 1 to 600, four pending logins maximum. | +| `protected_paths` / `public_paths` | `['/']` / `[]`. Literal segment prefixes: `/docs` matches itself and descendants, not `/docs-old`. Public exceptions take precedence. | +| `allow_domains` / `deny_domains` | Empty; exact DNS domains or `*.example.com` for subdomains only. | +| `allow_emails` / `deny_emails` | Empty; case-insensitive exact addresses. Deny rules take precedence. Boolean `email_verified: true` required. | +| `auth_path` | `/_soca`; reserves `client.json`, `jwks.json`, `login`, `callback`, `logout`. | +| `metadata_mode` / `proxy_template` | `hosted`; proxy default `https://dynamic-cimd.resoauth.cloud/cimd/%s`. | +| `client_name`, `client_uri`, `logo_uri`, `policy_uri`, `tos_uri` | Site identity and public legal/branding URLs. Client URI defaults to origin; unavailable optional fields are omitted. | +| `scopes` | `['openid', 'email']`; only `openid`, `email`, `profile` accepted. No refresh tokens or UserInfo retrieval. | +| `max_age_seconds`, `required_acr`, `required_amr` | Optional freshness/assurance. Defaults `null`, `[]`, `[]`; use the provider's documented assurance semantics. | +| `security_epoch` | Non-negative integer, default 0. Increment to invalidate cookies as updated edge versions propagate. | + +Selected-path protection covers **viewer paths**. Protect every alias to the same +object, including `/` if it maps to a protected default root object. Do not add +origin rewrites or custom error fallbacks that serve protected objects from public +paths. Ambiguous encoded delimiters, double encoding and dot segments are rejected. + +Proxy mode uses sorted-key compact UTF-8 JSON, unpadded base64url, no `client_id` +inside the payload and a 4096-character URL limit. It references a stable public +`jwks_uri`; inline JWKS is not implemented. Proxy metadata is public and visible +to the proxy. The proxy does not perform provider authentication. + +## Test and demo + +```sh +npm test +podman build -t soca-edge-demo . +podman run --rm --network=none soca-edge-demo npm test +podman run --rm -p 127.0.0.1:8443:8443 soca-edge-demo +``` + +Docker accepts the same commands. Open `https://localhost:8443` and accept the +local demo's ephemeral self-signed certificate. It uses real JWT/cookie +cryptography with an **in-process identity-provider simulator**, automatically +admitting `reader@example.com`. It simulates the CloudFront event and static +origin, not AWS replication or a real provider login. Simulator injection is +confined to demo/tests, never packaged as a runtime option. `npm run demo` runs +without a container, with `openssl` installed. + +CI tests source, standalone ZIP and container, validates infrastructure, audits +dependencies and emits a dependency SBOM. CodeQL scans JavaScript and workflows. +No secret-bearing ZIP is uploaded by CI. See the +[operations and threat model](docs/security.md) for rotation and stateless limits. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..f8addb0 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,8 @@ +# Security + +Read the [threat model](docs/security.md) and [requirement gaps](docs/requirements.md) +before production use. Report privately through +[GitHub security advisories](https://github.com/RESOAuth/cloudfront-soca-plugin/security/advisories/new). +Never include a ZIP, keys, live callback URL, token or cookie in a public issue. +The initial supported line is 0.1.x. Fix confirmed high/critical issues before +production release; this MVP has no published response SLA yet. diff --git a/cloudformation/README.md b/cloudformation/README.md new file mode 100644 index 0000000..2fdf711 --- /dev/null +++ b/cloudformation/README.md @@ -0,0 +1,15 @@ +# CloudFormation template + +CloudFormation creates AWS resources from a YAML template. This template is the equivalent of the Terraform Lambda module: it publishes the function and execution role, then returns `VersionArn`. It can be deployed directly or used as an `AWS::CloudFormation::Stack` nested stack. It does not create or change a distribution. + +1. Build the deployment ZIP using the generator. +2. Upload it to a private, versioned S3 bucket in `us-east-1`. Block public access and use server-side encryption. The ZIP contains private keys; restrict both artifact access and Lambda `GetFunction` permissions. +3. Calculate the base64 SHA-256 of the exact ZIP bytes, for example `openssl dgst -sha256 -binary deployment.zip | openssl base64 -A`. +4. Deploy `template.yaml` in `us-east-1` with `CAPABILITY_IAM`. Supply `ArtifactBucket`, `ArtifactKey`, `ArtifactVersion`, `CodeSha256` and a unique `FunctionName`. +5. Associate the output `VersionArn` with `viewer-request`, without a request body, on each relevant CloudFront behaviour. Keep the S3 origin private behind Origin Access Control and exclude cookies/query strings from the content cache policy and origin forwarding. Allow POST for logout. + +For every package update, change both `ArtifactVersion` and `CodeSha256`. CloudFormation does not notice an overwritten object at an unchanged S3 reference. The hash forces replacement of the version resource and prevents publication if the uploaded code does not match. A timeout change also replaces the published version. The function remains Node.js 24, x86_64, 128 MB, with a default 30-second timeout and no custom environment variables. Keys and session settings stay inside the private ZIP rather than stack parameters. + +Use the [Terraform example's bootstrap sequence](../examples/terraform/README.md) when the distribution hostname is not yet known. Keep the distribution disabled until a package for its canonical HTTPS origin is attached; public document checks and separate staging login tests then follow the main README. + +Old version resources are retained on replacement because CloudFront replicas may still reference them. Retention also keeps their secret-bearing packages available to principals allowed to read Lambda code. Remove unused versions after confirming that no distribution uses them and waiting for replica cleanup. Before deleting the stack, remove all associations and wait several hours, then delete retained versions separately. See [AWS replica cleanup](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-delete-replicas.html). diff --git a/cloudformation/template.yaml b/cloudformation/template.yaml new file mode 100644 index 0000000..c9c7674 --- /dev/null +++ b/cloudformation/template.yaml @@ -0,0 +1,95 @@ +AWSTemplateFormatVersion: '2010-09-09' +Description: SOCA Lambda@Edge from a private, versioned deployment ZIP. + +Parameters: + FunctionName: + Type: String + Default: cloudfront-soca + AllowedPattern: '^[A-Za-z0-9_-]{1,64}$' + Description: Unique Lambda function name. + ArtifactBucket: + Type: String + MinLength: 3 + Description: Private versioned S3 artifact bucket in us-east-1. + ArtifactKey: + Type: String + MinLength: 1 + Description: S3 object key for the generated private ZIP. + ArtifactVersion: + Type: String + MinLength: 1 + Description: Exact S3 object VersionId, changed on every package update. + CodeSha256: + Type: String + AllowedPattern: '^[A-Za-z0-9+/]{43}=$' + Description: Base64 SHA-256 of the ZIP bytes, changed on every package update. + TimeoutSeconds: + Type: Number + Default: 30 + MinValue: 1 + MaxValue: 30 + Description: Viewer-request timeout including identity-provider requests. + +Rules: + EdgeRegion: + Assertions: + - Assert: !Equals [!Ref 'AWS::Region', us-east-1] + AssertDescription: Lambda@Edge must be deployed in us-east-1. + +Resources: + ExecutionRole: + Type: AWS::IAM::Role + Properties: + Description: SOCA Lambda@Edge execution role + AssumeRolePolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: sts:AssumeRole + Principal: + Service: [lambda.amazonaws.com, edgelambda.amazonaws.com] + Policies: + - PolicyName: function-logs + PolicyDocument: + Version: '2012-10-17' + Statement: + - Effect: Allow + Action: [logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents] + Resource: + - !Sub 'arn:${AWS::Partition}:logs:*:${AWS::AccountId}:log-group:/aws/lambda/${FunctionName}' + - !Sub 'arn:${AWS::Partition}:logs:*:${AWS::AccountId}:log-group:/aws/lambda/${FunctionName}:*' + - !Sub 'arn:${AWS::Partition}:logs:*:${AWS::AccountId}:log-group:/aws/lambda/us-east-1.${FunctionName}' + - !Sub 'arn:${AWS::Partition}:logs:*:${AWS::AccountId}:log-group:/aws/lambda/us-east-1.${FunctionName}:*' + + Function: + Type: AWS::Lambda::Function + Properties: + FunctionName: !Ref FunctionName + Description: SOCA stateless CloudFront authentication + Role: !GetAtt ExecutionRole.Arn + Runtime: nodejs24.x + Handler: index.handler + Architectures: [x86_64] + MemorySize: 128 + Timeout: !Ref TimeoutSeconds + Code: + S3Bucket: !Ref ArtifactBucket + S3Key: !Ref ArtifactKey + S3ObjectVersion: !Ref ArtifactVersion + + Version: + Type: AWS::Lambda::Version + DeletionPolicy: Retain + UpdateReplacePolicy: Retain + Properties: + FunctionName: !Ref Function + CodeSha256: !Ref CodeSha256 + Description: !Sub '${CodeSha256}; timeout=${TimeoutSeconds}' + +Outputs: + VersionArn: + Description: Numbered ARN for a CloudFront viewer-request association. + Value: !Ref Version + DeployedFunctionName: + Description: Deployed function name. + Value: !Ref Function diff --git a/demo/provider.mjs b/demo/provider.mjs new file mode 100644 index 0000000..26769c2 --- /dev/null +++ b/demo/provider.mjs @@ -0,0 +1,57 @@ +import { createPrivateKey, randomBytes } from 'node:crypto'; +import { SignJWT, createLocalJWKSet, jwtVerify } from 'jose'; +import { digest, ensure } from '../src/config.mjs'; +import { newKeys } from '../generator/package.mjs'; + +// Deliberate protocol simulator for tests/demo only. Never part of deployment ZIPs. +export function simulatedProvider(deployment, clock = () => Math.floor(Date.now() / 1000)) { + const issuer = deployment.config.issuer; + const pair = newKeys(); + const signer = pair.signing_key; + const codes = new Map(); + const calls = []; + const discovery = { + issuer, authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, jwks_uri: `${issuer}/jwks`, + response_types_supported: ['code'], code_challenge_methods_supported: ['S256'], + token_endpoint_auth_methods_supported: ['private_key_jwt'], token_endpoint_auth_signing_alg_values_supported: ['ES256'], + id_token_signing_alg_values_supported: ['ES256'], client_id_metadata_document_supported: true, + authorization_response_iss_parameter_supported: true, + }; + function authorise(url, claims = {}, headers = {}) { + const p = new URL(url).searchParams; + ensure(p.get('code_challenge_method') === 'S256' && p.get('response_type') === 'code', 'Invalid authorisation request'); + const code = randomBytes(24).toString('base64url'); + codes.set(code, { params: p, claims, headers }); + const callback = new URL(p.get('redirect_uri')); + callback.searchParams.set('state', p.get('state')); + callback.searchParams.set('code', code); + callback.searchParams.set('iss', issuer); + return callback; + } + async function fetchJson(url, options = {}) { + calls.push(url); + if (url.endsWith('/.well-known/openid-configuration')) return discovery; + if (url === discovery.jwks_uri) return { keys: pair.public_keys }; + ensure(url === discovery.token_endpoint, 'Unexpected simulator endpoint'); + const p = new URLSearchParams(options.body); + const code = codes.get(p.get('code')); + ensure(code, 'Code was already consumed or unknown'); + codes.delete(p.get('code')); + ensure(p.get('grant_type') === 'authorization_code' && p.get('client_assertion_type') === 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', 'Invalid token request'); + ensure(p.get('redirect_uri') === code.params.get('redirect_uri') && p.get('client_id') === code.params.get('client_id'), 'Client/callback mismatch'); + ensure(digest(p.get('code_verifier')) === code.params.get('code_challenge'), 'PKCE mismatch'); + const assertion = await jwtVerify(p.get('client_assertion'), createLocalJWKSet({ keys: deployment.public_keys }), { + algorithms: ['ES256'], issuer: p.get('client_id'), audience: discovery.token_endpoint, + subject: p.get('client_id'), requiredClaims: ['jti', 'iat', 'exp'], currentDate: new Date(clock() * 1000), + }); + ensure(assertion.payload.exp - assertion.payload.iat <= 60, 'Assertion lifetime too long'); + const t = clock(); + const token = await new SignJWT({ + iss: issuer, sub: 'demo-user', aud: p.get('client_id'), iat: t, exp: t + 300, + nonce: code.params.get('nonce'), email: 'reader@example.com', email_verified: true, ...code.claims, + }).setProtectedHeader({ alg: 'ES256', kid: signer.kid, ...code.headers }) + .sign(createPrivateKey({ key: signer, format: 'jwk' })); + return { id_token: token, access_token: 'discarded-simulator-access-token', token_type: 'Bearer' }; + } + return { authorise, fetchJson, calls, discovery, pair }; +} diff --git a/demo/server.mjs b/demo/server.mjs new file mode 100644 index 0000000..bc451b2 --- /dev/null +++ b/demo/server.mjs @@ -0,0 +1,54 @@ +import { createServer } from 'node:https'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { createHandler } from '../src/runtime.mjs'; +import { newKeys, prepare } from '../generator/package.mjs'; +import { simulatedProvider } from './provider.mjs'; + +export async function startDemo(port = 8443) { + const directory = await mkdtemp(join(tmpdir(), 'soca-demo-')); + let cert, key; + try { + execFileSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost', '-keyout', join(directory, 'key.pem'), '-out', join(directory, 'cert.pem')], { stdio: 'ignore' }); + cert = await readFile(join(directory, 'cert.pem')); + key = await readFile(join(directory, 'key.pem')); + } finally { await rm(directory, { recursive: true, force: true }); } + const origin = `https://localhost:${port}`; + const deployment = prepare({ origin, issuer: 'https://simulated-idp.example', enabled: true, allow_domains: ['example.com'], client_name: 'Local SOCA simulator' }, newKeys()); + const provider = simulatedProvider(deployment); + const handler = createHandler(deployment, { fetchJson: provider.fetchJson }); + const server = createServer({ cert, key }, async (req, res) => { + try { + const url = new URL(req.url, origin); + if (url.pathname === '/_demo/authorize') { + const callback = provider.authorise(url.href); + res.writeHead(303, { location: callback.href, 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }); + res.end(); + return; + } + const headers = Object.fromEntries(Object.entries(req.headers).map(([name, value]) => [name, [{ value: String(value) }]])); + const result = await handler({ Records: [{ cf: { config: { eventType: 'viewer-request' }, request: { method: req.method, uri: url.pathname, querystring: url.search.slice(1), headers } } }] }); + if (result.status) { + const out = Object.fromEntries(Object.entries(result.headers).map(([name, values]) => [name, values.map(v => v.value)])); + if (out.location?.[0]?.startsWith(deployment.config.issuer)) { + const location = new URL(out.location[0]); + out.location = [`${origin}/_demo/authorize${location.search}`]; + } + res.writeHead(Number(result.status), out); + res.end(req.method === 'HEAD' ? '' : result.body); + return; + } + res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }); + res.end('SOCA local demo

Protected static content

The simulated identity provider admitted reader@example.com. This is a local protocol simulation, not an AWS or real-provider deployment.

Sign out'); + } catch { res.writeHead(500); res.end('Demo failed'); } + }); + await new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, '0.0.0.0', resolve); }); + return { server, cert, origin }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + startDemo().then(({ origin }) => console.log(`Local simulation: ${origin} (ephemeral self-signed TLS certificate)`)).catch(() => { console.error('Cannot start demo; check port 8443 and openssl.'); process.exitCode = 1; }); +} diff --git a/docs/requirements.md b/docs/requirements.md new file mode 100644 index 0000000..d47a930 --- /dev/null +++ b/docs/requirements.md @@ -0,0 +1,54 @@ +# SOCA requirements assessment + +Target: [requirements at 60ea4db](https://github.com/RESOAuth/soca-plugins/blob/60ea4db827457b4a4a7b11d79e86b654612a75e1/requirements.md). +Assessed 22 October 2026 for MVP 0.1.0. This is a static-content gate without host +accounts or admin UI. Partial/planned rows remain target gaps. No AWS deployment +or real-provider login is claimed. + +Versioned evidence: [configuration](../src/config.mjs), [runtime](../src/runtime.mjs), +[network](../src/network.mjs), [generator](../generator/package.mjs), +[protocol tests](../tests/runtime.test.mjs), [package tests](../tests/package.test.mjs), +[transport tests](../tests/network.test.mjs), [HTTPS demo](../tests/demo.test.mjs), +[operations](security.md) and the deployment modules. + +| ID | Status | Evidence and remaining gap | +| --- | --- | --- | +| F-01 | Partial | Explicit issuer/capability validation and RESOAuth default; one profile, no enforced real-login activation. | +| F-02 | Partial | Code, S256 PKCE, state, nonce, exact callback, ES256 assertions; F-25 global replay gap. | +| F-03 | Partial | Signature, issuer, subject, audience/azp, nonce, times, response issuer, auth_time/acr/amr. ID-token-only claims; UserInfo reconciliation planned. | +| F-04 | Partial | Public HTTPS CIMD/JWKS, stable ID, branding fields and document check. Promotion/reachability operator-enforced. No host branding API. | +| F-05 | Partial | Default proxy, sorted JSON, URI indirection, preview/check and 4096 limit. Real proxy/provider tests and negotiated transport limits planned. | +| F-06 | Partial | Public-only JWKS/metadata; inline JWKS planned. | +| F-07 | Partial | Stable jwks_uri through overlap and configuration-bound transactions. Atomic replica revocation and identity migration tooling planned. | +| F-08 | Partial | Persistent P-256 keys, private package handling. User-selected exportable keys; external non-exportable signing and recovery tests planned. | +| F-09 | Planned | Manual overlap tested locally; unattended rotation, cache confirmation and atomic promotion absent. | +| F-10 | Partial | Fixed ES256/P-256 default; alternative algorithms/vectors planned. | +| F-11 | Partial | Five-minute caches, bounded refresh and fail-closed verification. Provider cache directives/revocation feeds planned. | +| F-12 | Partial | Deny default, boolean verified email, domain/wildcard validation and deny precedence. Policy preview/sensitive-account controls planned. | +| F-13 | Not applicable | S3 has no local account lookup or enabled-user API; issuer/subject plus admission controls access. | +| F-14 | Not applicable | No account provisioning/default credentials; requires an account-bearing host. | +| F-15 | Partial | Identity/admission separate from static read access; no escalation. Provider-side removal affects existing sessions at expiry. | +| F-16 | Not applicable | No local accounts to link; exact issuer/subject, never email-based ownership. | +| F-17 | Partial | No silent email relinking; config/security_epoch revokes cookies. Audited migration tooling planned. | +| F-18 | Planned | No profile writes; admission uses validated email. Mapping/preview absent. | +| F-19 | Planned | No claim diagnostics or retained reports. | +| F-20 | Partial | Headless settings/defaults/TTL override, repeatable builds, revision-bound document results and disabled packages. Candidate-only login, enforced activation evidence and audit absent. No host GUI. | +| F-21 | Partial | Safe return, absolute sessions, CSRF local logout and freshness settings. Individual/RP/back-channel revocation planned. | +| F-22 | Partial | AWS IAM recovery, disable and security_epoch. Edge propagation prevents instantaneous disable; live drill planned. | +| F-23 | Partial | Immutable versions, no host mutations, lifecycle/recovery documented. Live rolling upgrade/restore tests planned. | +| F-24 | Supported | Identity scopes only; discard code/access/ID token, no refresh/offline or delegated profile. | +| F-25 | Partial | Confidential, purpose-separated, expiring browser-bound cookies and parallel-tab cap. No platform store; true atomic global consume needs shared state. First-binding race documented. | +| N-01 | Partial | Maintained JOSE, fail-closed crypto, CSRF logout and source review. Independent security review planned. | +| N-02 | Partial | TLS tests, mixed DNS, pinning, 5-second/128-KiB bounds, no redirects. Restricted-egress/slow-network fault matrix planned. | +| N-03 | Partial | Minimal encrypted identity, no app logging/telemetry/token retention, boundary tests. External logging, backups/deletion and retention are operator duties. | +| N-04 | Partial | Stateless workers, overlap and revocation tested locally. No live failover, rotation, restore or propagation measurements. | +| N-05 | Partial | Local normal requests, bounded cookies/caches/network, 5-MiB ZIP budget. Distributed rates and sustained load tests planned; use deployment controls such as WAF. | +| N-06 | Partial | Semantic logout/error UI, no token dumps. Accessibility audit, redacted incident references, tamper-evident audit and metrics planned. | +| N-07 | Partial | AGPL, Node24, locks, pinned actions/image, CI/audit/SBOM/Dependabot. Signed releases/provenance and rollback evidence planned. | +| N-08 | Partial | Negative crypto/protocol tests, standalone ZIP, TLS transport, browser-like HTTPS roundtrip and container CI. No real browser/provider login, AWS deployment or conformance/independent review. | +| N-09 | Partial | All 34 IDs with versioned evidence/gaps; production gates/coverage automation planned. | + +The simulator validates ES256 code/PKCE/assertions and rejects reused codes. Public +RESOAuth discovery was fetched using the real transport and advertised ES256. +That is a discovery check, not a real CIMD login. Hosted/proxy live-provider tests, +AWS propagation and real browser coverage remain unperformed. diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 0000000..7383890 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,88 @@ +# Operations and threat model + +The resource is static content accessible to every admitted identity. Trust the +configured issuer, HTTPS/TLS, AWS IAM/control plane, CloudFront behaviours and +private deployment package. Keep S3 private and readable by the specific +distribution through OAC, not an S3 website endpoint. + +## Cryptography and network + +Client assertions use P-256/ES256 and expire in 60 seconds. ID tokens use the +trusted issuer's P-256 keys and ES256 only. JWT headers/discovery ordering cannot +enable another algorithm. State, nonce and PKCE verifier are independent random +values. Encrypted transaction cookies bind browser, issuer, client ID, callback, +configuration and safe return path. A separate encrypted cookie provides browser +binding; parallel tabs use independent state-named transaction cookies. Two +first-ever concurrent login starts without an established browser cookie can race; +retry the affected tab. + +Cookies use purpose-separated HKDF-SHA256 keys, AES-256-GCM with random 96-bit IVs, +authenticated context, `Secure`, `HttpOnly`, `SameSite=Lax`, host-only scope and +`Path=/`. No JavaScript storage. Sessions retain only issuer, subject, random ID, +times and policy revision. No access/refresh/ID tokens survive the callback. +Expiry is absolute and is not extended by activity. + +Outbound JSON requests require public HTTPS endpoints on port 443, verify TLS, +check every DNS answer, pin the address, reject redirects, disable pooling and +enforce a five-second total deadline and 128 KiB limit. Discovery/JWKS expire in +five minutes; refreshes coalesce, with unknown-key/signature refreshes limited to +once per 30 seconds per instance. Outages/expired trust fail closed. Shorter +provider cache directives and revocation feeds are not implemented yet. + +## Rotation and revocation + +Key files contain `signing_key` (active private JWK), `public_keys` (public +current/next/retiring JWKs) and `session_keys` (first encrypts; all decrypt). +Each keyring has at most three entries. `init` generates an independent key file; +there is no unattended rotation or automatic promotion command. Prepare a combined +file locally without printing its contents or replacing the production file. + +For signing rotation, add the next public key while retaining the old signer. +Deploy, check public documents, wait for full CloudFront propagation and the +provider's documented JWKS cache bound, then switch `signing_key`. Retain the old +public key through outstanding assertions/transactions plus cache/rollout bounds. +Stable `jwks_uri` preserves client IDs in hosted and proxy modes. + +For session rotation, add the next key **second**. Deploy and wait for all replicas, +then promote it to first and redeploy. Retain old decryption keys through the +longest session lifetime plus propagation. Retained keys decrypt across versions; +configuration changes invalidate cookies. Increment `security_epoch` to force +invalidation without an admission change. + +Operators coordinate these procedures; they are not atomic across replicas. +Do not claim zero interruption until a real rollout is tested. Emergency changes +apply as new versions propagate. Disabling the distribution through AWS IAM is +the recovery control for an urgent incident. + +Without shared replay state, deleting a cookie cannot provide atomic global single +use. The IdP must reject reused codes, but that is not complete F-25 compliance. +Concurrent captured callback replay and an issuer reissuing codes remain risks. +Transactions expire in five minutes by default. There is no individual denylist or +back-channel logout: a copied session remains valid until expiry, key removal or +policy change reaches its replica. Provider account revocation alone does not +invalidate an existing session. Default bound: 12 hours. + +## Recovery, retention and releases + +Local logout requires same-origin POST and does not contact the provider. It clears +browser cookies, without revoking stolen copies. Rebuild with `enabled=false`, +increment `security_epoch` and deploy to disable SSO. Keep AWS IAM recovery separate +from SOCA and test distribution disable/rollback before uploading content. Never +remove authentication while leaving private content publicly accessible. + +Back up keys/configuration in restricted encrypted storage. Lost session keys sign +everyone out; lost signing keys require replacement. Old ZIPs, S3 object versions, +Lambda versions and backups contain secrets after rotation. Restrict +`lambda:GetFunction`, source-object access and deployment roles. Delete obsolete +versions after replica cleanup. Do not restore revoked keys or an earlier security +epoch. The software does not perform remote deletion. + +There is no application logging or telemetry. Disable/redact cookie/query logging +at CloudFront and in external observability pipelines. AWS execution logging is +infrastructure-managed; configure its retention/IAM. Public documents expose site +identity and public keys, never admission policy. Never publish deployment ZIPs. + +Patch high/critical findings before release. CI pins dependencies/actions, audits +packages and scans with CodeQL. Signed release provenance, browser accessibility +testing, OIDC conformance and independent review are planned. Report security +issues through [private vulnerability reporting](https://github.com/RESOAuth/cloudfront-soca-plugin/security/advisories/new). diff --git a/examples/config.json b/examples/config.json new file mode 100644 index 0000000..4620798 --- /dev/null +++ b/examples/config.json @@ -0,0 +1,12 @@ +{ + "origin": "https://static.example.com", + "issuer": "https://auth.resoauth.cloud", + "enabled": false, + "client_name": "Example private documents", + "session_ttl_seconds": 43200, + "protected_paths": ["/"], + "public_paths": [], + "allow_domains": ["example.com"], + "deny_domains": [], + "metadata_mode": "hosted" +} diff --git a/examples/terraform/.terraform.lock.hcl b/examples/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..0d70912 --- /dev/null +++ b/examples/terraform/.terraform.lock.hcl @@ -0,0 +1,26 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.69.1" + constraints = "~> 6.0" + hashes = [ + "h1:j8OcftKysEw0hTrFA5FczfGrXOFGMyorSTEiQihUw4o=", + "zh:0ad1319a9fea21dacf084152e236cfd6c150ccc91854ad547c5ab9bc1cddad9a", + "zh:113d7ceaca21f0e4b84f45e69369263311512f858a402955f9e9a8a5bb7f3151", + "zh:1828581462a8a985361c2f4e9af90b2bd5b7d4603b00146bb23a88c5b7d50888", + "zh:28d454d8ac98a88903540bf17bf63d6935dd2e08e572e41152d06db926a5333a", + "zh:2a3b594a98fedc396a4eb5f0fd324e641f83db0906d0129c2ddeffd8002fbe86", + "zh:32c3103af70480b5c3be86ab00af2f46d3a2a6f269ddadf8c1e53a7a3ea0031b", + "zh:3df1dd01ec3a65291f51f26b4d28dcd1bf7b4c73ed0bd3ab1e94e1153ce9b13d", + "zh:42699fbd59bf14adb1cf2836c80c209b3ce815d252f4e983afc8defa754b1dfe", + "zh:5522afd762a1ee95e6ef0d7ad1f165185303a3039e45e1632a3cd13314b7a1a4", + "zh:69f3537ccb012cf24cc11af3cfc3b4be5602b4a3bfbaae2dcab78e41b40f280b", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:a0c5bf13ba5e17a993aab381603a32d6c9dc2ae8d9f982b6a8c6407b5d7c4a50", + "zh:b9f8a73e11e0b82ba51474b6a6eb4ac3080d7f268087162cb10884655878670a", + "zh:be1f9728404d67dee586d16b69a445931e5e4dafbf7b996df3a7eed519a557b0", + "zh:dc15fb3443312a42deb8b13f92c8d10a701e46eca0155f0709ad763057a85a1d", + "zh:e9f6567a13f21123838aaf78d94f76da8c8f7783eff7f7aa781fd1c21d18d86c", + ] +} diff --git a/examples/terraform/README.md b/examples/terraform/README.md new file mode 100644 index 0000000..c78c7af --- /dev/null +++ b/examples/terraform/README.md @@ -0,0 +1,19 @@ +# Private S3 example + +This example creates a private S3 REST origin, Origin Access Control and a CloudFront distribution with the SOCA viewer-request handler always attached. The distribution defaults to disabled. Nothing uploads content or creates public S3 access. + +When using an allocated `cloudfront.net` hostname: + +1. Generate a candidate ZIP using a placeholder HTTPS origin such as `https://example.invalid`, with `enabled=false` in the authentication configuration. Keep its keys for subsequent builds. +2. In this directory run `terraform init`, then `terraform apply -var='zip_path=/private/deployment.zip'`. Leave `enabled=false`. AWS allocates the distribution hostname while the distribution remains disabled. +3. Read `terraform output -raw origin`. Regenerate the ZIP for that exact origin using the same keys. Keep authentication `enabled=false` while checking public documents. +4. Apply the replacement ZIP and `-var='enabled=true'`. Wait until CloudFront finishes deployment. The handler now serves public metadata; protected content and login remain disabled. +5. Run the document check in the root README. Verify real allowed and denied logins on a separate staging distribution with authentication `enabled=true`, then build and deploy the enabled production package. Candidate-only tests and enforced activation evidence are not implemented. Verify that anonymous requests redirect, an approved login reaches content and disallowed identities are denied. Upload static files to `content_bucket` only; never put deployment ZIPs in that bucket. + +For a custom domain, provide both `domain_name` and an ACM certificate ARN from `us-east-1` through `acm_certificate_arn`. The certificate must cover that domain. Configure DNS to point the domain at `distribution_domain`. Build for the custom origin before enabling; requests to the alternate CloudFront hostname are rejected by the handler's canonical-host check. DNS and certificate issuance are deliberately outside this example. + +The example allows POST so logout can reach the handler; content accepts GET/HEAD only and the S3 policy grants CloudFront only `GetObject`. Cookies, query strings and viewer headers are excluded from the content cache key and forwarding to S3. All viewers therefore receive the same static object after their session is checked, including on cache hits. Do not use this cache configuration for personalised origin responses. + +Attach the viewer handler to every additional behaviour you create. Changes to a generated ZIP publish a new numbered function version and update the association. CloudFront rollout takes time; old versions and policy may remain active during propagation. Disable the distribution before recovery changes that remove authentication. + +To tear down, disable/remove the distribution and its associations first. Allow several hours for Lambda@Edge replicas to disappear, then remove the Lambda resources. An immediate `terraform destroy` may fail until AWS finishes replica cleanup. Bucket deletion requires that its content has been removed. diff --git a/examples/terraform/main.tf b/examples/terraform/main.tf new file mode 100644 index 0000000..a701b66 --- /dev/null +++ b/examples/terraform/main.tf @@ -0,0 +1,148 @@ +terraform { + required_version = ">= 1.5.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + } +} + +provider "aws" { + region = "us-east-1" +} + +module "soca" { + source = "../../terraform" + function_name = var.name + zip_path = var.zip_path +} + +resource "aws_s3_bucket" "content" { + bucket_prefix = "${var.name}-" +} + +resource "aws_s3_bucket_public_access_block" "content" { + bucket = aws_s3_bucket.content.id + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_ownership_controls" "content" { + bucket = aws_s3_bucket.content.id + rule { + object_ownership = "BucketOwnerEnforced" + } +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "content" { + bucket = aws_s3_bucket.content.id + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_cloudfront_origin_access_control" "content" { + name = var.name + origin_access_control_origin_type = "s3" + signing_behavior = "always" + signing_protocol = "sigv4" +} + +resource "aws_cloudfront_cache_policy" "content" { + name = "${var.name}-static" + min_ttl = 0 + default_ttl = 3600 + max_ttl = 86400 + + parameters_in_cache_key_and_forwarded_to_origin { + enable_accept_encoding_brotli = true + enable_accept_encoding_gzip = true + cookies_config { + cookie_behavior = "none" + } + headers_config { + header_behavior = "none" + } + query_strings_config { + query_string_behavior = "none" + } + } +} + +resource "aws_cloudfront_distribution" "content" { + enabled = var.enabled + default_root_object = "index.html" + aliases = var.domain_name == null ? [] : [var.domain_name] + is_ipv6_enabled = true + price_class = "PriceClass_100" + + origin { + domain_name = aws_s3_bucket.content.bucket_regional_domain_name + origin_id = "private-s3" + origin_access_control_id = aws_cloudfront_origin_access_control.content.id + } + + default_cache_behavior { + target_origin_id = "private-s3" + viewer_protocol_policy = "redirect-to-https" + allowed_methods = ["GET", "HEAD", "OPTIONS", "PUT", "PATCH", "POST", "DELETE"] + cached_methods = ["GET", "HEAD"] + compress = true + cache_policy_id = aws_cloudfront_cache_policy.content.id + + lambda_function_association { + event_type = "viewer-request" + lambda_arn = module.soca.version_arn + include_body = false + } + } + + restrictions { + geo_restriction { + restriction_type = "none" + } + } + + viewer_certificate { + cloudfront_default_certificate = var.domain_name == null + acm_certificate_arn = var.acm_certificate_arn + ssl_support_method = var.domain_name == null ? null : "sni-only" + minimum_protocol_version = var.domain_name == null ? "TLSv1" : "TLSv1.2_2021" + } + + lifecycle { + precondition { + condition = (var.domain_name == null) == (var.acm_certificate_arn == null) + error_message = "Supply both domain_name and its us-east-1 ACM certificate ARN, or neither." + } + } +} + +resource "aws_s3_bucket_policy" "content" { + bucket = aws_s3_bucket.content.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Sid = "CloudFrontReadOnly" + Effect = "Allow" + Principal = { Service = "cloudfront.amazonaws.com" } + Action = "s3:GetObject" + Resource = "${aws_s3_bucket.content.arn}/*" + Condition = { StringEquals = { "AWS:SourceArn" = aws_cloudfront_distribution.content.arn } } + }, { + Sid = "RequireTLS" + Effect = "Deny" + Principal = "*" + Action = "s3:*" + Resource = [aws_s3_bucket.content.arn, "${aws_s3_bucket.content.arn}/*"] + Condition = { Bool = { "aws:SecureTransport" = "false" } } + }] + }) + depends_on = [aws_s3_bucket_public_access_block.content] +} diff --git a/examples/terraform/outputs.tf b/examples/terraform/outputs.tf new file mode 100644 index 0000000..9cc3f4e --- /dev/null +++ b/examples/terraform/outputs.tf @@ -0,0 +1,22 @@ +output "origin" { + description = "Canonical HTTPS origin to put in the generator configuration." + value = "https://${var.domain_name == null ? aws_cloudfront_distribution.content.domain_name : var.domain_name}" +} + +output "distribution_domain" { + description = "Assigned CloudFront hostname, also the DNS alias target for a custom domain." + value = aws_cloudfront_distribution.content.domain_name +} + +output "distribution_id" { + value = aws_cloudfront_distribution.content.id +} + +output "content_bucket" { + description = "Private content bucket; upload only static website files, never deployment ZIPs." + value = aws_s3_bucket.content.id +} + +output "version_arn" { + value = module.soca.version_arn +} diff --git a/examples/terraform/variables.tf b/examples/terraform/variables.tf new file mode 100644 index 0000000..9128381 --- /dev/null +++ b/examples/terraform/variables.tf @@ -0,0 +1,33 @@ +variable "name" { + type = string + description = "Unique deployment name used for Lambda, bucket prefix and CloudFront resources." + default = "cloudfront-soca-example" + + validation { + condition = can(regex("^[a-z0-9][a-z0-9-]{1,35}[a-z0-9]$", var.name)) + error_message = "Use 3 to 37 lowercase letters, digits or hyphens, starting and ending with a letter or digit." + } +} + +variable "zip_path" { + type = string + description = "Absolute path to the private deployment ZIP. Build it before terraform plan." +} + +variable "enabled" { + type = bool + description = "Enable only after the ZIP contains this distribution's canonical HTTPS origin." + default = false +} + +variable "domain_name" { + type = string + description = "Optional canonical DNS name; otherwise use the assigned cloudfront.net hostname." + default = null +} + +variable "acm_certificate_arn" { + type = string + description = "ACM certificate in us-east-1 covering domain_name." + default = null +} diff --git a/generator/cli.mjs b/generator/cli.mjs new file mode 100644 index 0000000..a2d3ce9 --- /dev/null +++ b/generator/cli.mjs @@ -0,0 +1,42 @@ +#!/usr/bin/env node +import { documents, ensure, stable, SocaError } from '../src/config.mjs'; +import { requestJson } from '../src/network.mjs'; +import { validateDiscovery } from '../src/runtime.mjs'; +import { packageZip, readDeployment, saveNewKeys } from './package.mjs'; + +async function main() { + const [command, config, keys, output, ...extra] = process.argv.slice(2); + ensure(extra.length === 0, 'Too many arguments'); + if (command === 'init') { + ensure(config && !keys && !output, 'Usage: init '); + await saveNewKeys(config); + console.log('Created private keys. Keep this file out of Git and reuse it for subsequent builds.'); + return; + } + ensure(['build', 'preview', 'check'].includes(command) && config && keys, 'Usage: init | build | preview/check '); + ensure(command === 'build' ? !!output : !output, 'Unexpected or missing output path'); + const deployment = await readDeployment(config, keys, process.env); + const docs = documents(deployment.config, deployment.public_keys); + if (command === 'build') { + console.log(JSON.stringify(await packageZip(deployment, output))); + console.log('Private deployment ZIP created. Do not publish it as a release or CI artefact.'); + return; + } + if (command === 'preview') { + console.log(JSON.stringify({ revision: deployment.revision, session_ttl_seconds: deployment.config.session_ttl_seconds, ...docs }, null, 2)); + return; + } + const [metadata, jwks, discovery] = await Promise.all([ + requestJson(docs.client_id), requestJson(docs.metadata.jwks_uri), + requestJson(`${deployment.config.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`), + ]); + ensure(stable(metadata) === stable(docs.metadata) && stable(jwks) === stable(docs.jwks), 'Published documents differ from this deployment'); + validateDiscovery(discovery, deployment.config); + console.log(JSON.stringify({ document_check: 'passed', revision: deployment.revision, cimd: discovery.client_id_metadata_document_supported === true ? 'advertised' : 'unconfirmed', real_login: 'not tested' })); +} + +main().catch(error => { + const reason = error instanceof SocaError ? error.message : error.code === 'EEXIST' ? 'Output exists. Use a new path; existing keys and packages are never overwritten.' : 'Check JSON, key files and public HTTPS endpoints.'; + console.error(`SOCA command failed: ${reason}`); + process.exitCode = 1; +}); diff --git a/generator/package.mjs b/generator/package.mjs new file mode 100644 index 0000000..4408918 --- /dev/null +++ b/generator/package.mjs @@ -0,0 +1,72 @@ +import { createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto'; +import { readFile, writeFile, mkdir } from 'node:fs/promises'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; +import { strToU8, zipSync } from 'fflate'; +import { digest, documents, ensure, normalise, stable } from '../src/config.mjs'; + +export function publicKey(jwk) { + const key = createPublicKey(createPrivateKey({ key: jwk, format: 'jwk' })).export({ format: 'jwk' }); + ensure(key.kty === 'EC' && key.crv === 'P-256', 'Only P-256 signing keys are supported'); + return { kty: key.kty, crv: key.crv, x: key.x, y: key.y, kid: digest(key), use: 'sig', alg: 'ES256' }; +} + +export function newKeys() { + const pair = generateKeyPairSync('ec', { namedCurve: 'prime256v1' }); + const signing = pair.privateKey.export({ format: 'jwk' }); + const pub = publicKey(signing); + return { signing_key: { ...signing, kid: pub.kid, alg: 'ES256' }, public_keys: [pub], session_keys: [{ kid: randomBytes(12).toString('base64url'), key: randomBytes(32).toString('base64url') }] }; +} + +export function prepare(config, keys, env = {}) { + const override = env.SOCA_SESSION_TTL_SECONDS; + const c = normalise({ ...config, ...(override === undefined ? {} : { session_ttl_seconds: Number(override) }) }); + const pub = publicKey(keys.signing_key); + ensure(keys.signing_key.kid === pub.kid && keys.signing_key.alg === 'ES256', 'Signing key metadata does not match its material'); + ensure(Array.isArray(keys.public_keys) && keys.public_keys.length > 0 && keys.public_keys.length <= 3, 'Invalid public signing keyring'); + ensure(keys.public_keys.some(k => stable(k) === stable(pub)), 'Active signing key is missing from JWKS'); + for (const key of keys.public_keys) { + ensure(Object.keys(key).every(k => ['kty', 'crv', 'x', 'y', 'kid', 'use', 'alg'].includes(k)), 'Public JWKS contains forbidden fields'); + ensure(key.kty === 'EC' && key.crv === 'P-256' && key.alg === 'ES256' && key.use === 'sig', 'Invalid public key'); + ensure(typeof key.kid === 'string' && key.kid.length <= 64, 'Invalid signing key ID'); + createPublicKey({ key, format: 'jwk' }); + } + ensure(new Set(keys.public_keys.map(k => k.kid)).size === keys.public_keys.length, 'Duplicate signing key ID'); + ensure(Array.isArray(keys.session_keys) && keys.session_keys.length > 0 && keys.session_keys.length <= 3, 'Invalid session keyring'); + for (const k of keys.session_keys) ensure(/^[A-Za-z0-9_-]{8,64}$/.test(k.kid) && /^[A-Za-z0-9_-]{43}$/.test(k.key) && Buffer.from(k.key, 'base64url').length === 32, 'Session keys must be 32-byte base64url values'); + ensure(new Set(keys.session_keys.map(k => k.kid)).size === keys.session_keys.length, 'Duplicate session key ID'); + const deployment = { config: c, signing_key: keys.signing_key, public_keys: keys.public_keys, session_keys: keys.session_keys }; + deployment.revision = digest({ config: c, public_keys: keys.public_keys, session_ids: keys.session_keys.map(k => k.kid) }); + documents(c, keys.public_keys); + return deployment; +} + +export async function saveNewKeys(path) { + await mkdir(dirname(resolve(path)), { recursive: true, mode: 0o700 }); + await writeFile(path, `${JSON.stringify(newKeys(), null, 2)}\n`, { mode: 0o600, flag: 'wx' }); +} + +export async function readDeployment(configPath, keyPath, env = {}) { + return prepare(JSON.parse(await readFile(configPath, 'utf8')), JSON.parse(await readFile(keyPath, 'utf8')), env); +} + +export async function packageZip(deployment, output) { + const root = fileURLToPath(new URL('../', import.meta.url)); + const result = await build({ + stdin: { contents: `import { readFileSync } from 'node:fs'; import { createHandler } from './src/runtime.mjs'; const deployment = JSON.parse(readFileSync(new URL('./deployment.json', import.meta.url), 'utf8')); export const handler = createHandler(deployment);`, resolveDir: root }, + bundle: true, platform: 'node', target: 'node24', format: 'esm', write: false, minify: true, legalComments: 'eof', + }); + // Fixed timestamps make identical source/config/keys produce identical archives. + const options = { mtime: new Date('2020-01-01T00:00:00Z'), os: 3, attrs: 0o100644 << 16 }; + const archive = zipSync({ + 'index.mjs': [result.outputFiles[0].contents, options], + 'deployment.json': [strToU8(stable(deployment)), options], + 'LICENSE': [new Uint8Array(await readFile(new URL('../LICENSE', import.meta.url))), options], + }, { level: 9 }); + ensure(archive.length < 5 * 1024 * 1024, 'Deployment ZIP exceeds the MVP size budget'); + await mkdir(dirname(resolve(output)), { recursive: true, mode: 0o700 }); + // Exclusive create prevents overwriting a symlink or weakening an existing file's mode. + await writeFile(output, archive, { mode: 0o600, flag: 'wx' }); + return { bytes: archive.length, revision: deployment.revision }; +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..d55eb39 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,533 @@ +{ + "name": "@resoauth/cloudfront-soca-plugin", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@resoauth/cloudfront-soca-plugin", + "version": "0.1.0", + "license": "AGPL-3.0-only", + "dependencies": { + "ipaddr.js": "2.5.0", + "jose": "6.2.13" + }, + "devDependencies": { + "esbuild": "0.28.2", + "fflate": "0.8.3" + }, + "engines": { + "node": ">=24 <25" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, + "node_modules/ipaddr.js": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/jose": { + "version": "6.2.13", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz", + "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e3b9c82 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "@resoauth/cloudfront-soca-plugin", + "version": "0.1.0", + "private": true, + "type": "module", + "description": "Self-contained SOCA authentication for CloudFront and private S3 content", + "license": "AGPL-3.0-only", + "engines": { "node": ">=24 <25" }, + "scripts": { + "test": "node --test tests/*.test.mjs", + "soca": "node generator/cli.mjs", + "demo": "node demo/server.mjs", + "check": "node --check src/runtime.mjs && node --check src/config.mjs && node --check src/network.mjs && node --check generator/cli.mjs" + }, + "dependencies": { + "ipaddr.js": "2.5.0", + "jose": "6.2.13" + }, + "devDependencies": { + "esbuild": "0.28.2", + "fflate": "0.8.3" + } +} diff --git a/src/config.mjs b/src/config.mjs new file mode 100644 index 0000000..4ab5441 --- /dev/null +++ b/src/config.mjs @@ -0,0 +1,121 @@ +import { createHash } from 'node:crypto'; + +export const DEFAULT_PROXY = 'https://dynamic-cimd.resoauth.cloud/cimd/%s'; +export const DEFAULTS = Object.freeze({ + issuer: 'https://auth.resoauth.cloud', enabled: false, security_epoch: 0, + session_ttl_seconds: 43200, transaction_ttl_seconds: 300, + auth_path: '/_soca', protected_paths: ['/'], public_paths: [], + allow_domains: [], deny_domains: [], allow_emails: [], deny_emails: [], + metadata_mode: 'hosted', proxy_template: DEFAULT_PROXY, + client_name: 'SOCA static content', scopes: ['openid', 'email'], + max_age_seconds: null, required_acr: [], required_amr: [], +}); + +export class SocaError extends Error {} + +export function ensure(condition, message) { + if (!condition) throw new SocaError(message); +} + +export function stable(value) { + if (Array.isArray(value)) return `[${value.map(stable).join(',')}]`; + if (value && typeof value === 'object') return `{${Object.keys(value).sort().map(k => `${JSON.stringify(k)}:${stable(value[k])}`).join(',')}}`; + return JSON.stringify(value); +} + +export function digest(value) { + return createHash('sha256').update(typeof value === 'string' ? value : stable(value)).digest('base64url'); +} + +export function httpsUrl(value) { + ensure(typeof value === 'string' && value.length <= 4096, 'Invalid HTTPS URL'); + const u = new URL(value); + ensure(u.protocol === 'https:' && !u.username && !u.password && !u.hash, 'HTTPS URL must not contain credentials or a fragment'); + ensure(!/[\u0000-\u0020\\]/u.test(value), 'Invalid URL characters'); + return u; +} + +export function canonicalPath(value) { + ensure(typeof value === 'string' && value.length <= 4096 && value.startsWith('/') && !value.startsWith('//'), 'Invalid path'); + // Reject ambiguous representations instead of guessing what S3 will serve. + ensure(!/[\\?#\u0000-\u0020\u007f]/u.test(value) && !/%(?:2f|5c|25|00|3f|23)/i.test(value), 'Ambiguous path'); + const decoded = decodeURIComponent(value); + ensure(!/[\\?#\u0000-\u0020\u007f]/u.test(decoded) && !decoded.includes('//'), 'Ambiguous path'); + ensure(!decoded.split('/').some(p => p === '.' || p === '..'), 'Dot segments are forbidden'); + return decoded; +} + +export function matches(path, prefix) { + return prefix === '/' || path === prefix || path.startsWith(`${prefix}/`); +} + +function domain(value, wildcard = true) { + ensure(typeof value === 'string', 'Domain rules must be strings'); + const d = value.toLowerCase(); + const plain = wildcard && d.startsWith('*.') ? d.slice(2) : d; + ensure(plain.length <= 253 && plain.includes('.') && plain.split('.').every(l => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(l)), 'Invalid domain rule'); + return d; +} + +function email(value) { + ensure(typeof value === 'string' && value.length <= 254 && /^[^\s@]+@[^\s@]+$/.test(value), 'Invalid email'); + const [local, host] = value.split('@'); + return `${local.toLowerCase()}@${domain(host, false)}`; +} + +export function normalise(input) { + const extra = ['origin', 'client_uri', 'logo_uri', 'policy_uri', 'tos_uri']; + ensure(input && typeof input === 'object' && !Array.isArray(input), 'Configuration must be an object'); + for (const k of Object.keys(input)) ensure(Object.hasOwn(DEFAULTS, k) || extra.includes(k), `Unknown setting: ${k}`); + const c = { ...DEFAULTS, ...input }; + const origin = httpsUrl(c.origin); + ensure(c.origin === origin.origin, 'origin must be a canonical HTTPS origin without a path or trailing slash'); + const issuer = httpsUrl(c.issuer); + ensure(!issuer.search, 'Issuer cannot contain a query'); + ensure(typeof c.enabled === 'boolean', 'enabled must be boolean'); + ensure(Number.isSafeInteger(c.security_epoch) && c.security_epoch >= 0, 'Invalid security_epoch'); + for (const [k, max] of [['session_ttl_seconds', 604800], ['transaction_ttl_seconds', 600]]) ensure(Number.isSafeInteger(c[k]) && c[k] > 0 && c[k] <= max, `Invalid ${k}`); + ensure(c.max_age_seconds === null || (Number.isSafeInteger(c.max_age_seconds) && c.max_age_seconds >= 0 && c.max_age_seconds <= 86400), 'Invalid max_age_seconds'); + ensure(canonicalPath(c.auth_path) === c.auth_path && c.auth_path !== '/' && !c.auth_path.endsWith('/') && /^[a-zA-Z0-9/_-]+$/.test(c.auth_path), 'Invalid auth_path'); + for (const k of ['protected_paths', 'public_paths']) { + ensure(Array.isArray(c[k]) && c[k].length <= 100, `Invalid ${k}`); + c[k] = c[k].map(p => { ensure(canonicalPath(p) === p && (p === '/' || !p.endsWith('/')), 'Use literal paths without trailing slashes'); return p; }); + } + ensure(c.protected_paths.length > 0, 'At least one protected path is required'); + for (const k of ['allow_domains', 'deny_domains', 'allow_emails', 'deny_emails', 'required_acr', 'required_amr', 'scopes']) ensure(Array.isArray(c[k]) && c[k].length <= 100, `Invalid ${k}`); + for (const k of ['allow_domains', 'deny_domains']) c[k] = c[k].map(v => domain(v)); + for (const k of ['allow_emails', 'deny_emails']) c[k] = c[k].map(email); + for (const k of ['required_acr', 'required_amr', 'scopes']) ensure(c[k].every(v => typeof v === 'string' && v.length > 0 && v.length <= 100 && !/\s/.test(v)), `Invalid ${k}`); + ensure(c.scopes.includes('openid') && c.scopes.every(v => ['openid', 'email', 'profile'].includes(v)), 'Only identity scopes are supported'); + ensure(typeof c.client_name === 'string' && c.client_name.length > 0 && c.client_name.length <= 128 && !/[\u0000-\u001f]/u.test(c.client_name), 'Invalid client_name'); + for (const k of extra.slice(1)) if (c[k] !== undefined) httpsUrl(c[k]); + ensure(['hosted', 'proxy'].includes(c.metadata_mode), 'Invalid metadata_mode'); + ensure(typeof c.proxy_template === 'string' && c.proxy_template.split('%s').length === 2, 'Proxy template needs exactly one %s'); + const proxy = httpsUrl(c.proxy_template.replace('%s', 'payload')); + ensure(!proxy.search && c.proxy_template.indexOf('%s') > c.proxy_template.indexOf('/', 8), 'Proxy placeholder must be in the HTTPS path'); + return c; +} + +export function documents(config, publicKeys) { + const base = `${config.origin}${config.auth_path}`; + const body = { + client_name: config.client_name, client_uri: config.client_uri ?? config.origin, + redirect_uris: [`${base}/callback`], grant_types: ['authorization_code'], response_types: ['code'], + token_endpoint_auth_method: 'private_key_jwt', token_endpoint_auth_signing_alg: 'ES256', + id_token_signed_response_alg: 'ES256', jwks_uri: `${base}/jwks.json`, + }; + for (const k of ['logo_uri', 'policy_uri', 'tos_uri']) if (config[k]) body[k] = config[k]; + const clientId = config.metadata_mode === 'hosted' ? `${base}/client.json` : config.proxy_template.replace('%s', Buffer.from(stable(body)).toString('base64url')); + ensure(clientId.length <= 4096, 'Client metadata URL exceeds 4096 bytes'); + return { client_id: clientId, metadata: { ...body, client_id: clientId }, jwks: { keys: publicKeys } }; +} + +export function admitted(c, claims) { + if (claims.email_verified !== true || typeof claims.email !== 'string') return false; + let e; + try { e = email(claims.email); } catch { return false; } + const host = e.split('@')[1]; + const match = rule => rule.startsWith('*.') ? host.endsWith(`.${rule.slice(2)}`) : host === rule; + if (c.deny_emails.includes(e) || c.deny_domains.some(match)) return false; + return c.allow_emails.includes(e) || c.allow_domains.some(match); +} diff --git a/src/network.mjs b/src/network.mjs new file mode 100644 index 0000000..b0245ff --- /dev/null +++ b/src/network.mjs @@ -0,0 +1,55 @@ +import { lookup } from 'node:dns/promises'; +import { request } from 'node:https'; +import ipaddr from 'ipaddr.js'; +import { ensure, httpsUrl } from './config.mjs'; + +export function publicAddress(address) { + try { return ipaddr.process(address).range() === 'unicast'; } catch { return false; } +} + +export async function resolvePublic(hostname, resolver = lookup) { + const records = await resolver(hostname.replace(/^\[|\]$/g, ''), { all: true, verbatim: true }); + ensure(records.length > 0 && records.every(r => publicAddress(r.address)), 'Endpoint DNS must resolve only to public addresses'); + return records[0]; +} + +// No redirects, pooled sockets, proxy environment variables or unpinned DNS lookup. +export async function requestJson(value, { body } = {}, { resolveEndpoint = resolvePublic, send = request } = {}) { + const url = httpsUrl(value); + ensure(!url.port || url.port === '443', 'Outbound HTTPS uses port 443 only'); + const signal = AbortSignal.timeout(5000); + const resolved = await Promise.race([ + resolveEndpoint(url.hostname), + new Promise((_, reject) => signal.addEventListener('abort', () => reject(new Error('Network deadline')), { once: true })), + ]); + return new Promise((resolve, reject) => { + const req = send(url, { + method: body === undefined ? 'GET' : 'POST', agent: false, signal, + lookup: (_host, options, cb) => options.all ? cb(null, [resolved]) : cb(null, resolved.address, resolved.family), + headers: { + accept: 'application/json', 'accept-encoding': 'identity', + ...(body === undefined ? {} : { 'content-type': 'application/x-www-form-urlencoded', 'content-length': Buffer.byteLength(body) }), + }, + }, res => { + let size = 0; + const chunks = []; + res.on('data', chunk => { + size += chunk.length; + if (size > 131072) res.destroy(new Error('Response too large')); + else chunks.push(chunk); + }); + res.on('error', reject); + res.on('end', () => { + try { + ensure(res.statusCode === 200, 'Remote endpoint did not return 200'); + ensure(/^application\/(?:[a-z0-9.+-]+\+)?json(?:;|$)/i.test(res.headers['content-type'] ?? ''), 'Expected JSON content type'); + const data = JSON.parse(Buffer.concat(chunks).toString('utf8')); + ensure(data && typeof data === 'object' && !Array.isArray(data), 'Expected JSON object'); + resolve(data); + } catch (error) { reject(error); } + }); + }); + req.on('error', reject); + req.end(body); + }); +} diff --git a/src/runtime.mjs b/src/runtime.mjs new file mode 100644 index 0000000..f5d905b --- /dev/null +++ b/src/runtime.mjs @@ -0,0 +1,281 @@ +import { createCipheriv, createDecipheriv, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto'; +import { SignJWT, createLocalJWKSet, importJWK, jwtVerify } from 'jose'; +import { admitted, canonicalPath, digest, documents, ensure, httpsUrl, matches, normalise } from './config.mjs'; +import { requestJson } from './network.mjs'; + +const SESSION = '__Host-soca_session'; +const BROWSER = '__Host-soca_browser'; +const TX = '__Host-soca_tx_'; +const random = () => randomBytes(32).toString('base64url'); +const equal = (a, b) => typeof a === 'string' && typeof b === 'string' && a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b)); + +function response(status, body = '', extra = {}, type = 'text/plain; charset=utf-8') { + const headers = { + 'content-type': [{ value: type }], 'cache-control': [{ value: 'no-store' }], + 'referrer-policy': [{ value: 'no-referrer' }], 'x-content-type-options': [{ value: 'nosniff' }], + 'content-security-policy': [{ value: "default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" }], + }; + for (const [name, value] of Object.entries(extra)) headers[name] = Array.isArray(value) ? value.map(v => ({ value: v })) : [{ value }]; + return { status: String(status), headers, body }; +} + +function cookie(name, value, age) { + ensure(value.length <= 3800, 'Cookie exceeds size limit'); + return `${name}=${value}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Lax`; +} + +function cookies(request) { + const raw = (request.headers.cookie ?? []).map(h => h.value).join(';'); + ensure(raw.length <= 16384, 'Cookie headers too large'); + const result = Object.create(null); + for (const part of raw.split(';')) { + const i = part.indexOf('='); + if (i < 0) continue; + const name = part.slice(0, i).trim(); + if (!name.startsWith('__Host-soca_')) continue; + ensure(!Object.hasOwn(result, name), 'Duplicate authentication cookie'); + result[name] = part.slice(i + 1).trim(); + } + return result; +} + +function params(query) { + ensure(typeof query === 'string' && query.length <= 8192, 'Query too large'); + const p = new URLSearchParams(query); + ensure([...p.keys()].every(k => p.getAll(k).length === 1), 'Duplicate query parameter'); + return p; +} + +function safeReturn(value, c) { + ensure(typeof value === 'string' && value.length <= 4096, 'Invalid return URL'); + const path = canonicalPath(value.split('?')[0]); + ensure(!matches(path, c.auth_path), 'Cannot return to authentication endpoints'); + const url = new URL(value, c.origin); + ensure(url.origin === c.origin && !url.hash, 'Invalid return URL'); + return value; +} + +export function validateDiscovery(d, c) { + ensure(d.issuer === c.issuer, 'Discovery issuer mismatch'); + for (const k of ['authorization_endpoint', 'token_endpoint', 'jwks_uri']) httpsUrl(d[k]); + for (const [k, v] of Object.entries({ + response_types_supported: 'code', code_challenge_methods_supported: 'S256', + token_endpoint_auth_methods_supported: 'private_key_jwt', + token_endpoint_auth_signing_alg_values_supported: 'ES256', id_token_signing_alg_values_supported: 'ES256', + })) ensure(Array.isArray(d[k]) && d[k].includes(v), `Provider lacks ${v}`); + ensure(!Object.hasOwn(d, 'client_id_metadata_document_supported') || d.client_id_metadata_document_supported === true, 'Provider explicitly rejects CIMD'); + return d; +} + +function validateJwks(data) { + ensure(Array.isArray(data.keys) && data.keys.length > 0 && data.keys.length <= 50, 'Invalid provider JWKS'); + ensure(data.keys.every(k => !['d', 'p', 'q', 'k'].some(name => Object.hasOwn(k, name))), 'Provider returned private key material'); + const keys = data.keys.filter(k => k.kty === 'EC' && k.crv === 'P-256' && (!k.alg || k.alg === 'ES256') && (!k.use || k.use === 'sig') && (!k.key_ops || k.key_ops.includes('verify'))); + ensure(keys.length > 0, 'Provider has no ES256 verification key'); + return createLocalJWKSet({ keys }); +} + +export function createHandler(deployment, { fetchJson = requestJson, now = () => Math.floor(Date.now() / 1000) } = {}) { + const c = normalise(deployment.config); + const docs = documents(c, deployment.public_keys); + const revision = digest({ config: c, public_keys: deployment.public_keys, session_ids: deployment.session_keys.map(k => k.kid) }); + ensure(revision === deployment.revision, 'Deployment revision mismatch'); + // Routine key overlap preserves cookies; configuration/security_epoch changes revoke them. + const cookieRevision = digest({ config: c, client_id: docs.client_id }); + ensure(deployment.session_keys.length > 0 && deployment.session_keys.length <= 3, 'Invalid session keyring'); + const sessionKeys = new Map(deployment.session_keys.map(k => { + ensure(/^[a-zA-Z0-9_-]{8,64}$/.test(k.kid) && /^[a-zA-Z0-9_-]{43}$/.test(k.key), 'Invalid session key'); + return [k.kid, Buffer.from(k.key, 'base64url')]; + })); + const signer = importJWK(deployment.signing_key, 'ES256'); + let discovery; + let keyCache; + let keyRefreshAt = 0; + let discoveryPending; + let keysPending; + + function seal(value, purpose) { + const { kid } = deployment.session_keys[0]; + const key = Buffer.from(hkdfSync('sha256', sessionKeys.get(kid), c.origin, purpose, 32)); + const iv = randomBytes(12); + const cipher = createCipheriv('aes-256-gcm', key, iv); + cipher.setAAD(Buffer.from(`soca:v1:${c.origin}:${purpose}`)); + const encrypted = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]); + return [kid, iv.toString('base64url'), encrypted.toString('base64url'), cipher.getAuthTag().toString('base64url')].join('.'); + } + + function open(value, purpose) { + try { + ensure(typeof value === 'string' && value.length <= 3800 && /^[a-zA-Z0-9_.-]+$/.test(value), 'Invalid cookie'); + const [kid, iv, encrypted, tag, extra] = value.split('.'); + ensure(!extra && sessionKeys.has(kid), 'Unknown cookie key'); + const key = Buffer.from(hkdfSync('sha256', sessionKeys.get(kid), c.origin, purpose, 32)); + ensure(Buffer.from(iv, 'base64url').length === 12 && Buffer.from(tag, 'base64url').length === 16, 'Invalid cookie encoding'); + const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64url')); + decipher.setAAD(Buffer.from(`soca:v1:${c.origin}:${purpose}`)); + decipher.setAuthTag(Buffer.from(tag, 'base64url')); + const v = JSON.parse(Buffer.concat([decipher.update(Buffer.from(encrypted, 'base64url')), decipher.final()]).toString('utf8')); + ensure(Number.isSafeInteger(v.exp) && v.exp > now() && Number.isSafeInteger(v.iat) && v.iat <= now() + 30 && v.iat <= v.exp && v.revision === cookieRevision, 'Expired or obsolete cookie'); + ensure(v.exp - v.iat <= (purpose === 'session' ? c.session_ttl_seconds : c.transaction_ttl_seconds), 'Cookie lifetime exceeds policy'); + return v; + } catch { return null; } + } + + async function provider() { + if (discovery?.exp > now()) return discovery.value; + if (!discoveryPending) discoveryPending = (async () => { + const value = validateDiscovery(await fetchJson(`${c.issuer.replace(/\/$/, '')}/.well-known/openid-configuration`), c); + discovery = { value, exp: now() + 300 }; + return value; + })().finally(() => { discoveryPending = undefined; }); + return discoveryPending; + } + + async function verificationKeys(d, refresh = false) { + if (keyCache?.uri === d.jwks_uri && keyCache.exp > now() && !refresh) return keyCache.value; + ensure(!refresh || now() >= keyRefreshAt, 'Provider key refresh rate exceeded'); + if (!keysPending) { + keyRefreshAt = now() + 30; + keysPending = (async () => { + const value = validateJwks(await fetchJson(d.jwks_uri)); + keyCache = { value, uri: d.jwks_uri, exp: now() + 300 }; + return value; + })().finally(() => { keysPending = undefined; }); + } + return keysPending; + } + + async function verifyIdentity(token, d, tx) { + ensure(typeof token === 'string' && token.length <= 32768, 'Invalid ID token'); + const options = { + issuer: c.issuer, audience: docs.client_id, algorithms: ['ES256'], + requiredClaims: ['iss', 'sub', 'aud', 'iat', 'exp', 'nonce'], + clockTolerance: 30, currentDate: new Date(now() * 1000), maxTokenAge: '10m', + }; + let result; + try { result = await jwtVerify(token, await verificationKeys(d), options); } + catch (error) { + if (!['ERR_JWKS_NO_MATCHING_KEY', 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED'].includes(error.code)) throw error; + result = await jwtVerify(token, await verificationKeys(d, true), options); + } + const p = result.payload; + ensure(typeof p.sub === 'string' && p.sub.length > 0 && p.sub.length <= 255, 'Invalid subject'); + ensure(equal(p.nonce, tx.nonce), 'Nonce mismatch'); + ensure((!Array.isArray(p.aud) || p.aud.length === 1 || p.azp === docs.client_id) && (p.azp === undefined || p.azp === docs.client_id), 'Invalid authorised party'); + for (const k of ['iat', 'exp', 'nbf', 'auth_time']) if (p[k] !== undefined) ensure(Number.isSafeInteger(p[k]), 'Invalid token time'); + ensure(p.exp > p.iat && p.iat <= now() + 30, 'Invalid token lifetime'); + if (c.max_age_seconds !== null) ensure(Number.isSafeInteger(p.auth_time) && p.auth_time <= now() + 30 && now() - p.auth_time <= c.max_age_seconds + 30, 'Fresh authentication required'); + if (c.required_acr.length) ensure(c.required_acr.includes(p.acr), 'Required assurance missing'); + if (c.required_amr.length) ensure(Array.isArray(p.amr) && p.amr.every(v => typeof v === 'string') && c.required_amr.every(v => p.amr.includes(v)), 'Required authentication method missing'); + // No UserInfo fetch: admission uses only the validated ID token. + ensure(admitted(c, p), 'Admission denied'); + return p; + } + + function forward(request) { + // Neither credentials nor callback query strings become S3/cache metadata. + if (request.headers.cookie) { + const kept = request.headers.cookie.flatMap(h => h.value.split(';')).filter(p => !p.trim().startsWith('__Host-soca_')).join(';'); + if (kept) request.headers.cookie = [{ key: 'Cookie', value: kept }]; + else delete request.headers.cookie; + } + delete request.headers.authorization; + return request; + } + + return async event => { + let clear = []; + try { + const request = event.Records?.[0]?.cf?.request; + ensure(request && event.Records[0].cf.config.eventType === 'viewer-request', 'Expected viewer-request event'); + ensure(request.headers.host?.length === 1 && request.headers.host[0].value === new URL(c.origin).host, 'Unexpected host'); + const path = canonicalPath(request.uri); + const auth = matches(path, c.auth_path); + const method = request.method; + if (path === `${c.auth_path}/client.json` || path === `${c.auth_path}/jwks.json`) { + if (!['GET', 'HEAD'].includes(method)) return response(405, 'Method not allowed'); + const body = path.endsWith('/client.json') ? docs.metadata : docs.jwks; + return response(200, method === 'HEAD' ? '' : stableJson(body), { 'cache-control': 'public, max-age=60' }, 'application/json'); + } + if (path === `${c.auth_path}/logout`) { + if (method === 'GET') return response(200, 'Sign out

Sign out

', {}, 'text/html; charset=utf-8'); + if (method !== 'POST' || request.headers.origin?.length !== 1 || request.headers.origin[0].value !== c.origin) return response(403, 'Sign-out requires a same-origin form submission'); + const jar = cookies(request); + const names = [SESSION, BROWSER, ...Object.keys(jar).filter(k => k.startsWith(TX))]; + return response(200, 'You have signed out. You may close this tab.', { 'set-cookie': names.map(k => cookie(k, '', 0)) }); + } + if (auth && ![`${c.auth_path}/login`, `${c.auth_path}/callback`].includes(path)) return response(404, 'Not found'); + const protectedPath = auth || (c.protected_paths.some(p => matches(path, p)) && !c.public_paths.some(p => matches(path, p))); + if (!protectedPath) return forward(request); + if (!['GET', 'HEAD'].includes(method)) return response(405, 'Only GET and HEAD are supported'); + if (!c.enabled) return response(503, 'SOCA sign-in is disabled. Contact the site operator.'); + const jar = cookies(request); + + if (path === `${c.auth_path}/callback`) { + ensure(method === 'GET', 'Callback must use GET'); + const q = params(request.querystring); + const state = q.get('state'); + ensure(typeof state === 'string' && /^[A-Za-z0-9_-]{43}$/.test(state), 'Invalid state'); + const txName = `${TX}${state}`; + clear = [cookie(txName, '', 0)]; + const tx = open(jar[txName], 'transaction'); + const binding = open(jar[BROWSER], 'browser'); + ensure(tx && binding && equal(tx.binding, binding.id) && equal(state, tx.state), 'Transaction/browser binding failed'); + ensure(tx.issuer === c.issuer && tx.client_id === docs.client_id && tx.callback === docs.metadata.redirect_uris[0], 'Transaction profile mismatch'); + ensure(!q.has('error') && typeof q.get('code') === 'string' && q.get('code').length > 0 && q.get('code').length <= 4096, 'Authorisation failed'); + const d = await provider(); + ensure((!q.has('iss') || q.get('iss') === c.issuer) && (d.authorization_response_iss_parameter_supported !== true || q.get('iss') === c.issuer), 'Response issuer mismatch'); + const at = now(); + const assertion = await new SignJWT({}).setProtectedHeader({ alg: 'ES256', kid: deployment.signing_key.kid, typ: 'JWT' }) + .setIssuer(docs.client_id).setSubject(docs.client_id).setAudience(d.token_endpoint) + .setIssuedAt(at).setExpirationTime(at + 60).setJti(random()).sign(await signer); + const token = await fetchJson(d.token_endpoint, { body: new URLSearchParams({ + grant_type: 'authorization_code', code: q.get('code'), redirect_uri: tx.callback, + client_id: docs.client_id, code_verifier: tx.verifier, + client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer', client_assertion: assertion, + }).toString() }); + ensure(!token.error, 'Token endpoint rejected authorisation'); + const identity = await verifyIdentity(token.id_token, d, tx); + const session = seal({ iat: at, exp: at + c.session_ttl_seconds, revision: cookieRevision, sid: random(), iss: c.issuer, sub: identity.sub }, 'session'); + return response(303, '', { location: `${c.origin}${safeReturn(tx.return_to, c)}`, 'set-cookie': [...clear, cookie(SESSION, session, c.session_ttl_seconds)] }); + } + + if (!auth) { + const session = open(jar[SESSION], 'session'); + if (session && session.iss === c.issuer && typeof session.sub === 'string' && typeof session.sid === 'string') return forward(request); + if (method === 'HEAD') return response(401, 'Authentication required'); + const returnTo = safeReturn(request.uri + (request.querystring ? `?${request.querystring}` : ''), c); + return response(303, '', { location: `${c.origin}${c.auth_path}/login?return_to=${encodeURIComponent(returnTo)}` }); + } + + ensure(method === 'GET', 'Login must use GET'); + const q = params(request.querystring); + const returnTo = safeReturn(q.get('return_to') ?? '/', c); + const active = Object.keys(jar).filter(k => k.startsWith(TX)); + const expired = active.filter(k => !open(jar[k], 'transaction')); + ensure(active.length - expired.length < 4, 'Too many pending logins'); + const d = await provider(); + const state = random(); + const nonce = random(); + const verifier = random(); + const at = now(); + const binding = open(jar[BROWSER], 'browser')?.id ?? random(); + const tx = { iat: at, exp: at + c.transaction_ttl_seconds, revision: cookieRevision, state, nonce, verifier, binding, + issuer: c.issuer, client_id: docs.client_id, callback: docs.metadata.redirect_uris[0], return_to: returnTo }; + const location = new URL(d.authorization_endpoint); + for (const [k, v] of Object.entries({ response_type: 'code', client_id: docs.client_id, redirect_uri: tx.callback, + scope: c.scopes.join(' '), state, nonce, code_challenge: digest(verifier), code_challenge_method: 'S256', response_mode: 'query' })) location.searchParams.set(k, v); + if (c.max_age_seconds !== null) location.searchParams.set('max_age', String(c.max_age_seconds)); + if (c.required_acr.length) location.searchParams.set('acr_values', c.required_acr.join(' ')); + return response(303, '', { location: location.href, 'set-cookie': [ + ...expired.map(k => cookie(k, '', 0)), cookie(BROWSER, seal({ iat: at, exp: tx.exp, revision: cookieRevision, id: binding }, 'browser'), c.transaction_ttl_seconds), + cookie(`${TX}${state}`, seal(tx, 'transaction'), c.transaction_ttl_seconds), + ] }); + } catch { + // Never log event objects, tokens, provider errors or callback URLs. + return response(403, 'SOCA could not authorise this request. Start a fresh sign-in or contact the site operator.', clear.length ? { 'set-cookie': clear } : {}); + } + }; +} + +function stableJson(value) { return JSON.stringify(value); } diff --git a/terraform/.terraform.lock.hcl b/terraform/.terraform.lock.hcl new file mode 100644 index 0000000..0d70912 --- /dev/null +++ b/terraform/.terraform.lock.hcl @@ -0,0 +1,26 @@ +# This file is maintained automatically by "terraform init". +# Manual edits may be lost in future updates. + +provider "registry.terraform.io/hashicorp/aws" { + version = "6.69.1" + constraints = "~> 6.0" + hashes = [ + "h1:j8OcftKysEw0hTrFA5FczfGrXOFGMyorSTEiQihUw4o=", + "zh:0ad1319a9fea21dacf084152e236cfd6c150ccc91854ad547c5ab9bc1cddad9a", + "zh:113d7ceaca21f0e4b84f45e69369263311512f858a402955f9e9a8a5bb7f3151", + "zh:1828581462a8a985361c2f4e9af90b2bd5b7d4603b00146bb23a88c5b7d50888", + "zh:28d454d8ac98a88903540bf17bf63d6935dd2e08e572e41152d06db926a5333a", + "zh:2a3b594a98fedc396a4eb5f0fd324e641f83db0906d0129c2ddeffd8002fbe86", + "zh:32c3103af70480b5c3be86ab00af2f46d3a2a6f269ddadf8c1e53a7a3ea0031b", + "zh:3df1dd01ec3a65291f51f26b4d28dcd1bf7b4c73ed0bd3ab1e94e1153ce9b13d", + "zh:42699fbd59bf14adb1cf2836c80c209b3ce815d252f4e983afc8defa754b1dfe", + "zh:5522afd762a1ee95e6ef0d7ad1f165185303a3039e45e1632a3cd13314b7a1a4", + "zh:69f3537ccb012cf24cc11af3cfc3b4be5602b4a3bfbaae2dcab78e41b40f280b", + "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", + "zh:a0c5bf13ba5e17a993aab381603a32d6c9dc2ae8d9f982b6a8c6407b5d7c4a50", + "zh:b9f8a73e11e0b82ba51474b6a6eb4ac3080d7f268087162cb10884655878670a", + "zh:be1f9728404d67dee586d16b69a445931e5e4dafbf7b996df3a7eed519a557b0", + "zh:dc15fb3443312a42deb8b13f92c8d10a701e46eca0155f0709ad763057a85a1d", + "zh:e9f6567a13f21123838aaf78d94f76da8c8f7783eff7f7aa781fd1c21d18d86c", + ] +} diff --git a/terraform/README.md b/terraform/README.md new file mode 100644 index 0000000..4ada713 --- /dev/null +++ b/terraform/README.md @@ -0,0 +1,25 @@ +# Terraform module + +Build the private deployment ZIP first. This module publishes a numbered Node.js 24 Lambda version in `us-east-1` and creates a logs-only execution role. It makes no distribution changes. It accepts the ZIP path, never individual keys or configuration values. + +```hcl +provider "aws" { + alias = "edge" + region = "us-east-1" +} + +module "soca" { + source = "./terraform" + providers = { aws = aws.edge } + function_name = "my-site-soca" + zip_path = "/private/deployment.zip" +} +``` + +Associate `module.soca.version_arn` with `viewer-request` and `include_body = false` on every relevant CloudFront behaviour. Allow POST so logout can reach the handler. The runtime permits only GET/HEAD for content. Cookies and query strings must not reach S3 or become content cache keys; the viewer handler sees them before cache-policy filtering. Keep the S3 bucket private using Origin Access Control. + +`timeout_seconds` defaults to 30; `tags` defaults to an empty map. Session lifetime and authentication settings belong in the generated package. ZIP changes are detected using `filebase64sha256`, and every update publishes an immutable numbered version. Terraform state contains package paths and hashes rather than ZIP contents; keep the ZIP and state access restricted. + +For a new site, use the [disabled-distribution bootstrap example](../examples/terraform/README.md). Deployment credentials need Lambda publishing, IAM role creation/passing, CloudFront association/replication and service-linked-role permissions; the function execution role itself only writes logs. Logs appear in the AWS Regions serving requests. + +Before destroying a deployed function, remove its CloudFront associations, wait for distribution propagation and allow several hours for replica cleanup. Terraform retains earlier published versions during ordinary updates. See [AWS replica cleanup](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-delete-replicas.html). diff --git a/terraform/main.tf b/terraform/main.tf new file mode 100644 index 0000000..3da6878 --- /dev/null +++ b/terraform/main.tf @@ -0,0 +1,69 @@ +terraform { + required_version = ">= 1.5.0" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 6.0" + } + } +} + +data "aws_region" "current" {} +data "aws_partition" "current" {} +data "aws_caller_identity" "current" {} + +resource "aws_iam_role" "edge" { + description = "SOCA Lambda@Edge execution role" + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = "sts:AssumeRole" + Principal = { Service = ["lambda.amazonaws.com", "edgelambda.amazonaws.com"] } + }] + }) + tags = var.tags +} + +resource "aws_iam_role_policy" "logs" { + name = "function-logs" + role = aws_iam_role.edge.id + policy = jsonencode({ + Version = "2012-10-17" + Statement = [{ + Effect = "Allow" + Action = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"] + Resource = [ + "arn:${data.aws_partition.current.partition}:logs:*:${data.aws_caller_identity.current.account_id}:log-group:/aws/lambda/${var.function_name}", + "arn:${data.aws_partition.current.partition}:logs:*:${data.aws_caller_identity.current.account_id}:log-group:/aws/lambda/${var.function_name}:*", + "arn:${data.aws_partition.current.partition}:logs:*:${data.aws_caller_identity.current.account_id}:log-group:/aws/lambda/us-east-1.${var.function_name}", + "arn:${data.aws_partition.current.partition}:logs:*:${data.aws_caller_identity.current.account_id}:log-group:/aws/lambda/us-east-1.${var.function_name}:*" + ] + }] + }) +} + +resource "aws_lambda_function" "edge" { + function_name = var.function_name + description = "SOCA stateless CloudFront authentication" + role = aws_iam_role.edge.arn + filename = var.zip_path + source_code_hash = filebase64sha256(var.zip_path) + runtime = "nodejs24.x" + handler = "index.handler" + architectures = ["x86_64"] + memory_size = 128 + timeout = var.timeout_seconds + publish = true + tags = var.tags + + depends_on = [aws_iam_role_policy.logs] + + lifecycle { + precondition { + condition = data.aws_region.current.region == "us-east-1" + error_message = "Lambda@Edge must be deployed using an AWS provider in us-east-1." + } + } +} diff --git a/terraform/outputs.tf b/terraform/outputs.tf new file mode 100644 index 0000000..d5755e6 --- /dev/null +++ b/terraform/outputs.tf @@ -0,0 +1,9 @@ +output "version_arn" { + description = "Numbered Lambda version ARN for a CloudFront viewer-request association." + value = aws_lambda_function.edge.qualified_arn +} + +output "function_name" { + description = "Deployed function name." + value = aws_lambda_function.edge.function_name +} diff --git a/terraform/variables.tf b/terraform/variables.tf new file mode 100644 index 0000000..30af364 --- /dev/null +++ b/terraform/variables.tf @@ -0,0 +1,37 @@ +variable "function_name" { + type = string + description = "Unique Lambda function name." + default = "cloudfront-soca" + + validation { + condition = can(regex("^[A-Za-z0-9_-]{1,64}$", var.function_name)) + error_message = "Use 1 to 64 letters, digits, underscores or hyphens." + } +} + +variable "zip_path" { + type = string + description = "Path to the private deployment ZIP produced before terraform plan." + + validation { + condition = fileexists(var.zip_path) + error_message = "Build the deployment ZIP before running Terraform." + } +} + +variable "timeout_seconds" { + type = number + description = "Viewer-request timeout, including identity-provider requests." + default = 30 + + validation { + condition = var.timeout_seconds >= 1 && var.timeout_seconds <= 30 && floor(var.timeout_seconds) == var.timeout_seconds + error_message = "Use a whole number of seconds between 1 and 30." + } +} + +variable "tags" { + type = map(string) + description = "Tags for the function and execution role." + default = {} +} diff --git a/tests/demo.test.mjs b/tests/demo.test.mjs new file mode 100644 index 0000000..16fec79 --- /dev/null +++ b/tests/demo.test.mjs @@ -0,0 +1,30 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { request } from 'node:https'; +import { startDemo } from '../demo/server.mjs'; + +test('local HTTPS demo completes browser redirects, session gating and same-origin logout', async () => { + const { server, cert, origin } = await startDemo(18443); + const jar = new Map(); + const get = (url, method = 'GET') => new Promise((resolve, reject) => { + const req = request(url, { method, ca: cert, headers: { cookie: [...jar].map(p => p.join('=')).join('; '), ...(method === 'POST' ? { origin } : {}) } }, res => { + for (const c of res.headers['set-cookie'] ?? []) { + const [name, value] = c.split(';')[0].split('='); + if (value) jar.set(name, value); else jar.delete(name); + } + let body = ''; + res.on('data', b => { body += b; }); + res.on('end', () => resolve({ status: res.statusCode, location: res.headers.location, body })); + }); + req.on('error', reject); req.end(); + }); + try { + let result = await get(`${origin}/private/file.html`); + assert.equal(result.status, 303); + for (let i = 0; i < 4; i++) { assert.ok(result.location.startsWith(origin)); result = await get(result.location); } + assert.equal(result.status, 200); + assert.match(result.body, /Protected static content/); + assert.equal((await get(`${origin}/_soca/logout`, 'POST')).status, 200); + assert.equal((await get(`${origin}/private/file.html`)).status, 303); + } finally { await new Promise(resolve => server.close(resolve)); } +}); diff --git a/tests/helpers.mjs b/tests/helpers.mjs new file mode 100644 index 0000000..dfcf925 --- /dev/null +++ b/tests/helpers.mjs @@ -0,0 +1,38 @@ +import assert from 'node:assert/strict'; +import { createHandler } from '../src/runtime.mjs'; +import { prepare, newKeys } from '../generator/package.mjs'; +import { simulatedProvider } from '../demo/provider.mjs'; + +export function event(path, { method = 'GET', cookies = '', headers = {} } = {}) { + const u = new URL(path, 'https://static.example.com'); + return { Records: [{ cf: { config: { eventType: 'viewer-request' }, request: { + uri: u.pathname, querystring: u.search.slice(1), method, + headers: { host: [{ value: 'static.example.com' }], ...(cookies ? { cookie: [{ value: cookies }] } : {}), ...headers }, + } } }] }; +} + +export function cookieJar(response, previous = '') { + const jar = new Map(previous.split('; ').filter(Boolean).map(p => p.split('='))); + for (const h of response.headers?.['set-cookie'] ?? []) { + const [name, value] = h.value.split(';')[0].split('='); + if (!value) jar.delete(name); else jar.set(name, value); + } + return [...jar].map(p => p.join('=')).join('; '); +} + +export function fixture(overrides = {}) { + let time = Math.floor(Date.now() / 1000); + const deployment = prepare({ origin: 'https://static.example.com', enabled: true, allow_domains: ['example.com'], ...overrides }, newKeys()); + const provider = simulatedProvider(deployment, () => time); + const handler = createHandler(deployment, { fetchJson: provider.fetchJson, now: () => time }); + return { deployment, provider, handler, advance: seconds => { time += seconds; } }; +} + +export async function login(f, { claims, headers, jar = '', returnTo = '/private/file.txt' } = {}) { + const start = await f.handler(event(`/_soca/login?return_to=${encodeURIComponent(returnTo)}`, { cookies: jar })); + assert.equal(start.status, '303'); + jar = cookieJar(start, jar); + const callback = f.provider.authorise(start.headers.location[0].value, claims, headers); + const finish = await f.handler(event(callback.href, { cookies: jar })); + return { start, finish, callback, transactionJar: jar, jar: cookieJar(finish, jar) }; +} diff --git a/tests/network.test.mjs b/tests/network.test.mjs new file mode 100644 index 0000000..3633a60 --- /dev/null +++ b/tests/network.test.mjs @@ -0,0 +1,52 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { publicAddress, resolvePublic, requestJson } from '../src/network.mjs'; +import { httpsUrl } from '../src/config.mjs'; +import { execFileSync } from 'node:child_process'; +import { mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createServer, request } from 'node:https'; + +test('network policy rejects private, loopback, link-local, mapped and reserved addresses', () => { + for (const ip of ['127.0.0.1', '10.0.0.1', '192.168.1.1', '169.254.169.254', '100.64.0.1', '0.0.0.0', '224.1.1.1', '::1', 'fe80::1', 'fc00::1', '::ffff:127.0.0.1', '2001:db8::1']) assert.equal(publicAddress(ip), false, ip); + for (const ip of ['8.8.8.8', '2606:4700:4700::1111']) assert.equal(publicAddress(ip), true, ip); +}); + +test('mixed DNS answers fail closed and selected public address is pinned', async () => { + await assert.rejects(resolvePublic('example.com', async () => [{ address: '8.8.8.8', family: 4 }, { address: '::1', family: 6 }])); + await assert.rejects(resolvePublic('example.com', async () => [])); + assert.deepEqual(await resolvePublic('example.com', async () => [{ address: '8.8.8.8', family: 4 }]), { address: '8.8.8.8', family: 4 }); +}); + +test('HTTPS endpoint validation rejects redirects through credentials, ports and unsafe schemes', async () => { + for (const value of ['http://example.com', 'https://user:pass@example.com', 'https://example.com/#x', 'file:///etc/passwd']) assert.throws(() => httpsUrl(value)); + await assert.rejects(requestJson('https://example.com:8443/')); + await assert.rejects(requestJson('https://127.0.0.1/')); +}); + +test('real Node 24 TLS transport: pinned lookup, POST, redirects, invalid/oversized JSON and TLS verification', async () => { + const dir = await mkdtemp(join(tmpdir(), 'soca-tls-')); + let server; + try { + execFileSync('openssl', ['req', '-x509', '-newkey', 'ec', '-pkeyopt', 'ec_paramgen_curve:P-256', '-nodes', '-days', '1', '-subj', '/CN=localhost', '-addext', 'subjectAltName=DNS:localhost', '-keyout', join(dir, 'key.pem'), '-out', join(dir, 'cert.pem')], { stdio: 'ignore' }); + const cert = await readFile(join(dir, 'cert.pem')); + server = createServer({ key: await readFile(join(dir, 'key.pem')), cert }, (req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.url === '/redirect') { res.writeHead(302, { location: '/ok' }); res.end('{}'); } + else if (req.url === '/large') res.end(JSON.stringify({ a: 'x'.repeat(140000) })); + else if (req.url === '/invalid') res.end('not JSON'); + else if (req.url === '/type') { res.setHeader('content-type', 'text/html'); res.end('{}'); } + else { let data = ''; req.on('data', c => { data += c; }); req.on('end', () => res.end(JSON.stringify({ ok: true, method: req.method, data }))); } + }); + await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); + const deps = { + resolveEndpoint: async () => ({ address: '127.0.0.1', family: 4 }), + send: (url, options, cb) => request(`https://localhost:${server.address().port}${url.pathname}`, { ...options, ca: cert }, cb), + }; + assert.deepEqual(await requestJson('https://public.example/ok', {}, deps), { ok: true, method: 'GET', data: '' }); + assert.deepEqual(await requestJson('https://public.example/ok', { body: 'a=b' }, deps), { ok: true, method: 'POST', data: 'a=b' }); + for (const path of ['/redirect', '/large', '/invalid', '/type']) await assert.rejects(requestJson(`https://public.example${path}`, {}, deps)); + await assert.rejects(requestJson('https://public.example/ok', {}, { ...deps, send: (url, options, cb) => request(`https://localhost:${server.address().port}${url.pathname}`, options, cb) })); + } finally { if (server) await new Promise(resolve => server.close(resolve)); await rm(dir, { recursive: true, force: true }); } +}); diff --git a/tests/package.test.mjs b/tests/package.test.mjs new file mode 100644 index 0000000..c7a7e4c --- /dev/null +++ b/tests/package.test.mjs @@ -0,0 +1,108 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { pathToFileURL } from 'node:url'; +import { unzipSync } from 'fflate'; +import { DEFAULT_PROXY, admitted, documents, normalise } from '../src/config.mjs'; +import { newKeys, packageZip, prepare, saveNewKeys } from '../generator/package.mjs'; +import { createHandler } from '../src/runtime.mjs'; +import { event, fixture, login } from './helpers.mjs'; + +const config = { origin: 'https://static.example.com' }; + +test('generator defaults, seconds override, stable key reuse and secret file permissions', async () => { + const dir = await mkdtemp(join(tmpdir(), 'soca-keys-')); + try { + const path = join(dir, 'keys.json'); + await saveNewKeys(path); + assert.equal((await stat(path)).mode & 0o777, 0o600); + await assert.rejects(saveNewKeys(path)); + const keys = JSON.parse(await readFile(path)); + const a = prepare(config, keys); + assert.equal(a.config.enabled, false); + assert.equal(a.config.session_ttl_seconds, 43200); + assert.deepEqual(a, prepare(config, keys)); + assert.equal(prepare(config, keys, { SOCA_SESSION_TTL_SECONDS: '120' }).config.session_ttl_seconds, 120); + for (const value of ['0', '-1', 'abc', '1.5', '604801']) assert.throws(() => prepare(config, keys, { SOCA_SESSION_TTL_SECONDS: value })); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +test('generated ZIP is reproducible, private and independently executable without node_modules', async () => { + const dir = await mkdtemp(join(tmpdir(), 'soca-zip-')); + try { + const f = fixture(); + const l = await login(f); + const first = join(dir, 'one.zip'); + const result = await packageZip(f.deployment, first); + assert.ok(result.bytes < 150000); + assert.equal((await stat(first)).mode & 0o777, 0o600); + await packageZip(f.deployment, join(dir, 'two.zip')); + assert.deepEqual(await readFile(first), await readFile(join(dir, 'two.zip'))); + await assert.rejects(packageZip(f.deployment, first)); + const files = unzipSync(await readFile(first)); + assert.deepEqual(Object.keys(files).sort(), ['LICENSE', 'deployment.json', 'index.mjs']); + for (const [name, bytes] of Object.entries(files)) await writeFile(join(dir, name), bytes, { mode: 0o600 }); + const bundle = await import(pathToFileURL(join(dir, 'index.mjs')).href); + assert.equal((await bundle.handler(event('/_soca/jwks.json'))).status, '200'); + assert.equal((await bundle.handler(event('/private', { cookies: l.jar }))).uri, '/private'); + const text = Buffer.from(files['index.mjs']).toString(); + assert.ok(!text.includes('simulatedProvider')); + assert.ok(!text.includes('aws-sdk')); + } finally { await rm(dir, { recursive: true, force: true }); } +}); + +test('manual two-stage key overlap preserves old sessions and rejects removed/revoked keys', async () => { + const f = fixture(); + const l = await login(f); + const next = newKeys(); + const ring = { ...f.deployment, session_keys: [...next.session_keys, ...f.deployment.session_keys], public_keys: [...f.deployment.public_keys, ...next.public_keys] }; + const handler = createHandler(prepare(f.deployment.config, ring)); + assert.equal((await handler(event('/private', { cookies: l.jar }))).uri, '/private'); + const removed = createHandler(prepare(f.deployment.config, { ...ring, session_keys: next.session_keys })); + assert.equal((await removed(event('/private', { cookies: l.jar }))).status, '303'); + const revoked = createHandler(prepare({ ...f.deployment.config, security_epoch: 1 }, ring)); + assert.equal((await revoked(event('/private', { cookies: l.jar }))).status, '303'); +}); + +test('hosted and proxy documents are deterministic, stable through public-key overlap and public only', () => { + const keys = newKeys(); + const c = normalise({ ...config, metadata_mode: 'proxy', allow_domains: ['private.example'] }); + const docs = documents(c, keys.public_keys); + assert.ok(docs.client_id.startsWith(DEFAULT_PROXY.replace('%s', ''))); + const decoded = JSON.parse(Buffer.from(docs.client_id.split('/').at(-1), 'base64url')); + assert.equal(decoded.client_id, undefined); + assert.equal(decoded.jwks_uri, 'https://static.example.com/_soca/jwks.json'); + assert.equal(decoded.allow_domains, undefined); + assert.deepEqual(documents(c, [...keys.public_keys, ...newKeys().public_keys]).client_id, docs.client_id); + assert.equal(documents(normalise(config), keys.public_keys).client_id, 'https://static.example.com/_soca/client.json'); +}); + +for (const changes of [ + { allow_domains: ['*example.com'] }, { allow_domains: ['localhost'] }, { allow_domains: ['a..example.com'] }, + { deny_domains: ['https://example.com'] }, { allow_emails: ['a@example.com@evil.example'] }, + { origin: 'https://example.com/' }, { origin: 'http://example.com' }, + { protected_paths: ['/private/'] }, { auth_path: '/' }, { enabled: 'true' }, + { unknown: true }, { proxy_template: 'https://%s.example.com/cimd' }, { proxy_template: 'https://example.com/cimd?x=%s' }, + { scopes: ['openid', 'offline_access'] }, { security_epoch: -1 }, +]) test(`invalid configuration rejected: ${JSON.stringify(changes)}`, () => assert.throws(() => normalise({ ...config, ...changes }))); + +test('domain label matching, wildcard depth, case folding, deny precedence and default deny', () => { + const c = normalise({ ...config, allow_domains: ['*.Example.com'], deny_domains: ['blocked.example.com'] }); + const claim = email => ({ email, email_verified: true }); + assert.equal(admitted(c, claim('A@a.b.EXAMPLE.com')), true); + for (const e of ['a@example.com', 'a@badexample.com', 'a@blocked.example.com', 'a@a..example.com']) assert.equal(admitted(c, claim(e)), false); + assert.equal(admitted(normalise(config), claim('a@example.com')), false); +}); + +test('private public-JWKS entries and duplicate/mismatched key IDs are rejected before packaging', () => { + const keys = newKeys(); + for (const changed of [ + { ...keys, public_keys: [{ ...keys.public_keys[0], d: keys.signing_key.d }] }, + { ...keys, signing_key: { ...keys.signing_key, kid: 'wrong' } }, + { ...keys, session_keys: [keys.session_keys[0], keys.session_keys[0]] }, + { ...keys, public_keys: [keys.public_keys[0], keys.public_keys[0]] }, + { ...keys, session_keys: [{ kid: 'validkeyid', key: 'weak' }] }, + ]) assert.throws(() => prepare(config, changed)); +}); diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs new file mode 100644 index 0000000..002fcea --- /dev/null +++ b/tests/runtime.test.mjs @@ -0,0 +1,175 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createHandler } from '../src/runtime.mjs'; +import { prepare } from '../generator/package.mjs'; +import { event, fixture, login, cookieJar } from './helpers.mjs'; + +test('complete code + PKCE + private_key_jwt flow, local asset checks and absolute 12-hour expiry', async () => { + const f = fixture(); + const l = await login(f); + assert.equal(l.finish.status, '303'); + assert.equal(l.finish.headers.location[0].value, 'https://static.example.com/private/file.txt'); + assert.match(l.finish.headers['set-cookie'][1].value, /Max-Age=43200; Secure; HttpOnly; SameSite=Lax$/); + assert.equal(f.provider.calls.length, 3); + const asset = await f.handler(event('/private/file.txt', { cookies: l.jar })); + assert.equal(asset.uri, '/private/file.txt'); + assert.equal(asset.headers.cookie, undefined); + assert.equal(f.provider.calls.length, 3); + f.advance(43200); + assert.equal((await f.handler(event('/private/file.txt', { cookies: l.jar }))).status, '303'); +}); + +test('head requests do not redirect to the provider, unsupported protected methods fail', async () => { + const f = fixture(); + assert.equal((await f.handler(event('/private', { method: 'HEAD' }))).status, '401'); + assert.equal((await f.handler(event('/private', { method: 'POST' }))).status, '405'); + assert.equal(f.provider.calls.length, 0); +}); + +test('closed default still serves public documents without leaking keys, rules or session material', async () => { + const f = fixture({ enabled: false }); + assert.equal((await f.handler(event('/'))).status, '503'); + const jwks = await f.handler(event('/_soca/jwks.json')); + const metadata = await f.handler(event('/_soca/client.json')); + assert.equal(jwks.status, '200'); + assert.equal(metadata.status, '200'); + for (const value of [jwks.body, metadata.body]) { + assert.ok(!value.includes(f.deployment.signing_key.d)); + assert.ok(!value.includes(f.deployment.session_keys[0].key)); + assert.ok(!value.includes('allow_domains')); + assert.ok(!value.includes('reader@example.com')); + } + assert.equal(JSON.parse(metadata.body).id_token_signed_response_alg, 'ES256'); +}); + +test('path boundary matching, explicitly public paths, unknown auth routes and host pinning', async () => { + const f = fixture({ protected_paths: ['/private'], public_paths: ['/private/public'] }); + assert.equal((await f.handler(event('/private'))).status, '303'); + assert.equal((await f.handler(event('/private/file'))).status, '303'); + assert.equal((await f.handler(event('/private-public'))).uri, '/private-public'); + assert.equal((await f.handler(event('/private/public/file'))).uri, '/private/public/file'); + assert.equal((await f.handler(event('/_soca/anything'))).status, '404'); + assert.equal((await f.handler(event('/private', { headers: { host: [{ value: 'attacker.example' }] } }))).status, '403'); +}); + +for (const raw of ['/private%2F..%2Fpublic', '/private/%252e%252e/public', '/private//file', '/private/%2e%2e/public', '/private\\file', '/private/%00file']) { + test(`ambiguous raw path rejected: ${raw}`, async () => { + const e = event('/'); + e.Records[0].cf.request.uri = raw; + assert.equal((await fixture().handler(e)).status, '403'); + }); +} + +test('encrypted transaction secrets are absent from URLs and cookie plaintext; browser binding is mandatory', async () => { + const f = fixture(); + const start = await f.handler(event('/_soca/login')); + const jar = cookieJar(start); + const url = new URL(start.headers.location[0].value); + assert.equal(url.searchParams.get('code_verifier'), null); + const callback = f.provider.authorise(url); + const unbound = jar.split('; ').filter(s => !s.startsWith('__Host-soca_browser=')).join('; '); + assert.equal((await f.handler(event(callback.href, { cookies: unbound }))).status, '403'); + const token = jar.split('; ').find(s => s.startsWith('__Host-soca_tx_')).split('=')[1]; + assert.ok(!Buffer.from(token.split('.')[2], 'base64url').toString().includes('verifier')); +}); + +test('tampered cookies, duplicate cookies, foreign callback issuer, duplicate state and expired transactions fail closed', async () => { + for (const kind of ['cookie', 'duplicate-cookie', 'issuer', 'duplicate-state', 'expired']) { + const f = fixture(); + const start = await f.handler(event('/_soca/login')); + let jar = cookieJar(start); + const callback = f.provider.authorise(start.headers.location[0].value); + if (kind === 'cookie') jar = jar.replace(/(__Host-soca_tx_[^=]+=)(.)/, (_, prefix, ch) => prefix + (ch === 'A' ? 'B' : 'A')); + if (kind === 'duplicate-cookie') jar += `; ${jar.split('; ')[0]}`; + if (kind === 'issuer') callback.searchParams.set('iss', 'https://evil.example'); + if (kind === 'duplicate-state') callback.searchParams.append('state', callback.searchParams.get('state')); + if (kind === 'expired') f.advance(301); + assert.equal((await f.handler(event(callback.href, { cookies: jar }))).status, '403', kind); + } +}); + +for (const [name, claims] of Object.entries({ + nonce: { nonce: 'wrong' }, issuer: { iss: 'https://evil.example' }, audience: { aud: 'wrong' }, + subject: { sub: '' }, unverified: { email_verified: false }, stringVerified: { email_verified: 'true' }, + missingEmail: { email: null }, domain: { email: 'reader@badexample.com' }, + authorisedParty: { aud: ['https://static.example.com/_soca/client.json', 'other'], azp: 'other' }, + expired: { exp: 1 }, future: { iat: 9999999999 }, fractionTime: { iat: 1.5 }, +})) { + test(`ID token/admission rejection: ${name}`, async () => { + const l = await login(fixture(), { claims }); + assert.equal(l.finish.status, '403'); + assert.ok(!l.finish.headers['set-cookie'].some(c => c.value.startsWith('__Host-soca_session='))); + }); +} + +test('provider auth codes are single-use, even if a captured transaction cookie is replayed', async () => { + const f = fixture(); + const l = await login(f); + assert.equal(l.finish.status, '303'); + assert.equal((await f.handler(event(l.callback.href, { cookies: l.transactionJar }))).status, '403'); +}); + +test('session tamper, configuration change and disable invalidate access', async () => { + const f = fixture(); + const l = await login(f); + const tampered = l.jar.replace(/(__Host-soca_session=[^.]+\.[^.]+\.)(.)/, (_, prefix, ch) => prefix + (ch === 'A' ? 'B' : 'A')); + assert.equal((await f.handler(event('/private', { cookies: tampered }))).status, '303'); + for (const config of [{ deny_domains: ['example.com'] }, { enabled: false }]) { + const changed = prepare({ ...f.deployment.config, ...config }, f.deployment); + const handler = createHandler(changed, { fetchJson: () => { throw new Error('No network'); } }); + assert.notEqual((await handler(event('/private', { cookies: l.jar }))).uri, '/private'); + } +}); + +test('parallel logins after browser binding use independent cookies and respect the pending cap', async () => { + const f = fixture(); + let jar = ''; + const starts = []; + for (let i = 0; i < 4; i++) { + const s = await f.handler(event('/_soca/login', { cookies: jar })); + assert.equal(s.status, '303'); + starts.push(s); + jar = cookieJar(s, jar); + } + assert.equal((await f.handler(event('/_soca/login', { cookies: jar }))).status, '403'); + for (const s of starts) { + const callback = f.provider.authorise(s.headers.location[0].value); + const finish = await f.handler(event(callback.href, { cookies: jar })); + assert.equal(finish.status, '303'); + jar = cookieJar(finish, jar); + } +}); + +test('safe return URLs and CSRF-protected local logout survive provider failure', async () => { + const f = fixture(); + for (const value of ['https://evil.example', '//evil.example', '/_soca/login', '/%2f%2fevil.example', '/private#fragment']) { + assert.equal((await f.handler(event(`/_soca/login?return_to=${encodeURIComponent(value)}`))).status, '403'); + } + const l = await login(f, { returnTo: '/private?tab=1' }); + assert.equal(l.finish.headers.location[0].value, 'https://static.example.com/private?tab=1'); + assert.equal((await f.handler(event('/_soca/logout', { method: 'POST', cookies: l.jar }))).status, '403'); + const result = await f.handler(event('/_soca/logout', { method: 'POST', cookies: l.jar, headers: { origin: [{ value: 'https://static.example.com' }] } })); + assert.equal(result.status, '200'); + assert.ok(result.headers['set-cookie'].every(h => h.value.includes('Max-Age=0'))); + assert.ok(result.body.includes('signed out')); +}); + +test('freshness and explicit assurance policy use validated auth_time/acr/amr', async () => { + const f = fixture({ max_age_seconds: 60, required_acr: ['urn:example:mfa'], required_amr: ['otp'] }); + const failed = await login(f); + assert.equal(failed.finish.status, '403'); + const passed = await login(f, { claims: { auth_time: Math.floor(Date.now() / 1000), acr: 'urn:example:mfa', amr: ['pwd', 'otp'] } }); + assert.equal(passed.finish.status, '303'); +}); + +test('provider metadata incompatibility and expired trust fail closed', async () => { + const f = fixture(); + f.provider.discovery.client_id_metadata_document_supported = false; + assert.equal((await f.handler(event('/_soca/login'))).status, '403'); + const g = fixture(); + const l = await login(g); + assert.equal(l.finish.status, '303'); + g.advance(301); + g.provider.discovery.issuer = 'https://evil.example'; + assert.equal((await g.handler(event('/_soca/login'))).status, '403'); +}); From f3f0425df07b75e904e4414d4f4f77aa5eccb3bf Mon Sep 17 00:00:00 2001 From: OllieJC Date: Thu, 22 Oct 2026 00:37:04 +0100 Subject: [PATCH 2/3] Bind package permission tests to open files and record CodeQL triage --- docs/security.md | 6 ++++++ tests/package.test.mjs | 23 ++++++++++++++++------- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/docs/security.md b/docs/security.md index 7383890..52ef31c 100644 --- a/docs/security.md +++ b/docs/security.md @@ -86,3 +86,9 @@ Patch high/critical findings before release. CI pins dependencies/actions, audit packages and scans with CodeQL. Signed release provenance, browser accessibility testing, OIDC conformance and independent review are planned. Report security issues through [private vulnerability reporting](https://github.com/RESOAuth/cloudfront-soca-plugin/security/advisories/new). + +Initial CodeQL triage: test permission checks/readbacks use the same open file +handle. [Alert 4](https://github.com/RESOAuth/cloudfront-soca-plugin/security/code-scanning/4) +traces operator-configured public document/issuer URLs from the configuration file +to the CLI's HTTPS document check, not key material. This intended flow was reviewed +and recorded as a false positive; the query remains enabled. diff --git a/tests/package.test.mjs b/tests/package.test.mjs index c7a7e4c..cf6d40b 100644 --- a/tests/package.test.mjs +++ b/tests/package.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'; +import { mkdtemp, open, readFile, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { pathToFileURL } from 'node:url'; @@ -17,9 +17,13 @@ test('generator defaults, seconds override, stable key reuse and secret file per try { const path = join(dir, 'keys.json'); await saveNewKeys(path); - assert.equal((await stat(path)).mode & 0o777, 0o600); - await assert.rejects(saveNewKeys(path)); - const keys = JSON.parse(await readFile(path)); + const handle = await open(path, 'r'); + let keys; + try { + assert.equal((await handle.stat()).mode & 0o777, 0o600); + await assert.rejects(saveNewKeys(path)); + keys = JSON.parse(await handle.readFile()); + } finally { await handle.close(); } const a = prepare(config, keys); assert.equal(a.config.enabled, false); assert.equal(a.config.session_ttl_seconds, 43200); @@ -37,11 +41,16 @@ test('generated ZIP is reproducible, private and independently executable withou const first = join(dir, 'one.zip'); const result = await packageZip(f.deployment, first); assert.ok(result.bytes < 150000); - assert.equal((await stat(first)).mode & 0o777, 0o600); + const handle = await open(first, 'r'); + let bytes; + try { + assert.equal((await handle.stat()).mode & 0o777, 0o600); + bytes = await handle.readFile(); + } finally { await handle.close(); } await packageZip(f.deployment, join(dir, 'two.zip')); - assert.deepEqual(await readFile(first), await readFile(join(dir, 'two.zip'))); + assert.deepEqual(bytes, await readFile(join(dir, 'two.zip'))); await assert.rejects(packageZip(f.deployment, first)); - const files = unzipSync(await readFile(first)); + const files = unzipSync(bytes); assert.deepEqual(Object.keys(files).sort(), ['LICENSE', 'deployment.json', 'index.mjs']); for (const [name, bytes] of Object.entries(files)) await writeFile(join(dir, name), bytes, { mode: 0o600 }); const bundle = await import(pathToFileURL(join(dir, 'index.mjs')).href); From 1bbb7f0d9816838d7c1a258e9ef9142b948e3ad4 Mon Sep 17 00:00:00 2001 From: OllieJC Date: Thu, 22 Oct 2026 06:21:45 +0100 Subject: [PATCH 3/3] Add opt-in JavaScript-readable ID token cookie --- README.md | 32 +++++++++ docs/requirements.md | 7 +- docs/security.md | 20 +++++- examples/config.json | 1 + src/config.mjs | 2 + src/runtime.mjs | 20 ++++-- tests/helpers.mjs | 2 +- tests/package.test.mjs | 5 +- tests/readable-id-token.test.mjs | 117 +++++++++++++++++++++++++++++++ 9 files changed, 193 insertions(+), 13 deletions(-) create mode 100644 tests/readable-id-token.test.mjs diff --git a/README.md b/README.md index abfccdc..71df2f3 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,7 @@ It has no runtime effect. Unknown settings fail validation. | `issuer` | Exact trusted issuer; default `https://auth.resoauth.cloud`. | | `enabled` | `false`: metadata stays public; protected content and login return 503. | | `session_ttl_seconds` | Absolute lifetime, `43200`; integer range 1 to 604800. | +| `enable_readable_id_token_cookie` | `false`; opt in to the full validated JWT in JavaScript-readable `__Host-soca_id_token`. | | `transaction_ttl_seconds` | `300`; integer range 1 to 600, four pending logins maximum. | | `protected_paths` / `public_paths` | `['/']` / `[]`. Literal segment prefixes: `/docs` matches itself and descendants, not `/docs-old`. Public exceptions take precedence. | | `allow_domains` / `deny_domains` | Empty; exact DNS domains or `*.example.com` for subdomains only. | @@ -100,6 +101,37 @@ inside the payload and a 4096-character URL limit. It references a stable public `jwks_uri`; inline JWKS is not implemented. Proxy metadata is public and visible to the proxy. The proxy does not perform provider authentication. +## Readable ID token + +Set `"enable_readable_id_token_cookie": true` in the deployment configuration and +rebuild the ZIP to expose the original, validated provider ID-token JWT to the +static app: + +```js +const idToken = document.cookie.split('; ') + .find(cookie => cookie.startsWith('__Host-soca_id_token='))?.split('=')[1]; +``` + +This separate cookie is host-only, `Secure`, `SameSite=Lax`, `Path=/` and deliberately +omits `HttpOnly`. It expires at the earlier of ID-token expiry and session expiry, +and is not refreshed by content requests. The authenticated session can outlive it; +the app must handle an absent token. Logout clears it, and a successful sign-in +with the option disabled clears a previous readable cookie. Full JWTs exceeding +3800 characters cause opted-in sign-in to fail; they are never truncated. + +For independent verification, use the **issuer's JWKS** from its trusted discovery +document, not this plugin's client-assertion JWKS. Pin ES256, the configured issuer +and exact client ID (including proxy mode), and validate expiry and other required +claims using a maintained library such as [JOSE](https://github.com/panva/jose). +Decoding alone does not verify a JWT. Browser JWKS retrieval requires provider CORS +support. The readable token is app identity data; edge access still requires the +encrypted `HttpOnly` session. Its signature alone does not bind it to that session. + +Opting in exposes all ID-token claims to scripts on this origin, including injected +or third-party scripts. Keep the default off unless the app needs those claims. +The token is stripped before origin forwarding and is never published in metadata +or logs. This explicit opt-in is recorded in the SOCA requirements assessment. + ## Test and demo ```sh diff --git a/docs/requirements.md b/docs/requirements.md index d47a930..268ef4d 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -8,6 +8,7 @@ or real-provider login is claimed. Versioned evidence: [configuration](../src/config.mjs), [runtime](../src/runtime.mjs), [network](../src/network.mjs), [generator](../generator/package.mjs), [protocol tests](../tests/runtime.test.mjs), [package tests](../tests/package.test.mjs), +[readable-token tests](../tests/readable-id-token.test.mjs), [transport tests](../tests/network.test.mjs), [HTTPS demo](../tests/demo.test.mjs), [operations](security.md) and the deployment modules. @@ -36,11 +37,11 @@ Versioned evidence: [configuration](../src/config.mjs), [runtime](../src/runtime | F-21 | Partial | Safe return, absolute sessions, CSRF local logout and freshness settings. Individual/RP/back-channel revocation planned. | | F-22 | Partial | AWS IAM recovery, disable and security_epoch. Edge propagation prevents instantaneous disable; live drill planned. | | F-23 | Partial | Immutable versions, no host mutations, lifecycle/recovery documented. Live rolling upgrade/restore tests planned. | -| F-24 | Supported | Identity scopes only; discard code/access/ID token, no refresh/offline or delegated profile. | -| F-25 | Partial | Confidential, purpose-separated, expiring browser-bound cookies and parallel-tab cap. No platform store; true atomic global consume needs shared state. First-binding race documented. | +| F-24 | Partial | Identity scopes only; discard code/access token, no refresh/offline or delegated profile. ID token discarded by default; explicit readable-cookie opt-in retains the full JWT without confidentiality until token/session expiry. | +| F-25 | Partial | Confidential, purpose-separated, expiring browser-bound authentication cookies and parallel-tab cap. Readable ID-token cookie is an explicit JavaScript-readable exception; no atomic global consume without shared state. First-binding race documented. | | N-01 | Partial | Maintained JOSE, fail-closed crypto, CSRF logout and source review. Independent security review planned. | | N-02 | Partial | TLS tests, mixed DNS, pinning, 5-second/128-KiB bounds, no redirects. Restricted-egress/slow-network fault matrix planned. | -| N-03 | Partial | Minimal encrypted identity, no app logging/telemetry/token retention, boundary tests. External logging, backups/deletion and retention are operator duties. | +| N-03 | Partial | Minimal encrypted session identity, no app logging/telemetry, boundary tests. Opt-in ID-token cookie exposes claims to origin scripts with bounded expiry. External logging, backups/deletion and retention are operator duties. | | N-04 | Partial | Stateless workers, overlap and revocation tested locally. No live failover, rotation, restore or propagation measurements. | | N-05 | Partial | Local normal requests, bounded cookies/caches/network, 5-MiB ZIP budget. Distributed rates and sustained load tests planned; use deployment controls such as WAF. | | N-06 | Partial | Semantic logout/error UI, no token dumps. Accessibility audit, redacted incident references, tamper-evident audit and metrics planned. | diff --git a/docs/security.md b/docs/security.md index 52ef31c..1b5d115 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,11 +16,25 @@ binding; parallel tabs use independent state-named transaction cookies. Two first-ever concurrent login starts without an established browser cookie can race; retry the affected tab. -Cookies use purpose-separated HKDF-SHA256 keys, AES-256-GCM with random 96-bit IVs, +Authentication/transaction cookies use purpose-separated HKDF-SHA256 keys, +AES-256-GCM with random 96-bit IVs, authenticated context, `Secure`, `HttpOnly`, `SameSite=Lax`, host-only scope and `Path=/`. No JavaScript storage. Sessions retain only issuer, subject, random ID, -times and policy revision. No access/refresh/ID tokens survive the callback. -Expiry is absolute and is not extended by activity. +times and policy revision. Access/refresh tokens are never retained. ID tokens are +discarded by default; `enable_readable_id_token_cookie=true` intentionally retains +the full validated JWT in a separate JavaScript-readable cookie for the static app. +Session expiry is absolute and is not extended by activity. + +That opt-in cookie, `__Host-soca_id_token`, is signed by the provider but not encrypted +or `HttpOnly`. It is host-only, `Secure`, `SameSite=Lax`, `Path=/`, limited to 3800 +characters, and expires no later than the ID token or session. Oversized/expired +tokens fail opted-in login before issuing any session. Logout deletes it; signing +in with the option off deletes a previous copy. It is not renewed on content access +and never authorises edge requests. All SOCA cookies are stripped from origin +requests. Every same-origin script can read or alter this cookie, so this is an +explicit exception to confidential token storage/browser-storage targets in F-24, +F-25 and N-03. Verify with trusted issuer keys and claims if the app needs independent +authenticity; the plugin's signing JWKS does not validate provider ID tokens. Outbound JSON requests require public HTTPS endpoints on port 443, verify TLS, check every DNS answer, pin the address, reject redirects, disable pooling and diff --git a/examples/config.json b/examples/config.json index 4620798..e12f01c 100644 --- a/examples/config.json +++ b/examples/config.json @@ -4,6 +4,7 @@ "enabled": false, "client_name": "Example private documents", "session_ttl_seconds": 43200, + "enable_readable_id_token_cookie": false, "protected_paths": ["/"], "public_paths": [], "allow_domains": ["example.com"], diff --git a/src/config.mjs b/src/config.mjs index 4ab5441..7e40c2d 100644 --- a/src/config.mjs +++ b/src/config.mjs @@ -4,6 +4,7 @@ export const DEFAULT_PROXY = 'https://dynamic-cimd.resoauth.cloud/cimd/%s'; export const DEFAULTS = Object.freeze({ issuer: 'https://auth.resoauth.cloud', enabled: false, security_epoch: 0, session_ttl_seconds: 43200, transaction_ttl_seconds: 300, + enable_readable_id_token_cookie: false, auth_path: '/_soca', protected_paths: ['/'], public_paths: [], allow_domains: [], deny_domains: [], allow_emails: [], deny_emails: [], metadata_mode: 'hosted', proxy_template: DEFAULT_PROXY, @@ -73,6 +74,7 @@ export function normalise(input) { const issuer = httpsUrl(c.issuer); ensure(!issuer.search, 'Issuer cannot contain a query'); ensure(typeof c.enabled === 'boolean', 'enabled must be boolean'); + ensure(typeof c.enable_readable_id_token_cookie === 'boolean', 'enable_readable_id_token_cookie must be boolean'); ensure(Number.isSafeInteger(c.security_epoch) && c.security_epoch >= 0, 'Invalid security_epoch'); for (const [k, max] of [['session_ttl_seconds', 604800], ['transaction_ttl_seconds', 600]]) ensure(Number.isSafeInteger(c[k]) && c[k] > 0 && c[k] <= max, `Invalid ${k}`); ensure(c.max_age_seconds === null || (Number.isSafeInteger(c.max_age_seconds) && c.max_age_seconds >= 0 && c.max_age_seconds <= 86400), 'Invalid max_age_seconds'); diff --git a/src/runtime.mjs b/src/runtime.mjs index f5d905b..081eada 100644 --- a/src/runtime.mjs +++ b/src/runtime.mjs @@ -4,6 +4,7 @@ import { admitted, canonicalPath, digest, documents, ensure, httpsUrl, matches, import { requestJson } from './network.mjs'; const SESSION = '__Host-soca_session'; +const ID_TOKEN = '__Host-soca_id_token'; const BROWSER = '__Host-soca_browser'; const TX = '__Host-soca_tx_'; const random = () => randomBytes(32).toString('base64url'); @@ -19,9 +20,9 @@ function response(status, body = '', extra = {}, type = 'text/plain; charset=utf return { status: String(status), headers, body }; } -function cookie(name, value, age) { +function cookie(name, value, age, httpOnly = true) { ensure(value.length <= 3800, 'Cookie exceeds size limit'); - return `${name}=${value}; Path=/; Max-Age=${age}; Secure; HttpOnly; SameSite=Lax`; + return `${name}=${value}; Path=/; Max-Age=${age}; Secure;${httpOnly ? ' HttpOnly;' : ''} SameSite=Lax`; } function cookies(request) { @@ -201,8 +202,8 @@ export function createHandler(deployment, { fetchJson = requestJson, now = () => if (method === 'GET') return response(200, 'Sign out

Sign out

', {}, 'text/html; charset=utf-8'); if (method !== 'POST' || request.headers.origin?.length !== 1 || request.headers.origin[0].value !== c.origin) return response(403, 'Sign-out requires a same-origin form submission'); const jar = cookies(request); - const names = [SESSION, BROWSER, ...Object.keys(jar).filter(k => k.startsWith(TX))]; - return response(200, 'You have signed out. You may close this tab.', { 'set-cookie': names.map(k => cookie(k, '', 0)) }); + const names = [SESSION, ID_TOKEN, BROWSER, ...Object.keys(jar).filter(k => k.startsWith(TX))]; + return response(200, 'You have signed out. You may close this tab.', { 'set-cookie': names.map(k => cookie(k, '', 0, k !== ID_TOKEN)) }); } if (auth && ![`${c.auth_path}/login`, `${c.auth_path}/callback`].includes(path)) return response(404, 'Not found'); const protectedPath = auth || (c.protected_paths.some(p => matches(path, p)) && !c.public_paths.some(p => matches(path, p))); @@ -237,7 +238,16 @@ export function createHandler(deployment, { fetchJson = requestJson, now = () => ensure(!token.error, 'Token endpoint rejected authorisation'); const identity = await verifyIdentity(token.id_token, d, tx); const session = seal({ iat: at, exp: at + c.session_ttl_seconds, revision: cookieRevision, sid: random(), iss: c.issuer, sub: identity.sub }, 'session'); - return response(303, '', { location: `${c.origin}${safeReturn(tx.return_to, c)}`, 'set-cookie': [...clear, cookie(SESSION, session, c.session_ttl_seconds)] }); + const issued = [...clear, cookie(SESSION, session, c.session_ttl_seconds)]; + if (c.enable_readable_id_token_cookie) { + const ttl = Math.min(at + c.session_ttl_seconds, identity.exp) - now(); + ensure(ttl > 0, 'Readable ID token has expired'); + // Explicit opt-in: expose the original, validated JWT for the static app. + issued.push(cookie(ID_TOKEN, token.id_token, ttl, false)); + } else if (Object.hasOwn(jar, ID_TOKEN)) { + issued.push(cookie(ID_TOKEN, '', 0, false)); + } + return response(303, '', { location: `${c.origin}${safeReturn(tx.return_to, c)}`, 'set-cookie': issued }); } if (!auth) { diff --git a/tests/helpers.mjs b/tests/helpers.mjs index dfcf925..9b1bbdd 100644 --- a/tests/helpers.mjs +++ b/tests/helpers.mjs @@ -25,7 +25,7 @@ export function fixture(overrides = {}) { const deployment = prepare({ origin: 'https://static.example.com', enabled: true, allow_domains: ['example.com'], ...overrides }, newKeys()); const provider = simulatedProvider(deployment, () => time); const handler = createHandler(deployment, { fetchJson: provider.fetchJson, now: () => time }); - return { deployment, provider, handler, advance: seconds => { time += seconds; } }; + return { deployment, provider, handler, now: () => time, advance: seconds => { time += seconds; } }; } export async function login(f, { claims, headers, jar = '', returnTo = '/private/file.txt' } = {}) { diff --git a/tests/package.test.mjs b/tests/package.test.mjs index cf6d40b..b7eef67 100644 --- a/tests/package.test.mjs +++ b/tests/package.test.mjs @@ -27,6 +27,7 @@ test('generator defaults, seconds override, stable key reuse and secret file per const a = prepare(config, keys); assert.equal(a.config.enabled, false); assert.equal(a.config.session_ttl_seconds, 43200); + assert.equal(a.config.enable_readable_id_token_cookie, false); assert.deepEqual(a, prepare(config, keys)); assert.equal(prepare(config, keys, { SOCA_SESSION_TTL_SECONDS: '120' }).config.session_ttl_seconds, 120); for (const value of ['0', '-1', 'abc', '1.5', '604801']) assert.throws(() => prepare(config, keys, { SOCA_SESSION_TTL_SECONDS: value })); @@ -36,7 +37,7 @@ test('generator defaults, seconds override, stable key reuse and secret file per test('generated ZIP is reproducible, private and independently executable without node_modules', async () => { const dir = await mkdtemp(join(tmpdir(), 'soca-zip-')); try { - const f = fixture(); + const f = fixture({ enable_readable_id_token_cookie: true }); const l = await login(f); const first = join(dir, 'one.zip'); const result = await packageZip(f.deployment, first); @@ -52,6 +53,7 @@ test('generated ZIP is reproducible, private and independently executable withou await assert.rejects(packageZip(f.deployment, first)); const files = unzipSync(bytes); assert.deepEqual(Object.keys(files).sort(), ['LICENSE', 'deployment.json', 'index.mjs']); + assert.equal(JSON.parse(Buffer.from(files['deployment.json']).toString()).config.enable_readable_id_token_cookie, true); for (const [name, bytes] of Object.entries(files)) await writeFile(join(dir, name), bytes, { mode: 0o600 }); const bundle = await import(pathToFileURL(join(dir, 'index.mjs')).href); assert.equal((await bundle.handler(event('/_soca/jwks.json'))).status, '200'); @@ -95,6 +97,7 @@ for (const changes of [ { protected_paths: ['/private/'] }, { auth_path: '/' }, { enabled: 'true' }, { unknown: true }, { proxy_template: 'https://%s.example.com/cimd' }, { proxy_template: 'https://example.com/cimd?x=%s' }, { scopes: ['openid', 'offline_access'] }, { security_epoch: -1 }, + { enable_readable_id_token_cookie: 'true' }, { enable_readable_id_token_cookie: 1 }, { enable_readable_id_token_cookie: null }, ]) test(`invalid configuration rejected: ${JSON.stringify(changes)}`, () => assert.throws(() => normalise({ ...config, ...changes }))); test('domain label matching, wildcard depth, case folding, deny precedence and default deny', () => { diff --git a/tests/readable-id-token.test.mjs b/tests/readable-id-token.test.mjs new file mode 100644 index 0000000..2d88895 --- /dev/null +++ b/tests/readable-id-token.test.mjs @@ -0,0 +1,117 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createLocalJWKSet, jwtVerify } from 'jose'; +import { createHandler } from '../src/runtime.mjs'; +import { cookieJar, event, fixture, login } from './helpers.mjs'; + +const NAME = '__Host-soca_id_token'; +const header = response => response.headers['set-cookie']?.find(h => h.value.startsWith(`${NAME}=`))?.value; +const value = response => header(response)?.split(';')[0].slice(NAME.length + 1); + +test('readable ID-token cookie is absent by default', async () => { + const l = await login(fixture()); + assert.equal(l.finish.status, '303'); + assert.equal(header(l.finish), undefined); +}); + +test('opt-in publishes the complete original provider JWT for JavaScript, keeping the session HttpOnly', async () => { + const f = fixture({ enable_readable_id_token_cookie: true }); + let original; + f.handler = createHandler(f.deployment, { + now: f.now, + fetchJson: async (...args) => { + const result = await f.provider.fetchJson(...args); + if (result.id_token) original = result.id_token; + return result; + }, + }); + const l = await login(f, { claims: { name: 'A Reader', custom_claim: { department: 'Research' } } }); + assert.equal(l.finish.status, '303'); + assert.equal(value(l.finish), original); + assert.match(header(l.finish), /; Path=\/; Max-Age=300; Secure; SameSite=Lax$/); + assert.ok(!header(l.finish).includes('HttpOnly')); + assert.ok(!header(l.finish).includes('Domain=')); + const session = l.finish.headers['set-cookie'].find(h => h.value.startsWith('__Host-soca_session=')); + assert.match(session.value, /; Secure; HttpOnly; SameSite=Lax$/); + assert.ok(!session.value.includes(original)); + const { payload } = await jwtVerify(value(l.finish), createLocalJWKSet({ keys: f.provider.pair.public_keys }), { + issuer: f.deployment.config.issuer, audience: 'https://static.example.com/_soca/client.json', algorithms: ['ES256'], + }); + assert.equal(payload.name, 'A Reader'); + assert.deepEqual(payload.custom_claim, { department: 'Research' }); + await assert.rejects(jwtVerify(value(l.finish), createLocalJWKSet({ keys: f.deployment.public_keys }), { algorithms: ['ES256'] })); +}); + +test('readable lifetime is bounded by both token expiry and the configured session lifetime', async () => { + for (const ttl of [60, 43200]) { + const f = fixture({ enable_readable_id_token_cookie: true, session_ttl_seconds: ttl }); + const l = await login(f); + assert.equal(l.finish.status, '303'); + assert.ok(header(l.finish).includes(`Max-Age=${Math.min(ttl, 300)};`)); + } + const f = fixture({ enable_readable_id_token_cookie: true }); + const l = await login(f, { claims: { iat: f.now() - 10, exp: f.now() - 1 } }); + assert.equal(l.finish.status, '403'); + assert.equal(header(l.finish), undefined); +}); + +test('invalid or unadmitted ID tokens never publish a readable cookie or new session', async () => { + for (const claims of [{ nonce: 'wrong' }, { email: 'reader@evil.example' }, { email_verified: false }]) { + const l = await login(fixture({ enable_readable_id_token_cookie: true }), { claims }); + assert.equal(l.finish.status, '403'); + assert.equal(header(l.finish), undefined); + assert.ok(!l.finish.headers['set-cookie'].some(h => h.value.startsWith('__Host-soca_session='))); + } +}); + +test('token exchange time cannot extend the readable cookie beyond the encrypted session expiry', async () => { + const f = fixture({ enable_readable_id_token_cookie: true, session_ttl_seconds: 60 }); + f.handler = createHandler(f.deployment, { + now: f.now, + fetchJson: async (url, options) => { + if (options?.body) f.advance(10); + return f.provider.fetchJson(url, options); + }, + }); + const l = await login(f); + assert.equal(l.finish.status, '303'); + assert.match(header(l.finish), /; Max-Age=50;/); +}); + +test('oversized full JWT fails opted-in login without truncation or a partial session', async () => { + const claims = { large_claim: 'x'.repeat(3000) }; + const on = await login(fixture({ enable_readable_id_token_cookie: true }), { claims }); + assert.equal(on.finish.status, '403'); + assert.equal(header(on.finish), undefined); + assert.ok(!on.finish.headers['set-cookie'].some(h => h.value.startsWith('__Host-soca_session='))); + assert.equal((await login(fixture(), { claims })).finish.status, '303'); +}); + +test('readable cookie grants no access and is stripped from both protected and public origin requests', async () => { + const f = fixture({ enable_readable_id_token_cookie: true, public_paths: ['/public'] }); + const l = await login(f); + const raw = `${NAME}=${value(l.finish)}`; + assert.equal((await f.handler(event('/private', { cookies: raw }))).status, '303'); + const tampered = l.jar.replace(raw, `${NAME}=client-modified`); + const asset = await f.handler(event('/private', { cookies: `${tampered}; preference=dark` })); + assert.equal(asset.uri, '/private'); + assert.equal(asset.headers.cookie[0].value, ' preference=dark'); + const publicAsset = await f.handler(event('/public', { cookies: raw })); + assert.equal(publicAsset.uri, '/public'); + assert.equal(publicAsset.headers.cookie, undefined); + assert.equal(f.provider.calls.length, 3); +}); + +test('logout and successful sign-in with the option off remove an existing readable cookie', async () => { + const f = fixture({ enable_readable_id_token_cookie: true }); + const l = await login(f); + const signedOut = await f.handler(event('/_soca/logout', { + method: 'POST', cookies: l.jar, headers: { origin: [{ value: f.deployment.config.origin }] }, + })); + assert.equal(signedOut.status, '200'); + assert.equal(header(signedOut), `${NAME}=; Path=/; Max-Age=0; Secure; SameSite=Lax`); + assert.ok(!cookieJar(signedOut, l.jar).includes(`${NAME}=`)); + const off = await login(fixture(), { jar: `${NAME}=${value(l.finish)}` }); + assert.equal(off.finish.status, '303'); + assert.equal(header(off.finish), `${NAME}=; Path=/; Max-Age=0; Secure; SameSite=Lax`); +});