hermes-access-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,131 @@
1
+ """``sync``, ``check``, ``impact``, ``audit``, ``publish``, ``doctor``."""
2
+
3
+ from datetime import datetime
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import typer
8
+ from hermes_access_admin.domain.changes import ChangeSet
9
+ from hermes_access_admin.domain.reports import CheckRequest
10
+ from pydantic import TypeAdapter, ValidationError
11
+
12
+ from hermes_access_cli.adapters.files import read_document
13
+ from hermes_access_cli.cli.options import Format, FormatOpt
14
+ from hermes_access_cli.cli.parse import (
15
+ entity_ref,
16
+ parse_action,
17
+ parse_context,
18
+ parse_resource,
19
+ parse_since,
20
+ )
21
+ from hermes_access_cli.cli.render import (
22
+ audit_text,
23
+ check_text,
24
+ doctor_text,
25
+ emit,
26
+ impact_text,
27
+ publish_text,
28
+ sync_text,
29
+ )
30
+ from hermes_access_cli.cli.state import EXIT_ERROR, cli_context, guarded
31
+ from hermes_access_cli.domain.errors import InputError
32
+
33
+ CLIENT_NAME = "cli"
34
+ APP_NAME = "hermes-access"
35
+
36
+
37
+ def build_check_request(
38
+ email: str,
39
+ action: str,
40
+ resource: str,
41
+ groups: list[str] | None,
42
+ context: list[str],
43
+ ) -> CheckRequest:
44
+ """Delegate: the request (``groups`` None = unknown). Context always carries client and app."""
45
+ merged = {"client": CLIENT_NAME, "app": APP_NAME, **parse_context(context)}
46
+ return CheckRequest(
47
+ email=entity_ref("user", email).id,
48
+ groups=None if groups is None else frozenset(groups),
49
+ action=parse_action(action),
50
+ resource=parse_resource(resource),
51
+ context=merged,
52
+ )
53
+
54
+
55
+ def load_change(path: Path) -> ChangeSet:
56
+ """Parse a JSON/YAML ``ChangeSet`` file with the contract model."""
57
+ try:
58
+ return TypeAdapter(ChangeSet).validate_python(read_document(path))
59
+ except ValidationError as exc:
60
+ raise InputError(
61
+ f"{path} is not a valid change set: {exc.error_count()} problem(s): {exc.errors()[0]['msg']}"
62
+ ) from exc
63
+
64
+
65
+ def sync(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
66
+ """Inventory profiles and boards from the Hermes home into the store."""
67
+ emit(cli_context(ctx).admin().sync(), fmt, sync_text)
68
+
69
+
70
+ def check( # noqa: PLR0913, PLR0917 - one parameter per CLI option
71
+ ctx: typer.Context,
72
+ email: Annotated[str, typer.Argument(help="User email.")],
73
+ action: Annotated[str, typer.Argument(help='Hermes::Action::"profile.view" or profile.view.')],
74
+ resource: Annotated[str, typer.Argument(help='Hermes::Profile::"assistant" or profile:assistant.')],
75
+ group: Annotated[list[str] | None, typer.Option("--group", help="Token group id; repeatable.")] = None,
76
+ ctx_pairs: Annotated[
77
+ list[str] | None, typer.Option("--ctx", help="Context key=value; repeatable.")
78
+ ] = None,
79
+ groups_unknown: Annotated[
80
+ bool, typer.Option("--groups-unknown", help="Evaluate with groups UNKNOWN.")
81
+ ] = False,
82
+ fmt: FormatOpt = Format.text,
83
+ ) -> None:
84
+ """Decide one request; a denial is not an error (exit 0)."""
85
+ groups = None if groups_unknown else list(group or [])
86
+ request = build_check_request(email, action, resource, groups, list(ctx_pairs or []))
87
+ emit(cli_context(ctx).admin().check(request), fmt, check_text)
88
+
89
+
90
+ def impact(
91
+ ctx: typer.Context,
92
+ change_file: Annotated[Path, typer.Argument(help="JSON/YAML ChangeSet.")],
93
+ fmt: FormatOpt = Format.text,
94
+ ) -> None:
95
+ """Report who would gain and lose what for a change file (writes nothing)."""
96
+ emit(cli_context(ctx).admin().impact(load_change(change_file)), fmt, impact_text)
97
+
98
+
99
+ def audit(
100
+ ctx: typer.Context,
101
+ since: Annotated[str | None, typer.Option("--since", help="7d, 12h, 30m or an ISO date.")] = None,
102
+ who: Annotated[str | None, typer.Option("--who", help="Only this actor.")] = None,
103
+ fmt: FormatOpt = Format.text,
104
+ ) -> None:
105
+ """Show the audit log, newest first."""
106
+ cli = cli_context(ctx)
107
+ moment: datetime | None = parse_since(since, cli.runtime.now()) if since else None
108
+ emit(cli.admin().audit(moment, who), fmt, audit_text)
109
+
110
+
111
+ def publish(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
112
+ """Build the snapshot from the store and write it to every sink."""
113
+ emit(cli_context(ctx).admin().publish(), fmt, publish_text)
114
+
115
+
116
+ def doctor(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
117
+ """Check store, schema, policies, sinks and snapshot freshness; exit 1 when a check fails."""
118
+ report = cli_context(ctx).admin().doctor()
119
+ emit(report, fmt, doctor_text)
120
+ if not report.ok:
121
+ raise typer.Exit(EXIT_ERROR)
122
+
123
+
124
+ def register(app: typer.Typer) -> None:
125
+ """Add these commands to the root app (each wrapped by ``guarded``)."""
126
+ app.command()(guarded(sync))
127
+ app.command()(guarded(check))
128
+ app.command()(guarded(impact))
129
+ app.command()(guarded(audit))
130
+ app.command()(guarded(publish))
131
+ app.command()(guarded(doctor))
@@ -0,0 +1,18 @@
1
+ """Shared option types."""
2
+
3
+ from enum import StrEnum
4
+ from typing import Annotated
5
+
6
+ import typer
7
+
8
+
9
+ class Format(StrEnum):
10
+ """Output format."""
11
+
12
+ text = "text"
13
+ json = "json"
14
+
15
+
16
+ FormatOpt = Annotated[Format, typer.Option("--format", help="Output format.")]
17
+ DryRunOpt = Annotated[bool, typer.Option("--dry-run", help="Report the impact; write nothing.")]
18
+ ReasonOpt = Annotated[str, typer.Option("--reason", help="Why (kept in the audit log).")]
@@ -0,0 +1,92 @@
1
+ """Pure parsers for command arguments (no I/O)."""
2
+
3
+ import json
4
+ import re
5
+ from collections.abc import Sequence
6
+ from datetime import UTC, datetime, timedelta
7
+
8
+ from hermes_access_admin.domain.reports import EntityKind
9
+ from hermes_access_client.domain.errors import HermesAccessError
10
+ from hermes_access_client.domain.refs import (
11
+ BOARD_TYPE,
12
+ GROUP_TYPE,
13
+ HERMES_NAMESPACE,
14
+ PROFILE_TYPE,
15
+ ROLE_TYPE,
16
+ USER_TYPE,
17
+ ActionRef,
18
+ CedarValue,
19
+ EntityRef,
20
+ )
21
+
22
+ from hermes_access_cli.domain.errors import InputError
23
+
24
+ KIND_TYPES: dict[EntityKind, str] = {
25
+ "user": USER_TYPE,
26
+ "group": GROUP_TYPE,
27
+ "role": ROLE_TYPE,
28
+ "profile": PROFILE_TYPE,
29
+ "board": BOARD_TYPE,
30
+ }
31
+ _UNITS = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}
32
+ _SINCE = re.compile(r"^(\d+)([smhdw])$")
33
+
34
+
35
+ def entity_ref(kind: EntityKind, ident: str) -> EntityRef:
36
+ """The ref of ``ident`` of ``kind`` (users are keyed by lower-case email)."""
37
+ return EntityRef(KIND_TYPES[kind], ident.lower() if kind == "user" else ident)
38
+
39
+
40
+ def parse_resource(text: str) -> EntityRef:
41
+ """``Hermes::Profile::"household"`` or the short form ``profile:household``."""
42
+ if '"' in text:
43
+ try:
44
+ return EntityRef.parse(text)
45
+ except HermesAccessError as exc:
46
+ raise InputError(str(exc)) from exc
47
+ kind, sep, ident = text.partition(":")
48
+ if not sep or not ident or kind not in KIND_TYPES:
49
+ raise InputError(f'resource must be Type::"id" or <{"|".join(KIND_TYPES)}>:<id>, got {text!r}')
50
+ return entity_ref(kind, ident) # type: ignore[arg-type] # narrowed by the membership test above
51
+
52
+
53
+ def parse_action(text: str) -> ActionRef:
54
+ """``Hermes::Action::"profile.view"`` or the short form ``profile.view``."""
55
+ if '"' not in text:
56
+ return ActionRef(HERMES_NAMESPACE, text)
57
+ try:
58
+ return ActionRef.parse(text)
59
+ except HermesAccessError as exc:
60
+ raise InputError(str(exc)) from exc
61
+
62
+
63
+ def parse_context(items: Sequence[str]) -> dict[str, str]:
64
+ """``key=value`` pairs into a mapping."""
65
+ context: dict[str, str] = {}
66
+ for item in items:
67
+ key, sep, value = item.partition("=")
68
+ if not sep or not key:
69
+ raise InputError(f"--ctx expects key=value, got {item!r}")
70
+ context[key] = value
71
+ return context
72
+
73
+
74
+ def parse_since(text: str, now: datetime) -> datetime:
75
+ """``7d``/``12h``/``30m``/``2w`` before ``now``, or an ISO date/time (naive means UTC)."""
76
+ match = _SINCE.match(text.strip())
77
+ if match:
78
+ return now - timedelta(seconds=int(match.group(1)) * _UNITS[match.group(2)])
79
+ try:
80
+ moment = datetime.fromisoformat(text)
81
+ except ValueError as exc:
82
+ raise InputError(f"--since expects 7d, 12h, 30m or an ISO date, got {text!r}") from exc
83
+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
84
+
85
+
86
+ def parse_value(text: str) -> CedarValue:
87
+ """A JSON literal (``true``, ``3``, ``["a"]``) when ``text`` is one, else the string itself."""
88
+ try:
89
+ value: CedarValue = json.loads(text)
90
+ except ValueError:
91
+ return text
92
+ return value
@@ -0,0 +1,162 @@
1
+ """``policy`` (list, show, add, enable, disable, remove, test) and ``app`` (register, list, show, remove)."""
2
+
3
+ from pathlib import Path
4
+ from typing import Annotated
5
+
6
+ import typer
7
+ from hermes_access_admin.domain.changes import (
8
+ AddPolicy,
9
+ ChangeOp,
10
+ RegisterApp,
11
+ RemoveApp,
12
+ RemovePolicy,
13
+ SetPolicyEnabled,
14
+ )
15
+ from hermes_access_client.domain.manifest import parse_manifest
16
+
17
+ from hermes_access_cli.adapters.files import read_document, read_text
18
+ from hermes_access_cli.cli.changes import apply_change
19
+ from hermes_access_cli.cli.options import DryRunOpt, Format, FormatOpt, ReasonOpt
20
+ from hermes_access_cli.cli.render import (
21
+ app_text,
22
+ apps_text,
23
+ emit,
24
+ policies_text,
25
+ policy_text,
26
+ tests_text,
27
+ )
28
+ from hermes_access_cli.cli.state import EXIT_ERROR, cli_context, guarded
29
+ from hermes_access_cli.domain.errors import InputError
30
+
31
+ policy_app = typer.Typer(no_args_is_help=True, help="Manage Cedar policies.")
32
+ app_app = typer.Typer(no_args_is_help=True, help="Manage registered apps.")
33
+
34
+ PolicyId = Annotated[str, typer.Argument(metavar="ID", help="Policy id.")]
35
+
36
+
37
+ def add_policy_op(policy_id: str, file: Path | None, text: str | None, owner: str) -> ChangeOp:
38
+ """Delegate: ``AddPolicy`` from exactly one of ``--file`` and ``--text``."""
39
+ if (file is None) == (text is None):
40
+ raise InputError("give exactly one of --file and --text")
41
+ body = text if text is not None else read_text(file) if file is not None else ""
42
+ return AddPolicy(id=policy_id, text=body.strip(), owner=owner)
43
+
44
+
45
+ def register_op(manifest: Path) -> ChangeOp:
46
+ """Delegate: ``RegisterApp`` from a manifest file (``ManifestError`` when invalid)."""
47
+ return RegisterApp(manifest=parse_manifest(read_document(manifest)))
48
+
49
+
50
+ @policy_app.command("list")
51
+ @guarded
52
+ def policy_list(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
53
+ """List every stored policy."""
54
+ emit(cli_context(ctx).admin().list_policies(), fmt, policies_text)
55
+
56
+
57
+ @policy_app.command("show")
58
+ @guarded
59
+ def policy_show(ctx: typer.Context, policy_id: PolicyId, fmt: FormatOpt = Format.text) -> None:
60
+ """Show one policy."""
61
+ emit(cli_context(ctx).admin().show_policy(policy_id), fmt, policy_text)
62
+
63
+
64
+ @policy_app.command("add")
65
+ @guarded
66
+ def policy_add( # noqa: PLR0913, PLR0917 - one parameter per CLI option
67
+ ctx: typer.Context,
68
+ policy_id: PolicyId,
69
+ file: Annotated[Path | None, typer.Option("--file", help="Cedar file with the statement.")] = None,
70
+ text: Annotated[str | None, typer.Option("--text", help="The Cedar statement.")] = None,
71
+ owner: Annotated[str, typer.Option("--owner", help="admin or an app name.")] = "admin",
72
+ dry_run: DryRunOpt = False,
73
+ reason: ReasonOpt = "",
74
+ ) -> None:
75
+ """Add a policy."""
76
+ op = add_policy_op(policy_id, file, text, owner)
77
+ apply_change(ctx, (op,), dry_run=dry_run, reason=reason, fmt=Format.text)
78
+
79
+
80
+ @policy_app.command("enable")
81
+ @guarded
82
+ def policy_enable(
83
+ ctx: typer.Context, policy_id: PolicyId, dry_run: DryRunOpt = False, reason: ReasonOpt = ""
84
+ ) -> None:
85
+ """Enable a policy."""
86
+ op = SetPolicyEnabled(id=policy_id, enabled=True)
87
+ apply_change(ctx, (op,), dry_run=dry_run, reason=reason, fmt=Format.text)
88
+
89
+
90
+ @policy_app.command("disable")
91
+ @guarded
92
+ def policy_disable(
93
+ ctx: typer.Context, policy_id: PolicyId, dry_run: DryRunOpt = False, reason: ReasonOpt = ""
94
+ ) -> None:
95
+ """Disable a policy (kept, never published)."""
96
+ op = SetPolicyEnabled(id=policy_id, enabled=False)
97
+ apply_change(ctx, (op,), dry_run=dry_run, reason=reason, fmt=Format.text)
98
+
99
+
100
+ @policy_app.command("remove")
101
+ @guarded
102
+ def policy_remove(
103
+ ctx: typer.Context, policy_id: PolicyId, dry_run: DryRunOpt = False, reason: ReasonOpt = ""
104
+ ) -> None:
105
+ """Remove a policy."""
106
+ apply_change(ctx, (RemovePolicy(id=policy_id),), dry_run=dry_run, reason=reason, fmt=Format.text)
107
+
108
+
109
+ @policy_app.command("test")
110
+ @guarded
111
+ def policy_test(
112
+ ctx: typer.Context,
113
+ policy_id: Annotated[
114
+ str | None, typer.Option("--id", help="Only tests this policy takes part in.")
115
+ ] = None,
116
+ fmt: FormatOpt = Format.text,
117
+ ) -> None:
118
+ """Run the apps' manifest policy tests; exit 1 when one fails."""
119
+ results = cli_context(ctx).admin().run_policy_tests(policy_id)
120
+ emit(results, fmt, tests_text)
121
+ if not all(r.passed for r in results):
122
+ raise typer.Exit(EXIT_ERROR)
123
+
124
+
125
+ @app_app.command("register")
126
+ @guarded
127
+ def app_register(
128
+ ctx: typer.Context,
129
+ manifest: Annotated[Path, typer.Argument(help="Manifest v1 file (YAML or JSON).")],
130
+ dry_run: DryRunOpt = False,
131
+ reason: ReasonOpt = "",
132
+ ) -> None:
133
+ """Register or update an app from its manifest."""
134
+ apply_change(ctx, (register_op(manifest),), dry_run=dry_run, reason=reason, fmt=Format.text)
135
+
136
+
137
+ @app_app.command("list")
138
+ @guarded
139
+ def app_list(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
140
+ """List registered apps."""
141
+ emit(cli_context(ctx).admin().list_apps(), fmt, apps_text)
142
+
143
+
144
+ @app_app.command("show")
145
+ @guarded
146
+ def app_show(
147
+ ctx: typer.Context, name: Annotated[str, typer.Argument()], fmt: FormatOpt = Format.text
148
+ ) -> None:
149
+ """Show one app."""
150
+ emit(cli_context(ctx).admin().show_app(name), fmt, app_text)
151
+
152
+
153
+ @app_app.command("remove")
154
+ @guarded
155
+ def app_remove(
156
+ ctx: typer.Context,
157
+ name: Annotated[str, typer.Argument()],
158
+ dry_run: DryRunOpt = False,
159
+ reason: ReasonOpt = "",
160
+ ) -> None:
161
+ """Unregister an app and remove the policies it owns."""
162
+ apply_change(ctx, (RemoveApp(name=name),), dry_run=dry_run, reason=reason, fmt=Format.text)
@@ -0,0 +1,151 @@
1
+ """Rendering of admin results: ``--format json`` (the models dumped) or plain text."""
2
+
3
+ import json
4
+ from collections.abc import Callable
5
+ from typing import TypeVar
6
+
7
+ import typer
8
+ from hermes_access_admin.domain.reports import (
9
+ AppRecord,
10
+ AuditEntry,
11
+ ChangeResult,
12
+ CheckResult,
13
+ DoctorReport,
14
+ EntityRecord,
15
+ ImpactEntry,
16
+ ImpactReport,
17
+ PolicyRecord,
18
+ PolicyTestResult,
19
+ PublishResult,
20
+ SyncReport,
21
+ ValidationReport,
22
+ )
23
+ from pydantic import TypeAdapter
24
+
25
+ from hermes_access_cli.cli.options import Format
26
+
27
+ T = TypeVar("T")
28
+
29
+
30
+ def jsonable(value: object) -> object:
31
+ """``model_dump(mode="json")`` of any result model (they are pydantic-compatible dataclasses)."""
32
+ return TypeAdapter(type(value)).dump_python(value, mode="json")
33
+
34
+
35
+ def emit(value: T, fmt: Format, as_text: Callable[[T], str]) -> None:
36
+ """Print ``value`` as JSON or through ``as_text``."""
37
+ typer.echo(json.dumps(jsonable(value), indent=2) if fmt is Format.json else as_text(value))
38
+
39
+
40
+ def entities_text(records: tuple[EntityRecord, ...]) -> str:
41
+ """One entity id per line."""
42
+ return "\n".join(r.ref.id for r in records) or "(none)"
43
+
44
+
45
+ def entity_text(rec: EntityRecord) -> str:
46
+ """An entity with attributes and parents."""
47
+ lines = [str(rec.ref)]
48
+ lines += [f" {k} = {json.dumps(v)}" for k, v in sorted(rec.attrs.items())]
49
+ lines += [f" member of {p}" for p in rec.parents]
50
+ return "\n".join(lines)
51
+
52
+
53
+ def policies_text(records: tuple[PolicyRecord, ...]) -> str:
54
+ """One policy per line: id, owner, state."""
55
+ rows = [f"{p.id}\t{p.owner}\t{'enabled' if p.enabled else 'disabled'}" for p in records]
56
+ return "\n".join(rows) or "(none)"
57
+
58
+
59
+ def policy_text(rec: PolicyRecord) -> str:
60
+ """A policy with its text."""
61
+ state = "enabled" if rec.enabled else "disabled"
62
+ return f"{rec.id} (owner {rec.owner}, {state})\n{rec.text}"
63
+
64
+
65
+ def apps_text(records: tuple[AppRecord, ...]) -> str:
66
+ """One app per line."""
67
+ return "\n".join(f"{a.name}\t{a.namespace}" for a in records) or "(none)"
68
+
69
+
70
+ def app_text(rec: AppRecord) -> str:
71
+ """An app with its manifest."""
72
+ return f"{rec.name} (namespace {rec.namespace})\n{rec.manifest_json}"
73
+
74
+
75
+ def _impact_line(sign: str, e: ImpactEntry) -> str:
76
+ return f" {sign} {e.principal} {e.action} {e.resource}"
77
+
78
+
79
+ def impact_text(report: ImpactReport) -> str:
80
+ """Who gains and loses what."""
81
+ lines = [f"impact: {len(report.gained)} gained, {len(report.lost)} lost ({report.evaluated} evaluated)"]
82
+ lines += [_impact_line("+", e) for e in report.gained]
83
+ lines += [_impact_line("-", e) for e in report.lost]
84
+ return "\n".join(lines)
85
+
86
+
87
+ def tests_text(results: tuple[PolicyTestResult, ...]) -> str:
88
+ """Policy test results, failures marked."""
89
+ rows = [f" {'ok ' if t.passed else 'FAIL'} {t.app}: {t.name} (expect {t.expect})" for t in results]
90
+ passed = sum(t.passed for t in results)
91
+ return "\n".join([f"policy tests: {passed}/{len(results)} passed", *rows])
92
+
93
+
94
+ def change_text(result: ChangeResult, *, dry_run: bool) -> str:
95
+ """Impact, tests and what happened."""
96
+ if dry_run:
97
+ outcome = "dry run: nothing written"
98
+ elif result.applied:
99
+ outcome = f"applied (generation {result.generation})"
100
+ else:
101
+ outcome = "rejected: nothing written"
102
+ return "\n".join([impact_text(result.impact), tests_text(result.tests), outcome])
103
+
104
+
105
+ def sync_text(report: SyncReport) -> str:
106
+ """What sync added and removed."""
107
+ lines = [f"+ {r}" for r in report.added] + [f"- {r}" for r in report.removed]
108
+ lines.append(f"{len(report.added)} added, {len(report.removed)} removed, {report.unchanged} unchanged")
109
+ return "\n".join(lines)
110
+
111
+
112
+ def check_text(result: CheckResult) -> str:
113
+ """allow/deny, the deciding policies and the generation."""
114
+ verdict = "allow" if result.allow else "deny"
115
+ lines = [
116
+ verdict,
117
+ f"policies: {', '.join(result.policy_ids) or '(none)'}",
118
+ f"generation: {result.generation}",
119
+ ]
120
+ return "\n".join([*lines, *(f"error: {e}" for e in result.errors)])
121
+
122
+
123
+ def audit_text(entries: tuple[AuditEntry, ...]) -> str:
124
+ """One audited write per line."""
125
+ rows = [
126
+ f"{e.at.isoformat()}\t{e.actor.kind}:{e.actor.name}\t{e.outcome}\tgen {e.generation}\t{e.reason}"
127
+ for e in entries
128
+ ]
129
+ return "\n".join(rows) or "(none)"
130
+
131
+
132
+ def publish_text(result: PublishResult) -> str:
133
+ """The published snapshot."""
134
+ return (
135
+ f"published generation {result.generation} to {', '.join(result.sinks)} "
136
+ f"({result.policy_count} policies, {result.entity_count} entities)"
137
+ )
138
+
139
+
140
+ def doctor_text(report: DoctorReport) -> str:
141
+ """One line per check."""
142
+ return "\n".join(f"{'ok ' if c.ok else 'FAIL'} {c.name} {c.detail}".rstrip() for c in report.checks)
143
+
144
+
145
+ def validation_text(report: ValidationReport) -> str:
146
+ """ok, or one line per issue."""
147
+ if report.ok:
148
+ return "ok"
149
+ return "\n".join(
150
+ f"{i.code}: {i.message}" + (f" [{i.subject}]" if i.subject else "") for i in report.issues
151
+ )
@@ -0,0 +1,61 @@
1
+ """Per-invocation CLI state: the runtime (how to reach the admin) and the error guard."""
2
+
3
+ from collections.abc import Callable
4
+ from dataclasses import dataclass
5
+ from functools import wraps
6
+ from pathlib import Path
7
+ from typing import ParamSpec
8
+
9
+ import typer
10
+ from hermes_access_admin.domain.errors import AccessAdminError
11
+ from hermes_access_admin.services.api import AdminApi
12
+ from hermes_access_client.domain.errors import ConfigError, HermesAccessError
13
+
14
+ from hermes_access_cli.domain.errors import HermesAccessCliError
15
+ from hermes_access_cli.domain.runtime import Runtime
16
+
17
+ EXIT_ERROR = 1
18
+ EXIT_USAGE = 2
19
+
20
+ P = ParamSpec("P")
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class CliContext:
25
+ """Stored in ``ctx.obj`` by the root callback."""
26
+
27
+ config: Path | None
28
+ runtime: Runtime
29
+
30
+ def admin(self) -> AdminApi:
31
+ """The admin facade for the global ``--config``."""
32
+ return self.runtime.admin(self.config)
33
+
34
+
35
+ def cli_context(ctx: typer.Context) -> CliContext:
36
+ """The ``CliContext`` the root callback stored."""
37
+ obj: object = ctx.obj
38
+ if not isinstance(obj, CliContext): # pragma: no cover - the root callback always sets it
39
+ raise TypeError("root callback did not run")
40
+ return obj
41
+
42
+
43
+ def fail(message: str, code: int) -> typer.Exit:
44
+ """Print one clear line to stderr and return the ``Exit`` to raise."""
45
+ typer.echo(f"error: {message}", err=True)
46
+ return typer.Exit(code)
47
+
48
+
49
+ def guarded(func: Callable[P, None]) -> Callable[P, None]:
50
+ """Turn expected errors into one stderr line and an exit code (2 config/usage, 1 the rest)."""
51
+
52
+ @wraps(func)
53
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> None:
54
+ try:
55
+ func(*args, **kwargs)
56
+ except (ConfigError, HermesAccessCliError) as exc:
57
+ raise fail(str(exc), EXIT_USAGE) from exc
58
+ except (AccessAdminError, HermesAccessError) as exc:
59
+ raise fail(str(exc), EXIT_ERROR) from exc
60
+
61
+ return wrapper