Skip to content

Commit 6503c45

Browse files
committed
fix(sections): the live-duplicate guard covers every snapshot; a repeated rule type is a settings-file error; addressed names and one plural in the guard
Copilot and gate review folds: the guard runs before every bespoke snapshot's projection (repo secrets and variables, custom properties, secret scanning patterns, collaborators and invitations, environments' nested lists); rulesets name a repeated rule type before the read instead of a BUG crash and refuse a live body repeating one; the guard names a live item with its address; plural() spells the nouns; collaborators and teams role drift and nested mapping mismatches render declared-first; webhook writes never carry name.
1 parent e7c8234 commit 6503c45

18 files changed

Lines changed: 262 additions & 52 deletions

File tree

‎docs/upgrading/v2-to-v3.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,9 @@ Anything that greps the check output for these lines needs the new spelling:
165165
## 13. Webhooks manage web hooks only
166166

167167
- A legacy service hook (`name` other than `web`) or a hook without a `config.url` is outside the section: plan neither matches, notes, nor deletes it (v2 deleted one under `_undeclared: delete`); snapshot leaves it out with a note.
168-
- The create body carries `name` only when the file declares it; GitHub defaults a new hook to `web`.
168+
- No write carries `name`: GitHub defaults a new hook to `web`, the one value the slice admits, and the update endpoint takes no name.
169169
- A declared `insecure_ssl: 0` is written as GitHub stores it, the string `"0"`.
170+
- A snapshot writes a hook's `config` keys in the order GitHub lists them, the `$SECRET_WEBHOOK_<id>` reference last.
170171

171172
## 14. A ruleset without `source_type` is repository-owned
172173

‎src/sections/collaborators/collaborators.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ describe("collaborators", () => {
4545
payload: { permission: "push" },
4646
describe: 'updating collaborator "alice"',
4747
drift: [
48-
'collaborators[alice]: live role "read" != declared "write"; apply will set the declared permission',
48+
'collaborators[alice]: declared "write" != live "read"; apply will set the declared permission',
4949
],
5050
change: 'updated collaborator "alice" (push)',
5151
},
@@ -132,7 +132,7 @@ describe("collaborators", () => {
132132
payload: { permissions: "write" },
133133
describe: 'updating the pending invitation for "alice"',
134134
drift: [
135-
'collaborators[alice]: pending invitation permission "read" != declared "write"; apply will update the invitation',
135+
'collaborators[alice] (pending invitation): declared "write" != live "read"; apply will update the invitation',
136136
],
137137
change: 'updated pending invitation for "alice" (push)',
138138
},

‎src/sections/collaborators/index.ts‎

Lines changed: 38 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
undeclaredDrift,
1212
undeclaredNote,
1313
undeclaredPolicy,
14+
valueDrift,
1415
} from "../contract/module.js";
1516
import type { SectionPermission } from "../contract/permissions.js";
1617
import type { PlanContext, PlannedOp, SectionPlan } from "../contract/plan.js";
@@ -91,13 +92,15 @@ function declaredPermission(label: string, role: string): string {
9192
return permission;
9293
}
9394

94-
/** Both pools in one read, so plan() and snapshot() see the same live access. */
95+
/** Both pools in one read, each indexed under the guard, so plan() and snapshot() see the same live access. */
9596
async function readLiveAccess(
9697
ctx: CollaboratorsContext,
9798
section: SectionMeta,
9899
): Promise<{
99100
collaborators: LiveCollaborator[];
101+
liveByLogin: Map<string, LiveCollaborator>;
100102
invitations: NamedInvitation[];
103+
inviteByLogin: Map<string, NamedInvitation>;
101104
emailInvitations: LiveInvitation[];
102105
}> {
103106
const collaborators = parseLive(
@@ -112,9 +115,24 @@ async function readLiveAccess(
112115
z.array(LiveInvitation),
113116
await ctx.read.listInvitations.listAll(),
114117
);
118+
const invitations = allInvitations.filter(isNamedInvitation);
115119
return {
116120
collaborators,
117-
invitations: allInvitations.filter(isNamedInvitation),
121+
liveByLogin: liveByIdentity(
122+
section,
123+
"collaborator",
124+
collaborators,
125+
(c) => c.login.toLowerCase(),
126+
(c) => c.login,
127+
),
128+
invitations,
129+
inviteByLogin: liveByIdentity(
130+
section,
131+
"pending invitation",
132+
invitations,
133+
(invitation) => invitation.invitee.login.toLowerCase(),
134+
(invitation) => invitation.invitee.login,
135+
),
118136
emailInvitations: allInvitations.filter((invitation) => !isNamedInvitation(invitation)),
119137
};
120138
}
@@ -150,21 +168,13 @@ export const collaboratorsSection = {
150168
// Both pools are resolved BEFORE the declared walk, so a declared user is never mistaken for
151169
// undeclared in the other pool; email invitations (null invitee, which no username can declare)
152170
// split into their own pool.
153-
const { collaborators: live, invitations, emailInvitations } = await readLiveAccess(ctx, this);
154-
const liveByLogin = liveByIdentity(
155-
this,
156-
"collaborator",
157-
live,
158-
(c) => c.login.toLowerCase(),
159-
(c) => c.login,
160-
);
161-
const inviteByLogin = liveByIdentity(
162-
this,
163-
"pending invitation",
171+
const {
172+
collaborators: live,
173+
liveByLogin,
164174
invitations,
165-
(invitation) => invitation.invitee.login.toLowerCase(),
166-
(invitation) => invitation.invitee.login,
167-
);
175+
inviteByLogin,
176+
emailInvitations,
177+
} = await readLiveAccess(ctx, this);
168178
const declaredKeys = new Set<string>();
169179
const plan: SectionPlan<PlannedOp<typeof ENDPOINTS>> = { ops: [], notes: [], drift: [] };
170180

@@ -185,7 +195,12 @@ export const collaboratorsSection = {
185195
payload: { permission: wantPermission },
186196
describe: `updating collaborator "${username}"`,
187197
drift: [
188-
`${label}: live role "${existing.role_name}" != declared "${wantRole}"; apply will set the declared permission`,
198+
valueDrift(
199+
label,
200+
JSON.stringify(wantRole),
201+
JSON.stringify(existing.role_name),
202+
"apply will set the declared permission",
203+
),
189204
],
190205
change: `updated collaborator "${username}" (${wantPermission})`,
191206
});
@@ -210,7 +225,12 @@ export const collaboratorsSection = {
210225
payload: { permissions: wantRole },
211226
describe: `updating the pending invitation for "${username}"`,
212227
drift: [
213-
`${label}: pending invitation permission "${invitation.permissions}" != declared "${wantRole}"; apply will update the invitation`,
228+
valueDrift(
229+
`${label} (pending invitation)`,
230+
JSON.stringify(wantRole),
231+
JSON.stringify(invitation.permissions),
232+
"apply will update the invitation",
233+
),
214234
],
215235
change: `updated pending invitation for "${username}" (${wantPermission})`,
216236
});

‎src/sections/contract/live.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,11 @@ import { type EndpointDecl, endpointMethod, endpointPath } from "./endpoints.js"
99
import type { SectionMeta } from "./module.js";
1010
import { collidingPairs } from "./requests.js";
1111

12+
/** The plural of a section noun for a message ("custom property" -> "custom properties", "deploy key" -> "deploy keys"). */
13+
export function plural(noun: string): string {
14+
return /[^aeiou]y$/.test(noun) ? `${noun.slice(0, -1)}ies` : `${noun}s`;
15+
}
16+
1217
/**
1318
* Live items indexed by the identity the section manages them under. GitHub may hold two under one
1419
* (repeated deploy-key titles, repeated hook urls, two names one fold apart), which a single-slot map
@@ -25,7 +30,7 @@ export function liveByIdentity<T, Key extends string>(
2530
const collisions = collidingPairs(items, keyOf, describe);
2631
if (collisions.length > 0) {
2732
throw new Error(
28-
`${section.key}: GitHub holds ${noun}s that resolve to one identity: ${collisions.join("; ")}. This section manages one ${noun} per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again`,
33+
`${section.key}: GitHub holds ${plural(noun)} that resolve to one identity: ${collisions.join("; ")}. This section manages one ${noun} per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again`,
2934
);
3035
}
3136
return new Map(items.map((item) => [keyOf(item), item]));

‎src/sections/custom_properties/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,13 @@ export const customPropertiesSection = {
245245
};
246246
}
247247
const live = parseLive(this, ENDPOINTS.list, z.array(LiveProperty), await ctx.read.list.call());
248+
liveByIdentity(
249+
this,
250+
"custom property",
251+
live,
252+
(p) => p.property_name,
253+
(p) => p.property_name,
254+
);
248255
const set = live.flatMap((property) => {
249256
if (property.value === null) {
250257
return [];

‎src/sections/deploy_keys/deploy_keys.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ describe("deploy_keys conflicts", () => {
107107
},
108108
});
109109
await expect(plan(api, [{ title: "deploy-bot", key: BOT_KEY }])).rejects.toThrow(
110-
'deploy_keys: GitHub holds deploy keys that resolve to one identity: "deploy-bot" and "deploy-bot". This section manages one deploy key per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again',
110+
'deploy_keys: GitHub holds deploy keys that resolve to one identity: "deploy-bot (key id 11)" and "deploy-bot (key id 12)". This section manages one deploy key per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again',
111111
);
112112
await expect(plan(api, [])).rejects.toThrow(/resolve to one identity/);
113113
expect(api.mutations()).toEqual([]);

‎src/sections/environments/snapshot.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,12 @@
66

77
import { snapshotSecretReference } from "../../engine/secrets.js";
88
import type { UndeclaredPolicyList } from "../../types.js";
9+
import { liveByIdentity } from "../contract/live.js";
910
import type { SectionMeta } from "../contract/module.js";
1011
import type { SnapshotContext } from "../contract/plan.js";
1112
import { secretKey } from "../shared/secrets-engine.js";
1213
import { projectOntoSchema, readOrNote } from "../shared/snapshot-helpers.js";
14+
import { variableKey } from "../shared/variables-engine.js";
1315
import { listBranchPolicies } from "./branch-policies.js";
1416
import type { ENDPOINTS } from "./endpoints.js";
1517
import {
@@ -85,13 +87,27 @@ export async function snapshotNested(
8587
const nested: NestedSnapshot = {};
8688
const notes: string[] = [];
8789
const variables = await listEnvironmentVariables(ctx, section, envName);
90+
liveByIdentity(
91+
section,
92+
"variable",
93+
variables,
94+
(variable) => variableKey(variable.name),
95+
(variable) => variable.name,
96+
);
8897
if (variables.length > 0) {
8998
nested.variables = wrapped(
9099
"variables",
91100
variables.map((variable) => projectOntoSchema(EnvironmentVariableConfig, variable)),
92101
);
93102
}
94103
const secrets = await listEnvironmentSecrets(ctx, section, envName);
104+
liveByIdentity(
105+
section,
106+
`${envName} environment secret`,
107+
secrets,
108+
(secret) => secretKey(secret.name),
109+
(secret) => secret.name,
110+
);
95111
if (secrets.length > 0) {
96112
// Names go through secretKey, the uppercase form GitHub stores and the planner compares by,
97113
// so a lowercase listing still mints a reference the settings-file grammar accepts.
@@ -118,6 +134,13 @@ export async function snapshotNested(
118134
() => listBranchPolicies(ctx, section, envName),
119135
);
120136
if ("value" in policies && policies.value.length > 0) {
137+
liveByIdentity(
138+
section,
139+
"deployment branch policy",
140+
policies.value,
141+
(policy) => String(policy.name),
142+
(policy) => String(policy.name),
143+
);
121144
nested.deployment_branch_policies = wrapped(
122145
"deployment_branch_policies",
123146
policies.value.map((policy) => projectOntoSchema(DeploymentBranchPolicyConfig, policy)),
@@ -132,6 +155,13 @@ export async function snapshotNested(
132155
);
133156
if ("value" in rules) {
134157
const enabled = rules.value.filter((rule) => rule.enabled !== false);
158+
liveByIdentity(
159+
section,
160+
"deployment protection rule",
161+
enabled,
162+
(rule) => liveRuleSlug(rule, envName),
163+
(rule) => liveRuleSlug(rule, envName),
164+
);
135165
if (enabled.length > 0) {
136166
nested.deployment_protection_rules = wrapped(
137167
"deployment_protection_rules",

‎src/sections/rulesets/index.ts‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,20 @@ export function normalizeRuleset(ruleset: RulesetConfig): RulesetConfig {
4444
return copy;
4545
}
4646

47+
/** The rule types a ruleset repeats; rules pair by type, so a repeat has no pairing. */
48+
function repeatedRuleTypes(rules: readonly { readonly type: unknown }[] | undefined): string[] {
49+
const seen = new Set<string>();
50+
const repeated = new Set<string>();
51+
for (const rule of rules ?? []) {
52+
const type = String(rule.type);
53+
if (seen.has(type)) {
54+
repeated.add(type);
55+
}
56+
seen.add(type);
57+
}
58+
return [...repeated];
59+
}
60+
4761
/**
4862
* A summary or a full body: the list and the per-item GET share these fields. The API type leaves
4963
* `source_type` optional; a body without it reads as repository-owned, the only kind the repository
@@ -53,7 +67,20 @@ const LiveRuleset = z.looseObject({
5367
id: z.number(),
5468
name: z.string(),
5569
source_type: z.string().optional(),
70+
rules: z.array(z.looseObject({ type: z.string() })).optional(),
5671
});
72+
type LiveRuleset = z.infer<typeof LiveRuleset>;
73+
74+
/** A live body repeating a rule type has no pairing either; GitHub keeps one rule per type, so this names a defect worth a look. */
75+
function pairableRuleset(live: LiveRuleset): LiveRuleset {
76+
const repeated = repeatedRuleTypes(live.rules);
77+
if (repeated.length > 0) {
78+
throw new Error(
79+
`rulesets: GitHub returned the ruleset "${live.name}" (id ${live.id}) with the rule type${repeated.length === 1 ? "" : "s"} ${repeated.map((type) => `"${type}"`).join(", ")} more than once, so its rules cannot be paired by type; delete the repeated rule on GitHub, then re-run`,
80+
);
81+
}
82+
return live;
83+
}
5784

5885
// Rules pass through verbatim, so a typo'd rules[].type reaches GitHub unchanged and comes back as
5986
// a 422; the valid types live in the endpoint docs, not here, so they cannot go stale.
@@ -100,10 +127,22 @@ export const rulesetsSection = listSection({
100127
// The full ruleset is the wire body (a partial PUT narrows a ruleset). The slice types rule
101128
// parameters and bypass actors as unknown passthrough; the factory proves the body plain at the payload.
102129
toWrite: (ruleset) => ({ ...normalizeRuleset(ruleset) }) as ListWrite<"name">,
103-
fromLive: (live) => live,
130+
fromLive: (live) => pairableRuleset(live),
104131
// Rules pair by type, as the layered merge does; every other list pairs by shape.
105132
matchBy: { rules: "type" },
106133
},
134+
// GitHub keeps one rule per type, and the comparison pairs rules by it, so a repeated type is a settings-file mistake.
135+
conflicts: {
136+
declared: (writes) =>
137+
writes.flatMap((write) => {
138+
const repeated = repeatedRuleTypes(write.rules as { readonly type: unknown }[] | undefined);
139+
return repeated.length === 0
140+
? []
141+
: [
142+
`the ruleset "${write.name}" lists the rule type${repeated.length === 1 ? "" : "s"} ${repeated.map((type) => `"${type}"`).join(", ")} more than once, and GitHub keeps one rule per type - declare each type once`,
143+
];
144+
}),
145+
},
107146
// Only a ruleset the API marks repository-owned is this section's; an inherited one is managed where it is defined.
108147
foreign: (live) =>
109148
live.source_type === undefined || live.source_type === "Repository"

‎src/sections/rulesets/rulesets.test.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,32 @@ describe("rulesets", () => {
395395
expect(api.calls).toHaveLength(0);
396396
});
397397

398+
test("a repeated rule type is a settings-file error before any read, and a live body repeating one fails loudly naming the ruleset", async () => {
399+
// Rules pair by type, so a repeat has no pairing; the settings-file case names the fix, the live case the defect.
400+
const api = writable({
401+
[listRoute]: { data: [{ id: 9, name: "main", source_type: "Repository" }] },
402+
"GET /repos/o/r/rulesets/9": {
403+
data: {
404+
id: 9,
405+
name: "main",
406+
target: "branch",
407+
enforcement: "active",
408+
rules: [{ type: "deletion" }, { type: "deletion" }],
409+
},
410+
},
411+
});
412+
await expect(
413+
plan(api, [{ name: "main", rules: [{ type: "deletion" }, { type: "deletion" }] }]),
414+
).rejects.toThrow(
415+
'rulesets: the settings file declares conflicting rulesets: the ruleset "main" lists the rule type "deletion" more than once, and GitHub keeps one rule per type - declare each type once. Fix the settings file, then re-run',
416+
);
417+
expect(api.calls).toHaveLength(0);
418+
await expect(plan(api, [{ name: "main", rules: [{ type: "deletion" }] }])).rejects.toThrow(
419+
'rulesets: GitHub returned the ruleset "main" (id 9) with the rule type "deletion" more than once, so its rules cannot be paired by type; delete the repeated rule on GitHub, then re-run',
420+
);
421+
expect(api.mutations()).toEqual([]);
422+
});
423+
398424
test("wrapped _undeclared:delete plans the DELETE after the declared upserts", async () => {
399425
const api = writable({
400426
[listRoute]: {
@@ -625,7 +651,7 @@ describe("rulesets snapshot", () => {
625651
served(2, "main", { target: "tag", enforcement: "active" }),
626652
]);
627653
await expect(snapshot(api)).rejects.toThrow(
628-
'rulesets: GitHub holds rulesets that resolve to one identity: "main" and "main". This section manages one ruleset per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again',
654+
'rulesets: GitHub holds rulesets that resolve to one identity: "main (ruleset id 1)" and "main (ruleset id 2)". This section manages one ruleset per identity, so it cannot tell them apart; delete all but one of each on GitHub, then run again',
629655
);
630656
});
631657

‎src/sections/secret_scanning_custom_patterns/index.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,6 +276,13 @@ export const secretScanningPatternsSection = {
276276
if (live.length === 0) {
277277
return { value: undefined, notes: [] };
278278
}
279+
liveByIdentity(
280+
this,
281+
"secret scanning custom pattern",
282+
live,
283+
(p) => p.name,
284+
(p) => p.name,
285+
);
279286
const entries = live.map((pattern) => projectOntoSchema(SecretScanningPatternConfig, pattern));
280287
return { value: knobbedSnapshot(this, entries), notes: [] };
281288
},

0 commit comments

Comments
 (0)