bitbucket-unofficial-cli 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. bitbucket_unofficial_cli/__init__.py +3 -0
  2. bitbucket_unofficial_cli/__main__.py +3 -0
  3. bitbucket_unofficial_cli/_version.py +3 -0
  4. bitbucket_unofficial_cli/auth/__init__.py +0 -0
  5. bitbucket_unofficial_cli/auth/authorization_code.py +61 -0
  6. bitbucket_unofficial_cli/auth/callback_server.py +91 -0
  7. bitbucket_unofficial_cli/auth/credentials.py +138 -0
  8. bitbucket_unofficial_cli/auth/env_store.py +44 -0
  9. bitbucket_unofficial_cli/auth/file_store.py +49 -0
  10. bitbucket_unofficial_cli/auth/keyring_store.py +62 -0
  11. bitbucket_unofficial_cli/auth/oauth.py +143 -0
  12. bitbucket_unofficial_cli/auth/resolver.py +34 -0
  13. bitbucket_unofficial_cli/commands/__init__.py +0 -0
  14. bitbucket_unofficial_cli/commands/annotation.py +150 -0
  15. bitbucket_unofficial_cli/commands/auth.py +283 -0
  16. bitbucket_unofficial_cli/commands/branch.py +66 -0
  17. bitbucket_unofficial_cli/commands/branch_restriction.py +126 -0
  18. bitbucket_unofficial_cli/commands/branching_model.py +104 -0
  19. bitbucket_unofficial_cli/commands/commit.py +187 -0
  20. bitbucket_unofficial_cli/commands/commit_comment.py +117 -0
  21. bitbucket_unofficial_cli/commands/commit_meta.py +153 -0
  22. bitbucket_unofficial_cli/commands/config.py +49 -0
  23. bitbucket_unofficial_cli/commands/default_reviewer.py +96 -0
  24. bitbucket_unofficial_cli/commands/deploy_key.py +119 -0
  25. bitbucket_unofficial_cli/commands/deployment.py +39 -0
  26. bitbucket_unofficial_cli/commands/download.py +82 -0
  27. bitbucket_unofficial_cli/commands/environment.py +179 -0
  28. bitbucket_unofficial_cli/commands/hook_event.py +48 -0
  29. bitbucket_unofficial_cli/commands/member.py +32 -0
  30. bitbucket_unofficial_cli/commands/permission.py +93 -0
  31. bitbucket_unofficial_cli/commands/permission_config.py +222 -0
  32. bitbucket_unofficial_cli/commands/pipeline.py +257 -0
  33. bitbucket_unofficial_cli/commands/pipeline_runner.py +107 -0
  34. bitbucket_unofficial_cli/commands/pipeline_schedule.py +138 -0
  35. bitbucket_unofficial_cli/commands/pipeline_settings.py +246 -0
  36. bitbucket_unofficial_cli/commands/pipeline_variable.py +116 -0
  37. bitbucket_unofficial_cli/commands/pr.py +379 -0
  38. bitbucket_unofficial_cli/commands/pr_comment.py +133 -0
  39. bitbucket_unofficial_cli/commands/pr_meta.py +76 -0
  40. bitbucket_unofficial_cli/commands/pr_task.py +114 -0
  41. bitbucket_unofficial_cli/commands/project.py +108 -0
  42. bitbucket_unofficial_cli/commands/ref.py +30 -0
  43. bitbucket_unofficial_cli/commands/repo.py +179 -0
  44. bitbucket_unofficial_cli/commands/repo_property.py +49 -0
  45. bitbucket_unofficial_cli/commands/report.py +105 -0
  46. bitbucket_unofficial_cli/commands/search.py +48 -0
  47. bitbucket_unofficial_cli/commands/snippet.py +229 -0
  48. bitbucket_unofficial_cli/commands/snippet_comment.py +102 -0
  49. bitbucket_unofficial_cli/commands/snippet_revision.py +71 -0
  50. bitbucket_unofficial_cli/commands/source.py +119 -0
  51. bitbucket_unofficial_cli/commands/tag.py +67 -0
  52. bitbucket_unofficial_cli/commands/team.py +114 -0
  53. bitbucket_unofficial_cli/commands/user.py +32 -0
  54. bitbucket_unofficial_cli/commands/user_keys.py +195 -0
  55. bitbucket_unofficial_cli/commands/user_variable.py +113 -0
  56. bitbucket_unofficial_cli/commands/webhook.py +118 -0
  57. bitbucket_unofficial_cli/commands/workspace.py +94 -0
  58. bitbucket_unofficial_cli/config/__init__.py +0 -0
  59. bitbucket_unofficial_cli/config/paths.py +25 -0
  60. bitbucket_unofficial_cli/config/settings.py +73 -0
  61. bitbucket_unofficial_cli/config/store.py +56 -0
  62. bitbucket_unofficial_cli/main.py +175 -0
  63. bitbucket_unofficial_cli/output/__init__.py +0 -0
  64. bitbucket_unofficial_cli/output/columns.py +459 -0
  65. bitbucket_unofficial_cli/output/formats.py +85 -0
  66. bitbucket_unofficial_cli/output/registry.py +29 -0
  67. bitbucket_unofficial_cli/output/renderer.py +79 -0
  68. bitbucket_unofficial_cli/runtime/__init__.py +0 -0
  69. bitbucket_unofficial_cli/runtime/client_factory.py +64 -0
  70. bitbucket_unofficial_cli/runtime/context.py +150 -0
  71. bitbucket_unofficial_cli/runtime/errors.py +91 -0
  72. bitbucket_unofficial_cli/runtime/exit_codes.py +15 -0
  73. bitbucket_unofficial_cli/runtime/params.py +94 -0
  74. bitbucket_unofficial_cli/runtime/scope.py +37 -0
  75. bitbucket_unofficial_cli/services/__init__.py +0 -0
  76. bitbucket_unofficial_cli/services/accounts.py +24 -0
  77. bitbucket_unofficial_cli/services/files.py +22 -0
  78. bitbucket_unofficial_cli/services/jsonvalue.py +24 -0
  79. bitbucket_unofficial_cli/services/listing.py +70 -0
  80. bitbucket_unofficial_cli/services/payloads.py +67 -0
  81. bitbucket_unofficial_cli/services/secrets.py +48 -0
  82. bitbucket_unofficial_cli-1.1.0.dist-info/METADATA +288 -0
  83. bitbucket_unofficial_cli-1.1.0.dist-info/RECORD +86 -0
  84. bitbucket_unofficial_cli-1.1.0.dist-info/WHEEL +4 -0
  85. bitbucket_unofficial_cli-1.1.0.dist-info/entry_points.txt +2 -0
  86. bitbucket_unofficial_cli-1.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,3 @@
1
+ from bitbucket_unofficial_cli._version import __version__
2
+
3
+ __all__ = ["__version__"]
@@ -0,0 +1,3 @@
1
+ from bitbucket_unofficial_cli.main import run
2
+
3
+ run()
@@ -0,0 +1,3 @@
1
+ from importlib.metadata import version
2
+
3
+ __version__ = version("bitbucket-unofficial-cli")
File without changes
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import secrets
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING
6
+ from typing import Final
7
+
8
+ from bitbucket_unofficial_cli.auth.callback_server import CallbackServer
9
+ from bitbucket_unofficial_cli.auth.callback_server import parse_redirect
10
+ from bitbucket_unofficial_cli.auth.oauth import authorize_url
11
+ from bitbucket_unofficial_cli.runtime.errors import CliError
12
+ from bitbucket_unofficial_cli.runtime.exit_codes import ExitCode
13
+
14
+ if TYPE_CHECKING:
15
+ from collections.abc import Callable
16
+
17
+ from bitbucket_unofficial_cli.auth.callback_server import CallbackResult
18
+ from bitbucket_unofficial_cli.auth.credentials import OAuthCredential
19
+ from bitbucket_unofficial_cli.auth.oauth import OAuthClient
20
+ from bitbucket_unofficial_cli.auth.oauth import OAuthConsumer
21
+
22
+ CALLBACK_TIMEOUT: Final = 300.0
23
+
24
+
25
+ # Everything that varies between the browser flow and the paste-the-URL flow is injected, so the
26
+ # command stays thin and tests drive both without a real browser or terminal.
27
+ @dataclass(frozen=True, slots=True)
28
+ class AuthorizationCodeFlow:
29
+ oauth: OAuthClient
30
+ open_browser: Callable[[str], object]
31
+ notify: Callable[[str], None]
32
+ read_redirect: Callable[[], str]
33
+ timeout: float = CALLBACK_TIMEOUT
34
+
35
+ def authorize(self, consumer: OAuthConsumer, *, port: int, use_browser: bool) -> OAuthCredential:
36
+ state = secrets.token_urlsafe(24)
37
+ url = authorize_url(consumer.client_id, state)
38
+ result = self._browser_result(url, port) if use_browser else self._pasted_result(url)
39
+ if result.error:
40
+ message = f"Bitbucket denied the authorization: {result.error}"
41
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION)
42
+ if not secrets.compare_digest((result.state or "").encode(), state.encode()):
43
+ message = "The authorization reply does not match this login (state mismatch)."
44
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION)
45
+ if not result.code:
46
+ message = "The authorization reply carries no code."
47
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION)
48
+ return self.oauth.exchange_code(consumer, result.code)
49
+
50
+ def _browser_result(self, url: str, port: int) -> CallbackResult:
51
+ server = CallbackServer(port)
52
+ try:
53
+ self.notify(f"Opening your browser to authorize; if it does not open, visit:\n{url}")
54
+ self.open_browser(url)
55
+ return server.wait(self.timeout)
56
+ finally:
57
+ server.close()
58
+
59
+ def _pasted_result(self, url: str) -> CallbackResult:
60
+ self.notify(f"Open this URL, authorize, then paste the address you were redirected to:\n{url}")
61
+ return parse_redirect(self.read_redirect().strip())
@@ -0,0 +1,91 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from dataclasses import dataclass
5
+ from http.server import BaseHTTPRequestHandler
6
+ from http.server import HTTPServer
7
+ from typing import Final
8
+ from typing import cast
9
+ from typing import override
10
+ from urllib.parse import parse_qs
11
+ from urllib.parse import urlparse
12
+
13
+ from bitbucket_unofficial_cli.runtime.errors import CliError
14
+ from bitbucket_unofficial_cli.runtime.exit_codes import ExitCode
15
+
16
+ LOOPBACK: Final = "127.0.0.1"
17
+ CALLBACK_PATH: Final = "/callback"
18
+ DEFAULT_PORT: Final = 8976
19
+ _PAGE: Final = b"<html><body><p>Bitbucket CLI: you can close this tab and return to the terminal.</p></body></html>"
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class CallbackResult:
24
+ code: str | None = None
25
+ state: str | None = None
26
+ error: str | None = None
27
+
28
+
29
+ def parse_redirect(url: str) -> CallbackResult:
30
+ query = parse_qs(urlparse(url).query)
31
+
32
+ def first(name: str) -> str | None:
33
+ values = query.get(name)
34
+ return values[0] if values else None
35
+
36
+ return CallbackResult(code=first("code"), state=first("state"), error=first("error_description") or first("error"))
37
+
38
+
39
+ class _Server(HTTPServer):
40
+ result: CallbackResult | None = None
41
+
42
+
43
+ class _Handler(BaseHTTPRequestHandler):
44
+ def do_GET(self) -> None:
45
+ if urlparse(self.path).path != CALLBACK_PATH:
46
+ self.send_error(404)
47
+ return
48
+ # HTTPServer types the attribute as its base class; this handler is only ever built by _Server.
49
+ cast("_Server", self.server).result = parse_redirect(self.path)
50
+ self.send_response(200)
51
+ self.send_header("Content-Type", "text/html; charset=utf-8")
52
+ self.send_header("Content-Length", str(len(_PAGE)))
53
+ self.end_headers()
54
+ self.wfile.write(_PAGE)
55
+
56
+ # Keeps the terminal clean: the CLI reports its own progress.
57
+ @override
58
+ def log_message(self, format: str, *args: object) -> None:
59
+ del format, args
60
+
61
+
62
+ # Bound to the loopback interface only, and it serves just the one callback request.
63
+ class CallbackServer:
64
+ def __init__(self, port: int = DEFAULT_PORT) -> None:
65
+ try:
66
+ self._server = _Server((LOOPBACK, port), _Handler)
67
+ except OSError as error:
68
+ message = f"Cannot listen on {LOOPBACK}:{port}: {error}"
69
+ raise CliError(
70
+ message,
71
+ exit_code=ExitCode.CONFIGURATION,
72
+ hint="Pick another port with --callback-port, or use --no-browser.",
73
+ ) from error
74
+
75
+ @property
76
+ def port(self) -> int:
77
+ return int(self._server.server_address[1])
78
+
79
+ def wait(self, timeout: float) -> CallbackResult:
80
+ deadline = time.monotonic() + timeout
81
+ while self._server.result is None:
82
+ remaining = deadline - time.monotonic()
83
+ if remaining <= 0:
84
+ message = "Timed out waiting for the browser to return to the callback URL."
85
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION, hint="Retry, or use --no-browser.")
86
+ self._server.timeout = remaining
87
+ self._server.handle_request()
88
+ return self._server.result
89
+
90
+ def close(self) -> None:
91
+ self._server.server_close()
@@ -0,0 +1,138 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from dataclasses import asdict
5
+ from dataclasses import dataclass
6
+ from enum import StrEnum
7
+ from typing import Final
8
+ from typing import Literal
9
+ from typing import Protocol
10
+
11
+ _VISIBLE_SUFFIX: Final = 4
12
+
13
+
14
+ class CredentialSource(StrEnum):
15
+ ENVIRONMENT = "environment"
16
+ KEYRING = "keyring"
17
+ FILE = "file"
18
+
19
+
20
+ class OAuthGrant(StrEnum):
21
+ AUTHORIZATION_CODE = "authorization_code"
22
+ CLIENT_CREDENTIALS = "client_credentials"
23
+
24
+
25
+ def mask(secret: str) -> str:
26
+ if len(secret) <= _VISIBLE_SUFFIX:
27
+ return "*" * len(secret)
28
+ return "*" * 8 + secret[-_VISIBLE_SUFFIX:]
29
+
30
+
31
+ # Atlassian API token, sent with the account email as HTTP Basic.
32
+ @dataclass(frozen=True, slots=True)
33
+ class ApiTokenCredential:
34
+ email: str
35
+ api_token: str
36
+ kind: Literal["api_token"] = "api_token"
37
+
38
+ def masked(self) -> str:
39
+ return mask(self.api_token)
40
+
41
+
42
+ # Any ready-made bearer: a repository, project or workspace access token, or a token
43
+ # obtained elsewhere. It is sent as-is and never refreshed.
44
+ @dataclass(frozen=True, slots=True)
45
+ class AccessTokenCredential:
46
+ access_token: str
47
+ kind: Literal["access_token"] = "access_token"
48
+
49
+ def masked(self) -> str:
50
+ return mask(self.access_token)
51
+
52
+
53
+ # An OAuth consumer's token. The client secret is kept so the token can be renewed without
54
+ # asking again; `expires_at` is epoch seconds, and 0 means the expiry is unknown.
55
+ @dataclass(frozen=True, slots=True)
56
+ class OAuthCredential:
57
+ client_id: str
58
+ client_secret: str
59
+ access_token: str
60
+ grant: OAuthGrant
61
+ refresh_token: str | None = None
62
+ expires_at: float = 0
63
+ kind: Literal["oauth"] = "oauth"
64
+
65
+ def masked(self) -> str:
66
+ return mask(self.access_token)
67
+
68
+
69
+ type Credential = ApiTokenCredential | AccessTokenCredential | OAuthCredential # pylint: disable=gajaguar-module-const-naming
70
+
71
+
72
+ @dataclass(frozen=True, slots=True)
73
+ class ResolvedCredential:
74
+ credential: Credential
75
+ source: CredentialSource
76
+
77
+
78
+ def encode(credential: Credential) -> str:
79
+ return json.dumps(asdict(credential))
80
+
81
+
82
+ def _text(payload: dict[str, object], key: str) -> str | None:
83
+ value = payload.get(key)
84
+ return value if isinstance(value, str) and value else None
85
+
86
+
87
+ def _decode_oauth(payload: dict[str, object]) -> OAuthCredential | None:
88
+ client_id = _text(payload, "client_id")
89
+ client_secret = _text(payload, "client_secret")
90
+ access_token = _text(payload, "access_token")
91
+ grant = _text(payload, "grant")
92
+ expires_at = payload.get("expires_at", 0)
93
+ if not (client_id and client_secret and access_token and grant):
94
+ return None
95
+ if grant not in OAuthGrant or not isinstance(expires_at, (int, float)):
96
+ return None
97
+ return OAuthCredential(
98
+ client_id=client_id,
99
+ client_secret=client_secret,
100
+ access_token=access_token,
101
+ grant=OAuthGrant(grant),
102
+ refresh_token=_text(payload, "refresh_token"),
103
+ expires_at=float(expires_at),
104
+ )
105
+
106
+
107
+ def decode(raw: str) -> Credential | None:
108
+ try:
109
+ payload: object = json.loads(raw)
110
+ except ValueError:
111
+ return None
112
+ if not isinstance(payload, dict):
113
+ return None
114
+ kind = payload.get("kind")
115
+ if kind == "api_token":
116
+ email, api_token = _text(payload, "email"), _text(payload, "api_token")
117
+ return ApiTokenCredential(email=email, api_token=api_token) if email and api_token else None
118
+ if kind == "access_token":
119
+ access_token = _text(payload, "access_token")
120
+ return AccessTokenCredential(access_token=access_token) if access_token else None
121
+ if kind == "oauth":
122
+ return _decode_oauth(payload)
123
+ return None
124
+
125
+
126
+ class CredentialStore(Protocol):
127
+ @property
128
+ def source(self) -> CredentialSource: ...
129
+
130
+ def get(self, profile: str) -> Credential | None: ...
131
+
132
+
133
+ class WritableCredentialStore(CredentialStore, Protocol):
134
+ def available(self) -> bool: ...
135
+
136
+ def set(self, profile: str, credential: Credential) -> None: ...
137
+
138
+ def delete(self, profile: str) -> bool: ...
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from bitbucket.config import ACCESS_TOKEN_ENV_VAR
6
+ from bitbucket.config import API_TOKEN_ENV_VAR
7
+ from bitbucket.config import EMAIL_ENV_VAR
8
+
9
+ from bitbucket_unofficial_cli.auth.credentials import AccessTokenCredential
10
+ from bitbucket_unofficial_cli.auth.credentials import ApiTokenCredential
11
+ from bitbucket_unofficial_cli.auth.credentials import CredentialSource
12
+ from bitbucket_unofficial_cli.runtime.errors import CliError
13
+ from bitbucket_unofficial_cli.runtime.exit_codes import ExitCode
14
+
15
+ if TYPE_CHECKING:
16
+ from collections.abc import Mapping
17
+
18
+
19
+ # The environment credential is profile-agnostic: it overrides whatever profile is selected, for CI.
20
+ # It reads the variables the SDK documents, and refuses to guess when both kinds are set, as the SDK does.
21
+ class EnvCredentialStore:
22
+ def __init__(self, environ: Mapping[str, str]) -> None:
23
+ self._environ = environ
24
+
25
+ @property
26
+ def source(self) -> CredentialSource:
27
+ return CredentialSource.ENVIRONMENT
28
+
29
+ def get(self, profile: str) -> ApiTokenCredential | AccessTokenCredential | None:
30
+ del profile
31
+ email = self._environ.get(EMAIL_ENV_VAR)
32
+ api_token = self._environ.get(API_TOKEN_ENV_VAR)
33
+ access_token = self._environ.get(ACCESS_TOKEN_ENV_VAR)
34
+ has_api_token = bool(email and api_token)
35
+ if has_api_token and access_token:
36
+ message = f"Both {API_TOKEN_ENV_VAR} and {ACCESS_TOKEN_ENV_VAR} are set."
37
+ raise CliError(
38
+ message,
39
+ exit_code=ExitCode.CONFIGURATION,
40
+ hint=f"Unset one of them; {ACCESS_TOKEN_ENV_VAR} sends a bearer token, the other sends Basic.",
41
+ )
42
+ if has_api_token and email and api_token:
43
+ return ApiTokenCredential(email=email, api_token=api_token)
44
+ return AccessTokenCredential(access_token=access_token) if access_token else None
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from bitbucket_unofficial_cli.auth.credentials import CredentialSource
6
+ from bitbucket_unofficial_cli.auth.credentials import decode
7
+ from bitbucket_unofficial_cli.auth.credentials import encode
8
+ from bitbucket_unofficial_cli.config.store import read_toml
9
+ from bitbucket_unofficial_cli.config.store import write_private_toml
10
+
11
+ if TYPE_CHECKING:
12
+ from pathlib import Path
13
+
14
+ from bitbucket_unofficial_cli.auth.credentials import Credential
15
+
16
+
17
+ # Plaintext fallback for hosts without a keyring backend; only written on explicit opt-in.
18
+ class FileCredentialStore:
19
+ def __init__(self, path: Path) -> None:
20
+ self.path = path
21
+
22
+ @property
23
+ def source(self) -> CredentialSource:
24
+ return CredentialSource.FILE
25
+
26
+ @staticmethod
27
+ def available() -> bool:
28
+ return True
29
+
30
+ def get(self, profile: str) -> Credential | None:
31
+ raw = self._entries().get(profile)
32
+ return decode(raw) if isinstance(raw, str) else None
33
+
34
+ def set(self, profile: str, credential: Credential) -> None:
35
+ entries = self._entries()
36
+ entries[profile] = encode(credential)
37
+ write_private_toml(self.path, {"profiles": entries})
38
+
39
+ def delete(self, profile: str) -> bool:
40
+ entries = self._entries()
41
+ if profile not in entries:
42
+ return False
43
+ del entries[profile]
44
+ write_private_toml(self.path, {"profiles": entries})
45
+ return True
46
+
47
+ def _entries(self) -> dict[str, object]:
48
+ profiles = read_toml(self.path).get("profiles")
49
+ return dict(profiles) if isinstance(profiles, dict) else {}
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+ from typing import Final
5
+
6
+ import keyring
7
+ from keyring.backends.fail import Keyring as FailKeyring
8
+ from keyring.errors import KeyringError
9
+ from keyring.errors import PasswordDeleteError
10
+
11
+ from bitbucket_unofficial_cli.auth.credentials import CredentialSource
12
+ from bitbucket_unofficial_cli.auth.credentials import decode
13
+ from bitbucket_unofficial_cli.auth.credentials import encode
14
+ from bitbucket_unofficial_cli.runtime.errors import CliError
15
+ from bitbucket_unofficial_cli.runtime.exit_codes import ExitCode
16
+
17
+ if TYPE_CHECKING:
18
+ from bitbucket_unofficial_cli.auth.credentials import Credential
19
+
20
+ SERVICE_NAME: Final = "bitbucket-cli"
21
+
22
+
23
+ class KeyringCredentialStore:
24
+ def __init__(self, service: str = SERVICE_NAME) -> None:
25
+ self._service = service
26
+
27
+ @property
28
+ def source(self) -> CredentialSource:
29
+ return CredentialSource.KEYRING
30
+
31
+ @staticmethod
32
+ def available() -> bool:
33
+ return not isinstance(keyring.get_keyring(), FailKeyring)
34
+
35
+ def get(self, profile: str) -> Credential | None:
36
+ if not self.available():
37
+ return None
38
+ try:
39
+ raw = keyring.get_password(self._service, profile)
40
+ except KeyringError:
41
+ return None
42
+ return decode(raw) if raw else None
43
+
44
+ def set(self, profile: str, credential: Credential) -> None:
45
+ try:
46
+ keyring.set_password(self._service, profile, encode(credential))
47
+ except KeyringError as error:
48
+ message = f"Could not write to the system keyring: {error}"
49
+ raise CliError(
50
+ message,
51
+ exit_code=ExitCode.CONFIGURATION,
52
+ hint="Retry with --insecure-storage to use a 0600 file instead.",
53
+ ) from error
54
+
55
+ def delete(self, profile: str) -> bool:
56
+ if not self.available():
57
+ return False
58
+ try:
59
+ keyring.delete_password(self._service, profile)
60
+ except PasswordDeleteError:
61
+ return False
62
+ return True
@@ -0,0 +1,143 @@
1
+ from __future__ import annotations
2
+
3
+ import time
4
+ from dataclasses import dataclass
5
+ from typing import TYPE_CHECKING
6
+ from typing import Final
7
+ from urllib.parse import urlencode
8
+
9
+ import httpx
10
+
11
+ from bitbucket_unofficial_cli.auth.credentials import OAuthCredential
12
+ from bitbucket_unofficial_cli.auth.credentials import OAuthGrant
13
+ from bitbucket_unofficial_cli.runtime.errors import CliError
14
+ from bitbucket_unofficial_cli.runtime.exit_codes import ExitCode
15
+
16
+ if TYPE_CHECKING:
17
+ from collections.abc import Callable
18
+
19
+ # The Bitbucket SDK leaves the OAuth dance to the application, so this module is the one place the
20
+ # CLI talks to Bitbucket without the SDK: the consumer's authorize and token endpoints.
21
+ AUTHORIZE_URL: Final = "https://bitbucket.org/site/oauth2/authorize"
22
+ TOKEN_URL: Final = "https://bitbucket.org/site/oauth2/access_token" # ruff: ignore[hardcoded-password-string]
23
+ EXPIRY_MARGIN: Final = 60.0
24
+ HTTP_TIMEOUT: Final = 30.0
25
+ LOGIN_HINT: Final = "Run `bitbucket auth login --oauth` to authorize again."
26
+
27
+ type Clock = Callable[[], float] # pylint: disable=gajaguar-module-const-naming
28
+ type HttpFactory = Callable[[], httpx.Client] # pylint: disable=gajaguar-module-const-naming
29
+
30
+
31
+ def default_http() -> httpx.Client:
32
+ return httpx.Client(timeout=HTTP_TIMEOUT)
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class OAuthConsumer:
37
+ client_id: str
38
+ client_secret: str
39
+
40
+
41
+ # Bitbucket sends the user back to the callback URL configured on the consumer, so the
42
+ # authorize URL carries no redirect_uri; `state` is echoed back to bind the reply to this login.
43
+ def authorize_url(client_id: str, state: str) -> str:
44
+ return f"{AUTHORIZE_URL}?{urlencode({'client_id': client_id, 'response_type': 'code', 'state': state})}"
45
+
46
+
47
+ def _failure(response: httpx.Response) -> CliError:
48
+ detail = f"HTTP {response.status_code}"
49
+ try:
50
+ payload: object = response.json()
51
+ except ValueError:
52
+ payload = None
53
+ if isinstance(payload, dict):
54
+ text = payload.get("error_description") or payload.get("error")
55
+ if isinstance(text, str):
56
+ detail = f"{text} ({detail})"
57
+ return CliError(f"Bitbucket rejected the OAuth request: {detail}.", exit_code=ExitCode.AUTHENTICATION)
58
+
59
+
60
+ class OAuthClient:
61
+ def __init__(self, http: HttpFactory = default_http, clock: Clock = time.time) -> None:
62
+ self._http = http
63
+ self._clock = clock
64
+
65
+ def exchange_code(self, consumer: OAuthConsumer, code: str) -> OAuthCredential:
66
+ data = {"grant_type": "authorization_code", "code": code}
67
+ return self._request(consumer, data, grant=OAuthGrant.AUTHORIZATION_CODE, previous_refresh=None)
68
+
69
+ def client_credentials(self, consumer: OAuthConsumer) -> OAuthCredential:
70
+ data = {"grant_type": "client_credentials"}
71
+ return self._request(consumer, data, grant=OAuthGrant.CLIENT_CREDENTIALS, previous_refresh=None)
72
+
73
+ # Client credentials have no refresh token, so renewing means asking again.
74
+ def renew(self, credential: OAuthCredential) -> OAuthCredential:
75
+ consumer = OAuthConsumer(credential.client_id, credential.client_secret)
76
+ if credential.grant is OAuthGrant.CLIENT_CREDENTIALS:
77
+ return self.client_credentials(consumer)
78
+ if not credential.refresh_token:
79
+ message = "The stored OAuth credential has no refresh token."
80
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION, hint=LOGIN_HINT)
81
+ data = {"grant_type": "refresh_token", "refresh_token": credential.refresh_token}
82
+ try:
83
+ return self._request(consumer, data, grant=credential.grant, previous_refresh=credential.refresh_token)
84
+ except CliError as error:
85
+ if error.exit_code is ExitCode.AUTHENTICATION:
86
+ raise CliError(error.message, exit_code=error.exit_code, hint=LOGIN_HINT) from error
87
+ raise
88
+
89
+ def is_expired(self, credential: OAuthCredential) -> bool:
90
+ return credential.expires_at > 0 and self._clock() >= credential.expires_at - EXPIRY_MARGIN
91
+
92
+ def _request(
93
+ self,
94
+ consumer: OAuthConsumer,
95
+ data: dict[str, str],
96
+ *,
97
+ grant: OAuthGrant,
98
+ previous_refresh: str | None,
99
+ ) -> OAuthCredential:
100
+ try:
101
+ with self._http() as http:
102
+ response = http.post(TOKEN_URL, data=data, auth=(consumer.client_id, consumer.client_secret))
103
+ except httpx.HTTPError as error:
104
+ message = f"Could not reach Bitbucket's OAuth endpoint: {error}"
105
+ raise CliError(message, exit_code=ExitCode.UNAVAILABLE) from error
106
+ if response.status_code != httpx.codes.OK:
107
+ raise _failure(response)
108
+ payload: object = response.json()
109
+ body: dict[str, object] = payload if isinstance(payload, dict) else {}
110
+ access_token = body.get("access_token")
111
+ if not isinstance(access_token, str) or not access_token:
112
+ message = "Bitbucket's OAuth reply has no access token."
113
+ raise CliError(message, exit_code=ExitCode.AUTHENTICATION)
114
+ refresh_token = body.get("refresh_token")
115
+ expires_in = body.get("expires_in")
116
+ return OAuthCredential(
117
+ client_id=consumer.client_id,
118
+ client_secret=consumer.client_secret,
119
+ access_token=access_token,
120
+ grant=grant,
121
+ refresh_token=refresh_token if isinstance(refresh_token, str) and refresh_token else previous_refresh,
122
+ expires_at=self._clock() + float(expires_in) if isinstance(expires_in, (int, float)) else 0,
123
+ )
124
+
125
+
126
+ # The SDK calls this on every request, so a long command keeps working across the token's lifetime:
127
+ # it renews shortly before expiry and hands the new credential back to be stored.
128
+ class OAuthTokenProvider:
129
+ def __init__(
130
+ self,
131
+ credential: OAuthCredential,
132
+ oauth: OAuthClient,
133
+ on_renew: Callable[[OAuthCredential], None],
134
+ ) -> None:
135
+ self._credential = credential
136
+ self._oauth = oauth
137
+ self._on_renew = on_renew
138
+
139
+ def __call__(self) -> str:
140
+ if self._oauth.is_expired(self._credential):
141
+ self._credential = self._oauth.renew(self._credential)
142
+ self._on_renew(self._credential)
143
+ return self._credential.access_token
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import TYPE_CHECKING
5
+
6
+ from bitbucket_unofficial_cli.auth.credentials import ResolvedCredential
7
+
8
+ if TYPE_CHECKING:
9
+ from bitbucket_unofficial_cli.auth.credentials import CredentialStore
10
+ from bitbucket_unofficial_cli.auth.credentials import WritableCredentialStore
11
+ from bitbucket_unofficial_cli.auth.env_store import EnvCredentialStore
12
+ from bitbucket_unofficial_cli.auth.file_store import FileCredentialStore
13
+ from bitbucket_unofficial_cli.auth.keyring_store import KeyringCredentialStore
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class CredentialStores:
18
+ environment: EnvCredentialStore
19
+ keyring: KeyringCredentialStore
20
+ file: FileCredentialStore
21
+
22
+ # Precedence order: the first store holding a credential for the profile wins.
23
+ def chain(self) -> tuple[CredentialStore, ...]:
24
+ return (self.environment, self.keyring, self.file)
25
+
26
+ def writable(self) -> tuple[WritableCredentialStore, ...]:
27
+ return (self.keyring, self.file)
28
+
29
+ def resolve(self, profile: str) -> ResolvedCredential | None:
30
+ for store in self.chain():
31
+ credential = store.get(profile)
32
+ if credential is not None:
33
+ return ResolvedCredential(credential=credential, source=store.source)
34
+ return None
File without changes