Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/refuse-weak-service-token.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'seamless-auth-api': minor
---

With `NODE_ENV=production`, the server now refuses to start when `SEAMLESS_SERVICE_TOKEN` (or the fallback `API_SERVICE_TOKEN`) is shorter than 32 bytes or is a published default or placeholder value, such as `local-development-service-token-not-for-deployment` from `docker-compose.yml` or `GRAB_FROM_SEAMLESS_AUTH_PORTAL_DEV` from the templates (#599). The token is the key that signs service tokens, so a guessable value lets anyone call the API as a trusted adapter. `validateEnvs.sh` applies the same check before migrations run, and `src/config/serviceToken.ts` applies it at boot.

This is a breaking change for a production deployment that kept one of those values. Before upgrading, set a new token with `openssl rand -base64 48` on the API and on every server adapter that calls it. Development and test runs are unchanged.
5 changes: 2 additions & 3 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,8 @@ services:
DB_PASSWORD: seamless
DB_LOGGING: ${DB_LOGGING:-false}

# Local-only shared secret. Outside development the API derives the refresh-token
# lookup, TOTP encryption, and OAuth state secrets from this when they are unset,
# so a deployed instance must set real, separate values.
# Local-only shared secret. With NODE_ENV=production the API refuses to start on
# this default or on any value shorter than 32 bytes.
SEAMLESS_SERVICE_TOKEN: ${SEAMLESS_SERVICE_TOKEN:-${API_SERVICE_TOKEN:-local-development-service-token-not-for-deployment}}

# Returns OTP codes and magic-link URLs in the response instead of sending them,
Expand Down
2 changes: 1 addition & 1 deletion docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ sinks need API 0.23.1 or later; 0.23.0 refuses them with a 400.

| Variable | Required | Default | Notes |
| ------------------------------- | ------------------------------------ | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. |
| `SEAMLESS_SERVICE_TOKEN` | Yes | - | Trusted server-adapter and internal bearer secret. No other secret falls back to it. In production, boot refuses a value shorter than 32 bytes or a published default (such as the `docker-compose.yml` value). Generate one with `openssl rand -base64 48`. |
| `API_SERVICE_TOKEN` | No | - | Supported fallback name for `SEAMLESS_SERVICE_TOKEN`. Used only when `SEAMLESS_SERVICE_TOKEN` is unset, with an info notice at boot. Setting both to different values stops the server at boot. |
| `REFRESH_TOKEN_LOOKUP_SECRET` | Production | development-only value | HMAC key for indexed refresh-token lookup fingerprints. Always required in production. |
| `TOTP_SECRET_ENCRYPTION_KEY` | Production, once TOTP is used | development-only value | Encrypts stored TOTP secrets (hashed with SHA-256 to derive the key, so any high-entropy value works). Production refuses to start while any TOTP credential exists without it, and `POST /totp/enroll/start` answers `409 secret_required` until it is set. |
Expand Down
4 changes: 3 additions & 1 deletion docs/production-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@ is no GitHub artifact attestation for the image, so `gh attestation verify` does

Production deployments should define:

- `SEAMLESS_SERVICE_TOKEN` (the older `API_SERVICE_TOKEN` name is still accepted as a fallback)
- `SEAMLESS_SERVICE_TOKEN` (the older `API_SERVICE_TOKEN` name is still accepted as a fallback).
It is the key that signs service tokens, so the server refuses to start in production when it is
shorter than 32 bytes or a published default. Generate one with `openssl rand -base64 48`.
- `REFRESH_TOKEN_LOOKUP_SECRET`
- `TOTP_SECRET_ENCRYPTION_KEY`
- `OAUTH_STATE_SECRET`
Expand Down
65 changes: 63 additions & 2 deletions src/config/serviceToken.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,68 @@ export class OidcServiceTokenReuseError extends Error {
}
}

export const MIN_SERVICE_TOKEN_BYTES = 32;

/**
* Values that have shipped in compose files, examples, templates and docs. Several are
* long enough to pass the length check, so a deployment that kept one would otherwise boot.
*/
export const KNOWN_DEFAULT_SERVICE_TOKENS: readonly string[] = [
'local-development-service-token-not-for-deployment',
'verify-dev-service-token-not-a-real-secret',
'local-dev-service-token-at-least-32-chars',
'GRAB_FROM_SEAMLESS_AUTH_PORTAL_DEV',
'GRAB_FROM_SEAMLESS_AUTH_PORTAL',
'32-byte-hex-string',
];

const PLACEHOLDER_MARKERS = ['replace-me', 'not-for-deployment', 'not-a-real-secret', 'changeme'];

export function isKnownDefaultServiceToken(value: string): boolean {
const lower = value.toLowerCase();
return (
KNOWN_DEFAULT_SERVICE_TOKENS.some((known) => known.toLowerCase() === lower) ||
PLACEHOLDER_MARKERS.some((marker) => lower.includes(marker))
);
}

export class WeakServiceTokenError extends Error {
constructor(source: ServiceTokenSource, reason: 'short' | 'default') {
const why =
reason === 'short'
? `is shorter than ${MIN_SERVICE_TOKEN_BYTES} bytes`
: 'is a published default or placeholder value';
super(
`${source} ${why}. It is the key that signs service tokens, so anyone who can guess it ` +
'can call the API as a trusted adapter. Generate one with: openssl rand -base64 48',
);
this.name = 'WeakServiceTokenError';
}
}

/**
* Boot-time check: throws on conflicting values so a misconfigured instance refuses to
* start, and notes once when only the legacy name is in use.
* Production only: local stacks and the test suite keep short fixed values, and development
* mode is refused off localhost unless SEAMLESS_ALLOW_INSECURE_DEV is set.
*/
export function assertServiceTokenStrength(
resolved: ResolvedServiceToken,
env: EnvSource = process.env,
) {
if (env.NODE_ENV !== 'production' || !resolved.value || !resolved.source) return;

if (Buffer.byteLength(resolved.value, 'utf8') < MIN_SERVICE_TOKEN_BYTES) {
throw new WeakServiceTokenError(resolved.source, 'short');
}

if (isKnownDefaultServiceToken(resolved.value)) {
throw new WeakServiceTokenError(resolved.source, 'default');
}
}

/**
* Boot-time check: throws on conflicting values, and in production on a weak or default
* value, so a misconfigured instance refuses to start. Notes once when only the legacy
* name is in use.
*/
export function assertServiceTokenConfig(env: EnvSource = process.env) {
const resolved = resolveServiceToken(env);
Expand All @@ -88,6 +147,8 @@ export function assertServiceTokenConfig(env: EnvSource = process.env) {
throw new OidcServiceTokenReuseError();
}

assertServiceTokenStrength(resolved, env);

if (resolved.source === LEGACY_SERVICE_TOKEN_ENV) {
logger.info(
`Service token read from ${LEGACY_SERVICE_TOKEN_ENV}. ${SERVICE_TOKEN_ENV} is the preferred name; ` +
Expand Down
68 changes: 68 additions & 0 deletions tests/unit/config/serviceToken.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import {
assertServiceTokenConfig,
getOidcServiceToken,
getServiceToken,
isKnownDefaultServiceToken,
KNOWN_DEFAULT_SERVICE_TOKENS,
OidcServiceTokenReuseError,
resolveServiceToken,
ServiceTokenConflictError,
WeakServiceTokenError,
} from '../../../src/config/serviceToken.js';
import getLogger from '../../../src/utils/logger.js';

Expand Down Expand Up @@ -133,3 +136,68 @@ describe('getOidcServiceToken', () => {
expect(getOidcServiceToken()).toBe('from-env');
});
});

describe('service token strength in production', () => {
const strong = 'q8VfX2m0bN7rT4yK1wZ9cH6jL3pD5sGa';

it('refuses a token shorter than 32 bytes', () => {
expect(() =>
assertServiceTokenConfig({ NODE_ENV: 'production', SEAMLESS_SERVICE_TOKEN: strong.slice(1) }),
).toThrow(new WeakServiceTokenError('SEAMLESS_SERVICE_TOKEN', 'short'));
});

it('counts bytes, not characters', () => {
expect(() =>
assertServiceTokenConfig({ NODE_ENV: 'production', SEAMLESS_SERVICE_TOKEN: 'é'.repeat(16) }),
).not.toThrow();
});

it.each(KNOWN_DEFAULT_SERVICE_TOKENS.filter((value) => value.length >= 32))(
'refuses the published default %s',
(value) => {
expect(() =>
assertServiceTokenConfig({ NODE_ENV: 'production', SEAMLESS_SERVICE_TOKEN: value }),
).toThrow(/published default or placeholder/);
},
);

it('refuses the compose default through the legacy name, naming that variable', () => {
expect(() =>
assertServiceTokenConfig({
NODE_ENV: 'production',
API_SERVICE_TOKEN: 'local-development-service-token-not-for-deployment',
}),
).toThrow(/^API_SERVICE_TOKEN is a published default/);
});

it('refuses placeholder markers whatever the case', () => {
expect(isKnownDefaultServiceToken('my-service-token-REPLACE-ME-before-launch')).toBe(true);
expect(isKnownDefaultServiceToken('grab_from_seamless_auth_portal_dev')).toBe(true);
expect(isKnownDefaultServiceToken(strong)).toBe(false);
});

it('accepts a strong token', () => {
expect(
assertServiceTokenConfig({ NODE_ENV: 'production', SEAMLESS_SERVICE_TOKEN: strong }),
).toEqual({
value: strong,
source: 'SEAMLESS_SERVICE_TOKEN',
});
});

it('leaves an unset token to the presence checks', () => {
expect(() => assertServiceTokenConfig({ NODE_ENV: 'production' })).not.toThrow();
});

it('keeps short and default values working outside production', () => {
expect(() =>
assertServiceTokenConfig({ NODE_ENV: 'development', SEAMLESS_SERVICE_TOKEN: 'devtoken' }),
).not.toThrow();
expect(() =>
assertServiceTokenConfig({
NODE_ENV: 'test',
SEAMLESS_SERVICE_TOKEN: 'local-development-service-token-not-for-deployment',
}),
).not.toThrow();
});
});
30 changes: 30 additions & 0 deletions validateEnvs.sh
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,36 @@ if [ -z "${SEAMLESS_SERVICE_TOKEN:-}" ] && [ -z "${API_SERVICE_TOKEN:-}" ]; then
exit 1
fi

# Mirrors assertServiceTokenStrength in src/config/serviceToken.ts, so a weak token stops
# the container before migrations run. Keep the two lists in step.
if [ "${NODE_ENV:-development}" = "production" ]; then
if [ -n "${SEAMLESS_SERVICE_TOKEN:-}" ]; then
token_name="SEAMLESS_SERVICE_TOKEN"
token_value="$SEAMLESS_SERVICE_TOKEN"
else
token_name="API_SERVICE_TOKEN"
token_value="$API_SERVICE_TOKEN"
fi

if [ "$(printf '%s' "$token_value" | wc -c | tr -d ' ')" -lt 32 ]; then
echo "$token_name is shorter than 32 bytes. Generate one with: openssl rand -base64 48"
exit 1
fi

case "$(printf '%s' "$token_value" | tr '[:upper:]' '[:lower:]')" in
local-development-service-token-not-for-deployment | \
verify-dev-service-token-not-a-real-secret | \
local-dev-service-token-at-least-32-chars | \
grab_from_seamless_auth_portal_dev | \
grab_from_seamless_auth_portal | \
32-byte-hex-string | \
*replace-me* | *not-for-deployment* | *not-a-real-secret* | *changeme*)
echo "$token_name is a published default or placeholder value. Generate one with: openssl rand -base64 48"
exit 1
;;
esac
fi

if [ "${NODE_ENV:-development}" = "production" ]; then
require_var SEAMLESS_JWKS_ACTIVE_KID
require_var SEAMLESS_JWKS_PUBLIC_KEYS
Expand Down