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
15 changes: 14 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 `<googleEmailPrefix>@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 <user-id>` 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:
Expand Down Expand Up @@ -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

Expand Down
11 changes: 11 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
109 changes: 87 additions & 22 deletions scripts/test-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -45,18 +51,38 @@ import {
let passed = 0;
let failed = 0;

function test(name: string, fn: () => boolean) {
const pending: Promise<void>[] = [];

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<boolean>) {
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;
}
}

Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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);
});
9 changes: 9 additions & 0 deletions scripts/validate-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down Expand Up @@ -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);
Expand Down
41 changes: 41 additions & 0 deletions src/cloudflare.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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(
Expand Down
2 changes: 2 additions & 0 deletions src/config/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,8 @@ export const MEMBERS: readonly Member[] = [
},
{
github: 'sambhav',
githubUserId: 16130816,
workspaceSso: true,
email: 'sambhavs.email@gmail.com',
firstName: 'Sambhav',
lastName: 'Kothari',
Expand Down
4 changes: 4 additions & 0 deletions src/config/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) */
Expand Down
41 changes: 41 additions & 0 deletions src/config/workspaceSso.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> {
const table: Record<string, string> = {};
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<string, string>, 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)}
)`;
}
Loading