Skip to content
Merged
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
6 changes: 6 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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 .",
Expand Down
148 changes: 148 additions & 0 deletions scripts/sync-team-members.ts
Original file line number Diff line number Diff line change
@@ -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=<token> npm run sync-team-members # list only
* GITHUB_TOKEN=<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<Response> {
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<string[]> {
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<string[]> {
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<TeamState> {
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<void> {
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<void> {
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);
});
55 changes: 54 additions & 1 deletion scripts/test-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<string>()],
['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', () =>
Expand Down
77 changes: 77 additions & 0 deletions src/config/teamSync.ts
Original file line number Diff line number Diff line change
@@ -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<string, Set<string>> {
const declared = new Map<string, Set<string>>();
for (const role of roles) {
if (!role.github) continue;
const logins = declared.get(role.github.team) ?? new Set<string>();
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<string, Set<string>> = 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.'
);
}
}
2 changes: 2 additions & 0 deletions src/config/users.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
],
},
{
Expand Down
Loading