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
13 changes: 13 additions & 0 deletions .changeset/minor-request-continuation-routes.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

60 changes: 60 additions & 0 deletions actions/setup/js/bind_continuation_evidence.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// @ts-check
/// <reference types="@actions/github-script" />

const crypto = require("crypto");
const fs = require("fs");

const POSITIVE_DECIMAL = /^[1-9][0-9]*$/;

/**
* Bind the final agent_output.json bytes to the producing run attempt.
* Returns `<run_id>:<run_attempt>:<sha256>`, or null when there is no output to bind.
* Only a regular file is hashed; a symlink or other file type is rejected.
* @param {{path: string, runId: string | undefined, runAttempt: string | undefined}} options
* @returns {string | null}
*/
function bindContinuationEvidence({ path, runId, runAttempt }) {
if (!path) throw new Error("continuation_evidence_path_missing");
if (!POSITIVE_DECIMAL.test(String(runId || "")) || !POSITIVE_DECIMAL.test(String(runAttempt || ""))) {
throw new Error("continuation_evidence_context_invalid");
}
let fd;
try {
fd = fs.openSync(path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
} catch (error) {
if (/** @type {NodeJS.ErrnoException} */ error.code === "ENOENT") return null;
throw new Error("continuation_evidence_unreadable", { cause: error });
}
try {
if (!fs.fstatSync(fd).isFile()) throw new Error("continuation_evidence_not_regular_file");
// Hash exactly the bytes read once from the open descriptor.
const bytes = fs.readFileSync(fd);
if (bytes.length === 0) return null;
return `${runId}:${runAttempt}:${crypto.createHash("sha256").update(bytes).digest("hex")}`;
} finally {
fs.closeSync(fd);
}
}

/**
* Agent-job step: expose `continuation_evidence` for routed request_continuation.
* Missing, empty or unreadable output leaves the output unset, so no handoff can occur.
* @param {{core: typeof import('@actions/core'), env?: NodeJS.ProcessEnv}} options
*/
async function main({ core, env = process.env }) {
let evidence;
try {
evidence = bindContinuationEvidence({ path: env.GH_AW_CONTINUATION_AGENT_OUTPUT || "", runId: env.GITHUB_RUN_ID, runAttempt: env.GITHUB_RUN_ATTEMPT });
} catch (error) {
core.warning(`Continuation evidence unavailable: ${error instanceof Error ? error.message : String(error)}`);
return;
}
if (evidence === null) {
core.info("No agent output to bind; continuation routing has no evidence for this attempt.");
return;
}
core.setOutput("continuation_evidence", evidence);
core.info("Bound continuation evidence to this run attempt.");
}

module.exports = { bindContinuationEvidence, main };
69 changes: 69 additions & 0 deletions actions/setup/js/bind_continuation_evidence.test.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRequire } from "node:module";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";

const require = createRequire(import.meta.url);
const { bindContinuationEvidence, main } = require("./bind_continuation_evidence.cjs");

describe("bind_continuation_evidence", () => {
let tempDir;
let outputPath;
let core;

beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "gh-aw-continuation-evidence-"));
outputPath = path.join(tempDir, "agent_output.json");
core = { info: vi.fn(), warning: vi.fn(), setOutput: vi.fn() };
});

afterEach(() => {
fs.rmSync(tempDir, { recursive: true, force: true });
});

const env = extra => ({ GH_AW_CONTINUATION_AGENT_OUTPUT: outputPath, GITHUB_RUN_ID: "123", GITHUB_RUN_ATTEMPT: "2", ...extra });

it("binds the exact final bytes to the run attempt", async () => {
const bytes = Buffer.from('{"items":[{"type":"request_continuation","message":"Summarize page 2"}],"errors":[]}');
fs.writeFileSync(outputPath, bytes);
await main({ core, env: env() });
const digest = crypto.createHash("sha256").update(bytes).digest("hex");
expect(core.setOutput).toHaveBeenCalledWith("continuation_evidence", `123:2:${digest}`);
expect(core.setOutput.mock.calls[0][1]).toMatch(/^123:2:[0-9a-f]{64}$/);
// The message never appears in the output value.
expect(core.setOutput.mock.calls[0][1]).not.toContain("Summarize");
});

it("leaves the output unset for missing or empty output", async () => {
await main({ core, env: env() });
fs.writeFileSync(outputPath, "");
await main({ core, env: env() });
expect(core.setOutput).not.toHaveBeenCalled();
});

it("rejects symlinks and non-regular files", async () => {
const target = path.join(tempDir, "other.json");
fs.writeFileSync(target, "{}");
fs.symlinkSync(target, outputPath);
await main({ core, env: env() });
expect(core.setOutput).not.toHaveBeenCalled();
expect(core.warning).toHaveBeenCalled();
fs.rmSync(outputPath);
fs.mkdirSync(outputPath);
expect(() => bindContinuationEvidence({ path: outputPath, runId: "1", runAttempt: "1" })).toThrow();
});

it("rejects an invalid run context", () => {
fs.writeFileSync(outputPath, "{}");
for (const [runId, runAttempt] of [
["", "1"],
["1", "0"],
["01", "1"],
["1", "x"],
]) {
expect(() => bindContinuationEvidence({ path: outputPath, runId, runAttempt })).toThrow("continuation_evidence_context_invalid");
}
});
});
84 changes: 49 additions & 35 deletions actions/setup/js/check_permissions_utils.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,50 @@ async function checkBotStatus(actor, owner, repo) {
}
}

/**
* Resolve the effective repository role from a `repos.getCollaboratorPermissionLevel`
* response body. Pure: no API calls, no logging, no ambient clients.
*
* Standard GitHub repository permission levels. Custom org repository roles (e.g.
* "Security Champions") have a role_name that is not one of these — for those, fall back
* to the standard `permission` level reported by the same endpoint so the actor is not
* blocked simply because their custom role name is not literally listed in on.roles.
* A custom role can never grant admin: GitHub derives custom repository roles from the
* read/triage/write/maintain base roles only, so `admin` is refused here even if the API
* unexpectedly reports it for a custom role.
* @param {{permission?: unknown, role_name?: unknown} | null | undefined} data
* @returns {{effectiveRole: string, normalizedPermission: string, normalizedRoleName: string, isCustomRole: boolean, resolvedBaseRole: string}}
*/
function resolveRepositoryRole(data) {
const permission = typeof data?.permission === "string" ? data.permission : "";
const rawRoleName = data?.role_name;
const normalizedRoleName = normalizeRoleName(typeof rawRoleName === "string" ? rawRoleName : "");
const normalizedPermission = normalizeRoleName(permission);
const effectiveRole = normalizedRoleName || normalizedPermission;
const isCustomRole = normalizedRoleName !== "" && !STANDARD_ROLES.has(normalizedRoleName);
const resolvedBaseRole = isCustomRole && CUSTOM_ROLE_BASE_ROLES.has(normalizedPermission) ? normalizedPermission : "";
return { effectiveRole, normalizedPermission, normalizedRoleName, isCustomRole, resolvedBaseRole };
}

/**
* Match a resolved role against required roles. For standard roles, use role_name
* (precise: maintain/triage are not collapsed to write/read). For custom org roles,
* fall back to the standard `permission` level GitHub already computes for the actor
* (readable with the repository-scoped GITHUB_TOKEN); fail closed if it is not one of
* the non-admin base roles.
* @param {ReturnType<typeof resolveRepositoryRole>} resolved
* @param {string[]} requiredPermissions
* @returns {{ permission: string, roleMatchType: "effective-role" | "base-role" } | null}
*/
function matchRepositoryRole(resolved, requiredPermissions) {
for (const requiredPerm of requiredPermissions) {
const normalizedRequired = normalizeRoleName(requiredPerm);
if (normalizedRequired !== "" && normalizedRequired === resolved.effectiveRole) return { permission: normalizedRequired, roleMatchType: "effective-role" };
if (resolved.resolvedBaseRole !== "" && normalizedRequired === resolved.resolvedBaseRole) return { permission: normalizedRequired, roleMatchType: "base-role" };
}
return null;
}

/**
* Check if user has required repository permissions
* @param {string} actor - GitHub username to check
Expand All @@ -259,26 +303,11 @@ async function checkRepositoryPermission(actor, owner, repo, requiredPermissions
username: actor,
});

/** @type {{ permission: string, role_name?: unknown }} */
const repoPermissionData = repoPermission.data;
const permission = repoPermissionData.permission;
const rawRoleName = repoPermissionData.role_name;
const roleName = rawRoleName == null ? "" : typeof rawRoleName === "string" ? rawRoleName : "";
const normalizedRoleName = normalizeRoleName(roleName);
const normalizedPermission = normalizeRoleName(permission);
const effectiveRole = normalizedRoleName || normalizedPermission;
const resolved = resolveRepositoryRole(repoPermission.data);
const { effectiveRole, normalizedPermission, normalizedRoleName, isCustomRole, resolvedBaseRole } = resolved;
const logDetails = normalizedRoleName && normalizedRoleName !== normalizedPermission ? `${normalizedPermission} (role: ${normalizedRoleName})` : normalizedPermission;
core.info(`Repository permission level: ${logDetails}`);

// Standard GitHub repository permission levels. Custom org repository roles (e.g.
// "Security Champions") have a role_name that is not one of these — for those, fall back
// to the standard `permission` level reported by the same endpoint so the actor is not
// blocked simply because their custom role name is not literally listed in on.roles.
// A custom role can never grant admin: GitHub derives custom repository roles from the
// read/triage/write/maintain base roles only, so `admin` is refused here even if the API
// unexpectedly reports it for a custom role.
const isCustomRole = normalizedRoleName !== "" && !STANDARD_ROLES.has(normalizedRoleName);
const resolvedBaseRole = isCustomRole && CUSTOM_ROLE_BASE_ROLES.has(normalizedPermission) ? normalizedPermission : "";
const debugRoleName = normalizedRoleName || "<empty>";
const debugBaseRole = resolvedBaseRole || "<empty>";
core.debug?.(`Repository permission API fields for '${actor}': permission='${normalizedPermission}', role='${debugRoleName}'`);
Expand All @@ -290,24 +319,7 @@ async function checkRepositoryPermission(actor, owner, repo, requiredPermissions
core.info(`Repository permission fallback unavailable for custom role '${normalizedRoleName}' because GitHub did not report a standard permission level`);
}

// Check if user has one of the required permission levels.
// For standard roles, use role_name (precise: maintain/triage are not collapsed to
// write/read). For custom org roles, fall back to the standard `permission` level that
// GitHub already computes for the actor (readable with the repository-scoped
// GITHUB_TOKEN); fail closed if it is not one of the non-admin base roles.
/** @type {{ permission: string, roleMatchType: string }|null} */
let permissionMatch = null;
for (const requiredPerm of requiredPermissions) {
const normalizedRequired = normalizeRoleName(requiredPerm);
if (normalizedRequired === effectiveRole) {
permissionMatch = { permission: normalizedRequired, roleMatchType: "effective-role" };
break;
}
if (resolvedBaseRole !== "" && normalizedRequired === resolvedBaseRole) {
permissionMatch = { permission: normalizedRequired, roleMatchType: "base-role" };
break;
}
}
const permissionMatch = matchRepositoryRole(resolved, requiredPermissions);

if (permissionMatch) {
if (permissionMatch.roleMatchType === "base-role") {
Expand Down Expand Up @@ -336,4 +348,6 @@ module.exports = {
isConfusedDeputyAttack,
checkRepositoryPermission,
checkBotStatus,
matchRepositoryRole,
resolveRepositoryRole,
};
16 changes: 16 additions & 0 deletions actions/setup/js/collect_ndjson_output.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const { isProbingNoopMessage } = require("./intent_probe.cjs");
const { buildEmptyOutputOutcome, collectOutcomeSession, hasFailedFinalResult } = require("./empty_output_outcome.cjs");
const { normalizeSafeOutputName, normalizeSafeOutputConfig } = require("./safe_output_names.cjs");
const { isDependencyUnsupportedType, validateSubmissionMetadata } = require("./safe_output_submission.cjs");
const { routedRequestError } = require("./request_continuation_routes.cjs");

const MENTION_AWARE_OUTPUT_TYPES = new Set(["add_comment", "close_discussion", "create_discussion", "create_issue", "create_pull_request", "create_pull_request_review_comment", "reply_to_pull_request_review_comment"]);

Expand Down Expand Up @@ -298,6 +299,16 @@ async function main() {
rejectItem(`Line ${i + 1}: depends-on is not supported for ${itemType}, which executes outside the safe-output handler manager.`);
continue;
}
// A routed request is rejected, never truncated, before lossy sanitization; it
// carries only its message (route, destination and budget are compiled).
const routedContinuation = itemType === "request_continuation" && expectedOutputTypes[itemType]?.route !== undefined;
if (routedContinuation) {
const routedError = routedRequestError(item);
if (routedError) {
rejectItem(`Line ${i + 1}: ${routedError}`);
continue;
}
}
if (!queueScope && itemType === "noop" && isProbingNoopMessage(item.message)) {
core.info(`[INGESTION] Line ${i + 1}: Ignoring probing noop message (does not count against the noop budget): ${JSON.stringify(item.message)}`);
continue;
Expand Down Expand Up @@ -346,6 +357,11 @@ async function main() {
// Use the normalized item (with sanitized/validated fields) rather
// than the raw input, so downstream consumers see the canonical form.
core.info(`Line ${i + 1}: Valid ${itemType} item`);
const sanitizedRoutedError = routedContinuation ? routedRequestError(validationResult.normalizedItem) : null;
if (sanitizedRoutedError) {
rejectItem(`Line ${i + 1}: ${sanitizedRoutedError} after sanitization`);
continue;
}
parsedItems.push(queueScope ? { ...validationResult.normalizedItem, ...(item.claim_handle ? { claim_handle: item.claim_handle } : {}) } : validationResult.normalizedItem);
} else {
// Fall back to validateItemWithSafeJobConfig for unknown types
Expand Down
28 changes: 28 additions & 0 deletions actions/setup/js/collect_ndjson_output.test.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,34 @@ describe("collect_ndjson_output.cjs", () => {
expect(output.collectorFailureCause).toBe("missing_terminal_safe_output");
expect(output.items.some(item => item.type === "report_incomplete")).toBe(true);
}),
it("rejects oversized or field-carrying routed requests before truncation and keeps advisory limits", async () => {
const testFile = "/tmp/gh-aw/test-ndjson-output.txt";
const oversized = "😀".repeat(4097);
const lines = [
{ type: "request_continuation", message: oversized },
{ type: "request_continuation", message: "Continue", route: "dispatch", remaining: 15 },
{ type: "request_continuation", message: " " },
{ type: "request_continuation", message: "Summarize page 2" },
];
fs.writeFileSync(testFile, lines.map(line => JSON.stringify(line)).join("\n"));
process.env.GH_AW_SAFE_OUTPUTS = testFile;
fs.writeFileSync(process.env.GH_AW_VALIDATION_CONFIG_PATH, JSON.stringify({ request_continuation: { defaultMax: 4, fields: { message: { required: true, type: "string", sanitize: true, maxLength: 65536 } } } }));
fs.writeFileSync(process.env.GH_AW_SAFE_OUTPUTS_CONFIG_PATH, JSON.stringify({ request_continuation: { max: 4, route: "dispatch" } }));

await eval(`(async () => { ${collectScript}; await main(); })()`);

let output = JSON.parse(fs.readFileSync(path.join(TMP_GH_AW_PATH, AGENT_OUTPUT_FILENAME), "utf8"));
expect(output.items.filter(item => item.type === "request_continuation").map(item => item.message)).toEqual(["Summarize page 2"]);
expect(output.errors).toEqual([expect.stringMatching(/^Line 1: .*exceeds 16384 UTF-8 bytes/), expect.stringMatching(/^Line 2: .*agent-supplied field\(s\): remaining, route/), expect.stringMatching(/^Line 3: /)]);

// The advisory form keeps its existing validation for the same input.
fs.writeFileSync(testFile, JSON.stringify({ type: "request_continuation", message: oversized }));
fs.writeFileSync(process.env.GH_AW_SAFE_OUTPUTS_CONFIG_PATH, JSON.stringify({ request_continuation: { max: 1 } }));
await eval(`(async () => { ${collectScript}; await main(); })()`);
output = JSON.parse(fs.readFileSync(path.join(TMP_GH_AW_PATH, AGENT_OUTPUT_FILENAME), "utf8"));
expect(output.items.some(item => item.type === "request_continuation")).toBe(true);
expect(output.errors).toEqual([]);
}),
it("should fail with infra error when safeoutputs gateway-empty flag exists and outputs file is missing", async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "collect-gateway-empty-"));
const missingFile = path.join(tempDir, "nonexistent-outputs.jsonl");
Expand Down
Loading
Loading