diff --git a/application/single_app/templates/bitbucket_connection.html b/application/single_app/templates/bitbucket_connection.html
new file mode 100644
index 000000000..dead352fb
--- /dev/null
+++ b/application/single_app/templates/bitbucket_connection.html
@@ -0,0 +1,22 @@
+
+
+
+
+
+
Connect Bitbucket - SimpleChat
+
+
+
+
+
+ Connect Bitbucket
+ Connect your own Bitbucket account for this action. Bitbucket handles smart-card or SSO sign-in; SimpleChat does not copy your browser session.
+ Your connection is private. Repository and branch restrictions still apply. Disconnecting removes local access; revoke the grant in Bitbucket to remove provider-side authorization.
+ Checking your connection...
+ Connect Bitbucket
+ Disconnect
+ Refresh status
+ After connecting, return to your conversation and retry the review.
+
+
+
diff --git a/application/v2_ui/src/components/workspaceActions/ActionAuthentication.tsx b/application/v2_ui/src/components/workspaceActions/ActionAuthentication.tsx
index afe2740da..1ca8d6759 100644
--- a/application/v2_ui/src/components/workspaceActions/ActionAuthentication.tsx
+++ b/application/v2_ui/src/components/workspaceActions/ActionAuthentication.tsx
@@ -97,6 +97,7 @@ export function ActionAuthentication(props: ActionConnectorProps & { definition:
) : null;
+ if (draft.type === 'bitbucket') return
Configure Bitbucket authentication and your private connection in Configuration. Shared credentials are never substituted for a failed personal connection.
;
if (native.internal) return (
{draft.auth.type === 'user'
diff --git a/application/v2_ui/src/components/workspaceActions/ActionConfigurationFields.tsx b/application/v2_ui/src/components/workspaceActions/ActionConfigurationFields.tsx
index 0d28f4bbb..8e1d1453a 100644
--- a/application/v2_ui/src/components/workspaceActions/ActionConfigurationFields.tsx
+++ b/application/v2_ui/src/components/workspaceActions/ActionConfigurationFields.tsx
@@ -7,6 +7,7 @@ import { ActionField, ActionJsonInput, ActionLinesInput, ActionSecretInput, ACTI
import { ActionSchemaFields } from './ActionSchemaFields';
import { CallAgentActionConfiguration } from './CallAgentActionConfiguration';
import { DocumentSearchActionConfiguration } from './DocumentSearchActionConfiguration';
+import { BitbucketActionConfiguration } from './BitbucketActionConfiguration';
import {
actionFieldError, actionHasStoredArraySecrets, actionText, actionValueAt, changeActionField,
changeSqlConnectionMethod, deriveBlobEndpoint, displayedActionValue,
@@ -109,7 +110,7 @@ function schemaHasVisibleProperties(definition: ActionTypeDefinition) {
}
export function hasActionConfigurationFields(definition: ActionTypeDefinition) {
- if (definition.type === 'agent' || definition.type === 'document_search' || definition.type === 'search' ||
+ if (definition.type === 'bitbucket' || definition.type === 'agent' || definition.type === 'document_search' || definition.type === 'search' ||
definition.type === 'openapi' || definition.type === 'mcp') return true;
const native = nativeActionDefinition(definition.type);
return native.fields.length > 0 || Boolean(capabilityDefinition(definition, native)) || schemaHasVisibleProperties(definition);
@@ -121,6 +122,7 @@ export function ActionConfigurationFields(props: ActionConnectorProps & { defini
const [confirmParameters, setConfirmParameters] = useState(false);
const native = nativeActionDefinition(draft.type);
if (draft.type === 'agent') return ;
+ if (draft.type === 'bitbucket') return ;
if (draft.type === 'document_search' || draft.type === 'search') return ;
const sql = ['sql_query', 'sql_schema'].includes(draft.type);
const capabilities = capabilityDefinition(definition, native);
diff --git a/application/v2_ui/src/components/workspaceActions/BitbucketActionConfiguration.tsx b/application/v2_ui/src/components/workspaceActions/BitbucketActionConfiguration.tsx
new file mode 100644
index 000000000..c7d7487ea
--- /dev/null
+++ b/application/v2_ui/src/components/workspaceActions/BitbucketActionConfiguration.tsx
@@ -0,0 +1,180 @@
+// BitbucketActionConfiguration.tsx
+
+import { useId, useState } from 'react';
+import { api, request } from '../../lib/apiClient';
+import { isRecord } from '../../lib/workspaceAuthoring';
+import type { ActionConnectorProps } from '../../lib/workspaceActionTypes';
+import { changeActionCredentialSource, changeActionField } from '../../lib/workspaceActionLogic';
+import { ActionField, ActionSecretInput, ACTION_INPUT_CLASS } from './ActionFields';
+import { EditorFieldset } from '../workspace/EditorLayout';
+
+interface Repository {
+ id: string;
+ project: string;
+ slug: string;
+ name: string;
+ branch_mode: string;
+ default_branch: string;
+}
+
+function repositories(value: unknown): Repository[] {
+ return Array.isArray(value) ? value.filter(isRecord).map((item) => ({
+ id: String(item.id ?? ''), project: String(item.project ?? ''), slug: String(item.slug ?? ''),
+ name: String(item.name ?? ''), branch_mode: String(item.branch_mode ?? 'any'),
+ default_branch: String(item.default_branch ?? ''),
+ })) : [];
+}
+
+export function BitbucketActionConfiguration(props: ActionConnectorProps) {
+ const { draft, onChange, readOnly } = props;
+ const id = useId();
+ const [project, setProject] = useState('');
+ const [options, setOptions] = useState([]);
+ const [cursor, setCursor] = useState(null);
+ const [message, setMessage] = useState('');
+ const [busy, setBusy] = useState(false);
+ const method = String(draft.additionalFields.auth_method ?? 'oauth');
+ const edition = String(draft.additionalFields.edition ?? 'data_center');
+ const selected = repositories(draft.additionalFields.repositories);
+ const personal = Boolean(draft.credential_requirements?.slots.service);
+ const scope = props.globalScope ? 'global:global' : props.groupScope ? `group:${props.groupScope.id}` : 'personal:self';
+ const reference = draft.id ? `${scope}:${draft.id}` : '';
+ const update = (path: string, value: unknown) => onChange((current) => changeActionField(current, path, value));
+ const updateRepo = (index: number, patch: Partial) =>
+ update('/additionalFields/repositories', selected.map((repo, i) => i === index ? { ...repo, ...patch } : repo));
+
+ async function discover(next: number | string = 0) {
+ setBusy(true);
+ setMessage('');
+ try {
+ const status = await api.get<{ csrf_token: string }>(`/api/bitbucket/connection?action_ref=${encodeURIComponent(reference)}`);
+ const result = await request<{ repositories: unknown; next_cursor: number | string | null }>('/api/bitbucket/discover',
+ { method: 'POST', body: { action_ref: reference, project, cursor: next },
+ headers: { 'X-CSRFToken': status.csrf_token } });
+ setOptions((previous) => next ? [...previous, ...repositories(result.repositories)] : repositories(result.repositories));
+ setCursor(result.next_cursor);
+ setMessage(result.repositories && Array.isArray(result.repositories) && result.repositories.length
+ ? 'Select permitted repositories below. Save again to apply changes.'
+ : 'No repositories are accessible in this project or workspace.');
+ } catch (error) {
+ setMessage(error instanceof Error ? error.message : 'Repository discovery failed.');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return
+
Read source and compare branches. This action cannot change repositories or post reviews.
+
+ {
+ update('/additionalFields/edition', event.target.value);
+ if (event.target.value === 'cloud') update('/endpoint', 'https://api.bitbucket.org');
+ }}>
+ Self-hosted Data Center Bitbucket Cloud
+
+
+
+ update('/endpoint', event.target.value)} />
+
+
+ onChange((current) => ({
+ ...current, identity_id: '', credential_requirements: undefined,
+ auth: { type: event.target.value === 'oauth' ? 'user' : event.target.value === 'username_password' ? 'username_password' : 'key' },
+ additionalFields: { ...current.additionalFields, auth_method: event.target.value },
+ }))}>
+ Each user's OAuth connection (SSO / smart card)
+ HTTP access / bearer token
+ {edition === 'cloud' ? Atlassian email and scoped API token : null}
+
+
+ {method === 'oauth' ? <>
+
+ update('/auth/identity', event.target.value)} />
+
+
update('/auth/key', value)} />
+ {reference ? Connect / reconnect my Bitbucket account
+ : Save this action first, connect your account, then reopen it to select permitted repositories.
}
+ Connections belong to the invoking user, not the action author. SimpleChat and Microsoft 365 session tokens are never reused.
+ > : <>
+
+ {
+ if (event.target.value === 'personal') onChange((current) => changeActionCredentialSource(current, 'service', true));
+ else onChange((current) => ({
+ ...current, credential_requirements: undefined, identity_id: '',
+ auth: { type: event.target.value === 'identity' ? 'identity' : method === 'username_password' ? 'username_password' : 'key', identity: '', key: '' },
+ }));
+ }}>
+ Each user's private identity, requested in chat
+ Shared action credential
+ Saved workspace identity (shared by action users)
+
+
+ {!draft.credential_requirements?.slots.service ? <>
+
+ onChange((current) => ({ ...current, identity_id: event.target.value,
+ auth: { ...current.auth, type: event.target.value ? 'identity' : method === 'username_password' ? 'username_password' : 'key', identity: event.target.value, key: '' } }))}>
+ Use action credential below
+ {draft.identity_id && !props.identities.some((candidate) => candidate.id === draft.identity_id)
+ ? Unavailable identity — kept as is : null}
+ {props.identities.filter((identity) => identity.auth_type === method).map((identity) =>
+ {identity.name} )}
+
+
+ {props.identitiesError ? {props.identitiesError}
: null}
+ {!draft.identity_id ? <>
+ {method === 'username_password' ?
+ update('/auth/identity', event.target.value)} />
+ : null}
+ update('/auth/key', value)} />
+ > : null}
+ > : Each invoking user supplies a compatible personal token identity privately in chat. No shared token is saved here.
}
+ >}
+
+
+ { setProject(event.target.value); setOptions([]); setCursor(null); }} />
+
+ void discover()}>
+ {busy ? 'Loading repositories...' : 'Find repositories'}
+
+ {personal ? Discover using OAuth or a saved/shared token before switching to per-user tokens.
: null}
+ {cursor !== null ? void discover(cursor)}>Load more repositories : null}
+ {message ? {message}
: null}
+ {options.map((repo) =>
+ item.id === repo.id)} disabled={readOnly}
+ onChange={(event) => update('/additionalFields/repositories', event.target.checked
+ ? [...selected, repo] : selected.filter((item) => item.id !== repo.id))} />
+ {repo.name} ({repo.slug})
+ )}
+ {selected.map((repo, index) =>
+
+ updateRepo(index, { branch_mode: event.target.value })}>
+ Any branch One fixed branch
+
+
+
+ updateRepo(index, { default_branch: event.target.value })} />
+
+ update('/additionalFields/repositories', selected.filter((item) => item.id !== repo.id))}>Remove repository
+ )}
+
+ ;
+}
diff --git a/application/v2_ui/src/lib/workspaceActionLogic.ts b/application/v2_ui/src/lib/workspaceActionLogic.ts
index 03be8b82a..6d590ccb7 100644
--- a/application/v2_ui/src/lib/workspaceActionLogic.ts
+++ b/application/v2_ui/src/lib/workspaceActionLogic.ts
@@ -414,6 +414,7 @@ export function actionAuthModes(type: string, allowed: string[]): ActionAuthMode
}
export function actionAuthMethod(draft: ActionConfiguration): string {
+ if (draft.type === 'bitbucket') return actionText(draft.additionalFields.auth_method) || 'oauth';
if (draft.type === 'sql_query' || draft.type === 'sql_schema') {
return actionText(draft.additionalFields.auth_type) ||
(draft.auth.type === 'servicePrincipal' ? 'service_principal' : draft.auth.type === 'identity' ? 'managed_identity' : 'username_password');
@@ -456,7 +457,8 @@ export function usesPersonalActionCredential(draft: ActionConfiguration, slot: '
export function changeActionCredentialSource(
draft: ActionConfiguration, slot: 'service' | 'proxy', personal: boolean,
): ActionConfiguration {
- if (draft.type !== 'yamcs') throw new Error('Personal credentials are not supported by this action.');
+ if (!['yamcs', 'bitbucket'].includes(draft.type)) throw new Error('Personal credentials are not supported by this action.');
+ if (draft.type === 'bitbucket' && slot !== 'service') throw new Error('Bitbucket supports only service token credentials.');
const slots = { ...draft.credential_requirements?.slots };
if (!personal) {
delete slots[slot];
@@ -611,7 +613,7 @@ export function validateActionDraft(
errors['/additionalFields/user'] = 'Snowflake user is required for key-pair or OAuth authentication.';
}
if (draft.credential_requirements) {
- if (draft.type !== 'yamcs' || draft.credential_requirements.version !== 1) {
+ if (!['yamcs', 'bitbucket'].includes(draft.type) || draft.credential_requirements.version !== 1) {
errors['/credential_requirements'] = 'This action does not support these credential requirements.';
}
if (!isRecord(draft.credential_requirements.slots)) {
@@ -619,6 +621,7 @@ export function validateActionDraft(
}
for (const [slot, requirement] of Object.entries(draft.credential_requirements.slots ?? {})) {
if (!requirement || requirement.source !== 'personal' || !['service', 'proxy'].includes(slot) ||
+ (draft.type === 'bitbucket' && slot !== 'service') ||
!['username_password', 'api_key', 'bearer_token'].includes(requirement.auth_type)) {
errors['/credential_requirements'] = 'Choose a supported personal credential source.';
} else if (slot === 'service' && requirement.auth_type !== actionAuthMethod(draft)) {
diff --git a/application/v2_ui/src/lib/workspaceActionRegistry.ts b/application/v2_ui/src/lib/workspaceActionRegistry.ts
index 4cbbb7ef7..6014589f0 100644
--- a/application/v2_ui/src/lib/workspaceActionRegistry.ts
+++ b/application/v2_ui/src/lib/workspaceActionRegistry.ts
@@ -137,6 +137,12 @@ const internalUtility = (type: string, help: string): ActionNativeDefinition =>
/** Native controls supplement, never replace, the governed catalogue and its schemas. */
export const NATIVE_ACTION_TYPES: Record = {
+ bitbucket: {
+ fields: [], identityTypes: ['bearer_token', 'username_password'],
+ defaults: { endpoint: '', auth: { type: 'user', identity: '', key: '' },
+ additionalFields: { edition: 'data_center', auth_method: 'oauth', repositories: [] } },
+ help: 'Read repository source and compare permitted branches using Bitbucket OAuth or token identities.',
+ },
openapi: { fields: [], identityTypes: ['api_key', 'bearer_token', 'username_password'], defaults: {
auth: { type: 'key', key: '' }, additionalFields: { auth_method: 'none', openapi_source_type: 'content' },
} },
diff --git a/docs/_data/app_surface.yml b/docs/_data/app_surface.yml
index 66110edee..6b8bf6783 100644
--- a/docs/_data/app_surface.yml
+++ b/docs/_data/app_surface.yml
@@ -5,10 +5,10 @@ counts:
admin_groups: 15
admin_tabs: 49
admin_sections: 109
- actions: 34
+ actions: 35
chat_controls: 47
sub_elements: 3
- app_pages: 33
+ app_pages: 34
feature_surfaces: 26
capabilities:
- key: enable_action_ai_assistant
@@ -968,6 +968,9 @@ actions:
- slug: azure-maps-openlayers
module: azure_maps_openlayers_plugin.py
class_name: AzureMapsOpenLayersPlugin
+- slug: bitbucket
+ module: bitbucket_plugin.py
+ class_name: BitbucketPlugin
- slug: blob-storage
module: blob_storage_plugin.py
class_name: BlobStoragePlugin
@@ -1234,6 +1237,9 @@ app_pages:
- template: approvals.html
slug: approvals
route_url: /approvals
+- template: bitbucket_connection.html
+ slug: bitbucket-connection
+ route_url: /bitbucket/connect
- template: chats.html
slug: chats
route_url: /chats
diff --git a/docs/explanation/features/BITBUCKET_REPOSITORY_ACTION.md b/docs/explanation/features/BITBUCKET_REPOSITORY_ACTION.md
new file mode 100644
index 000000000..011c5cb40
--- /dev/null
+++ b/docs/explanation/features/BITBUCKET_REPOSITORY_ACTION.md
@@ -0,0 +1,161 @@
+# Bitbucket repository review action
+
+Fixed/Implemented in version: **0.261.450**.
+Error-boundary correction implemented in version: **0.261.451**.
+The application version is recorded in `application/single_app/config.py`.
+
+## Overview and dependencies
+
+The `bitbucket` native action retrieves allowlisted repository source and
+merge-base-to-target branch comparisons. It supports self-hosted Data Center
+and Cloud through REST, without Git execution or repository writes. Users select
+repositories and branches conversationally.
+
+Dependencies are the existing requests/guarded HTTP transport, cryptography
+Fernet, Cosmos SDK, action catalog/governance, scoped workspace identities and
+Semantic Kernel. No new package, external browser asset or Azure test server
+is introduced. Provider applications/tokens need repository-read access.
+
+## Architecture and configuration
+
+`functions_bitbucket_operations.py` owns manifest validation, branch policy,
+stable repository-ID verification, provider URLs, bounded response parsing and
+read-only operations. `semantic_kernel_plugins/bitbucket_plugin.py` exposes
+`list_repositories`, `list_branches`, `list_tree`, `read_file` and
+`compare_branches`. The current authorized action is rechecked at invocation.
+
+An action names one HTTPS deployment/edition and up to 50 repositories, each
+with stable `id`, `project`, `slug`, `name`, `branch_mode` (`fixed`/`any`) and
+`default_branch`. An empty allowlist is a setup-only state: save connection
+configuration, connect, discover/select repositories, then save again.
+
+Repository access verifies that the current provider ID matches the saved ID.
+Both comparison branches satisfy policy and resolve to immutable commits
+before source retrieval. Fixed branch mode does not permit a different
+baseline. A configured default never falls back if unavailable.
+
+Data Center uses repository REST `/rest/api/1.0`, including context paths;
+Cloud uses `https://api.bitbucket.org/2.0`. Cloud diffstat orders source first
+and baseline second, unlike `git diff`. Comparisons explicitly obtain the
+merge base and retrieve full bounded before/after text to generate local
+patches, rather than assuming a provider's truncated patch is complete.
+
+Pagination reconstructs requests to the same API operation. Cloud continuation
+URLs must retain the origin, path and relevant filters; only their opaque page
+token is carried forward. Credentials are never sent to returned arbitrary
+URLs or HTTP redirects. Enterprise private addressing remains supported by
+the existing destination guard; loopback/link-local/metadata targets do not.
+
+## Authentication and storage
+
+`functions_bitbucket_connections.py` is bootstrap-free; initialized
+`functions_action_credential_runtime.py` supplies storage, current action
+authorization, scoped identity hydration and secret resolution.
+
+OAuth connections use `bitbucket_connections`, partitioned by `/user_id`.
+Tokens and PKCE verifiers are encrypted with the deployment's
+`BITBUCKET_TOKEN_ENCRYPTION_KEY`. That setting must contain a persistent Fernet
+key from secret storage. `BITBUCKET_REDIRECT_URI` is the canonical HTTPS callback
+ending in `/api/bitbucket/callback`; request Host is not its authority.
+
+OAuth state is single-use, session/actor/action/policy-bound and expires after
+600 seconds. Connections retain ETags and generation fencing. Refresh claims
+are conditional, preventing concurrent replay of rotating refresh tokens.
+Disconnect and newer connect flows fence older callbacks/refresh responses.
+The actor/action connection has a stable storage key, so disconnect also clears
+the old tokens after an author changes repository or branch policy. Restoring
+the old policy cannot resurrect a disconnected connection.
+An uncertain refresh is not replayed; reconnect after a failed or interrupted
+claim. Local disconnect does not promise provider-side grant revocation.
+
+Data Center uses its incoming application-link authorization-code API with
+S256 PKCE and `REPO_READ`. Cloud uses its OAuth consumer confidential-client
+flow. Smart-card/SSO participation occurs on Bitbucket's browser sign-in.
+SimpleChat/M365 tokens, cookies and SSH keys are never forwarded.
+
+Bearer tokens and Cloud email/API-token pairs reuse existing scoped identities.
+Shared action credentials are resolved through the established secret owner;
+personal token slots use the existing private credential request/continuation
+services. OAuth is not represented as a copied static bearer-token identity.
+
+## APIs and user workflows
+
+`route_backend_bitbucket.py` registers a user-session Blueprint:
+
+| Method and route | Purpose |
+| --- | --- |
+| GET `/bitbucket/connect` | Private connect/reconnect/disconnect page for authorized action users, including non-editors |
+| GET `/api/bitbucket/connection` | Safe actor-local connection status and interaction CSRF token |
+| POST `/api/bitbucket/connect` | Begin provider sign-in with a trusted callback |
+| GET `/api/bitbucket/callback` | Consume bound state and exchange the authorization code server-side |
+| POST `/api/bitbucket/disconnect` | Remove local token usability |
+| POST `/api/bitbucket/discover` | Editor-only repository discovery or permitted-branch discovery |
+
+Mutations require the shared interaction CSRF token. User IDs and ownership are
+derived from the signed-in actor/current action origin, not request bodies.
+Discovery requires personal ownership, current active-group management rights,
+or global admin rights; it cannot expose the shared credential's wider
+repository access to ordinary action users.
+
+Classic uses `_plugin_modal.html`, the shared stepper and the local
+`bitbucket-action-editor.js` module. V2 uses
+`BitbucketActionConfiguration.tsx` with existing field/secret/editor components.
+Both preserve selected repositories when discovery fails.
+
+OAuth's private page uses the local `bitbucket-connection.js` asset. After
+connecting, users retry the chat request. Personal token credentials instead use
+the existing private Save and continue flow. No chat toolbar picker is added.
+
+See the [Bitbucket action reference](../../reference/actions/bitbucket.md) for
+setup steps, authentication choices and usage examples.
+
+## Testing, performance and limitations
+
+Focused coverage is in `functional_tests/test_bitbucket_action_plugin.py`,
+`test_bitbucket_connections.py`, `test_bitbucket_routes.py`, and
+`ui_tests/test_bitbucket_action_configuration.py`. Tests use real Fernet,
+SDK-default Cosmos response doubles and production Classic/V2 components;
+fresh normal/optimized processes verify real application imports without
+network access. Route policy tests cover the registered authentication boundary.
+Error-boundary regressions verify that malformed configuration, including missing
+dictionary keys, returns a safe HTTP 400 response, while unavailable or unauthorized
+actions retain HTTP 404 responses and private-response headers.
+
+Implementation validation passed 30 focused backend cases, 33 route/policy
+cases, 134 dependent action/outbound regressions, and 32 Classic/Bitbucket plus
+27 V2 credential UI cases. The V2 typecheck and production build passed.
+Classic and V2 layouts were checked at 390- and 1440-pixel widths with local
+production styles. Private token tests exercise both supported token identity
+types through real SDK identity storage and rejected-token continuation.
+
+The network-blocked SDK/core selection passed 107 cases; its inventory check
+failed on 18 pre-existing module-fingerprint mismatches belonging only to
+unchanged `route_backend_orchestration.py`. The full
+`check_cosmos_response_boundaries.py --run-contracts` gate stops on that same
+baseline drift. This change reviews its three new OAuth storage owners and
+renews the seven affected identity-owner contracts without approving unrelated
+orchestration entries.
+
+Requests have connect/read timeouts of 10/30 seconds. Directory/branch pages
+contain at most 50 entries; comparison pages at most 10 files. Files are bounded
+to 250,000 bytes, returned line windows to 500, and provider JSON/combined patch
+text to 1,000,000 bytes. Serialized comparison results also stay within that byte
+budget. Comparison inputs are limited to 10,000 lines per file.
+Comparison omissions and further pages remain explicit.
+Exact Data Center branch matching examines at most 10 filtered pages, then
+fails explicitly instead of choosing a similar branch.
+
+Offline fixtures are not a live-provider or smart-card acceptance claim.
+Validate the customer's Data Center version, SSO/proxy configuration and Cloud
+consumer/scopes against authorized test repositories before rollout.
+No Azure lab was deployed. SSH transport, cookie replay, forward proxy
+authentication, repository indexing, pull-request operations, code execution
+and posted review feedback are outside this version.
+
+## Provider references
+
+- [Data Center HTTP access tokens](https://confluence.atlassian.com/bitbucketserver/http-access-tokens-939515499.html)
+- [Incoming application links](https://confluence.atlassian.com/bitbucketserver/configure-an-incoming-link-1108483657.html)
+- [Data Center OAuth provider API](https://confluence.atlassian.com/bitbucketserver/bitbucket-oauth-2-0-provider-api-1108483661.html)
+- [Cloud REST authentication](https://developer.atlassian.com/cloud/bitbucket/rest/intro/)
+- [Cloud commit/diff APIs](https://developer.atlassian.com/cloud/bitbucket/rest/api-group-commits/)
diff --git a/docs/explanation/fixes/BITBUCKET_ERROR_BOUNDARY_FIX.md b/docs/explanation/fixes/BITBUCKET_ERROR_BOUNDARY_FIX.md
new file mode 100644
index 000000000..2d764c33d
--- /dev/null
+++ b/docs/explanation/fixes/BITBUCKET_ERROR_BOUNDARY_FIX.md
@@ -0,0 +1,45 @@
+# Bitbucket error-boundary exception ordering fix
+
+Fixed/Implemented in version: **0.261.451**.
+The application version is recorded in `application/single_app/config.py`.
+Related pull request: [#1949](https://github.com/microsoft/simplechat/pull/1949).
+
+## Issue and root cause
+
+CodeQL reported `py/unreachable-except` in the new Bitbucket route boundary.
+Python's `KeyError` inherits from `LookupError`, so the earlier unavailable-action
+handler intercepted missing configuration keys before their intended invalid
+configuration handler. Those errors returned HTTP 404 instead of HTTP 400.
+
+## Technical details
+
+`application/single_app/route_backend_bitbucket.py` now handles
+`ValueError`, `TypeError` and `KeyError` before the broader `LookupError`
+handler. The earlier `BitbucketError` handler still preserves domain-specific
+status codes and safe messages. Other lookup failures and permission failures
+still return HTTP 404; response privacy headers remain unchanged.
+
+`functional_tests/test_bitbucket_routes.py` exercises six exception types
+through the real Flask connection-status endpoint, checking status codes, safe
+response bodies, `Cache-Control: no-store` and `Referrer-Policy: no-referrer`.
+The new missing-key case failed against the original handler order.
+
+## Validation and separate follow-up
+
+The network-blocked pytest selection passed **62 tests**, covering all three
+Bitbucket backend suites and the Blueprint inventory, unauthenticated policy
+and route-policy coverage suites. This includes the six error-mapping cases.
+
+`python functional_tests\test_docs_app_surface_coverage.py` passed all seven
+checks; `python functional_tests\test_docs_site_quality.py` passed all six.
+`python scripts\check_swagger_routes.py application\single_app\route_backend_bitbucket.py`
+passed for the changed route module. Python compilation and whitespace
+validation also passed.
+
+The original CI Cosmos failure is independent of this fix: the boundary
+inventory reports 18 mismatches only in unchanged
+`application/single_app/route_backend_orchestration.py`. Comparing the
+implementation and its reviewed entries against PR base commit
+`74d3bd035bdefb2f0dd51f361a075badcc3aaa0d` reproduces the same 18 mismatches.
+Those entries require a separate owner review; this PR does not refresh or
+approve unrelated fingerprint drift. A rerun alone will not repair it.
diff --git a/docs/guides/personal-action-credentials.md b/docs/guides/personal-action-credentials.md
index 5b3fdea5c..c71f43f93 100644
--- a/docs/guides/personal-action-credentials.md
+++ b/docs/guides/personal-action-credentials.md
@@ -1,20 +1,25 @@
---
layout: page
title: "Use your own credentials with a shared action"
-description: "Provide a private personal identity when a shared Yamcs action needs your sign-in."
+description: "Provide a private personal identity when a shared Yamcs or Bitbucket action needs your sign-in."
section: "Guides"
audience: user
-version: "0.261.348"
+version: "0.261.450"
---
## What this does
A shared action can describe the server and operations everyone uses while each
person signs in separately. Your administrator does not need to publish a copy
-of the action or agent for you. This first integration supports Yamcs service
+of the action or agent for you. This supports Yamcs service
credentials and the username/password required by a reverse proxy in front of
Yamcs.
+As of **0.261.450**, [Bitbucket actions]({{ '/reference/actions/bitbucket/' | relative_url }})
+also support personal bearer-token identities and Cloud email/API-token
+identities through this card. OAuth uses a separate private Bitbucket
+connection page; connect there, return to chat and retry the request.
+
Fixed/Implemented in version: **0.261.333**, recorded in
`application/single_app/config.py`.
Continuation failure feedback and status recovery were fixed in **0.261.343**.
diff --git a/docs/reference/actions/bitbucket.md b/docs/reference/actions/bitbucket.md
new file mode 100644
index 000000000..46883476c
--- /dev/null
+++ b/docs/reference/actions/bitbucket.md
@@ -0,0 +1,138 @@
+---
+layout: page
+title: "Bitbucket"
+description: "Read approved repository source and compare branches with private Bitbucket connections or token identities."
+section: "Reference"
+audience: user
+version: "0.261.450"
+---
+
+
+
+## What this action does
+
+Supplies repository source and branch changes to an agent for code review.
+It supports self-hosted **Bitbucket Data Center** and **Bitbucket Cloud**.
+It cannot push commits, create pull requests, post comments, approve reviews,
+merge branches, execute repository code, or clone repositories.
+
+Fixed/Implemented in version: **0.261.450**, recorded in
+`application/single_app/config.py`.
+
+## Choose authentication
+
+| Method | Use it when | Credential |
+| --- | --- | --- |
+| Each user's OAuth connection | Users should sign in individually through Bitbucket, potentially using its SSO or smart-card login | A registered Data Center incoming application link or Cloud OAuth consumer; each user connects separately |
+| HTTP access / bearer token | A Data Center HTTP access token or Cloud repository/project/workspace access token authorizes the repository | Bearer-token identity or shared action token |
+| Cloud email and scoped API token | An Atlassian API token is the credential available to the user | Username/password identity with Atlassian email as username and API token as password |
+
+Select **Each user's private identity** for personal token selection in chat.
+Alternatively, bind an identity from the action's own workspace, or enter a
+shared credential. A shared group/global identity is shared by the action's
+users; it is not automatically replaced with the caller's identity.
+
+SimpleChat and Microsoft 365 login tokens are **not forwarded** to Bitbucket.
+The same identity provider does not make their token audiences interchangeable.
+OAuth redirects to Bitbucket's own sign-in; an existing browser SSO session may
+help there. Browser cookies, smart-card private keys, SSH keys and deprecated
+Cloud app passwords are not accepted by this REST action.
+
+## Configure repositories and branches
+
+1. Select the edition and HTTPS server base URL. Include a Data Center context
+ path when configured. Cloud uses `https://api.bitbucket.org`.
+2. Configure authentication and save. An action with no permitted repositories
+ can be saved for setup, but cannot read code.
+3. For OAuth, open **Connect / reconnect my Bitbucket account** and complete
+ Bitbucket sign-in. Return to the editor.
+4. Enter a Data Center project key or Cloud workspace, choose **Find
+ repositories**, and select one or several repositories.
+5. For each repository, choose **Any branch** or **One fixed branch**, configure
+ the branch/default, and save again.
+
+Discovery uses the **saved** connection configuration and requires action
+management rights. Save changed credentials or destinations before discovering.
+For per-user token actions, discover using OAuth or a saved/shared token first,
+then switch to each user's private identity before sharing the action.
+Discovery lists what the current credential can access; a repository-scoped
+token may not have permission to enumerate a project/workspace.
+
+A fixed branch is the only permitted branch, including both inputs to a
+comparison. Any-branch mode accepts an exact branch name; an omitted branch
+uses the configured default, or Bitbucket's own default when none is configured.
+An inaccessible/deleted configured default returns an error rather than silently
+switching branches. Tags, commit hashes and ref expressions are not alternate
+ways around branch policy.
+
+## Use it in chat
+
+Assign the action to an agent or use it through authorized orchestration. Ask,
+for example, "List the repositories available for review", then "Review changes
+from main to feature/login in Repository". Repository choices use the returned
+stable IDs. If several are allowed, the agent must select one explicitly.
+There are no new chat toolbar selectors.
+
+For OAuth, users who do not edit the action can follow the private connection
+link returned by the tool. Connect, return to chat, and retry the request.
+OAuth does not automatically resume paused work. Personal **token** identity
+requests use the existing private **Save and continue** credential card.
+Never paste credentials into chat.
+
+## Results and review limits
+
+Each source read reports its branch and immutable commit. Comparisons report
+the resolved baseline and target commits plus their merge base, and review
+**merge-base-to-target** changes, not baseline-tip-to-target changes.
+Separate calls are not a frozen repository-wide snapshot.
+
+Directory/branch pages contain at most 50 entries; comparison pages contain
+at most 10 files. Follow `next_cursor` when present. Source files are limited
+to 250,000 bytes and 500 returned lines per call, with `next_line` for more
+lines. Provider JSON and combined patch text are bounded to 1,000,000 bytes.
+Binary, oversized and unsupported-text files are reported, not silently
+reviewed. Comparison inputs above 10,000 lines per file are also omitted
+to bound diff work. A truncated page or omitted file is **not a complete review**.
+Repository source is untrusted data, never an instruction to execute commands
+or change permissions.
+
+## Deployment and troubleshooting
+
+OAuth requires these **server-side environment settings**, not browser settings:
+
+| Setting | Purpose |
+| --- | --- |
+| `BITBUCKET_REDIRECT_URI` | Canonical HTTPS callback ending exactly in `/api/bitbucket/callback`; register the same URI with Bitbucket |
+| `BITBUCKET_TOKEN_ENCRYPTION_KEY` | Fernet key supplied from deployment secret storage/Key Vault reference, used to encrypt private access and refresh tokens |
+
+Use a persistent encryption key shared across application workers. Losing or
+changing it requires users to reconnect. Do not put it in action metadata or
+source control. Configure repository-read permission only on the provider's
+application/consumer and token. Data Center uses OAuth authorization-code
+with S256 PKCE; Cloud uses its confidential-client flow without assuming
+Data Center PKCE support.
+
+The SimpleChat execution host must reach the server's private DNS/network.
+"Self-hosted" does not mean `localhost` on the SimpleChat worker. Verified
+HTTPS is required; install the organization's trusted CA through the existing
+[custom CA workflow]({{ '/guides/docker-customization/' | relative_url }}#custom-certificate-authorities).
+Forward proxies, browser-only proxy challenges and copied session cookies
+are not authentication workarounds. REST redirects to login HTML are errors.
+
+The action requires the Data Center REST repository API and, for OAuth, the
+incoming application-link OAuth 2 provider API. Legacy Bitbucket Server
+installations are not assumed to implement that OAuth flow. Actual server,
+Cloud consumer and customer smart-card/SSO acceptance require live deployment
+testing; offline contract tests do not establish that compatibility.
+
+Disconnect removes this user's local token access and fences in-flight work.
+Revoke the application grant in Bitbucket to remove provider-side authorization.
+Changing destination, edition, OAuth client ID or repository/branch policy
+requires a new OAuth connection. A failed/interrupted refresh requires retry
+or reconnect; SimpleChat does not replay a possibly rotated refresh token.
+
+## Related
+
+- [Personal action credentials]({{ '/guides/personal-action-credentials/' | relative_url }})
+- [Actions reference]({{ '/reference/actions/' | relative_url }})
+- [Bitbucket implementation details]({{ '/explanation/features/BITBUCKET_REPOSITORY_ACTION/' | relative_url }})
diff --git a/docs/reference/actions/index.md b/docs/reference/actions/index.md
index 7c06db1bc..87f89cfe5 100644
--- a/docs/reference/actions/index.md
+++ b/docs/reference/actions/index.md
@@ -50,6 +50,7 @@ If an action type does not appear, check Agents settings, workspace action permi
| Action | What it does | Typical use | Depth |
| --- | --- | --- | --- |
+| [Bitbucket](./bitbucket/) | Reads allowlisted Data Center/Cloud source and merge-base branch changes using private OAuth connections or token identities. | Conversational read-only code review without posting comments or changing repositories. | full guide |
| [Azure Maps OpenLayers](./azure-maps-openlayers/) | Creates inline OpenLayers map payloads and proxies Azure Maps raster tiles through SimpleChat. | Use it when an agent needs to turn known locations, areas, or paths into a map inside chat. Do not use it for general GIS editing or broad geocoding. | overview |
| [Yamcs](./yamcs/) | Retrieves read-only Yamcs telemetry, mission database, archive, event, packet, alarm, and link information. | Use it for mission-control visibility. Do not use it for commanding; the plugin source intentionally does not support commands or writes. | overview |
| [MCP](./mcp/) | Connects to a Model Context Protocol server and exposes selected server tools to agents. | Standard tool-server integrations. | full guide |
diff --git a/functional_tests/cosmos_response_boundaries.json b/functional_tests/cosmos_response_boundaries.json
index bf6854adb..17887202c 100644
--- a/functional_tests/cosmos_response_boundaries.json
+++ b/functional_tests/cosmos_response_boundaries.json
@@ -9776,6 +9776,74 @@
],
"evidence_scope": "owner-runtime"
},
+ "application/single_app/functions_bitbucket_connections.py::BitbucketConnections.read": {
+ "boundary": {
+ "sha256": "f9afd2e6f2a7e7e317c24f5803af40b3449b00936671422aabc9fc1c8b0ef851",
+ "points": [
+ {
+ "method": "read_item",
+ "receiver": "self.container",
+ "response": "consumed"
+ }
+ ],
+ "queries": [],
+ "batches": [],
+ "module_sha256": "e2fdd2d30a8d9a52ae571cb32b760f54efe3db2ed8436efdb62eb6401452b48f"
+ },
+ "classification": "normalized-strict",
+ "contract": "Point reads are normalized to a plain top-level dict before ownership checks, encrypted-state inspection and conditional lifecycle transitions; fields and ETags are retained. Only Cosmos not-found means absence.",
+ "tests": [
+ "functional_tests/test_bitbucket_connections.py"
+ ],
+ "evidence_scope": "owner-runtime"
+ },
+ "application/single_app/functions_bitbucket_connections.py::BitbucketConnections.replace": {
+ "boundary": {
+ "sha256": "6784eab92dc780206ab55bed8286e17b06cb538a1f369f7787746dc17dcfe4c2",
+ "points": [
+ {
+ "method": "replace_item",
+ "receiver": "self.container",
+ "response": "consumed"
+ }
+ ],
+ "queries": [],
+ "batches": [],
+ "module_sha256": "e2fdd2d30a8d9a52ae571cb32b760f54efe3db2ed8436efdb62eb6401452b48f"
+ },
+ "classification": "normalized-strict",
+ "contract": "Conditional replace responses are normalized before the next refresh/callback generation/ETag transition. Conflicts remain visible and fence disconnect races; an uncertain rotating refresh is never replayed.",
+ "tests": [
+ "functional_tests/test_bitbucket_connections.py"
+ ],
+ "evidence_scope": "owner-runtime"
+ },
+ "application/single_app/functions_bitbucket_connections.py::BitbucketConnections.start": {
+ "boundary": {
+ "sha256": "648d23512582d464d6b148884b6ace2c9971dbb58a5e6d9ea897c81a0cec8487",
+ "points": [
+ {
+ "method": "create_item",
+ "receiver": "self.container",
+ "response": "unused"
+ },
+ {
+ "method": "create_item",
+ "receiver": "self.container",
+ "response": "unused"
+ }
+ ],
+ "queries": [],
+ "batches": [],
+ "module_sha256": "e2fdd2d30a8d9a52ae571cb32b760f54efe3db2ed8436efdb62eb6401452b48f"
+ },
+ "classification": "response-unused",
+ "contract": "Create response values for the private connection and expiring OAuth flow are discarded. Connection state is reread through the normalized owner before conditional generation changes. State/verifiers are actor/session/policy bound.",
+ "tests": [
+ "functional_tests/test_bitbucket_connections.py"
+ ],
+ "evidence_scope": "owner-runtime"
+ },
"application/single_app/functions_chat_content_review.py::_clear_conversation_projection": {
"boundary": {
"sha256": "4e30e4949334e4e6b84adf43440484dca2d5e3fb79c58b975968170d517cdce0",
@@ -27311,10 +27379,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "normalized-strict",
- "contract": "create_workspace_identity: normalizes returned create/conditional replace SDK documents before credential submission consumes ETags and copies identity state. Lost-response confirmation reads the owned SDK point record before preserving committed Key Vault references; failed writes retain conflict/error behavior and never delete possibly live secrets.",
+ "contract": "create_workspace_identity: normalizes returned create/conditional replace SDK documents before credential submission consumes ETags and copies identity state. Lost-response confirmation reads the owned SDK point record before preserving committed Key Vault references; failed writes retain conflict/error behavior and never delete possibly live secrets. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py"
@@ -27332,10 +27400,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "response-unused",
- "contract": "delete_workspace_identity: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible.",
+ "contract": "delete_workspace_identity: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py"
@@ -27353,10 +27421,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "response-unused",
- "contract": "delete_workspace_identity_conditional: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible.",
+ "contract": "delete_workspace_identity_conditional: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py"
@@ -27374,10 +27442,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "sdk-compatible",
- "contract": "get_workspace_identity: point documents use Mapping field reads/JSON encoding/metadata projections; batch status/body lists are separate, never top-level-normalized as documents. Strict domain sinks remain with their storage owners.",
+ "contract": "get_workspace_identity: point documents use Mapping field reads/JSON encoding/metadata projections; batch status/body lists are separate, never top-level-normalized as documents. Strict domain sinks remain with their storage owners. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py",
@@ -27397,10 +27465,10 @@
}
],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "sdk-compatible",
- "contract": "list_workspace_identities: query rows/pages are plain JSON, not Cosmos point wrappers. Nested domain shape checks therefore need no point-response repair.",
+ "contract": "list_workspace_identities: query rows/pages are plain JSON, not Cosmos point wrappers. Nested domain shape checks therefore need no point-response repair. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py",
@@ -27419,10 +27487,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "response-unused",
- "contract": "update_workspace_identity: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible.",
+ "contract": "update_workspace_identity: point response values are discarded; query rows, if present, are separate plain SDK JSON. Existing write errors remain visible. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py"
@@ -27440,10 +27508,10 @@
],
"queries": [],
"batches": [],
- "module_sha256": "e59833a886b751793747703c811f00fb198e1fa3861ccc6146117f57e033a441"
+ "module_sha256": "2ce402a9b3edab138e788a97dd50ea7bab0731bc8853498f4350b1d91b0da9f2"
},
"classification": "normalized-strict",
- "contract": "update_workspace_identity_conditional: normalizes returned create/conditional replace SDK documents before credential submission consumes ETags and copies identity state. Lost-response confirmation reads the owned SDK point record before preserving committed Key Vault references; failed writes retain conflict/error behavior and never delete possibly live secrets.",
+ "contract": "update_workspace_identity_conditional: normalizes returned create/conditional replace SDK documents before credential submission consumes ETags and copies identity state. Lost-response confirmation reads the owned SDK point record before preserving committed Key Vault references; failed writes retain conflict/error behavior and never delete possibly live secrets. Renewed module review: Bitbucket adds token auth compatibility and rejects hydration with a mismatched method; storage owners are unchanged. Real SDK identity CRUD and both Bitbucket private-token round trips retain ETags, scoped secrets and rejected-token continuation.",
"evidence_scope": "owner-runtime",
"tests": [
"functional_tests/test_action_personal_credentials.py",
diff --git a/functional_tests/route_tests/test_route_blueprint_policy_inventory.py b/functional_tests/route_tests/test_route_blueprint_policy_inventory.py
index 69958b19a..498546d16 100644
--- a/functional_tests/route_tests/test_route_blueprint_policy_inventory.py
+++ b/functional_tests/route_tests/test_route_blueprint_policy_inventory.py
@@ -89,6 +89,7 @@
"backend_models": ("login_required", "user_required"),
"backend_msgraph_pending_actions": ("login_required", "user_required"),
"backend_m365": ("login_required", "user_required"),
+ "backend_bitbucket": ("login_required", "user_required"),
"backend_notifications": ("login_required", "user_required"),
"backend_orchestration": ("login_required", "user_required"),
"backend_prompts": ("login_required", "user_required"),
diff --git a/functional_tests/route_tests/test_route_unauthenticated_policy_contract.py b/functional_tests/route_tests/test_route_unauthenticated_policy_contract.py
index 63c935d11..c86724439 100644
--- a/functional_tests/route_tests/test_route_unauthenticated_policy_contract.py
+++ b/functional_tests/route_tests/test_route_unauthenticated_policy_contract.py
@@ -78,6 +78,7 @@
)
USER_SESSION_PATH_PREFIXES = (
+ "/bitbucket/",
"/conversation/",
"/content-review",
"/feedback/submit",
diff --git a/functional_tests/test_action_credentials_orchestration_continuation.py b/functional_tests/test_action_credentials_orchestration_continuation.py
index 867165d7a..bfb6e8693 100644
--- a/functional_tests/test_action_credentials_orchestration_continuation.py
+++ b/functional_tests/test_action_credentials_orchestration_continuation.py
@@ -1,7 +1,7 @@
# test_action_credentials_orchestration_continuation.py
"""Real orchestration leases/checkpoints and independent credential waits.
-Version: 0.261.343
+Version: 0.261.450
Implemented in: 0.261.333
Worker authorization and durable outcome regressions added in: 0.261.343
@@ -40,6 +40,9 @@ def configure_real_credentials(harness, monkeypatch, raw):
lambda: deepcopy(harness.settings))
monkeypatch.setattr(credentials, "_services", credentials._services)
monkeypatch.setattr(continuation, "_services", continuation._services)
+ monkeypatch.setattr(harness.config, "cosmos_bitbucket_connections_container", CredentialContainer("user_id"), raising=False)
+ bitbucket = importlib.import_module("functions_bitbucket_connections")
+ monkeypatch.setattr(bitbucket, "_service", bitbucket._service)
runtime.configure_action_credential_runtime()
identity = {"id": "fixture-identity", "_etag": "identity-etag", "name": "Mission",
"auth": {"auth_type": "api_key"}, "usage_contexts": ["action"],
diff --git a/functional_tests/test_action_personal_credentials.py b/functional_tests/test_action_personal_credentials.py
index aa0f2cf66..cdcdf6337 100644
--- a/functional_tests/test_action_personal_credentials.py
+++ b/functional_tests/test_action_personal_credentials.py
@@ -1,7 +1,7 @@
# test_action_personal_credentials.py
"""Backend functional tests for actor-bound personal action credentials.
-Version: 0.261.348
+Version: 0.261.450
Implemented in: 0.261.333
Exercises real storage owners, identity CRUD, resolver, schema and Flask routes
@@ -107,6 +107,7 @@ def discard(names, *args, **kwargs):
})
config.cosmos_collaboration_conversations_container = CredentialContainer("id")
config.cosmos_collaboration_messages_container = CredentialContainer("conversation_id")
+ config.cosmos_bitbucket_connections_container = CredentialContainer("user_id")
monkeypatch.setitem(sys.modules, "config", config)
monkeypatch.setitem(sys.modules, "functions_keyvault", module(
"functions_keyvault", SecretReturnType=SimpleNamespace(VALUE="value", TRIGGER="trigger", NAME="name"),
@@ -161,9 +162,18 @@ def resolve(user_id, reference, **kwargs):
"route_backend_chats", _authorize_personal_conversation_access=authorize,
cosmos_conversations_container=CredentialContainer("id"),
))
+ def unexpected_input(*args, **kwargs):
+ raise AssertionError("User-input validation is outside this credential-owner fixture.")
+
+ monkeypatch.setitem(sys.modules, "functions_orchestration_context", module(
+ "functions_orchestration_context", normalize_elicitation_answer=unexpected_input,
+ ElicitationContextError=ValueError,
+ ))
continuation = importlib.import_module("functions_action_credential_continuation")
monkeypatch.setattr(credentials, "_services", None)
monkeypatch.setattr(continuation, "_services", None)
+ bitbucket = importlib.import_module("functions_bitbucket_connections")
+ monkeypatch.setattr(bitbucket, "_service", None)
importlib.import_module("functions_action_credential_runtime").configure_action_credential_runtime()
monkeypatch.setattr(credentials, "_services", replace(
credentials.credential_services(), authorize_request_context=None,
@@ -234,6 +244,49 @@ def test_sdk_owner_conditional_request_binding_and_safe_resolution(environment):
env.state.claim_request("alice", env.state.read("alice", dto["id"]), ready["etag"])
+@pytest.mark.parametrize("method", ["bearer_token", "username_password"])
+def test_bitbucket_private_identity_roundtrip_and_rejected_token_reprompts(environment, monkeypatch, method):
+ env = environment
+ env.current.update(
+ type="bitbucket", endpoint="https://api.bitbucket.org",
+ auth={"type": "key" if method == "bearer_token" else "username_password", "identity": "", "key": ""},
+ additionalFields={"edition": "cloud", "auth_method": method, "repositories": [
+ {"id": "{repo}", "project": "team", "slug": "repo", "name": "Repository",
+ "branch_mode": "any", "default_branch": "main"},
+ ]},
+ credential_requirements={"version": 1, "slots": {"service": {"source": "personal", "auth_type": method}}},
+ )
+ dto = challenge(env)
+ assert dto["requirements"][0]["label"] == "Bitbucket sign-in"
+ secret = {"auth_type": method, "secret": "PRIVATE_BITBUCKET_TOKEN"} if method == "bearer_token" else {
+ "auth_type": method, "username": "email@example.test", "password": "PRIVATE_BITBUCKET_TOKEN",
+ }
+ ready = submit(env, dto, [{"slot": "service", "name": "Private Bitbucket", "credentials": secret}])
+ assert ready["status"] == "ready"
+ resolved = env.credentials.resolve_personal_credentials(env.current)
+ assert resolved["auth"]["key"] == "PRIVATE_BITBUCKET_TOKEN"
+ assert env.current["auth"]["key"] == ""
+ plugin_module = importlib.import_module("semantic_kernel_plugins.bitbucket_plugin")
+ connections = importlib.import_module("functions_bitbucket_connections")
+ operations = importlib.import_module("functions_bitbucket_operations")
+ monkeypatch.setattr(plugin_module, "actor_context", env.credentials.actor_context)
+ monkeypatch.setattr(plugin_module, "authorized_manifest", lambda *args: env.current)
+ monkeypatch.setattr(connections._service, "authorize", lambda *args: env.current)
+
+ class Rejected:
+ def __init__(self, manifest, auth):
+ assert auth["secret"] == "PRIVATE_BITBUCKET_TOKEN"
+
+ def repositories(self):
+ raise operations.BitbucketError("reconnect_required", "Rejected", 401)
+
+ monkeypatch.setattr(plugin_module, "BitbucketClient", Rejected)
+ plugin = plugin_module.BitbucketPlugin(env.current)
+ with env.credentials.credential_continuation(env.descriptor), pytest.raises(env.contracts.ActionCredentialsRequired):
+ plugin.list_repositories()
+ assert "PRIVATE_BITBUCKET_TOKEN" not in repr(env.store.items)
+
+
@pytest.mark.parametrize("scope", ["global", "group", "personal"])
def test_actor_is_private_and_destination_contract_changes_invalidate(environment, scope):
env = environment
diff --git a/functional_tests/test_bitbucket_action_plugin.py b/functional_tests/test_bitbucket_action_plugin.py
new file mode 100644
index 000000000..759de1d24
--- /dev/null
+++ b/functional_tests/test_bitbucket_action_plugin.py
@@ -0,0 +1,288 @@
+# test_bitbucket_action_plugin.py
+"""
+Functional tests for read-only Bitbucket repository review.
+Version: 0.261.450
+Implemented in: 0.261.450
+
+Validates provider wire contracts, branch/allowlist enforcement, immutable
+source attribution, bounded output, comparison direction, and bootstrap safety.
+"""
+
+import copy
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[1]
+APP = ROOT / "application" / "single_app"
+sys.path.insert(0, str(APP))
+
+from functions_bitbucket_operations import BitbucketClient, BitbucketError, bounded_response, normalize_bitbucket_manifest, policy_fingerprint
+
+
+BASE = "a" * 40
+TARGET = "b" * 40
+MERGE = "c" * 40
+
+
+def manifest(cloud=False, method="bearer_token"):
+ return {
+ "id": "review", "name": "review", "type": "bitbucket",
+ "endpoint": "https://api.bitbucket.org" if cloud else "https://bitbucket.example.test/context",
+ "auth": {"type": "key", "identity": "", "key": "private-token"},
+ "additionalFields": {
+ "edition": "cloud" if cloud else "data_center", "auth_method": method,
+ "repositories": [{"id": "{repo-uuid}" if cloud else "1", "project": "team", "slug": "repo",
+ "name": "Repository", "branch_mode": "any", "default_branch": "main"}],
+ },
+ }
+
+
+class Response:
+ def __init__(self, value, status=200):
+ self.content = value if isinstance(value, bytes) else json.dumps(value).encode()
+ self.status_code = status
+ self.closed = False
+
+ def iter_content(self, chunk_size):
+ for offset in range(0, len(self.content), chunk_size):
+ yield self.content[offset:offset + chunk_size]
+
+ def close(self):
+ self.closed = True
+
+
+class Transport:
+ def __init__(self, responses):
+ self.responses = list(responses)
+ self.calls = []
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def get(self, url, **kwargs):
+ self.calls.append((url, kwargs))
+ value = self.responses.pop(0)
+ return value if isinstance(value, Response) else Response(value)
+
+
+def client(responses, cloud=False):
+ transport = Transport(responses)
+ instance = BitbucketClient(manifest(cloud), {"method": "bearer_token", "secret": "private-token"},
+ session_factory=lambda: transport)
+ return instance, transport
+
+
+def test_allowlist_fixed_branches_and_input_rejections_before_source_reads():
+ instance, transport = client([{"id": 1}, {
+ "values": [{"id": "refs/heads/main", "latestCommit": BASE}], "isLastPage": True,
+ }])
+ with pytest.raises(BitbucketError, match="permitted repository"):
+ instance.read_file("unlisted", path="secret.py")
+ assert not transport.calls
+ instance.fields["repositories"][0].update(branch_mode="fixed")
+ with pytest.raises(BitbucketError) as error:
+ instance.compare("", "main", "feature")
+ assert error.value.code == "branch_denied"
+ assert not any("/raw/" in url for url, _ in transport.calls)
+ for branch in ("main~1", "main..other", "refs/tags/main", "main\n", "../other"):
+ candidate = manifest()
+ candidate["additionalFields"]["repositories"][0]["default_branch"] = branch
+ with pytest.raises(BitbucketError):
+ normalize_bitbucket_manifest(candidate)
+
+
+@pytest.mark.parametrize("cloud", [False, True])
+def test_read_file_pins_commit_and_bounds_lines(cloud):
+ repo = {"uuid": "{repo-uuid}"} if cloud else {"id": 1}
+ branch = {"target": {"hash": TARGET}} if cloud else {
+ "values": [{"id": "refs/heads/main", "latestCommit": TARGET}], "isLastPage": True,
+ }
+ instance, transport = client([repo, branch, b"one\ntwo\nthree\n"], cloud)
+ result = instance.read_file("", "", "src/review.py", 2, 1)
+ assert result["content"] == "two"
+ assert result["commit"] == TARGET
+ assert result["start_line"] == result["end_line"] == 2
+ assert result["truncated"] and result["next_line"] == 3
+ source_url, options = transport.calls[-1]
+ assert TARGET in source_url if cloud else options["params"]["at"] == TARGET
+ assert all(call["allow_redirects"] is False and call["stream"] for _, call in transport.calls)
+ assert all(call["headers"]["Authorization"] == "Bearer private-token" for _, call in transport.calls)
+
+
+def test_data_center_exact_branch_lookup_continues_pages_and_never_falls_back():
+ instance, transport = client([
+ {"values": [{"id": "refs/heads/main-long", "latestCommit": TARGET}], "isLastPage": False, "nextPageStart": 1},
+ {"values": [{"id": "refs/heads/main", "latestCommit": BASE}], "isLastPage": True},
+ ])
+ name, commit = instance.resolve(instance.fields["repositories"][0])
+ assert (name, commit) == ("main", BASE)
+ assert transport.calls[-1][1]["params"]["start"] == 1
+ instance, transport = client([{"values": [], "isLastPage": True}])
+ with pytest.raises(BitbucketError) as error:
+ instance.resolve(instance.fields["repositories"][0])
+ assert error.value.code == "branch_not_found"
+ assert len(transport.calls) == 1
+
+
+@pytest.mark.parametrize("cloud", [False, True])
+def test_comparison_merge_base_direction_add_delete_and_rename(cloud):
+ repo = {"uuid": "{repo-uuid}"} if cloud else {"id": 1}
+ branches = ([{"target": {"hash": value}} for value in (BASE, TARGET)] if cloud else [
+ {"values": [{"id": f"refs/heads/{name}", "latestCommit": value}], "isLastPage": True}
+ for name, value in (("main", BASE), ("feature", TARGET))
+ ])
+ changes = [
+ {"old": None, "new": {"path": "added.py"}},
+ {"old": {"path": "deleted.py"}, "new": None},
+ {"old": {"path": "old.py"}, "new": {"path": "renamed.py"}},
+ ] if cloud else [
+ {"type": "ADD", "path": {"toString": "added.py"}},
+ {"type": "DELETE", "path": {"toString": "deleted.py"}},
+ {"type": "MOVE", "srcPath": {"toString": "old.py"}, "path": {"toString": "renamed.py"}},
+ ]
+ page = {"values": changes, **({} if cloud else {"isLastPage": True})}
+ instance, transport = client([repo, *branches, {"hash" if cloud else "id": MERGE},
+ page, b"added\n", b"deleted\n", b"old\n", b"new\n"], cloud)
+ result = instance.compare("", "main", "feature")
+ assert result["comparison_mode"] == "merge_base_to_target"
+ assert result["merge_base"] == MERGE and not result["truncated"]
+ assert "+added" in result["files"][0]["patch"]
+ assert "-deleted" in result["files"][1]["patch"]
+ assert "-old" in result["files"][2]["patch"] and "+new" in result["files"][2]["patch"]
+ url, options = transport.calls[4]
+ if cloud:
+ assert url.endswith(f"/diffstat/{TARGET}..{MERGE}")
+ assert options["params"]["topic"] == "false"
+ else:
+ assert options["params"]["since"] == MERGE and options["params"]["until"] == TARGET
+
+
+@pytest.mark.parametrize("response,code", [
+ (Response(b"binary\x00"), "binary_file"), (Response(b"\xff"), "response_invalid"),
+ (Response([]), "response_invalid"), (Response({"error": "secret"}, 302), "provider_failed"),
+ (Response(b"x" * 21), "result_too_large"),
+])
+def test_bounded_provider_failures_are_safe_and_responses_closed(response, code):
+ with pytest.raises(BitbucketError) as error:
+ bounded_response(response, as_json=code not in {"binary_file", "result_too_large"}, limit=20)
+ assert error.value.code == code
+ assert "secret" not in str(error.value)
+ assert response.closed
+
+
+def test_cloud_basic_token_auth_and_no_credentials_or_missing_repo_fails_closed():
+ transport = Transport([{"values": [], "next": "https://api.bitbucket.org/2.0/repositories/team?page=opaque-token&pagelen=50"}])
+ instance = BitbucketClient(manifest(True, "username_password"), {
+ "method": "username_password", "username": "email@example.test", "secret": "api-token",
+ }, session_factory=lambda: transport)
+ result = instance.discover("team")
+ assert result["next_cursor"] == "opaque-token"
+ assert len(transport.calls) == 1
+ assert transport.calls[0][1]["auth"] == ("email@example.test", "api-token")
+ assert "Authorization" not in transport.calls[0][1]["headers"]
+ instance.auth = {}
+ with pytest.raises(BitbucketError) as error:
+ instance.get("/test")
+ assert error.value.code == "credentials_required"
+ staged = manifest()
+ staged["additionalFields"]["repositories"] = []
+ saved = normalize_bitbucket_manifest(staged, allow_empty=True)
+ with pytest.raises(BitbucketError):
+ normalize_bitbucket_manifest(saved)
+
+
+def test_token_identity_hydration_does_not_change_policy_fingerprint():
+ record = manifest(True, "username_password")
+ record["identity_id"] = "saved-id"
+ record["auth"] = {"type": "identity", "identity": "saved-id"}
+ hydrated = copy.deepcopy(record)
+ hydrated["auth"] = {"type": "username_password", "identity": "email@example.test", "key": "private"}
+ assert policy_fingerprint(record) == policy_fingerprint(hydrated)
+
+
+@pytest.mark.parametrize("next_url", [
+ "https://untrusted.invalid/2.0/repositories/team?page=2",
+ "https://api.bitbucket.org/2.0/repositories/other?page=2",
+ "https://api.bitbucket.org/2.0/repositories/team?page=1",
+ "https://api.bitbucket.org/2.0/repositories/team?page=2&pagelen=1000",
+])
+def test_pagination_never_changes_destination_operation_or_budget(next_url):
+ instance, transport = client([{"values": [], "next": next_url}], cloud=True)
+ with pytest.raises(BitbucketError) as error:
+ instance.discover("team")
+ assert error.value.code == "response_invalid"
+ assert len(transport.calls) == 1
+
+
+def test_comparison_serialized_budget_and_continuation_are_truthful():
+ instance, _transport = client([], cloud=True)
+ instance.repository = lambda repository: instance.fields["repositories"][0]
+ instance.resolve = lambda repo, branch: (branch, BASE if branch == "main" else TARGET)
+ instance.get = lambda *args, **kwargs: {"hash": MERGE}
+ instance.page = lambda *args, **kwargs: ([
+ {"old": None, "new": {"path": "one.py"}}, {"old": None, "new": {"path": "two.py"}},
+ ], "opaque-next")
+ instance.source = lambda *args, **kwargs: "\u00e9" * 100000
+ result = instance.compare("", "main", "feature")
+ assert len(json.dumps(result).encode()) <= 1000000
+ assert result["truncated"] and result["next_cursor"] == "opaque-next"
+ assert any(file.get("omitted") == "comparison_byte_limit" for file in result["files"])
+ reviewed = next(file for file in result["files"] if "patch" in file)
+ assert "\\ No newline at end of file\n" in reviewed["patch"]
+
+
+@pytest.mark.parametrize("optimized", [False, True])
+def test_bitbucket_modules_and_real_web_bootstrap_import_network_free(optimized):
+ probe = """
+import importlib
+from test_support.offline_bootstrap import offline_app_imports
+with offline_app_imports() as environment:
+ import functions_bitbucket_operations
+ import functions_bitbucket_connections
+ from semantic_kernel_plugins.bitbucket_plugin import BitbucketPlugin
+ import app
+ import functions_orchestration_bootstrap
+ from semantic_kernel_plugins.plugin_loader import discover_plugins
+ discovered = discover_plugins()
+ if discovered.get("BitbucketPlugin") is not BitbucketPlugin:
+ raise AssertionError("Canonical Bitbucket discovery failed")
+ from test_bitbucket_action_plugin import manifest
+ from functions_action_manifest import bind_action_origin
+ from semantic_kernel import Kernel
+ from semantic_kernel_plugins.plugin_health_checker import PluginHealthChecker
+ from semantic_kernel_plugins.logged_plugin_loader import LoggedPluginLoader
+ from semantic_kernel_loader import load_plugins_for_kernel
+ candidate = bind_action_origin({**manifest(), "description": "Review repository source."}, "personal", "actor")
+ valid, errors = PluginHealthChecker.validate_plugin_manifest(candidate, "bitbucket")
+ if not valid:
+ raise AssertionError(errors)
+ kernel = Kernel()
+ loaded = LoggedPluginLoader(kernel).load_plugin_from_manifest(candidate, "actor")
+ if not loaded or set(kernel.plugins["review"].functions) != {
+ "list_repositories", "list_branches", "list_tree", "read_file", "compare_branches",
+ }:
+ raise AssertionError("Logged loader did not register the read-only tool contract")
+ kernel = Kernel()
+ settings = {key: False for key in (
+ "enable_time_plugin", "enable_http_plugin", "enable_wait_plugin", "enable_math_plugin",
+ "enable_text_plugin", "enable_default_embedding_model_plugin",
+ )}
+ load_plugins_for_kernel(kernel, [candidate], settings)
+ if "review" not in kernel.plugins or "compare_branches" not in kernel.plugins["review"].functions:
+ raise AssertionError("Runtime kernel loader did not register Bitbucket")
+ if environment.network_attempts:
+ raise AssertionError("Unexpected startup network request")
+"""
+ environment = {**os.environ, "PYTHONPATH": os.pathsep.join((str(APP), str(ROOT / "functional_tests")))}
+ command = [sys.executable, *(["-O"] if optimized else []), "-c", probe]
+ result = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True, timeout=180)
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/functional_tests/test_bitbucket_connections.py b/functional_tests/test_bitbucket_connections.py
new file mode 100644
index 000000000..5771d20f7
--- /dev/null
+++ b/functional_tests/test_bitbucket_connections.py
@@ -0,0 +1,250 @@
+# test_bitbucket_connections.py
+"""
+Functional tests for private Bitbucket OAuth storage.
+Version: 0.261.450
+Implemented in: 0.261.450
+
+Real Fernet encryption and SDK-shaped conditional Cosmos responses validate
+single-use, session-bound state, refresh serialization, and disconnect fencing.
+"""
+
+import copy
+from pathlib import Path
+import sys
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from azure.cosmos.exceptions import CosmosHttpResponseError
+from cryptography.fernet import Fernet
+
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "application" / "single_app"))
+
+from functions_bitbucket_connections import BitbucketConnections
+from functions_bitbucket_operations import BitbucketError
+from test_bitbucket_action_plugin import manifest, Response
+from test_support.m365 import CosmosContainer
+
+
+@pytest.fixture
+def service():
+ record = manifest()
+ record["auth"] = {"type": "user", "identity": "client-id", "key": "client-secret"}
+ record["additionalFields"]["auth_method"] = "oauth"
+ key = Fernet(Fernet.generate_key())
+ instance = BitbucketConnections(CosmosContainer("user_id"), lambda user, ref: copy.deepcopy(record),
+ key_provider=lambda: key, clock=lambda: 1000)
+ return instance
+
+
+def start(service, user="actor", session="browser", ref="personal:actor:review"):
+ result = service.start(user, ref, session, "https://simplechat.example.test/api/bitbucket/callback")
+ return parse_qs(urlsplit(result["authorization_url"]).query)
+
+
+def tokens(access="access-private", refresh="refresh-private"):
+ return {"access_token": access, "refresh_token": refresh, "expires_in": 3600}
+
+
+def connect(service):
+ query = start(service)
+ service.exchange = lambda manifest, data: tokens()
+ service.complete("actor", query["state"][0], "code-private", "browser")
+
+
+def test_oauth_sdk_owner_state_encryption_replay_and_session_binding(service):
+ query = start(service)
+ assert query["code_challenge_method"] == ["S256"] and "code_verifier" not in query
+ state = query["state"][0]
+ with pytest.raises(BitbucketError) as error:
+ service.complete("actor", state, "code", "wrong-browser")
+ assert error.value.code == "state_invalid"
+ with pytest.raises(BitbucketError):
+ service.complete("other-user", state, "code", "browser")
+ calls = []
+
+ def exchange(manifest, data):
+ calls.append(data)
+ return tokens()
+
+ service.exchange = exchange
+ service.complete("actor", state, "code-private", "browser")
+ assert len(calls) == 1 and calls[0]["code_verifier"]
+ status = service.status("actor", "personal:actor:review")
+ saved = service.read("actor", status["connection_id"])
+ assert type(saved) is dict and saved["_etag"]
+ assert status["connected"]
+ serialized = repr(service.container.items)
+ assert "access-private" not in serialized and "refresh-private" not in serialized and "code-private" not in serialized
+ token = service.token("actor", "personal:actor:review")
+ assert token == "access-private"
+ with pytest.raises(BitbucketError):
+ service.complete("actor", state, "code-private", "browser")
+ service.disconnect("actor", "personal:actor:review")
+ status = service.status("actor", "personal:actor:review")
+ assert not status["connected"]
+ with pytest.raises(BitbucketError):
+ service.token("actor", "personal:actor:review")
+
+
+def test_expired_state_changed_policy_and_newer_connect_fence_old_flows(service):
+ query = start(service)
+ service.clock = lambda: 1601
+ with pytest.raises(BitbucketError):
+ service.complete("actor", query["state"][0], "code", "browser")
+ service.clock = lambda: 1000
+ query = start(service)
+ newer = start(service)
+ with pytest.raises(BitbucketError) as error:
+ service.complete("actor", query["state"][0], "code", "browser")
+ assert error.value.code == "connection_changed"
+ service.exchange = lambda manifest, data: tokens()
+ service.complete("actor", newer["state"][0], "code", "browser")
+ original = service.authorize
+
+ def changed(user, ref):
+ record = original(user, ref)
+ record["additionalFields"]["repositories"][0]["default_branch"] = "other"
+ return record
+
+ service.authorize = changed
+ with pytest.raises(BitbucketError) as error:
+ service.token("actor", "personal:actor:review")
+ assert error.value.code == "reconnect_required"
+
+
+def test_refresh_rotates_once_and_disconnect_wins_inflight_response(service):
+ connect(service)
+ service.clock = lambda: 5000
+ calls = []
+
+ def refresh(manifest, data):
+ calls.append(data)
+ with pytest.raises(BitbucketError) as error:
+ service.token("actor", "personal:actor:review")
+ assert error.value.code == "refresh_in_progress"
+ return tokens("rotated-private", "rotated-refresh")
+
+ service.exchange = refresh
+ value = service.token("actor", "personal:actor:review")
+ assert value == "rotated-private" and len(calls) == 1
+ value = service.token("actor", "personal:actor:review")
+ assert value == "rotated-private" and len(calls) == 1
+ service.clock = lambda: 9000
+
+ def disconnect(manifest, data):
+ service.disconnect("actor", "personal:actor:review")
+ return tokens("must-not-resurrect", "new-refresh")
+
+ service.exchange = disconnect
+ with pytest.raises(CosmosHttpResponseError):
+ service.token("actor", "personal:actor:review")
+ status = service.status("actor", "personal:actor:review")
+ assert not status["connected"]
+
+
+def test_failed_uncertain_refresh_is_not_replayed(service):
+ connect(service)
+ service.clock = lambda: 5000
+ calls = []
+
+ def failed(manifest, data):
+ calls.append(data)
+ raise BitbucketError("connection_failed", "Unavailable", 502)
+
+ service.exchange = failed
+ for _ in range(2):
+ with pytest.raises(BitbucketError):
+ service.token("actor", "personal:actor:review")
+ assert len(calls) == 1
+
+
+def test_disconnect_after_policy_edit_cannot_resurrect_old_connection(service):
+ connect(service)
+ original = service.authorize
+
+ def changed(user, reference):
+ record = original(user, reference)
+ record["additionalFields"]["repositories"][0]["default_branch"] = "other"
+ return record
+
+ service.authorize = changed
+ status = service.status("actor", "personal:actor:review")
+ assert not status["connected"]
+ service.disconnect("actor", "personal:actor:review")
+ service.authorize = original
+ with pytest.raises(BitbucketError) as error:
+ service.token("actor", "personal:actor:review")
+ assert error.value.code == "reconnect_required"
+
+
+def test_cloud_callback_does_not_send_data_center_pkce_fields(service):
+ original = service.authorize
+
+ def cloud(user, reference):
+ record = original(user, reference)
+ record["endpoint"] = "https://api.bitbucket.org"
+ record["additionalFields"]["edition"] = "cloud"
+ return record
+
+ service.authorize = cloud
+ query = start(service)
+ assert "code_challenge" not in query
+ calls = []
+
+ def exchange(manifest, data):
+ calls.append(data)
+ return tokens()
+
+ service.exchange = exchange
+ service.complete("actor", query["state"][0], "code-private", "browser")
+ assert "code_verifier" not in calls[0]
+
+
+def test_callback_disconnect_and_cipher_binding_prevent_resurrection(service):
+ query = start(service)
+
+ def disconnect(manifest, data):
+ service.disconnect("actor", "personal:actor:review")
+ return tokens()
+
+ service.exchange = disconnect
+ with pytest.raises(CosmosHttpResponseError):
+ service.complete("actor", query["state"][0], "code", "browser")
+ cipher = service.seal(tokens(), ["actor", "connection"])
+ with pytest.raises(BitbucketError):
+ service.open(cipher, ["other", "connection"])
+
+
+@pytest.mark.parametrize("cloud", [False, True])
+def test_token_exchange_wire_auth_and_redirects(service, cloud):
+ record = service.authorize("actor", "ref")
+ if cloud:
+ record["endpoint"] = "https://api.bitbucket.org"
+ record["additionalFields"]["edition"] = "cloud"
+ response = Response({**tokens(), "token_type": "bearer"})
+ calls = []
+
+ class Http:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def post(self, url, **options):
+ calls.append((url, options))
+ return response
+
+ service.session_factory = Http
+ result = service.exchange(record, {"grant_type": "refresh_token", "refresh_token": "private-refresh"})
+ assert result == tokens() and response.closed
+ url, options = calls[0]
+ assert options["allow_redirects"] is False
+ if cloud:
+ assert url == "https://bitbucket.org/site/oauth2/access_token"
+ assert options["auth"] == ("client-id", "client-secret")
+ assert "client_secret" not in options["data"]
+ else:
+ assert url.endswith("/context/rest/oauth2/latest/token")
+ assert options["data"]["client_secret"] == "client-secret"
diff --git a/functional_tests/test_bitbucket_routes.py b/functional_tests/test_bitbucket_routes.py
new file mode 100644
index 000000000..162a395c0
--- /dev/null
+++ b/functional_tests/test_bitbucket_routes.py
@@ -0,0 +1,157 @@
+# test_bitbucket_routes.py
+"""
+Functional tests for Bitbucket routes, identity hydration and authoring policy.
+Version: 0.261.451
+Implemented in: 0.261.450
+Error-boundary regression implemented in: 0.261.451
+
+Real modules run in a fresh offline bootstrap with scoped external/actor seams.
+Exercises canonical callback configuration, CSRF, private status and edit-only discovery.
+"""
+
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+ROOT = Path(__file__).resolve().parents[1]
+APP = ROOT / "application" / "single_app"
+
+
+def test_real_bitbucket_route_identity_and_plugin_integration():
+ probe = r"""
+import copy
+import importlib
+from urllib.parse import parse_qs, urlsplit
+from unittest.mock import Mock, patch
+from flask import Blueprint, Flask
+from cryptography.fernet import Fernet
+from test_support.offline_bootstrap import offline_app_imports
+from test_support.m365 import CosmosContainer
+from test_bitbucket_action_plugin import manifest
+with offline_app_imports():
+ routes = importlib.import_module("route_backend_bitbucket")
+ connections = importlib.import_module("functions_bitbucket_connections")
+ identities = importlib.import_module("functions_workspace_identities")
+ plugin_module = importlib.import_module("semantic_kernel_plugins.bitbucket_plugin")
+ governance = importlib.import_module("functions_governance")
+ from azure.cosmos._cosmos_responses import CosmosDict
+ from functions_action_manifest import bind_action_origin
+ with patch.object(governance, "cosmos_governance_policies_container", CosmosContainer("id")), \
+ patch.object(governance, "cosmos_governance_item_policies_container", CosmosContainer("id")), \
+ patch.object(governance, "get_settings", return_value={"governance_user_actions": True}), \
+ patch.object(governance, "get_user_governance_group_ids", return_value=set()), \
+ patch.object(governance, "log_governance_change"):
+ feature = governance.upsert_feature_policy("governance_user_actions", {"allow_all": True}, "admin", "")
+ policy = governance.upsert_item_policy("personal_action_type", "bitbucket", {
+ "allow_all": False, "allowed_users": ["actor"], "denied_users": ["other"],
+ }, "admin", "")
+ assert isinstance(feature, CosmosDict) and isinstance(policy, CosmosDict)
+ governance.ensure_action_type_access("governance_user_actions", "actor", "bitbucket", "personal")
+ try:
+ governance.ensure_action_type_access("governance_user_actions", "other", "bitbucket", "personal")
+ except PermissionError:
+ pass
+ else:
+ raise AssertionError("Bitbucket type policy did not enforce the saved SDK policy")
+ assert governance.get_governed_action_type_label("bitbucket") == "Bitbucket"
+ governance.invalidate_governance_cache()
+ record = manifest()
+ record["auth"] = {"type": "user", "identity": "oauth-client", "key": "private-client-secret"}
+ record["additionalFields"]["auth_method"] = "oauth"
+ def authorize(user, reference):
+ scope, scope_id, action_id = reference.split(":", 2)
+ if scope == "personal" and scope_id != user:
+ raise PermissionError("Not your action")
+ return bind_action_origin(copy.deepcopy(record), scope, scope_id)
+ service = connections.BitbucketConnections(
+ CosmosContainer("user_id"), authorize, key_provider=lambda: Fernet(b"zFCFYhfl8RR--EK2uJWvX8Khq6m-uTfhEOzMBc3_bN4="),
+ )
+ app = Flask(__name__, template_folder=str(__import__("pathlib").Path(routes.__file__).parent / "templates"))
+ app.secret_key = "offline-bitbucket-test"
+ with patch.object(routes, "login_required", lambda function: function), \
+ patch.object(routes, "user_required", lambda function: function), \
+ patch.object(routes, "get_current_user_id", lambda: "actor"), \
+ patch.object(routes, "get_current_user_info", lambda: {"roles": []}), \
+ patch.object(connections, "_service", service):
+ bp = Blueprint("backend_bitbucket", __name__)
+ routes.register_route_backend_bitbucket(bp)
+ app.register_blueprint(bp)
+ client = app.test_client()
+ status = client.get("/api/bitbucket/connection?action_ref=personal:self:review")
+ assert status.status_code == 200 and not status.json["connected"]
+ assert status.headers["Cache-Control"] == "no-store"
+ csrf = status.json["csrf_token"]
+ for error_type, expected_status, expected_message in (
+ (KeyError, 400, "Invalid Bitbucket configuration or request."),
+ (ValueError, 400, "Invalid Bitbucket configuration or request."),
+ (TypeError, 400, "Invalid Bitbucket configuration or request."),
+ (LookupError, 404, "The Bitbucket action is unavailable."),
+ (IndexError, 404, "The Bitbucket action is unavailable."),
+ (PermissionError, 404, "The Bitbucket action is unavailable."),
+ ):
+ with patch.object(service, "status", side_effect=error_type("private-error-detail")):
+ failed = client.get("/api/bitbucket/connection?action_ref=personal:self:review")
+ assert failed.status_code == expected_status, (error_type.__name__, failed.json)
+ assert failed.json == {"error": expected_message}
+ assert failed.headers["Cache-Control"] == "no-store"
+ assert failed.headers["Referrer-Policy"] == "no-referrer"
+ assert client.get("/api/bitbucket/connection?action_ref=personal:other:review").status_code == 404
+ assert client.post("/api/bitbucket/connect", json={"action_ref": "personal:self:review"}).status_code == 403
+ headers = {"X-CSRFToken": csrf}
+ assert client.post("/api/bitbucket/disconnect", headers={**headers, "Sec-Fetch-Site": "cross-site"},
+ json={"action_ref": "personal:self:review"}).status_code == 403
+ with patch.dict("os.environ", {"BITBUCKET_REDIRECT_URI": ""}):
+ assert client.post("/api/bitbucket/connect", headers=headers, json={"action_ref": "personal:self:review"}).status_code == 503
+ with patch.dict("os.environ", {"BITBUCKET_REDIRECT_URI": "https://simplechat.example.test/api/bitbucket/callback"}):
+ result = client.post("/api/bitbucket/connect", headers={**headers, "X-Forwarded-Host": "attacker.invalid"},
+ json={"action_ref": "personal:self:review"})
+ assert result.status_code == 200, result.json
+ query = parse_qs(urlsplit(result.json["authorization_url"]).query)
+ assert query["redirect_uri"] == ["https://simplechat.example.test/api/bitbucket/callback"]
+ with client.session_transaction() as browser:
+ binding = browser["bitbucket_session_binding"]
+ with patch.object(service, "exchange", return_value={"access_token": "private-access", "refresh_token": "private-refresh", "expires_in": 3600}):
+ callback = client.get("/api/bitbucket/callback", query_string={"state": query["state"][0], "code": "private-code"})
+ assert callback.status_code == 200
+ replay = client.get("/api/bitbucket/callback", query_string={"state": query["state"][0], "code": "private-code"})
+ assert replay.status_code == 400
+ assert client.get("/bitbucket/connect?action_ref=personal:self:review").status_code == 200
+ with patch.object(routes, "BitbucketClient") as factory:
+ factory.return_value.discover.return_value = {"repositories": [], "next_cursor": None}
+ found = client.post("/api/bitbucket/discover", headers=headers, json={"action_ref": "personal:self:review", "project": "team"})
+ assert found.status_code == 200
+ factory.return_value.discover.assert_called_once_with("team", 0)
+ denied = client.post("/api/bitbucket/discover", headers=headers, json={"action_ref": "global:global:review", "project": "team"})
+ assert denied.status_code == 404
+ assert factory.call_count == 1
+ with patch.object(routes, "find_group_by_id", return_value={"id": "group", "status": "active"}), \
+ patch.object(routes, "get_user_role_in_group", return_value="User"), \
+ patch.object(routes, "get_settings", return_value={"enable_group_workspaces": True}):
+ denied = client.post("/api/bitbucket/discover", headers=headers, json={"action_ref": "group:group:review", "project": "team"})
+ assert denied.status_code == 404
+ disconnected = client.post("/api/bitbucket/disconnect", headers=headers, json={"action_ref": "personal:self:review"})
+ assert disconnected.status_code == 200 and disconnected.json == {"connected": False}
+ saved = copy.deepcopy(record)
+ saved["additionalFields"]["auth_method"] = "bearer_token"
+ saved["auth"] = {"type": "identity", "identity": "identity-id"}
+ hydrated = identities._apply_action_identity_auth(saved, {"auth_type": "bearer_token", "secret": "identity-private"})
+ assert hydrated["auth"]["key"] == "identity-private"
+ try:
+ identities._apply_action_identity_auth(saved, {"auth_type": "username_password", "username": "email", "password": "private"})
+ except ValueError:
+ pass
+ else:
+ raise AssertionError("Mismatched identity auth method accepted")
+ plugin = plugin_module.BitbucketPlugin(authorize("actor", "personal:actor:review"))
+ with patch.object(plugin_module, "actor_context", return_value=("actor", "chat", None)), \
+ patch.object(plugin_module, "authorized_manifest", side_effect=authorize):
+ result = plugin.list_repositories()
+ assert result["error"] == "reconnect_required" and result["connect_url"].startswith("/bitbucket/connect?")
+ assert "private-client-secret" not in repr(result)
+ """
+ environment = {**os.environ, "PYTHONPATH": os.pathsep.join((str(APP), str(ROOT / "functional_tests")))}
+ result = subprocess.run([sys.executable, "-c", probe], cwd=ROOT, env=environment,
+ capture_output=True, text=True, timeout=180)
+ assert result.returncode == 0, result.stdout + result.stderr
diff --git a/ui_tests/fixtures/orchestration/harness_entry.tsx b/ui_tests/fixtures/orchestration/harness_entry.tsx
index 5dc60b68d..5630c4932 100644
--- a/ui_tests/fixtures/orchestration/harness_entry.tsx
+++ b/ui_tests/fixtures/orchestration/harness_entry.tsx
@@ -41,6 +41,7 @@ import * as actionRecovery from '../../../application/v2_ui/src/lib/actionRecove
import * as chatSse from '../../../application/v2_ui/src/lib/sse';
import * as credentialEvents from '../../../application/v2_ui/src/lib/actionCredentialEvents';
import { ActionAuthentication } from '../../../application/v2_ui/src/components/workspaceActions/ActionAuthentication';
+import { ActionConfigurationFields } from '../../../application/v2_ui/src/components/workspaceActions/ActionConfigurationFields';
import type { ActionConfiguration, ActionTypeDefinition } from '../../../application/v2_ui/src/lib/workspaceAuthoring';
import { OrchestrationPlanPanel } from '../../../application/v2_ui/src/components/chat/OrchestrationPlanPanel';
import { OrchestrationRunView } from '../../../application/v2_ui/src/components/chat/OrchestrationRunView';
@@ -82,7 +83,11 @@ function ActionCredentialAuthoring({ initial, definition }: {
{}} identities={[]}
identitiesLoading={false} identitiesError={null} identitiesResolvable globalScope />
+ {draft.type === 'bitbucket' ? {}} identities={[]}
+ identitiesLoading={false} identitiesError={null} identitiesResolvable globalScope /> : null}
{JSON.stringify(draft.credential_requirements ?? {})}
+ {JSON.stringify(draft.additionalFields.repositories ?? [])}
>;
}
diff --git a/ui_tests/test_bitbucket_action_configuration.py b/ui_tests/test_bitbucket_action_configuration.py
new file mode 100644
index 000000000..4b7ff5392
--- /dev/null
+++ b/ui_tests/test_bitbucket_action_configuration.py
@@ -0,0 +1,132 @@
+# test_bitbucket_action_configuration.py
+"""
+Functional UI tests for Classic and V2 Bitbucket action configuration.
+Version: 0.261.450
+Implemented in: 0.261.450
+
+Real production components exercise repository discovery, fixed branches,
+private token sources, connection links and narrow/mobile layouts.
+"""
+
+import json
+from pathlib import Path
+import sys
+
+import pytest
+from playwright.sync_api import expect
+
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "ui_tests" / "fixtures"))
+from classic_action_credentials import ClassicCredentialFixture
+from ui_tests.fixtures.orchestration import harness_build as hb
+
+
+REPOSITORY = {"id": "1", "project": "team", "slug": "repo", "name": "Repository",
+ "branch_mode": "any", "default_branch": ""}
+ACTION = {
+ "id": "review", "name": "code_review", "displayName": "Code review",
+ "type": "bitbucket", "endpoint": "https://bitbucket.example.test",
+ "auth": {"type": "user", "identity": "client-id", "key": ""},
+ "additionalFields": {"edition": "data_center", "auth_method": "oauth", "repositories": []},
+ "metadata": {},
+}
+
+
+def _reply(route, value):
+ route.fulfill(content_type="application/json", body=json.dumps(value))
+
+
+@pytest.mark.parametrize("width", [390, 1440])
+def test_classic_bitbucket_repository_discovery_and_private_token_source(page, width):
+ page.set_viewport_size({"width": width, "height": 1000})
+ fixture = ClassicCredentialFixture(page, modal=True)
+ page.route("**/api/*/plugins/types", lambda route: _reply(route, [
+ {"type": "bitbucket", "display": "Bitbucket", "description": "Review repository source."},
+ ]))
+ page.route("**/api/bitbucket/connection?**", lambda route: _reply(route, {"connected": True, "csrf_token": "fixture-csrf"}))
+ calls = []
+
+ def discover(route):
+ calls.append(route.request.post_data_json)
+ assert route.request.headers["x-csrftoken"] == "fixture-csrf"
+ _reply(route, {"repositories": [REPOSITORY], "next_cursor": None})
+
+ page.route("**/api/bitbucket/discover", discover)
+ fixture.open()
+ fixture.show_action(manifest=ACTION)
+ expect(page.get_by_role("link", name="Connect / reconnect my Bitbucket account")).to_have_attribute(
+ "href", "/bitbucket/connect?action_ref=personal%3Aself%3Areview",
+ )
+ page.get_by_label("Data Center project key or Cloud workspace").fill("team")
+ page.get_by_role("button", name="Find repositories", exact=True).click()
+ page.get_by_role("checkbox", name="Repository (team/repo)").check()
+ page.get_by_label("Allowed branches", exact=True).select_option("fixed")
+ page.get_by_label("Fixed branch (required)").fill("main")
+ form = fixture.form_data()
+ assert form["additionalFields"]["repositories"] == [{**REPOSITORY, "branch_mode": "fixed", "default_branch": "main"}]
+ assert calls == [{"action_ref": "personal:self:review", "project": "team", "cursor": 0}]
+ page.get_by_label("Bitbucket authentication", exact=True).select_option("bearer_token")
+ page.get_by_label("Token credential source").select_option("personal")
+ form = fixture.form_data()
+ assert form["auth"]["key"] == "" and form["identity_id"] == ""
+ assert form["credential_requirements"] == {"version": 1, "slots": {"service": {"source": "personal", "auth_type": "bearer_token"}}}
+ expect(page.get_by_label("Read-only token", exact=True)).to_be_hidden()
+ expect(page.get_by_role("button", name="Find repositories", exact=True)).to_be_disabled()
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
+ fixture.assert_clean()
+
+
+@pytest.mark.parametrize("width", [390, 1440])
+def test_v2_bitbucket_discovery_policy_and_oauth_connection(page, width):
+ errors = []
+ page.on("pageerror", lambda error: errors.append(str(error)))
+ hb.ensure_bundle()
+ with hb.start_static_server() as origin:
+ page.goto(f"{origin}/{hb.HARNESS_HTML_REL}")
+ page.wait_for_function("() => typeof window.OrchHarness?.mount === 'function'")
+ css = next((ROOT / "application" / "single_app" / "static" / "v2" / "assets").glob("*.css"), None)
+ if css is None:
+ raise AssertionError("Build the production V2 UI before Bitbucket layout tests.")
+ page.add_style_tag(url=f"{origin}/application/single_app/static/v2/assets/{css.name}")
+ page.set_viewport_size({"width": width, "height": 1000})
+ page.evaluate("""(initial) => {
+ const H = window.OrchHarness;
+ H.reset();
+ H.stores.bootstrap.useBootstrapStore.setState({data: {user: {id: 'actor'}}});
+ window.__bitbucketCalls = [];
+ window.fetch = async (url, options = {}) => {
+ window.__bitbucketCalls.push({url: String(url), body: options.body ? JSON.parse(options.body) : null, headers: options.headers});
+ const result = String(url).includes('/connection?')
+ ? {connected: true, csrf_token: 'fixture-csrf'}
+ : {repositories: [{id: '1', project: 'team', slug: 'repo', name: 'Repository', branch_mode: 'any', default_branch: ''}], next_cursor: null};
+ return new Response(JSON.stringify(result), {headers: {'Content-Type': 'application/json'}});
+ };
+ H.mount('mount-a', 'ActionCredentialAuthoring', {
+ initial, definition: {type: 'bitbucket', display: 'Bitbucket',
+ allowed_auth_types: ['user', 'key', 'identity', 'username_password'], additional_fields_schema: {}, metadata_schema: {}}
+ });
+ }""", ACTION)
+ expect(page.get_by_role("link", name="Connect / reconnect my Bitbucket account")).to_have_attribute(
+ "href", "/bitbucket/connect?action_ref=global%3Aglobal%3Areview",
+ )
+ page.get_by_label("Data Center project key", exact=True).fill("team")
+ page.get_by_role("button", name="Find repositories", exact=True).click()
+ page.get_by_role("checkbox", name="Repository (repo)").check()
+ page.get_by_label("Allowed branches", exact=True).select_option("fixed")
+ page.get_by_label("Fixed branch", exact=True).fill("main")
+ content = page.get_by_label("Bitbucket repository configuration").inner_text()
+ assert json.loads(content) == [{**REPOSITORY, "branch_mode": "fixed", "default_branch": "main"}]
+ page.get_by_label("Bitbucket authentication", exact=True).select_option("bearer_token")
+ page.get_by_label("Token credential source", exact=True).select_option("identity")
+ expect(page.get_by_label("Token credential source", exact=True)).to_have_value("identity")
+ page.get_by_label("Token credential source", exact=True).select_option("personal")
+ requirements = page.get_by_label("Action credential requirements").inner_text()
+ assert json.loads(requirements) == {"version": 1, "slots": {"service": {"source": "personal", "auth_type": "bearer_token"}}}
+ expect(page.get_by_label("Read-only token", exact=True)).to_have_count(0)
+ calls = page.evaluate("window.__bitbucketCalls")
+ discovered = next(call for call in calls if call["url"].endswith("/discover"))
+ assert discovered["headers"]["X-CSRFToken"] == "fixture-csrf"
+ assert discovered["body"] == {"action_ref": "global:global:review", "project": "team", "cursor": 0}
+ assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
+ assert not errors, errors