Skip to content

refactor: consolidate duplicated auth header construction into shared utility#424

Merged
ColeMurray merged 2 commits intomainfrom
refactor/shared-auth-headers
Mar 28, 2026
Merged

refactor: consolidate duplicated auth header construction into shared utility#424
ColeMurray merged 2 commits intomainfrom
refactor/shared-auth-headers

Conversation

@ColeMurray
Copy link
Copy Markdown
Owner

@ColeMurray ColeMurray commented Mar 28, 2026

Summary

  • Add buildInternalAuthHeaders(secret, traceId) to @open-inspect/shared/src/auth.ts that encapsulates the repeated pattern of generating an HMAC token and building Authorization + x-trace-id headers
  • Replace 9 duplicated auth header construction sites across 5 packages (slack-bot, github-bot, linear-bot, web) to use the shared helper
  • The shared function intentionally omits Content-Type/Accept since those vary by call site -- callers spread the auth headers alongside their own content-type header

Sites consolidated

Package File Pattern
slack-bot src/index.ts getAuthHeaders wrapper delegates to shared
slack-bot src/classifier/repos.ts Inline replaced
slack-bot src/completion/extractor.ts Inline replaced
github-bot src/handlers.ts getAuthHeaders wrapper delegates to shared
github-bot src/utils/integration-config.ts Inline replaced
linear-bot src/webhook-handler.ts getAuthHeaders wrapper delegates to shared
linear-bot src/utils/integration-config.ts Inline replaced
linear-bot src/classifier/repos.ts Inline replaced
linear-bot src/completion/extractor.ts Inline replaced
web src/lib/control-plane.ts getControlPlaneHeaders delegates to shared

Test plan

  • npm run build -w @open-inspect/shared passes
  • npm run typecheck passes for shared, slack-bot, github-bot, linear-bot, web
  • npm run lint passes
  • npm test -w @open-inspect/slack-bot -- 30 tests pass
  • npm test -w @open-inspect/github-bot -- 100 tests pass
  • npm test -w @open-inspect/linear-bot -- 90 tests pass
  • npm test -w @open-inspect/web -- 118 tests pass

Summary by CodeRabbit

  • Refactor

    • Consolidated internal authentication header construction across multiple services to improve code maintainability and reduce duplication.
  • Tests

    • Updated test mocks to support consolidated authentication logic.

…rnalAuthHeaders

Add buildInternalAuthHeaders(secret, traceId) to @open-inspect/shared
and replace 9 duplicated auth header construction sites across
slack-bot, github-bot, linear-bot, and web packages.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 28, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: af99d39b-e967-4176-8f73-00af21744ec4

📥 Commits

Reviewing files that changed from the base of the PR and between 3f8e1bc and d491f60.

📒 Files selected for processing (1)
  • packages/shared/src/completion/extractor.ts

📝 Walkthrough

Walkthrough

This PR introduces a new buildInternalAuthHeaders helper function to consolidate HTTP header construction for internal service-to-service requests, then systematically refactors multiple packages to replace direct token generation and header construction with calls to this centralized helper. All existing control flow and error handling remain unchanged.

Changes

Cohort / File(s) Summary
New Internal Auth Headers Helper
packages/shared/src/auth.ts
Added new async helper buildInternalAuthHeaders(secret, traceId?) that returns HTTP headers object with conditionally included Authorization: Bearer <token> and x-trace-id fields.
Re-exports of buildInternalAuthHeaders
packages/github-bot/src/utils/internal.ts, packages/linear-bot/src/utils/internal.ts, packages/slack-bot/src/utils/internal.ts
Extended module exports to include new buildInternalAuthHeaders alongside existing generateInternalToken.
Handler and Integration Config Refactoring
packages/github-bot/src/handlers.ts, packages/github-bot/src/utils/integration-config.ts, packages/linear-bot/src/classifier/repos.ts, packages/linear-bot/src/utils/integration-config.ts, packages/linear-bot/src/webhook-handler.ts, packages/slack-bot/src/classifier/repos.ts, packages/slack-bot/src/index.ts, packages/web/src/lib/control-plane.ts
Replaced direct internal token generation and manual header construction with calls to buildInternalAuthHeaders helper, consolidating auth/trace header logic.
Shared Package Refactoring
packages/shared/src/completion/extractor.ts
Replaced inline token generation and header composition with buildInternalAuthHeaders helper for consistency.
Test Mocks
packages/github-bot/test/handlers.test.ts, packages/github-bot/test/integration-config.test.ts
Added mock definitions for new buildInternalAuthHeaders function to support test assertions.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • open-inspect

Poem

🐰 A helper born to centralize the way,
Auth headers dance in a unified display,
No more scattered tokens left and right,
One function shines, making headers bright!
✨🔐

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: consolidating duplicated auth header construction into a shared utility function across multiple packages.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/shared-auth-headers

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@open-inspect open-inspect Bot left a comment

Choose a reason for hiding this comment

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

Summary

PR Title and number: refactor: consolidate duplicated auth header construction into shared utility (#424)
Author: @ColeMurray
Files changed: 16 files, +67 / -70

This refactor cleanly centralizes the repeated internal auth header construction without changing the observable behavior at the updated call sites. I reviewed the diff and did not find any correctness, security, performance, or maintainability regressions.

Critical Issues

  • None.

Suggestions

  • [Testing] packages/shared/src/auth.ts:58 - Consider adding a small shared-unit test for buildInternalAuthHeaders() over time so the new helper's optional-secret and optional-trace-id behavior is covered at the abstraction boundary, rather than only through downstream mocks.

Nitpicks

  • None.

Positive Feedback

  • Consolidating the auth-header assembly into @open-inspect/shared removes a lot of low-value duplication while keeping Content-Type/Accept decisions at the call site, which preserves flexibility.
  • The helper keeps the previous fail-open/fail-closed behavior intact across the different packages instead of forcing a one-size-fits-all policy.
  • The updated package tests and repo typecheck/build all pass, which gives good confidence that the refactor is behavior-preserving.

Questions

  • None.

Verdict

  • Approve: Ready to merge, no blocking issues.

Take thin wrapper extractors from main (PR #423), update shared
extractor to use buildInternalAuthHeaders instead of inline
generateInternalToken.
@github-actions
Copy link
Copy Markdown

Terraform Validation Results

Step Status
Format
Init
Validate

Note: Terraform plan was skipped because secrets are not configured. This is expected for external contributors. See docs/GETTING_STARTED.md for setup instructions.

Pushed by: @ColeMurray, Action: pull_request

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/github-bot/src/utils/integration-config.ts (1)

29-36: Consider adding an early guard for missing secret.

Unlike packages/linear-bot/src/utils/integration-config.ts (which has an early guard at line 25), this implementation relies on the helper returning an empty headers object when INTERNAL_CALLBACK_SECRET is undefined. The request will proceed without an Authorization header, and the control plane will reject it with a non-ok response, triggering fail-closed behavior.

This works correctly but is less efficient—it makes a network request that will fail. If consistency with linear-bot is desired, consider adding an early guard:

 export async function getGitHubConfig(
   env: Env,
   repo: string,
   log?: Logger
 ): Promise<ResolvedGitHubConfig> {
+  if (!env.INTERNAL_CALLBACK_SECRET) {
+    return { ...FAIL_CLOSED, model: env.DEFAULT_MODEL };
+  }
   const [owner, name] = repo.split("/");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/github-bot/src/utils/integration-config.ts` around lines 29 - 36,
Add an early guard that checks env.INTERNAL_CALLBACK_SECRET before calling
buildInternalAuthHeaders to avoid making a needless network request when the
secret is missing: if env.INTERNAL_CALLBACK_SECRET is falsy, return early (e.g.,
throw or return a suitable empty/unauthorized result) instead of calling
env.CONTROL_PLANE.fetch; update the code path that currently calls
buildInternalAuthHeaders(repo) and
env.CONTROL_PLANE.fetch(`https://internal/integration-settings/github/resolved/${owner}/${name}`,
{ headers }) to perform the pre-check and short-circuit before building headers
or fetching.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/github-bot/test/handlers.test.ts`:
- Around line 20-22: The mock for buildInternalAuthHeaders should mirror the
real helper by returning both Authorization and the x-trace-id header; update
the vi.fn().mockResolvedValue to include an "x-trace-id" entry (or, if the real
helper accepts a trace-id/ctx param, make the mock inspect its arg and return
that value for "x-trace-id") so tests exercise trace propagation failures;
locate and update the mock declaration for buildInternalAuthHeaders to return {
Authorization: "Bearer test-internal-token", "x-trace-id":
"<same-or-propagated-trace-id>" } (or dynamically propagate the input trace id)
instead of only Authorization.

---

Nitpick comments:
In `@packages/github-bot/src/utils/integration-config.ts`:
- Around line 29-36: Add an early guard that checks env.INTERNAL_CALLBACK_SECRET
before calling buildInternalAuthHeaders to avoid making a needless network
request when the secret is missing: if env.INTERNAL_CALLBACK_SECRET is falsy,
return early (e.g., throw or return a suitable empty/unauthorized result)
instead of calling env.CONTROL_PLANE.fetch; update the code path that currently
calls buildInternalAuthHeaders(repo) and
env.CONTROL_PLANE.fetch(`https://internal/integration-settings/github/resolved/${owner}/${name}`,
{ headers }) to perform the pre-check and short-circuit before building headers
or fetching.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 011720f9-62d4-4bdd-a978-141595e72ebd

📥 Commits

Reviewing files that changed from the base of the PR and between 89319ac and 3f8e1bc.

📒 Files selected for processing (16)
  • packages/github-bot/src/handlers.ts
  • packages/github-bot/src/utils/integration-config.ts
  • packages/github-bot/src/utils/internal.ts
  • packages/github-bot/test/handlers.test.ts
  • packages/github-bot/test/integration-config.test.ts
  • packages/linear-bot/src/classifier/repos.ts
  • packages/linear-bot/src/completion/extractor.ts
  • packages/linear-bot/src/utils/integration-config.ts
  • packages/linear-bot/src/utils/internal.ts
  • packages/linear-bot/src/webhook-handler.ts
  • packages/shared/src/auth.ts
  • packages/slack-bot/src/classifier/repos.ts
  • packages/slack-bot/src/completion/extractor.ts
  • packages/slack-bot/src/index.ts
  • packages/slack-bot/src/utils/internal.ts
  • packages/web/src/lib/control-plane.ts

Comment thread packages/github-bot/test/handlers.test.ts
@ColeMurray ColeMurray merged commit 56d2833 into main Mar 28, 2026
14 of 15 checks passed
@ColeMurray ColeMurray deleted the refactor/shared-auth-headers branch March 28, 2026 06:30
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