Skip to content

GitHub sign-in for Google Workspace via Cloudflare Access - #230

Open
sambhav wants to merge 5 commits into
mainfrom
sambhav/access-site
Open

sambhav wants to merge 5 commits into
mainfrom
sambhav/access-site

Conversation

@sambhav

@sambhav sambhav commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Allow a single maintainer, sambhav, to sign in to MCP Google Workspace with GitHub through Cloudflare Access for SaaS. Cloudflare signs the SAML assertion. The earlier custom OIDC Worker, GitHub App and D1 database are no longer part of this change.

The direct members of the workspace-sso GitHub team are the pilot roster. The same entries in users.ts supply the numeric GitHub ID → Workspace email mapping. An enabled member needs a GitHub login and a current Google provisioning role, including inherited roles. CI resolves each enabled ID with GitHub and checks the login. The policy uses the slug from the Pulumi-managed team and requires a GitHub login method. The app allows only the GitHub identity provider, disables Cloudflare One Client authentication, and sends one constant SAML attribute (source: cloudflare-access) in place of Access's default group attributes. The app and policy each use a one-hour session duration.

The NameID transform checks GitHub org membership and looks up the numeric GitHub ID. It does not check the identity provider, because Cloudflare's transform input has no idp field (verified live, see below). The policy's login-method rule enforces GitHub instead. allowedIdps only limits which providers the login page offers.

Verification

  • Local checks pass: npm run validate, npm test, npm run check-github-ids (live GitHub ID → login check, its own CI step) and npm run format:check.
  • Live-tested on a throwaway Access SaaS app in the MCP account (since deleted), using a local test SP. Redacted example responses are in the live-checks thread.

Live results

The test used the app settings from src/cloudflare.ts and Google's SP values were never set. Its policy admitted the whole GitHub org rather than the workspace-sso team, so an unmapped member could reach the transform.

Case Outcome
API read-back Both transforms and nameIdFormat returned byte-for-byte, with no custom attributes
Original expression Everyone, including the mapped pilot, got unmapped@access.invalid. The transform input is {id, name, email, groups[{id, name, teams[{name}]}]}, with no idp field, so the idp.id clause was always false. Fixed in this PR, and the tests now use the captured shape.
Fixed expression, mapped member Signed Success, NameID <pilot>@modelcontextprotocol.io, format emailAddress, empty AttributeStatement
Unmapped Exactly unmapped@access.invalid
Transform error No assertion. Access shows "Failed to generate a SAML Response".
Empty result ("") Signed Success with an empty <NameID/> and the format switched to persistent. No fallback to email. buildNameIdTransform always ends in a non-empty string literal, so it can't produce this.
Propagation A transform change took about 20–40s to reach the edge. The NameID is recomputed for each assertion, not fixed for the session.

Second round, on Den's follow-ups. The app allowed GitHub and one-time PIN, so the PIN case could be exercised, and the policy included the login-method rule:

Case Outcome
Final expression, table without the signer's ID Signed Success, NameID exactly unmapped@access.invalid
One-time PIN session, same user, after a GitHub sign-in in another browser Refused. Access sent the user back to the sign-in picker and issued no assertion. It was also refused with the login-method rule removed, because the org include already fails for a PIN identity. Access did not reuse the stored GitHub groups.
Login-method rule on its own Same app and email include (which the identity matched); only requires.loginMethod changed. Requiring PIN: a GitHub sign-in was refused ("That account does not have access", no assertion). Requiring GitHub: the same sign-in was admitted. The rule enforces the login method by itself.
Dashboard save Comparing the full app before and after, only updated_at changed. A mapped sign-in after the save still worked.
Constant attribute Exactly one attribute, source = cloudflare-access (xs:string). The NameID is unaffected, both mapped and unmapped.

PIN codes were delivered to an address the policy admitted. In our tests no code arrived for addresses the policy did not admit, including every address under an org-only policy. Delivery was intermittent during testing, so that negative case is observed rather than proven.

Neither negative case fell back to email, so nameIdFormat: 'id' is not needed.

Pilot rollout

Before merge

  • Live checks on a throwaway app (above)
  • Dashboard save and read-back (second round, above)
  • Den's follow-ups: login-method rule (tested on its own), unmapped lookup with the final expression, PIN refusal, constant attribute
  • @localden resolves the live-checks thread

Not covered, and not blocking: checking the signature against the app certificate.

After merge — connect Google and activate the pilot

  1. Deploy with inert SP values. Wait about a minute for the edge to update. Then @sambhav:
    • Reads the app back (cf zero-trust access applications get) and confirms:
      • the NameID transform matches buildNameIdTransform and has no idp clause
      • the attribute transform is {"source": "cloudflare-access"}
      • the policy has the GitHub login-method rule
      • allowed_idps is GitHub only and the Cloudflare One Client option is off
      • both the app and the policy use 1h
    • Verifies that an org member outside the workspace-sso team is denied.
    • Records the tenant's global session duration.
    • Optional: signs in with a SAML tracer browser extension and confirms the NameID is the mapped address. The POST to access.invalid fails, but the signed response is visible before it's sent.
  2. @localden owns the Access edit token follow-up. Complete it before connecting Google.
  3. @sambhav supplies the Access SSO URL, entity ID and signing certificate. Either @dsp-ant or @localden creates a modern SAML profile, leaves it unassigned, and returns its SP entity ID and ACS URL. Keep legacy SSO disabled.
  4. @sambhav sets both Google values in a follow-up PR. After deployment, wait about a minute, then:
    • the Workspace admin confirms that post-SSO verification applies to SSO-profile users, 2-Step Verification is enforced for the pilot, and sambhav@ is enrolled and has no Workspace admin role
    • then the admin assigns the profile to the OU that contains only that account.
  5. @sambhav tests a fresh sign-in to the expected mailbox. If rollback is needed, the Workspace admin removes the pilot OU assignment.

The README covers enabling more members and revoking Google and Cloudflare sessions during offboarding. A mapping change takes effect on the next assertion, about a minute after deploy. Existing Google sessions and Access sessions still have to be revoked.

@sambhav
sambhav requested a review from a team as a code owner October 24, 2026 16:34
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Pulumi Preview

No preview ran for this commit: the preview environment has no deploy secrets.

sambhav commented Oct 24, 2026

Copy link
Copy Markdown
Member Author

@dsp-ant this is ready for review. Three things need you, all in the Setup → @dsp-ant section of the description:

  1. Create the GitHub App (needs an org owner) and post its client ID here
  2. Generate the OIDC client secret into GitHub secrets (one command; you keep the file for step 3)
  3. Once the discovery URL is live, add the custom OIDC SSO profile in the Admin console, assign it to a pilot sub-OU with only sambhav@, and post the redirect URI here

Sign-in starts as a pilot for me only (PILOT_GITHUB_LOGINS = "sambhav"), so nothing changes for anyone else until we widen it. Super admins are exempt from the SSO profile, so your login is unaffected.

The PR can merge before any of this; the deploy job skips until the secrets exist.


Generated by Claude Code

dsp-ant commented Oct 26, 2026

Copy link
Copy Markdown
Member

Automated review (Claude-generated)

Heads-up: everything below was produced by Claude Code's /code-review running over this PR's diff (two passes, merged and de-duplicated here). The severity labels are also Claude's judgement. The top items were spot-checked against the code, but none of this has been verified by a human yet — please treat each item as a claim to confirm, not an established fact.

Severity key: 🔴 High · 🟠 Medium · 🟡 Low · ⚪ Nit


🔴 High

1. existingGWSUser accounts are locked out — access-site/src/eligibility.ts:30
workspaceEmailFor() requires hasProvisionUserRole(...), but scripts/validate-config.ts and src/google.ts both treat existingGWSUser: true entries as real, kept accounts that are exempt from the role rule. There are ~14 such entries in users.ts today (several with memberOf: []). Once the OIDC profile is assigned to the whole OU, those people hit no_account → 403 and are told to "add a googleEmailPrefix" they already have, with no password fallback for non-super-admins. The README's "same rule Pulumi uses" claim is not currently true.
Suggested fix: export one shared "has a Workspace account" predicate from src/config/utils.ts and use it in google.ts, validate-config.ts, and the Worker (this also closes the firstName/lastName divergence noted under #9).

2. Identity is trust-on-first-use of a mutable GitHub login — access-site/src/db.ts:110
pinGithubIdentity binds login→GitHub ID on first sign-in. On day one the pin table is empty, so any users.ts login whose owner has since renamed their GitHub account can be registered by a stranger, who then completes /login and is issued an ID token for that person's @modelcontextprotocol.io mailbox; the real owner is afterwards refused with identity_mismatch. Impact is full mailbox/Drive access, so rating this High even though it needs a stale login to exist.
Suggested fix: anchor on something GitHub tracks by immutable ID — record the numeric GitHub user ID in users.ts (validated in CI), or require org/team membership at sign-in — rather than TOFU on the login string.

🟠 Medium

3. GitHub error callback causes a redirect loop — access-site/src/index.ts:86
/login?error=access_denied&state=… (user clicks Cancel, app suspended, temporarily_unavailable) has no code, so githubAuth treats it as a fresh start and 302s straight back to GitHub. The denial is never surfaced, Google never gets an error response, nothing is logged, and for non-interactive errors it's a tight loop until the browser gives up or the rate limiter 429s.
Suggested fix: check c.req.query('error') before invoking githubAuth and render an error page / redirect back to Google with error=access_denied.

4. OAuth state cookie is not __Host- and not bound to the pending authorization — access-site/src/index.ts:94
The state cookie from @hono/oauth-providers is a plain host cookie. Anyone who can run script on any *.modelcontextprotocol.io origin can toss a Domain=modelcontextprotocol.io; Path=/login state cookie and splice their own unredeemed GitHub code into a victim's pending Google sign-in (login-CSRF into the attacker's Workspace account). Preconditions are narrow (subdomain script execution), hence Medium rather than High.
Suggested fix: use a __Host- prefixed state cookie and/or bind state to the __Host-mcp_pending value.

5. Key-rotation procedure can break verification for up to the JWKS cache TTL — access-site/README.md:79, access-site/src/oidc.ts:91
/jwks is served with max-age=300, and the documented rotation starts signing with the new key in the same deploy that first publishes it (only a previous slot exists). A relying party holding a cached JWKS sees an unknown kid for up to 5 minutes. Google usually refetches on kid miss, but that isn't guaranteed.
Suggested fix: document "publish new public key via OIDC_PREVIOUS_JWK first → wait past TTL → swap SIGNING_KEY → move old key to previous", or add a NEXT_JWK slot.

6. Deploy gate doesn't require the GitHub client secret — .github/workflows/access-site.yml:68
ready=true needs the Cloudflare token, signing key and OIDC client secret, but not ACCESS_SITE_GITHUB_CLIENT_SECRET. A first deploy with steps 1/2/4 done but not 3 ships a live issuer where every sign-in fails at the GitHub token exchange ("Sign-in was interrupted"), and revokeGitHubToken sends Basic <id>:undefined.
Suggested fix: add HAS_GITHUB_SECRET to the gate (or have deploy.sh require it when no secret exists yet).

7. Test fixtures are derived from live src/config and gate the deploy job — access-site/test/helpers.ts:99
memberWithoutAccount() / ineligibleMember() throw if users.ts happens not to contain a member of that shape. Since the workflow runs these tests on every src/config/** change and deploy has needs: test, an unrelated, valid users.ts PR can break CI and stop the Worker redeploying (so removed users keep signing in) until someone edits the tests.
Suggested fix: use synthetic logins / injected MEMBERS for the negative cases.

🟡 Low

8. Cross-Origin-Opener-Policy: same-origin on the redirect responses — access-site/src/index.ts:25
secureHeaders() defaults add COOP to every response including the 302s on /authorize and /login. If Google ever runs this federated hop inside a popup (GIS popup mode, re-auth popups), the opener is severed and the result can't be posted back. Workspace SSO is normally full-page, so Low, but the fix is one line: crossOriginOpenerPolicy: false.

9. Eligibility predicate is re-implemented instead of shared — access-site/src/eligibility.ts:27
Beyond #1, the Worker's copy also drops the firstName/lastName requirement that src/google.ts applies, so it can assert email_verified: true for an address Pulumi never created. test/helpers.ts copies the predicate a third time. One exported helper in src/config/utils.ts fixes all of these.

10. no_account conflates several distinct situations and is checked before the pilot gate — access-site/src/oidc.ts:168
"Not in users.ts", "opted out via skipGoogleUserProvisioning", "alias entry without a prefix" and "no eligible role" all render noAccountPage telling the user to open a PR adding googleEmailPrefix, which is wrong advice for most of those cases and will prompt bogus config PRs during the pilot.

11. onError turns the deliberate 502 into a generic 500 — access-site/src/index.ts:143
Only HTTPExceptions with status < 500 keep their status/message, so HTTPException(502, 'GitHub did not return a user.') is logged as unexpected and returned as 500 "Something went wrong", making upstream GitHub failures indistinguishable from Worker bugs.

12. pinGithubIdentity does two sequential D1 round-trips — access-site/src/db.ts:116
INSERT OR IGNORE then SELECT on every successful sign-in. One statement (INSERT … ON CONFLICT(login) DO UPDATE SET login=login RETURNING github_id) or a db.batch([...]) halves hot-path latency, and avoids a read-after-write surprise if D1 read replication is ever enabled.

⚪ Nit

13. Hand-rolled base64url — access-site/src/crypto.ts:13: jose (already a dependency) exports base64url.encode(Uint8Array).

14. /authorize is GET-only — access-site/src/index.ts:56: OIDC Core §3.1.2.1 says the OP must accept GET and POST. Google uses GET, so this is spec-compliance only; app.on(['GET','POST'], '/authorize', …) if you want it.


Generated by Claude Code

sambhav commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

@dsp-ant thanks for the review. All 14 items are addressed in bf5bde6, and 72b7dcf simplifies the result:

# Item Resolution
1 existingGWSUser accounts locked out hasGoogleWorkspaceAccount() in src/config/utils.ts is the one predicate used by google.ts, validate-config.ts and the Worker, so existing accounts sign in without a provisioning role (tested)
2 Trust-on-first-use of a mutable login Removed the pin table. The numeric githubUserId is recorded in users.ts (validated in CI, unique, behind CODEOWNERS) and must match before any token is issued. Accounts without one get identity_unverified
3 GitHub error callback loop ?error= returns to Google with access_denied / temporarily_unavailable and its original state, and consumes the pending request
4 Unbound state cookie Dropped @hono/oauth-providers. OAuth state and S256 PKCE are both derived from the __Host-mcp_pending value, so there is no separate state cookie
5 Key rotation vs JWKS cache /jwks can publish an extra key before cutover and keep the old one after. 72b7dcf folds the two slots into one OIDC_ROTATION_JWKS JWK Set; runbook in access-site/README.md
6 Deploy gate Gate and deploy.sh now require ACCESS_SITE_GITHUB_CLIENT_SECRET
7 Tests depend on live users.ts Tests mock users.ts with synthetic members. The only live-config test checks that pilot logins have a verified ID. 72b7dcf moves login uniqueness into validate-config.ts
8 COOP on redirects crossOriginOpenerPolicy: false
9 Predicate re-implemented Same fix as 1, including firstName/lastName
10 no_account advice and order Pilot is checked first; refusal pages say "ask the Infrastructure WG to check your entry" rather than suggesting a googleEmailPrefix PR
11 502 turned into 500 HTTPExceptions keep their status; 502s are logged as upstream warnings
12 Two D1 round-trips Gone with the pin table
13 Hand-rolled base64url Uses jose's base64url
14 GET-only /authorize Accepts GET and form POST (303 after POST)

Worker: 23 tests and typecheck pass. Repo: format, config validation and 79 tests pass. wrangler deploy --dry-run builds.


Generated by Claude Code

sambhav commented Nov 9, 2026

Copy link
Copy Markdown
Member Author

Ready for review. The review fixes are in, and the access-site, repository CI, and Pulumi preview checks all passed. I also backfilled the numeric GitHub IDs for all 139 configured usernames in src/config/users.ts using their current GitHub profiles.

The Workspace SSO pilot is still limited to sambhav. Before widening it, we’ll confirm each account with its maintainer.

dsp-ant commented Nov 16, 2026

Copy link
Copy Markdown
Member

Thanks for working through the review. The overall design looks good to me. Three things we should fix before merging:

1. Sign-in fails in the Workers runtime (access-site/src/github.ts:38, :59, :82)
All three GitHub fetches use redirect: 'error'. workerd rejects that value and throws a TypeError before the request goes out. exchangeGitHubCode swallows the error, so every sign-in ends in a 502. Token revocation fails silently for the same reason. The tests don't catch it because they run in Node with a mocked fetch.

redirect: 'manual' fixes it, since the existing response.ok checks already reject a 3xx. I had Claude run the full flow in workerd 1.20261012.1 with GitHub mocked. As is, the callback returns 502 with no outbound calls. With only that change, sign-in, /token and /userinfo all pass.

2. The pilot allowlist fails open (access-site/src/oidc.ts:155)
An empty PILOT_GITHUB_LOGINS lets every Workspace account with a recorded ID sign in. Removing the last pilot user leaves exactly that value, so offboarding or pausing the pilot would open sign-in to everyone. Can we make unset or empty mean nobody, and require an explicit * to open it up? The comments in wrangler.toml and env.ts and the README need to change with it.

3. Merge conflict in scripts/validate-config.ts
It's only the import block, after #247.

Two notes on CI. The production environment now only accepts main. environment: production in access-site.yml is still fine, but please store all four access-site secrets with --env production and not at the repository level. Preview will fail on your next push because it also uses that environment. I'm fixing that separately on main, and it's not a required check.

The rest can be follow-ups, but verifying the backfilled GitHub IDs has to happen before we widen the pilot beyond you.


Generated by Claude Code

@sambhav
sambhav force-pushed the sambhav/access-site branch from dce9ae3 to aa706d7 Compare November 18, 2026 06:24
@sambhav
sambhav force-pushed the sambhav/access-site branch from 0a9a350 to 9ba46ca Compare November 24, 2026 09:57
@sambhav sambhav changed the title Add access.modelcontextprotocol.io: GitHub sign-in for Google Workspace GitHub sign-in for Google Workspace via Cloudflare Access Nov 24, 2026

sambhav commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Thanks for the review, @localden. I’ve addressed the profile defaults, GitHub ID and role checks, session duration, offboarding docs, and JSONata tests in f10a86b. CI and the Pulumi preview passed. I’ve also added your token-hardening follow-up to the rollout plan so we complete it before connecting Google.

I’ve left the NameID thread open. After merge, I’ll use a throwaway Cloudflare app to confirm an unlisted org member gets unmapped@access.invalid and check what Cloudflare sends when the transform errors. I’ll post the redacted results in that thread before we assign the Google profile. Ready for another look when you are.

@sambhav
sambhav requested a review from localden November 29, 2026 02:18

@localden localden 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.

Thanks for the quick fixes - a few small follow-ups.


Generated by Claude Code

Comment thread src/cloudflare.ts Resolved
Comment thread src/cloudflare.ts Resolved
Comment thread README.md Resolved
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…access-site

# Conflicts:
#	README.md

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>

This branch had an error being deployed

1 failed (outdated) and 1 active deployments
preview — 6239681f Deployed Nov 30, 2026 by sambhav via Preview Changes #465
production — 9ba46ca1 Deployed Nov 24, 2026 by sambhav via Preview Changes #427
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants