Skip to content

feat(labeler): Cloudflare Access operator authentication (W9.1) - #2005

Merged
ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-access-auth
Jul 13, 2026
Merged

ascorbic merged 2 commits into
feat/plugin-registry-labelling-servicefrom
feat/labeler-access-auth

Conversation

@ascorbic

@ascorbic ascorbic commented Jul 13, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Adds the labeler operator console's Cloudflare Access authentication module — plan item W9.1, spec §12. verifyAccessRequest establishes an OperatorIdentity from the Cf-Access-Jwt-Assertion header before any console route (W9.2+) will permit moderation actions.

Design:

  • Identity comes only from a cryptographically verified assertion. The module reads exactly one header — Cf-Access-Jwt-Assertion — and verifies it with jose against Cloudflare Access's remote JWKS (${teamDomain}/cdn-cgi/access/certs). Plaintext identity headers like Cf-Access-Authenticated-User-Email are attacker-spoofable and are never read; a test pins that a request carrying only the plaintext header fails with missing-token.
  • Exact issuer/audience pinning, zero clock tolerance. issuer = team domain, audience = the Access application AUD tag; exp/nbf enforced with jose's default zero tolerance. algorithms is pinned to ["RS256"] and exp is a required claim — both defense-in-depth (alg-confusion and alg:none are already structurally rejected by jose's JWKS key selector, and Access always sets exp), so a future resolver change fails hard instead of quietly widening acceptance.
  • Human vs service-token identities. A common_name claim yields a service identity, email a human one; neither yields an identity without a non-empty sub. Roles (admin/reviewer) are mapped by exact Set membership of the principal plus signed groups claims against config allowlists — empty allowlists fail closed, and hasRole gives admins reviewer capability by inheritance.
  • JWKS resolver cached on globalThis (Symbol.for, keyed by team domain) so Vite SSR chunk duplication and isolate reuse share one resolver; jose handles kid rotation and cooldown internally.
  • parseAccessAuthConfig validates the deployment config up front: HTTPS team domain, non-empty audience, non-empty string allowlists.

Error surface is two static-message AccessAuthError reasons (missing-token / invalid-token) — token contents are never interpolated into messages.

Two independent opus adversarial passes traced the full jose verification path (key selection, key-type checks, claims validation) from installed source: no authorization path exists without a verified signature, and role claims cannot be self-escalated. Their two recommendations (RS256 pin + alg-confusion/alg:none regression tests) are applied here.

No routes are added yet — W9.2 (mutation protections) and W9.3 (console shell) consume this module.

Targets feat/plugin-registry-labelling-service. Related to #1909 and RFC #694.

Type of change

  • Bug fix
  • Feature (requires maintainer-approved Discussion)
  • Refactor (no behavior change)
  • Translation
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • I have read CONTRIBUTING.md
  • pnpm typecheck passes
  • pnpm lint passes
  • pnpm test passes (or targeted tests for my change)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • User-visible strings in the admin UI are wrapped for translation (if applicable). Do not include messages.po changes except in translation PRs — a workflow extracts catalogs on merge to main.
  • I have added a changeset (if this PR changes a published package)
  • New features link to an approved Discussion: RFC RFC: Decentralized Plugin Registry #694

Admin i18n and changeset are n/a — this touches only apps/labeler, a private, unpublished Worker app (no admin UI yet, not on npm).

AI-generated code disclosure

  • This PR includes AI-generated code — model/tool: Claude Code with Claude Fable 5 (design, coordination), Opus 4.8 subagents (security implementation review and hardening), and a Sonnet subagent (implementation)

Screenshots / test output

  • pnpm --filter @emdash-cms/labeler test: 259 pass (17 files) — new suite covers verified accept paths (human, service token, group-derived roles), and rejections for: missing header, spoofed plaintext email header only, garbage token, wrong signing key, wrong issuer, wrong audience, expired, not-yet-valid, missing sub, neither email nor common_name, malformed groups, ES256-signed token, HS256 token whose signature the resolver's key would verify (isolates the RS256 pin), unsigned alg:none token, and a token omitting exp
  • Typecheck clean; pnpm lint:json diagnostics: 0
  • Error messages verified to never contain token material

https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM


Try this PR

Open a fresh playground →

A full working EmDash site, deployed from this branch. Each visit gets its own session-scoped sandbox: no login needed and no shared state. Try the admin, edit content, hit the public site.

Tracks feat/labeler-access-auth. Updated automatically when the playground redeploys.

Verify Cf-Access-Jwt-Assertion against the team's remote JWKS with
exact issuer/audience pinning, RS256-only, required exp, and zero
clock tolerance. Derive human/service operator identities and map
admin/reviewer roles from signed claims against config allowlists;
plaintext identity headers are never read.

Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
@changeset-bot

changeset-bot Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 0dc6c3a

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added review/needs-review No maintainer or bot review yet size/XL labels Jul 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Scope check

This PR changes 573 lines across 4 files. Large PRs are harder to review and more likely to be closed without review.

If this scope is intentional, no action needed. A maintainer will review it. If not, please consider splitting this into smaller PRs.

See CONTRIBUTING.md for contribution guidelines.

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-cache 0dc6c3a Jul 13 2026, 08:04 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-playground 0dc6c3a Jul 13 2026, 08:04 AM

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Updated (UTC)
✅ Deployment successful!
View logs
emdash-demo-do 0dc6c3a Jul 13 2026, 08:06 AM

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR adds a focused, sound Cloudflare Access authentication module for the labeler operator console (W9.1). The approach is right for the target architecture: it reads only the signed Cf-Access-Jwt-Assertion header, verifies with jose using RS256-only algorithm pinning, exact issuer/audience checks, a required exp claim, and zero clock tolerance; roles are derived from config allowlists with fail-closed empty lists and admin→reviewer inheritance; the JWKS resolver is cached on globalThis via Symbol.for. The test suite is comprehensive and covers the adversarial cases the description claims.

I checked the new module and tests against the repo conventions: jose ^6.1.3 matches other workspace packages; internal imports use .js extensions; type/value imports are separated; the oxlint disable comment matches the configured rule name; no admin UI strings or SQL are involved; no changeset is required because apps/labeler is an unpublished private Worker. I found no logic bugs, regressions, or security vulnerabilities.

Two minor suggestions remain — both about making the config validation intent ("HTTPS team domain") match the JWKS URL construction exactly, and about keeping group-derived principals consistent with the non-empty allowlist validation.

Comment thread apps/labeler/src/access-auth.ts Outdated
} catch {
throw new TypeError("Access auth config teamDomain must be an HTTPS URL");
}
if (teamDomainUrl.protocol !== "https:")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] parseAccessAuthConfig only checks the URL protocol here. Values like https://team.example.com/ (trailing slash), https://team.example.com/internal, or https://user:[email protected] pass validation, but getAccessKeyResolver builds the JWKS URL on line 76 via string concatenation: new URL(\${teamDomain}/cdn-cgi/access/certs`)`. That can produce double slashes, appended paths, or leaked credentials in the fetch/cache key. Since the PR emphasizes up-front deployment config validation, consider rejecting anything that isn't a bare HTTPS origin.

Suggested change
if (teamDomainUrl.protocol !== "https:")
if (
teamDomainUrl.protocol !== "https:" ||
teamDomainUrl.username !== "" ||
teamDomainUrl.password !== "" ||
teamDomainUrl.pathname !== "/" ||
teamDomainUrl.search !== "" ||
teamDomainUrl.hash !== ""
)
throw new TypeError("Access auth config teamDomain must be an HTTPS origin");

You may also want to construct the JWKS URL defensively on line 76 with new URL("/cdn-cgi/access/certs", teamDomain) so a trailing slash is harmless even if validation drifts.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 0dc6c3a — parseAccessAuthConfig now rejects paths, credentials, query, and hash, and normalizes the stored value to URL.origin (Access emits iss as the bare origin, so a trailing-slash config previously failed every token silently; normalizing keeps the issuer pin byte-exact while accepting both forms). JWKS URL is now built relative to the origin as suggested. Covered by new rejection tests plus a trailing-slash normalization test.

~ 🤖 Fable

Comment thread apps/labeler/src/access-auth.ts Outdated

function groupPrincipals(groups: unknown): readonly string[] {
if (!Array.isArray(groups)) return [];
return groups.filter((entry): entry is string => typeof entry === "string");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[suggestion] groupPrincipals keeps empty strings in the principal set. They cannot match the non-empty allowlists (which parseStringArray already rejects), but filtering them here is consistent and avoids surprising entries in the identity's effective principal set.

Suggested change
return groups.filter((entry): entry is string => typeof entry === "string");
return groups.filter(
(entry): entry is string => typeof entry === "string" && entry.length > 0,
);

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 0dc6c3a. Also added a test proving the filter is load-bearing: a token with an empty-string group entry against a (deliberately odd) config allowlist containing "" would otherwise grant admin.

~ 🤖 Fable

@github-actions github-actions Bot added review/awaiting-author Reviewed; waiting on the author to respond and removed review/needs-review No maintainer or bot review yet labels Jul 13, 2026
…rincipals

Normalize teamDomain to URL.origin so a trailing slash no longer
silently rejects every token (Access emits iss as the bare origin);
reject paths, credentials, query, and hash outright. Build the JWKS
URL relative to the origin and drop empty-string group entries from
the principal set.

Claude-Session: https://claude.ai/code/session_014rikrGMh25h1rJczUQyTMM
@github-actions github-actions Bot added review/needs-rereview New commits since the last review and removed review/awaiting-author Reviewed; waiting on the author to respond labels Jul 13, 2026
@ascorbic ascorbic added the bot:review Trigger an emdashbot code review on this PR label Jul 13, 2026

@emdashbot emdashbot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This re-review covers the Cloudflare Access authentication module for the labeler operator console (W9.1). The approach remains sound: identity is derived only from a cryptographically verified Cf-Access-Jwt-Assertion, with RS256-only pinning, exact issuer/audience matching, a required exp claim, zero clock tolerance, and roles sourced from config allowlists with admin→reviewer inheritance.

I checked the current revision against my two prior suggestions:

  1. Config validation intent matches JWKS URL construction — resolved. parseAccessAuthConfig now rejects any teamDomain that is not a bare HTTPS origin: it checks protocol === "https:", no username/password, no query, no fragment, and pathname === "/". It then stores teamDomainUrl.origin and constructs the JWKS URL as new URL("/cdn-cgi/access/certs", teamDomain), so the validated value and the URL used at runtime are exactly aligned.

  2. Group-derived principals consistent with non-empty allowlist validation — resolved. groupPrincipals filters the groups claim to entries where typeof entry === "string" && entry.length > 0, matching parseStringArray’s requirement that allowlist entries be non-empty strings. Combined with the existing test that an empty-string group does not match an [""] allowlist, the fail-closed behavior is consistent.

I also re-checked the full module and test suite for new issues: identity extraction, sub validation, error-message safety (static messages, no token interpolation), algorithm/issuer/audience/clock rejection, JWKS resolver caching on globalThis via Symbol.for, dependency version alignment (jose ^6.1.3), ESM .js imports, and type/value import separation. No new logic bugs, security gaps, or convention violations were found.

The prior comments are addressed and the PR is clean. LGTM.

@github-actions github-actions Bot added review/approved Approved; no new commits since and removed review/needs-rereview New commits since the last review labels Jul 13, 2026
@ascorbic
ascorbic merged commit 675eaa5 into feat/plugin-registry-labelling-service Jul 13, 2026
18 checks passed
@ascorbic
ascorbic deleted the feat/labeler-access-auth branch July 13, 2026 08:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bot:review Trigger an emdashbot code review on this PR cla: signed review/approved Approved; no new commits since size/XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant