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
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""API keys over the public API, from a browser sign-in that asked for ``keys:manage``.
|
|
2
|
+
|
|
3
|
+
The server lets nothing else manage keys: never an API key, and never a session
|
|
4
|
+
that did not ask, or one approved too long ago to create a key. So each command
|
|
5
|
+
first tries the profile's own browser session, if it has one; when the server
|
|
6
|
+
refuses it for one of those reasons, it signs in once in the browser asking for
|
|
7
|
+
``keys:manage`` alone (the member's full access), sends the request again with
|
|
8
|
+
that session, and revokes the session as soon as the command is done.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from collections.abc import Callable, Sequence
|
|
14
|
+
from http import HTTPMethod
|
|
15
|
+
from urllib.parse import quote
|
|
16
|
+
|
|
17
|
+
import httpx
|
|
18
|
+
from pydantic import ValidationError
|
|
19
|
+
|
|
20
|
+
from pacific_cli.auth.client import PacificCliApiClient
|
|
21
|
+
from pacific_cli.auth.runtime import PacificCliRuntime
|
|
22
|
+
from pacific_cli.auth.types import (
|
|
23
|
+
PacificCliApiError,
|
|
24
|
+
PacificCliBrowserOpener,
|
|
25
|
+
PacificCliError,
|
|
26
|
+
PacificCliOAuthCredential,
|
|
27
|
+
PacificCliProfileSource,
|
|
28
|
+
PacificCliResolvedProfile,
|
|
29
|
+
PacificCliSessionEndedError,
|
|
30
|
+
)
|
|
31
|
+
from pacific_cli.keys.config import (
|
|
32
|
+
PACIFIC_CLI_KEY_MANAGEMENT_SCOPE,
|
|
33
|
+
PACIFIC_CLI_KEYS_PATH,
|
|
34
|
+
)
|
|
35
|
+
from pacific_cli.keys.types import (
|
|
36
|
+
PacificCliApiKeyList,
|
|
37
|
+
PacificCliApiKeyRequest,
|
|
38
|
+
PacificCliCreatedApiKey,
|
|
39
|
+
PacificCliKeyId,
|
|
40
|
+
PacificCliKeyLifetime,
|
|
41
|
+
PacificCliKeyRefusalBody,
|
|
42
|
+
PacificCliKeyRefusalResponse,
|
|
43
|
+
PacificCliRevoked,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class PacificCliKeyService:
|
|
48
|
+
"""Your own API keys, managed from a browser sign-in."""
|
|
49
|
+
|
|
50
|
+
def __init__(
|
|
51
|
+
self,
|
|
52
|
+
runtime: PacificCliRuntime,
|
|
53
|
+
*,
|
|
54
|
+
open_browser: PacificCliBrowserOpener,
|
|
55
|
+
notify: Callable[[str], None],
|
|
56
|
+
) -> None:
|
|
57
|
+
self._runtime = runtime
|
|
58
|
+
self._open_browser = open_browser
|
|
59
|
+
self._notify = notify
|
|
60
|
+
|
|
61
|
+
def list_keys(self) -> PacificCliApiKeyList:
|
|
62
|
+
return self._as_manager(
|
|
63
|
+
lambda client: client.parsed(
|
|
64
|
+
PacificCliApiKeyList, method=HTTPMethod.GET, path=PACIFIC_CLI_KEYS_PATH
|
|
65
|
+
)
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def create_key(
|
|
69
|
+
self,
|
|
70
|
+
*,
|
|
71
|
+
scopes: Sequence[str],
|
|
72
|
+
name: str | None,
|
|
73
|
+
lifetime: PacificCliKeyLifetime,
|
|
74
|
+
) -> PacificCliCreatedApiKey:
|
|
75
|
+
request = PacificCliApiKeyRequest(
|
|
76
|
+
scopes=list(scopes), name=name, expires_in=lifetime
|
|
77
|
+
)
|
|
78
|
+
return self._as_manager(
|
|
79
|
+
lambda client: PacificCliCreatedApiKey.model_validate_json(
|
|
80
|
+
client.request(
|
|
81
|
+
HTTPMethod.POST,
|
|
82
|
+
path=PACIFIC_CLI_KEYS_PATH,
|
|
83
|
+
json_body=request.model_dump(mode="json", exclude_none=True),
|
|
84
|
+
).content
|
|
85
|
+
)
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
def revoke_key(self, key_id: PacificCliKeyId) -> PacificCliRevoked:
|
|
89
|
+
return self._as_manager(
|
|
90
|
+
lambda client: client.parsed(
|
|
91
|
+
PacificCliRevoked,
|
|
92
|
+
method=HTTPMethod.DELETE,
|
|
93
|
+
path=f"{PACIFIC_CLI_KEYS_PATH}/{quote(key_id, safe='')}",
|
|
94
|
+
)
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
def _as_manager[ResultT](
|
|
98
|
+
self, send: Callable[[PacificCliApiClient], ResultT]
|
|
99
|
+
) -> ResultT:
|
|
100
|
+
"""``send`` with the profile's own session, or a one-off sign-in when that is refused."""
|
|
101
|
+
profile = self._runtime.resolved()
|
|
102
|
+
if isinstance(profile.credential, PacificCliOAuthCredential):
|
|
103
|
+
try:
|
|
104
|
+
return send(self._runtime.client())
|
|
105
|
+
except PacificCliSessionEndedError as exc:
|
|
106
|
+
# The stored session could not be renewed: the same fix as a
|
|
107
|
+
# profile with no session at all, so the same fallback.
|
|
108
|
+
self._notify(
|
|
109
|
+
f"{exc.message}\nSigning in once for this command, asking to "
|
|
110
|
+
"manage keys; the sign-in is revoked when it is done."
|
|
111
|
+
)
|
|
112
|
+
except PacificCliApiError as exc:
|
|
113
|
+
refusal = self._key_refusal(exc)
|
|
114
|
+
if refusal is None:
|
|
115
|
+
raise
|
|
116
|
+
self._notify(
|
|
117
|
+
f"{refusal.message}\nSigning in once more, asking to manage "
|
|
118
|
+
"keys; this sign-in is revoked when the command is done."
|
|
119
|
+
)
|
|
120
|
+
else:
|
|
121
|
+
self._notify(
|
|
122
|
+
"API keys are managed from a browser sign-in, never with a key. "
|
|
123
|
+
"Signing in for this command; the sign-in is revoked when it is done."
|
|
124
|
+
)
|
|
125
|
+
return self._with_one_off_sign_in(profile, send=send)
|
|
126
|
+
|
|
127
|
+
def _with_one_off_sign_in[ResultT](
|
|
128
|
+
self,
|
|
129
|
+
profile: PacificCliResolvedProfile,
|
|
130
|
+
*,
|
|
131
|
+
send: Callable[[PacificCliApiClient], ResultT],
|
|
132
|
+
) -> ResultT:
|
|
133
|
+
runtime = self._runtime
|
|
134
|
+
signed_in = runtime.oauth.login(
|
|
135
|
+
profile.base_url,
|
|
136
|
+
scopes=(PACIFIC_CLI_KEY_MANAGEMENT_SCOPE,),
|
|
137
|
+
open_browser=self._open_browser,
|
|
138
|
+
)
|
|
139
|
+
client = PacificCliApiClient(
|
|
140
|
+
PacificCliResolvedProfile(
|
|
141
|
+
name=None,
|
|
142
|
+
source=PacificCliProfileSource.ONE_OFF_SIGN_IN,
|
|
143
|
+
base_url=profile.base_url,
|
|
144
|
+
credential=signed_in.credential,
|
|
145
|
+
credential_from_environment=False,
|
|
146
|
+
),
|
|
147
|
+
http=runtime.http,
|
|
148
|
+
profiles=runtime.profiles,
|
|
149
|
+
oauth=runtime.oauth,
|
|
150
|
+
settings=runtime.settings,
|
|
151
|
+
)
|
|
152
|
+
try:
|
|
153
|
+
return send(client)
|
|
154
|
+
finally:
|
|
155
|
+
try:
|
|
156
|
+
runtime.oauth.revoke(signed_in.credential)
|
|
157
|
+
except (PacificCliError, httpx.TransportError) as exc:
|
|
158
|
+
# Never masks what send raised or returned: the key was already
|
|
159
|
+
# created or refused, and saying so is the command's answer.
|
|
160
|
+
self._notify(
|
|
161
|
+
f"The one-off sign-in could not be revoked ({exc}); it ends on "
|
|
162
|
+
"its own within the hour."
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
@staticmethod
|
|
166
|
+
def _key_refusal(exc: PacificCliApiError) -> PacificCliKeyRefusalBody | None:
|
|
167
|
+
"""Why the server refused the caller as a key manager; None for any other error."""
|
|
168
|
+
try:
|
|
169
|
+
return PacificCliKeyRefusalResponse.model_validate_json(exc.body).detail
|
|
170
|
+
except ValidationError:
|
|
171
|
+
return None
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""What the key routes take and answer; each model is held to the server's schema of the same name by ``contract_test.py``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from enum import StrEnum
|
|
7
|
+
from typing import NewType
|
|
8
|
+
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
10
|
+
|
|
11
|
+
#: A key's id at its issuer, as the key routes name it.
|
|
12
|
+
PacificCliKeyId = NewType("PacificCliKeyId", str)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class PacificCliKeyLifetime(StrEnum):
|
|
16
|
+
"""``ApiKeyLifetime``: how long a key lasts."""
|
|
17
|
+
|
|
18
|
+
THIRTY_MINUTES = "30m"
|
|
19
|
+
SEVEN_DAYS = "7d"
|
|
20
|
+
THIRTY_DAYS = "30d"
|
|
21
|
+
NINETY_DAYS = "90d"
|
|
22
|
+
ONE_YEAR = "1y"
|
|
23
|
+
NEVER = "never"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class PacificCliKeyRefusal(StrEnum):
|
|
27
|
+
"""``ApiKeyManagementRefusal``: why the key routes refused the caller."""
|
|
28
|
+
|
|
29
|
+
BROWSER_SESSION_REQUIRED = "browser_session_required"
|
|
30
|
+
KEY_MANAGEMENT_NOT_GRANTED = "key_management_not_granted"
|
|
31
|
+
SIGN_IN_AGAIN = "sign_in_again"
|
|
32
|
+
SESSION_INACTIVE = "session_inactive"
|
|
33
|
+
SCOPES_EXCEED_SESSION = "scopes_exceed_session"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class PacificCliKeyRefusalBody(BaseModel):
|
|
37
|
+
"""``ApiKeyManagementRefusalBody``."""
|
|
38
|
+
|
|
39
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
40
|
+
|
|
41
|
+
reason: PacificCliKeyRefusal = Field(..., description="Why, as a code")
|
|
42
|
+
message: str = Field(..., description="What to do about it")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PacificCliKeyRefusalResponse(BaseModel):
|
|
46
|
+
"""``ApiKeyManagementRefusalResponse``: FastAPI's ``detail`` envelope."""
|
|
47
|
+
|
|
48
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
49
|
+
|
|
50
|
+
detail: PacificCliKeyRefusalBody = Field(..., description="The refusal")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class PacificCliApiKeyRequest(BaseModel):
|
|
54
|
+
"""``PublicMintApiKeyRequest``: a key for yourself."""
|
|
55
|
+
|
|
56
|
+
model_config = ConfigDict(frozen=True, extra="forbid")
|
|
57
|
+
|
|
58
|
+
scopes: list[str] = Field(..., min_length=1, description="What it may do")
|
|
59
|
+
name: str | None = Field(None, description="A label, shown in the list")
|
|
60
|
+
expires_in: PacificCliKeyLifetime = Field(..., description="How long it lasts")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class PacificCliApiKey(BaseModel):
|
|
64
|
+
"""``PatSummary``: one of your keys, without its value."""
|
|
65
|
+
|
|
66
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
67
|
+
|
|
68
|
+
key_id: PacificCliKeyId = Field(..., description="Its id, for revoking it")
|
|
69
|
+
token_prefix: str = Field(
|
|
70
|
+
..., description="The start of its value, to recognize it"
|
|
71
|
+
)
|
|
72
|
+
name: str | None = Field(None, description="Its label")
|
|
73
|
+
scopes: list[str] = Field(..., description="What it may do")
|
|
74
|
+
created_at: datetime = Field(..., description="When it was created")
|
|
75
|
+
expires_at: datetime | None = Field(
|
|
76
|
+
..., description="When it stops working; null never"
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class PacificCliApiKeyList(BaseModel):
|
|
81
|
+
"""``ListPatsResponse``."""
|
|
82
|
+
|
|
83
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
84
|
+
|
|
85
|
+
data: list[PacificCliApiKey] = Field(..., description="Your keys")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class PacificCliCreatedApiKey(PacificCliApiKey):
|
|
89
|
+
"""``MintPatResponse``: the new key, its value shown once."""
|
|
90
|
+
|
|
91
|
+
token: str = Field(..., description="The key's value; never shown again")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class PacificCliRevoked(BaseModel):
|
|
95
|
+
"""``RevokePatResponse``."""
|
|
96
|
+
|
|
97
|
+
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
98
|
+
|
|
99
|
+
revoked: bool = Field(..., description="Always true")
|
pacific_cli/main.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""The ``pacific`` root command and its groups."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import override
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
from pacific_cli.auth.commands import auth_group, profile_group
|
|
11
|
+
from pacific_cli.auth.config import (
|
|
12
|
+
PACIFIC_CLI_HELP,
|
|
13
|
+
PacificCliEnvironment,
|
|
14
|
+
PacificCliSettings,
|
|
15
|
+
)
|
|
16
|
+
from pacific_cli.auth.runtime import PacificCliRuntime
|
|
17
|
+
from pacific_cli.auth.types import PacificCliError
|
|
18
|
+
from pacific_cli.documents.commands import documents_group
|
|
19
|
+
from pacific_cli.keys.commands import keys_group
|
|
20
|
+
from pacific_cli.policy.commands import policy_group
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class PacificCliGroup(click.Group):
|
|
24
|
+
"""The root group: a server that cannot be reached is a one-line error, not a traceback."""
|
|
25
|
+
|
|
26
|
+
@override
|
|
27
|
+
def invoke(self, ctx: click.Context) -> object:
|
|
28
|
+
try:
|
|
29
|
+
return super().invoke(ctx)
|
|
30
|
+
except httpx.TransportError as exc:
|
|
31
|
+
raise PacificCliError(f"Could not reach {exc.request.url}: {exc}") from exc
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@click.group(cls=PacificCliGroup, help=PACIFIC_CLI_HELP)
|
|
35
|
+
@click.option(
|
|
36
|
+
"--profile",
|
|
37
|
+
"-p",
|
|
38
|
+
"requested_profile",
|
|
39
|
+
help="The profile to run as (default: $PACIFIC_PROFILE, then the current profile)",
|
|
40
|
+
)
|
|
41
|
+
@click.pass_context
|
|
42
|
+
def pacific_cli(ctx: click.Context, requested_profile: str | None) -> None:
|
|
43
|
+
settings = PacificCliSettings()
|
|
44
|
+
http = httpx.Client(timeout=settings.http_timeout.total_seconds())
|
|
45
|
+
ctx.call_on_close(http.close)
|
|
46
|
+
ctx.obj = PacificCliRuntime(
|
|
47
|
+
settings,
|
|
48
|
+
environment=PacificCliEnvironment(),
|
|
49
|
+
http=http,
|
|
50
|
+
requested_profile=requested_profile,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
pacific_cli.add_command(profile_group)
|
|
55
|
+
pacific_cli.add_command(auth_group)
|
|
56
|
+
pacific_cli.add_command(documents_group)
|
|
57
|
+
pacific_cli.add_command(policy_group)
|
|
58
|
+
pacific_cli.add_command(keys_group)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Writing access policies, listing them, and attaching them to principals."""
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"""``pacific policy``: write permissions, list them, and attach them to principals."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
from rich.table import Table
|
|
11
|
+
|
|
12
|
+
from pacific_cli.auth.runtime import PacificCliRuntime
|
|
13
|
+
from pacific_cli.policy.service import PacificCliPolicyService
|
|
14
|
+
from pacific_cli.policy.types import (
|
|
15
|
+
PacificCliAttachmentList,
|
|
16
|
+
PacificCliEnforcementScope,
|
|
17
|
+
PacificCliPolicyKind,
|
|
18
|
+
PacificCliPolicyName,
|
|
19
|
+
PacificCliPrincipalKind,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
_KIND = click.option(
|
|
23
|
+
"--kind",
|
|
24
|
+
"segment",
|
|
25
|
+
type=click.Choice([segment.value for segment in PacificCliPolicyKind]),
|
|
26
|
+
default=PacificCliPolicyKind.PERMISSION_POLICIES.value,
|
|
27
|
+
show_default=True,
|
|
28
|
+
help="The kind of object",
|
|
29
|
+
)
|
|
30
|
+
_PRINCIPAL_KIND = click.argument(
|
|
31
|
+
"principal_kind",
|
|
32
|
+
type=click.Choice([kind.value for kind in PacificCliPrincipalKind]),
|
|
33
|
+
)
|
|
34
|
+
_PRINCIPAL = click.argument("principal", metavar="ID_OR_EMAIL_OR_NAME")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _print_coverage(scope: PacificCliEnforcementScope | None) -> None:
|
|
38
|
+
"""What the organization applies now: the server's coverage, not the policy's text."""
|
|
39
|
+
if scope is None:
|
|
40
|
+
return
|
|
41
|
+
surfaces = ", ".join(scope.surfaces) or "none"
|
|
42
|
+
click.echo(f"Applied now to: {surfaces}")
|
|
43
|
+
if not scope.document_statements_enforced:
|
|
44
|
+
click.echo(
|
|
45
|
+
"Document statements are not applied to reads until the organization's "
|
|
46
|
+
"documents mode is enforce."
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _print_attachments(attachments: PacificCliAttachmentList) -> None:
|
|
51
|
+
if attachments.items:
|
|
52
|
+
table = Table("policy", "via", box=None)
|
|
53
|
+
for item in attachments.items:
|
|
54
|
+
table.add_row(item.policy, item.target)
|
|
55
|
+
Console().print(table)
|
|
56
|
+
else:
|
|
57
|
+
click.echo("policies: none attached")
|
|
58
|
+
_print_coverage(attachments.enforcement_scope)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@click.group("policy")
|
|
62
|
+
def policy_group() -> None:
|
|
63
|
+
"""Access policies: write them, list them, attach them to people, groups, agents and services."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@policy_group.command("me")
|
|
67
|
+
@click.pass_obj
|
|
68
|
+
def policy_me(runtime: PacificCliRuntime) -> None:
|
|
69
|
+
"""Who you are to the policy engine: your groups, admin standing and what applies to you."""
|
|
70
|
+
me = PacificCliPolicyService(runtime.client()).me()
|
|
71
|
+
click.echo(
|
|
72
|
+
f"{me.principal.name} <{me.principal.email or me.principal.id}> {me.principal.prn}"
|
|
73
|
+
)
|
|
74
|
+
click.echo(f"admin: {'yes' if me.is_admin else 'no'}")
|
|
75
|
+
click.echo(f"groups: {', '.join(group.name for group in me.groups) or '-'}")
|
|
76
|
+
_print_attachments(me.policies)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@policy_group.command("list")
|
|
80
|
+
@_KIND
|
|
81
|
+
@click.option("--json", "as_json", is_flag=True, help="Print JSON")
|
|
82
|
+
@click.pass_obj
|
|
83
|
+
def policy_list(runtime: PacificCliRuntime, segment: str, as_json: bool) -> None:
|
|
84
|
+
"""List the organization's policies (or agents, services, resource sets with --kind)."""
|
|
85
|
+
objects = list(
|
|
86
|
+
PacificCliPolicyService(runtime.client()).objects(PacificCliPolicyKind(segment))
|
|
87
|
+
)
|
|
88
|
+
if as_json:
|
|
89
|
+
click.echo(
|
|
90
|
+
json.dumps(
|
|
91
|
+
[item.model_dump(mode="json", exclude_none=True) for item in objects],
|
|
92
|
+
indent=2,
|
|
93
|
+
)
|
|
94
|
+
)
|
|
95
|
+
return
|
|
96
|
+
table = Table("name", "version", "active", "description", box=None)
|
|
97
|
+
for item in objects:
|
|
98
|
+
table.add_row(
|
|
99
|
+
item.metadata.name,
|
|
100
|
+
str(item.metadata.version),
|
|
101
|
+
"-" if item.status is None else ("yes" if item.status.active else "no"),
|
|
102
|
+
item.metadata.description or "",
|
|
103
|
+
)
|
|
104
|
+
Console().print(table)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@policy_group.command("get")
|
|
108
|
+
@click.argument("name")
|
|
109
|
+
@_KIND
|
|
110
|
+
@click.pass_obj
|
|
111
|
+
def policy_get(runtime: PacificCliRuntime, name: str, segment: str) -> None:
|
|
112
|
+
"""Print one object as JSON: edit it and `policy apply` it back."""
|
|
113
|
+
item = PacificCliPolicyService(runtime.client()).object(
|
|
114
|
+
PacificCliPolicyKind(segment), name=PacificCliPolicyName(name)
|
|
115
|
+
)
|
|
116
|
+
click.echo(item.model_dump_json(indent=2, exclude_none=True))
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@policy_group.command("apply")
|
|
120
|
+
@click.option(
|
|
121
|
+
"--file",
|
|
122
|
+
"-f",
|
|
123
|
+
"path",
|
|
124
|
+
required=True,
|
|
125
|
+
type=click.Path(exists=True, dir_okay=False, path_type=Path),
|
|
126
|
+
help="The object, as JSON or YAML (by suffix)",
|
|
127
|
+
)
|
|
128
|
+
@click.option(
|
|
129
|
+
"--dry-run", is_flag=True, help="Validate and show the change without writing"
|
|
130
|
+
)
|
|
131
|
+
@click.option(
|
|
132
|
+
"--draft", is_flag=True, help="Save a version that is not active until activated"
|
|
133
|
+
)
|
|
134
|
+
@click.option(
|
|
135
|
+
"--overwrite",
|
|
136
|
+
is_flag=True,
|
|
137
|
+
help="Write over the latest version instead of refusing when the file's metadata.version is stale",
|
|
138
|
+
)
|
|
139
|
+
@click.option(
|
|
140
|
+
"--accept-mcp-terms",
|
|
141
|
+
"accepts_mcp_tos",
|
|
142
|
+
is_flag=True,
|
|
143
|
+
help="Accept the Pacific MCP terms of service, for you and on the agent's "
|
|
144
|
+
"behalf; required when an Agent file creates a new agent",
|
|
145
|
+
)
|
|
146
|
+
@click.pass_obj
|
|
147
|
+
def policy_apply(
|
|
148
|
+
runtime: PacificCliRuntime,
|
|
149
|
+
path: Path,
|
|
150
|
+
dry_run: bool,
|
|
151
|
+
draft: bool,
|
|
152
|
+
overwrite: bool,
|
|
153
|
+
accepts_mcp_tos: bool,
|
|
154
|
+
) -> None:
|
|
155
|
+
"""Create a policy from a file, or write its next version (as an administrator)."""
|
|
156
|
+
service = PacificCliPolicyService(runtime.client())
|
|
157
|
+
result = service.apply(
|
|
158
|
+
service.read_document(path),
|
|
159
|
+
activate=not draft,
|
|
160
|
+
dry_run=dry_run,
|
|
161
|
+
overwrite=overwrite,
|
|
162
|
+
accepts_mcp_tos=accepts_mcp_tos,
|
|
163
|
+
)
|
|
164
|
+
click.echo(json.dumps(result, indent=2))
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@policy_group.command("delete")
|
|
168
|
+
@click.argument("name")
|
|
169
|
+
@_KIND
|
|
170
|
+
@click.confirmation_option(prompt="Delete it? Attachments must be removed first.")
|
|
171
|
+
@click.pass_obj
|
|
172
|
+
def policy_delete(runtime: PacificCliRuntime, name: str, segment: str) -> None:
|
|
173
|
+
"""Delete an object (as an administrator)."""
|
|
174
|
+
deleted = PacificCliPolicyService(runtime.client()).delete(
|
|
175
|
+
PacificCliPolicyKind(segment), name=PacificCliPolicyName(name)
|
|
176
|
+
)
|
|
177
|
+
click.echo(f"Deleted {deleted.kind} {deleted.name}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@policy_group.command("principals")
|
|
181
|
+
@_PRINCIPAL_KIND
|
|
182
|
+
@click.option(
|
|
183
|
+
"--query", "-q", help="Match a name, or (as an administrator) a user's email"
|
|
184
|
+
)
|
|
185
|
+
@click.pass_obj
|
|
186
|
+
def policy_principals(
|
|
187
|
+
runtime: PacificCliRuntime, principal_kind: str, query: str | None
|
|
188
|
+
) -> None:
|
|
189
|
+
"""List users, groups, agents or services, with the ids policies name them by."""
|
|
190
|
+
principals = PacificCliPolicyService(runtime.client()).principals(
|
|
191
|
+
PacificCliPrincipalKind(principal_kind), query=query
|
|
192
|
+
)
|
|
193
|
+
table = Table("id", "name", "email", "prn", box=None)
|
|
194
|
+
for principal in principals:
|
|
195
|
+
table.add_row(
|
|
196
|
+
principal.id, principal.name, principal.email or "", principal.prn
|
|
197
|
+
)
|
|
198
|
+
Console().print(table)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@policy_group.command("attached")
|
|
202
|
+
@_PRINCIPAL_KIND
|
|
203
|
+
@_PRINCIPAL
|
|
204
|
+
@click.pass_obj
|
|
205
|
+
def policy_attached(
|
|
206
|
+
runtime: PacificCliRuntime, principal_kind: str, principal: str
|
|
207
|
+
) -> None:
|
|
208
|
+
"""The policies that apply to a principal, and what each comes through.
|
|
209
|
+
|
|
210
|
+
\b
|
|
211
|
+
pacific policy attached user alice@acme.com
|
|
212
|
+
"""
|
|
213
|
+
service = PacificCliPolicyService(runtime.client())
|
|
214
|
+
kind = PacificCliPrincipalKind(principal_kind)
|
|
215
|
+
_print_attachments(
|
|
216
|
+
service.attached(
|
|
217
|
+
kind, principal_id=service.principal_id(kind, reference=principal)
|
|
218
|
+
)
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@policy_group.command("attach")
|
|
223
|
+
@click.argument("policy")
|
|
224
|
+
@_PRINCIPAL_KIND
|
|
225
|
+
@_PRINCIPAL
|
|
226
|
+
@click.pass_obj
|
|
227
|
+
def policy_attach(
|
|
228
|
+
runtime: PacificCliRuntime, policy: str, principal_kind: str, principal: str
|
|
229
|
+
) -> None:
|
|
230
|
+
"""Attach POLICY to a user, group, agent or service (as an administrator).
|
|
231
|
+
|
|
232
|
+
\b
|
|
233
|
+
pacific policy attach board-readers user alice@acme.com
|
|
234
|
+
pacific policy attach board-readers group "Investment Committee"
|
|
235
|
+
"""
|
|
236
|
+
service = PacificCliPolicyService(runtime.client())
|
|
237
|
+
kind = PacificCliPrincipalKind(principal_kind)
|
|
238
|
+
attached = service.attach(
|
|
239
|
+
kind,
|
|
240
|
+
principal_id=service.principal_id(kind, reference=principal),
|
|
241
|
+
policy=PacificCliPolicyName(policy),
|
|
242
|
+
)
|
|
243
|
+
click.echo(f"Attached {attached.policy} to {attached.target}")
|
|
244
|
+
_print_coverage(attached.enforcement_scope)
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
@policy_group.command("detach")
|
|
248
|
+
@click.argument("policy")
|
|
249
|
+
@_PRINCIPAL_KIND
|
|
250
|
+
@_PRINCIPAL
|
|
251
|
+
@click.pass_obj
|
|
252
|
+
def policy_detach(
|
|
253
|
+
runtime: PacificCliRuntime, policy: str, principal_kind: str, principal: str
|
|
254
|
+
) -> None:
|
|
255
|
+
"""Detach POLICY from a user, group, agent or service (as an administrator)."""
|
|
256
|
+
service = PacificCliPolicyService(runtime.client())
|
|
257
|
+
kind = PacificCliPrincipalKind(principal_kind)
|
|
258
|
+
detached = service.detach(
|
|
259
|
+
kind,
|
|
260
|
+
principal_id=service.principal_id(kind, reference=principal),
|
|
261
|
+
policy=PacificCliPolicyName(policy),
|
|
262
|
+
)
|
|
263
|
+
click.echo(f"Detached {detached.policy} from {detached.target}")
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""Constants for the Pacific CLI's policy commands."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pacific_cli.config import PACIFIC_CLI_PUBLIC_API_PREFIX
|
|
6
|
+
|
|
7
|
+
PACIFIC_CLI_POLICY_PATH = f"{PACIFIC_CLI_PUBLIC_API_PREFIX}/policy"
|
|
8
|
+
PACIFIC_CLI_POLICY_PRINCIPALS_PATH = f"{PACIFIC_CLI_POLICY_PATH}/principals"
|
|
9
|
+
PACIFIC_CLI_POLICY_ME_PATH = f"{PACIFIC_CLI_POLICY_PRINCIPALS_PATH}/me"
|
|
10
|
+
PACIFIC_CLI_POLICY_ATTACHMENTS_SEGMENT = "policies"
|
|
11
|
+
|
|
12
|
+
#: The largest page the policy list routes serve (``POLICY_PAGE_ITEMS_CEILING``).
|
|
13
|
+
PACIFIC_CLI_POLICY_PAGE_SIZE = 200
|
|
14
|
+
|
|
15
|
+
#: The ``error`` of a write sent with a stale ``metadata.version``.
|
|
16
|
+
PACIFIC_CLI_POLICY_VERSION_CONFLICT = "version_conflict"
|
|
17
|
+
|
|
18
|
+
#: A policy file read as YAML; any other suffix is read as JSON.
|
|
19
|
+
PACIFIC_CLI_POLICY_YAML_SUFFIXES = frozenset({".yaml", ".yml"})
|
|
20
|
+
|
|
21
|
+
#: What the server answers when an organization has not opted into the Policy
|
|
22
|
+
#: API: the router answers a plain 404 rather than say the feature exists.
|
|
23
|
+
#: The issue code the server answers when an Agent document would create an
|
|
24
|
+
#: agent without the MCP terms being accepted.
|
|
25
|
+
PACIFIC_CLI_POLICY_MCP_TOS_NOT_ACCEPTED = "mcp_tos_not_accepted"
|
|
26
|
+
PACIFIC_CLI_POLICY_MCP_TOS_HINT = (
|
|
27
|
+
"Creating an agent accepts the Pacific MCP terms of service for you and on "
|
|
28
|
+
"the agent's behalf. Read them, then pass --accept-mcp-terms."
|
|
29
|
+
)
|
|
30
|
+
PACIFIC_CLI_POLICY_API_OFF_HINT = (
|
|
31
|
+
"If every policy command answers 404, the Policy API is off for your "
|
|
32
|
+
"organization: an administrator turns on access_policy_api_enabled."
|
|
33
|
+
)
|