Skip to content

Phase 2: Worker auth layer for GitHub App tokens (#437) - #442

Merged
neuromechanist merged 2 commits into
feature/issue-432-epic-github-appfrom
feature/issue-437-phase2-worker-auth
May 11, 2026
Merged

neuromechanist merged 2 commits into
feature/issue-432-epic-github-appfrom
feature/issue-437-phase2-worker-auth

Conversation

@neuromechanist

Copy link
Copy Markdown
Contributor

Summary

Adds the Worker-side GitHub App auth helper. No callsite changes — all 48 existing reads of `GITHUB_ADMIN_PAT` keep working untouched. Phase 3 (#438) will route `githubFetchWithRetry` through `GitHubAuth` and flip every site over.

New module: `backend/src/services/github-auth.ts`

Export Purpose
`signAppJwt(appId, pem, nowSeconds?)` Behavioral mirror of the Phase 1 standalone helper. Same PKCS#1 / encrypted-PKCS#8 rejection, same 30 s iat skew margin. Duplicate by design — script must stay standalone, Worker must not reach into `scripts/`. Two test suites pin the same invariants.
`fetchInstallationToken(jwt, id, opts)` POST `/app/installations/:id/access_tokens`. Parses `token` + `expires_at`, throws with the raw body on non-2xx or malformed responses. `opts.fetchFn` / `opts.baseUrl` exist for the Bun.serve test seam.
`getInstallationToken(env, id, opts?)` Module-scoped cache keyed by installation ID. Refresh at 5 min before expiry. Concurrent callers attach to a single in-flight `refreshing` promise — no mint storm. Failed mints drop the entry so retries start clean.
`GitHubAuth` Discriminated source: `{ kind: "pat"; token } | { kind: "app"; installationId; getToken }`.
`getDefaultGitHubAuth(env, installationId?)` App auth when all App fields are set and `installationId` is provided; PAT fallback otherwise. The fallback keeps dev environments without App secrets working until ops sets them.
`resolveInstallationId(env, orgLogin)` Maps "nemarDatasets"/"nemarOrg" to the configured installation ID. Decouples Phase 3 callsites from env var names.
`__resetInstallationTokenCacheForTests`, `__seedInstallationTokenCacheForTests` Test seams mirroring the pattern in `backend/src/services/github.ts:40-46`.

`backend/src/types/bindings.ts`

Four new optional fields in the existing optional-secrets block:

  • `GITHUB_APP_ID?`
  • `GITHUB_APP_PRIVATE_KEY?` (PKCS#8 PEM)
  • `GITHUB_APP_INSTALLATION_ID_NEMAR_DATASETS?`
  • `GITHUB_APP_INSTALLATION_ID_NEMAR_ORG?`

Optional in this phase. Phase 5 drops PAT and makes them required.

Tests (`test/github-auth.test.ts`)

20 tests, all green:

  • JWT structure / RS256 header / 10-min window / -30 s iat / signature verifies against generated public key.
  • PKCS#1 and encrypted-PKCS#8 rejection with actionable errors.
  • `fetchInstallationToken` against a Bun.serve fake that captures the JWT in the `Authorization` header and returns a canned `expires_at`.
  • Cache hit returns the seeded token without a network call.
  • Expiring-soon (4 min remaining < 5 min lead) triggers a refresh.
  • Two-installation cache isolation.
  • 5 concurrent callers share one in-flight mint (asserts exactly one captured POST).
  • Failed mints drop the entry; next call gets a clean retry.
  • `getDefaultGitHubAuth` returns app/pat across every missing-field permutation.
  • `resolveInstallationId` for known + unknown + non-numeric values.

Out of scope (deferred)

Closes #437. Part of epic #432.

Test plan

  • `bun test test/github-auth.test.ts test/verify-github-app.test.ts` — 31 pass / 0 fail.
  • `bunx tsc --noEmit` clean at repo root and `backend/`.
  • Post-merge: ops sets `GITHUB_APP_*` secrets on dev Worker. No runtime behavior changes until Phase 3.

New module backend/src/services/github-auth.ts:
- signAppJwt: behavioral mirror of the Phase 1 script's helper. Same
  PKCS#1 / encrypted-PKCS#8 rejection and 30s iat skew margin. Two
  copies (script + Worker) are intentional; tests in both files pin the
  same invariants.
- fetchInstallationToken: POST /app/installations/:id/access_tokens,
  parses token + expires_at, throws with the raw body on non-2xx or
  malformed responses. Takes a fetch override + baseUrl for the test
  Bun.serve fake.
- getInstallationToken: module-scoped cache keyed by installation ID.
  Refresh at 5 min before expiry. Concurrent callers attach to a single
  in-flight `refreshing` promise so we never mint N tokens for N
  parallel orchestrator steps. Failed mints drop the entry so retries
  start clean.
- GitHubAuth discriminated source ({kind: "pat"} | {kind: "app", ...}).
- getDefaultGitHubAuth returns app auth when all App fields and the
  requested installationId are set, falls back to PAT otherwise. The
  fallback keeps dev environments without App secrets working until
  ops sets them.
- resolveInstallationId maps an org login to its configured installation
  id, decoupling Phase 3 callsites from the exact env var names.
- Test seams (__resetInstallationTokenCacheForTests,
  __seedInstallationTokenCacheForTests) mirror the same pattern in
  backend/src/services/github.ts.

backend/src/types/bindings.ts:
- Add four optional fields (GITHUB_APP_ID, GITHUB_APP_PRIVATE_KEY,
  GITHUB_APP_INSTALLATION_ID_NEMAR_DATASETS,
  GITHUB_APP_INSTALLATION_ID_NEMAR_ORG). Optional in this phase; Phase 5
  drops the PAT and makes these required.

test/github-auth.test.ts (20 tests, all green):
- JWT contract parallels test/verify-github-app.test.ts.
- fetchInstallationToken against a Bun.serve fake that captures the
  JWT in the Authorization header and returns a canned response.
- Cache hit / expiring-soon refresh / two-installation isolation /
  concurrent-caller coalescing / failed-mint cleanup.
- getDefaultGitHubAuth across each missing-field permutation.
- resolveInstallationId for known + unknown + non-numeric values.

No callsites changed; the 48 reads of GITHUB_ADMIN_PAT keep working
unmodified. Phase 3 (#438) does the cutover.
@github-actions

github-actions Bot commented May 11, 2026 •

Copy link
Copy Markdown

📦 Package Preview

Your package is ready to test!

bun install -g nemar-cli@PR442

Version: 0.8.11-PR442.8deb686
Commit: 8deb686


🤖 Updated on each push.

Reviewer themes: silent fallbacks (test-analyzer + silent-failure-hunter
agreed), type design polish, comment rot.

Code (backend/src/services/github-auth.ts):
- fetchInstallationToken now rejects empty-string `token` and
  already-expired `expires_at` (silent-failure / test-analyzer #3). A
  born-expired token would have looped the cache on every call.
- New getGitHubAppConfig(env) is the single source of truth for "is the
  App configured". Consolidates the duplicated GITHUB_APP_ID / KEY
  reads, parses the installation IDs once, and emits a console.warn
  when a configured installation ID is malformed. Without the warn, a
  typo'd ID silently degrades to the PAT path with zero indication
  (silent-failure #2).
- getDefaultGitHubAuth now throws when neither App nor a non-empty PAT
  is configured (silent-failure #1). Before, callers got
  { kind: "pat", token: "" } and the eventual GitHub call surfaced an
  opaque "Bad credentials" 401.
- resolveInstallationId routes through getGitHubAppConfig so the App
  config check and install-ID lookup share one entry point.
- New `EpochMs` branded type for `expiresAt`. Prevents seconds/ms
  mixing across the module (type-design #2).
- `FetchInstallationTokenOptions` renamed to internal-only and not
  exported (type-design #3).
- Trimmed phase/issue narrative from doc comments (comment-analyzer).

Tests (test/github-auth.test.ts):
- New: appId=0 boundary (matches Phase 1's coverage of the same case
  in the script copy).
- New: empty-token rejection.
- New: past-`expires_at` rejection.
- New: signAppJwt failure during refresh clears the cache; recovery on
  next call succeeds.
- New: concurrent failures don't poison the cache for a fresh caller.
- New: case-sensitive org match pinned with a regression test.
- New: getGitHubAppConfig (3 tests covering null, happy path, warn-on-
  malformed-install-id).
- New: getDefaultGitHubAuth throws when neither App nor PAT configured.

bindings.ts didn't need to change for this round; the four
GITHUB_APP_* fields stay optional, and the consolidated validation
happens at runtime via getGitHubAppConfig.

31/31 tests pass. tsc --noEmit clean at root and backend/.
@neuromechanist

Copy link
Copy Markdown
Contributor Author

Review findings addressed (commit 8deb686)

Five reviews ran in parallel. Aggregated and applied; full details in commit body.

Source Finding Action
code-reviewer none ≥ 80% confidence; concurrency analysis confirms the cache logic is safe (single-threaded JS sets the in-flight promise before any yield) ship-ready — no changes needed for this report's concerns
silent-failure-hunter / test-analyzer `fetchInstallationToken` accepted empty `token` and past `expires_at` Fixed: reject empty token, reject past timestamps; covered by two new tests
silent-failure-hunter `getDefaultGitHubAuth` silently returned `{kind:"pat",token:""}` when nothing was configured Fixed: throws `No GitHub auth configured: ...` with actionable message; new test covers it
silent-failure-hunter `resolveInstallationId` silently degraded a typo'd install ID to PAT Fixed: consolidated through new `getGitHubAppConfig` which emits a `console.warn` naming the org + bad value; new test asserts the warn
test-analyzer concurrent caller arriving mid-failure not tested Added: two concurrent callers fail together, third caller succeeds after responder swaps
test-analyzer `signAppJwt` throwing mid-refresh (bad PEM) path not tested Added: bad-PEM env rejects, cache stays empty, next call with good env succeeds
test-analyzer `appId=0` boundary not covered for the Worker copy Added: parallels the Phase 1 script-side test
test-analyzer case-sensitive org match wasn't an explicit decision Pinned as current behavior with a regression test
type-design (#2) `expiresAt` unit lived in a comment; risked sec/ms confusion Fixed: branded `EpochMs` type; tsc enforces
type-design (#3) `FetchInstallationTokenOptions` was exported but only for tests Fixed: renamed `FetchInstallationTokenInternalOptions`, not exported
type-design (#5) Bindings GitHub App fields had no all-or-nothing enforcement Fixed at runtime via the new `getGitHubAppConfig` accessor — collapses the two separate runtime checks into one entry point with structured output
type-design (#4) `CacheEntry` shape encodes 3 states with optional field Deferred to a Phase 3 prep follow-up — the current shape passes all tests and Phase 3 will exercise the cache under real load
comment-analyzer 7 rot-prone phase/issue refs Fixed: trimmed file-top docstring, `REFRESH_LEAD_MS` comment, `signAppJwt` 30s comment, "discriminated source" header, `resolveInstallationId` docstring, and the test file's top docstring
silent-failure-hunter `__reset/seed` unguarded Deferred — matches the existing convention in `backend/src/services/github.ts:40-46`; staying consistent rather than introducing a new safety pattern in this PR
silent-failure-hunter PEM multi-block regex Deferred — speculative without real-world signal; the explicit PKCS#1/encrypted-PKCS#8 paths already cover the operator footguns

Tests: 31/31 pass. `tsc --noEmit` clean at root and `backend/`.

@neuromechanist
neuromechanist merged commit 719b61b into feature/issue-432-epic-github-app May 11, 2026
1 check passed
@neuromechanist
neuromechanist deleted the feature/issue-437-phase2-worker-auth branch May 14, 2026 15:33

This branch was previously deployed

1 inactive deployment
npm — 8deb6863 Deployed May 11, 2026 by neuromechanist via publish #763
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.

1 participant