BerriAI/litellm · error · Exception

Authentication failed. Check your BitBucket access token and

Error message

Authentication failed. Check your BitBucket access token and permissions.

What it means

Raised by BitBucketClient.get_file when BitBucket returns 401 Unauthorized: the credentials themselves were rejected. Distinguished from 403 (error 335) — 401 means the token/app password is invalid, expired, or the Authorization header scheme does not match auth_method. The client sends Bearer tokens for auth_method 'token' and Basic for 'basic' with username.

Source

Thrown at litellm/integrations/bitbucket/bitbucket_client.py:114

                return response.text
            else:
                # For binary files or when content-type is not text, try to decode as base64
                try:
                    return base64.b64decode(response.content).decode("utf-8")
                except Exception:
                    return response.text

        except Exception as e:
            # Check if it's an HTTP error
            if hasattr(e, "response") and hasattr(e.response, "status_code"):
                if e.response.status_code == 404:
                    return None
                elif e.response.status_code == 403:
                    raise Exception(
                        f"Access denied to file '{file_path}'. Check your BitBucket permissions for workspace '{self.workspace}' and repository '{self.repository}'."
                    )
                elif e.response.status_code == 401:
                    raise Exception("Authentication failed. Check your BitBucket access token and permissions.")
                else:
                    raise Exception(f"Failed to fetch file '{file_path}': {e}")
            else:
                raise Exception(f"Error fetching file '{file_path}': {e}")

    def list_files(self, directory_path: str = "", file_extension: str = ".prompt") -> list[str]:
        """
        List files in a directory with a specific extension.

        Args:
            directory_path: Directory path in the repository (empty for root)
            file_extension: File extension to filter by (default: .prompt)

        Returns:
            List of file paths
        """
        safe_dir: Final = _sanitize_file_path(directory_path) if directory_path else ""
        url: Final = f"{self.base_url}/repositories/{self.workspace}/{self.repository}/src/{self.branch}/{safe_dir}"

View on GitHub (pinned to 6c2dcb801b)

Solutions

  1. Regenerate the app password / token in Bitbucket and update the config
  2. Strip whitespace: access_token.strip() when loading from env
  3. For basic auth set both username and access_token (app password); for token auth use a valid API token with auth_method 'token'
  4. Verify the credential with a direct curl to the BitBucket API before retrying through litellm

Example fix

# before
config = {"workspace": "w", "repository": "r", "access_token": os.getenv("BB_TOKEN"), "auth_method": "basic"}  # username missing -> 401

# after
config = {
    "workspace": "w", "repository": "r",
    "access_token": os.environ["BB_APP_PASSWORD"].strip(),
    "auth_method": "basic",
    "username": "my-user",
}
Defensive patterns

Strategy: try-catch

Validate before calling

import httpx

def credentials_valid(workspace: str, token: str) -> bool:
    r = httpx.get(
        f"https://api.bitbucket.org/2.0/repositories/{workspace}",
        auth=("x-token-auth", token),
        timeout=10,
    )
    return r.status_code == 200  # 401 means bad credentials

Try / catch

try:
    content = client.get_file(path)
except Exception as e:
    if "Authentication failed" in str(e):
        raise CredentialsError("BitBucket token invalid/expired — regenerate it") from e
    raise

Prevention

When it happens

Trigger: Expired or revoked app password; access_token containing whitespace/newline from copy-paste; auth_method 'basic' but username not set so Basic header never added (falls back to no/Bearer auth); using an OAuth token where an app password is expected.

Common situations: App passwords pasted with a trailing newline in env vars; token revoked when the owner changed their Bitbucket password; misconfigured auth_method mismatching the credential type; base64 of 'username:password' built from empty username.

Understand the failure class

Related errors


AI-assisted analysis of BerriAI/litellm@6c2dcb801b (2026-08-15). Data as JSON: /api/errors/0adbe8c16c0d3ad0. Report an issue: GitHub.