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.
- pacific_cli/__init__.py +11 -0
- pacific_cli/__main__.py +6 -0
- pacific_cli/auth/__init__.py +1 -0
- pacific_cli/auth/client.py +218 -0
- pacific_cli/auth/commands.py +247 -0
- pacific_cli/auth/config.py +133 -0
- pacific_cli/auth/oauth.py +386 -0
- pacific_cli/auth/profiles.py +265 -0
- pacific_cli/auth/runtime.py +82 -0
- pacific_cli/auth/types.py +388 -0
- pacific_cli/config.py +10 -0
- pacific_cli/documents/__init__.py +1 -0
- pacific_cli/documents/commands.py +171 -0
- pacific_cli/documents/config.py +53 -0
- pacific_cli/documents/service.py +213 -0
- pacific_cli/documents/types.py +176 -0
- pacific_cli/keys/__init__.py +1 -0
- pacific_cli/keys/commands.py +117 -0
- pacific_cli/keys/config.py +11 -0
- pacific_cli/keys/service.py +171 -0
- pacific_cli/keys/types.py +99 -0
- pacific_cli/main.py +58 -0
- pacific_cli/policy/__init__.py +1 -0
- pacific_cli/policy/commands.py +263 -0
- pacific_cli/policy/config.py +33 -0
- pacific_cli/policy/service.py +341 -0
- pacific_cli/policy/types.py +235 -0
- pacific_cli-0.1.0.dist-info/METADATA +185 -0
- pacific_cli-0.1.0.dist-info/RECORD +32 -0
- pacific_cli-0.1.0.dist-info/WHEEL +4 -0
- pacific_cli-0.1.0.dist-info/entry_points.txt +2 -0
- pacific_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
pacific_cli/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""The ``pacific`` command line: a client of a Pacific server's public API.
|
|
2
|
+
|
|
3
|
+
It uploads documents with the labels and attributes access policies match, and
|
|
4
|
+
writes, lists and attaches those policies. It signs in with an API key or in the
|
|
5
|
+
browser through the server's own OAuth broker, and keeps one profile per server
|
|
6
|
+
and identity (``pacific profile``).
|
|
7
|
+
|
|
8
|
+
A standalone project: it talks to the server only over HTTP and imports nothing
|
|
9
|
+
from ``pacific``. Its wire models are checked against the server's published
|
|
10
|
+
OpenAPI document by ``contract_test.py``.
|
|
11
|
+
"""
|
pacific_cli/__main__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Profiles, credentials and sign-in for the ``pacific`` command line."""
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
"""The public API, called as one profile."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Mapping, Sequence
|
|
7
|
+
from contextlib import ExitStack
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from http import HTTPMethod
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
from pydantic import BaseModel, JsonValue, ValidationError
|
|
13
|
+
|
|
14
|
+
from pacific_cli.auth.config import PacificCliSettings
|
|
15
|
+
from pacific_cli.auth.oauth import PacificCliOAuthService
|
|
16
|
+
from pacific_cli.auth.profiles import PacificCliProfileService
|
|
17
|
+
from pacific_cli.auth.types import (
|
|
18
|
+
PacificCliApiError,
|
|
19
|
+
PacificCliApiKeyCredential,
|
|
20
|
+
PacificCliCredential,
|
|
21
|
+
PacificCliError,
|
|
22
|
+
PacificCliErrorBody,
|
|
23
|
+
PacificCliOAuthCredential,
|
|
24
|
+
PacificCliProfileSource,
|
|
25
|
+
PacificCliResolvedProfile,
|
|
26
|
+
PacificCliSessionEndedError,
|
|
27
|
+
PacificCliUploadPart,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
#: A query string's values, as httpx encodes them (a bool becomes ``true``/``false``).
|
|
31
|
+
type PacificCliQueryParams = Mapping[str, str | int | bool]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PacificCliApiClient:
|
|
35
|
+
"""Sends requests to a Pacific server as one profile, renewing a browser session as it goes.
|
|
36
|
+
|
|
37
|
+
A session about to expire is refreshed before the request, and a 401 is
|
|
38
|
+
refreshed and retried once. Either way the rotated session is written back
|
|
39
|
+
to the profile, because the refresh token it replaced is dead.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
profile: PacificCliResolvedProfile,
|
|
45
|
+
*,
|
|
46
|
+
http: httpx.Client,
|
|
47
|
+
profiles: PacificCliProfileService,
|
|
48
|
+
oauth: PacificCliOAuthService,
|
|
49
|
+
settings: PacificCliSettings,
|
|
50
|
+
) -> None:
|
|
51
|
+
self._profile = profile
|
|
52
|
+
self._credential: PacificCliCredential | None = profile.credential
|
|
53
|
+
self._http = http
|
|
54
|
+
self._profiles = profiles
|
|
55
|
+
self._oauth = oauth
|
|
56
|
+
self._settings = settings
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def profile(self) -> PacificCliResolvedProfile:
|
|
60
|
+
return self._profile
|
|
61
|
+
|
|
62
|
+
def bearer(self) -> str:
|
|
63
|
+
"""The token to send now, refreshed first if it is about to expire."""
|
|
64
|
+
match self._credential:
|
|
65
|
+
case None:
|
|
66
|
+
profile = self._profile.name or "PACIFIC_BASE_URL"
|
|
67
|
+
raise PacificCliError(
|
|
68
|
+
f"{profile} is signed out; run `pacific auth login` or `pacific auth set-key`"
|
|
69
|
+
)
|
|
70
|
+
case PacificCliApiKeyCredential(api_key=api_key):
|
|
71
|
+
return api_key.get_secret_value()
|
|
72
|
+
case PacificCliOAuthCredential() as session:
|
|
73
|
+
if session.expires_within(
|
|
74
|
+
self._settings.token_refresh_window, now=datetime.now(UTC)
|
|
75
|
+
):
|
|
76
|
+
session = self._refresh(session)
|
|
77
|
+
return session.access_token.get_secret_value()
|
|
78
|
+
|
|
79
|
+
def request(
|
|
80
|
+
self,
|
|
81
|
+
method: HTTPMethod,
|
|
82
|
+
*,
|
|
83
|
+
path: str,
|
|
84
|
+
params: PacificCliQueryParams | None = None,
|
|
85
|
+
json_body: JsonValue | None = None,
|
|
86
|
+
form: Mapping[str, str] | None = None,
|
|
87
|
+
files: Sequence[PacificCliUploadPart] = (),
|
|
88
|
+
) -> httpx.Response:
|
|
89
|
+
"""Send one request; a refusal raises :class:`PacificCliApiError` with the server's reason."""
|
|
90
|
+
response = self._send(
|
|
91
|
+
method,
|
|
92
|
+
path=path,
|
|
93
|
+
params=params,
|
|
94
|
+
json_body=json_body,
|
|
95
|
+
form=form,
|
|
96
|
+
files=files,
|
|
97
|
+
)
|
|
98
|
+
# Retried once with a fresh token. An upload is retried too: each attempt
|
|
99
|
+
# opens its files anew (see _send).
|
|
100
|
+
# A one-off session (no profile name) is never refreshed: it lives for
|
|
101
|
+
# one command, and a rotated token would have nowhere to be kept.
|
|
102
|
+
if (
|
|
103
|
+
response.status_code == httpx.codes.UNAUTHORIZED
|
|
104
|
+
and isinstance(self._credential, PacificCliOAuthCredential)
|
|
105
|
+
and self._profile.source is not PacificCliProfileSource.ONE_OFF_SIGN_IN
|
|
106
|
+
):
|
|
107
|
+
self._refresh(self._credential)
|
|
108
|
+
response = self._send(
|
|
109
|
+
method,
|
|
110
|
+
path=path,
|
|
111
|
+
params=params,
|
|
112
|
+
json_body=json_body,
|
|
113
|
+
form=form,
|
|
114
|
+
files=files,
|
|
115
|
+
)
|
|
116
|
+
if response.is_error:
|
|
117
|
+
raise PacificCliApiError(
|
|
118
|
+
self._refusal(response),
|
|
119
|
+
status_code=response.status_code,
|
|
120
|
+
body=response.content,
|
|
121
|
+
)
|
|
122
|
+
return response
|
|
123
|
+
|
|
124
|
+
def parsed[ModelT: BaseModel](
|
|
125
|
+
self,
|
|
126
|
+
model: type[ModelT],
|
|
127
|
+
*,
|
|
128
|
+
method: HTTPMethod,
|
|
129
|
+
path: str,
|
|
130
|
+
params: PacificCliQueryParams | None = None,
|
|
131
|
+
json_body: JsonValue | None = None,
|
|
132
|
+
) -> ModelT:
|
|
133
|
+
"""Send a request and read its answer as ``model``."""
|
|
134
|
+
response = self.request(method, path=path, params=params, json_body=json_body)
|
|
135
|
+
return model.model_validate_json(response.content)
|
|
136
|
+
|
|
137
|
+
def _send(
|
|
138
|
+
self,
|
|
139
|
+
method: HTTPMethod,
|
|
140
|
+
*,
|
|
141
|
+
path: str,
|
|
142
|
+
params: PacificCliQueryParams | None,
|
|
143
|
+
json_body: JsonValue | None,
|
|
144
|
+
form: Mapping[str, str] | None,
|
|
145
|
+
files: Sequence[PacificCliUploadPart],
|
|
146
|
+
) -> httpx.Response:
|
|
147
|
+
bearer = self.bearer()
|
|
148
|
+
# Opened for this attempt only: httpx streams each file as it sends, so
|
|
149
|
+
# nothing holds a whole document in memory, and a second attempt reads
|
|
150
|
+
# from the start rather than from wherever the first one stopped.
|
|
151
|
+
with ExitStack() as handles:
|
|
152
|
+
return self._http.request(
|
|
153
|
+
method,
|
|
154
|
+
f"{self._profile.base_url}{path}",
|
|
155
|
+
params=params,
|
|
156
|
+
json=json_body,
|
|
157
|
+
data=form,
|
|
158
|
+
files=[
|
|
159
|
+
(
|
|
160
|
+
part.field,
|
|
161
|
+
(part.path.name, handles.enter_context(part.path.open("rb"))),
|
|
162
|
+
)
|
|
163
|
+
for part in files
|
|
164
|
+
]
|
|
165
|
+
or None,
|
|
166
|
+
headers={"Authorization": f"Bearer {bearer}"},
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
def _refresh(self, session: PacificCliOAuthCredential) -> PacificCliOAuthCredential:
|
|
170
|
+
"""The profile's session renewed, by this command or by one that got there first.
|
|
171
|
+
|
|
172
|
+
The refresh token rotates and the broker revokes the whole session when a
|
|
173
|
+
spent one is presented again, so two commands must never renew the same
|
|
174
|
+
session. The stored copy is reread under the credentials lock: when
|
|
175
|
+
another command has already rotated it, that rotation is used as it is
|
|
176
|
+
(or renewed in turn if it too is about to expire).
|
|
177
|
+
"""
|
|
178
|
+
name = self._profile.name
|
|
179
|
+
if name is None:
|
|
180
|
+
# Only a stored profile holds a browser session; PACIFIC_API_KEY is a key.
|
|
181
|
+
raise ValueError("a browser session must belong to a named profile")
|
|
182
|
+
with self._profiles.credentials_locked():
|
|
183
|
+
stored = self._profiles.credentials().profiles.get(name)
|
|
184
|
+
if not isinstance(stored, PacificCliOAuthCredential):
|
|
185
|
+
raise PacificCliSessionEndedError(
|
|
186
|
+
f"{name} was signed out or given an API key while this command "
|
|
187
|
+
"ran; run it again"
|
|
188
|
+
)
|
|
189
|
+
if (
|
|
190
|
+
stored.refresh_token.get_secret_value()
|
|
191
|
+
!= session.refresh_token.get_secret_value()
|
|
192
|
+
):
|
|
193
|
+
self._credential = stored
|
|
194
|
+
if not stored.expires_within(
|
|
195
|
+
self._settings.token_refresh_window, now=datetime.now(UTC)
|
|
196
|
+
):
|
|
197
|
+
return stored
|
|
198
|
+
session = stored
|
|
199
|
+
renewed = self._oauth.refresh(session)
|
|
200
|
+
self._credential = renewed
|
|
201
|
+
self._profiles.save_credential(name, credential=renewed)
|
|
202
|
+
return renewed
|
|
203
|
+
|
|
204
|
+
@staticmethod
|
|
205
|
+
def _refusal(response: httpx.Response) -> str:
|
|
206
|
+
"""The server's reason, as one line: its code and message, or FastAPI's detail."""
|
|
207
|
+
prefix = f"{response.status_code} {response.reason_phrase}"
|
|
208
|
+
try:
|
|
209
|
+
body = PacificCliErrorBody.model_validate_json(response.content)
|
|
210
|
+
except ValidationError:
|
|
211
|
+
text = response.text.strip()
|
|
212
|
+
return f"{prefix}: {text[:1000]}" if text else prefix
|
|
213
|
+
parts = [part for part in (body.error, body.message) if part]
|
|
214
|
+
if isinstance(body.detail, str):
|
|
215
|
+
parts.append(body.detail)
|
|
216
|
+
elif body.detail is not None:
|
|
217
|
+
parts.append(json.dumps(body.detail))
|
|
218
|
+
return f"{prefix}: {' - '.join(parts)}" if parts else prefix
|
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
"""``pacific profile`` and ``pacific auth``: which server, as whom, and signing in."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
import webbrowser
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from http import HTTPMethod
|
|
9
|
+
|
|
10
|
+
import click
|
|
11
|
+
import httpx
|
|
12
|
+
from pydantic import SecretStr
|
|
13
|
+
from rich.console import Console
|
|
14
|
+
from rich.table import Table
|
|
15
|
+
|
|
16
|
+
from pacific_cli.auth.runtime import PacificCliRuntime
|
|
17
|
+
from pacific_cli.auth.types import (
|
|
18
|
+
PacificCliApiError,
|
|
19
|
+
PacificCliApiKeyCredential,
|
|
20
|
+
PacificCliCredential,
|
|
21
|
+
PacificCliError,
|
|
22
|
+
PacificCliOAuthCredential,
|
|
23
|
+
PacificCliProbeEnvelope,
|
|
24
|
+
)
|
|
25
|
+
from pacific_cli.config import PACIFIC_CLI_PROBE_PATH
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _describe(
|
|
29
|
+
credential: PacificCliCredential | None, *, from_environment: bool
|
|
30
|
+
) -> str:
|
|
31
|
+
"""One line on how a profile authenticates; never the secret."""
|
|
32
|
+
match credential:
|
|
33
|
+
case None:
|
|
34
|
+
return "signed out"
|
|
35
|
+
case PacificCliApiKeyCredential():
|
|
36
|
+
return "API key (PACIFIC_API_KEY)" if from_environment else "API key"
|
|
37
|
+
case PacificCliOAuthCredential(expires_at=expires_at):
|
|
38
|
+
state = "expired" if expires_at <= datetime.now(UTC) else "valid"
|
|
39
|
+
return f"browser session (access token {state} until {expires_at:%Y-%m-%d %H:%M} UTC; refreshes itself)"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@click.group("profile")
|
|
43
|
+
def profile_group() -> None:
|
|
44
|
+
"""Servers and identities: one profile per server and person."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@profile_group.command("add")
|
|
48
|
+
@click.argument("name")
|
|
49
|
+
@click.option(
|
|
50
|
+
"--base-url",
|
|
51
|
+
required=True,
|
|
52
|
+
help="The server's origin, such as https://api.pacific.app or http://localhost:5001",
|
|
53
|
+
)
|
|
54
|
+
@click.option("--use", "make_current", is_flag=True, help="Make it the current profile")
|
|
55
|
+
@click.pass_obj
|
|
56
|
+
def profile_add(
|
|
57
|
+
runtime: PacificCliRuntime, name: str, base_url: str, make_current: bool
|
|
58
|
+
) -> None:
|
|
59
|
+
"""Add a profile, or point an existing one at another server (which signs it out)."""
|
|
60
|
+
profile = runtime.profiles.add(name, base_url=base_url, make_current=make_current)
|
|
61
|
+
click.echo(f"Profile {name} -> {profile.base_url}")
|
|
62
|
+
click.echo(f"Sign in: pacific -p {name} auth login (or: auth set-key)")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@profile_group.command("list")
|
|
66
|
+
@click.pass_obj
|
|
67
|
+
def profile_list(runtime: PacificCliRuntime) -> None:
|
|
68
|
+
"""Every profile, the current one marked."""
|
|
69
|
+
config = runtime.profiles.config()
|
|
70
|
+
credentials = runtime.profiles.credentials().profiles
|
|
71
|
+
table = Table("", "profile", "server", "credential", box=None)
|
|
72
|
+
for name, profile in sorted(config.profiles.items()):
|
|
73
|
+
table.add_row(
|
|
74
|
+
"*" if name == config.current_profile else "",
|
|
75
|
+
name,
|
|
76
|
+
profile.base_url,
|
|
77
|
+
_describe(credentials.get(name), from_environment=False),
|
|
78
|
+
)
|
|
79
|
+
Console().print(table)
|
|
80
|
+
click.echo(f"\nStored in {runtime.profiles.directory}")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@profile_group.command("use")
|
|
84
|
+
@click.argument("name")
|
|
85
|
+
@click.pass_obj
|
|
86
|
+
def profile_use(runtime: PacificCliRuntime, name: str) -> None:
|
|
87
|
+
"""Make NAME the profile commands use when none is named."""
|
|
88
|
+
runtime.profiles.use(name)
|
|
89
|
+
click.echo(f"Now using {name}")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@profile_group.command("remove")
|
|
93
|
+
@click.argument("name")
|
|
94
|
+
@click.pass_obj
|
|
95
|
+
def profile_remove(runtime: PacificCliRuntime, name: str) -> None:
|
|
96
|
+
"""Sign NAME out (revoking a browser session) and forget it."""
|
|
97
|
+
click.echo(runtime.sign_out(name))
|
|
98
|
+
runtime.profiles.remove(name)
|
|
99
|
+
click.echo(f"Removed {name}")
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@profile_group.command("show")
|
|
103
|
+
@click.pass_obj
|
|
104
|
+
def profile_show(runtime: PacificCliRuntime) -> None:
|
|
105
|
+
"""The profile this command would run as, and why."""
|
|
106
|
+
profile = runtime.resolved()
|
|
107
|
+
click.echo(
|
|
108
|
+
f"profile: {profile.name or '(none)'} [chosen by {profile.source.value}]"
|
|
109
|
+
)
|
|
110
|
+
click.echo(f"server: {profile.base_url}")
|
|
111
|
+
click.echo(
|
|
112
|
+
"credential: "
|
|
113
|
+
+ _describe(
|
|
114
|
+
profile.credential, from_environment=profile.credential_from_environment
|
|
115
|
+
)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@click.group("auth")
|
|
120
|
+
def auth_group() -> None:
|
|
121
|
+
"""Sign in, see who you are, and get a token for scripts."""
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@auth_group.command("login")
|
|
125
|
+
@click.option(
|
|
126
|
+
"--scope",
|
|
127
|
+
"-s",
|
|
128
|
+
"scopes",
|
|
129
|
+
multiple=True,
|
|
130
|
+
metavar="SCOPE",
|
|
131
|
+
help="An API scope the session may use, such as documents:write or "
|
|
132
|
+
"tools:read (repeatable). None: your full access",
|
|
133
|
+
)
|
|
134
|
+
@click.option(
|
|
135
|
+
"--no-browser",
|
|
136
|
+
is_flag=True,
|
|
137
|
+
help="Print the sign-in link instead of opening a browser (for a remote shell, forward the port it names)",
|
|
138
|
+
)
|
|
139
|
+
@click.pass_obj
|
|
140
|
+
def auth_login(
|
|
141
|
+
runtime: PacificCliRuntime, scopes: tuple[str, ...], no_browser: bool
|
|
142
|
+
) -> None:
|
|
143
|
+
"""Sign in in the browser, as you do in the Pacific app.
|
|
144
|
+
|
|
145
|
+
The session is bound to the public API and acts as you, limited to the
|
|
146
|
+
--scope values given (your full access when none is). It refreshes itself,
|
|
147
|
+
and lasts until you sign out or stop using it for the server's refresh
|
|
148
|
+
lifetime.
|
|
149
|
+
"""
|
|
150
|
+
profile = runtime.stored_profile()
|
|
151
|
+
|
|
152
|
+
def show(*, url: str) -> None:
|
|
153
|
+
click.echo(f"Sign in at:\n\n {url}\n", err=True)
|
|
154
|
+
if not no_browser and not webbrowser.open(url):
|
|
155
|
+
click.echo("Could not open a browser; open the link above.", err=True)
|
|
156
|
+
|
|
157
|
+
if profile.credential_from_environment:
|
|
158
|
+
click.echo(
|
|
159
|
+
"Note: PACIFIC_API_KEY is set and is used instead of this session.",
|
|
160
|
+
err=True,
|
|
161
|
+
)
|
|
162
|
+
signed_in = runtime.oauth.login(profile.base_url, scopes=scopes, open_browser=show)
|
|
163
|
+
runtime.profiles.save_credential(profile.name, credential=signed_in.credential)
|
|
164
|
+
granted = ", ".join(scopes) if scopes else "your full access"
|
|
165
|
+
if signed_in.probe is None:
|
|
166
|
+
click.echo(
|
|
167
|
+
f"Signed in to {profile.base_url} (profile {profile.name}) with {granted}."
|
|
168
|
+
)
|
|
169
|
+
return
|
|
170
|
+
click.echo(
|
|
171
|
+
f"Signed in to {profile.base_url} as user {signed_in.probe.user_id} "
|
|
172
|
+
f"(profile {profile.name}) with {granted}."
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
@auth_group.command("set-key")
|
|
177
|
+
@click.option(
|
|
178
|
+
"--stdin",
|
|
179
|
+
"from_stdin",
|
|
180
|
+
is_flag=True,
|
|
181
|
+
help="Read the key from standard input instead of a prompt",
|
|
182
|
+
)
|
|
183
|
+
@click.pass_obj
|
|
184
|
+
def auth_set_key(runtime: PacificCliRuntime, from_stdin: bool) -> None:
|
|
185
|
+
"""Store an API key (minted in the Pacific app under API keys) on the profile."""
|
|
186
|
+
profile = runtime.stored_profile()
|
|
187
|
+
key = (
|
|
188
|
+
sys.stdin.read().strip()
|
|
189
|
+
if from_stdin
|
|
190
|
+
else click.prompt("API key", hide_input=True).strip()
|
|
191
|
+
)
|
|
192
|
+
if not key:
|
|
193
|
+
raise PacificCliError("No key given")
|
|
194
|
+
if any(character.isspace() for character in key):
|
|
195
|
+
# A key is one token; spaces or lines mean something else was pasted
|
|
196
|
+
# (pbpaste of a copied command), and storing it breaks every command.
|
|
197
|
+
raise PacificCliError(
|
|
198
|
+
"That is not an API key: it has spaces or several lines. Copy the key "
|
|
199
|
+
"itself and try again; nothing was stored."
|
|
200
|
+
)
|
|
201
|
+
runtime.profiles.save_credential(
|
|
202
|
+
profile.name, credential=PacificCliApiKeyCredential(api_key=SecretStr(key))
|
|
203
|
+
)
|
|
204
|
+
click.echo(f"Stored an API key on profile {profile.name}.")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@auth_group.command("status")
|
|
208
|
+
@click.pass_obj
|
|
209
|
+
def auth_status(runtime: PacificCliRuntime) -> None:
|
|
210
|
+
"""Ask the server who this profile is and which scopes it holds."""
|
|
211
|
+
client = runtime.client()
|
|
212
|
+
profile = client.profile
|
|
213
|
+
click.echo(f"profile: {profile.name or '(PACIFIC_BASE_URL)'} -> {profile.base_url}")
|
|
214
|
+
try:
|
|
215
|
+
probe = client.parsed(
|
|
216
|
+
PacificCliProbeEnvelope, method=HTTPMethod.GET, path=PACIFIC_CLI_PROBE_PATH
|
|
217
|
+
).data
|
|
218
|
+
except PacificCliApiError as exc:
|
|
219
|
+
if exc.status_code != httpx.codes.FORBIDDEN:
|
|
220
|
+
raise
|
|
221
|
+
click.echo(
|
|
222
|
+
"The server accepts this credential, but it does not hold "
|
|
223
|
+
"documents:read, the scope this check asks for, so the server did "
|
|
224
|
+
"not say who it is."
|
|
225
|
+
)
|
|
226
|
+
return
|
|
227
|
+
click.echo(f"user: {probe.user_id}")
|
|
228
|
+
click.echo(f"auth: {probe.auth_type}")
|
|
229
|
+
click.echo(f"scopes: {', '.join(probe.scopes)}")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
@auth_group.command("token")
|
|
233
|
+
@click.pass_obj
|
|
234
|
+
def auth_token(runtime: PacificCliRuntime) -> None:
|
|
235
|
+
"""Print a bearer token for scripts, refreshed if it was about to expire.
|
|
236
|
+
|
|
237
|
+
curl -H "Authorization: Bearer $(pacific auth token)" "$URL/public/v1/documents"
|
|
238
|
+
"""
|
|
239
|
+
click.echo(runtime.client().bearer())
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
@auth_group.command("logout")
|
|
243
|
+
@click.pass_obj
|
|
244
|
+
def auth_logout(runtime: PacificCliRuntime) -> None:
|
|
245
|
+
"""Revoke the profile's browser session and forget its credential."""
|
|
246
|
+
profile = runtime.stored_profile()
|
|
247
|
+
click.echo(runtime.sign_out(profile.name))
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Constants and settings for the Pacific CLI's profiles and sign-in."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import timedelta
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from pydantic import Field, SecretStr
|
|
9
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
10
|
+
|
|
11
|
+
from pacific_cli.auth.types import PacificCliBaseUrl, PacificCliProfileName
|
|
12
|
+
|
|
13
|
+
PACIFIC_CLI_CONFIG_DIR_NAME = "pacific"
|
|
14
|
+
PACIFIC_CLI_CONFIG_FILE_NAME = "config.json"
|
|
15
|
+
PACIFIC_CLI_CREDENTIALS_FILE_NAME = "credentials.json"
|
|
16
|
+
#: Held by every command that reads a credential to replace it, so two commands
|
|
17
|
+
#: never rotate one browser session at once (the broker revokes a session whose
|
|
18
|
+
#: refresh token is presented twice) nor lose each other's writes.
|
|
19
|
+
PACIFIC_CLI_CREDENTIALS_LOCK_FILE_NAME = "credentials.lock"
|
|
20
|
+
#: Owner-only: the credentials file holds bearer tokens and API keys.
|
|
21
|
+
PACIFIC_CLI_CREDENTIALS_FILE_MODE = 0o600
|
|
22
|
+
PACIFIC_CLI_CONFIG_FILE_MODE = 0o600
|
|
23
|
+
PACIFIC_CLI_CONFIG_DIR_MODE = 0o700
|
|
24
|
+
|
|
25
|
+
#: RFC 8252 loopback redirect. An IP literal rather than ``localhost``, which a
|
|
26
|
+
#: resolver can point elsewhere.
|
|
27
|
+
PACIFIC_CLI_LOOPBACK_HOST = "127.0.0.1"
|
|
28
|
+
PACIFIC_CLI_CALLBACK_PATH = "/callback"
|
|
29
|
+
PACIFIC_CLI_OAUTH_CLIENT_NAME = "Pacific CLI"
|
|
30
|
+
#: RFC 8414 discovery at the server root, where Pacific serves its broker's document.
|
|
31
|
+
PACIFIC_CLI_OAUTH_DISCOVERY_PATH = "/.well-known/oauth-authorization-server"
|
|
32
|
+
PACIFIC_CLI_OAUTH_GRANT_TYPES: tuple[str, ...] = ("authorization_code", "refresh_token")
|
|
33
|
+
PACIFIC_CLI_OAUTH_RESPONSE_TYPE = "code"
|
|
34
|
+
#: What the broker grants a request that names no scope. Sent beside the API
|
|
35
|
+
#: scopes of a scoped sign-in, so it differs from a full one only in those.
|
|
36
|
+
PACIFIC_CLI_OAUTH_IDENTITY_SCOPES: tuple[str, ...] = (
|
|
37
|
+
"openid",
|
|
38
|
+
"profile",
|
|
39
|
+
"email",
|
|
40
|
+
"offline_access",
|
|
41
|
+
)
|
|
42
|
+
#: The only method the broker takes; ``plain`` would put the verifier in the URL.
|
|
43
|
+
PACIFIC_CLI_PKCE_METHOD = "S256"
|
|
44
|
+
#: A native client holds no secret; PKCE is what protects the code.
|
|
45
|
+
PACIFIC_CLI_OAUTH_TOKEN_ENDPOINT_AUTH_METHOD = "none"
|
|
46
|
+
PACIFIC_CLI_OAUTH_STATE_ENTROPY_BYTES = 32
|
|
47
|
+
PACIFIC_CLI_OAUTH_INVALID_GRANT = "invalid_grant"
|
|
48
|
+
|
|
49
|
+
#: The root command's help; ``\b`` keeps click from rewrapping the examples.
|
|
50
|
+
PACIFIC_CLI_HELP = """Upload documents with the metadata access policies match, and write,
|
|
51
|
+
list and attach those policies, against a Pacific server's public API.
|
|
52
|
+
|
|
53
|
+
\b
|
|
54
|
+
pacific profile add local --base-url http://localhost:5001 --use
|
|
55
|
+
pacific auth login
|
|
56
|
+
pacific documents upload deck.pdf -l board -a deal_stage=diligence --wait
|
|
57
|
+
pacific policy apply -f board-readers.yaml
|
|
58
|
+
pacific policy attach board-readers user alice@acme.com
|
|
59
|
+
pacific keys create -s documents:write --name "CI deploy" --expires 90d
|
|
60
|
+
"""
|
|
61
|
+
|
|
62
|
+
PACIFIC_CLI_LOGIN_SUCCESS_PAGE = (
|
|
63
|
+
"<!doctype html><title>Pacific CLI</title>"
|
|
64
|
+
"<p>Signed in. You can close this tab and return to your terminal.</p>"
|
|
65
|
+
)
|
|
66
|
+
PACIFIC_CLI_LOGIN_FAILURE_PAGE = (
|
|
67
|
+
"<!doctype html><title>Pacific CLI</title>"
|
|
68
|
+
"<p>Sign-in did not complete. Your terminal says why.</p>"
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class PacificCliSettings(BaseSettings):
|
|
73
|
+
"""Tunables of the CLI itself, as ``PACIFIC_CLI_*`` variables."""
|
|
74
|
+
|
|
75
|
+
model_config = SettingsConfigDict(
|
|
76
|
+
env_prefix="PACIFIC_CLI_", extra="ignore", env_ignore_empty=True
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
config_dir: Path | None = Field(
|
|
80
|
+
None,
|
|
81
|
+
description="Where profiles and credentials live; unset is "
|
|
82
|
+
"$XDG_CONFIG_HOME/pacific, or ~/.config/pacific without it",
|
|
83
|
+
)
|
|
84
|
+
xdg_config_home: Path | None = Field(
|
|
85
|
+
None,
|
|
86
|
+
validation_alias="XDG_CONFIG_HOME",
|
|
87
|
+
description="The XDG base directory for configuration",
|
|
88
|
+
)
|
|
89
|
+
http_timeout: timedelta = Field(
|
|
90
|
+
timedelta(minutes=5),
|
|
91
|
+
description="How long one request may take; an upload is one request",
|
|
92
|
+
)
|
|
93
|
+
login_timeout: timedelta = Field(
|
|
94
|
+
timedelta(minutes=5), description="How long to wait for the browser sign-in"
|
|
95
|
+
)
|
|
96
|
+
token_refresh_window: timedelta = Field(
|
|
97
|
+
timedelta(minutes=1),
|
|
98
|
+
description="Refresh an access token this long before it expires",
|
|
99
|
+
)
|
|
100
|
+
credentials_lock_timeout: timedelta = Field(
|
|
101
|
+
timedelta(seconds=30),
|
|
102
|
+
description="How long to wait for another pacific command to finish "
|
|
103
|
+
"renewing or saving a credential",
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
def resolved_config_dir(self) -> Path:
|
|
107
|
+
"""The configuration directory these settings name."""
|
|
108
|
+
if self.config_dir is not None:
|
|
109
|
+
return self.config_dir
|
|
110
|
+
if self.xdg_config_home is not None:
|
|
111
|
+
return self.xdg_config_home / PACIFIC_CLI_CONFIG_DIR_NAME
|
|
112
|
+
return Path.home() / ".config" / PACIFIC_CLI_CONFIG_DIR_NAME
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class PacificCliEnvironment(BaseSettings):
|
|
116
|
+
"""What a shell or CI job sets instead of, or on top of, a stored profile.
|
|
117
|
+
|
|
118
|
+
The same names Pacific's public API examples read.
|
|
119
|
+
``PACIFIC_API_KEY`` replaces the selected profile's credential;
|
|
120
|
+
``PACIFIC_BASE_URL`` stands in for a profile when none is selected.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
model_config = SettingsConfigDict(
|
|
124
|
+
env_prefix="PACIFIC_", extra="ignore", env_ignore_empty=True
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
profile: PacificCliProfileName | None = Field(
|
|
128
|
+
None, description="The profile to use when --profile is not given"
|
|
129
|
+
)
|
|
130
|
+
api_key: SecretStr | None = Field(None, description="An API key to send")
|
|
131
|
+
base_url: PacificCliBaseUrl | None = Field(
|
|
132
|
+
None, description="The server, when no profile is selected"
|
|
133
|
+
)
|