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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.git
node_modules
.soca
dist
*.zip
*.pem
*.key
**/.terraform
**/*.tfstate*
21 changes: 21 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -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
53 changes: 53 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -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
27 changes: 27 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
node_modules/
.soca/
dist/
*.zip
*.pem
*.key
*.tfstate*
.terraform/
*.tfplan
coverage/
__pycache__/
6 changes: 6 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -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`.
13 changes: 13 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -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"]
157 changes: 155 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,155 @@
# 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. |
| `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. |
| `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.

## 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
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 `[email protected]`. 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.
8 changes: 8 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions cloudformation/README.md
Original file line number Diff line number Diff line change
@@ -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).
Loading