Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
105 changes: 92 additions & 13 deletions scripts/lib/delegated-github-token.mjs
Original file line number Diff line number Diff line change
@@ -1,31 +1,110 @@
import { readFileSync } from "node:fs";
import {
closeSync,
constants,
fstatSync,
openSync,
readSync,
} from "node:fs";

const MAX_DELEGATED_TOKEN_BYTES = 16 * 1024;

function boundedFileError(error) {
return String(error?.message ?? error)
.replace(/\bbearer\s+\S+/gi, "Bearer [REDACTED]")
.replace(/\bgh[pousr]_[A-Za-z0-9_]+\b/g, "[REDACTED]")
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.replace(/[\u0000-\u001f\u007f]/g, "")
.slice(0, 1_024);
}

function sameFileVersion(left, right) {
return (
left.dev === right.dev
&& left.ino === right.ino
&& left.size === right.size
&& left.mtimeNs === right.mtimeNs
&& left.ctimeNs === right.ctimeNs
);
}

/**
* Load a short-lived delegated GitHub token from an explicit capability file.
*
* The file path is non-secret runtime configuration. The bearer token itself
* must not be read from the Node process environment. Callers are responsible
* for creating the file with restrictive permissions in trusted bootstrap code
* and deleting it after use.
* must not be read from the Node process environment. The reader fails closed
* unless the capability is a bounded, owner-only, regular file opened without
* following symlinks and remains the same descriptor version throughout the read.
* Callers remain responsible for trusted bootstrap creation and prompt cleanup.
*/
export function readDelegatedGithubToken(tokenPath) {
const path = String(tokenPath ?? "").trim();
if (!path) {
throw new Error("Maintainer token file path is required.");
}
if (!Number.isInteger(constants.O_NOFOLLOW)) {
throw new Error("Maintainer token capability requires no-follow file support.");
}

let token;
let descriptor;
try {
token = readFileSync(path, "utf8");
descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
} catch (error) {
throw new Error(`Maintainer token file could not be read: ${String(error?.message ?? error)}`);
throw new Error(`Maintainer token file could not be opened safely: ${boundedFileError(error)}`);
}

if (!token) {
throw new Error("Maintainer token file must not be empty.");
}
if (/[\u0000-\u001f\u007f]/.test(token)) {
throw new Error("Maintainer token must not contain control characters.");
try {
const before = fstatSync(descriptor, { bigint: true });
if (!before.isFile()) {
throw new Error("Maintainer token capability must be a regular file.");
}
if ((before.mode & 0o077n) !== 0n) {
throw new Error("Maintainer token file permissions must be owner-only.");
}
if (typeof process.getuid === "function" && before.uid !== BigInt(process.getuid())) {
throw new Error("Maintainer token file must be owned by the current process user.");
}
if (before.size === 0n) {
throw new Error("Maintainer token file must not be empty.");
}
if (before.size > BigInt(MAX_DELEGATED_TOKEN_BYTES)) {
throw new Error("Maintainer token file exceeds the bounded size limit.");
}

const buffer = Buffer.alloc(MAX_DELEGATED_TOKEN_BYTES + 1);
let bytesRead = 0;
while (bytesRead < buffer.length) {
const count = readSync(
descriptor,
buffer,
bytesRead,
buffer.length - bytesRead,
bytesRead,
);
if (count === 0) break;
bytesRead += count;
}
if (bytesRead > MAX_DELEGATED_TOKEN_BYTES) {
throw new Error("Maintainer token file exceeds the bounded size limit.");
}

const after = fstatSync(descriptor, { bigint: true });
if (!sameFileVersion(before, after) || BigInt(bytesRead) !== before.size) {
throw new Error("Maintainer token file changed during the bounded read.");
}

let token;
try {
token = new TextDecoder("utf-8", { fatal: true }).decode(buffer.subarray(0, bytesRead));
} catch {
throw new Error("Maintainer token file contains invalid UTF-8.");
}
if (!token) {
throw new Error("Maintainer token file must not be empty.");
}
if (/[\u0000-\u001f\u007f]/.test(token)) {
throw new Error("Maintainer token must not contain control characters.");
}
return token;
} finally {
closeSync(descriptor);
}
return token;
}
56 changes: 52 additions & 4 deletions test/github-credential-capability-ingress.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,31 @@
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import {
chmodSync,
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { readDelegatedGithubToken } from "../scripts/lib/delegated-github-token.mjs";

const temporaryDirectories: string[] = [];
const MAX_DELEGATED_TOKEN_BYTES = 16 * 1024;

function temporaryFile(contents: string) {
function temporaryDirectory() {
const directory = mkdtempSync(join(tmpdir(), "noema-token-capability-"));
temporaryDirectories.push(directory);
return directory;
}

function temporaryFile(contents: string, mode = 0o600) {
const directory = temporaryDirectory();
const path = join(directory, "token");
writeFileSync(path, contents, { encoding: "utf8", mode: 0o600 });
chmodSync(path, mode);
return path;
}

Expand All @@ -29,15 +44,15 @@ afterEach(() => {
});

describe("GitHub credential capability ingress", () => {
it("reads a non-empty control-free delegated token from the explicit capability path", () => {
it("reads a non-empty control-free delegated token from an owner-only capability file", () => {
const path = temporaryFile("delegated-token-value");
expect(readDelegatedGithubToken(path)).toBe("delegated-token-value");
});

it("fails closed for missing, unreadable, empty, and control-bearing capability files", () => {
expect(() => readDelegatedGithubToken("")).toThrow("Maintainer token file path is required.");
expect(() => readDelegatedGithubToken("/definitely/not/a/noema/token")).toThrow(
"Maintainer token file could not be read:",
"Maintainer token file could not be opened safely:",
);
expect(() => readDelegatedGithubToken(temporaryFile(""))).toThrow(
"Maintainer token file must not be empty.",
Expand All @@ -47,6 +62,39 @@ describe("GitHub credential capability ingress", () => {
);
});

it("rejects group/world-readable delegated credential files", () => {
for (const mode of [0o640, 0o604, 0o666]) {
const path = temporaryFile("delegated-token-value", mode);
expect(() => readDelegatedGithubToken(path)).toThrow(
"Maintainer token file permissions must be owner-only.",
);
}
});

it("rejects symlink and non-regular-file capability paths", () => {
const directory = temporaryDirectory();
const target = join(directory, "real-token");
const link = join(directory, "token-link");
const nestedDirectory = join(directory, "token-directory");
writeFileSync(target, "delegated-token-value", { encoding: "utf8", mode: 0o600 });
symlinkSync(target, link);
mkdirSync(nestedDirectory, { mode: 0o700 });

expect(() => readDelegatedGithubToken(link)).toThrow(
"Maintainer token file could not be opened safely:",
);
expect(() => readDelegatedGithubToken(nestedDirectory)).toThrow(
"Maintainer token capability must be a regular file.",
);
});

it("bounds delegated token bytes before parsing secret content", () => {
const path = temporaryFile("x".repeat(MAX_DELEGATED_TOKEN_BYTES + 1));
expect(() => readDelegatedGithubToken(path)).toThrow(
"Maintainer token file exceeds the bounded size limit.",
);
});

it("keeps delegated GitHub bearer tokens out of Node process-environment reads", () => {
for (const scriptPath of [
"scripts/main-governance-audit.mjs",
Expand Down
Loading