Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
25 changes: 25 additions & 0 deletions src/entrypoint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import worker, {
} from "./worker";

export { NoemaOidcReplayGuard, NoemaRateLimiter };
/**
* Runtime configuration accepted by the public request-edge worker. It inherits the
* credential, replay-protection, rate-limit, and workflow-trust settings required by
* the protected worker while keeping this entrypoint's outbound GitHub API checks explicit.
*/
export interface Env extends WorkerEnv {}

const TRUSTED_GITHUB_API_ORIGIN = "https://api.github.com";
Expand All @@ -32,10 +37,21 @@ type ExchangeBodyFailure = {
status: 400 | 413 | 415;
};

/**
* Result of bounding an exchange request body at the public request edge. Successful
* results carry the rebuilt bounded Request; failures carry only the reviewed reason
* and HTTP status needed to produce a fail-closed response without exposing body bytes.
*/
export type BoundedExchangeRequest =
| { ok: true; request: Request }
| { ok: false; failure: ExchangeBodyFailure };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
* Validate that a configured GitHub API base is exactly the trusted GitHub Cloud REST
* origin, with no credentials, path, query, or fragment that could redirect secrets.
* @param value Candidate runtime configuration value to validate.
* @returns True only when the value is the exact accepted GitHub API base origin.
*/
export function isTrustedGithubApiBase(value: unknown): value is string {
if (
typeof value !== "string"
Expand Down Expand Up @@ -64,6 +80,8 @@ export function isTrustedGithubApiBase(value: unknown): value is string {
/**
* Accept only a compact, bounded JWT envelope before any decoding or credential use.
* Missing and non-Bearer authorization values are delegated to the normal API error path.
* @param value Authorization header value observed at the request edge, or null when absent.
* @returns False only when a Bearer JWT envelope is structurally invalid or exceeds limits.
*/
export function isBoundedOidcBearer(value: string | null): boolean {
if (value === null) return true;
Expand Down Expand Up @@ -153,6 +171,8 @@ function hasDuplicateTargetRepositoryKey(body: Uint8Array): boolean {
* Streaming consumption prevents a chunked request from bypassing Content-Length checks.
* The security-relevant top-level `target_repository` member must appear at most once after
* JSON escape decoding so downstream parsing cannot silently apply last-key-wins semantics.
* @param request Incoming request whose optional JSON body must be bounded before delegation.
* @returns A rebuilt bounded request, or a typed failure describing the fail-closed response.
*/
export async function boundExchangeJsonBody(request: Request): Promise<BoundedExchangeRequest> {
if (request.method !== "POST" || request.body === null) {
Expand Down Expand Up @@ -453,6 +473,11 @@ function recordExchangeBodyFailure(request: Request, failure: ExchangeBodyFailur
}
}

/**
* Public Cloudflare Worker entrypoint that enforces request-body, OIDC-envelope, and
* GitHub egress policy before delegating to the credential-exchange worker. It fails closed
* on rejected security boundaries; requests outside /exchange retain the underlying contract.
*/
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const url = new URL(request.url);
Expand Down
10 changes: 10 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ import {
type OidcReplayProtectionEnv,
} from "./oidc-replay";

/**
* Runtime configuration consumed by Noema's base credential-exchange worker. These
* values define the trusted GitHub Actions OIDC issuer/audience/workflow boundary,
* GitHub App identity, exact API origin, replay protection, and bounded cache/rate limits.
*/
export interface Env extends OidcReplayProtectionEnv {
ALLOWED_ISSUER: string;
ALLOWED_AUDIENCE: string;
Expand Down Expand Up @@ -608,6 +613,11 @@ async function handleExchange(request: Request, env: Env, traceId: string): Prom
/* v8 ignore stop */
}

/**
* Base public Worker entrypoint for Noema health and credential exchange. It validates
* methods, OIDC/GitHub App exchange policy, local rate limits, structured errors, and
* bounded operational headers/log metadata while returning credentials only on success.
*/
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const traceId = traceIdFromRequest(request);
Expand Down
44 changes: 44 additions & 0 deletions src/oidc-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,18 @@ const MAX_TOKEN_LIFETIME_SECONDS = 3_600;
const ALARM_GRACE_MS = 30_000;
const trustedJtiPattern = /^[A-Za-z0-9._:-]+$/;

/**
* Supplies the Cloudflare Durable Object namespace that owns replay-claim state.
* The binding is optional at the type boundary so callers can fail closed when deployment wiring is absent.
*/
export interface OidcReplayProtectionEnv {
NOEMA_OIDC_REPLAY_GUARD?: DurableObjectNamespace;
}

/**
* Reports whether a single-use OIDC token claim was accepted and the authoritative expiry attached to that claim.
* A rejected `accepted` value preserves the stored expiry so callers can distinguish replay from infrastructure failure.
*/
export type OidcReplayClaimDecision = {
accepted: boolean;
expires_at_epoch_seconds: number;
Expand All @@ -22,6 +30,10 @@ type ReplayAlarmDecision =
| { action: "delete" }
| { action: "reschedule"; expires_at_epoch_seconds: number };

/**
* Signals a confirmed OIDC replay after an atomic claim finds a still-live prior use.
* The original expiry remains available for bounded diagnostics without disclosing the bearer token itself.
*/
export class OidcReplayDetected extends Error {
constructor(public readonly expiresAtEpochSeconds: number) {
super("GitHub Actions OIDC token has already been used");
Expand All @@ -30,6 +42,10 @@ export class OidcReplayDetected extends Error {
}
}

/**
* Signals that replay protection cannot produce a trustworthy decision and therefore must fail closed.
* This covers missing bindings, malformed responses, invalid expiry windows, and Durable Object failures.
*/
export class OidcReplayUnavailable extends Error {
constructor(message: string) {
super(message);
Expand Down Expand Up @@ -78,6 +94,12 @@ async function sha256Hex(value: string): Promise<string> {
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}

/**
* Derives the stable, non-secret Durable Object name used to serialize claims for one OIDC `jti`.
* @param jti Unique JWT identifier supplied by the already-validated OIDC token.
* @returns A SHA-256 hash-derived object name that never embeds the raw token identifier.
* @throws {OidcReplayUnavailable} When the identifier is empty, oversized, or outside the accepted character set.
*/
export async function oidcReplayObjectName(jti: string): Promise<string> {
if (!validJti(jti)) {
throw new OidcReplayUnavailable("OIDC jti claim is missing or malformed");
Expand All @@ -95,6 +117,15 @@ function isClaimDecision(value: unknown): value is OidcReplayClaimDecision {
);
}

/**
* Atomically claims one validated GitHub Actions OIDC token before privileged credential exchange can continue.
* @param jti Unique token identifier used only to derive the replay-guard object name.
* @param expiresAtEpochSeconds Validated token expiry that bounds how long replay state is retained.
* @param env Environment containing the required replay-protection Durable Object namespace.
* @returns The accepted claim decision with the exact expiry echoed by the replay guard.
* @throws {OidcReplayDetected} When the same live token identifier has already been claimed.
* @throws {OidcReplayUnavailable} When replay authority is missing, malformed, mismatched, or otherwise unavailable.
*/
export async function claimOidcTokenUsage(
jti: string,
expiresAtEpochSeconds: number,
Expand Down Expand Up @@ -161,9 +192,18 @@ function parseClaimRequest(value: unknown, nowEpochSeconds: number): number | un
return expiresAt;
}

/**
* Cloudflare Durable Object that provides the atomic single-use authority for GitHub Actions OIDC tokens.
* Storage transactions ensure concurrent claims cannot both succeed, while alarms bound retention to token expiry.
*/
export class NoemaOidcReplayGuard {
constructor(private readonly state: DurableObjectState) {}

/**
* Applies the fail-closed replay claim protocol to the internal Durable Object endpoint.
* @param request Internal POST request carrying only the validated token expiry, never the bearer token.
* @returns A JSON response whose 201 or 409 status reflects the atomic replay decision.
*/
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
if (request.method !== "POST" || url.pathname !== "/claim") {
Expand Down Expand Up @@ -213,6 +253,10 @@ export class NoemaOidcReplayGuard {
return jsonResponse(decision, decision.accepted ? 201 : 409);
}

/**
* Removes expired replay state or reschedules cleanup when an alarm fires before the authoritative expiry.
* @returns A promise that resolves after cleanup or alarm reschedule has been durably requested.
*/
async alarm(): Promise<void> {
const nowEpochSeconds = Math.floor(Date.now() / 1_000);
const decision = await this.state.storage.transaction(async (transaction) => {
Expand Down
39 changes: 30 additions & 9 deletions src/outbound-fetch-policy.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
/**
* Represents the fetch capability wrapped by Noema's credential-egress policy.
* Implementations receive a request target plus optional request initialization and return the resulting response promise.
*/
export type FetchLike = (
input: RequestInfo | URL,
init?: RequestInit,
) => Promise<Response>;

/**
* Represents a mutable host on which Noema can install and later verify the fail-closed outbound fetch wrapper.
* The fetch member is optional so missing runtime capability is detected explicitly instead of silently bypassed.
*/
export type FetchHost = {
fetch?: FetchLike;
};
Expand Down Expand Up @@ -209,7 +217,11 @@ function githubApiOperation(url: URL): GitHubApiOperation | undefined {
return undefined;
}

/** Return whether an outbound request is inside Noema's credential egress destination allowlist. */
/**
* Checks whether an outbound destination is on the exact HTTPS credential-egress allowlist used by Noema.
* @param input Candidate request target supplied to the protected fetch path.
* @returns `true` only for reviewed GitHub API or GitHub OIDC discovery/JWKS allowlist destinations.
*/
export function isTrustedCredentialEgress(input: RequestInfo | URL): boolean {
const url = outboundUrl(input);
if (
Expand All @@ -231,10 +243,10 @@ export function isTrustedCredentialEgress(input: RequestInfo | URL): boolean {
}

/**
* Enforce endpoint-specific request shape so credentials cannot cross protocol roles.
* OIDC metadata is public GET-only traffic with no body or ambient credentials.
* GitHub REST traffic is restricted to the reviewed App-JWT installation operations:
* repository lookup, app installation inventory, and least-privilege installation-token issuance.
* Enforces endpoint-specific request shape so credentials cannot cross protocol roles or accompany public OIDC metadata traffic.
* @param input Candidate destination that must already belong to the reviewed credential-egress allowlist.
* @param init Optional request initialization containing method, headers, and body semantics to validate.
* @returns `true` only when the request matches the reviewed credential protocol for its exact endpoint role.
*/
export function isTrustedCredentialEgressRequest(
input: RequestInfo | URL,
Expand Down Expand Up @@ -284,8 +296,9 @@ export function isTrustedCredentialEgressRequest(
}

/**
* Wrap fetch so credentials cannot leave reviewed GitHub endpoints, cross endpoint roles,
* follow redirects, return unbounded bodies, or hold an exchange request open indefinitely.
* Wraps fetch with fail-closed credential destination, request-role, redirect, response-size, and timeout enforcement.
* @param rawFetch Trusted underlying fetch implementation that performs only requests admitted by the wrapper.
* @returns A fetch-compatible function that blocks redirects and timeout violations instead of leaking credentials.
*/
export function createFailClosedFetch(rawFetch: FetchLike): FetchLike {
return async (input, init) => {
Expand Down Expand Up @@ -328,7 +341,11 @@ export function createFailClosedFetch(rawFetch: FetchLike): FetchLike {
};
}

/** Install the policy once on a fetch host and detect later tampering fail-closed. */
/**
* Installs the fail-closed fetch policy exactly once on a host and detects later fetch replacement as tamper evidence.
* @param host Mutable fetch host to protect; defaults to the current global runtime object.
* @returns `true` only when the wrapper is installed and still intact, otherwise `false` without bypassing policy.
*/
export function ensureGlobalOutboundFetchPolicy(
host: FetchHost = globalThis,
): boolean {
Expand Down Expand Up @@ -358,7 +375,11 @@ export function ensureGlobalOutboundFetchPolicy(
return true;
}

/** Restore a host after tests; production never removes the installed policy. */
/**
* Restores an installed fetch host during tests while leaving production policy installation one-way for normal operation.
* @param host Mutable fetch host whose test-only installation state should be removed.
* @returns Nothing; cleanup is best-effort and never masks the security behavior being tested.
*/
export function resetGlobalOutboundFetchPolicy(
host: FetchHost = globalThis,
): void {
Expand Down
53 changes: 53 additions & 0 deletions src/rate-limit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,19 @@ const rateLimitDecisionKeys = new Set([
"retry_after_seconds",
]);

/**
* Provides the Durable Object namespace and optional per-minute limit used by distributed exchange throttling.
* The binding is mandatory so production requests never silently fall back to a process-local or shared limiter.
*/
export interface DistributedRateLimitEnv {
NOEMA_RATE_LIMIT_PER_MINUTE?: string;
NOEMA_RATE_LIMITER: DurableObjectNamespace;
}

/**
* Describes the authoritative distributed rate-limit result for one request, including whether it is allowed,
* the configured limit, remaining capacity, and retry delay that a rejected caller should observe.
*/
export type DistributedRateLimitDecision = {
allowed: boolean;
limit: number;
Expand All @@ -39,6 +47,10 @@ type AlarmDecision =
| { action: "delete" }
| { action: "reschedule"; reset_at_ms: number };

/**
* Signals that the distributed rate-limit authority cannot return a trustworthy decision and the caller must fail closed.
* This includes malformed decisions, missing trusted client identity, transport errors, and Durable Object failures.
*/
export class DistributedRateLimitUnavailable extends Error {
constructor(message: string) {
super(message);
Expand All @@ -59,11 +71,21 @@ function jsonResponse(body: unknown, status = 200): Response {
});
}

/**
* Tests whether a response Content-Type identifies JSON while tolerating ordinary media-type parameters.
* @param raw Raw Content-Type header value from the trusted internal rate-limit response.
* @returns `true` only when the normalized media type is exactly `application/json`.
*/
export function isJsonMediaType(raw: string | null): boolean {
const mediaType = (raw ?? "").split(";", 1)[0]!.trim().toLowerCase();
return mediaType === "application/json";
}

/**
* Normalizes an operator-supplied per-minute request limit into the bounded production configuration range.
* @param raw Optional textual limit from deployment configuration.
* @returns A positive integer no greater than the hard maximum, or the safe default when input is invalid.
*/
export function configuredDistributedRateLimit(raw: string | undefined): number {
const parsed = Number(raw ?? String(DEFAULT_RATE_LIMIT_PER_MINUTE));
if (!Number.isFinite(parsed) || parsed <= 0) return DEFAULT_RATE_LIMIT_PER_MINUTE;
Expand Down Expand Up @@ -101,6 +123,11 @@ function canonicalIpv6(candidate: string): string | undefined {
}
}

/**
* Extracts a canonical trusted client identifier only from Cloudflare's `CF-Connecting-IP` request header.
* @param request Edge request whose Cloudflare-supplied client address is used for distributed bucketing.
* @returns A canonical IPv4 or IPv6 address, or `undefined` when the trusted header is missing or malformed.
*/
export function trustedClientIdentifier(request: Request): string | undefined {
const candidate = request.headers.get("cf-connecting-ip")?.trim() ?? "";
if (!candidate || candidate.length > MAX_CLIENT_IDENTIFIER_LENGTH) {
Expand All @@ -114,6 +141,12 @@ async function sha256Hex(value: string): Promise<string> {
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}

/**
* Derives the stable privacy-preserving Durable Object name for the trusted client represented by a request.
* @param request Edge request carrying the trusted Cloudflare client-address header.
* @returns A SHA-256 hash-derived bucket name that does not expose the raw client identifier.
* @throws {DistributedRateLimitUnavailable} When no trustworthy client identifier can be established.
*/
export async function distributedRateLimitObjectName(request: Request): Promise<string> {
const identifier = trustedClientIdentifier(request);
if (!identifier) {
Expand Down Expand Up @@ -268,6 +301,13 @@ async function readBoundedRateLimitDecision(response: Response): Promise<unknown
}
}

/**
* Obtains the authoritative distributed rate-limit decision from the client-specific Durable Object and validates it fail closed.
* @param request Edge request used to derive the trusted client bucket without exposing credentials.
* @param env Rate-limit environment containing the Durable Object namespace and bounded operator configuration.
* @returns A validated allow/deny decision with remaining capacity and retry guidance.
* @throws {DistributedRateLimitUnavailable} When identity, transport, media type, bounds, JSON, or decision validation fails.
*/
export async function checkDistributedRateLimit(
request: Request,
env: DistributedRateLimitEnv,
Expand Down Expand Up @@ -316,9 +356,18 @@ function parseLimitRequest(value: unknown): number | undefined {
return numericLimit;
}

/**
* Cloudflare Durable Object implementing the atomic per-client fixed-window limiter used by the exchange boundary.
* Transactional bucket updates prevent concurrent requests from bypassing the configured distributed rate limit.
*/
export class NoemaRateLimiter {
constructor(private readonly state: DurableObjectState) {}

/**
* Atomically checks and updates one client bucket while returning only the public fail-closed rate-limit decision.
* @param request Internal JSON request carrying the validated limit for this Durable Object bucket.
* @returns A JSON response describing allowance, remaining capacity, and retry guidance for the caller.
*/
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
if (request.method !== "POST" || url.pathname !== "/check") {
Expand Down Expand Up @@ -382,6 +431,10 @@ export class NoemaRateLimiter {
return jsonResponse(publicDecision);
}

/**
* Deletes an expired rate-limit bucket or reschedules cleanup when the active fixed window has not ended yet.
* @returns A promise that resolves after cleanup or the required alarm reschedule is durably requested.
*/
async alarm(): Promise<void> {
const now = Date.now();
const decision = await this.state.storage.transaction(async (transaction) => {
Expand Down
Loading
Loading