Skip to content

Commit 4536eaa

Browse files
fix(api): build SAML entityID and SSO endpoints from our own settings
getSamlContext derived the IdP entity ID and both SingleSignOnService Locations from SLACK_TEAM_HOST, so the live metadata advertised https://codeforphilly.slack.com/api/saml/slack/... — Slack's host, not ours. Per specs/api/saml.md#idp-identity-and-hosts: - entityId (metadata entityID + assertion Issuer, one value flowing through SlackSamlEntities.entityId → issuerEntityId) now comes from the new SAML_ENTITY_ID env var, defaulting to https://codeforphilly.org/api/saml/slack/metadata. It is a stable logical identifier and intentionally does not follow CFP_SITE_HOST, so the next.codeforphilly.org → codeforphilly.org flip at cutover leaves the issuer Slack stored at setup untouched. - ssoLoginPostUrl / ssoLoginRedirectUrl are built on CFP_SITE_HOST so the metadata points Slack at the host actually serving the API. - SLACK_TEAM_HOST keeps only its Slack-side roles (ACS URL, NameID NameQualifier, launch redirect). Tests assert the default entityID, the CFP_SITE_HOST-driven Locations, Issuer == entityID on both Response and Assertion, that CFP_SITE_HOST=next.example.org moves the Locations without moving the entityID, and that an explicit SAML_ENTITY_ID flows to both. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RdRwHvDupRLV8GuJpYKzEr
1 parent 86b988c commit 4536eaa

4 files changed

Lines changed: 155 additions & 19 deletions

File tree

‎apps/api/src/env.ts‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@
66
*/
77
import { z } from 'zod';
88

9+
/**
10+
* Default SAML IdP entity ID. Stable across hosts — see the SAML_ENTITY_ID
11+
* field below and specs/api/saml.md#idp-identity-and-hosts.
12+
*/
13+
export const SAML_ENTITY_ID_DEFAULT = 'https://codeforphilly.org/api/saml/slack/metadata';
14+
915
export const EnvSchema = z.object({
1016
/** TCP port the Fastify server listens on. */
1117
PORT: z.coerce.number().default(3001),
@@ -49,8 +55,17 @@ export const EnvSchema = z.object({
4955
/** SAML IdP certificate (PEM) for the Slack SAML integration. */
5056
SAML_CERTIFICATE: z.string().optional(),
5157
/**
52-
* Slack workspace host. Used as the SAML `NameQualifier` per
53-
* specs/api/saml.md and shared with the `/chat` redirect handler.
58+
* SAML IdP entity ID — the metadata `entityID` and the `<Issuer>` on every
59+
* assertion. A stable logical identifier Slack stores at setup time, so it
60+
* deliberately does NOT follow CFP_SITE_HOST: the pre-cutover
61+
* `next.codeforphilly.org` deploy and the post-cutover `codeforphilly.org`
62+
* deploy present the same issuer. Per specs/api/saml.md#idp-identity-and-hosts.
63+
*/
64+
SAML_ENTITY_ID: z.url().default(SAML_ENTITY_ID_DEFAULT),
65+
/**
66+
* Slack workspace host. Used for the SAML ACS URL and `NameQualifier` per
67+
* specs/api/saml.md and shared with the `/chat` redirect handler. Never
68+
* used for our own IdP entity ID or endpoint URLs.
5469
*/
5570
SLACK_TEAM_HOST: z.string().default('codeforphilly.slack.com'),
5671
/**
@@ -64,7 +79,9 @@ export const EnvSchema = z.object({
6479
* `next-v2.codeforphilly.org` in sandbox). Used by the server-side
6580
* markdown renderer to distinguish internal from external links — anchors
6681
* with a host different from this one get `target="_blank" rel="noopener
67-
* nofollow"`. Per specs/behaviors/markdown-rendering.md.
82+
* nofollow"`. Per specs/behaviors/markdown-rendering.md. Also the host the
83+
* SAML IdP metadata advertises for its SSO endpoint Locations (per
84+
* specs/api/saml.md#idp-identity-and-hosts).
6885
*/
6986
CFP_SITE_HOST: z.string().default('codeforphilly.org'),
7087
/**
@@ -121,6 +138,7 @@ export const envJsonSchema = {
121138
CFP_JWT_SIGNING_KEY: { type: 'string', minLength: 1 },
122139
SAML_PRIVATE_KEY: { type: 'string' },
123140
SAML_CERTIFICATE: { type: 'string' },
141+
SAML_ENTITY_ID: { type: 'string', default: SAML_ENTITY_ID_DEFAULT },
124142
SLACK_TEAM_HOST: { type: 'string', default: 'codeforphilly.slack.com' },
125143
CFP_WEB_DIST_PATH: { type: 'string' },
126144
CFP_SITE_HOST: { type: 'string', default: 'codeforphilly.org' },

‎apps/api/src/routes/saml.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -128,18 +128,21 @@ function getSamlContext(fastify: FastifyInstance): SamlContext {
128128
throw new ApiValidationError('SAML IdP is not configured');
129129
}
130130

131-
const base = `https://${cfg.SLACK_TEAM_HOST}`.replace('https://', '');
132-
const issuerHost = base;
133-
// Fallback to the team host for the metadata entity ID if we can't see
134-
// the inbound request origin. Per spec the entityID is our own URL —
135-
// we'll prefer the request origin when building responses.
131+
// Three distinct sources, per specs/api/saml.md#idp-identity-and-hosts:
132+
// - entityId (metadata entityID + assertion Issuer) is the stable
133+
// SAML_ENTITY_ID — it must NOT track the serving host, because Slack
134+
// stored it at setup and the host flips at cutover;
135+
// - the SSO endpoint Locations follow CFP_SITE_HOST so the metadata
136+
// points Slack at whatever host this deployment answers on;
137+
// - SLACK_TEAM_HOST is Slack's side only (ACS URL, NameQualifier).
138+
const ssoUrl = `https://${cfg.CFP_SITE_HOST}/api/saml/slack/sso`;
136139
const ctx: SamlContext = {
137140
entities: buildSlackSamlEntities({
138141
privateKey: cfg.SAML_PRIVATE_KEY,
139142
certificate: cfg.SAML_CERTIFICATE,
140-
entityId: `https://${issuerHost}/api/saml/slack/metadata`,
141-
ssoLoginPostUrl: `https://${issuerHost}/api/saml/slack/sso`,
142-
ssoLoginRedirectUrl: `https://${issuerHost}/api/saml/slack/sso`,
143+
entityId: cfg.SAML_ENTITY_ID,
144+
ssoLoginPostUrl: ssoUrl,
145+
ssoLoginRedirectUrl: ssoUrl,
143146
slackTeamHost: cfg.SLACK_TEAM_HOST,
144147
}),
145148
};

‎apps/api/src/saml/config.ts‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,21 @@ export interface SamlIdpSettings {
3636
readonly privateKey: string;
3737
/** PEM-encoded X.509 certificate (the public half). */
3838
readonly certificate: string;
39-
/** The IdP entity ID — also the metadata URL. */
39+
/**
40+
* The IdP entity ID — becomes the metadata `entityID` AND the `<Issuer>`
41+
* on every Response/Assertion (via `SlackSamlEntities.entityId` →
42+
* `issuerEntityId`). A stable logical identifier (`SAML_ENTITY_ID`), not
43+
* necessarily a URL that resolves on the serving host.
44+
*/
4045
readonly entityId: string;
41-
/** The IdP SSO POST binding location (the /launch endpoint). */
46+
/** The IdP SSO POST binding location — `https://<CFP_SITE_HOST>/api/saml/slack/sso`. */
4247
readonly ssoLoginPostUrl: string;
43-
/** The IdP SSO Redirect binding location. */
48+
/** The IdP SSO Redirect binding location — same URL as the POST binding. */
4449
readonly ssoLoginRedirectUrl: string;
45-
/** Slack team host (e.g. `codeforphilly.slack.com`). */
50+
/**
51+
* Slack team host (e.g. `codeforphilly.slack.com`). Slack-side only: the
52+
* ACS URL and the NameID `NameQualifier`. Never part of our own identity.
53+
*/
4654
readonly slackTeamHost: string;
4755
}
4856

‎apps/api/tests/saml.test.ts‎

Lines changed: 111 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,36 @@ import { getSamlTestKeyPair, type SamlTestKeyPair } from './helpers/saml-cert.js
2626

2727
const JWT_KEY = 'test-jwt-signing-key-at-least-32-chars!!';
2828
const SLACK_TEAM_HOST = 'codeforphilly.slack.com';
29+
/** Default SAML_ENTITY_ID per specs/api/saml.md#idp-identity-and-hosts. */
30+
const DEFAULT_ENTITY_ID = 'https://codeforphilly.org/api/saml/slack/metadata';
31+
/** Default CFP_SITE_HOST — the SSO endpoint Locations are built on it. */
32+
const DEFAULT_SITE_HOST = 'codeforphilly.org';
33+
34+
const MD_NS = 'urn:oasis:names:tc:SAML:2.0:metadata';
35+
const ASSERTION_NS = 'urn:oasis:names:tc:SAML:2.0:assertion';
36+
37+
function ssoLocations(metadataXml: string): { entityId: string | null; locations: string[] } {
38+
const doc = new DOMParser().parseFromString(metadataXml, 'application/xml');
39+
const root = doc.documentElement;
40+
const locations = Array.from(root?.getElementsByTagNameNS(MD_NS, 'SingleSignOnService') ?? [])
41+
.map((el) => el.getAttribute('Location'))
42+
.filter((v): v is string => typeof v === 'string');
43+
return { entityId: root?.getAttribute('entityID') ?? null, locations };
44+
}
45+
46+
/** Every `<saml:Issuer>` text in a decoded SAMLResponse (Response + Assertion). */
47+
function issuers(responseXml: string): string[] {
48+
const doc = new DOMParser().parseFromString(responseXml, 'application/xml');
49+
return Array.from(doc.documentElement?.getElementsByTagNameNS(ASSERTION_NS, 'Issuer') ?? []).map(
50+
(el) => el.textContent ?? '',
51+
);
52+
}
53+
54+
function decodeSamlResponse(html: string): string {
55+
const match = /name="SAMLResponse" value="([^"]+)"/.exec(html);
56+
expect(match).not.toBeNull();
57+
return Buffer.from(match![1]!, 'base64').toString('utf8');
58+
}
2959

3060
async function seedPerson(
3161
repoDir: string,
@@ -129,10 +159,17 @@ describe('SAML IdP — Slack', () => {
129159
const root = doc.documentElement;
130160
expect(root?.localName).toBe('EntityDescriptor');
131161

132-
// entityID present
133-
expect(root?.getAttribute('entityID')).toBe(
134-
`https://${SLACK_TEAM_HOST}/api/saml/slack/metadata`,
135-
);
162+
// entityID is the stable SAML_ENTITY_ID default — NOT built on
163+
// SLACK_TEAM_HOST (Slack's host) and NOT on the serving host.
164+
expect(root?.getAttribute('entityID')).toBe(DEFAULT_ENTITY_ID);
165+
166+
// Both SSO bindings point at our own site host.
167+
const { locations } = ssoLocations(res.body);
168+
expect(locations).toHaveLength(2);
169+
for (const loc of locations) {
170+
expect(loc).toBe(`https://${DEFAULT_SITE_HOST}/api/saml/slack/sso`);
171+
}
172+
expect(res.body).not.toContain(`https://${SLACK_TEAM_HOST}/api/saml`);
136173

137174
// IDPSSODescriptor + at least one SingleSignOnService and an X509Certificate.
138175
const idpDescriptors = root?.getElementsByTagNameNS(
@@ -190,6 +227,10 @@ describe('SAML IdP — Slack', () => {
190227
const root = doc.documentElement;
191228
expect(root?.localName).toBe('Response');
192229

230+
// Issuer on both the Response and the Assertion is the entity ID — the
231+
// same value the metadata advertises as entityID.
232+
expect(issuers(xml)).toEqual([DEFAULT_ENTITY_ID, DEFAULT_ENTITY_ID]);
233+
193234
// NameID is the slackSamlNameId, format persistent
194235
const nameIdEl = root?.getElementsByTagNameNS(
195236
'urn:oasis:names:tc:SAML:2.0:assertion',
@@ -319,6 +360,72 @@ describe('SAML IdP — Slack', () => {
319360
});
320361
});
321362

363+
describe('SAML IdP — entity ID vs. site host', () => {
364+
let dataRepo: { path: string; cleanup: () => Promise<void> };
365+
let privateStore: { path: string; cleanup: () => Promise<void> };
366+
let keyPair: SamlTestKeyPair;
367+
const personId = '01951a3c-0000-7000-8000-000000000002';
368+
const slug = 'sam';
369+
370+
beforeAll(async () => {
371+
keyPair = await getSamlTestKeyPair();
372+
dataRepo = await createFullDataRepo();
373+
privateStore = await createPrivateStorageDir();
374+
await seedPerson(dataRepo.path, { id: personId, slug, slackSamlNameId: slug });
375+
await seedPrivateProfile(privateStore.path, { personId, email: 'sam@example.com' });
376+
});
377+
378+
afterAll(async () => {
379+
await dataRepo.cleanup();
380+
await privateStore.cleanup();
381+
});
382+
383+
it('CFP_SITE_HOST moves the SSO Locations but leaves entityID alone', async () => {
384+
const app = await buildTestApp(dataRepo.path, privateStore.path, keyPair, {
385+
CFP_SITE_HOST: 'next.example.org',
386+
});
387+
try {
388+
const res = await app.inject({ method: 'GET', url: '/api/saml/slack/metadata' });
389+
expect(res.statusCode).toBe(200);
390+
const { entityId, locations } = ssoLocations(res.body);
391+
expect(locations).toHaveLength(2);
392+
for (const loc of locations) {
393+
expect(loc).toBe('https://next.example.org/api/saml/slack/sso');
394+
}
395+
// The pre-cutover host does not leak into the identifier Slack stores.
396+
expect(entityId).toBe(DEFAULT_ENTITY_ID);
397+
} finally {
398+
await app.close();
399+
}
400+
});
401+
402+
it('SAML_ENTITY_ID overrides both the metadata entityID and the assertion Issuer', async () => {
403+
const entityId = 'https://idp.example.org/saml/slack';
404+
const app = await buildTestApp(dataRepo.path, privateStore.path, keyPair, {
405+
SAML_ENTITY_ID: entityId,
406+
CFP_SITE_HOST: 'next.example.org',
407+
});
408+
try {
409+
const meta = await app.inject({ method: 'GET', url: '/api/saml/slack/metadata' });
410+
expect(meta.statusCode).toBe(200);
411+
expect(ssoLocations(meta.body).entityId).toBe(entityId);
412+
413+
const { accessToken } = await mintSessionFor(personId, 'user', JWT_KEY);
414+
const launch = await app.inject({
415+
method: 'GET',
416+
url: '/api/saml/slack/launch',
417+
cookies: { cfp_session: accessToken },
418+
});
419+
expect(launch.statusCode).toBe(200);
420+
expect(issuers(decodeSamlResponse(launch.body))).toEqual([entityId, entityId]);
421+
// Slack-side values still come from SLACK_TEAM_HOST.
422+
expect(launch.body).toContain(`action="https://${SLACK_TEAM_HOST}/sso/saml"`);
423+
} finally {
424+
await app.close();
425+
}
426+
});
427+
});
428+
322429
describe('SAML IdP — without configured cert/key', () => {
323430
let dataRepo: { path: string; cleanup: () => Promise<void> };
324431
let privateStore: { path: string; cleanup: () => Promise<void> };

0 commit comments

Comments
 (0)