Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 34 additions & 1 deletion application/single_app/action_credential_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from agent_interaction_contracts import AgentInteractionRequired

from functions_action_manifest import get_action_origin, resolve_action_type
from functions_bitbucket_operations import normalize_bitbucket_manifest, policy_fingerprint

Check warning on line 11 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains security control, sanitization, or audit marker. Recommendation%3A Confirm the change does not weaken auth, CSRF, CSP, XSS defenses, settings sanitization, redaction, audit logging, or tests.
from functions_yamcs_operations import (
normalize_yamcs_auth_method,
normalize_yamcs_server_url,
Expand Down Expand Up @@ -118,7 +119,39 @@
return list(slots)


ADAPTERS = {"yamcs": YamcsCredentialAdapter()}
class BitbucketCredentialAdapter:

Check warning on line 122 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains secret or sensitive data source marker. Recommendation%3A Pair this source with any nearby network, logging, serialization, or process execution sink before approving.
slots = {"service": {"username_password", "bearer_token"}}

Check warning on line 123 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains security control, sanitization, or audit marker. Recommendation%3A Confirm the change does not weaken auth, CSRF, CSP, XSS defenses, settings sanitization, redaction, audit logging, or tests.

Check warning on line 123 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains secret or sensitive data source marker. Recommendation%3A Pair this source with any nearby network, logging, serialization, or process execution sink before approving.

@staticmethod
def validate(manifest, slots):

Check warning on line 126 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains security control, sanitization, or audit marker. Recommendation%3A Confirm the change does not weaken auth, CSRF, CSP, XSS defenses, settings sanitization, redaction, audit logging, or tests.
normalized = normalize_bitbucket_manifest(manifest)
method = normalized["additionalFields"]["auth_method"]
service = slots.get("service")
if method == "oauth" or not service or service["auth_type"] != method:
raise ValueError("Bitbucket personal credentials must match the token authentication method.")

Check warning on line 131 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains secret or sensitive data source marker. Recommendation%3A Pair this source with any nearby network, logging, serialization, or process execution sink before approving.
auth = manifest.get("auth") or {}
if manifest.get("identity_id") or any(auth.get(key) for key in ("key", "identity", "tenantId")):
raise ValueError("Personal Bitbucket credentials cannot include shared credentials.")

Check warning on line 134 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains secret or sensitive data source marker. Recommendation%3A Pair this source with any nearby network, logging, serialization, or process execution sink before approving.

@staticmethod
def destination(manifest):
normalized = normalize_bitbucket_manifest(manifest)
return {"endpoint": normalized["endpoint"], "policy": policy_fingerprint(normalized)}

Check warning on line 139 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains security control, sanitization, or audit marker. Recommendation%3A Confirm the change does not weaken auth, CSRF, CSP, XSS defenses, settings sanitization, redaction, audit logging, or tests.

@staticmethod
def inject(manifest, slot, auth):
manifest["auth"] = {
"type": "username_password" if auth["auth_type"] == "username_password" else "key",

Check warning on line 144 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains security control, sanitization, or audit marker. Recommendation%3A Confirm the change does not weaken auth, CSRF, CSP, XSS defenses, settings sanitization, redaction, audit logging, or tests.

Check warning on line 144 in application/single_app/action_credential_contracts.py

View workflow job for this annotation

GitHub Actions / malicious-pr-security-review

Important - Changed line contains secret or sensitive data source marker. Recommendation%3A Pair this source with any nearby network, logging, serialization, or process execution sink before approving.
"identity": auth.get("username", ""),
"key": auth["password"] if auth["auth_type"] == "username_password" else auth["secret"],
}

@staticmethod
def rejected_slots(manifest, error):
return ["service"] if getattr(error, "status", None) == 401 else []


ADAPTERS = {"yamcs": YamcsCredentialAdapter(), "bitbucket": BitbucketCredentialAdapter()}


def credential_slots(manifest):
Expand Down
2 changes: 1 addition & 1 deletion application/single_app/action_usage.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def action_usage_target(manifest):
connector_types = {
"mcp": "mcp", "openapi": "openapi", "databricks": "databricks",
"databrickstable": "databricks_table", "snowflake": "snowflake",
"tableau": "tableau", "yamcs": "yamcs",
"tableau": "tableau", "yamcs": "yamcs", "bitbucket": "bitbucket",
}
action_type = connector_types.get(compact_type, declared_type)
fields = manifest.get("additionalFields")
Expand Down
2 changes: 2 additions & 0 deletions application/single_app/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
from route_frontend_content_screening import register_route_frontend_content_screening
from route_backend_msgraph_pending_actions import register_route_backend_msgraph_pending_actions
from route_backend_m365 import configure_m365_routes, register_route_backend_m365
from route_backend_bitbucket import register_route_backend_bitbucket
from functions_m365_approvals import configure_m365_approvals
from functions_m365_connections import configure_m365_connection_authorization
from functions_m365_execution import configure_m365_execution, validate_m365_workflow_context
Expand Down Expand Up @@ -1521,6 +1522,7 @@ def list_semantic_kernel_plugins():
configure_m365_file_runtime()
configure_m365_pending_delivery_runtime(app.test_request_context)
register_route_blueprint('backend_m365', register_route_backend_m365, user_required_blueprint)
register_route_blueprint('backend_bitbucket', register_route_backend_bitbucket, user_required_blueprint)


@app.after_request
Expand Down
7 changes: 6 additions & 1 deletion application/single_app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
EXECUTOR_MAX_WORKERS = 30
CHAT_STREAM_EXECUTOR_MAX_WORKERS = max(8, int(os.getenv('SIMPLECHAT_CHAT_STREAM_WORKERS', '32') or '32'))
SESSION_TYPE = 'filesystem'
VERSION = "0.261.450"
VERSION = "0.261.451"
IS_DEVELOPMENT = is_development_env_enabled()

# Opt-out for deployments where App Service Easy Auth is active but the platform
Expand Down Expand Up @@ -893,6 +893,11 @@ def _create_container_if_not_exists_with_conflict_recovery(*args, **kwargs):

cosmos_personal_workspace_identities_container_name = "personal_workspace_identities"
cosmos_action_credential_state_container_name = "action_credential_state"
cosmos_bitbucket_connections_container = cosmos_database.create_container_if_not_exists(
id="bitbucket_connections",
partition_key=PartitionKey(path="/user_id"),
default_ttl=-1,
)
cosmos_action_credential_state_container = cosmos_database.create_container_if_not_exists(
id=cosmos_action_credential_state_container_name,
partition_key=PartitionKey(path="/user_id"),
Expand Down
26 changes: 26 additions & 0 deletions application/single_app/functions_action_credential_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,32 @@ def resolve_agent(reference, *, user_id):
reference, user_id=user_id, settings=functions_settings.get_settings(),
)

# Compose Bitbucket storage and secret owners only after web/scheduler bootstrap.
from config import cosmos_bitbucket_connections_container
from functions_action_manifest import bind_action_origin, get_action_origin
from functions_bitbucket_connections import BitbucketConnections, configure_bitbucket_connections
def bitbucket_manifest(user_id, reference):
# Secret owners are needed only when the initialized runtime resolves a Bitbucket action.
from functions_keyvault import SecretReturnType, keyvault_plugin_get_helper

manifest = resolve_manifest(user_id, reference)
if manifest.get("type") != "bitbucket":
raise PermissionError("The selected action is not a Bitbucket action.")
origin = get_action_origin(manifest)
manifest = keyvault_plugin_get_helper(
manifest, scope_value=origin.action_id if origin.scope_type == "global" else origin.scope_id,
scope="user" if origin.scope_type == "personal" else origin.scope_type,
return_type=SecretReturnType.VALUE,
)
manifest = identities.hydrate_action_identity_reference(
manifest, origin.scope_type, origin.scope_id, return_type=SecretReturnType.VALUE,
)
return bind_action_origin(manifest, origin.scope_type, origin.scope_id)

configure_bitbucket_connections(BitbucketConnections(
cosmos_bitbucket_connections_container, bitbucket_manifest,
))

def update_identity(*args, **kwargs):
try:
return identities.update_workspace_identity_conditional(*args, **kwargs)
Expand Down
3 changes: 2 additions & 1 deletion application/single_app/functions_action_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ def safe_request(item, manifest):
context = request_conversation(item)
requirements = [
{"slot": slot, "auth_type": auth_type,
"label": "Proxy sign-in" if slot == "proxy" else "YAMCS sign-in"}
"label": "Proxy sign-in" if slot == "proxy" else (
"Bitbucket sign-in" if resolve_action_type(manifest) == "bitbucket" else "YAMCS sign-in")}
for slot, auth_type in item["requirements"].items()
]
result = {
Expand Down
214 changes: 214 additions & 0 deletions application/single_app/functions_bitbucket_connections.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
# functions_bitbucket_connections.py
"""Private Bitbucket OAuth connections; storage and secrets supplied by composition."""

import base64
import hashlib
import hmac
import json
import os
import secrets
import time
from urllib.parse import urlencode

import requests
from azure.core import MatchConditions
from azure.cosmos.exceptions import CosmosResourceNotFoundError
from cryptography.fernet import Fernet, InvalidToken

from cosmos_document_utils import normalize_cosmos_document
from functions_bitbucket_operations import (
BitbucketError, bounded_response, fail, normalize_bitbucket_manifest, policy_fingerprint,
)
from functions_outbound_http import create_guarded_session
from functions_outbound_destinations import OutboundDestinationError


_service = None


def configure_bitbucket_connections(service):
global _service
_service = service


def bitbucket_connections():
if _service is None:
fail("connection_unavailable", "Bitbucket connections are not configured.", 503)
return _service


def encryption_key():
"""Deploy through a server-side secret/Key Vault App Service reference, never settings JSON."""
value = os.environ.get("BITBUCKET_TOKEN_ENCRYPTION_KEY", "")
try:
return Fernet(value.encode("ascii"))
except (ValueError, UnicodeError):
fail("encryption_required", "Configure BITBUCKET_TOKEN_ENCRYPTION_KEY before connecting Bitbucket.", 503)


class BitbucketConnections:
def __init__(self, container, authorize, *, key_provider=encryption_key, clock=time.time,
session_factory=create_guarded_session):
self.container = container
self.authorize = authorize
self.key_provider = key_provider
self.clock = clock
self.session_factory = session_factory

def read(self, user_id, item_id):
try:
item = normalize_cosmos_document(self.container.read_item(item=item_id, partition_key=user_id))
except CosmosResourceNotFoundError:
return None
if item.get("user_id") != user_id or item.get("id") != item_id:
fail("connection_invalid", "Bitbucket connection ownership could not be verified.", 409)
return item

def replace(self, item, changes):
return normalize_cosmos_document(self.container.replace_item(
item=item["id"], body={**item, **changes}, etag=item["_etag"],
match_condition=MatchConditions.IfNotModified,
))

def binding(self, user_id, action_ref):
manifest = normalize_bitbucket_manifest(self.authorize(user_id, action_ref), allow_empty=True)
fingerprint = policy_fingerprint(manifest)
key = hashlib.sha256(json.dumps([user_id, action_ref]).encode()).hexdigest()
return manifest, fingerprint, f"bitbucket-{key}"

def seal(self, value, binding):
return self.key_provider().encrypt(json.dumps({"binding": binding, "value": value}).encode()).decode("ascii")

def open(self, value, binding):
try:
payload = json.loads(self.key_provider().decrypt(value.encode("ascii")))
if payload["binding"] != binding or not isinstance(payload["value"], dict):
raise ValueError("binding")
return payload["value"]
except (InvalidToken, ValueError, KeyError, TypeError):
fail("reconnect_required", "Bitbucket credentials could not be verified. Reconnect your account.", 409)

def endpoints(self, manifest):
if manifest["additionalFields"]["edition"] == "cloud":
return "https://bitbucket.org/site/oauth2/authorize", "https://bitbucket.org/site/oauth2/access_token"
root = manifest["endpoint"] + "/rest/oauth2/latest"
return root + "/authorize", root + "/token"

def status(self, user_id, action_ref):
_manifest, fingerprint, item_id = self.binding(user_id, action_ref)
item = self.read(user_id, item_id)
return {"connected": bool(item and item.get("fingerprint") == fingerprint
and item.get("tokens") and not item.get("refresh_lease")), "connection_id": item_id}

def start(self, user_id, action_ref, session_binding, redirect_uri):
manifest, fingerprint, item_id = self.binding(user_id, action_ref)
if manifest["additionalFields"]["auth_method"] != "oauth":
fail("configuration_invalid", "This action is not configured for OAuth.")
if not manifest["auth"].get("identity") or not manifest["auth"].get("key"):
fail("configuration_invalid", "Configure the Bitbucket OAuth client ID and secret.")
self.key_provider()
current = self.read(user_id, item_id)
if current is None:
self.container.create_item({"id": item_id, "user_id": user_id, "generation": secrets.token_hex(16),
"tokens": None, "refresh_lease": None, "ttl": -1})
current = self.read(user_id, item_id)
current = self.replace(current, {"generation": secrets.token_hex(16), "fingerprint": fingerprint,
"tokens": None, "refresh_lease": None})
state = secrets.token_urlsafe(32)
verifier = secrets.token_urlsafe(48)
flow = {
"id": f"flow-{hashlib.sha256(state.encode()).hexdigest()}", "user_id": user_id,
"action_ref": action_ref, "fingerprint": fingerprint, "connection_id": item_id,
"generation": current["generation"], "session_binding": session_binding,
"redirect_uri": redirect_uri, "expires": self.clock() + 600, "ttl": 600,
"consumed": False, "verifier": self.seal({"verifier": verifier}, [user_id, item_id]),
}
self.container.create_item(flow)
endpoint, _token = self.endpoints(manifest)
query = {"client_id": manifest["auth"]["identity"], "response_type": "code",
"redirect_uri": redirect_uri, "state": state}
if manifest["additionalFields"]["edition"] == "data_center":
query.update(scope="REPO_READ", code_challenge_method="S256",
code_challenge=base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("="))
return {"authorization_url": endpoint + "?" + urlencode(query)}

def exchange(self, manifest, data):
_authorize, endpoint = self.endpoints(manifest)
client = manifest["auth"]
basic = None
if manifest["additionalFields"]["edition"] == "cloud":
basic = (client["identity"], client["key"])
else:
data = {**data, "client_id": client["identity"], "client_secret": client["key"]}
try:
with self.session_factory() as session:
response = session.post(endpoint, data=data, auth=basic, timeout=(10, 30),
stream=True, allow_redirects=False)
if response.status_code in {400, 401, 403}:
response.close()
fail("reconnect_required", "Bitbucket authorization expired or was rejected. Reconnect your account.", 409)
tokens = bounded_response(response, limit=65536)
except requests.RequestException:
fail("connection_failed", "The Bitbucket authorization service could not be reached.", 502)
except OutboundDestinationError as error:
raise BitbucketError("destination_invalid", error.public_message) from None
if (
not isinstance(tokens.get("access_token"), str) or not tokens["access_token"]
or str(tokens.get("token_type", "")).lower() != "bearer"
or not isinstance(tokens.get("refresh_token"), str) or not tokens["refresh_token"]
or type(tokens.get("expires_in")) is not int or tokens["expires_in"] <= 0
):
fail("response_invalid", "Bitbucket returned an invalid OAuth token response.", 502)
return {key: tokens[key] for key in ("access_token", "refresh_token", "expires_in")}

def complete(self, user_id, state, code, session_binding):
if not isinstance(state, str) or not 32 <= len(state) <= 128 or not isinstance(code, str) or not 1 <= len(code) <= 8192:
fail("state_invalid", "The Bitbucket sign-in request is invalid or expired.")
flow = self.read(user_id, f"flow-{hashlib.sha256(state.encode()).hexdigest()}")
if (
not flow or flow["consumed"] or flow["expires"] < self.clock()
or not hmac.compare_digest(flow["session_binding"], session_binding)
):
fail("state_invalid", "The Bitbucket sign-in request is invalid or expired.")
manifest, fingerprint, item_id = self.binding(user_id, flow["action_ref"])
current = self.read(user_id, item_id)
if fingerprint != flow["fingerprint"] or not current or current["generation"] != flow["generation"]:
fail("connection_changed", "The action or connection changed. Start sign-in again.", 409)
self.replace(flow, {"consumed": True})
verifier = self.open(flow["verifier"], [user_id, item_id])["verifier"]
data = {"grant_type": "authorization_code", "code": code, "redirect_uri": flow["redirect_uri"]}
if manifest["additionalFields"]["edition"] == "data_center":
data["code_verifier"] = verifier
tokens = self.exchange(manifest, data)
# A concurrent disconnect or reconnect must win over an in-flight token exchange.
self.replace(current, {"tokens": self.seal(tokens, [user_id, item_id]),
"expires": self.clock() + tokens["expires_in"],
"redirect_uri": flow["redirect_uri"], "refresh_lease": None})

def disconnect(self, user_id, action_ref):
_manifest, _fingerprint, item_id = self.binding(user_id, action_ref)
item = self.read(user_id, item_id)
if item:
self.replace(item, {"tokens": None, "generation": secrets.token_hex(16), "refresh_lease": None})

def token(self, user_id, action_ref):
manifest, fingerprint, item_id = self.binding(user_id, action_ref)
item = self.read(user_id, item_id)
if not item or item.get("fingerprint") != fingerprint or not item.get("tokens"):
fail("reconnect_required", "Connect Bitbucket in the action's connection controls before reviewing code.", 409)
if item.get("refresh_lease"):
fail("refresh_in_progress", "Bitbucket token refresh is in progress. Retry or reconnect if interrupted.", 409)
tokens = self.open(item["tokens"], [user_id, item_id])
if item["expires"] > self.clock() + 60:
return tokens["access_token"]
claimed = self.replace(item, {"refresh_lease": secrets.token_hex(16)})
try:
refreshed = self.exchange(manifest, {"grant_type": "refresh_token", "refresh_token": tokens["refresh_token"],
"redirect_uri": item["redirect_uri"]})
except BitbucketError:
# Rotation may have happened even if a response was lost. Never replay the old refresh token.
self.replace(claimed, {"tokens": None, "refresh_lease": None})
raise
self.replace(claimed, {"tokens": self.seal(refreshed, [user_id, item_id]),
"expires": self.clock() + refreshed["expires_in"], "refresh_lease": None})
return refreshed["access_token"]
Loading
Loading