diff --git a/README.md b/README.md index d7a1155..99f7a9d 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Infrastructure as Code for managing access to MCP community resources using Pulu - **Google Workspace Groups**: Automatically syncs group memberships for @modelcontextprotocol.io email accounts - **Email Groups**: Groups with `isEmailGroup: true` accept emails from anyone (including external users) and notify all members. External posts are moderated for security. - **Google Workspace User Accounts**: Provisions @modelcontextprotocol.io accounts for members of roles with `provisionUser: true` (directly, or via a role nested under one through `github.parent` — e.g. SDK teams under `sdk-maintainers`, working groups under `working-groups`) +- **GitHub sign-in for Google Workspace**: Cloudflare Access is the SAML identity provider for Google Workspace, so allowlisted maintainers sign in to their `@modelcontextprotocol.io` account with GitHub. The allowlist and account mapping come from [`src/config/workspaceSso.ts`](src/config/workspaceSso.ts) and `users.ts`. See [GitHub sign-in for Google Workspace](#github-sign-in-for-google-workspace) below. - **Discord**: Syncs the Discord roles declared in [`src/config/roles.ts`](src/config/roles.ts) to the members' Discord IDs in `users.ts`, and manages the settings of the channels declared in [`src/config/channels.ts`](src/config/channels.ts), including thread-only forum/media channels. See [Discord channels](#discord-channels) below. - **Cloudflare Access (security-room)**: Syncs the Cloudflare Zero Trust Access policy that decides who can sign in to `securityroom.modelcontextprotocol.io` from the roles declared in [`src/config/accessPolicies.ts`](src/config/accessPolicies.ts). See [Cloudflare Access (security-room)](#cloudflare-access-security-room) below. - **npm & PyPI Package Publishing Access** (declared, not applied): Expected registry access is declared in [`src/config/packageAccess.ts`](src/config/packageAccess.ts) and drift against the live npm registry is detected by CI — but changes are applied manually by a maintainer. See [npm & PyPI Package Publishing Access](#npm--pypi-package-publishing-access) below for why and how. @@ -126,6 +127,18 @@ Channels listed in [`src/config/channels.ts`](src/config/channels.ts) are manage - With `cloudflare:importExistingPolicies: "true"` in `Pulumi.prod.yaml`, the first deploy imports the existing `Maintainers` policy (by its `cloudflarePolicyId`) as-is, ignoring its rule lists. - Then set the flag to `"false"` in a follow-up PR; its preview shows exactly the include-rule changes that the next deploy applies. Leave the flag off from then on. +## GitHub sign-in for Google Workspace + +Google Workspace hands the password step to a third-party SAML SSO profile whose identity provider is a Cloudflare Access app (`Google Workspace`, managed in [`src/cloudflare.ts`](src/cloudflare.ts)): **App → Google → Cloudflare Access → GitHub**. + +- **Who:** members with `workspaceSso: true` and a confirmed numeric `githubUserId` in `users.ts`. [`src/config/workspaceSso.ts`](src/config/workspaceSso.ts) turns them into a NameID transform from the identity's `id` (the GitHub user ID) to `@modelcontextprotocol.io`. It also requires the GitHub login method (`idp.id`) and `modelcontextprotocol` in `groups`. Everyone else gets `unmapped@access.invalid`, which Google refuses. Removing the flag revokes sign-in on the next deploy. +- **Policy:** org members only, GitHub login method only (no one-time PIN), 1 hour Access session. Super admins are exempt from third-party SSO and keep password sign-in. +- **Checking an identity:** the dashboard's login-method test shows only `name`, `email` and `groups`; `cf zero-trust access users last-seen-identity get ` shows `id` and `idp` too. + +**Setup (Workspace super admin):** after deploy, copy the app's SSO endpoint, entity ID and public key from Zero Trust → Access → Applications → Google Workspace. Add a SAML profile under Admin console → Security → Authentication → SSO with third-party IdP, with change-password URL `https://github.com/settings/security`, and assign it to an OU. If Google shows a profile-specific SP entity ID or ACS URL, set `cloudflare:googleSamlEntityId` / `cloudflare:googleSamlAcsUrl` in `Pulumi.prod.yaml`. + +**Adding someone:** confirm their GitHub user ID with them, set `githubUserId` and `workspaceSso: true` in a reviewed PR, and only then move their account into an OU with the profile assigned. Anyone in that OU without a mapping cannot sign in at all. + ## npm & PyPI Package Publishing Access Publishing access to the `modelcontextprotocol` npm organization and to the MCP PyPI projects is **config-as-code with human-applied changes** — deliberately outside the Pulumi resource graph: @@ -232,7 +245,7 @@ The following secrets must be configured in GitHub Actions for automated deploym - Keep this secure - if lost, you cannot decrypt your Pulumi state - **`CLOUDFLARE_ROLE_MANAGEMENT_TOKEN`** (optional, `production` and `preview` environments): Cloudflare token dedicated to Access policy role management, scoped only to **Account → Access: Apps and Policies → Edit** on the MCP Domain Account (not a general-purpose API token) - - Used to manage the Cloudflare Access policy for `securityroom.modelcontextprotocol.io` (see [Cloudflare Access (security-room)](#cloudflare-access-security-room)) + - Used to manage the Cloudflare Access policy for `securityroom.modelcontextprotocol.io` (see [Cloudflare Access (security-room)](#cloudflare-access-security-room)) and the Google Workspace sign-in application (see [GitHub sign-in for Google Workspace](#github-sign-in-for-google-workspace)) ## Initial Setup diff --git a/package-lock.json b/package-lock.json index 2fa2562..46d5ceb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ }, "devDependencies": { "@types/node": "^22.18.6", + "jsonata": "^2.0.6", "prettier": "^3.7.2", "ts-node": "^10.9.2", "typescript": "^5.9.2" @@ -1820,6 +1821,16 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/jsonata": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/jsonata/-/jsonata-2.0.6.tgz", + "integrity": "sha512-WhQB5tXQ32qjkx2GYHFw2XbL90u+LLzjofAYwi+86g6SyZeXHz9F1Q0amy3dWRYczshOC3Haok9J4pOCgHtwyQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, "node_modules/jsonparse": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/jsonparse/-/jsonparse-1.3.1.tgz", diff --git a/package.json b/package.json index 2f73f4d..1fe8983 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ }, "devDependencies": { "@types/node": "^22.18.6", + "jsonata": "^2.0.6", "prettier": "^3.7.2", "ts-node": "^10.9.2", "typescript": "^5.9.2" diff --git a/scripts/test-config.ts b/scripts/test-config.ts index 15307b1..a2dfe62 100644 --- a/scripts/test-config.ts +++ b/scripts/test-config.ts @@ -8,7 +8,7 @@ import { ROLES, buildRoleLookup, getRolesForPlatform } from '../src/config/roles'; import { ROLE_IDS, isValidRoleId } from '../src/config/roleIds'; import { MEMBERS } from '../src/config/users'; -import { hasProvisionUserRole } from '../src/config/utils'; +import { hasProvisionUserRole, type Member } from '../src/config/utils'; import { NPM_ORG, NPM_PACKAGES, @@ -18,6 +18,12 @@ import { NPM_DEFAULT_POLICY, } from '../src/config/packageAccess'; import { ACCESS_POLICIES, getAccessPolicyTeams } from '../src/config/accessPolicies'; +import jsonata from 'jsonata'; +import { + UNMAPPED_NAME_ID, + buildNameIdTransform, + getWorkspaceSsoTable, +} from '../src/config/workspaceSso'; import { REPOSITORY_ACCESS, REPOSITORY_DEFAULTS } from '../src/config/repoAccess'; import { DISCORD_CHANNELS, @@ -45,18 +51,38 @@ import { let passed = 0; let failed = 0; -function test(name: string, fn: () => boolean) { +const pending: Promise[] = []; + +function report(name: string, ok: boolean, error?: unknown) { + console.log(error === undefined ? `${ok ? '✓' : '✗'} ${name}` : `✗ ${name}: ${error}`); + if (ok) passed++; + else failed++; +} + +/** Run a test. Async tests are awaited (and reported) before the summary. */ +function test(name: string, fn: () => boolean | Promise) { try { - if (fn()) { - console.log(`✓ ${name}`); - passed++; - } else { - console.log(`✗ ${name}`); - failed++; - } + const result = fn(); + if (typeof result === 'boolean') report(name, result); + else + pending.push( + result.then( + (ok) => report(name, ok), + (e) => report(name, false, e) + ) + ); } catch (e) { - console.log(`✗ ${name}: ${e}`); - failed++; + report(name, false, e); + } +} + +/** True if fn throws. */ +function throws(fn: () => unknown): boolean { + try { + fn(); + return false; + } catch { + return true; } } @@ -241,19 +267,15 @@ test('security-room policy renders the expected include-rule teams in order', () }); test('security-team team has members', () => MEMBERS.some((m) => m.github && m.memberOf.includes(ROLE_IDS.SECURITY_TEAM))); -test('getAccessPolicyTeams throws for a role without a GitHub team', () => { - try { +test('getAccessPolicyTeams throws for a role without a GitHub team', () => + throws(() => getAccessPolicyTeams({ id: 'bogus', description: '', cloudflarePolicyName: 'x', roles: [ROLE_IDS.ADMINISTRATORS], - }); - return false; - } catch { - return true; - } -}); + }) + )); // Test Discord channel config (channels.ts) and its pure Discord API mapping const SNOWFLAKE = '123456789012345678'; @@ -714,6 +736,49 @@ test('Configured Discord role permissions are all valid', () => getDiscordRolePermissionErrors(r.discord.role, r.discord.permissions).length === 0 )); -// Summary -console.log(`\n${passed} passed, ${failed} failed`); -process.exit(failed > 0 ? 1 : 0); +// Test Workspace SSO (workspaceSso.ts) against the Access identity shape for GitHub +const OCTO = 'octo@modelcontextprotocol.io'; +const ok = { id: 42, idp: { id: 'gh' }, groups: [{ id: 1, name: 'modelcontextprotocol' }] }; +const ssoCases: Array<[string, object, string]> = [ + ['listed GitHub ID', ok, OCTO], + ['string id', { ...ok, id: '42' }, OCTO], + ['unlisted GitHub ID', { ...ok, id: 43 }, UNMAPPED_NAME_ID], + ['another login method', { ...ok, idp: { id: 'otp' } }, UNMAPPED_NAME_ID], + ['outside the org', { ...ok, groups: [{ name: 'evil-org' }] }, UNMAPPED_NAME_ID], + ['no groups', { ...ok, groups: undefined }, UNMAPPED_NAME_ID], + ['no idp', { ...ok, idp: undefined }, UNMAPPED_NAME_ID], + ['no id', { ...ok, id: undefined }, UNMAPPED_NAME_ID], + ['non-scalar id', { ...ok, id: [42] }, UNMAPPED_NAME_ID], + ['prototype key', { ...ok, id: '__proto__' }, UNMAPPED_NAME_ID], +]; +for (const [name, identity, expected] of ssoCases) { + test(`Workspace SSO NameID: ${name}`, async () => + (await jsonata(buildNameIdTransform({ '42': OCTO }, 'gh')).evaluate(identity)) === expected); +} +test('Workspace SSO NameID: empty table maps nobody', async () => + (await jsonata(buildNameIdTransform({}, 'gh')).evaluate(ok)) === UNMAPPED_NAME_ID); +const sso: Member = { + github: 'octo', + githubUserId: 42, + workspaceSso: true, + googleEmailPrefix: 'octo', + memberOf: [], +}; +test('Workspace SSO table maps only workspaceSso members', () => { + const table = getWorkspaceSsoTable([sso, { ...sso, githubUserId: 7, workspaceSso: false }]); + return JSON.stringify(table) === JSON.stringify({ '42': OCTO }); +}); +test('Workspace SSO table rejects bad IDs, unsafe prefixes and duplicates', () => + [ + [{ ...sso, githubUserId: undefined }], + [{ ...sso, githubUserId: -1 }], + [{ ...sso, googleEmailPrefix: 'x@evil.com' }], + [{ ...sso, googleEmailPrefix: undefined }], + [sso, { ...sso, googleEmailPrefix: 'cat' }], + ].every((members) => throws(() => getWorkspaceSsoTable(members)))); + +void Promise.all(pending).then(() => { + // Summary + console.log(`\n${passed} passed, ${failed} failed`); + process.exit(failed > 0 ? 1 : 0); +}); diff --git a/scripts/validate-config.ts b/scripts/validate-config.ts index e75ccad..bbe9bb2 100644 --- a/scripts/validate-config.ts +++ b/scripts/validate-config.ts @@ -19,6 +19,7 @@ import { DISCORD_CHANNELS, validateDiscordChannels } from '../src/config/channel import { getDiscordRolePermissionErrors } from '../src/config/discordPermissions'; import { hasProvisionUserRole, resolveGoogleMemberEmail } from '../src/config/utils'; import type { RoleId } from '../src/config/roleIds'; +import { getWorkspaceSsoTable } from '../src/config/workspaceSso'; const roleLookup = buildRoleLookup(); @@ -445,6 +446,14 @@ for (const role of ROLES) { } } +console.log('Validating Workspace SSO members...'); +try { + getWorkspaceSsoTable(); +} catch (e) { + console.error(`ERROR: ${(e as Error).message}`); + hasErrors = true; +} + if (hasErrors) { console.error('\nValidation failed! Please fix the errors above.'); process.exit(1); diff --git a/src/cloudflare.ts b/src/cloudflare.ts index 08c4c64..c79d066 100644 --- a/src/cloudflare.ts +++ b/src/cloudflare.ts @@ -1,6 +1,7 @@ import * as pulumi from '@pulumi/pulumi'; import * as cloudflare from '@pulumi/cloudflare'; import { ACCESS_POLICIES, GITHUB_ORG, getAccessPolicyTeams } from './config/accessPolicies'; +import { buildNameIdTransform, getWorkspaceSsoTable } from './config/workspaceSso'; const config = new pulumi.Config('cloudflare'); // Cloudflare integration is optional - only enabled if roleManagementToken is configured, @@ -65,6 +66,46 @@ if (CLOUDFLARE_ENABLED) { } ); }); + + // GitHub sign-in for Google Workspace: Access is the SAML IdP for Google's SSO + // profile. Org members only, GitHub only; the NameID transform picks the account. + const workspaceSsoPolicy = new cloudflare.ZeroTrustAccessPolicy( + 'access-policy-workspace-sso', + { + accountId, + name: 'Google Workspace sign-in', + decision: 'allow', + includes: [ + { githubOrganization: { identityProviderId: githubIdentityProviderId, name: GITHUB_ORG } }, + ], + }, + { provider, ignoreChanges: ['connectionRules', 'sessionDuration'] } + ); + new cloudflare.ZeroTrustAccessApplication( + 'access-app-workspace-sso', + { + accountId, + name: 'Google Workspace', + type: 'saas', + allowedIdps: [githubIdentityProviderId], + autoRedirectToIdentity: true, + appLauncherVisible: false, + sessionDuration: '1h', + policies: [{ id: workspaceSsoPolicy.id, precedence: 1 }], + saasApp: { + authType: 'saml', + spEntityId: config.get('googleSamlEntityId') ?? 'google.com/a/modelcontextprotocol.io', + consumerServiceUrl: + config.get('googleSamlAcsUrl') ?? 'https://www.google.com/a/modelcontextprotocol.io/acs', + nameIdFormat: 'email', + nameIdTransformJsonata: buildNameIdTransform( + getWorkspaceSsoTable(), + githubIdentityProviderId + ), + }, + }, + { provider } + ); } export const cloudflareAccessPolicyIds = Object.fromEntries( diff --git a/src/config/users.ts b/src/config/users.ts index 70884a2..38e013d 100644 --- a/src/config/users.ts +++ b/src/config/users.ts @@ -975,6 +975,8 @@ export const MEMBERS: readonly Member[] = [ }, { github: 'sambhav', + githubUserId: 16130816, + workspaceSso: true, email: 'sambhavs.email@gmail.com', firstName: 'Sambhav', lastName: 'Kothari', diff --git a/src/config/utils.ts b/src/config/utils.ts index 4178427..12c6e9f 100644 --- a/src/config/utils.ts +++ b/src/config/utils.ts @@ -9,6 +9,10 @@ import type { Role } from './roles'; export interface Member { /** GitHub username */ github?: string; + /** Numeric GitHub user ID, confirmed with the member (required for workspaceSso) */ + githubUserId?: number; + /** May sign in to their Workspace account with GitHub (src/config/workspaceSso.ts) */ + workspaceSso?: boolean; /** Email address (for Google Workspace) */ email?: string; /** Discord user ID (snowflake) */ diff --git a/src/config/workspaceSso.ts b/src/config/workspaceSso.ts new file mode 100644 index 0000000..1bb3d3a --- /dev/null +++ b/src/config/workspaceSso.ts @@ -0,0 +1,41 @@ +// GitHub sign-in for Google Workspace via a Cloudflare Access SAML app (src/cloudflare.ts). +// See README "GitHub sign-in for Google Workspace". +import { GITHUB_ORG } from './accessPolicies'; +import { MEMBERS } from './users'; +import { resolveGoogleMemberEmail, type Member } from './utils'; + +/** NameID for anyone not mapped; `.invalid` (RFC 2606) is never a Workspace account. */ +export const UNMAPPED_NAME_ID = 'unmapped@access.invalid'; + +/** `githubUserId -> Workspace email` for members with `workspaceSso`; throws on bad config. */ +export function getWorkspaceSsoTable(members: readonly Member[] = MEMBERS): Record { + const table: Record = {}; + for (const m of members.filter((m) => m.workspaceSso)) { + const id = m.githubUserId ?? 0; + if ( + !Number.isSafeInteger(id) || + id <= 0 || + String(id) in table || + !/^[a-z0-9][a-z0-9._-]*$/.test(m.googleEmailPrefix ?? '') + ) { + throw new Error( + `Workspace SSO: "${m.github}" needs a unique githubUserId and googleEmailPrefix` + ); + } + table[String(id)] = resolveGoogleMemberEmail(m)!; + } + return table; +} + +/** + * JSONata NameID transform, evaluated against the Access identity: `id` (numeric + * GitHub user ID), `idp.id` (login method), `groups[].name` (GitHub orgs). Fails + * closed to UNMAPPED_NAME_ID. Literals are JSON-encoded, so config can't inject JSONata. + */ +export function buildNameIdTransform(table: Record, githubIdpId: string): string { + return `( + $allowed := idp.id = ${JSON.stringify(githubIdpId)} and ${JSON.stringify(GITHUB_ORG)} in groups.name and $type(id) in ["number", "string"]; + $email := $allowed ? $lookup(${JSON.stringify(table)}, $string(id)); + $type($email) = "string" ? $email : ${JSON.stringify(UNMAPPED_NAME_ID)} +)`; +}