pacific-cli 0.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.
@@ -0,0 +1,386 @@
1
+ """Signing in in the browser, as an RFC 8252 native app does.
2
+
3
+ The server's own OAuth broker is the authorization server: the CLI reads its
4
+ RFC 8414 document from the server root, holds a loopback port, registers a client
5
+ for exactly that redirect (the broker matches redirects exactly, so a client
6
+ registered on an earlier port could not reuse it), and runs the authorization
7
+ code grant with PKCE. The token is bound (RFC 8707) to the public API, which is
8
+ the only resource a broker token for an OAuth app may name.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hmac
14
+ import secrets
15
+ import time
16
+ from collections.abc import Sequence
17
+ from datetime import UTC, datetime, timedelta
18
+ from http.server import BaseHTTPRequestHandler, HTTPServer
19
+ from types import TracebackType
20
+ from typing import Self, override
21
+ from urllib.parse import parse_qsl, urlencode, urlsplit
22
+
23
+ import httpx
24
+ from pydantic import SecretStr, ValidationError
25
+
26
+ from pacific_cli.auth.config import (
27
+ PACIFIC_CLI_CALLBACK_PATH,
28
+ PACIFIC_CLI_LOGIN_FAILURE_PAGE,
29
+ PACIFIC_CLI_LOGIN_SUCCESS_PAGE,
30
+ PACIFIC_CLI_LOOPBACK_HOST,
31
+ PACIFIC_CLI_OAUTH_CLIENT_NAME,
32
+ PACIFIC_CLI_OAUTH_DISCOVERY_PATH,
33
+ PACIFIC_CLI_OAUTH_GRANT_TYPES,
34
+ PACIFIC_CLI_OAUTH_IDENTITY_SCOPES,
35
+ PACIFIC_CLI_OAUTH_INVALID_GRANT,
36
+ PACIFIC_CLI_OAUTH_RESPONSE_TYPE,
37
+ PACIFIC_CLI_OAUTH_STATE_ENTROPY_BYTES,
38
+ PACIFIC_CLI_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD,
39
+ PACIFIC_CLI_PKCE_METHOD,
40
+ PacificCliSettings,
41
+ )
42
+ from pacific_cli.auth.types import (
43
+ PacificCliBrowserOpener,
44
+ PacificCliClientRegistration,
45
+ PacificCliError,
46
+ PacificCliLoopbackCallback,
47
+ PacificCliOAuthClientId,
48
+ PacificCliOAuthCredential,
49
+ PacificCliOAuthErrorBody,
50
+ PacificCliOAuthMetadata,
51
+ PacificCliOAuthTokens,
52
+ PacificCliPkce,
53
+ PacificCliProbeEnvelope,
54
+ PacificCliRegisteredClient,
55
+ PacificCliSessionEndedError,
56
+ PacificCliSignedIn,
57
+ PacificCliTokenResponse,
58
+ )
59
+ from pacific_cli.config import PACIFIC_CLI_PROBE_PATH, PACIFIC_CLI_PUBLIC_API_PREFIX
60
+
61
+
62
+ class PacificCliCallbackServer(HTTPServer):
63
+ """A one-request HTTP server on loopback; keeps the first callback it receives."""
64
+
65
+ callback: PacificCliLoopbackCallback | None = None
66
+
67
+
68
+ class PacificCliCallbackHandler(BaseHTTPRequestHandler):
69
+ """Answers the browser's redirect, and anything else on the port with a 404."""
70
+
71
+ def do_GET(self) -> None: # noqa: N802 -- the name BaseHTTPRequestHandler dispatches to
72
+ parsed = urlsplit(self.path)
73
+ if parsed.path != PACIFIC_CLI_CALLBACK_PATH:
74
+ self.send_error(404)
75
+ return
76
+ callback = PacificCliLoopbackCallback.model_validate(
77
+ dict(parse_qsl(parsed.query))
78
+ )
79
+ server = self.server
80
+ if not isinstance(server, PacificCliCallbackServer):
81
+ raise TypeError("the callback handler serves only PacificCliCallbackServer")
82
+ if server.callback is None:
83
+ server.callback = callback
84
+ page = (
85
+ PACIFIC_CLI_LOGIN_SUCCESS_PAGE
86
+ if callback.code is not None and callback.error is None
87
+ else PACIFIC_CLI_LOGIN_FAILURE_PAGE
88
+ ).encode()
89
+ self.send_response(200)
90
+ self.send_header("Content-Type", "text/html; charset=utf-8")
91
+ self.send_header("Content-Length", str(len(page)))
92
+ self.end_headers()
93
+ self.wfile.write(page)
94
+
95
+ @override
96
+ def log_message(self, format: str, *args: object) -> None: # noqa: A002 -- the stdlib's parameter name
97
+ """Quiet: the default writes every request to stderr, query string (the code) included."""
98
+
99
+
100
+ class PacificCliLoopbackListener:
101
+ """A loopback port held open for the length of one sign-in."""
102
+
103
+ def __init__(self) -> None:
104
+ # Port 0: the kernel picks a free one, which is why the client is
105
+ # registered only after this is bound.
106
+ self._server = PacificCliCallbackServer(
107
+ (PACIFIC_CLI_LOOPBACK_HOST, 0), PacificCliCallbackHandler
108
+ )
109
+
110
+ @property
111
+ def redirect_uri(self) -> str:
112
+ port = self._server.server_address[1]
113
+ return f"http://{PACIFIC_CLI_LOOPBACK_HOST}:{port}{PACIFIC_CLI_CALLBACK_PATH}"
114
+
115
+ def wait(self, *, timeout: timedelta) -> PacificCliLoopbackCallback:
116
+ """Serve until the browser comes back, or ``timeout`` passes."""
117
+ deadline = time.monotonic() + timeout.total_seconds()
118
+ self._server.timeout = 0.5
119
+ while self._server.callback is None:
120
+ if time.monotonic() >= deadline:
121
+ raise PacificCliError(
122
+ "Timed out waiting for the browser sign-in; run `pacific auth login` again"
123
+ )
124
+ self._server.handle_request()
125
+ return self._server.callback
126
+
127
+ def __enter__(self) -> Self:
128
+ return self
129
+
130
+ def __exit__(
131
+ self,
132
+ exc_type: type[BaseException] | None,
133
+ exc: BaseException | None,
134
+ traceback: TracebackType | None,
135
+ ) -> None:
136
+ self._server.server_close()
137
+
138
+
139
+ class PacificCliOAuthService:
140
+ """Browser sign-in, refresh and sign-out against a Pacific server's OAuth broker."""
141
+
142
+ def __init__(self, http: httpx.Client, *, settings: PacificCliSettings) -> None:
143
+ self._http = http
144
+ self._settings = settings
145
+
146
+ def discover(self, base_url: str) -> PacificCliOAuthMetadata:
147
+ """The broker's RFC 8414 document, which Pacific serves at the server root."""
148
+ url = f"{base_url}{PACIFIC_CLI_OAUTH_DISCOVERY_PATH}"
149
+ response = self._http.get(url)
150
+ if response.status_code == httpx.codes.NOT_FOUND:
151
+ raise PacificCliError(
152
+ f"{base_url} offers no browser sign-in; use an API key instead: "
153
+ "`pacific auth set-key`"
154
+ )
155
+ self._raise_for_error(response, step="read the server's sign-in settings")
156
+ try:
157
+ metadata = PacificCliOAuthMetadata.model_validate_json(response.content)
158
+ except ValidationError as exc:
159
+ raise PacificCliError(
160
+ f"{url} is not an OAuth authorization server document: {exc}"
161
+ ) from exc
162
+ methods = metadata.code_challenge_methods_supported
163
+ if methods and PACIFIC_CLI_PKCE_METHOD not in methods:
164
+ raise PacificCliError(
165
+ f"The server's sign-in does not take PKCE {PACIFIC_CLI_PKCE_METHOD}; "
166
+ "use an API key instead: `pacific auth set-key`"
167
+ )
168
+ return metadata
169
+
170
+ def login(
171
+ self,
172
+ base_url: str,
173
+ *,
174
+ scopes: Sequence[str],
175
+ open_browser: PacificCliBrowserOpener,
176
+ ) -> PacificCliSignedIn:
177
+ """Run the browser sign-in, and keep the session only if the public API takes it.
178
+
179
+ ``scopes`` are the API scopes the session may use; none asks for the
180
+ member's full access. The server refuses a scope it does not define, and
181
+ the refusal comes back through the browser like any other.
182
+
183
+ A deployment can run the broker and still not accept its tokens on the
184
+ public API (its kill switch is off). Such a session would 401 on every
185
+ command, so it is revoked here instead of kept.
186
+ """
187
+ server = self.discover(base_url)
188
+ resource = f"{base_url}{PACIFIC_CLI_PUBLIC_API_PREFIX}"
189
+ with PacificCliLoopbackListener() as listener:
190
+ redirect_uri = listener.redirect_uri
191
+ client_id = self._register(server, redirect_uri=redirect_uri)
192
+ pkce = PacificCliPkce.generate()
193
+ state = secrets.token_urlsafe(PACIFIC_CLI_OAUTH_STATE_ENTROPY_BYTES)
194
+ request = {
195
+ "response_type": PACIFIC_CLI_OAUTH_RESPONSE_TYPE,
196
+ "client_id": client_id,
197
+ "redirect_uri": redirect_uri,
198
+ "state": state,
199
+ "code_challenge": pkce.challenge,
200
+ "code_challenge_method": PACIFIC_CLI_PKCE_METHOD,
201
+ "resource": resource,
202
+ }
203
+ if scopes:
204
+ request["scope"] = " ".join(
205
+ dict.fromkeys([*PACIFIC_CLI_OAUTH_IDENTITY_SCOPES, *scopes])
206
+ )
207
+ query = urlencode(request)
208
+ open_browser(url=f"{server.authorization_endpoint}?{query}")
209
+ callback = listener.wait(timeout=self._settings.login_timeout)
210
+ code = self._accepted_code(callback, server=server, state=state)
211
+ tokens = self._token(
212
+ server.token_endpoint,
213
+ form={
214
+ "grant_type": "authorization_code",
215
+ "code": code,
216
+ "redirect_uri": redirect_uri,
217
+ "client_id": client_id,
218
+ "code_verifier": pkce.verifier,
219
+ "resource": resource,
220
+ },
221
+ )
222
+ credential = PacificCliOAuthCredential(
223
+ access_token=tokens.access_token,
224
+ refresh_token=tokens.refresh_token,
225
+ expires_at=tokens.expires_at,
226
+ client_id=client_id,
227
+ issuer=server.issuer,
228
+ token_endpoint=server.token_endpoint,
229
+ revocation_endpoint=server.revocation_endpoint,
230
+ resource=resource,
231
+ )
232
+ probe = self._http.get(
233
+ f"{base_url}{PACIFIC_CLI_PROBE_PATH}",
234
+ headers={
235
+ "Authorization": f"Bearer {tokens.access_token.get_secret_value()}"
236
+ },
237
+ )
238
+ if probe.status_code == httpx.codes.UNAUTHORIZED:
239
+ self.revoke(credential)
240
+ raise PacificCliError(
241
+ f"You signed in, but {base_url}'s public API does not accept browser "
242
+ "sessions, so the session was revoked. Use an API key instead: "
243
+ "`pacific auth set-key`"
244
+ )
245
+ if probe.status_code == httpx.codes.FORBIDDEN:
246
+ # Accepted, and scoped without documents:read: the probe's scope.
247
+ return PacificCliSignedIn(credential=credential, probe=None)
248
+ self._raise_for_error(probe, step="check the new session with the API")
249
+ return PacificCliSignedIn(
250
+ credential=credential,
251
+ probe=PacificCliProbeEnvelope.model_validate_json(probe.content).data,
252
+ )
253
+
254
+ def refresh(
255
+ self, credential: PacificCliOAuthCredential
256
+ ) -> PacificCliOAuthCredential:
257
+ """A renewed session. The refresh token rotates, so the old credential is dead after this."""
258
+ return credential.renewed(
259
+ self._token(
260
+ credential.token_endpoint,
261
+ form={
262
+ "grant_type": "refresh_token",
263
+ "refresh_token": credential.refresh_token.get_secret_value(),
264
+ "client_id": credential.client_id,
265
+ "resource": credential.resource,
266
+ },
267
+ )
268
+ )
269
+
270
+ def revoke(self, credential: PacificCliOAuthCredential) -> bool:
271
+ """Revoke the session at the broker; False when the broker offers no revocation."""
272
+ if credential.revocation_endpoint is None:
273
+ return False
274
+ for token in (credential.refresh_token, credential.access_token):
275
+ response = self._http.post(
276
+ credential.revocation_endpoint,
277
+ data={
278
+ "token": token.get_secret_value(),
279
+ "client_id": credential.client_id,
280
+ },
281
+ )
282
+ self._raise_for_error(response, step="revoke the session")
283
+ return True
284
+
285
+ def _register(
286
+ self, server: PacificCliOAuthMetadata, *, redirect_uri: str
287
+ ) -> PacificCliOAuthClientId:
288
+ """RFC 7591 registration of a public client for this one redirect."""
289
+ if server.registration_endpoint is None:
290
+ raise PacificCliError(
291
+ "The server's sign-in does not register command-line clients; "
292
+ "use an API key instead: `pacific auth set-key`"
293
+ )
294
+ request = PacificCliClientRegistration(
295
+ client_name=PACIFIC_CLI_OAUTH_CLIENT_NAME,
296
+ redirect_uris=[redirect_uri],
297
+ grant_types=list(PACIFIC_CLI_OAUTH_GRANT_TYPES),
298
+ response_types=[PACIFIC_CLI_OAUTH_RESPONSE_TYPE],
299
+ token_endpoint_auth_method=PACIFIC_CLI_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD,
300
+ )
301
+ response = self._http.post(
302
+ server.registration_endpoint, json=request.model_dump(mode="json")
303
+ )
304
+ self._raise_for_error(response, step="register the CLI")
305
+ return PacificCliRegisteredClient.model_validate_json(
306
+ response.content
307
+ ).client_id
308
+
309
+ @staticmethod
310
+ def _accepted_code(
311
+ callback: PacificCliLoopbackCallback,
312
+ *,
313
+ server: PacificCliOAuthMetadata,
314
+ state: str,
315
+ ) -> str:
316
+ """The code, once the callback is shown to answer this request from this server."""
317
+ if callback.error is not None:
318
+ reason = (
319
+ f" ({callback.error_description})" if callback.error_description else ""
320
+ )
321
+ raise PacificCliError(f"Sign-in was refused: {callback.error}{reason}")
322
+ if callback.state is None or not hmac.compare_digest(callback.state, state):
323
+ raise PacificCliError(
324
+ "The browser returned a response to a different sign-in; run "
325
+ "`pacific auth login` again"
326
+ )
327
+ # RFC 9207: compared as strings with the issuer the document named.
328
+ if callback.iss is not None and callback.iss != server.issuer:
329
+ raise PacificCliError(
330
+ f"The sign-in came back from {callback.iss}, not {server.issuer}"
331
+ )
332
+ if (
333
+ callback.iss is None
334
+ and server.authorization_response_iss_parameter_supported
335
+ ):
336
+ raise PacificCliError(
337
+ "The sign-in response did not say which server sent it"
338
+ )
339
+ if callback.code is None:
340
+ raise PacificCliError("The browser came back without an authorization code")
341
+ return callback.code
342
+
343
+ def _token(self, endpoint: str, *, form: dict[str, str]) -> PacificCliOAuthTokens:
344
+ """One token request; a refused refresh is a sign-in to repeat, not a fault."""
345
+ response = self._http.post(endpoint, data=form)
346
+ error = self._oauth_error(response)
347
+ if error is not None and error.error == PACIFIC_CLI_OAUTH_INVALID_GRANT:
348
+ raise PacificCliSessionEndedError(
349
+ "Your session has ended; sign in again with `pacific auth login`"
350
+ )
351
+ self._raise_for_error(response, step="get a token")
352
+ token = PacificCliTokenResponse.model_validate_json(response.content)
353
+ if token.expires_in is None or token.refresh_token is None:
354
+ raise PacificCliError(
355
+ "The server's token has no expiry or refresh token, so the CLI "
356
+ "could not keep the session alive"
357
+ )
358
+ return PacificCliOAuthTokens(
359
+ access_token=SecretStr(token.access_token),
360
+ refresh_token=SecretStr(token.refresh_token),
361
+ expires_at=datetime.now(UTC) + timedelta(seconds=token.expires_in),
362
+ )
363
+
364
+ @staticmethod
365
+ def _oauth_error(response: httpx.Response) -> PacificCliOAuthErrorBody | None:
366
+ """The RFC 6749 error a failed response carries, if it carries one."""
367
+ if not response.is_error:
368
+ return None
369
+ try:
370
+ return PacificCliOAuthErrorBody.model_validate_json(response.content)
371
+ except ValidationError:
372
+ return None
373
+
374
+ def _raise_for_error(self, response: httpx.Response, *, step: str) -> None:
375
+ if not response.is_error:
376
+ return
377
+ error = self._oauth_error(response)
378
+ if error is None:
379
+ detail = response.text[:500]
380
+ elif error.error_description:
381
+ detail = f"{error.error}: {error.error_description}"
382
+ else:
383
+ detail = error.error
384
+ raise PacificCliError(
385
+ f"Could not {step} ({response.status_code} from {response.request.url}): {detail}"
386
+ )
@@ -0,0 +1,265 @@
1
+ """The Pacific CLI's profiles: which servers a person talks to, and as whom.
2
+
3
+ Two files under the configuration directory. ``config.json`` names each profile's
4
+ server and the current profile; ``credentials.json`` holds each profile's API key
5
+ or browser session and is owner-only. Splitting them keeps the file a person
6
+ edits or shares free of secrets, as the AWS and GitHub CLIs do.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ from collections.abc import Generator
13
+ from contextlib import contextmanager
14
+ from pathlib import Path
15
+
16
+ from filelock import FileLock, Timeout
17
+ from pydantic import BaseModel, ValidationError
18
+
19
+ from pacific_cli.auth.config import (
20
+ PACIFIC_CLI_CONFIG_DIR_MODE,
21
+ PACIFIC_CLI_CONFIG_FILE_MODE,
22
+ PACIFIC_CLI_CONFIG_FILE_NAME,
23
+ PACIFIC_CLI_CREDENTIALS_FILE_MODE,
24
+ PACIFIC_CLI_CREDENTIALS_FILE_NAME,
25
+ PACIFIC_CLI_CREDENTIALS_LOCK_FILE_NAME,
26
+ PacificCliEnvironment,
27
+ PacificCliSettings,
28
+ )
29
+ from pacific_cli.auth.types import (
30
+ PacificCliApiKeyCredential,
31
+ PacificCliConfig,
32
+ PacificCliCredential,
33
+ PacificCliCredentials,
34
+ PacificCliError,
35
+ PacificCliProfile,
36
+ PacificCliProfileName,
37
+ PacificCliProfileSource,
38
+ PacificCliResolvedProfile,
39
+ )
40
+
41
+
42
+ class PacificCliProfileService:
43
+ """Reads and writes profiles and credentials, and picks the one a command runs as."""
44
+
45
+ def __init__(
46
+ self, settings: PacificCliSettings, *, environment: PacificCliEnvironment
47
+ ) -> None:
48
+ self._directory = settings.resolved_config_dir()
49
+ self._environment = environment
50
+ self._lock_timeout = settings.credentials_lock_timeout
51
+ # One lock object per service, so a save inside a held block re-enters
52
+ # it rather than waiting on itself.
53
+ self._credentials_lock = FileLock(
54
+ self._directory / PACIFIC_CLI_CREDENTIALS_LOCK_FILE_NAME,
55
+ timeout=settings.credentials_lock_timeout.total_seconds(),
56
+ )
57
+
58
+ @property
59
+ def directory(self) -> Path:
60
+ return self._directory
61
+
62
+ def config(self) -> PacificCliConfig:
63
+ return (
64
+ self._read(
65
+ self._directory / PACIFIC_CLI_CONFIG_FILE_NAME, model=PacificCliConfig
66
+ )
67
+ or PacificCliConfig()
68
+ )
69
+
70
+ def credentials(self) -> PacificCliCredentials:
71
+ return (
72
+ self._read(
73
+ self._directory / PACIFIC_CLI_CREDENTIALS_FILE_NAME,
74
+ model=PacificCliCredentials,
75
+ )
76
+ or PacificCliCredentials()
77
+ )
78
+
79
+ def add(
80
+ self,
81
+ name: PacificCliProfileName,
82
+ *,
83
+ base_url: str,
84
+ make_current: bool,
85
+ ) -> PacificCliProfile:
86
+ """Create or repoint a profile. Repointing signs it out: its credential was for the old server."""
87
+ config = self.config()
88
+ profile = PacificCliProfile(base_url=base_url)
89
+ previous = config.profiles.get(name)
90
+ if previous is not None and previous.base_url != profile.base_url:
91
+ self.clear_credential(name)
92
+ current = (
93
+ name
94
+ if make_current or config.current_profile is None
95
+ else config.current_profile
96
+ )
97
+ self._write_config(
98
+ PacificCliConfig(
99
+ current_profile=current, profiles={**config.profiles, name: profile}
100
+ )
101
+ )
102
+ return profile
103
+
104
+ def remove(self, name: PacificCliProfileName) -> None:
105
+ config = self.config()
106
+ if name not in config.profiles:
107
+ raise PacificCliError(f"No profile named {name!r}")
108
+ self.clear_credential(name)
109
+ remaining = {
110
+ key: value for key, value in config.profiles.items() if key != name
111
+ }
112
+ current = None if config.current_profile == name else config.current_profile
113
+ self._write_config(
114
+ PacificCliConfig(current_profile=current, profiles=remaining)
115
+ )
116
+
117
+ def use(self, name: PacificCliProfileName) -> None:
118
+ config = self.config()
119
+ if name not in config.profiles:
120
+ raise PacificCliError(
121
+ f"No profile named {name!r}; add it with `pacific profile add {name} --base-url URL`"
122
+ )
123
+ self._write_config(config.model_copy(update={"current_profile": name}))
124
+
125
+ @contextmanager
126
+ def credentials_locked(self) -> Generator[None]:
127
+ """Hold the credentials against every other pacific command until the block ends.
128
+
129
+ A read that decides a write (renewing a session, replacing one profile's
130
+ credential among several) happens inside it, so a second command sees
131
+ the first one's result instead of overwriting it or spending the same
132
+ refresh token.
133
+ """
134
+ self._directory.mkdir(
135
+ mode=PACIFIC_CLI_CONFIG_DIR_MODE, parents=True, exist_ok=True
136
+ )
137
+ try:
138
+ self._credentials_lock.acquire()
139
+ except Timeout as exc:
140
+ raise PacificCliError(
141
+ f"Another pacific command has held {self._credentials_lock.lock_file} "
142
+ f"for {self._lock_timeout}; let it finish and run this again"
143
+ ) from exc
144
+ try:
145
+ yield
146
+ finally:
147
+ self._credentials_lock.release()
148
+
149
+ def save_credential(
150
+ self, name: PacificCliProfileName, *, credential: PacificCliCredential
151
+ ) -> None:
152
+ with self.credentials_locked():
153
+ stored = self.credentials()
154
+ self._write_credentials(
155
+ PacificCliCredentials(profiles={**stored.profiles, name: credential})
156
+ )
157
+
158
+ def clear_credential(
159
+ self, name: PacificCliProfileName
160
+ ) -> PacificCliCredential | None:
161
+ """Forget a profile's credential; returns what was stored so a caller can revoke it."""
162
+ with self.credentials_locked():
163
+ stored = self.credentials()
164
+ credential = stored.profiles.get(name)
165
+ if credential is None:
166
+ return None
167
+ self._write_credentials(
168
+ PacificCliCredentials(
169
+ profiles={
170
+ key: value
171
+ for key, value in stored.profiles.items()
172
+ if key != name
173
+ }
174
+ )
175
+ )
176
+ return credential
177
+
178
+ def resolve(
179
+ self, requested: PacificCliProfileName | None
180
+ ) -> PacificCliResolvedProfile:
181
+ """The profile a command runs as: ``--profile``, then ``PACIFIC_PROFILE``, then the current one.
182
+
183
+ With none of those, ``PACIFIC_BASE_URL`` (and ``PACIFIC_API_KEY``) stand
184
+ in for a profile, which is how a CI job runs without a config file.
185
+ ``PACIFIC_API_KEY`` replaces whichever profile's credential is chosen.
186
+ """
187
+ environment = self._environment
188
+ config = self.config()
189
+ if requested is not None:
190
+ source, name = PacificCliProfileSource.FLAG, requested
191
+ elif environment.profile is not None:
192
+ source, name = PacificCliProfileSource.ENVIRONMENT, environment.profile
193
+ else:
194
+ source, name = PacificCliProfileSource.CURRENT, config.current_profile
195
+ env_credential = (
196
+ PacificCliApiKeyCredential(api_key=environment.api_key)
197
+ if environment.api_key is not None
198
+ else None
199
+ )
200
+ if name is None:
201
+ if environment.base_url is None:
202
+ raise PacificCliError(
203
+ "No profile selected. Add one with "
204
+ "`pacific profile add NAME --base-url URL`, or set "
205
+ "PACIFIC_BASE_URL and PACIFIC_API_KEY."
206
+ )
207
+ return PacificCliResolvedProfile(
208
+ name=None,
209
+ source=PacificCliProfileSource.ENVIRONMENT_ONLY,
210
+ base_url=environment.base_url,
211
+ credential=env_credential,
212
+ credential_from_environment=env_credential is not None,
213
+ )
214
+ profile = config.profiles.get(name)
215
+ if profile is None:
216
+ raise PacificCliError(
217
+ f"No profile named {name!r} (chosen by {source.value}); "
218
+ f"add it with `pacific profile add {name} --base-url URL`"
219
+ )
220
+ return PacificCliResolvedProfile(
221
+ name=name,
222
+ source=source,
223
+ base_url=profile.base_url,
224
+ credential=(
225
+ env_credential
226
+ if env_credential is not None
227
+ else self.credentials().profiles.get(name)
228
+ ),
229
+ credential_from_environment=env_credential is not None,
230
+ )
231
+
232
+ def _write_config(self, config: PacificCliConfig) -> None:
233
+ self._write(
234
+ self._directory / PACIFIC_CLI_CONFIG_FILE_NAME,
235
+ model=config,
236
+ mode=PACIFIC_CLI_CONFIG_FILE_MODE,
237
+ )
238
+
239
+ def _write_credentials(self, credentials: PacificCliCredentials) -> None:
240
+ self._write(
241
+ self._directory / PACIFIC_CLI_CREDENTIALS_FILE_NAME,
242
+ model=credentials,
243
+ mode=PACIFIC_CLI_CREDENTIALS_FILE_MODE,
244
+ )
245
+
246
+ @staticmethod
247
+ def _read[ModelT: BaseModel](path: Path, *, model: type[ModelT]) -> ModelT | None:
248
+ if not path.exists():
249
+ return None
250
+ try:
251
+ return model.model_validate_json(path.read_text(encoding="utf-8"))
252
+ except ValidationError as exc:
253
+ raise PacificCliError(f"{path} is not valid: {exc}") from exc
254
+
255
+ def _write(self, path: Path, *, model: BaseModel, mode: int) -> None:
256
+ """Replace ``path`` atomically, created with ``mode`` so a secret is never briefly world-readable."""
257
+ self._directory.mkdir(
258
+ mode=PACIFIC_CLI_CONFIG_DIR_MODE, parents=True, exist_ok=True
259
+ )
260
+ staging = path.with_name(f".{path.name}.{os.getpid()}.tmp")
261
+ descriptor = os.open(staging, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
262
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
263
+ handle.write(model.model_dump_json(indent=2))
264
+ handle.write("\n")
265
+ os.replace(staging, path)