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,341 @@
1
+ """Access policies over ``/public/v1/policy``: write, read, list, and attach to principals.
2
+
3
+ Reads need ``tools:read``; writes need ``tools:write``, a person (not an agent
4
+ key) who administers the organization, and the organization's Policy API
5
+ switched on. The server is the validator: ``apply --dry-run`` shows its verdict
6
+ without writing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Iterator
12
+ from http import HTTPMethod
13
+ from pathlib import Path
14
+ from urllib.parse import quote
15
+ from uuid import UUID
16
+
17
+ import yaml
18
+ from pydantic import BaseModel, JsonValue, TypeAdapter, ValidationError
19
+
20
+ from pacific_cli.auth.client import PacificCliApiClient, PacificCliQueryParams
21
+ from pacific_cli.auth.types import PacificCliApiError, PacificCliError
22
+ from pacific_cli.policy.config import (
23
+ PACIFIC_CLI_POLICY_API_OFF_HINT,
24
+ PACIFIC_CLI_POLICY_ATTACHMENTS_SEGMENT,
25
+ PACIFIC_CLI_POLICY_MCP_TOS_HINT,
26
+ PACIFIC_CLI_POLICY_MCP_TOS_NOT_ACCEPTED,
27
+ PACIFIC_CLI_POLICY_ME_PATH,
28
+ PACIFIC_CLI_POLICY_PAGE_SIZE,
29
+ PACIFIC_CLI_POLICY_PATH,
30
+ PACIFIC_CLI_POLICY_PRINCIPALS_PATH,
31
+ PACIFIC_CLI_POLICY_VERSION_CONFLICT,
32
+ PACIFIC_CLI_POLICY_YAML_SUFFIXES,
33
+ )
34
+ from pacific_cli.policy.types import (
35
+ PacificCliAttachment,
36
+ PacificCliAttachmentList,
37
+ PacificCliDeleted,
38
+ PacificCliDetached,
39
+ PacificCliPolicyErrorBody,
40
+ PacificCliPolicyKind,
41
+ PacificCliPolicyMe,
42
+ PacificCliPolicyName,
43
+ PacificCliPolicyObject,
44
+ PacificCliPolicyPage,
45
+ PacificCliPrincipal,
46
+ PacificCliPrincipalId,
47
+ PacificCliPrincipalKind,
48
+ PacificCliPrincipalPage,
49
+ )
50
+
51
+ _JSON = TypeAdapter(JsonValue)
52
+
53
+
54
+ class PacificCliPolicyService:
55
+ """The policy routes, with principals named by email or name as well as id."""
56
+
57
+ def __init__(self, client: PacificCliApiClient) -> None:
58
+ self._client = client
59
+
60
+ def me(self) -> PacificCliPolicyMe:
61
+ return self._call(
62
+ PacificCliPolicyMe, method=HTTPMethod.GET, path=PACIFIC_CLI_POLICY_ME_PATH
63
+ )
64
+
65
+ def objects(self, kind: PacificCliPolicyKind) -> Iterator[PacificCliPolicyObject]:
66
+ """Every object of one kind, by name."""
67
+ cursor: str | None = None
68
+ while True:
69
+ page = self._call(
70
+ PacificCliPolicyPage,
71
+ method=HTTPMethod.GET,
72
+ path=f"{PACIFIC_CLI_POLICY_PATH}/{kind.value}",
73
+ params=self._page(cursor),
74
+ )
75
+ yield from page.items
76
+ if page.next_cursor is None:
77
+ return
78
+ cursor = page.next_cursor
79
+
80
+ def object(
81
+ self, kind: PacificCliPolicyKind, *, name: PacificCliPolicyName
82
+ ) -> PacificCliPolicyObject:
83
+ return self._call(
84
+ PacificCliPolicyObject,
85
+ method=HTTPMethod.GET,
86
+ path=self._object_path(kind, name=name),
87
+ )
88
+
89
+ @staticmethod
90
+ def read_document(path: Path) -> PacificCliPolicyObject:
91
+ """A policy file (JSON, or YAML by its suffix) with a kind and a name."""
92
+ try:
93
+ text = path.read_text(encoding="utf-8")
94
+ except OSError as exc:
95
+ raise PacificCliError(f"Could not read {path}: {exc}") from exc
96
+ try:
97
+ if path.suffix.lower() in PACIFIC_CLI_POLICY_YAML_SUFFIXES:
98
+ return PacificCliPolicyObject.model_validate(yaml.safe_load(text))
99
+ return PacificCliPolicyObject.model_validate_json(text)
100
+ except (ValidationError, yaml.YAMLError) as exc:
101
+ raise PacificCliError(f"{path} is not a policy object: {exc}") from exc
102
+
103
+ def apply(
104
+ self,
105
+ document: PacificCliPolicyObject,
106
+ *,
107
+ activate: bool,
108
+ dry_run: bool,
109
+ overwrite: bool,
110
+ accepts_mcp_tos: bool,
111
+ ) -> JsonValue:
112
+ """Create the object, or write its next version; returns the server's answer.
113
+
114
+ The server refuses a write whose ``metadata.version`` is not the latest,
115
+ so two people cannot silently overwrite each other. ``overwrite`` reads
116
+ the latest version first and writes on top of it, for a file that is the
117
+ source of truth.
118
+
119
+ ``accepts_mcp_tos`` is the caller's own acceptance of the MCP terms,
120
+ which creating an agent requires. It is sent only when given, never
121
+ assumed: the server ignores it for anything that is not a new agent.
122
+ """
123
+ kind = document.kind.route
124
+ name = document.metadata.name
125
+ if overwrite:
126
+ current = self._existing(kind, name=name)
127
+ if current is not None:
128
+ document = document.model_copy(
129
+ update={
130
+ "metadata": document.metadata.model_copy(
131
+ update={"version": current.metadata.version}
132
+ )
133
+ }
134
+ )
135
+ params: dict[str, str | int | bool] = {"activate": activate, "dry_run": dry_run}
136
+ if accepts_mcp_tos:
137
+ params["accepts_mcp_tos"] = True
138
+ try:
139
+ response = self._client.request(
140
+ HTTPMethod.PUT,
141
+ path=self._object_path(kind, name=name),
142
+ params=params,
143
+ json_body=document.model_dump(mode="json", exclude_none=True),
144
+ )
145
+ except PacificCliApiError as exc:
146
+ raise self._refusal(exc) from exc
147
+ return _JSON.validate_json(response.content)
148
+
149
+ def delete(
150
+ self, kind: PacificCliPolicyKind, *, name: PacificCliPolicyName
151
+ ) -> PacificCliDeleted:
152
+ return self._call(
153
+ PacificCliDeleted,
154
+ method=HTTPMethod.DELETE,
155
+ path=self._object_path(kind, name=name),
156
+ )
157
+
158
+ def principals(
159
+ self, kind: PacificCliPrincipalKind, *, query: str | None
160
+ ) -> Iterator[PacificCliPrincipal]:
161
+ """The organization's principals of one kind; ``query`` matches a name, and a user's email for an admin."""
162
+ cursor: str | None = None
163
+ while True:
164
+ params = self._page(cursor)
165
+ if query is not None:
166
+ params["q"] = query
167
+ page = self._call(
168
+ PacificCliPrincipalPage,
169
+ method=HTTPMethod.GET,
170
+ path=f"{PACIFIC_CLI_POLICY_PRINCIPALS_PATH}/{kind.value}",
171
+ params=params,
172
+ )
173
+ yield from page.items
174
+ if page.next_cursor is None:
175
+ return
176
+ cursor = page.next_cursor
177
+
178
+ def principal_id(
179
+ self, kind: PacificCliPrincipalKind, *, reference: str
180
+ ) -> PacificCliPrincipalId:
181
+ """The id the attachment routes take, from an id, a user's email or a group's name.
182
+
183
+ Only an exact, unique match is taken: attaching a policy to the wrong
184
+ person is not something to guess at.
185
+ """
186
+ match kind:
187
+ case PacificCliPrincipalKind.AGENT | PacificCliPrincipalKind.SERVICE:
188
+ # An agent's id is its agent_id and a service's is its name.
189
+ return PacificCliPrincipalId(reference)
190
+ case PacificCliPrincipalKind.USER | PacificCliPrincipalKind.GROUP:
191
+ pacific_id = self._uuid(reference)
192
+ if pacific_id is not None:
193
+ return PacificCliPrincipalId(str(pacific_id))
194
+ wanted = reference.casefold()
195
+ matches = [
196
+ principal
197
+ for principal in self.principals(kind, query=reference)
198
+ if principal.name.casefold() == wanted
199
+ or (principal.email is not None and principal.email.casefold() == wanted)
200
+ ]
201
+ if len(matches) != 1:
202
+ found = "no" if not matches else f"{len(matches)}"
203
+ raise PacificCliError(
204
+ f"{found} {kind.value} matches {reference!r} exactly; pass its id "
205
+ f"(`pacific policy principals {kind.value} --query ...` lists them)"
206
+ )
207
+ return matches[0].id
208
+
209
+ def attached(
210
+ self, kind: PacificCliPrincipalKind, *, principal_id: PacificCliPrincipalId
211
+ ) -> PacificCliAttachmentList:
212
+ return self._call(
213
+ PacificCliAttachmentList,
214
+ method=HTTPMethod.GET,
215
+ path=self._attachments_path(kind, principal_id=principal_id),
216
+ )
217
+
218
+ def attach(
219
+ self,
220
+ kind: PacificCliPrincipalKind,
221
+ *,
222
+ principal_id: PacificCliPrincipalId,
223
+ policy: PacificCliPolicyName,
224
+ ) -> PacificCliAttachment:
225
+ return self._call(
226
+ PacificCliAttachment,
227
+ method=HTTPMethod.PUT,
228
+ path=self._attachment_path(kind, principal_id=principal_id, policy=policy),
229
+ )
230
+
231
+ def detach(
232
+ self,
233
+ kind: PacificCliPrincipalKind,
234
+ *,
235
+ principal_id: PacificCliPrincipalId,
236
+ policy: PacificCliPolicyName,
237
+ ) -> PacificCliDetached:
238
+ return self._call(
239
+ PacificCliDetached,
240
+ method=HTTPMethod.DELETE,
241
+ path=self._attachment_path(kind, principal_id=principal_id, policy=policy),
242
+ )
243
+
244
+ def _existing(
245
+ self, kind: PacificCliPolicyKind, *, name: PacificCliPolicyName
246
+ ) -> PacificCliPolicyObject | None:
247
+ try:
248
+ return self.object(kind, name=name)
249
+ except PacificCliApiError as exc:
250
+ if exc.status_code == 404:
251
+ return None
252
+ raise
253
+
254
+ def _call[ModelT: BaseModel](
255
+ self,
256
+ model: type[ModelT],
257
+ *,
258
+ method: HTTPMethod,
259
+ path: str,
260
+ params: PacificCliQueryParams | None = None,
261
+ ) -> ModelT:
262
+ try:
263
+ return self._client.parsed(model, method=method, path=path, params=params)
264
+ except PacificCliApiError as exc:
265
+ raise self._refusal(exc) from exc
266
+
267
+ @staticmethod
268
+ def _refusal(exc: PacificCliApiError) -> PacificCliApiError:
269
+ """The refusal in the policy API's own terms: its code, message and each issue."""
270
+ try:
271
+ body = PacificCliPolicyErrorBody.model_validate_json(exc.body)
272
+ except ValidationError:
273
+ if exc.status_code != 404:
274
+ return exc
275
+ return PacificCliApiError(
276
+ f"{exc.message}\n{PACIFIC_CLI_POLICY_API_OFF_HINT}",
277
+ status_code=exc.status_code,
278
+ body=exc.body,
279
+ )
280
+ lines = [f"{exc.status_code} {body.error}: {body.message}"]
281
+ for label, issues in (("error", body.errors), ("warning", body.warnings)):
282
+ for issue in issues or []:
283
+ lines.append(
284
+ f" {label} at {issue.path or '/'}: {issue.message} [{issue.code}]"
285
+ )
286
+ lines.extend(
287
+ f" try: {suggestion}" for suggestion in issue.suggestions
288
+ )
289
+ if body.references:
290
+ lines.append(f" still used by: {', '.join(body.references)}")
291
+ if any(
292
+ issue.code == PACIFIC_CLI_POLICY_MCP_TOS_NOT_ACCEPTED
293
+ for issue in body.errors or []
294
+ ):
295
+ lines.append(f" {PACIFIC_CLI_POLICY_MCP_TOS_HINT}")
296
+ if body.error == PACIFIC_CLI_POLICY_VERSION_CONFLICT:
297
+ lines.append(
298
+ f" The latest version is {body.latest}. Set metadata.version to it, "
299
+ "or pass --overwrite to write over it."
300
+ )
301
+ return PacificCliApiError(
302
+ "\n".join(lines), status_code=exc.status_code, body=exc.body
303
+ )
304
+
305
+ @staticmethod
306
+ def _uuid(reference: str) -> UUID | None:
307
+ """``reference`` as a Pacific id, or None when it is a name or an email instead."""
308
+ try:
309
+ return UUID(reference)
310
+ except ValueError:
311
+ return None
312
+
313
+ @staticmethod
314
+ def _page(cursor: str | None) -> dict[str, str | int | bool]:
315
+ params: dict[str, str | int | bool] = {"limit": PACIFIC_CLI_POLICY_PAGE_SIZE}
316
+ if cursor is not None:
317
+ params["cursor"] = cursor
318
+ return params
319
+
320
+ @staticmethod
321
+ def _object_path(kind: PacificCliPolicyKind, *, name: PacificCliPolicyName) -> str:
322
+ return f"{PACIFIC_CLI_POLICY_PATH}/{kind.value}/{quote(name, safe='')}"
323
+
324
+ @staticmethod
325
+ def _attachments_path(
326
+ kind: PacificCliPrincipalKind, *, principal_id: PacificCliPrincipalId
327
+ ) -> str:
328
+ return (
329
+ f"{PACIFIC_CLI_POLICY_PRINCIPALS_PATH}/{kind.value}/"
330
+ f"{quote(principal_id, safe='')}/{PACIFIC_CLI_POLICY_ATTACHMENTS_SEGMENT}"
331
+ )
332
+
333
+ def _attachment_path(
334
+ self,
335
+ kind: PacificCliPrincipalKind,
336
+ *,
337
+ principal_id: PacificCliPrincipalId,
338
+ policy: PacificCliPolicyName,
339
+ ) -> str:
340
+ base = self._attachments_path(kind, principal_id=principal_id)
341
+ return f"{base}/{quote(policy, safe='')}"
@@ -0,0 +1,235 @@
1
+ """What the CLI reads from and sends to ``/public/v1/policy``.
2
+
3
+ The server is the only validator of a policy object: a file is sent as written,
4
+ and the CLI reads just its kind, name and version, so a field the CLI has never
5
+ heard of still reaches the server. ``contract_test.py`` holds each response
6
+ model to the schema of the same name in ``docs/api/public_api_openapi.json``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from enum import StrEnum
12
+ from typing import NewType
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ #: A policy object's name; an agent's is its agent_id.
17
+ PacificCliPolicyName = NewType("PacificCliPolicyName", str)
18
+ #: What the attachment routes take: a user's or group's Pacific id, an agent's
19
+ #: agent_id, a service's name.
20
+ PacificCliPrincipalId = NewType("PacificCliPrincipalId", str)
21
+
22
+
23
+ class PacificCliPolicyKind(StrEnum):
24
+ """``PolicyKindSegment``: a kind as it appears in a route."""
25
+
26
+ PERMISSION_POLICIES = "permission-policies"
27
+ AGENTS = "agents"
28
+ SERVICES = "services"
29
+ RESOURCE_SETS = "resource-sets"
30
+
31
+
32
+ class PacificCliPolicyObjectKind(StrEnum):
33
+ """An object's ``kind`` as a document writes it; the server reads it in any case."""
34
+
35
+ PERMISSION_POLICY = "PermissionPolicy"
36
+ AGENT = "Agent"
37
+ SERVICE = "Service"
38
+ RESOURCE_SET = "ResourceSet"
39
+
40
+ @classmethod
41
+ def _missing_(cls, value: object) -> PacificCliPolicyObjectKind | None:
42
+ if not isinstance(value, str):
43
+ return None
44
+ return next((kind for kind in cls if kind.value.lower() == value.lower()), None)
45
+
46
+ @property
47
+ def route(self) -> PacificCliPolicyKind:
48
+ """The route segment objects of this kind are written under."""
49
+ match self:
50
+ case PacificCliPolicyObjectKind.PERMISSION_POLICY:
51
+ return PacificCliPolicyKind.PERMISSION_POLICIES
52
+ case PacificCliPolicyObjectKind.AGENT:
53
+ return PacificCliPolicyKind.AGENTS
54
+ case PacificCliPolicyObjectKind.SERVICE:
55
+ return PacificCliPolicyKind.SERVICES
56
+ case PacificCliPolicyObjectKind.RESOURCE_SET:
57
+ return PacificCliPolicyKind.RESOURCE_SETS
58
+
59
+
60
+ class PacificCliPrincipalKind(StrEnum):
61
+ """``PolicyPrincipalKind``: what a policy can be attached to."""
62
+
63
+ USER = "user"
64
+ GROUP = "group"
65
+ AGENT = "agent"
66
+ SERVICE = "service"
67
+
68
+
69
+ class PacificCliPolicyMetadata(BaseModel):
70
+ """``PolicyEnvelopeMetadata``: an object's name and the version it was read at."""
71
+
72
+ model_config = ConfigDict(frozen=True, extra="allow")
73
+
74
+ name: PacificCliPolicyName = Field(..., description="The object's name")
75
+ description: str | None = Field(None, description="What it is for")
76
+ version: int | None = Field(
77
+ None, description="The version read; absent on create, required on update"
78
+ )
79
+
80
+
81
+ class PacificCliPolicyStatus(BaseModel):
82
+ """``PolicyObjectStatus``: server-kept state."""
83
+
84
+ model_config = ConfigDict(frozen=True, extra="ignore")
85
+
86
+ active: bool = Field(..., description="The kill switch")
87
+
88
+
89
+ class PacificCliPolicyObject(BaseModel):
90
+ """``PolicyEnvelope``: a policy object as written and as read.
91
+
92
+ ``extra="allow"`` keeps ``api_version``, ``spec`` and anything else exactly
93
+ as the file or the server had them.
94
+ """
95
+
96
+ model_config = ConfigDict(frozen=True, extra="allow")
97
+
98
+ kind: PacificCliPolicyObjectKind = Field(..., description="The object's kind")
99
+ metadata: PacificCliPolicyMetadata = Field(..., description="Name and version")
100
+ status: PacificCliPolicyStatus | None = Field(
101
+ None, description="Server-kept; ignored on write"
102
+ )
103
+
104
+
105
+ class PacificCliPolicyPage(BaseModel):
106
+ """``PolicyListPage``."""
107
+
108
+ model_config = ConfigDict(frozen=True, extra="ignore")
109
+
110
+ items: list[PacificCliPolicyObject] = Field(..., description="The objects, by name")
111
+ next_cursor: str | None = Field(None, description="Null at the end")
112
+
113
+
114
+ class PacificCliPrincipal(BaseModel):
115
+ """``PolicyPrincipalView``."""
116
+
117
+ model_config = ConfigDict(frozen=True, extra="ignore")
118
+
119
+ kind: PacificCliPrincipalKind = Field(
120
+ ..., description="user, group, agent or service"
121
+ )
122
+ id: PacificCliPrincipalId = Field(
123
+ ..., description="What the attachment routes take"
124
+ )
125
+ prn: str = Field(..., description="What a policy names it by")
126
+ name: str = Field(..., description="Its display name")
127
+ email: str | None = Field(
128
+ None, description="A user's email, shown to administrators"
129
+ )
130
+
131
+
132
+ class PacificCliPrincipalPage(BaseModel):
133
+ """``PolicyPrincipalPage``."""
134
+
135
+ model_config = ConfigDict(frozen=True, extra="ignore")
136
+
137
+ items: list[PacificCliPrincipal] = Field(..., description="One page, by id")
138
+ next_cursor: str | None = Field(None, description="Null on the last page")
139
+
140
+
141
+ class PacificCliEnforcementScope(BaseModel):
142
+ """``PolicyEnforcementScope``: what the organization applies statements to now."""
143
+
144
+ model_config = ConfigDict(frozen=True, extra="ignore")
145
+
146
+ surfaces: list[str] = Field(
147
+ default_factory=list, description="Surfaces whose statements apply now"
148
+ )
149
+ document_statements_enforced: bool = Field(
150
+ False, description="Whether document statements apply to reads now"
151
+ )
152
+
153
+
154
+ class PacificCliAttachment(BaseModel):
155
+ """``PolicyAttachmentView``: a policy attached to a target."""
156
+
157
+ model_config = ConfigDict(frozen=True, extra="ignore")
158
+
159
+ policy: str = Field(..., description="prn:policy:<name>")
160
+ target: str = Field(
161
+ ..., description="A principal PRN, organization, or connector:<id>"
162
+ )
163
+ enforcement_scope: PacificCliEnforcementScope | None = Field(
164
+ None, description="What the organization applies now"
165
+ )
166
+
167
+
168
+ class PacificCliAttachmentList(BaseModel):
169
+ """``PolicyAttachmentList``: what applies to a principal, and through what."""
170
+
171
+ model_config = ConfigDict(frozen=True, extra="ignore")
172
+
173
+ items: list[PacificCliAttachment] = Field(..., description="Each attachment")
174
+ enforcement_scope: PacificCliEnforcementScope | None = Field(
175
+ None, description="What the organization applies now"
176
+ )
177
+
178
+
179
+ class PacificCliDetached(BaseModel):
180
+ """``PolicyDetachResponse``."""
181
+
182
+ model_config = ConfigDict(frozen=True, extra="ignore")
183
+
184
+ policy: str = Field(..., description="prn:policy:<name>")
185
+ target: str = Field(..., description="What it was detached from")
186
+
187
+
188
+ class PacificCliDeleted(BaseModel):
189
+ """``PolicyDeleteResponse``."""
190
+
191
+ model_config = ConfigDict(frozen=True, extra="ignore")
192
+
193
+ kind: str = Field(..., description="The object's kind")
194
+ name: str = Field(..., description="The object's name")
195
+
196
+
197
+ class PacificCliPolicyMe(BaseModel):
198
+ """``PolicyMe``: the caller as the policy engine sees them."""
199
+
200
+ model_config = ConfigDict(frozen=True, extra="ignore")
201
+
202
+ principal: PacificCliPrincipal = Field(..., description="The calling person")
203
+ is_admin: bool = Field(..., description="Whether they administer the organization")
204
+ groups: list[PacificCliPrincipal] = Field(..., description="Their directory groups")
205
+ policies: PacificCliAttachmentList = Field(..., description="What applies to them")
206
+
207
+
208
+ class PacificCliPolicyIssue(BaseModel):
209
+ """``PolicyValidationIssue``: one thing wrong with an object."""
210
+
211
+ model_config = ConfigDict(frozen=True, extra="ignore")
212
+
213
+ path: str = Field(..., description="JSON Pointer to the problem")
214
+ code: str = Field(..., description="A stable code")
215
+ message: str = Field(..., description="What is wrong")
216
+ suggestions: list[str] = Field(
217
+ default_factory=list, description="What would fix it"
218
+ )
219
+
220
+
221
+ class PacificCliPolicyErrorBody(BaseModel):
222
+ """``PolicyErrorBody``: every refusal the policy routes answer with."""
223
+
224
+ model_config = ConfigDict(frozen=True, extra="ignore")
225
+
226
+ error: str = Field(..., description="The error code")
227
+ message: str = Field(..., description="What happened")
228
+ errors: list[PacificCliPolicyIssue] | None = Field(None, description="Each error")
229
+ warnings: list[PacificCliPolicyIssue] | None = Field(
230
+ None, description="Each warning"
231
+ )
232
+ latest: int | None = Field(
233
+ None, description="The latest version, on version_conflict"
234
+ )
235
+ references: list[str] | None = Field(None, description="What still uses the object")