Skip to content

Commit c6a2fcd

Browse files
committed
feat(snapshot): repository, actions, and rulesets read back
The three bespoke sections gain snapshot(): repository reads back the documented PATCH fields (an allowlist pinned to the octokit PATCH body type, since the passthrough slice cannot tell server fields apart; name and null fields are left out), topics, every readable toggle, and the two GraphQL keys, noting Git LFS, an owner-enforced toggle, and any denied sub-read; actions reads every endpoint back onto its key through the routing table (each routed destination now carries its own snapshot), with a denied sub-read a note naming the key and the allowlist read only under the selected policy; rulesets reads repository-owned rulesets back as keep entries, noting an inherited ruleset and an invisible bypass_actors instead of claiming an empty list. The round-trip harness fake now dispatches GraphQL onto the mock's GraphQL handlers, which the repository row (and the GraphQL-reading sections still to come) needs; the engine test's supported-section pins and the changed-sections fan-out canary follow the new snapshot() declarations and import edges.
1 parent da2af61 commit c6a2fcd

16 files changed

Lines changed: 884 additions & 35 deletions

File tree

‎COVERAGE.md‎

Lines changed: 3 additions & 3 deletions
Large diffs are not rendered by default.

‎src/sections/actions/actions.docs.yml‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ coverage:
3535
Actions are on), and selected_actions with no allowed_actions infers allowed_actions:
3636
selected. RISK: a key GitHub adds that belongs on a NEW sub-endpoint gets routed to the base
3737
PUT where GitHub ignores it; audit the routing whenever GitHub adds a permissions
38-
sub-endpoint.
38+
sub-endpoint. Snapshot reads every endpoint back onto its key (the allowlist only under the
39+
selected policy; the read-only fields each GET adds, like maximum_allowed_days, fall away); a
40+
sub-endpoint the token cannot read, such as the OIDC template under a token without the
41+
Actions permission, is noted and left out rather than failing the section.
3942
schema:
4043
SettingsFile.actions: GitHub Actions permissions for the repository.
4144
ActionsConfig: GitHub Actions settings, routed to the right endpoint by key.

‎src/sections/actions/actions.test.ts‎

Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { provePlanIdempotent } from "../../../test/sections/plan-idempotence.js"
77
import { REPO } from "../../../test/sections/section-run.js";
88
import { describeProblem } from "../../problem.js";
99
import { PermissionDenied } from "../contract/errors.js";
10+
import { sectionGrant } from "../contract/module.js";
1011
import { grantFor } from "../contract/permissions.js";
1112
import { actionsSection, endpointRouted } from "./index.js";
1213
// The `as ActionsConfig` casts below simulate keys GitHub adds: the shape passes unknown keys through verbatim, which the static config type cannot
@@ -547,6 +548,7 @@ describe("actions", () => {
547548
label: "actions.access",
548549
applied: "applied",
549550
body: (value) => ({ access_level: value }),
551+
read: () => "none",
550552
});
551553
expect(typeof paired.plan).toBe("function");
552554
endpointRouted<"access_level", "Access">({
@@ -556,13 +558,15 @@ describe("actions", () => {
556558
label: "actions.access",
557559
applied: "applied",
558560
body: (value) => ({ access_level: value }),
561+
read: () => "none",
559562
});
560563
// @ts-expect-error an enum-valued key cannot be PUT bare: body is required
561564
endpointRouted<"access_level", "Access">({
562565
get: "getAccess",
563566
put: "putAccess",
564567
label: "actions.access",
565568
applied: "applied",
569+
read: () => "none",
566570
});
567571
});
568572

@@ -576,3 +580,127 @@ describe("actions", () => {
576580
const _silent: Op = silent;
577581
});
578582
});
583+
584+
describe("actions snapshot", () => {
585+
const snapshot = (api: GithubClient) =>
586+
actionsSection.snapshot(planContext(actionsSection, api, REPO));
587+
/** The note a sub-read the fake has no body for produces: its 404 classifies as a denial. */
588+
const leftOut = (key: string, path: string, grant = sectionGrant(actionsSection)) =>
589+
`actions.${key}: left out of the snapshot - the token was denied GET ${path}: 404 Not Found (a 404 here can also mean the resource does not exist). To fix, ${grant}`;
590+
591+
test("reads every endpoint back onto its key, dropping the server fields each GET adds", async () => {
592+
const api = liveActions({
593+
[BASE]: {
594+
enabled: true,
595+
allowed_actions: "selected",
596+
selected_actions_url: `https://api.github.com${BASE}/selected-actions`,
597+
},
598+
[`${BASE}/selected-actions`]: {
599+
github_owned_allowed: true,
600+
verified_allowed: false,
601+
patterns_allowed: ["actions/*"],
602+
},
603+
[`${BASE}/workflow`]: {
604+
default_workflow_permissions: "read",
605+
can_approve_pull_request_reviews: false,
606+
},
607+
[`${BASE}/access`]: { access_level: "organization" },
608+
[`${BASE}/artifact-and-log-retention`]: { days: 30, maximum_allowed_days: 400 },
609+
"/repos/o/r/actions/cache/retention-limit": { max_cache_retention_days: 5 },
610+
"/repos/o/r/actions/cache/storage-limit": { max_cache_size_gb: 20 },
611+
"/repos/o/r/actions/oidc/customization/sub": {
612+
use_default: false,
613+
include_claim_keys: ["repo", "context"],
614+
},
615+
[`${BASE}/fork-pr-contributor-approval`]: { approval_policy: "first_time_contributors" },
616+
[`${BASE}/fork-pr-workflows-private-repos`]: {
617+
run_workflows_from_fork_pull_requests: true,
618+
send_write_tokens_to_workflows: false,
619+
send_secrets_and_variables: false,
620+
require_approval_for_fork_pr_workflows: true,
621+
},
622+
});
623+
expect(await snapshot(api)).toEqual({
624+
value: {
625+
enabled: true,
626+
allowed_actions: "selected",
627+
default_workflow_permissions: "read",
628+
can_approve_pull_request_reviews: false,
629+
selected_actions: {
630+
github_owned_allowed: true,
631+
verified_allowed: false,
632+
patterns_allowed: ["actions/*"],
633+
},
634+
access_level: "organization",
635+
artifact_and_log_retention: { days: 30 },
636+
cache: { max_cache_retention_days: 5, max_cache_size_gb: 20 },
637+
oidc_customization_sub: { use_default: false, include_claim_keys: ["repo", "context"] },
638+
fork_pr_contributor_approval: { approval_policy: "first_time_contributors" },
639+
fork_pr_workflows_private_repos: {
640+
run_workflows_from_fork_pull_requests: true,
641+
send_write_tokens_to_workflows: false,
642+
send_secrets_and_variables: false,
643+
require_approval_for_fork_pr_workflows: true,
644+
},
645+
},
646+
notes: [],
647+
});
648+
expect(api.writes).toEqual([]);
649+
});
650+
651+
test("a denied sub-read is a note naming its key with the read's own grant; the allowlist is skipped off the selected policy", async () => {
652+
const live = liveActions({
653+
[BASE]: { enabled: true, allowed_actions: "all" },
654+
[`${BASE}/artifact-and-log-retention`]: { days: 90, maximum_allowed_days: 400 },
655+
"/repos/o/r/actions/cache/retention-limit": { max_cache_retention_days: 7 },
656+
"/repos/o/r/actions/cache/storage-limit": { max_cache_size_gb: 10 },
657+
[`${BASE}/fork-pr-contributor-approval`]: { approval_policy: "all_external_contributors" },
658+
});
659+
const requested: string[] = [];
660+
const api: GithubClient = {
661+
tryRequest: (method, path, payload) => {
662+
requested.push(`${method} ${path}`);
663+
return live.tryRequest(method, path, payload);
664+
},
665+
tryGraphql: live.tryGraphql,
666+
};
667+
const read = await snapshot(api);
668+
expect(read).toEqual({
669+
value: {
670+
enabled: true,
671+
allowed_actions: "all",
672+
artifact_and_log_retention: { days: 90 },
673+
cache: { max_cache_retention_days: 7, max_cache_size_gb: 10 },
674+
fork_pr_contributor_approval: { approval_policy: "all_external_contributors" },
675+
},
676+
notes: [
677+
leftOut(
678+
"default_workflow_permissions/can_approve_pull_request_reviews",
679+
`${BASE}/workflow`,
680+
),
681+
leftOut("access_level", `${BASE}/access`),
682+
leftOut(
683+
"oidc_customization_sub",
684+
"/repos/o/r/actions/oidc/customization/sub",
685+
grantFor({ repo: ["actions"] }, undefined, "write"),
686+
),
687+
`${leftOut("fork_pr_workflows_private_repos", `${BASE}/fork-pr-workflows-private-repos`)}. Note: the fork PR workflow settings are documented for private repositories, so a denial here can also mean the repository is public`,
688+
],
689+
});
690+
// Off the "selected" policy there is no allowlist to read, so the GET is never issued.
691+
expect(requested).not.toContain(`GET ${BASE}/selected-actions`);
692+
expect(live.writes).toEqual([]);
693+
});
694+
695+
test("a denied primary read fails the section like any other, carrying the grant advice", async () => {
696+
const api = liveActions({});
697+
let thrown: unknown;
698+
try {
699+
await snapshot(api);
700+
} catch (error) {
701+
thrown = error;
702+
}
703+
expect(thrown).toBeInstanceOf(PermissionDenied);
704+
expect((thrown as PermissionDenied).detail).toContain(sectionGrant(actionsSection));
705+
});
706+
});

‎src/sections/actions/index.ts‎

Lines changed: 80 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
plainData,
1313
type SectionPlan,
1414
} from "../contract/plan.js";
15+
import { projectOntoSchema, readOrNote } from "../shared/snapshot-helpers.js";
1516
import { ActionsConfig } from "./schema.js";
1617

1718
const permission: SectionPermission = { repo: ["administration"] };
@@ -181,9 +182,12 @@ function sameClaimKeyOrder(declared: readonly string[], live: readonly string[])
181182
// subsetDiff as passthrough.
182183
const LiveOidcSub = z.looseObject({ include_claim_keys: z.array(z.string()).nullish() });
183184

185+
/** The base-permissions keys as the primary read reports them; the allowlist read hangs off the policy. */
186+
type BasePermissions = Pick<ActionsConfig, "enabled" | "allowed_actions">;
187+
184188
/**
185-
* The routing table holds the handler itself, so a routed key without a handler cannot exist.
186-
* A function-valued property, not method shorthand, so the per-key value types check strictly.
189+
* The routing table holds the handlers themselves, so a routed key without one cannot exist.
190+
* Function-valued properties, not method shorthand, so the per-key value types check strictly.
187191
*/
188192
interface RoutedDestination<K extends keyof ActionsConfig> {
189193
plan: (
@@ -192,6 +196,12 @@ interface RoutedDestination<K extends keyof ActionsConfig> {
192196
declared: NonNullable<ActionsConfig[K]>,
193197
plan: ActionsPlan,
194198
) => Promise<void>;
199+
/** Read the live state back as the settings file would declare it; undefined when none applies. */
200+
snapshot: (
201+
ctx: ActionsContext,
202+
section: SectionMeta,
203+
base: BasePermissions,
204+
) => Promise<ActionsConfig[K]>;
195205
}
196206

197207
/** `N` is inferred from the GET alone, so a PUT of another name does not compile. */
@@ -204,6 +214,8 @@ export function endpointRouted<K extends keyof ActionsConfig, N extends string>(
204214
/** The change line apply reports after the PUT lands. */
205215
applied: string;
206216
describe?: string;
217+
/** The GET body as the settings file declares the key (the inverse of `body`). */
218+
read: (live: unknown) => ActionsConfig[K];
207219
} & (NonNullable<ActionsConfig[K]> extends Record<string, unknown>
208220
? { body?: (declared: NonNullable<ActionsConfig[K]>) => Record<string, unknown> }
209221
: { body: (declared: NonNullable<ActionsConfig[K]>) => Record<string, unknown> }),
@@ -226,9 +238,16 @@ export function endpointRouted<K extends keyof ActionsConfig, N extends string>(
226238
});
227239
}
228240
},
241+
snapshot: async (ctx) => wiring.read(await ctx.read[wiring.get].call()),
229242
};
230243
}
231244

245+
/** The live body of one routed key projected onto its slice of the section shape. */
246+
function sliceOf<K extends keyof ActionsConfig>(key: K): (live: unknown) => ActionsConfig[K] {
247+
const slice: z.ZodType = ActionsConfig.shape[key];
248+
return (live) => projectOntoSchema(slice, live) as ActionsConfig[K];
249+
}
250+
232251
// Every DECLARED key names its destination, so the mapped `satisfies` makes a schema field with no
233252
// entry a compile error; a routed entry IS its handler, so routed-but-unhandled cannot exist either.
234253
// Undeclared (future) keys fall through to the base permissions PUT verbatim, never silently dropped.
@@ -255,6 +274,15 @@ const KEY_DESTINATION = {
255274
});
256275
}
257276
},
277+
// The allowlist exists only under the "selected" policy (the GET 409s otherwise), so no
278+
// other policy reads it: an allowlist beside another policy is a document the shape rejects.
279+
snapshot: async (ctx, _section, base) => {
280+
if (base.allowed_actions !== "selected") {
281+
return undefined;
282+
}
283+
const probe = await ctx.read.getSelected.probeAbsent();
284+
return "missing" in probe ? undefined : sliceOf("selected_actions")(probe.data);
285+
},
258286
},
259287
default_workflow_permissions: "workflow",
260288
can_approve_pull_request_reviews: "workflow",
@@ -264,13 +292,15 @@ const KEY_DESTINATION = {
264292
label: "actions.access",
265293
applied: "applied workflows access level",
266294
body: (value) => ({ access_level: value }),
295+
read: (live) => sliceOf("access_level")((live as { access_level?: unknown }).access_level),
267296
}),
268297
artifact_and_log_retention: endpointRouted({
269298
get: "getRetention",
270299
put: "putRetention",
271300
label: "actions.artifact_and_log_retention",
272301
applied: "applied artifact and log retention",
273302
describe: "setting the artifact and log retention window",
303+
read: sliceOf("artifact_and_log_retention"),
274304
}),
275305
cache: {
276306
plan: async (ctx, _section, declared, plan) => {
@@ -293,6 +323,14 @@ const KEY_DESTINATION = {
293323
}
294324
}
295325
},
326+
// Each limit is its own GET; merged, the strict cache slice keeps exactly the two keys.
327+
snapshot: async (ctx) => {
328+
const limits: Record<string, unknown> = {};
329+
for (const wiring of Object.values(CACHE_ENDPOINT_BY_KEY)) {
330+
Object.assign(limits, await ctx.read[wiring.get].call());
331+
}
332+
return sliceOf("cache")(limits);
333+
},
296334
},
297335
oidc_customization_sub: {
298336
plan: async (ctx, section, declared, plan) => {
@@ -325,20 +363,26 @@ const KEY_DESTINATION = {
325363
});
326364
}
327365
},
366+
snapshot: async (ctx, section) =>
367+
sliceOf("oidc_customization_sub")(
368+
parseLive(section, ENDPOINTS.getOidcSub, LiveOidcSub, await ctx.read.getOidcSub.call()),
369+
),
328370
},
329371
fork_pr_contributor_approval: endpointRouted({
330372
get: "getForkPrApproval",
331373
put: "putForkPrApproval",
332374
label: "actions.fork_pr_contributor_approval",
333375
applied: "applied the fork PR contributor approval policy",
334376
describe: "setting the fork PR contributor approval policy",
377+
read: sliceOf("fork_pr_contributor_approval"),
335378
}),
336379
fork_pr_workflows_private_repos: endpointRouted({
337380
get: "getForkPrPrivate",
338381
put: "putForkPrPrivate",
339382
label: "actions.fork_pr_workflows_private_repos",
340383
applied: "applied the private-repo fork PR workflow settings",
341384
describe: "setting the private-repo fork PR workflow settings",
385+
read: sliceOf("fork_pr_workflows_private_repos"),
342386
}),
343387
} satisfies { [K in keyof ActionsConfig]-?: "base" | "workflow" | RoutedDestination<K> };
344388

@@ -369,6 +413,20 @@ async function planRouted<K extends RoutedKey>(
369413
await ROUTED_DESTINATIONS[key].plan(ctx, section, declared, plan);
370414
}
371415

416+
/** Read one routed key back; generic so the handler and the value stay correlated to one key. */
417+
async function snapshotRouted<K extends RoutedKey>(
418+
key: K,
419+
ctx: ActionsContext,
420+
section: SectionMeta,
421+
base: BasePermissions,
422+
notes: string[],
423+
): Promise<ActionsConfig[K]> {
424+
const read = await readOrNote(notes, `actions.${key}`, () =>
425+
ROUTED_DESTINATIONS[key].snapshot(ctx, section, base),
426+
);
427+
return "denied" in read ? undefined : read.value;
428+
}
429+
372430
function keysTo(destination: "base" | "workflow"): Set<string> {
373431
return new Set(
374432
Object.entries(KEY_DESTINATION)
@@ -460,4 +518,24 @@ export const actionsSection = {
460518
}
461519
return plan;
462520
},
521+
// The base permissions are the primary read, so their denial classifies the section; every
522+
// other key the token cannot read is a note naming it.
523+
async snapshot(ctx) {
524+
const notes: string[] = [];
525+
const base = projectOntoSchema(ActionsConfig, await ctx.read.getPermissions.call());
526+
const value: Record<string, unknown> = { ...base };
527+
const workflow = await readOrNote(notes, `actions.${[...WORKFLOW_KEYS].join("/")}`, () =>
528+
ctx.read.getWorkflow.call(),
529+
);
530+
if (!("denied" in workflow)) {
531+
Object.assign(value, projectOntoSchema(ActionsConfig, workflow.value));
532+
}
533+
for (const key of ROUTED_KEYS) {
534+
const read = await snapshotRouted(key, ctx, this, base, notes);
535+
if (read !== undefined) {
536+
value[key] = read;
537+
}
538+
}
539+
return { value: value as ActionsConfig, notes };
540+
},
463541
} satisfies SectionModule<"actions", typeof ENDPOINTS>;

0 commit comments

Comments
 (0)