hermes-access-cli 0.1.0__tar.gz

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.
Files changed (33) hide show
  1. hermes_access_cli-0.1.0/.gitignore +16 -0
  2. hermes_access_cli-0.1.0/PKG-INFO +26 -0
  3. hermes_access_cli-0.1.0/README.md +11 -0
  4. hermes_access_cli-0.1.0/pyproject.toml +39 -0
  5. hermes_access_cli-0.1.0/src/hermes_access_cli/__init__.py +10 -0
  6. hermes_access_cli-0.1.0/src/hermes_access_cli/adapters/__init__.py +1 -0
  7. hermes_access_cli-0.1.0/src/hermes_access_cli/adapters/config_files.py +77 -0
  8. hermes_access_cli-0.1.0/src/hermes_access_cli/adapters/files.py +25 -0
  9. hermes_access_cli-0.1.0/src/hermes_access_cli/adapters/memory.py +142 -0
  10. hermes_access_cli-0.1.0/src/hermes_access_cli/app.py +49 -0
  11. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/__init__.py +3 -0
  12. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/changes.py +37 -0
  13. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/config.py +50 -0
  14. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/entities.py +130 -0
  15. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/main.py +55 -0
  16. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/ops.py +131 -0
  17. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/options.py +18 -0
  18. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/parse.py +92 -0
  19. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/policies.py +162 -0
  20. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/render.py +151 -0
  21. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/state.py +61 -0
  22. hermes_access_cli-0.1.0/src/hermes_access_cli/cli/validate.py +102 -0
  23. hermes_access_cli-0.1.0/src/hermes_access_cli/domain/__init__.py +1 -0
  24. hermes_access_cli-0.1.0/src/hermes_access_cli/domain/errors.py +11 -0
  25. hermes_access_cli-0.1.0/src/hermes_access_cli/domain/runtime.py +28 -0
  26. hermes_access_cli-0.1.0/src/hermes_access_cli/py.typed +0 -0
  27. hermes_access_cli-0.1.0/tests/conftest.py +29 -0
  28. hermes_access_cli-0.1.0/tests/integration/test_round_trip.py +227 -0
  29. hermes_access_cli-0.1.0/tests/test_cli_commands.py +283 -0
  30. hermes_access_cli-0.1.0/tests/test_cli_config_validate.py +175 -0
  31. hermes_access_cli-0.1.0/tests/test_cli_version.py +12 -0
  32. hermes_access_cli-0.1.0/tests/test_examples.py +49 -0
  33. hermes_access_cli-0.1.0/tests/test_smoke_hermes_access_cli.py +6 -0
@@ -0,0 +1,16 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.py[cod]
4
+ .pytest_cache/
5
+ .ruff_cache/
6
+ dist/
7
+ build/
8
+ *.egg-info/
9
+ # real config, stores and snapshots never belong in the repo (examples/ holds the example config)
10
+ hermes-access-control.yaml
11
+ *.db
12
+ *.db-wal
13
+ *.db-shm
14
+ *.snapshot.json
15
+ data/
16
+ .DS_Store
@@ -0,0 +1,26 @@
1
+ Metadata-Version: 2.5
2
+ Name: hermes-access-cli
3
+ Version: 0.1.0
4
+ Summary: The hermes-access command: manage and validate Hermes access control.
5
+ Project-URL: Homepage, https://github.com/ejlevin1/hermes-access
6
+ Project-URL: Issues, https://github.com/ejlevin1/hermes-access/issues
7
+ License-Expression: MIT
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Classifier: Typing :: Typed
11
+ Requires-Python: >=3.11
12
+ Requires-Dist: hermes-access-admin
13
+ Requires-Dist: typer>=0.12
14
+ Description-Content-Type: text/markdown
15
+
16
+ # hermes-access-cli
17
+
18
+ The `hermes-access` command: manage and validate Hermes access control.
19
+
20
+ ```sh
21
+ uv tool install hermes-access-cli
22
+ hermes-access config init
23
+ ```
24
+
25
+ Documentation: see the [root README](../../README.md) and the [command reference](../../docs/cli.md).
26
+ Part of hermes-access. License: MIT.
@@ -0,0 +1,11 @@
1
+ # hermes-access-cli
2
+
3
+ The `hermes-access` command: manage and validate Hermes access control.
4
+
5
+ ```sh
6
+ uv tool install hermes-access-cli
7
+ hermes-access config init
8
+ ```
9
+
10
+ Documentation: see the [root README](../../README.md) and the [command reference](../../docs/cli.md).
11
+ Part of hermes-access. License: MIT.
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "hermes-access-cli"
3
+ dynamic = ["version"]
4
+ description = "The hermes-access command: manage and validate Hermes access control."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.11"
8
+ dependencies = ["hermes-access-admin", "typer>=0.12"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3 :: Only",
11
+ "License :: OSI Approved :: MIT License",
12
+ "Typing :: Typed",
13
+ ]
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/ejlevin1/hermes-access"
17
+ Issues = "https://github.com/ejlevin1/hermes-access/issues"
18
+
19
+ [project.scripts]
20
+ hermes-access = "hermes_access_cli.cli.main:app"
21
+
22
+ [tool.uv.sources]
23
+ hermes-access-admin = { workspace = true }
24
+
25
+ [build-system]
26
+ requires = ["hatchling>=1.26", "hatch-vcs>=0.4"]
27
+ build-backend = "hatchling.build"
28
+
29
+ [tool.hatch.version]
30
+ source = "vcs"
31
+ tag-pattern = "^v(?P<version>.+)$"
32
+
33
+ [tool.hatch.version.raw-options]
34
+ root = "../.."
35
+ git_describe_command = ["git", "describe", "--dirty", "--tags", "--long", "--match", "v*"]
36
+ fallback_version = "0.0.0+unknown"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/hermes_access_cli"]
@@ -0,0 +1,10 @@
1
+ """The hermes-access command: manage and validate Hermes access control."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("hermes-access-cli")
7
+ except PackageNotFoundError: # pragma: no cover - source tree without install
8
+ __version__ = "0.0.0+unknown"
9
+
10
+ __all__ = ["__version__"]
@@ -0,0 +1 @@
1
+ """I/O of the CLI: reading input files, writing and inspecting the config file."""
@@ -0,0 +1,77 @@
1
+ """Writes and inspects the access-control config file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ from hermes_access_admin.domain.reports import ValidationIssue, ValidationReport
9
+ from hermes_access_client.domain.settings import AccessSettings, FileLocation
10
+
11
+ from hermes_access_cli.domain.errors import InputError
12
+
13
+ OWNER_ONLY = 0o600
14
+
15
+ CONFIG_TEMPLATE = """\
16
+ # hermes-access settings v1. Relative paths resolve against this file's directory.
17
+ v: 1
18
+ store:
19
+ path: hermes-access.db
20
+ snapshot:
21
+ sinks:
22
+ - kind: file
23
+ path: access-snapshot.json
24
+ source:
25
+ kind: file
26
+ path: access-snapshot.json
27
+ inventory:
28
+ hermes_home: ~/.hermes
29
+ tools:
30
+ profiles: []
31
+ audit:
32
+ log_denials: sample
33
+ """
34
+
35
+
36
+ def write_config(path: Path, *, force: bool) -> None:
37
+ """Write the v1 template to ``path`` with mode 0600; refuse to overwrite unless ``force``."""
38
+ if path.exists() and not force:
39
+ raise InputError(f"{path} already exists (use --force to overwrite)")
40
+ path.parent.mkdir(parents=True, exist_ok=True)
41
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, OWNER_ONLY)
42
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
43
+ handle.write(CONFIG_TEMPLATE)
44
+ path.chmod(OWNER_ONLY)
45
+
46
+
47
+ def _writable_dir(directory: Path) -> bool:
48
+ probe = directory
49
+ while not probe.exists() and probe != probe.parent:
50
+ probe = probe.parent
51
+ return probe.is_dir() and os.access(probe, os.W_OK)
52
+
53
+
54
+ def _issue(code: str, message: str, subject: str) -> ValidationIssue:
55
+ return ValidationIssue(code=code, message=message, subject=subject)
56
+
57
+
58
+ def _location_paths(settings: AccessSettings) -> tuple[tuple[str, Path], ...]:
59
+ found = [("store", settings.store.path)]
60
+ for i, sink in enumerate(settings.snapshot.sinks):
61
+ if isinstance(sink, FileLocation):
62
+ found.append((f"snapshot.sinks[{i}]", sink.path))
63
+ return tuple(found)
64
+
65
+
66
+ def inspect_config(path: Path, settings: AccessSettings) -> ValidationReport:
67
+ """Check a parsed config: file mode 0600 and writable locations (store and sinks)."""
68
+ issues: list[ValidationIssue] = []
69
+ mode = path.stat().st_mode & 0o777
70
+ if mode != OWNER_ONLY:
71
+ issues.append(_issue("mode", f"config mode is {mode:04o}, expected 0600", str(path)))
72
+ for name, target in _location_paths(settings):
73
+ if target.is_dir():
74
+ issues.append(_issue("path", f"{target} is a directory", name))
75
+ elif not (os.access(target, os.W_OK) if target.exists() else _writable_dir(target.parent)):
76
+ issues.append(_issue("writable", f"{target} is not writable", name))
77
+ return ValidationReport(issues=tuple(issues))
@@ -0,0 +1,25 @@
1
+ """Reads user-supplied input files (YAML or JSON documents and plain text)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import yaml
8
+
9
+ from hermes_access_cli.domain.errors import InputError
10
+
11
+
12
+ def read_text(path: Path) -> str:
13
+ """The text of ``path``; ``InputError`` when it cannot be read."""
14
+ try:
15
+ return path.read_text(encoding="utf-8")
16
+ except OSError as exc:
17
+ raise InputError(f"cannot read {path}: {exc.strerror}") from exc
18
+
19
+
20
+ def read_document(path: Path) -> object:
21
+ """Decode a YAML or JSON file (JSON is YAML); ``InputError`` when unreadable or malformed."""
22
+ try:
23
+ return yaml.safe_load(read_text(path))
24
+ except yaml.YAMLError as exc:
25
+ raise InputError(f"{path} is not valid YAML or JSON: {exc}") from exc
@@ -0,0 +1,142 @@
1
+ """``InMemoryAdmin``: an in-memory ``AdminApi`` that records its calls (the CLI tests' fake)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from datetime import UTC, datetime
7
+
8
+ from hermes_access_admin.domain.changes import Actor, ChangeSet
9
+ from hermes_access_admin.domain.reports import (
10
+ AppRecord,
11
+ AuditEntry,
12
+ ChangeResult,
13
+ CheckRequest,
14
+ CheckResult,
15
+ DoctorCheck,
16
+ DoctorReport,
17
+ EntityKind,
18
+ EntityRecord,
19
+ ImpactEntry,
20
+ ImpactReport,
21
+ PolicyRecord,
22
+ PolicyTestResult,
23
+ PublishResult,
24
+ SyncReport,
25
+ )
26
+ from hermes_access_client.domain.refs import ActionRef, EntityRef
27
+
28
+ MOMENT = datetime(2026, 1, 10, 12, 0, tzinfo=UTC)
29
+ ALICE = EntityRef("Hermes::User", "alice@example.com")
30
+ _PERMIT_ALL = "permit(principal, action, resource);"
31
+
32
+
33
+ @dataclass(frozen=True, slots=True, kw_only=True)
34
+ class AppliedChange:
35
+ """One recorded ``apply`` call."""
36
+
37
+ change: ChangeSet
38
+ dry_run: bool
39
+ actor: Actor
40
+ reason: str
41
+
42
+
43
+ class InMemoryAdmin:
44
+ """Canned answers; ``healthy`` False makes policy tests and doctor fail."""
45
+
46
+ def __init__(self) -> None:
47
+ self.calls: list[str] = []
48
+ self.applies: list[AppliedChange] = []
49
+ self.checked: list[CheckRequest] = []
50
+ self.audits: list[tuple[datetime | None, str | None]] = []
51
+ self.impacted: list[ChangeSet] = []
52
+ self.test_ids: list[str | None] = []
53
+ self.healthy = True
54
+
55
+ def written(self) -> bool:
56
+ """True when any call could have written (a real ``apply`` or ``publish``)."""
57
+ return "publish" in self.calls or any(not a.dry_run for a in self.applies)
58
+
59
+ def sync(self) -> SyncReport:
60
+ self.calls.append("sync")
61
+ return SyncReport(added=(EntityRef("Hermes::Profile", "assistant"),), unchanged=2, generation=3)
62
+
63
+ def list_entities(self, kind: EntityKind) -> tuple[EntityRecord, ...]:
64
+ self.calls.append(f"list_entities:{kind}")
65
+ return (EntityRecord(ref=ALICE, attrs={"tier": "gold"}),)
66
+
67
+ def show_entity(self, kind: EntityKind, id: str) -> EntityRecord:
68
+ self.calls.append(f"show_entity:{kind}:{id}")
69
+ return EntityRecord(ref=ALICE, attrs={"tier": "gold"}, parents=(EntityRef("Hermes::Role", "admin"),))
70
+
71
+ def apply(self, change: ChangeSet, *, dry_run: bool, actor: Actor, reason: str) -> ChangeResult:
72
+ self.calls.append("apply")
73
+ self.applies.append(AppliedChange(change=change, dry_run=dry_run, actor=actor, reason=reason))
74
+ entry = ImpactEntry(
75
+ principal="alice@example.com",
76
+ action=ActionRef("Hermes", "profile.view"),
77
+ resource=EntityRef("Hermes::Profile", "assistant"),
78
+ before=False,
79
+ after=True,
80
+ )
81
+ test = PolicyTestResult(app="example-app", name="t1", expect="allow", passed=self.healthy)
82
+ written = not dry_run and self.healthy
83
+ return ChangeResult(
84
+ impact=ImpactReport(gained=(entry,), evaluated=4),
85
+ tests=(test,),
86
+ generation=7 if written else None,
87
+ applied=written,
88
+ )
89
+
90
+ def impact(self, change: ChangeSet) -> ImpactReport:
91
+ self.calls.append("impact")
92
+ self.impacted.append(change)
93
+ return ImpactReport(evaluated=1)
94
+
95
+ def list_policies(self) -> tuple[PolicyRecord, ...]:
96
+ self.calls.append("list_policies")
97
+ return (PolicyRecord(id="p1", text=_PERMIT_ALL, owner="admin"),)
98
+
99
+ def show_policy(self, id: str) -> PolicyRecord:
100
+ self.calls.append(f"show_policy:{id}")
101
+ return PolicyRecord(id=id, text=_PERMIT_ALL, owner="admin", enabled=False)
102
+
103
+ def run_policy_tests(self, policy_id: str | None) -> tuple[PolicyTestResult, ...]:
104
+ self.calls.append("run_policy_tests")
105
+ self.test_ids.append(policy_id)
106
+ return (PolicyTestResult(app="example-app", name="t1", expect="deny", passed=self.healthy),)
107
+
108
+ def check(self, req: CheckRequest) -> CheckResult:
109
+ self.calls.append("check")
110
+ self.checked.append(req)
111
+ return CheckResult(allow=False, policy_ids=("forbid-guests",), generation=5)
112
+
113
+ def audit(self, since: datetime | None, who: str | None) -> tuple[AuditEntry, ...]:
114
+ self.calls.append("audit")
115
+ self.audits.append((since, who))
116
+ entry = AuditEntry(
117
+ at=MOMENT,
118
+ actor=Actor(kind="cli", name="op"),
119
+ reason="why",
120
+ change=ChangeSet(ops=()),
121
+ generation=2,
122
+ outcome="applied",
123
+ )
124
+ return (entry,)
125
+
126
+ def publish(self) -> PublishResult:
127
+ self.calls.append("publish")
128
+ return PublishResult(
129
+ generation=7, published_at=MOMENT, sinks=("snap.json",), policy_count=2, entity_count=4
130
+ )
131
+
132
+ def doctor(self) -> DoctorReport:
133
+ self.calls.append("doctor")
134
+ return DoctorReport(checks=(DoctorCheck(name="store", ok=self.healthy, detail="fine"),))
135
+
136
+ def list_apps(self) -> tuple[AppRecord, ...]:
137
+ self.calls.append("list_apps")
138
+ return (AppRecord(name="example-app", namespace="ExampleApp", manifest_json="{}"),)
139
+
140
+ def show_app(self, name: str) -> AppRecord:
141
+ self.calls.append(f"show_app:{name}")
142
+ return AppRecord(name=name, namespace="ExampleApp", manifest_json="{}")
@@ -0,0 +1,49 @@
1
+ """Composition root of the CLI: wires the real runtime (config search, admin service, clock, OS user)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import pwd
7
+ from datetime import UTC, datetime
8
+ from pathlib import Path
9
+
10
+ from hermes_access_admin.app import build_admin
11
+ from hermes_access_admin.services.api import AdminApi
12
+ from hermes_access_client.app import load_settings, lookup_from_env
13
+ from hermes_access_client.domain.resolve import choose_config, config_candidates
14
+
15
+ from hermes_access_cli.domain.runtime import LoadedConfig, Runtime
16
+
17
+
18
+ def load_config(path: Path | None) -> LoadedConfig:
19
+ """Find (explicit > env > real home > pwd home) and load the config."""
20
+ lookup = lookup_from_env(path)
21
+ found = choose_config(lookup, Path.is_file)
22
+ return LoadedConfig(path=found, settings=load_settings(lookup))
23
+
24
+
25
+ def build_service(path: Path | None) -> AdminApi:
26
+ """The admin service for the config found from ``path``."""
27
+ return build_admin(load_config(path).settings)
28
+
29
+
30
+ def config_target(path: Path | None) -> Path:
31
+ """Where ``config init`` writes: ``path`` or the first default location."""
32
+ return config_candidates(lookup_from_env(path))[0]
33
+
34
+
35
+ def os_user() -> str:
36
+ """The OS user name from the password database."""
37
+ return pwd.getpwuid(os.getuid()).pw_name
38
+
39
+
40
+ def utc_now() -> datetime:
41
+ """Current time, timezone-aware."""
42
+ return datetime.now(UTC)
43
+
44
+
45
+ def default_runtime() -> Runtime:
46
+ """The runtime the installed command uses."""
47
+ return Runtime(
48
+ admin=build_service, load_config=load_config, config_target=config_target, now=utc_now, user=os_user
49
+ )
@@ -0,0 +1,3 @@
1
+ """Typer commands (thin: parse, call a delegate, render)."""
2
+
3
+ __all__: list[str] = []
@@ -0,0 +1,37 @@
1
+ """Writes: build a ``ChangeSet``, call ``AdminApi.apply``, render the result."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ import typer
6
+ from hermes_access_admin.domain.changes import Actor, ChangeOp, ChangeSet
7
+ from hermes_access_admin.domain.reports import ChangeResult
8
+ from hermes_access_admin.services.api import AdminApi
9
+
10
+ from hermes_access_cli.cli.options import Format
11
+ from hermes_access_cli.cli.render import change_text, emit
12
+ from hermes_access_cli.cli.state import EXIT_ERROR, cli_context
13
+
14
+
15
+ def submit_change(
16
+ admin: AdminApi, ops: Sequence[ChangeOp], *, dry_run: bool, user: str, reason: str
17
+ ) -> ChangeResult:
18
+ """Delegate: one ``apply`` call (``dry_run`` is passed through; the admin does the write)."""
19
+ return admin.apply(
20
+ ChangeSet(tuple(ops)), dry_run=dry_run, actor=Actor(kind="cli", name=user), reason=reason
21
+ )
22
+
23
+
24
+ def failed(result: ChangeResult, *, dry_run: bool) -> bool:
25
+ """True when a policy test failed, or a real write was refused."""
26
+ return not all(t.passed for t in result.tests) or (not dry_run and not result.applied)
27
+
28
+
29
+ def apply_change(
30
+ ctx: typer.Context, ops: Sequence[ChangeOp], *, dry_run: bool, reason: str, fmt: Format
31
+ ) -> None:
32
+ """Apply ``ops`` as the OS user, print the result, exit 1 when tests failed or the write was refused."""
33
+ cli = cli_context(ctx)
34
+ result = submit_change(cli.admin(), ops, dry_run=dry_run, user=cli.runtime.user(), reason=reason)
35
+ emit(result, fmt, lambda r: change_text(r, dry_run=dry_run))
36
+ if failed(result, dry_run=dry_run):
37
+ raise typer.Exit(EXIT_ERROR)
@@ -0,0 +1,50 @@
1
+ """``config init|show|validate``."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import typer
8
+
9
+ from hermes_access_cli.adapters.config_files import inspect_config, write_config
10
+ from hermes_access_cli.cli.options import Format, FormatOpt
11
+ from hermes_access_cli.cli.render import emit, jsonable, validation_text
12
+ from hermes_access_cli.cli.state import EXIT_ERROR, cli_context, guarded
13
+
14
+ config_app = typer.Typer(no_args_is_help=True, help="Create, show and validate the config file.")
15
+
16
+
17
+ @config_app.command("init")
18
+ @guarded
19
+ def config_init(
20
+ ctx: typer.Context,
21
+ config: Annotated[Path | None, typer.Option("--config", help="Where to write the file.")] = None,
22
+ force: Annotated[bool, typer.Option("--force", help="Overwrite an existing file.")] = False,
23
+ ) -> None:
24
+ """Write a v1 config with relative paths (mode 0600)."""
25
+ cli = cli_context(ctx)
26
+ target = cli.runtime.config_target(config or cli.config)
27
+ write_config(target, force=force)
28
+ typer.echo(f"wrote {target}")
29
+
30
+
31
+ @config_app.command("show")
32
+ @guarded
33
+ def config_show(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
34
+ """Print the config with resolved absolute paths."""
35
+ cli = cli_context(ctx)
36
+ loaded = cli.runtime.load_config(cli.config)
37
+ data = {"config": str(loaded.path), "settings": jsonable(loaded.settings)}
38
+ emit(data, fmt, lambda d: f"config: {d['config']}\n" + json.dumps(d["settings"], indent=2))
39
+
40
+
41
+ @config_app.command("validate")
42
+ @guarded
43
+ def config_validate(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
44
+ """Check the config parses, its paths are writable and its mode is 0600."""
45
+ cli = cli_context(ctx)
46
+ loaded = cli.runtime.load_config(cli.config)
47
+ report = inspect_config(loaded.path, loaded.settings)
48
+ emit(report, fmt, validation_text)
49
+ if not report.ok:
50
+ raise typer.Exit(EXIT_ERROR)
@@ -0,0 +1,130 @@
1
+ """``user|group|role`` (list, show, assign, remove); ``profile|board`` (set-attr, unset-attr)."""
2
+
3
+ from typing import Annotated
4
+
5
+ import typer
6
+ from hermes_access_admin.domain.changes import (
7
+ AssignMembership,
8
+ ChangeOp,
9
+ RemoveMembership,
10
+ SetAttr,
11
+ UnsetAttr,
12
+ )
13
+ from hermes_access_admin.domain.reports import EntityKind
14
+ from hermes_access_client.domain.refs import GROUP_TYPE, ROLE_TYPE, EntityRef
15
+
16
+ from hermes_access_cli.cli.changes import apply_change
17
+ from hermes_access_cli.cli.options import DryRunOpt, Format, FormatOpt, ReasonOpt
18
+ from hermes_access_cli.cli.parse import entity_ref, parse_value
19
+ from hermes_access_cli.cli.render import emit, entities_text, entity_text
20
+ from hermes_access_cli.cli.state import cli_context, guarded
21
+ from hermes_access_cli.domain.errors import InputError
22
+
23
+ RolesOpt = Annotated[list[str], typer.Option("--role", help="Role to (un)assign; repeatable.")]
24
+ GroupsOpt = Annotated[list[str], typer.Option("--group", help="Group to (un)assign; repeatable.")]
25
+
26
+
27
+ def membership_ops(
28
+ kind: EntityKind, ident: str, roles: list[str], groups: list[str], *, remove: bool
29
+ ) -> tuple[ChangeOp, ...]:
30
+ """Delegate: one membership op per ``--role``/``--group`` (``InputError`` when none given)."""
31
+ parents = [EntityRef(ROLE_TYPE, r) for r in roles] + [EntityRef(GROUP_TYPE, g) for g in groups]
32
+ if not parents:
33
+ raise InputError("give at least one --role or --group")
34
+ member = entity_ref(kind, ident)
35
+ if remove:
36
+ return tuple(RemoveMembership(member=member, parent=p) for p in parents)
37
+ return tuple(AssignMembership(member=member, parent=p) for p in parents)
38
+
39
+
40
+ def attr_ops(kind: EntityKind, ident: str, name: str, value: str | None) -> tuple[ChangeOp, ...]:
41
+ """Delegate: ``SetAttr`` when ``value`` is given, else ``UnsetAttr``."""
42
+ entity = entity_ref(kind, ident)
43
+ if value is None:
44
+ return (UnsetAttr(entity=entity, name=name),)
45
+ return (SetAttr(entity=entity, name=name, value=parse_value(value)),)
46
+
47
+
48
+ def _register_reads(group: typer.Typer, kind: EntityKind) -> None:
49
+ @group.command("list")
50
+ @guarded
51
+ def list_(ctx: typer.Context, fmt: FormatOpt = Format.text) -> None:
52
+ """List the stored entities."""
53
+ emit(cli_context(ctx).admin().list_entities(kind), fmt, entities_text)
54
+
55
+ @group.command("show")
56
+ @guarded
57
+ def show(
58
+ ctx: typer.Context, ident: Annotated[str, typer.Argument(metavar="ID")], fmt: FormatOpt = Format.text
59
+ ) -> None:
60
+ """Show one entity."""
61
+ emit(cli_context(ctx).admin().show_entity(kind, entity_ref(kind, ident).id), fmt, entity_text)
62
+
63
+
64
+ def membership_group(name: str, kind: EntityKind) -> typer.Typer:
65
+ """The ``user|group|role`` command group."""
66
+ group = typer.Typer(no_args_is_help=True, help=f"Manage {name} memberships.")
67
+ _register_reads(group, kind)
68
+
69
+ @group.command("assign")
70
+ @guarded
71
+ def assign( # noqa: PLR0913, PLR0917 - one parameter per CLI option
72
+ ctx: typer.Context,
73
+ ident: Annotated[str, typer.Argument(metavar="ID")],
74
+ roles: RolesOpt = [], # noqa: B006 - typer copies defaults
75
+ groups: GroupsOpt = [], # noqa: B006
76
+ dry_run: DryRunOpt = False,
77
+ reason: ReasonOpt = "",
78
+ ) -> None:
79
+ """Add the entity to roles/groups."""
80
+ ops = membership_ops(kind, ident, roles, groups, remove=False)
81
+ apply_change(ctx, ops, dry_run=dry_run, reason=reason, fmt=Format.text)
82
+
83
+ @group.command("remove")
84
+ @guarded
85
+ def remove( # noqa: PLR0913, PLR0917 - one parameter per CLI option
86
+ ctx: typer.Context,
87
+ ident: Annotated[str, typer.Argument(metavar="ID")],
88
+ roles: RolesOpt = [], # noqa: B006
89
+ groups: GroupsOpt = [], # noqa: B006
90
+ dry_run: DryRunOpt = False,
91
+ reason: ReasonOpt = "",
92
+ ) -> None:
93
+ """Remove the entity from roles/groups."""
94
+ ops = membership_ops(kind, ident, roles, groups, remove=True)
95
+ apply_change(ctx, ops, dry_run=dry_run, reason=reason, fmt=Format.text)
96
+
97
+ return group
98
+
99
+
100
+ def attr_group(name: str, kind: EntityKind) -> typer.Typer:
101
+ """The ``profile|board`` command group."""
102
+ group = typer.Typer(no_args_is_help=True, help=f"Manage {name} attributes.")
103
+ _register_reads(group, kind)
104
+
105
+ @group.command("set-attr")
106
+ @guarded
107
+ def set_attr( # noqa: PLR0913, PLR0917 - one parameter per CLI option
108
+ ctx: typer.Context,
109
+ ident: Annotated[str, typer.Argument(metavar="ID")],
110
+ attr: Annotated[str, typer.Argument(metavar="NAME")],
111
+ value: Annotated[str, typer.Argument(help='JSON literal (true, 3, ["a"]) or a plain string.')],
112
+ dry_run: DryRunOpt = False,
113
+ reason: ReasonOpt = "",
114
+ ) -> None:
115
+ """Set an attribute."""
116
+ apply_change(ctx, attr_ops(kind, ident, attr, value), dry_run=dry_run, reason=reason, fmt=Format.text)
117
+
118
+ @group.command("unset-attr")
119
+ @guarded
120
+ def unset_attr(
121
+ ctx: typer.Context,
122
+ ident: Annotated[str, typer.Argument(metavar="ID")],
123
+ attr: Annotated[str, typer.Argument(metavar="NAME")],
124
+ dry_run: DryRunOpt = False,
125
+ reason: ReasonOpt = "",
126
+ ) -> None:
127
+ """Remove an optional attribute."""
128
+ apply_change(ctx, attr_ops(kind, ident, attr, None), dry_run=dry_run, reason=reason, fmt=Format.text)
129
+
130
+ return group