Skip to content
Open
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
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ bitbucket-cli/
- `BB_USER`: Bitbucket account email
- `BB_TOKEN`: API token from id.atlassian.com (never echoed)
- `BB_WORKSPACE`: workspace slug
- **MCP runtime**: stdlib-only at runtime; the `mcp` package is the only third-party dep, installed into a self-bootstrapped venv at `$XDG_DATA_HOME/bitbucket-cli/venv` (default `~/.local/share/bitbucket-cli/venv`) on first invocation.
- **MCP runtime**: stdlib-only at runtime; the `mcp` package is the only third-party dep, installed into a self-bootstrapped venv at `$XDG_DATA_HOME/bitbucket-cli/venv-mcp2` (default `~/.local/share/bitbucket-cli/venv-mcp2`) on first invocation. The directory is named for the mcp major version, so releases built for another major keep their own venv.

## Configuration

Expand All @@ -61,7 +61,7 @@ Loaded in this order (later overrides earlier):
- HTTP helpers: `bb_get` / `bb_post` / `bb_put` / `bb_delete`.
- `resolve_repo` sets `repo` + `BB_WORKSPACE` in the CALLER's scope (called as `resolve_repo "$1"`, NOT `repo=$(...)`, so it escapes the subshell and can set the workspace). Precedence: `-w` flag > `workspace/slug` arg > git origin auto-detect > `BB_WORKSPACE` default > error. `resolve_workspace` is the repo-less companion for workspace-level commands. Both mirror the Python `_resolve_repo` contract.
- `BB_WORKSPACE` is OPTIONAL — only `BB_USER` + `BB_TOKEN` are required at load; a missing workspace fails at the point of use, not at startup.
- Boundary validation via `_require_*` helpers, one per user-supplied value that reaches a URL or a jq program: `_require_build_number` / `_require_pr_id` / `_require_step_index` (numeric guards — the last two also close jq/URL injection surfaces, `_require_step_index` specifically prevents `$ENV.BB_TOKEN` exfiltration through the logs jq program), `_require_count` and `_require_pr_state` (query-param injection). Every value Python validates (`_is_positive_int` / `_validate_pr_id`) MUST have a bash `_require_*` sibling — parity gaps here are security bugs, not cosmetics.
- Boundary validation via `_require_*` helpers, one per user-supplied value that reaches a URL or a jq program: `_require_build_number` / `_require_pr_id` / `_require_step_index` (numeric guards — the last two also close jq/URL injection surfaces, `_require_step_index` specifically prevents `$ENV.BB_TOKEN` exfiltration through the logs jq program), `_require_count` and `_require_pr_state` (query-param injection). Workspace and repo slugs are limited to `[A-Za-z0-9._-]` by `bb_api.validate_slug` (Python) and `_slug_chars_ok` in `repo_path` / `_require_workspace` (bash), because slugs reach URL paths unencoded. Every value Python validates (`_is_positive_int` / `_validate_pr_id`) MUST have a bash `_require_*` sibling — parity gaps here are security bugs, not cosmetics.
- User-supplied values ride into JSON via `jq` (`--arg` / `--args`), never string interpolation, to prevent injection. Delimited streams are off-limits for value lists: bash arguments are C strings, so a NUL delimiter embedded in a jq program is silently dropped by the shell (jq sees `split("")` and shreds the stream per character), and any printable delimiter can collide with a value. `bb trigger` passes each `KEY=VALUE` pair as its own jq argument via `$ARGS.positional` (jq 1.6+).
- Error rc capture: `local rc=0; out=$(cmd) || rc=$?` — NOT `if ! cmd; then rc=$?` (the `!` negation makes `$?` always 0; verified on bash 3.2 + 5.x).
- bash 3.2+ floor (macOS system bash supported) — no `${var,,}` / `${var^^}` / `mapfile` / `declare -A`; a `bash:3.2` CI job (`bash32-floor`) parses `bb` to catch regressions.
Expand Down
12 changes: 8 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,11 +503,15 @@ claude mcp add --scope user bitbucket \
# (see "Multiple workspaces" below).

# 3. On first invocation, the server self-bootstraps a durable venv at
# $XDG_DATA_HOME/bitbucket-cli/venv (default: ~/.local/share/bitbucket-cli/venv)
# and installs the `mcp` package into it. Subsequent launches reuse the venv.
# $XDG_DATA_HOME/bitbucket-cli/venv-mcp2 (default:
# ~/.local/share/bitbucket-cli/venv-mcp2) and installs the `mcp` package
# into it. Subsequent launches reuse the venv. The directory is named for
# the mcp major version, so releases built for mcp 1.x keep their own
# `bitbucket-cli/venv`; once you no longer run one, that old directory
# can be deleted.
#
# To force a clean rebuild:
# rm -rf "${XDG_DATA_HOME:-$HOME/.local/share}/bitbucket-cli/venv"
# rm -rf "${XDG_DATA_HOME:-$HOME/.local/share}/bitbucket-cli/venv-mcp2"
# and relaunch the MCP server.

# 4. Verify the connection (handshake only — does NOT validate credentials):
Expand Down Expand Up @@ -543,7 +547,7 @@ claude mcp add --scope user bitbucket-work \
|---|---|
| `BB_API_BASE` | Override the Bitbucket REST base URL (default `https://api.bitbucket.org/2.0`). Useful for a test / proxied / staging mirror. |
| `BB_DEFAULT_REPO_PATH` | Default working directory for repo auto-detection (when a Bitbucket tool is called with `repo=""`) AND for the `git_*` tools' default `path=""` resolution. Defaults to the MCP server's launch cwd. |
| `XDG_DATA_HOME` | Standard XDG override for the data root. The venv lives at `$XDG_DATA_HOME/bitbucket-cli/venv` (default `~/.local/share/bitbucket-cli/venv`). |
| `XDG_DATA_HOME` | Standard XDG override for the data root. The venv lives at `$XDG_DATA_HOME/bitbucket-cli/venv-mcp2` (default `~/.local/share/bitbucket-cli/venv-mcp2`). |

### Optional: install the bundled `bitbucket` agent for delegated use

Expand Down
2 changes: 1 addition & 1 deletion agents/bitbucket.md
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ Surface the log's relevant tail (last ~50 lines or the stderr region around the
The CLI is two parallel implementations:

- **`bb`** (bash) — human-facing CLI, ~1000 lines of pure bash + curl + jq.
- **`bb_api.py`** + **`bb_ops.py`** + **`git_ops.py`** + **`mcp_server.py`** (Python) — what the MCP server uses. Stdlib-only runtime (no `requests` etc.); `mcp` is the only third-party dep, installed by the self-bootstrapping venv at `~/.local/share/bitbucket-cli/venv`.
- **`bb_api.py`** + **`bb_ops.py`** + **`git_ops.py`** + **`mcp_server.py`** (Python) — what the MCP server uses. Stdlib-only runtime (no `requests` etc.); `mcp` is the only third-party dep, installed by the self-bootstrapping venv at `~/.local/share/bitbucket-cli/venv-mcp2`.

### When delegated a `bb` change

Expand Down
44 changes: 42 additions & 2 deletions bb
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,18 @@ _resolve_pr_args() {
[[ -n "$pr_id" ]] && _require_pr_id "$pr_id"
}

# True when every byte of $1 is a slug character: [A-Za-z0-9._-].
# Slugs are interpolated into URL paths unencoded, so a space, `?`, `#`,
# `%` or control character would change which endpoint a request reaches.
# LC_ALL=C keeps the ranges byte-exact, matching the ASCII-only
# bb_api._SLUG_RE on the Python side in every locale. The trailing `x`
# is load-bearing: `$(...)` strips trailing newlines, so without it a
# value whose only bad bytes are newlines would test as empty and pass.
# Emptiness is the callers' check, so an empty value passes here.
_slug_chars_ok() {
[[ "$(printf '%s' "$1" | LC_ALL=C tr -d 'A-Za-z0-9._-'; printf x)" == "x" ]]
}

repo_path() {
local repo="$1"
# Validate inputs at the boundary so a malformed slug doesn't
Expand Down Expand Up @@ -443,6 +455,14 @@ repo_path() {
echo "Error: repo must not be '.' or '..'." >&2
kill -TERM $$
fi
if ! _slug_chars_ok "$BB_WORKSPACE"; then
echo "Error: workspace must contain only letters, digits, '.', '_' and '-' (got '$BB_WORKSPACE')." >&2
kill -TERM $$
fi
if ! _slug_chars_ok "$repo"; then
echo "Error: repo must contain only letters, digits, '.', '_' and '-' (got '$repo')." >&2
kill -TERM $$
fi
# `exit 1` inside a `$(repo_path ...)` command substitution only
# terminates the subshell — the caller would proceed with an
# empty path. `kill -TERM $$` terminates the parent script so
Expand Down Expand Up @@ -570,6 +590,10 @@ _require_workspace() {
echo "Error: workspace must not be '.' or '..' (got '$ws')." >&2
exit 1
fi
if ! _slug_chars_ok "$ws"; then
echo "Error: workspace must contain only letters, digits, '.', '_' and '-' (got '$ws')." >&2
exit 1
fi
}

# Allowlist the PR state before it's interpolated into the request URL.
Expand Down Expand Up @@ -1060,6 +1084,10 @@ cmd_pipeline_approve() {
echo "Usage: bb approve [repo] <build-number>" >&2
exit 1
fi
_require_build_number "$build_number"
# Validate both slugs exactly as API URLs do (repo_path exits on a
# bad one); the path itself is not needed here.
repo_path "$repo" > /dev/null

echo "Manual step approval is not supported by the Bitbucket public API."
echo "Opening pipeline in browser..."
Expand Down Expand Up @@ -2243,6 +2271,7 @@ cmd_members() {

cmd_repos() {
resolve_workspace
_require_workspace "$BB_WORKSPACE"
echo "Repositories in ${BB_WORKSPACE}:"
echo ""

Expand Down Expand Up @@ -2814,8 +2843,10 @@ _vars_base_path() {
# and Python's `.strip()` emptiness check (parity).
local _ws_stripped
_ws_stripped="$(printf '%s' "${BB_WORKSPACE:-}" | tr -d '[:space:]')"
if [[ -z "$_ws_stripped" || "$BB_WORKSPACE" == */* \
|| "$BB_WORKSPACE" == "." || "$BB_WORKSPACE" == ".." ]]; then
if [[ -z "$_ws_stripped" || "$_ws_stripped" != "$BB_WORKSPACE" \
|| "$BB_WORKSPACE" == */* \
|| "$BB_WORKSPACE" == "." || "$BB_WORKSPACE" == ".." ]] \
|| ! _slug_chars_ok "$BB_WORKSPACE"; then
echo "Error: invalid workspace for workspace-scope variables: '${BB_WORKSPACE:-}'." >&2
# Inside `$(...)`; kill the parent, not just the subshell.
kill -TERM $$
Expand Down Expand Up @@ -3353,6 +3384,12 @@ cmd_whoami() {
if [[ -z "$probe_ws" ]]; then
echo " Skipped — no workspace to probe (set BB_WORKSPACE or run"
echo " inside a Bitbucket git checkout). Config + token look set."
elif [[ "$probe_ws" == "." || "$probe_ws" == ".." ]] \
|| ! _slug_chars_ok "$probe_ws"; then
# A `..` or `?`/`#` would probe a different endpoint (`..` reaches
# the global /repositories listing and falsely reports auth OK).
echo " Workspace '${probe_ws}' is not a valid slug (letters, digits,"
echo " '.', '_' and '-' only); probe skipped. Fix BB_WORKSPACE / -w."
elif bb_get "/repositories/${probe_ws}?pagelen=1" > /dev/null 2>&1; then
echo " Workspace '${probe_ws}' reachable — auth OK."
else
Expand All @@ -3368,6 +3405,9 @@ cmd_open() {
local repo
resolve_repo "${1:-}"
local section="${2:-}"
# Validate both slugs exactly as API URLs do (repo_path exits on a
# bad one); the path itself is not needed here.
repo_path "$repo" > /dev/null

local url="https://bitbucket.org/${BB_WORKSPACE}/${repo}"

Expand Down
51 changes: 39 additions & 12 deletions bb_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,23 +257,50 @@ def detect_repo(
return repo


def repo_path(workspace: str, repo: str) -> str:
"""Build the Bitbucket REST path for a repo (`/repositories/{ws}/{repo}`).
# Bitbucket workspace and repository slugs use only these characters.
# Slugs are interpolated into URL paths unencoded, so anything else (a
# space, `?`, `#`, `%`, a control character) would either be rejected by
# urllib or change which endpoint the request reaches. UUID-form
# identifiers (`{...}`) are not accepted here. Mirrored by the bash
# _slug_chars_ok helper.
_SLUG_RE = re.compile(r"[A-Za-z0-9._-]+")


Mirrors the bash repo_path helper. Validates inputs reject:
- empty / whitespace-only values (would produce `/repositories//repo`)
def validate_slug(label: str, value: Any) -> str:
"""Validate a workspace or repo slug before it reaches a URL path.

Rejects, in order (the earlier messages are the long-standing ones):
- non-strings and empty / whitespace-only values (would produce
`/repositories//repo`)
- embedded `/` (would silently change path structure)
- `.` or `..` segments (path-traversal: after URL normalisation,
- `.` or `..` (path traversal: after URL normalisation,
`/repositories/../widget` resolves to `/repositories/widget` with
the wrong workspace)
- any character outside `_SLUG_RE`
Returns the value unchanged.
"""
if not isinstance(value, str) or not value.strip():
raise ValueError(f"{label} must be a non-empty, non-whitespace string. Got {value!r}.")
if "/" in value:
raise ValueError(f"{label} must not contain '/'. Got {value!r}.")
if value in (".", ".."):
raise ValueError(f"{label} must not be '.' or '..'. Got {value!r}.")
if not _SLUG_RE.fullmatch(value):
raise ValueError(
f"{label} must contain only letters, digits, '.', '_' and '-'. "
f"Got {value!r}."
)
return value


def repo_path(workspace: str, repo: str) -> str:
"""Build the Bitbucket REST path for a repo (`/repositories/{ws}/{repo}`).

Mirrors the bash repo_path helper; both slugs go through
validate_slug.
"""
for label, value in (("workspace", workspace), ("repo", repo)):
if not value or not value.strip():
raise ValueError(f"{label} must be a non-empty, non-whitespace string. Got {value!r}.")
if "/" in value:
raise ValueError(f"{label} must not contain '/'. Got {value!r}.")
if value in (".", ".."):
raise ValueError(f"{label} must not be '.' or '..'. Got {value!r}.")
validate_slug("workspace", workspace)
validate_slug("repo", repo)
return f"/repositories/{workspace}/{repo}"


Expand Down
6 changes: 5 additions & 1 deletion bb_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from typing import Any, Iterable
from urllib.parse import quote

from bb_api import BBApiError, BBClient, repo_path
from bb_api import BBApiError, BBClient, repo_path, validate_slug


# ---------------------------------------------------------------------------
Expand Down Expand Up @@ -1127,6 +1127,7 @@ def projects_list(
raise ValueError(f"workspace must not contain '/', got {ws!r}")
if ws in (".", ".."):
raise ValueError(f"workspace must not be '.' or '..', got {ws!r}")
validate_slug("workspace", ws)
if not _is_positive_int(count):
raise ValueError(f"count must be a positive int, got {count!r}")

Expand Down Expand Up @@ -1174,6 +1175,7 @@ def members_list(
raise ValueError(f"workspace must not contain '/', got {ws!r}")
if ws in (".", ".."):
raise ValueError(f"workspace must not be '.' or '..', got {ws!r}")
validate_slug("workspace", ws)
if not _is_positive_int(count):
raise ValueError(f"count must be a positive int, got {count!r}")

Expand Down Expand Up @@ -1226,6 +1228,7 @@ def repos_list(
raise ValueError(f"workspace must not contain '/', got {ws!r}")
if ws in (".", ".."):
raise ValueError(f"workspace must not be '.' or '..', got {ws!r}")
validate_slug("workspace", ws)
if not _is_positive_int(count):
raise ValueError(f"count must be a positive int, got {count!r}")

Expand Down Expand Up @@ -1629,6 +1632,7 @@ def _variables_base(
raise ValueError(f"workspace must not contain '/', got {workspace!r}")
if workspace in (".", ".."):
raise ValueError(f"workspace must not be '.' or '..', got {workspace!r}")
validate_slug("workspace", workspace)
# HYPHEN form — verified against the live API; the underscore
# form 404s at the workspace scope.
return f"/workspaces/{workspace}/pipelines-config/variables/"
Expand Down
Loading
Loading