diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 257c52a5..e42a1870 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -116,3 +116,9 @@ jobs: pulumi config set githubBillingEmail "$ORG_BILLING_EMAIL" --secret --stack prod pulumi config set cloudflare:roleManagementToken "$CLOUDFLARE_ROLE_MANAGEMENT_TOKEN" --secret --stack prod make up + + # Pulumi manages only the memberships it created. Remove anyone else from managed teams. + - name: Sync team members + env: + GITHUB_TOKEN: ${{ steps.app-token.outputs.token }} + run: npm run sync-team-members -- --apply diff --git a/README.md b/README.md index 8e9dd4bb..dc7a3ffc 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ npm and PyPI are the exception to automatic deploys. Their expected access is re 2. Open a pull request. A core maintainer has to approve it. 3. Merge it. The [Deploy workflow](.github/workflows/deploy.yml) applies it, usually within 10 to 20 minutes. -Manual changes to anything managed here are usually undone by the next deploy. +Manual changes to anything managed here are usually undone by the next deploy. That includes people added to a team in GitHub's UI. The deploy removes anyone from a team that [`users.ts`](src/config/users.ts) doesn't put them in, up to 20 at a time. A team that lacks someone declared there is skipped with a warning. To list who would be removed, run `npm run sync-team-members`. ## Common tasks diff --git a/package.json b/package.json index 39350d30..fac74421 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "validate": "npx ts-node scripts/validate-config.ts", "test": "npx ts-node scripts/test-config.ts && npx ts-node scripts/test-workspace-sso.ts", "check-github-ids": "npx ts-node scripts/check-github-ids.ts", + "sync-team-members": "npx ts-node scripts/sync-team-members.ts", "check-package-drift": "npx ts-node scripts/check-package-drift.ts", "check": "npm run format:check && npm run validate && npm run test", "format": "prettier --write .", diff --git a/scripts/sync-team-members.ts b/scripts/sync-team-members.ts new file mode 100644 index 00000000..ed6cd8be --- /dev/null +++ b/scripts/sync-team-members.ts @@ -0,0 +1,148 @@ +/** + * Removes people from the GitHub teams in roles.ts whom users.ts doesn't put there. Pulumi + * manages only the memberships it created, so it never sees someone added by hand. + * + * Only direct members count. GitHub gives a parent team its child teams' members too. + * + * GITHUB_TOKEN= npm run sync-team-members # list only + * GITHUB_TOKEN= npm run sync-team-members -- --apply # remove (done by the deploy) + */ +import { GITHUB_ORG } from '../src/config/accessPolicies'; +import { + assertSafeToRemove, + declaredTeamMembers, + planRemovals, + type Removal, + type TeamState, +} from '../src/config/teamSync'; + +const API = 'https://api.github.com'; +const PER_PAGE = 100; +const token = process.env.GITHUB_TOKEN; +const apply = process.argv.includes('--apply'); + +const QUERY = `query($org: String!, $team: String!, $after: String) { + organization(login: $org) { + team(slug: $team) { + members(membership: IMMEDIATE, first: ${PER_PAGE}, after: $after) { + nodes { login } + pageInfo { hasNextPage endCursor } + } + } + } +}`; + +interface MembersPage { + data?: { + organization?: { + team?: { + members: { + nodes: { login: string }[]; + pageInfo: { hasNextPage: boolean; endCursor: string | null }; + }; + } | null; + } | null; + }; + errors?: { message: string }[]; +} + +async function request(method: string, path: string, body?: unknown): Promise { + return fetch(`${API}${path}`, { + method, + headers: { + Authorization: `Bearer ${token}`, + Accept: 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + }, + body: body === undefined ? undefined : JSON.stringify(body), + }); +} + +async function listMembers(team: string): Promise { + const members: string[] = []; + let after: string | null = null; + do { + const response = await request('POST', '/graphql', { + query: QUERY, + variables: { org: GITHUB_ORG, team, after }, + }); + if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); + const page = (await response.json()) as MembersPage; + if (page.errors?.length) throw new Error(page.errors.map((e) => e.message).join('; ')); + const found = page.data?.organization?.team?.members; + if (!found) throw new Error('team not found'); + members.push(...found.nodes.map(({ login }) => login)); + after = found.pageInfo.hasNextPage ? found.pageInfo.endCursor : null; + } while (after); + return members; +} + +async function listInvited(team: string): Promise { + const invited: string[] = []; + for (let page = 1; ; page++) { + const response = await request( + 'GET', + `/orgs/${GITHUB_ORG}/teams/${team}/invitations?per_page=${PER_PAGE}&page=${page}` + ); + if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); + const found = (await response.json()) as { login: string | null }[]; + // An invitation sent to an email address has no login + invited.push(...found.flatMap(({ login }) => login ?? [])); + if (found.length < PER_PAGE) return invited; + } +} + +async function readTeam(team: string): Promise { + try { + return { team, members: await listMembers(team), invited: await listInvited(team) }; + } catch (error) { + throw new Error(`Reading ${team} failed: ${(error as Error).message}`); + } +} + +async function remove({ team, login }: Removal): Promise { + const path = `/orgs/${GITHUB_ORG}/teams/${team}/memberships/${encodeURIComponent(login)}`; + const response = await request('DELETE', path); + if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`); +} + +async function main(): Promise { + if (!token) throw new Error('GITHUB_TOKEN is not set'); + // An old checkout would remove people who were added since + if (apply && process.env.GITHUB_REF !== 'refs/heads/main') { + throw new Error('--apply only runs in the deploy of main'); + } + + const declared = declaredTeamMembers(); + const live: TeamState[] = []; + for (const team of declared.keys()) live.push(await readTeam(team)); + if (live.every(({ members }) => members.length === 0)) { + throw new Error('GitHub returned no members for any team'); + } + + const { removals, skipped } = planRemovals(live, declared); + for (const reason of skipped) console.log(`::warning::Skipped ${reason}`); + console.log(`${removals.length} people in teams that users.ts doesn't put them in`); + for (const { team, login } of removals) console.log(`- ${login} in ${team}`); + if (!apply) return; + + assertSafeToRemove(removals); + let failures = 0; + for (const removal of removals) { + try { + await remove(removal); + console.log(`Removed ${removal.login} from ${removal.team}`); + } catch (error) { + failures++; + console.error( + `Removing ${removal.login} from ${removal.team} failed: ${(error as Error).message}` + ); + } + } + if (failures > 0) throw new Error(`${failures} of ${removals.length} removals failed`); +} + +main().catch((error: Error) => { + console.error(error.message); + process.exit(1); +}); diff --git a/scripts/test-config.ts b/scripts/test-config.ts index 3fbe97ef..063702da 100644 --- a/scripts/test-config.ts +++ b/scripts/test-config.ts @@ -6,7 +6,8 @@ */ import { ROLES, buildRoleLookup, getRolesForPlatform, type Role } from '../src/config/roles'; -import { ROLE_IDS, isValidRoleId } from '../src/config/roleIds'; +import { ROLE_IDS, isValidRoleId, type RoleId } from '../src/config/roleIds'; +import { assertSafeToRemove, declaredTeamMembers, planRemovals } from '../src/config/teamSync'; import { MEMBERS } from '../src/config/users'; import { getTeamGrantErrors, hasProvisionUserRole } from '../src/config/utils'; import { @@ -215,6 +216,58 @@ test('A parent may be granted less than its child', () => { team: 'bottom', permission: 'admin' }, ]).length === 0); +// Team member sync +const syncDeclared = new Map([ + ['parent', new Set()], + ['child', new Set(['alice'])], +]); +const plan = (team: string, members: string[], invited: string[] = []) => { + const { removals, skipped } = planRemovals([{ team, members, invited }], syncDeclared); + return `${removals.map((r) => r.login).join()}|${skipped.length}`; +}; +test('Sync keeps declared members, whatever the case', () => plan('child', ['Alice']) === '|0'); +test('Sync removes undeclared members', () => plan('child', ['alice', 'bob']) === 'bob|0'); +test('Sync removes everyone from a team with none declared', () => + plan('parent', ['alice']) === 'alice|0'); +test('Sync removes undeclared invitations', () => plan('child', ['alice'], ['bob']) === 'bob|0'); +test('Sync counts an invitation as present', () => plan('child', ['bob'], ['alice']) === 'bob|0'); +test('Sync skips a team that lacks a declared member', () => plan('child', ['bob']) === '|1'); +test('Sync ignores teams that are not managed', () => plan('other', ['bob']) === '|0'); +test('Sync refuses to remove too many people', () => { + const removals = ['a', 'b'].map((login) => ({ team: 'child', login })); + assertSafeToRemove(removals, 2); + try { + assertSafeToRemove(removals, 1); + return false; + } catch { + return true; + } +}); +test('Sync declares the members of two roles that share a team', () => { + const role = (id: RoleId) => ({ id, description: '', github: { team: 'shared' } }); + const declared = declaredTeamMembers( + [ + { github: 'alice', memberOf: [ROLE_IDS.GO_SDK] }, + { github: 'bob', memberOf: [ROLE_IDS.RUST_SDK] }, + ], + [role(ROLE_IDS.GO_SDK), role(ROLE_IDS.RUST_SDK)] + ); + return [...declared.get('shared')!].join() === 'alice,bob'; +}); +test('Sync declares every member of every managed team', () => { + const declared = declaredTeamMembers(); + return ROLES.every( + (r) => + !r.github || + MEMBERS.every( + (m) => + !m.github || + !m.memberOf.includes(r.id) || + declared.get(r.github!.team)?.has(m.github.toLowerCase()) + ) + ); +}); + // Test members test('MEMBERS array is not empty', () => MEMBERS.length > 0); test('All members have at least one identifier', () => diff --git a/src/config/teamSync.ts b/src/config/teamSync.ts new file mode 100644 index 00000000..b0e270b0 --- /dev/null +++ b/src/config/teamSync.ts @@ -0,0 +1,77 @@ +import { ROLES, type Role } from './roles'; +import { MEMBERS } from './users'; +import type { Member } from './utils'; + +/** A GitHub team's direct members and its pending invitations. */ +export interface TeamState { + team: string; + members: string[]; + invited: string[]; +} + +export interface Removal { + team: string; + login: string; +} + +export interface RemovalPlan { + removals: Removal[]; + /** Teams left alone, with the reason */ + skipped: string[]; +} + +/** Most removals one deploy may make. More than this likely means a mistake in the config. */ +export const MAX_REMOVALS = 20; + +/** The logins that users.ts puts directly in each GitHub team, in lower case. */ +export function declaredTeamMembers( + members: readonly Member[] = MEMBERS, + roles: readonly Role[] = ROLES +): Map> { + const declared = new Map>(); + for (const role of roles) { + if (!role.github) continue; + const logins = declared.get(role.github.team) ?? new Set(); + for (const m of members) { + if (m.github && m.memberOf.includes(role.id)) logins.add(m.github.toLowerCase()); + } + declared.set(role.github.team, logins); + } + return declared; +} + +/** + * The people to remove: in a managed team, but not put there by users.ts. A team that lacks + * someone users.ts declares is skipped. That person may have renamed their account, and would + * then look like someone undeclared. + */ +export function planRemovals( + live: readonly TeamState[], + declared: Map> = declaredTeamMembers() +): RemovalPlan { + const plan: RemovalPlan = { removals: [], skipped: [] }; + for (const { team, members, invited } of live) { + const logins = declared.get(team); + if (!logins) continue; + const present = [...members, ...invited]; + const presentLogins = new Set(present.map((login) => login.toLowerCase())); + const extra = present.filter((login) => !logins.has(login.toLowerCase())); + if (extra.length === 0) continue; + const missing = [...logins].filter((login) => !presentLogins.has(login)); + if (missing.length > 0) { + plan.skipped.push(`${team}: ${missing.join(', ')} not found in the team`); + } else { + plan.removals.push(...extra.map((login) => ({ team, login }))); + } + } + return plan; +} + +export function assertSafeToRemove(removals: readonly Removal[], max = MAX_REMOVALS): void { + if (removals.length > max) { + throw new Error( + `${removals.length} removals is over the limit of ${max}, so nothing was removed. ` + + 'Add the people to users.ts, or remove them in GitHub.' + ); + } +} diff --git a/src/config/users.ts b/src/config/users.ts index 3a7db0ca..1d7e3d38 100644 --- a/src/config/users.ts +++ b/src/config/users.ts @@ -330,6 +330,7 @@ export const MEMBERS: readonly Member[] = [ ROLE_IDS.CORE_MAINTAINERS, ROLE_IDS.DOCS_MAINTAINERS, ROLE_IDS.MODERATORS, + ROLE_IDS.SDK_MAINTAINERS, ROLE_IDS.SERVER_CARD_WG, ROLE_IDS.AGENTS_IG, ROLE_IDS.CORE_PRIMITIVE_WG, @@ -398,6 +399,7 @@ export const MEMBERS: readonly Member[] = [ ROLE_IDS.SECURITY_IG, ROLE_IDS.SECURITY_TEAM, ROLE_IDS.TYPESCRIPT_SDK, + ROLE_IDS.TYPESCRIPT_SDK_AUTH, ], }, {