formist-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,375 @@
1
+ """Which `fm` subcommand needs what: the privilege audit, as data.
2
+
3
+ `fm` must be fully usable with an ordinary user's login and must not do
4
+ anything that oversteps that user's privilege. "Usable" and "bounded" are
5
+ only compatible if it is written down which commands are which, so this
6
+ table exists, and a test fails if a subcommand is added without an entry.
7
+ A new command cannot be shipped unclassified.
8
+
9
+ This table is not a security control and must never become one. The
10
+ server is the trust boundary: it decides, on every single call, both
11
+ whether the account is a platform admin and whether this credential was
12
+ granted the admin scope. What the table buys is a better failure: without
13
+ it, running ``fm users`` on a normal login produces a 403 phrased as an
14
+ HTTP status after a network round-trip. With it, `fm` says which
15
+ privilege is missing and how to get it, before opening a socket, and it
16
+ says so in a way that does not suggest a workaround, because there isn't
17
+ one.
18
+
19
+ The check is advisory in one direction only, and that is deliberate. It
20
+ refuses early only when the stored credential positively records that it
21
+ lacks the admin scope (``fm login`` writes the granted scopes beside the
22
+ token). A credential with no recorded scopes (an older file, a
23
+ hand-placed one) is passed through to the server rather than guessed
24
+ about. A local check that can say "no" to something the server would
25
+ have allowed is the failure mode this codebase keeps finding: the thing
26
+ being checked stops being the thing being used.
27
+
28
+ Levels:
29
+
30
+ ``LEVEL_LOCAL`` touches no API at all (``fm gate``, ``fm heads``, ``fm use``).
31
+ ``LEVEL_PUBLIC`` an unauthenticated endpoint (``fm health`` without ``--admin``).
32
+ ``LEVEL_USER`` the caller's own permissions: project membership and role decide
33
+ it server-side. This is what an ordinary login is for, and it is the
34
+ majority of the tool.
35
+ ``LEVEL_ADMIN`` needs ``User.is_platform_admin`` and the ``admin`` scope on the
36
+ credential. Two shapes reach it, and both are gated by the same
37
+ server-side check: the ``/admin/*`` surface, and a handful of
38
+ project-scoped paths under ``/projects/{space}/admin/...`` that end
39
+ at the same platform-admin check, which is why a space owner role
40
+ neither grants nor withholds it.
41
+ ``LEVEL_MIXED`` subcommands differ, or one flag crosses the line (``fm health
42
+ --admin``). Never refused early: the table cannot see which
43
+ subcommand is about to run, so refusing would refuse the user-level
44
+ half as well.
45
+
46
+ A second, independent gate sits beside this table and is NOT about scopes at all:
47
+ every LEVEL_ADMIN command, and every admin-only branch of a LEVEL_MIXED one, also
48
+ requires the ``--admin`` flag on the command line itself (:func:`require_admin_flag`).
49
+ A credential that happens to carry the admin scope does not skip it. The point is
50
+ not "can this credential reach the server" (the server decides that, every time);
51
+ it is that the admin-only surface stays behind one explicit flag rather than being
52
+ the thing a bare `fm spaces` happens to do.
53
+ """
54
+
55
+ from __future__ import annotations
56
+
57
+ from dataclasses import dataclass
58
+
59
+ #: The OAuth scopes this client asks for, and the ``software_id`` it
60
+ #: registers itself under.
61
+ #:
62
+ #: Duplicated as plain strings rather than imported, and that is a rule,
63
+ #: not laziness: this CLI is stdlib-only by design and must run under a
64
+ #: bare system ``python3`` with no venv, including at deploy time, where
65
+ #: the server's dependency tree is not present. A test asserts each
66
+ #: string equals the server's own constant, which is what makes the
67
+ #: duplication safe rather than a promise.
68
+ SCOPE_KB = "evane:kb"
69
+ SCOPE_CLI = "evane:cli"
70
+ SCOPE_ADMIN = "evane:admin"
71
+ CLI_SOFTWARE_ID = "formist-cli"
72
+
73
+ #: Prefixed, and not for tidiness: a bare ``LEVEL_LOCAL`` / ``LEVEL_USER`` at a
74
+ #: module's top level is a name any module might bind to mean something
75
+ #: else entirely, and a name that means two things in one codebase is one
76
+ #: refactor away from someone importing the wrong one. The prefix costs
77
+ #: five characters and removes the ambiguity instead of declaring it.
78
+ LEVEL_LOCAL = "local"
79
+ LEVEL_PUBLIC = "public"
80
+ LEVEL_USER = "user"
81
+ LEVEL_ADMIN = "admin"
82
+ LEVEL_MIXED = "mixed"
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class Privilege:
87
+ level: str
88
+ #: The endpoint(s) this command calls, as they appear in the source. Prose is
89
+ #: allowed for the non-HTTP ones: the point is that a reader can check the
90
+ #: claim, not that a machine can parse it.
91
+ endpoints: tuple[str, ...]
92
+ note: str = ""
93
+
94
+
95
+ #: Keys must equal ``formist_cli.cli._COMMANDS``' keys exactly, asserted
96
+ #: in both directions: a removed command must lose its row too, or the
97
+ #: table starts describing a tool that no longer exists.
98
+ TABLE: dict[str, Privilege] = {
99
+ # --- credentials ---------------------------------------------------------
100
+ "login": Privilege(
101
+ LEVEL_PUBLIC,
102
+ (
103
+ "GET /.well-known/oauth-authorization-server",
104
+ "POST /register",
105
+ "GET /authorize",
106
+ "POST /token",
107
+ ),
108
+ "the OAuth 2.1 flow the MCP connector uses; unauthenticated by "
109
+ "construction, it is how a credential is obtained",
110
+ ),
111
+ "logout": Privilege(
112
+ LEVEL_USER, ("POST /auth/apps/revoke",), "revokes only the caller's own grant"
113
+ ),
114
+ "whoami": Privilege(
115
+ LEVEL_USER, ("GET /auth/apps (only with --remote)",), "reads the local file"
116
+ ),
117
+ # --- read-only diagnostics ------------------------------------------------
118
+ "health": Privilege(
119
+ LEVEL_MIXED, ("GET /health", "GET /admin/health (only with --admin)"),
120
+ "public without --admin",
121
+ ),
122
+ "instance": Privilege(
123
+ LEVEL_ADMIN, ("GET /admin/instance",),
124
+ "build/migration identity has no user-level meaning",
125
+ ),
126
+ "doctor": Privilege(
127
+ LEVEL_LOCAL, ("GET /health",), "local config checks plus the public health probe"
128
+ ),
129
+ "use": Privilege(LEVEL_LOCAL, (), "writes the remembered space to the config dir"),
130
+ # --- the user's own spaces -------------------------------------------------
131
+ "get": Privilege(LEVEL_USER, ("GET /projects/{space}/...",)),
132
+ "chats": Privilege(
133
+ LEVEL_USER,
134
+ (
135
+ "GET /projects/{space}/chats",
136
+ "GET /projects/{space}/chats/{id}",
137
+ "GET /projects/{space}/chats/{id}/messages",
138
+ ),
139
+ ),
140
+ "chat": Privilege(LEVEL_USER, ("POST /projects/{space}/chats",)),
141
+ "export": Privilege(
142
+ LEVEL_USER,
143
+ (
144
+ "GET /projects/{space}/export",
145
+ "POST /projects/{space}/export/bundle",
146
+ "GET /projects/{space}/export/bundle/{file_id}",
147
+ ),
148
+ ),
149
+ "import": Privilege(LEVEL_USER, ("POST /projects/{space}/import",)),
150
+ "upload": Privilege(
151
+ LEVEL_USER,
152
+ (
153
+ "POST /projects/{space}/uploads/sessions",
154
+ "GET/DELETE /projects/{space}/uploads/sessions/{id}",
155
+ "GET /projects/{space}/files/{id}",
156
+ ),
157
+ ),
158
+ "skill-attach": Privilege(
159
+ LEVEL_USER, ("POST /projects/{space}/uploads/sessions", "GET /projects/{space}/skills/{id}")
160
+ ),
161
+ "entity-fields": Privilege(LEVEL_USER, ("GET /projects/{space}/entity-fields",)),
162
+ "diff": Privilege(LEVEL_USER, ("the export surface",), "compares two exports"),
163
+ # --- platform administration ------------------------------------------------
164
+ "spaces": Privilege(
165
+ LEVEL_MIXED,
166
+ (
167
+ "GET /projects (default: the caller's own spaces)",
168
+ "GET /admin/spaces (only with --admin: every space, every region)",
169
+ "POST /projects (`create`; the caller's own token, not --admin)",
170
+ "GET/PATCH/DELETE /admin/spaces/{space} (only with --admin)",
171
+ "GET /admin/spaces/{space}/members|invitations|skills|conversations|usage "
172
+ "(only with --admin)",
173
+ "POST /admin/spaces/{space}/transfer-ownership (only with --admin)",
174
+ "POST /admin/users/{id}/spaces (`add-member`; only with --admin)",
175
+ ),
176
+ "MIXED: `list` (the default, no subject needed) and `create` work for any "
177
+ "signed-in user; every other subject is platform-admin and needs --admin",
178
+ ),
179
+ "users": Privilege(
180
+ LEVEL_ADMIN,
181
+ (
182
+ "GET/POST /admin/users",
183
+ "GET/PATCH /admin/users/{id}",
184
+ "GET /admin/users/{id}/spaces",
185
+ "DELETE /admin/users/{id}/spaces/{space}",
186
+ "GET /admin/users/{id}/grants",
187
+ ),
188
+ "platform user management has no user-level meaning: there is nothing for "
189
+ "an ordinary signed-in user to default to",
190
+ ),
191
+ "proposals": Privilege(
192
+ LEVEL_MIXED,
193
+ (
194
+ "GET /projects/{space}/proposals (default: member)",
195
+ "GET /admin/spaces/{space}/proposals (only with --admin)",
196
+ "POST /admin/spaces/{space}/proposals/unstick (always needs --admin)",
197
+ ),
198
+ "MIXED: `list` (the default subject) works for any member of the space; "
199
+ "`unstick` is a platform-admin repair tool with no member-level equivalent",
200
+ ),
201
+ "audit-log": Privilege(
202
+ LEVEL_MIXED,
203
+ (
204
+ "GET /projects/{space}/audit-log (default: member)",
205
+ "GET /admin/spaces/{space}/audit-log (only with --admin: no membership needed)",
206
+ ),
207
+ "a member already sees their space's own audit log; --admin reads a space "
208
+ "this credential is not a member of",
209
+ ),
210
+ "connectors": Privilege(
211
+ LEVEL_MIXED,
212
+ (
213
+ "GET /projects/{space}/connections (default subject `list`: member)",
214
+ "GET /admin/spaces/{space}/connectors (only with --admin)",
215
+ "GET /admin/spaces/{space}/connectors/grants (`grants`; always needs --admin)",
216
+ ),
217
+ "MIXED: `list` (the default subject) works for any member of the space; "
218
+ "`grants` is a platform-admin view with no member-level equivalent",
219
+ ),
220
+ "logs": Privilege(
221
+ LEVEL_ADMIN, ("GET /admin/events", "GET /admin/events/{subject}"),
222
+ "also shells out to `az` for Log Analytics, which has its own identity",
223
+ ),
224
+ "space-plan": Privilege(LEVEL_ADMIN, ("GET/PUT /admin/spaces/{space}/plan",)),
225
+ "usage-tokens": Privilege(LEVEL_ADMIN, ("GET /admin/usage/tokens",)),
226
+ "alerts": Privilege(LEVEL_ADMIN, ("GET /admin/alerts", "GET /admin/alerts/conditions",)),
227
+ "messages": Privilege(
228
+ LEVEL_ADMIN,
229
+ ("GET /admin/messages/dedupe-scan", "POST /admin/messages/dedupe"),
230
+ ),
231
+ "settings": Privilege(LEVEL_ADMIN, ("GET/PUT /admin/settings",)),
232
+ "skill-library-install": Privilege(
233
+ LEVEL_USER,
234
+ (
235
+ "GET /projects/{space}/skill-library/packages",
236
+ "GET /projects/{space}/skills",
237
+ "POST /projects/{space}/skill-library/packages/{id}/install",
238
+ ),
239
+ "member-facing (require_member/require_writer): unlike skill-library-sync, "
240
+ "which writes the GLOBAL admin-only catalog, this installs one already-"
241
+ "synced package into the caller's own space, the same route the gallery's "
242
+ "own 'Install' button uses",
243
+ ),
244
+ # These three are NOT under /admin, and that is exactly why they are easy to
245
+ # misfile. They are project-scoped paths gated by the same platform-admin
246
+ # check as everything above.
247
+ "update": Privilege(
248
+ LEVEL_ADMIN, ("POST /projects/{space}/admin/data-changes",),
249
+ "bulk data changes: site-wide admin, not a space role",
250
+ ),
251
+ "airtable": Privilege(
252
+ LEVEL_ADMIN, ("POST /projects/{space}/admin/airtable/direction",),
253
+ ),
254
+ "whatsapp": Privilege(
255
+ LEVEL_ADMIN,
256
+ (
257
+ "GET/POST /admin/whatsapp/devices",
258
+ "GET /admin/whatsapp/devices/{id}",
259
+ "POST /admin/whatsapp/devices/{id}/{pair,start,stop,logout,mark-account-deleted}",
260
+ "GET /admin/whatsapp/devices/{id}/pairing",
261
+ "GET /admin/whatsapp/devices/{id}/groups",
262
+ "DELETE /admin/whatsapp/devices/{id}",
263
+ "GET /admin/whatsapp/runner",
264
+ "POST /admin/whatsapp/runner/{start,stop}",
265
+ ),
266
+ "platform-owned WhatsApp devices; every write is dry-run unless --apply",
267
+ ),
268
+ "kb": Privilege(
269
+ LEVEL_USER,
270
+ ("GET /projects/{space}/search", "GET /projects/{space}/files/{id}/content"),
271
+ ),
272
+ "meeting": Privilege(
273
+ LEVEL_USER,
274
+ (
275
+ "GET /projects/{space}/meetings",
276
+ "GET /projects/{space}/meetings/{task}/transcript",
277
+ "POST /projects/{space}/meetings/join-now (only with --apply)",
278
+ ),
279
+ ),
280
+ "files": Privilege(
281
+ LEVEL_MIXED,
282
+ (
283
+ "POST /projects/{space}/files/reevaluate (only with --apply)",
284
+ "POST /projects/{space}/files/{id}/reevaluate (only with --apply)",
285
+ "GET/POST /projects/{space}/admin/files/merge (always needs --admin)",
286
+ "GET /projects/{space}/files, GET /projects/{space}/files/{id}/download (download)",
287
+ ),
288
+ "MIXED because `fm files` carries three subcommands at different "
289
+ "levels: `reevaluate` and `download` are ordinary member reads/writes, "
290
+ "`merge` is platform-admin because hard-deleting the dropped row is "
291
+ "irreversible",
292
+ ),
293
+ "project": Privilege(
294
+ LEVEL_USER, ("POST /projects/{space}/logo (only with --apply)",)
295
+ ),
296
+ "connector": Privilege(
297
+ LEVEL_USER,
298
+ (
299
+ "POST /projects/{space}/connections/{id}/reauth (only with --apply)",
300
+ "GET /projects/{space}/connections/{id}/reauth/poll",
301
+ "POST /projects/{space}/connectors/{id}/sync (only with --apply)",
302
+ ),
303
+ "the caller's own space connections; the server's project ACL decides",
304
+ ),
305
+ "participants": Privilege(
306
+ LEVEL_ADMIN,
307
+ ("GET/POST /projects/{space}/admin/participants/dedupe",),
308
+ "the duplicate-people merge. Project-scoped but platform-admin gated: "
309
+ "participants are region-local data, so the surface cannot live "
310
+ "under a bare /admin path",
311
+ ),
312
+ "skills-add": Privilege(
313
+ LEVEL_USER,
314
+ ("POST /projects/{space}/skills/import",),
315
+ "creates a skill from a SKILL.md, through require_writer and apply_change "
316
+ "(actor_type=HUMAN), identical to a member typing one into the app",
317
+ ),
318
+ "skills-update": Privilege(
319
+ LEVEL_USER,
320
+ ("PATCH /projects/{space}/skills/{id}/import",),
321
+ "updates an existing skill IN PLACE through the same require_writer gate; "
322
+ "never creates a second row",
323
+ ),
324
+ }
325
+
326
+
327
+ class PrivilegeError(Exception):
328
+ """A refusal raised before any request. The message is written for a human."""
329
+
330
+
331
+ def level_for(command: str) -> str | None:
332
+ entry = TABLE.get(command)
333
+ return entry.level if entry else None
334
+
335
+
336
+ def requires_admin(command: str) -> bool:
337
+ return level_for(command) == LEVEL_ADMIN
338
+
339
+
340
+ def check(command: str, scopes: object) -> None:
341
+ """Refuse an LEVEL_ADMIN command whose credential positively lacks the admin scope.
342
+
343
+ ``scopes`` is what `fm login` recorded beside the token. ``None``/empty means
344
+ "not recorded" and is passed through, see the module docstring on why this
345
+ check only ever says no to something it KNOWS the server would also refuse.
346
+ """
347
+ if not requires_admin(command):
348
+ return
349
+ if not isinstance(scopes, (list, tuple)) or not scopes:
350
+ return
351
+ if SCOPE_ADMIN in scopes:
352
+ return
353
+ raise PrivilegeError(
354
+ f"`fm {command}` is a platform-admin action and this credential was not "
355
+ f"granted the '{SCOPE_ADMIN}' scope (it has: {', '.join(map(str, scopes))}).\n"
356
+ "This is not something the CLI can work around; the server decides, on "
357
+ "every call. If your account IS a platform admin, run `fm login --admin` "
358
+ "and approve the platform-administration scope on the authorization page. "
359
+ "If it is not, this action is not available to you."
360
+ )
361
+
362
+
363
+ def require_admin_flag(label: str, admin_flag: bool) -> None:
364
+ """Refuse before any request when ``--admin`` was not passed.
365
+
366
+ Independent of :func:`check` and of what scopes are recorded: this is the
367
+ gate that keeps an admin-only command, or an admin-only branch of a MIXED
368
+ one, off the default path. It fires on the missing FLAG alone, not on the
369
+ credential, so it refuses the same way whether or not this login actually
370
+ is a platform admin. ``label`` is how the caller names itself in the
371
+ message, e.g. ``"fm users"`` or ``"fm spaces members"``.
372
+ """
373
+ if admin_flag:
374
+ return
375
+ raise PrivilegeError(f"`{label}` needs --admin (platform administrators only).")
@@ -0,0 +1,127 @@
1
+ """``fm project set-logo``: upload a project's logo image (write).
2
+
3
+ Uploads a local image via a plain multipart ``POST /projects/{id}/logo``.
4
+ The server sniffs the magic bytes (png/jpeg/gif/webp) rather than
5
+ trusting the declared Content-Type, so an SVG cannot be uploaded as an
6
+ image.
7
+
8
+ Idempotent (re-running overwrites the stored URL), but still a write:
9
+ dry run by default, ``--apply`` performs the upload. There is no
10
+ ``--url`` mode to reuse an existing blob; the server always uploads
11
+ the bytes it is given.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import mimetypes
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ from formist_cli import api, context
23
+ from formist_cli.cli_support import build_standalone_parser as _build_standalone_parser
24
+
25
+
26
+ class ProjectsError(Exception):
27
+ """A refusal about the project surface, written for an operator."""
28
+
29
+
30
+ SUBJECTS = ("set-logo",)
31
+
32
+ _DESCRIPTION = """Project-level operations.
33
+
34
+ fm project set-logo <path> --space <id> dry run
35
+ fm project set-logo <path> --space <id> --apply upload for real
36
+
37
+ A project id/UUID may also be given positionally instead of --space, matching
38
+ `fm connectors <space-id>`.
39
+ """
40
+
41
+
42
+ def add_parser(subparsers) -> argparse.ArgumentParser:
43
+ parser = subparsers.add_parser(
44
+ "project",
45
+ help="project-level ops: set-logo (WRITE)",
46
+ description=_DESCRIPTION,
47
+ formatter_class=argparse.RawDescriptionHelpFormatter,
48
+ )
49
+ _add_arguments(parser)
50
+ return parser
51
+
52
+
53
+ def _add_arguments(parser: argparse.ArgumentParser) -> None:
54
+ from formist_cli.cli import _add_env, _add_space
55
+
56
+ _add_env(parser, for_write=True)
57
+ _add_space(parser)
58
+ parser.add_argument("subject", help=f"one of: {', '.join(SUBJECTS)}")
59
+ parser.add_argument("path", nargs="?", default=None, help="local image path")
60
+ parser.add_argument(
61
+ "space_id", nargs="?", default=None,
62
+ help="project UUID (an alternative to --space)",
63
+ )
64
+ parser.add_argument("--apply", action="store_true", help="perform the upload (default: dry run)")
65
+ parser.add_argument("--json", action="store_true", help="raw JSON instead of a report")
66
+
67
+
68
+ def build_standalone_parser() -> argparse.ArgumentParser:
69
+ return _build_standalone_parser(add_parser)
70
+
71
+
72
+ def _subject_error(subject: object) -> ProjectsError:
73
+ return ProjectsError(
74
+ f"unknown subcommand {subject!r}. Valid: {', '.join(SUBJECTS)}."
75
+ )
76
+
77
+
78
+ def run(args) -> int:
79
+ subject = (getattr(args, "subject", None) or "").strip().lower()
80
+ if subject not in SUBJECTS:
81
+ raise _subject_error(getattr(args, "subject", None))
82
+
83
+ # The space_id positional is optional and merges before context.resolve
84
+ # runs, since resolve only reads args.space.
85
+ if getattr(args, "space_id", None) and not getattr(args, "space", None):
86
+ args.space = args.space_id
87
+
88
+ if not args.path:
89
+ raise ProjectsError(
90
+ "`fm project set-logo` needs a local image path.\n"
91
+ "Usage: fm project set-logo <path> --space <id> [--apply]"
92
+ )
93
+ image_path = Path(args.path)
94
+ if not image_path.is_file():
95
+ raise ProjectsError(f"no such file: {image_path}")
96
+
97
+ ctx = context.resolve(args, for_write=True, need_space=True, need_token=True)
98
+
99
+ if not args.apply:
100
+ print(
101
+ f"DRY RUN: nothing was changed.\n"
102
+ f"Would upload {image_path} ({image_path.stat().st_size} bytes) as the "
103
+ f"logo for project {ctx.space} ({ctx.target.name}).\n"
104
+ f"To apply: re-run with --apply.",
105
+ file=sys.stderr,
106
+ )
107
+ return 0
108
+
109
+ data = image_path.read_bytes()
110
+ content_type = mimetypes.guess_type(image_path.name)[0] or "application/octet-stream"
111
+ payload = api.post_multipart(
112
+ ctx.target,
113
+ f"/projects/{ctx.space}/logo",
114
+ fields={},
115
+ files={"file": (image_path.name, data)},
116
+ token=ctx.token,
117
+ )
118
+ if not isinstance(payload, dict):
119
+ raise ProjectsError(
120
+ f"expected a JSON object from /projects/{{id}}/logo, got {type(payload).__name__}."
121
+ )
122
+ if args.json:
123
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
124
+ else:
125
+ print(f"uploaded {len(data)} bytes ({content_type})")
126
+ print(f"logo -> {payload.get('logo')}")
127
+ return 0