Skip to content

Comments

feat: add Bitbucket Cloud OAuth identity provider#924

Merged
brendan-kellam merged 3 commits intomainfrom
brendan/bitbucket-cloud-oauth-idp
Feb 24, 2026
Merged

feat: add Bitbucket Cloud OAuth identity provider#924
brendan-kellam merged 3 commits intomainfrom
brendan/bitbucket-cloud-oauth-idp

Conversation

@brendan-kellam
Copy link
Contributor

@brendan-kellam brendan-kellam commented Feb 24, 2026

Summary

  • Adds BitbucketCloudIdentityProviderConfig schema (provider: "bitbucket-cloud") with sso and account_linking purpose support
  • Wires up next-auth's built-in Bitbucket provider in sso.ts with the ID overridden to "bitbucket-cloud", requesting account + repository scopes when permission syncing is enabled
  • Adds bitbucket-cloud token refresh in tokenRefresh.ts using HTTP Basic Auth (Bitbucket's required auth method, unlike GitHub/GitLab which use request body params)
  • Adds IdentityProviderType (derived from the schema union) and PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS constant for type-safe provider handling in the account permission syncer
  • Adds Bitbucket Cloud setup instructions to docs/configuration/idp.mdx

Test plan

  • Register a Bitbucket Cloud OAuth consumer with callback URL <host>/api/auth/callback/bitbucket-cloud, Account: Read scope, and Repositories: Read scope
  • Add "provider": "bitbucket-cloud" identity provider to config.json and verify login flow works
  • Link a Bitbucket Cloud account and verify Account row is created with provider = 'bitbucket-cloud'
  • Set expires_at = 1 on the linked account in the DB and trigger a session refresh; verify token is refreshed via logs

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added Bitbucket Cloud as a supported OAuth identity provider for SSO and account-linked permission syncing.
  • Improvements
    • Improved token refresh handling, including per-user locking to reduce concurrent refresh conflicts.
  • Documentation
    • Added a Bitbucket Cloud setup guide covering OAuth registration and configuration steps.

- Add BitbucketCloudIdentityProviderConfig schema (provider: "bitbucket-cloud")
- Add createBitbucketCloudProvider() in sso.ts with id override and repository scope
- Add bitbucket-cloud token refresh support using HTTP Basic Auth
- Add IdentityProviderType derived from schema union for type-safe provider constants
- Add PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS constant
- Add Bitbucket Cloud provider info to getAuthProviderInfo() utility
- Add idp.mdx docs for Bitbucket Cloud OAuth consumer setup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@github-actions

This comment has been minimized.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 24, 2026

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b5f71c and cc2a3fc.

📒 Files selected for processing (2)
  • packages/db/prisma/schema.prisma
  • packages/web/src/ee/features/sso/sso.ts

Walkthrough

Adds Bitbucket Cloud as a supported OAuth identity provider (SSO and account-linked permission syncing), updating schemas, types, provider wiring, token-refresh logic, backend permission-sync filtering, docs, and UI metadata.

Changes

Cohort / File(s) Summary
Documentation & Changelog
CHANGELOG.md, docs/docs/configuration/idp.mdx
Added Bitbucket Cloud changelog entry and a full Bitbucket Cloud configuration guide with OAuth setup and example identityProviders snippet.
Schema Snippets (docs)
docs/snippets/schemas/v3/identityProvider.schema.mdx, docs/snippets/schemas/v3/index.schema.mdx
Added BitbucketCloudIdentityProviderConfig definition and included it in the public oneOf for identity provider configs.
Published JSON Schema
schemas/v3/identityProvider.json
Wired new BitbucketCloudIdentityProviderConfig into the top-level identity provider oneOf.
Runtime Schemas & Types
packages/schemas/src/v3/identityProvider.schema.ts, packages/schemas/src/v3/index.schema.ts, packages/schemas/src/v3/identityProvider.type.ts, packages/schemas/src/v3/index.type.ts
Introduced BitbucketCloudIdentityProviderConfig type/schema and included it in the IdentityProviderConfig union (supports env or Google secret credentials, purpose: sso
Shared Types Export
packages/shared/src/types.ts, packages/shared/src/index.server.ts
Added exported IdentityProviderType (derived from IdentityProviderConfig['provider']).
Backend Constants & Syncer
packages/backend/src/constants.ts, packages/backend/src/ee/accountPermissionSyncer.ts
Added PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS constant and switched accountPermissionSyncer to use it when filtering accounts for permission syncing.
Database Comment
packages/db/prisma/schema.prisma
Added documentation comment linking Account.provider to the identity provider schema provider value.
Token Refresh & Permission Syncing (web EE)
packages/web/src/ee/features/permissionSyncing/tokenRefresh.ts
Added Bitbucket Cloud token refresh support, per-user in-memory refresh locking, support for provider-specific credential resolution (env or secrets), and Basic Auth handling for Bitbucket token endpoint; exposed refreshLinkedAccountTokens(userId).
SSO Provider Wiring (web EE)
packages/web/src/ee/features/sso/sso.ts
Added Bitbucket Cloud provider creation (createBitbucketCloudProvider) and integration into getEEIdentityProviders; annotated provider id values with IdentityProviderType.
UI Utilities
packages/web/src/lib/utils.ts
Extended getAuthProviderInfo to include Bitbucket Cloud metadata and logo.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Scheduler
participant WebServer
participant DB as Database
participant OAuth as BitbucketOAuth
Scheduler->>WebServer: trigger permission-sync / refreshLinkedAccountTokens(userId)
WebServer->>DB: load user's linked accounts & provider configs
WebServer->>WebServer: acquire per-user refresh lock
WebServer->>OAuth: token refresh request (client creds / Basic Auth)
OAuth-->>WebServer: token response / error
WebServer->>DB: store refreshed tokens or mark errors
WebServer->>WebServer: release per-user refresh lock
WebServer-->>Scheduler: return results

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

  • #924: Adds Bitbucket Cloud OAuth support and overlaps identity provider schemas, sso wiring, token refresh logic, and constants.
  • #841: Modifies token refresh orchestration and credential handling in tokenRefresh.ts, overlapping with per-user locking and refresh flow changes.
  • #600: Refactors accountPermissionSyncer logic; intersects with the account syncer changes that now reference PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS.

Suggested labels

sourcebot-team

Suggested reviewers

  • msukkari
🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat: add Bitbucket Cloud OAuth identity provider' accurately and concisely summarizes the main change—adding support for Bitbucket Cloud as an OAuth identity provider. It is specific, clear, and directly reflects the primary objective of the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch brendan/bitbucket-cloud-oauth-idp

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 and usage tips.

Copy link
Contributor

@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: 3

🧹 Nitpick comments (1)
packages/backend/src/ee/accountPermissionSyncer.ts (1)

173-272: Add a defensive else clause to prevent silent permission wipe for future providers.

PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS and the if/else if branches inside runJob are implicitly coupled. When 'bitbucket-cloud' (or any future provider) is added to that constant without a matching branch here, aggregatedRepoIds stays empty and the transaction at lines 275-293 will deleteMany all existing permissions while creating none — silently revoking all repo access for every affected user.

🛡️ Proposed fix — defensive else clause
             repos.forEach(repo => aggregatedRepoIds.add(repo.id));
+        } else {
+            throw new Error(`Unsupported identity provider for permission syncing: ${account.provider}. Add a handler branch in runJob.`);
         }

         return Array.from(aggregatedRepoIds);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/backend/src/ee/accountPermissionSyncer.ts` around lines 173 - 272,
The permission-collection logic in runJob risks returning an empty
aggregatedRepoIds for unknown providers (e.g., when
PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS is extended) which can silently
delete all permissions; add a defensive else branch after the account.provider
checks that either throws a clear error or logs and returns early when
account.provider is unrecognized, referencing the aggregatedRepoIds variable and
the runJob/account.provider check so the function fails fast instead of allowing
the later deleteMany to run with an empty set.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/docs/configuration/idp.mdx`:
- Around line 172-173: The docs currently claim Bitbucket Cloud supports
"permission syncing" but the codebase (see the account permission syncer branch
in runJob and the PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS constant which
excludes 'bitbucket-cloud') does not schedule Bitbucket Cloud syncs; update the
docs in idp.mdx (references around the sentence mentioning "permission syncing"
and the Repositories: Read note at lines ~183–185) to either remove
permission-syncing references for Bitbucket Cloud or explicitly mark permission
syncing as "not yet implemented / coming soon", and add a brief TODO or link to
the tracking issue so readers know it's planned; use the symbols runJob and
PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS to verify the implementation status
while editing the text.

In `@packages/db/prisma/schema.prisma`:
- Around line 409-411: The schema comment describing "matches the `provider`
field of the `IdentityProviderConfig` schema" is misplaced on the `type` field;
update the Prisma model by removing that note from the `type` field and adding
it to the `provider` field so the comment sits directly above `provider` (the
field used for provider identifiers like "github"/"gitlab"); verify the `type`
field remains documented for account category semantics and that only the
`provider` field carries the referenced note.

In `@packages/web/src/ee/features/sso/sso.ts`:
- Around line 225-245: The Bitbucket Cloud provider defined in
createBitbucketCloudProvider is missing the required "email" OAuth scope, so
update the authorization.params.scope array inside createBitbucketCloudProvider
to include "email" (alongside "account" and the conditional "repository" scope)
so requests to /2.0/user/emails will be authorized; ensure the "email" string is
included in the same join(' ') list used for authorization.params.scope in the
Bitbucket provider configuration.

---

Nitpick comments:
In `@packages/backend/src/ee/accountPermissionSyncer.ts`:
- Around line 173-272: The permission-collection logic in runJob risks returning
an empty aggregatedRepoIds for unknown providers (e.g., when
PERMISSION_SYNC_SUPPORTED_IDENTITY_PROVIDERS is extended) which can silently
delete all permissions; add a defensive else branch after the account.provider
checks that either throws a clear error or logs and returns early when
account.provider is unrecognized, referencing the aggregatedRepoIds variable and
the runJob/account.provider check so the function fails fast instead of allowing
the later deleteMany to run with an empty set.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5be4667 and 8b5f71c.

📒 Files selected for processing (17)
  • CHANGELOG.md
  • docs/docs/configuration/idp.mdx
  • docs/snippets/schemas/v3/identityProvider.schema.mdx
  • docs/snippets/schemas/v3/index.schema.mdx
  • packages/backend/src/constants.ts
  • packages/backend/src/ee/accountPermissionSyncer.ts
  • packages/db/prisma/schema.prisma
  • packages/schemas/src/v3/identityProvider.schema.ts
  • packages/schemas/src/v3/identityProvider.type.ts
  • packages/schemas/src/v3/index.schema.ts
  • packages/schemas/src/v3/index.type.ts
  • packages/shared/src/index.server.ts
  • packages/shared/src/types.ts
  • packages/web/src/ee/features/permissionSyncing/tokenRefresh.ts
  • packages/web/src/ee/features/sso/sso.ts
  • packages/web/src/lib/utils.ts
  • schemas/v3/identityProvider.json

@brendan-kellam brendan-kellam merged commit 8d171f6 into main Feb 24, 2026
9 of 10 checks passed
@brendan-kellam brendan-kellam deleted the brendan/bitbucket-cloud-oauth-idp branch February 24, 2026 03:40
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