Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
643761f
chore(kin): claim APPR-11 rulesets and CODEOWNERS
Surajsm60720 Nov 8, 2026
a82f220
feat(kin): rulesets, CODEOWNERS check and security test 23 (APPR-11)
Surajsm60720 Nov 8, 2026
d679513
Merge remote-tracking branch 'origin/kin-appr-8-github-app' into kin-…
Surajsm60720 Nov 8, 2026
76a4074
fix(kin): harden rulesets and security test 23 per review (APPR-11)
Surajsm60720 Nov 8, 2026
21dfdba
Merge origin/kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
976e281
fix(kin): test 23 treats rate limits as try-again and takes --probe-p…
Surajsm60720 Nov 8, 2026
fae245e
Merge remote-tracking branch 'origin/kin-appr-8-github-app' into kin-…
Surajsm60720 Nov 8, 2026
86ecc29
fix(kin): require last-push approval and harden test 23 cleanup (APPR…
Surajsm60720 Nov 8, 2026
c74f768
Merge origin/kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
f57c77c
Merge remote-tracking branch 'origin/kin-appr-8-github-app' into kin-…
Surajsm60720 Nov 8, 2026
59baeb8
chore: merge kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
23057e8
chore: merge kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
8fabb11
chore: merge kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
37c8f31
Merge branch 'kin-appr-8-github-app' into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
4edd4e4
Merge branch 'kin-appr-8-github-app' into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
be4b411
Merge kin-appr-8-github-app into kin-appr-11-rulesets
Surajsm60720 Nov 8, 2026
acdb988
Merge remote-tracking branch 'origin/kin-appr-8-github-app' into kin-…
GLDRoger Nov 8, 2026
8ca4362
Merge remote-tracking branch 'origin/kin' into kin-appr-11-rulesets
GLDRoger Nov 8, 2026
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
220 changes: 220 additions & 0 deletions apps/server/src/kin/github/KinRulesets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
// Pure: the approvals spec section 10 rulesets and CODEOWNERS rule. Apply, `--check` and the
// tests all read `kinRulesets`, so there is one definition of what GitHub should hold.

/**
* Required status check contexts per Kin repository; other repos pass `--status-check`. Its keys
* count as Kin repositories even when `KIN_GITHUB_REPOS` leaves them out.
*/
export const KIN_REPO_REQUIRED_CHECKS: Readonly<Record<string, ReadonlyArray<string>>> = {
// ci.yml's `Check` job fails unless every other CI job passed or was skipped as not needed.
"GLDRoger/t3code": ["Check"],
};

/**
* The GitHub Actions App (`GET /apps/github-actions`). Pinning required checks to it stops a
* status anyone with commit-status access posts from satisfying them.
*/
export const GITHUB_ACTIONS_INTEGRATION_ID = 15368;

export const KIN_CODEOWNERS_PATH = ".github/CODEOWNERS";

export interface KinRulesetRule {
readonly type: string;
readonly parameters?: Readonly<Record<string, unknown>>;
}

export interface KinRuleset {
readonly name: string;
readonly target: "branch" | "tag";
readonly enforcement: "active";
/** Always empty: a bypass for admins lets the owner's merge token skip review, one for the App lets the bot merge alone. */
readonly bypass_actors: readonly [];
readonly conditions: {
readonly ref_name: { readonly include: ReadonlyArray<string>; readonly exclude: readonly [] };
};
readonly rules: ReadonlyArray<KinRulesetRule>;
}

/** @public The rulesets for one repository, given its required status check contexts. */
export const kinRulesets = (requiredChecks: ReadonlyArray<string>): ReadonlyArray<KinRuleset> => [
{
name: "kin-main",
target: "branch",
enforcement: "active",
bypass_actors: [],
conditions: { ref_name: { include: ["~DEFAULT_BRANCH"], exclude: [] } },
rules: [
{ type: "deletion" },
{ type: "non_fast_forward" },
{
type: "pull_request",
parameters: {
required_approving_review_count: 1,
require_code_owner_review: true,
dismiss_stale_reviews_on_push: true,
// Stale dismissal ignores diff-neutral pushes, so a bot commit added then reverted would
// keep the owner's approval. Upstream syncs end with a bot push for this (spec section 10).
require_last_push_approval: true,
required_review_thread_resolution: true,
// `merge` is for the owner's upstream syncs; the executor squashes bot PRs.
allowed_merge_methods: ["squash", "merge"],
},
},
{
type: "required_status_checks",
parameters: {
strict_required_status_checks_policy: true,
do_not_enforce_on_create: false,
required_status_checks: requiredChecks.map((context) => ({
context,
integration_id: GITHUB_ACTIONS_INTEGRATION_ID,
})),
},
},
],
},
{
name: "kin-release",
target: "tag",
enforcement: "active",
bypass_actors: [],
// `*` stops at `/`, so `v*/**` covers tags like `v1/rc`.
conditions: { ref_name: { include: ["refs/tags/v*", "refs/tags/v*/**"], exclude: [] } },
rules: [
{ type: "creation" },
{ type: "update", parameters: { update_allows_fetch_and_merge: false } },
{ type: "deletion" },
],
},
];

/** The fields of a GitHub ruleset that `diffRuleset` reads. */
export interface LiveRuleset {
readonly target: string;
readonly enforcement: string;
/** GitHub omits this for a credential that can't administer the repository. */
readonly bypass_actors?:
| ReadonlyArray<{
readonly actor_id?: number | null | undefined;
readonly actor_type: string;
readonly bypass_mode?: string | undefined;
}>
| undefined;
/** How the credential reading the ruleset could bypass it: `never` for every Kin credential. */
readonly current_user_can_bypass?: string | undefined;
readonly conditions?: unknown;
readonly rules?:
| ReadonlyArray<{
readonly type: string;
readonly parameters?: Readonly<Record<string, unknown>> | undefined;
}>
| undefined;
}

export interface KinRulesetDrift {
readonly field: string;
readonly expected: string;
readonly actual: string;
}

/** Key-sorted, and array order ignored: GitHub doesn't promise to keep either. */
const canonical = (value: unknown): string => {
if (value === undefined) return "absent";
if (Array.isArray(value)) return `[${value.map(canonical).toSorted().join(",")}]`;
if (value !== null && typeof value === "object") {
const record = value as Readonly<Record<string, unknown>>;
return `{${Object.keys(record)
.toSorted()
.map((key) => `${key}:${canonical(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value);
};

/**
* Every field where `live` differs from `desired`: missing rules, rules someone added, changed
* parameters and any bypass actor. Parameters GitHub added that the spec doesn't set are not read.
*/
export function diffRuleset(
desired: KinRuleset,
live: LiveRuleset | undefined,
): ReadonlyArray<KinRulesetDrift> {
if (live === undefined) return [{ field: "ruleset", expected: "present", actual: "missing" }];
const drift: Array<KinRulesetDrift> = [];
const compare = (field: string, expected: unknown, actual: unknown) => {
if (canonical(expected) !== canonical(actual)) {
drift.push({ field, expected: canonical(expected), actual: canonical(actual) });
}
};
compare("target", desired.target, live.target);
compare("enforcement", desired.enforcement, live.enforcement);
// GitHub omits `bypass_actors` for a token without Administration even when its user is an admin.
if (live.bypass_actors === undefined) {
drift.push({
field: "bypass_actors",
expected: "none",
actual: "not visible to this credential",
});
} else {
compare("current_user_can_bypass", "never", live.current_user_can_bypass);
}
for (const actor of live.bypass_actors ?? []) {
drift.push({
field: "bypass_actors",
expected: "none",
actual: `${actor.actor_type}${actor.actor_id == null ? "" : ` ${actor.actor_id}`} (${actor.bypass_mode ?? "always"})`,
});
}
compare("conditions", desired.conditions, live.conditions ?? undefined);
const liveRules = new Map((live.rules ?? []).map((rule) => [rule.type, rule]));
for (const rule of desired.rules) {
const got = liveRules.get(rule.type);
if (got === undefined) {
drift.push({ field: `rules.${rule.type}`, expected: "present", actual: "missing" });
continue;
}
for (const [key, want] of Object.entries(rule.parameters ?? {})) {
// GitHub may leave out a boolean parameter that is false.
const value = got.parameters?.[key] ?? (want === false ? false : undefined);
compare(`rules.${rule.type}.${key}`, want, value);
}
}
const desiredTypes = new Set(desired.rules.map((rule) => rule.type));
for (const type of liveRules.keys()) {
if (!desiredTypes.has(type)) {
drift.push({ field: `rules.${type}`, expected: "absent", actual: "present" });
}
}
return drift;
}

/**
* Why `content` (the default branch's `.github/CODEOWNERS`) fails to make `owner` the sole code
* owner of every path; empty when it passes. A `*` rule must exist, and every rule must name
* exactly the owner, so no later rule can hand a path to someone else or to no one.
*/
export function codeownersProblems(content: string, owner: string): ReadonlyArray<string> {
const problems: Array<string> = [];
const expected = `@${owner}`.toLowerCase();
let coversAll = false;
content.split(/\r?\n/).forEach((raw, index) => {
// A BOM, non-breaking space or other non-ASCII character can make GitHub read a line
// differently from this check, so only printable ASCII and tabs are accepted.
if (/[^\t\x20-\x7e]/.test(raw)) {
problems.push(`line ${index + 1}: has a non-ASCII or control character (or a BOM)`);
return;
}
const tokens = raw.split(/[ \t]+/).filter(Boolean);
const commentAt = tokens.findIndex((token) => token.startsWith("#"));
const [pattern, ...owners] = commentAt === -1 ? tokens : tokens.slice(0, commentAt);
if (pattern === undefined) return;
if (pattern === "*") coversAll = true;
if (owners.length !== 1 || owners[0]!.toLowerCase() !== expected) {
problems.push(
`line ${index + 1}: "${pattern}" is owned by ${owners.length === 0 ? "no one" : owners.join(" ")}, not only @${owner}`,
);
}
});
if (!coversAll) problems.unshift(`no "* @${owner}" rule, so some paths have no code owner`);
return problems;
}
16 changes: 4 additions & 12 deletions apps/server/src/kin/github/OwnerMergeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import { HttpClient } from "effect/http";
// inside effects, after both modules have loaded.
import { CredentialHygienePass } from "../approvals/CredentialHygiene.ts";
import {
GITHUB_PAT_NOT_ACCESSIBLE,
gitHubJson,
gitHubStatus,
isGitHubRateLimit,
type GitHubStatusResponse,
type KinGitHubRequestError,
} from "./githubRest.ts";
Expand All @@ -33,8 +35,6 @@ const PASS_MAX_AGE_MS = 60 * 1000;
* when the token could review, so the probe can never create a review.
*/
const DEFAULT_REVIEW_PROBE_PR = 1;
/** What GitHub says when a fine-grained token lacks the permission an endpoint needs. */
const NOT_ACCESSIBLE_MESSAGE = "Resource not accessible by personal access token";
const REVIEW_PROBE_BODY = {
event: "KIN_PERMISSION_PROBE",
commit_id: "0000000000000000000000000000000000000000",
Expand Down Expand Up @@ -62,18 +62,10 @@ const RepoInfo = Schema.Struct({
function classifyProbe(
answer: GitHubStatusResponse,
): "denied" | "rate_limited" | "inconclusive" | "allowed" {
if (answer.status === 429) return "rate_limited";
if (isGitHubRateLimit(answer)) return "rate_limited";
if (answer.status === 404) return "inconclusive";
if (answer.status !== 403) return "allowed";
if (
answer.headers["x-ratelimit-remaining"] === "0" ||
answer.headers["retry-after"] !== undefined
) {
return "rate_limited";
}
// GitHub's secondary limit can come with neither header.
if (answer.message?.toLowerCase().includes("secondary rate limit")) return "rate_limited";
return answer.message?.trim() === NOT_ACCESSIBLE_MESSAGE ? "denied" : "allowed";
return answer.message?.trim() === GITHUB_PAT_NOT_ACCESSIBLE ? "denied" : "allowed";
}

export class OwnerMergeTokenRefusedError extends Schema.TaggedError<OwnerMergeTokenRefusedError>()(
Expand Down
72 changes: 70 additions & 2 deletions apps/server/src/kin/github/githubRest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface GitHubJsonResponse<A> {

/** Standard headers for a Kin GitHub REST call. */
export const gitHubRequest = (
method: "GET" | "POST" | "PUT" | "DELETE",
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE",
path: string,
token: Redacted.Redacted<string> | undefined,
) => {
Expand All @@ -55,7 +55,7 @@ export const gitHubRequest = (
export const gitHubJson = Effect.fn("KinGitHub.request")(function* <S extends Schema.Top>(input: {
readonly client: HttpClient.HttpClient;
readonly operation: string;
readonly method: "GET" | "POST" | "PUT" | "DELETE";
readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
readonly path: string;
readonly token?: Redacted.Redacted<string> | undefined;
readonly body?: unknown;
Expand Down Expand Up @@ -126,3 +126,71 @@ export const gitHubStatus = Effect.fn("KinGitHub.status")(function* (input: {
),
} satisfies GitHubStatusResponse;
});

/**
* GitHub's rate limits: 429, or a 403 that says so in its headers. A rate-limited refusal says
* nothing about the token's permissions.
*/
export const isGitHubRateLimit = (
answer: Pick<GitHubStatusResponse, "status" | "headers"> & {
readonly message?: string | null | undefined;
},
) =>
answer.status === 429 ||
(answer.status === 403 &&
(answer.headers["x-ratelimit-remaining"] === "0" ||
answer.headers["retry-after"] !== undefined ||
// GitHub's secondary limit can come with neither header.
(answer.message?.toLowerCase().includes("secondary rate limit") ?? false)));

/**
* GitHub's 403 message when a fine-grained token lacks the permission an endpoint needs. An App
* installation token gets "Resource not accessible by integration" instead.
*/
export const GITHUB_PAT_NOT_ACCESSIBLE = "Resource not accessible by personal access token";

/** `/repos/{owner}/{name}` for an `owner/name` slug. */
export const repoPath = (repo: string) => {
const [owner = "", name = ""] = repo.split("/");
return `/repos/${encodeURIComponent(owner)}/${encodeURIComponent(name)}`;
};

export interface GitHubAnswer {
readonly status: number;
readonly headers: Readonly<Record<string, string | undefined>>;
/** GitHub's `message`, or "" when the body has none. Error messages carry no credential. */
readonly message: string;
readonly body: unknown;
}

/** One GitHub REST call whose answer is judged by the caller; any status is returned. */
export const gitHubAnswer = Effect.fn("KinGitHub.answer")(function* (input: {
readonly client: HttpClient.HttpClient;
readonly operation: string;
readonly method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
readonly path: string;
readonly token: Redacted.Redacted<string>;
readonly body?: unknown;
}) {
yield* Effect.annotateCurrentSpan({ "kin.github.operation": input.operation });
const fail = () => new KinGitHubRequestError({ operation: input.operation, stage: "transport" });
let request = gitHubRequest(input.method, input.path, input.token);
if (input.body !== undefined) {
request = yield* HttpClientRequest.bodyJson(request, input.body).pipe(Effect.mapError(fail));
}
const response = yield* input.client.execute(request).pipe(Effect.mapError(fail));
const body: unknown = yield* response.json.pipe(Effect.orElseSucceed(() => null));
const message =
typeof body === "object" &&
body !== null &&
"message" in body &&
typeof body.message === "string"
? body.message
: "";
return {
status: response.status,
headers: response.headers,
message,
body,
} satisfies GitHubAnswer;
});
Loading