Skip to content

fix(backend): recover entitlements after license sync#1454

Merged
brendan-kellam merged 3 commits into
mainfrom
brendan/fix-SOU-1511
Jul 15, 2026
Merged

fix(backend): recover entitlements after license sync#1454
brendan-kellam merged 3 commits into
mainfrom
brendan/fix-SOU-1511

Conversation

@brendan-kellam

@brendan-kellam brendan-kellam commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Fixes SOU-1511

Summary

  • remove one-time worker entitlement decisions during startup
  • lazily initialize and retry GitHub App authentication when the license assertion becomes available
  • keep permission-sync enforcement at scheduling and job-execution boundaries
  • fail GitHub App authentication safely instead of falling back to incomplete repository discovery

Testing

  • yarn workspace @sourcebot/backend test --run (161 tests passed)
  • yarn workspace @sourcebot/backend build

Note

Medium Risk
Changes GitHub connection sync and repo auth to error instead of PAT fallback when GitHub Apps are configured, and shifts permission-sync scheduling—both affect EE auth and repository visibility after license changes.

Overview
Fixes worker behavior when EE entitlements arrive after startup (e.g. online license refresh) by removing one-time entitlement gates at boot and re-checking at use time.

GitHub App: Startup no longer calls GithubAppManager.init() only when github-app is licensed at launch. ensureInitialized() loads config on first need, dedupes concurrent init, and retries after transient failures. When apps are configured in config, getOctokitWithGithubApp and getAuthCredentialsForRepo require the github-app entitlement and throw instead of silently falling back to PATs—so connection sync cannot treat a partial repo list as complete. Token/installation errors propagate the same way.

Permission sync: Schedulers always start when PERMISSION_SYNC_ENABLED is true; polling skips enqueueing without the entitlement, and in-flight jobs delay 30s and retry via BullMQ DelayedError if permission-syncing is missing mid-run.

Tests cover concurrent/retry init and GitHub App auth entitlement and no-fallback behavior.

Reviewed by Cursor Bugbot for commit a19d611. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where GitHub App authentication and permission synchronization could stop working after an online license refresh until a restart.
    • Permission syncing now safely postpones and retries work when the required entitlement is temporarily missing, without aborting schedulers.
    • Improved initialization reliability for concurrent requests and added clearer error reporting when GitHub App authentication can’t be completed.
    • When GitHub App auth is configured, failures no longer fall back silently to other authentication methods.
  • Tests
    • Added coverage for GitHub App initialization and authentication credential selection behavior.

@github-actions

This comment has been minimized.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

GitHub App initialization is now asynchronous, shared across concurrent callers, and retryable after failure. Authentication errors propagate explicitly. Permission sync schedulers remain active without entitlements and delay jobs for later retries.

Changes

Entitlement-aware services

Layer / File(s) Summary
Lazy GitHub App initialization
packages/backend/src/ee/githubAppManager.ts, packages/backend/src/ee/githubAppManager.test.ts
GithubAppManager uses shared asynchronous initialization, retries failed configuration loads, and requires initialization before token retrieval.
Licensed GitHub App authentication
packages/backend/src/github.ts, packages/backend/src/utils.ts, packages/backend/src/githubAppAuth.test.ts
GitHub App authentication initializes explicitly, checks entitlements, creates installation-token clients, and propagates token failures without legacy fallback.
Permission sync entitlement gating
packages/backend/src/ee/accountPermissionSyncer.ts, packages/backend/src/ee/repoPermissionSyncer.ts
Schedulers skip unavailable entitlement checks, while active jobs move to delayed state and throw DelayedError for 30-second retries.
Startup and worker activation
packages/backend/src/index.ts, CHANGELOG.md
Startup removes eager GitHub App initialization and entitlement-based worker gating; the changelog records the race-condition fix.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Request
  participant GithubAppManager
  participant Entitlements
  participant GitHub
  Request->>GithubAppManager: ensureInitialized()
  Request->>Entitlements: check github-app
  Request->>GithubAppManager: getInstallationToken()
  GithubAppManager->>GitHub: retrieve installation token
  GitHub-->>Request: authenticated Octokit client
Loading
sequenceDiagram
  participant Scheduler
  participant PermissionSyncWorker
  participant Entitlements
  participant BullMQ
  Scheduler->>Entitlements: check permission-syncing
  PermissionSyncWorker->>Entitlements: re-check entitlement
  PermissionSyncWorker->>BullMQ: move job to delayed state
  BullMQ-->>PermissionSyncWorker: DelayedError
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the backend fix for entitlement recovery after license synchronization.
✨ 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 brendan/fix-SOU-1511

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

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

🧹 Nitpick comments (3)
packages/backend/src/utils.ts (1)

135-163: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Entitlement-gated token flow duplicates github.ts::getOctokitWithGithubApp.

Same ensureInitialized → appsConfigured → hasEntitlement('github-app') → getInstallationToken sequence as in packages/backend/src/github.ts (Lines 123-151). See consolidated comment for a shared-helper suggestion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/backend/src/utils.ts` around lines 135 - 163, Refactor the GitHub
App authentication branch in the repository token flow to reuse the existing
shared logic from github.ts::getOctokitWithGithubApp, preserving entitlement
validation, initialization, app configuration checks, and installation-token
acquisition. Remove the duplicated
ensureInitialized/appsConfigured/hasEntitlement/getInstallationToken sequence
while retaining the current repository-specific URL and clone-token
construction.
packages/backend/src/github.ts (1)

123-151: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Entitlement-gated token flow is duplicated in utils.ts::getAuthCredentialsForRepo.

The ensureInitialized()appsConfigured()hasEntitlement('github-app')getInstallationToken() sequence here is re-implemented almost verbatim in packages/backend/src/utils.ts (Lines 135-152). Worth extracting into a shared helper to avoid the two call sites drifting (e.g., diverging error messages or entitlement logic) as this code evolves.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/backend/src/github.ts` around lines 123 - 151, Extract the shared
GitHub App initialization, configuration, entitlement validation, and
installation-token retrieval logic from getOctokitWithGithubApp into a reusable
helper, then update both getOctokitWithGithubApp and
utils.ts::getAuthCredentialsForRepo to use it. Preserve the existing behavior,
context-aware entitlement checks, hostname handling, and error propagation while
removing the duplicated sequence.
packages/backend/src/ee/githubAppManager.test.ts (1)

28-57: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add coverage for getInstallationToken() / assertInitialized().

The suite covers ensureInitialized() single-flight and retry semantics well, but the companion guard change — getInstallationToken() now throwing via assertInitialized() when called before a successful ensureInitialized() — has no direct test here. Worth adding a case asserting it throws pre-init and resolves correctly post-init, since this guard is the other half of the entitlement-recovery contract this PR introduces.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/backend/src/ee/githubAppManager.test.ts` around lines 28 - 57, Add a
test in the GithubAppManager.ensureInitialized suite covering
getInstallationToken and assertInitialized: verify getInstallationToken throws
before ensureInitialized succeeds, then initialize the manager and verify it
returns the expected token afterward. Reuse the existing mocks and manager
setup, preserving the current concurrency and retry tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/backend/src/ee/githubAppManager.test.ts`:
- Around line 28-57: Add a test in the GithubAppManager.ensureInitialized suite
covering getInstallationToken and assertInitialized: verify getInstallationToken
throws before ensureInitialized succeeds, then initialize the manager and verify
it returns the expected token afterward. Reuse the existing mocks and manager
setup, preserving the current concurrency and retry tests.

In `@packages/backend/src/github.ts`:
- Around line 123-151: Extract the shared GitHub App initialization,
configuration, entitlement validation, and installation-token retrieval logic
from getOctokitWithGithubApp into a reusable helper, then update both
getOctokitWithGithubApp and utils.ts::getAuthCredentialsForRepo to use it.
Preserve the existing behavior, context-aware entitlement checks, hostname
handling, and error propagation while removing the duplicated sequence.

In `@packages/backend/src/utils.ts`:
- Around line 135-163: Refactor the GitHub App authentication branch in the
repository token flow to reuse the existing shared logic from
github.ts::getOctokitWithGithubApp, preserving entitlement validation,
initialization, app configuration checks, and installation-token acquisition.
Remove the duplicated
ensureInitialized/appsConfigured/hasEntitlement/getInstallationToken sequence
while retaining the current repository-specific URL and clone-token
construction.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 13ddd89f-3e76-4df4-9a1b-e8a438a0bbac

📥 Commits

Reviewing files that changed from the base of the PR and between a50ca10 and ae7c73d.

📒 Files selected for processing (9)
  • CHANGELOG.md
  • packages/backend/src/ee/accountPermissionSyncer.ts
  • packages/backend/src/ee/githubAppManager.test.ts
  • packages/backend/src/ee/githubAppManager.ts
  • packages/backend/src/ee/repoPermissionSyncer.ts
  • packages/backend/src/github.ts
  • packages/backend/src/githubAppAuth.test.ts
  • packages/backend/src/index.ts
  • packages/backend/src/utils.ts

@brendan-kellam brendan-kellam merged commit bb5c4df into main Jul 15, 2026
10 checks passed
@brendan-kellam brendan-kellam deleted the brendan/fix-SOU-1511 branch July 15, 2026 23:24
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