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
5 changes: 5 additions & 0 deletions .changeset/secret-host-pins.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'seamless-auth-api': patch
---

Secrets named by configuration can now be pinned to the hosts they may be sent to. Set `<NAME>_HOSTS` (for example `GOOGLE_CLIENT_SECRET_HOSTS=oauth2.googleapis.com`) and an OAuth provider whose token endpoint, or an OTLP audit sink whose endpoint, is not among those hosts is refused, when written where the endpoint is known and always before each token exchange or send. Pinning is recommended in production. An unpinned secret is still sent, and production logs a warning naming its variable once.
2 changes: 1 addition & 1 deletion docs/adr/0005-extensibility-callouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ Among roles of one kind, sets apply in role-name order, so the last name alphabe
- OTLP/HTTP with JSON encoding to `<endpoint>/v1/logs`, and syslog (RFC 5424) over TLS (RFC 5425) with octet counting. Plain TCP only outside production, never UDP.
- Every record carries the event's `seamless-auth-events/1` line, with `seq`, `prevHash`, `hash` and `payload`, so the chain verifies downstream as an export does.
- Each sink has its own cursor and retries until its destination takes the events, backing off to one minute. There is no dead letter: a sink falls behind and reports its lag.
- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. A send whose named env var is unset or unusable, or whose settings production does not allow (plain TCP syslog), fails as `misconfigured` before any connection.
- Credentials are never stored. A sink names env vars ending `_AUDIT_SINK_SECRET`, the same pattern OAuth providers use. An operator can pin each to the hosts it may be sent to with `<NAME>_HOSTS`; an OTLP sink whose endpoint is not among them is refused, when written and before each send ([#601](https://github.com/fells-code/seamless-auth-api/issues/601)). An unpinned secret is still sent, with a warning in production (decided 2026-12-04), so no deployment stops on upgrade. A send whose named env var is unset or unusable, or whose settings production does not allow (plain TCP syslog), fails as `misconfigured` before any connection.
- Retention never deletes past the oldest sink cursor, and a disabled sink holds it too (decided 2026-11-07). An audit event deleted before a SIEM receives it cannot be recovered, so a disabled sink holds retention until it is deleted. Retention logs a warning naming the holding sink and saying to delete it to release retention.
- An OTLP 2xx counts as delivered, including one whose `partialSuccess` reports rejected records (decided 2026-11-07). A collector rejects such records for their content, so retrying them would stall the sink forever.
- Syslog records carry `seq` and `hash` in the SD-ID `seamless@67592`, under the Fells Code IANA Private Enterprise Number 67592 (#586). Collectors key their parsing rules on the SD-ID, so it does not change.
Expand Down
23 changes: 23 additions & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,29 @@ sinks need API 0.23.1 or later; 0.23.0 refuses them with a 400.
> pool, so a callout can reuse an open connection a provider request made to a host listed only
> in `OAUTH_PROVIDER_PRIVATE_HOSTS`.

### Secret host pins

Configuration names the env var a secret lives in, not the secret, but it also names the host the
secret is sent to: an OAuth provider's `tokenUrl` receives the `clientSecretEnv` value, and an OTLP
audit sink's endpoint receives every `headersFromEnv` value. Pin each such secret to the hosts it
belongs to, so that an administrator account cannot send it anywhere else.

| Variable | Required | Default | Notes |
| -------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `<NAME>_HOSTS` | No | - | Comma-separated hosts the secret in `<NAME>` may be sent to, compared without case or a trailing dot. Recommended in production for every `*_CLIENT_SECRET` and every `*_AUDIT_SINK_SECRET` used as an OTLP header. List bare host names, without a scheme or port; any port on a listed host is allowed. A pin that is set but lists no host allows none. A provider or sink that would send a pinned secret elsewhere is refused. |

```bash
GOOGLE_CLIENT_SECRET_HOSTS=oauth2.googleapis.com
DD_AUDIT_SINK_SECRET_HOSTS=http-intake.logs.datadoghq.com
```

The pin is checked when a provider or sink is written, and again before each token exchange or
send. A provider configured with only an `issuer` has no token endpoint to check until discovery
finds one, so it is refused when it is resolved for sign-in. An unpinned secret is still sent, and
production logs a warning naming its variable the first time it is used. Syslog TLS material
(`tlsCaEnv`, `tlsClientCertEnv`, `tlsClientKeyEnv`) never goes on the wire as a value, but a name
with a pin is still refused for a syslog host outside it.

### Database

Provide **either** a connection string (`DATABASE_URL`, or `DB_URI` as an alias) **or** the
Expand Down
4 changes: 3 additions & 1 deletion docs/oauth.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ Provider access tokens are used only during callback handling to fetch profile d
2. Configure one or more providers in `oauth_providers` system config or the `OAUTH_PROVIDERS` environment variable.
3. Store provider client secrets in environment variables referenced by `clientSecretEnv`. The name must
end in `_CLIENT_SECRET` (for example `GOOGLE_CLIENT_SECRET`), so provider configuration cannot name any
other secret the server holds.
other secret the server holds. In production, also pin each secret to its token endpoint host with
`<NAME>_HOSTS`, for example `GOOGLE_CLIENT_SECRET_HOSTS=oauth2.googleapis.com`, so provider
configuration cannot send it anywhere else (see [docs/configuration.md](./configuration.md#secret-host-pins)).
4. In production, provider URLs must use `https` and resolve to public addresses, and the server does not
follow redirects from them. For an on-premises IdP, list its host in `OAUTH_PROVIDER_PRIVATE_HOSTS`.
Link-local addresses are refused even when listed. Outside production, `http` and private or loopback
Expand Down
23 changes: 22 additions & 1 deletion src/lib/auditSinkTransport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
calloutRequest,
calloutUrlProblem,
} from './calloutTransport.js';
import { checkSecretHost, secretHostProblem } from './secretHostPins.js';

type EnvSource = Record<string, string | undefined>;

Expand Down Expand Up @@ -82,7 +83,13 @@ function destinationProblem(
): DestinationProblem | null {
if (settings.kind === 'otlp') {
const problem = calloutUrlProblem(settings.endpoint, env);
return problem ? { problem: `endpoint ${problem}`, failure: 'refused' } : null;
if (problem) return { problem: `endpoint ${problem}`, failure: 'refused' };
const host = new URL(settings.endpoint).hostname;
for (const envName of Object.values(settings.headersFromEnv)) {
const pinProblem = secretHostProblem(envName, host, env);
if (pinProblem) return { problem: `headersFromEnv: ${pinProblem}`, failure: 'misconfigured' };
}
return null;
}

const misconfigured = (problem: string): DestinationProblem => ({
Expand All @@ -99,6 +106,12 @@ function destinationProblem(
return misconfigured('tlsClientCertEnv and tlsClientKeyEnv must be set together');
}

// TLS material never goes on the wire as a value, but a pinned name stays with its hosts here too.
for (const envName of [settings.tlsCaEnv, settings.tlsClientCertEnv, settings.tlsClientKeyEnv]) {
const pinProblem = envName ? secretHostProblem(envName, settings.host, env) : null;
if (pinProblem) return misconfigured(pinProblem);
}

const problem = calloutHostProblem(settings.host, env);
return problem ? { problem: `host ${problem}`, failure: 'refused' } : null;
}
Expand Down Expand Up @@ -126,7 +139,15 @@ const HEADER_VALUE = /^[\t\x20-\x7e\x80-\xff]+$/;

function otlpHeaders(settings: OtlpSinkSettings, env: EnvSource) {
const headers: Record<string, string> = { 'content-type': 'application/json' };
let host: string;
try {
host = new URL(settings.endpoint).hostname;
} catch {
throw new CalloutError('refused', 'Audit sink endpoint is not a valid URL');
}
for (const [name, envName] of Object.entries(settings.headersFromEnv)) {
const pinProblem = checkSecretHost(envName, host, env);
if (pinProblem) throw new SinkMisconfigured(pinProblem);
const value = secretFromEnv(envName, env);
if (!HEADER_VALUE.test(value)) throw new SinkMisconfigured(`${envName} is not a header value`);
headers[name] = value;
Expand Down
14 changes: 14 additions & 0 deletions src/lib/oauthProviderPolicy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { missingOAuthProviderEndpoints } from '@seamless-auth/types';
import type { OAuthProviderConfig } from '../schemas/systemConfig.schema.js';
import { inList, neverReachable, nonPublic, unmapIPv4 } from './outboundAddress.js';
import { sendProviderRequest } from './providerTransport.js';
import { secretHostProblem } from './secretHostPins.js';

type EnvSource = Record<string, string | undefined>;

Expand Down Expand Up @@ -109,6 +110,19 @@ export function oauthProviderProblems(
const secretProblem = clientSecretEnvProblem(provider.clientSecretEnv);
if (secretProblem) problems.push(secretProblem);

if (!secretProblem && provider.tokenUrl) {
try {
const pinProblem = secretHostProblem(
provider.clientSecretEnv,
new URL(provider.tokenUrl).hostname,
env,
);
if (pinProblem) problems.push(`tokenUrl: ${pinProblem}`);
} catch {
// An invalid tokenUrl is reported by the URL checks below.
}
}

for (const field of PROVIDER_URL_FIELDS) {
const value = provider[field];
if (typeof value !== 'string' || !value) continue;
Expand Down
60 changes: 60 additions & 0 deletions src/lib/secretHostPins.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Copyright © 2026 Fells Code, LLC
* Licensed under the Apache License, Version 2.0
* See LICENSE file in the project root for full license information
*/

import getLogger from '../utils/logger.js';

const logger = getLogger('secretHostPins');

type EnvSource = Record<string, string | undefined>;

/**
* Configuration names the env var a secret lives in, and the host it is sent to, so
* `admin:write` alone could send any such secret to a host of its choosing. `<NAME>_HOSTS` lets
* the operator pin the secret to the hosts it belongs to. It is an env var, and no name a secret
* may have ends in `_HOSTS`, so nothing written through the API can set or name it.
*/
export function secretHostsEnv(secretEnv: string) {
return `${secretEnv}_HOSTS`;
}

function normalise(host: string) {
return host
.trim()
.replace(/^\[|\]$/g, '')
.replace(/\.$/, '')
.toLowerCase();
}

// A pin that is set but lists no host, such as " , ", pins the secret to nothing rather than
// leaving it unpinned, so an operator's typo does not open it to every host.
function pinnedHosts(secretEnv: string, env: EnvSource): Set<string> | null {
const value = env[secretHostsEnv(secretEnv)] ?? '';
if (!value.trim()) return null;
return new Set(value.split(',').map(normalise).filter(Boolean));
}

/** Why `secretEnv` may not be sent to `host`, or null when it may. */
export function secretHostProblem(secretEnv: string, host: string, env: EnvSource = process.env) {
const pinned = pinnedHosts(secretEnv, env);
if (!pinned || pinned.has(normalise(host))) return null;
return `${secretEnv} may only be sent to the hosts in ${secretHostsEnv(secretEnv)}`;
}

const warned = new Set<string>();

/**
* `secretHostProblem` for the moment a secret is about to be sent. An unpinned secret is still
* sent; production warns once per name.
*/
export function checkSecretHost(secretEnv: string, host: string, env: EnvSource = process.env) {
if (!pinnedHosts(secretEnv, env) && env.NODE_ENV === 'production' && !warned.has(secretEnv)) {
warned.add(secretEnv);
logger.warn(
`${secretEnv} is not pinned to a host. Set ${secretHostsEnv(secretEnv)} to the hosts it may be sent to.`,
);
}
return secretHostProblem(secretEnv, host, env);
}
7 changes: 7 additions & 0 deletions src/services/oauthService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
} from '../lib/oauthProviderPolicy.js';
import { withOwnerAdminRole } from '../lib/ownerAdmin.js';
import { allowedRedirect } from '../lib/redirectAllowlist.js';
import { checkSecretHost } from '../lib/secretHostPins.js';
import { OAuthIdentity } from '../models/oauthIdentities.js';
import { UserExternalId } from '../models/userExternalIds.js';
import { User } from '../models/users.js';
Expand Down Expand Up @@ -489,6 +490,12 @@ export async function exchangeOAuthTokens({
throw new OAuthProviderPolicyError(secretProblem);
}

// The token endpoint may come from discovery, so the pin is checked against the URL in use.
const pinProblem = checkSecretHost(provider.clientSecretEnv, new URL(provider.tokenUrl).hostname);
if (pinProblem) {
throw new OAuthProviderPolicyError(pinProblem);
}

const clientSecret = process.env[provider.clientSecretEnv];

if (!clientSecret) {
Expand Down
44 changes: 44 additions & 0 deletions tests/unit/lib/auditSinkTransport.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,34 @@ describe('OTLP', () => {
expect(received[0].headers['dd-api-key']).toBe('key-1');
});

it('sends a header secret only to the hosts it is pinned to', async () => {
const settings = otlp({ headersFromEnv: { 'DD-API-KEY': 'DD_AUDIT_SINK_SECRET' } });
const pinnedElsewhere = {
DD_AUDIT_SINK_SECRET: 'key-1',
DD_AUDIT_SINK_SECRET_HOSTS: 'http-intake.logs.example.com',
};

expect(sinkDestinationProblem(settings, pinnedElsewhere)).toBe(
'headersFromEnv: DD_AUDIT_SINK_SECRET may only be sent to the hosts in DD_AUDIT_SINK_SECRET_HOSTS',
);
expect((await sendToSink(settings, chain(1).map(eventRecord), pinnedElsewhere)).failure).toBe(
'misconfigured',
);
expect(received).toHaveLength(0);

const pinnedHere = { ...pinnedElsewhere, DD_AUDIT_SINK_SECRET_HOSTS: '127.0.0.1' };
expect(sinkDestinationProblem(settings, pinnedHere)).toBeNull();
expect((await sendToSink(settings, chain(1).map(eventRecord), pinnedHere)).ok).toBe(true);
});

it('refuses an endpoint that is not a URL before reading any header secret', async () => {
const settings = otlp({
endpoint: 'not a url',
headersFromEnv: { 'DD-API-KEY': 'DD_AUDIT_SINK_SECRET' },
});
expect((await sendToSink(settings, chain(1).map(eventRecord), {})).failure).toBe('refused');
});

it('refuses to send when a header env var is missing or empty, rather than send it empty', async () => {
const settings = otlp({ headersFromEnv: { Authorization: 'OTEL_AUDIT_SINK_SECRET' } });

Expand Down Expand Up @@ -567,3 +595,19 @@ describe('syslog', () => {
});
});
});

describe('syslog secret pins', () => {
it('refuses TLS material pinned to another host', () => {
const settings = syslog(6514, {
host: 'collector.example.com',
transport: 'tls',
tlsCaEnv: 'CA_AUDIT_SINK_SECRET',
});
expect(
sinkDestinationProblem(settings, { CA_AUDIT_SINK_SECRET_HOSTS: 'other.example.com' }),
).toBe('CA_AUDIT_SINK_SECRET may only be sent to the hosts in CA_AUDIT_SINK_SECRET_HOSTS');
expect(
sinkDestinationProblem(settings, { CA_AUDIT_SINK_SECRET_HOSTS: 'collector.example.com' }),
).toBeNull();
});
});
18 changes: 18 additions & 0 deletions tests/unit/lib/oauthProviderPolicy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,24 @@ describe('oauthProviderProblems', () => {
expect(oauthProviderProblems(provider(), production)).toEqual([]);
});

it('refuses a tokenUrl outside the hosts its secret is pinned to', () => {
const env = { ...production, GOOGLE_CLIENT_SECRET_HOSTS: 'oauth2.googleapis.com' };

expect(oauthProviderProblems(provider(), env)).toEqual([
'tokenUrl: GOOGLE_CLIENT_SECRET may only be sent to the hosts in GOOGLE_CLIENT_SECRET_HOSTS',
]);
expect(
oauthProviderProblems(provider({ tokenUrl: 'https://oauth2.googleapis.com/token' }), env),
).toEqual([]);
});

it('leaves an unparseable tokenUrl to the URL checks when the secret is pinned', () => {
const env = { GOOGLE_CLIENT_SECRET_HOSTS: 'oauth2.googleapis.com' };
expect(oauthProviderProblems(provider({ tokenUrl: 'not a url' }), env)).toEqual([
'tokenUrl is not a valid URL',
]);
});

it('needs the endpoints of a provider without an issuer', () => {
expect(oauthProviderProblems(provider({ tokenUrl: undefined }), {})).toEqual([
'tokenUrl is required unless the provider has an issuer to discover it from',
Expand Down
81 changes: 81 additions & 0 deletions tests/unit/lib/secretHostPins.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';

const warn = vi.fn();
vi.mock('../../../src/utils/logger.js', () => ({
default: vi.fn(() => ({ info: vi.fn(), warn, error: vi.fn(), debug: vi.fn() })),
}));

const { checkSecretHost, secretHostProblem, secretHostsEnv } =
await import('../../../src/lib/secretHostPins.js');

describe('secretHostProblem', () => {
it('names the pin env after the secret', () => {
expect(secretHostsEnv('GOOGLE_CLIENT_SECRET')).toBe('GOOGLE_CLIENT_SECRET_HOSTS');
});

it('admits any host while the secret is not pinned', () => {
expect(secretHostProblem('GOOGLE_CLIENT_SECRET', 'idp.example.com', {})).toBeNull();
expect(
secretHostProblem('GOOGLE_CLIENT_SECRET', 'idp.example.com', {
GOOGLE_CLIENT_SECRET_HOSTS: ' ',
}),
).toBeNull();
});

it.each(['oauth2.googleapis.com', 'OAUTH2.googleapis.com.', 'backup.example.com'])(
'admits a pinned host (%s)',
(host) => {
const env = { GOOGLE_CLIENT_SECRET_HOSTS: 'oauth2.googleapis.com, Backup.example.com.' };
expect(secretHostProblem('GOOGLE_CLIENT_SECRET', host, env)).toBeNull();
},
);

it('admits a pinned IPv6 literal with or without brackets', () => {
const env = { IDP_CLIENT_SECRET_HOSTS: '[2001:db8::1]' };
expect(secretHostProblem('IDP_CLIENT_SECRET', '2001:db8::1', env)).toBeNull();
expect(secretHostProblem('IDP_CLIENT_SECRET', '[2001:db8::1]', env)).toBeNull();
});

it('pins a secret to nothing when its pin lists no host', () => {
expect(
secretHostProblem('GOOGLE_CLIENT_SECRET', 'idp.example.com', {
GOOGLE_CLIENT_SECRET_HOSTS: ' , ',
}),
).toContain('GOOGLE_CLIENT_SECRET_HOSTS');
});

it('refuses a host the secret is not pinned to', () => {
expect(
secretHostProblem('GOOGLE_CLIENT_SECRET', 'collector.example.net', {
GOOGLE_CLIENT_SECRET_HOSTS: 'oauth2.googleapis.com',
}),
).toBe('GOOGLE_CLIENT_SECRET may only be sent to the hosts in GOOGLE_CLIENT_SECRET_HOSTS');
});
});

describe('checkSecretHost', () => {
beforeEach(() => warn.mockClear());

it('warns once per unpinned secret in production, naming the env var only', () => {
const env = { NODE_ENV: 'production', A_CLIENT_SECRET: 'value-never-logged' };

expect(checkSecretHost('A_CLIENT_SECRET', 'idp.example.com', env)).toBeNull();
expect(checkSecretHost('A_CLIENT_SECRET', 'idp.example.com', env)).toBeNull();
checkSecretHost('B_CLIENT_SECRET', 'idp.example.com', env);

expect(warn).toHaveBeenCalledTimes(2);
expect(warn.mock.calls[0][0]).toContain('A_CLIENT_SECRET_HOSTS');
expect(warn.mock.calls.flat().join(' ')).not.toContain('value-never-logged');
});

it('does not warn outside production or for a pinned secret', () => {
checkSecretHost('C_CLIENT_SECRET', 'idp.example.com', { NODE_ENV: 'development' });
const pinned = { NODE_ENV: 'production', D_CLIENT_SECRET_HOSTS: 'idp.example.com' };
expect(checkSecretHost('D_CLIENT_SECRET', 'idp.example.com', pinned)).toBeNull();
expect(checkSecretHost('D_CLIENT_SECRET', 'other.example.com', pinned)).toContain(
'D_CLIENT_SECRET_HOSTS',
);

expect(warn).not.toHaveBeenCalled();
});
});
Loading
Loading