hermes-access-admin 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.
- hermes_access_admin/__init__.py +13 -0
- hermes_access_admin/adapters/__init__.py +3 -0
- hermes_access_admin/adapters/file_sink.py +88 -0
- hermes_access_admin/adapters/hermes_inventory.py +44 -0
- hermes_access_admin/adapters/sqlite_repository.py +200 -0
- hermes_access_admin/adapters/sqlite_rows.py +223 -0
- hermes_access_admin/adapters/sqlite_schema.py +71 -0
- hermes_access_admin/app.py +42 -0
- hermes_access_admin/domain/__init__.py +99 -0
- hermes_access_admin/domain/changes.py +155 -0
- hermes_access_admin/domain/errors.py +35 -0
- hermes_access_admin/domain/reports.py +244 -0
- hermes_access_admin/ports.py +64 -0
- hermes_access_admin/py.typed +0 -0
- hermes_access_admin/services/__init__.py +3 -0
- hermes_access_admin/services/admin_service.py +276 -0
- hermes_access_admin/services/api.py +91 -0
- hermes_access_admin/services/check.py +47 -0
- hermes_access_admin/services/doctor.py +51 -0
- hermes_access_admin/services/impact.py +99 -0
- hermes_access_admin/services/manifest_tests.py +110 -0
- hermes_access_admin/services/publisher.py +85 -0
- hermes_access_admin/services/state_ops.py +269 -0
- hermes_access_admin/services/sync.py +46 -0
- hermes_access_admin/services/validator.py +266 -0
- hermes_access_admin-0.1.0.dist-info/METADATA +21 -0
- hermes_access_admin-0.1.0.dist-info/RECORD +28 -0
- hermes_access_admin-0.1.0.dist-info/WHEEL +4 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Admin services for hermes-access: store, validation, impact reports, snapshot publishing, audit."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from hermes_access_admin.domain.errors import AccessAdminError
|
|
6
|
+
from hermes_access_admin.services.api import AdminApi
|
|
7
|
+
|
|
8
|
+
try:
|
|
9
|
+
__version__ = version("hermes-access-admin")
|
|
10
|
+
except PackageNotFoundError: # pragma: no cover - source tree without install
|
|
11
|
+
__version__ = "0.0.0+unknown"
|
|
12
|
+
|
|
13
|
+
__all__ = ["AccessAdminError", "AdminApi", "__version__"]
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""``FileSnapshotSink``: writes the snapshot JSON atomically (temp file in the same dir, fsync, rename; 0600).
|
|
2
|
+
|
|
3
|
+
Idempotent by generation; verifies what it wrote."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import contextlib
|
|
8
|
+
import logging
|
|
9
|
+
import os
|
|
10
|
+
import stat
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from hermes_access_client.domain.errors import SnapshotError
|
|
15
|
+
from hermes_access_client.domain.snapshot import Snapshot, parse_snapshot_json
|
|
16
|
+
|
|
17
|
+
from hermes_access_admin.domain.errors import PublishError
|
|
18
|
+
from hermes_access_admin.domain.reports import SinkStatus
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
_FILE_MODE = 0o600
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _display(path: Path) -> str:
|
|
26
|
+
"""``file:~/x`` for paths under the home, else ``file:<path>`` (never prints the home dir itself)."""
|
|
27
|
+
try:
|
|
28
|
+
return f"file:~/{path.relative_to(Path.home())}"
|
|
29
|
+
except ValueError:
|
|
30
|
+
return f"file:{path}"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _published_generation(path: Path) -> int | None:
|
|
34
|
+
"""Generation of the valid snapshot at ``path``; None when absent or unreadable."""
|
|
35
|
+
try:
|
|
36
|
+
return parse_snapshot_json(path.read_bytes()).generation
|
|
37
|
+
except (OSError, SnapshotError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class FileSnapshotSink:
|
|
42
|
+
"""``SnapshotSink`` for a JSON file read by ``FileSnapshotSource``."""
|
|
43
|
+
|
|
44
|
+
def __init__(self, path: Path) -> None:
|
|
45
|
+
self._path = path
|
|
46
|
+
|
|
47
|
+
def publish(self, snapshot: Snapshot) -> str:
|
|
48
|
+
"""Write ``snapshot`` unless the file already holds this or a newer generation."""
|
|
49
|
+
current = _published_generation(self._path)
|
|
50
|
+
if current is not None and current >= snapshot.generation:
|
|
51
|
+
log.info("snapshot at %s already at generation %d; nothing to write", self._path, current)
|
|
52
|
+
return _display(self._path)
|
|
53
|
+
payload = snapshot.model_dump_json(by_alias=True).encode()
|
|
54
|
+
try:
|
|
55
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
self._write_atomically(payload)
|
|
57
|
+
except OSError as exc:
|
|
58
|
+
raise PublishError(f"cannot write the snapshot to {self._path}: {exc}") from exc
|
|
59
|
+
if _published_generation(self._path) != snapshot.generation:
|
|
60
|
+
raise PublishError(
|
|
61
|
+
f"the snapshot written to {self._path} does not read back as generation {snapshot.generation}"
|
|
62
|
+
)
|
|
63
|
+
return _display(self._path)
|
|
64
|
+
|
|
65
|
+
def _write_atomically(self, payload: bytes) -> None:
|
|
66
|
+
fd, tmp_name = tempfile.mkstemp(dir=self._path.parent, prefix=f".{self._path.name}.", suffix=".tmp")
|
|
67
|
+
tmp = Path(tmp_name)
|
|
68
|
+
try:
|
|
69
|
+
with os.fdopen(fd, "wb") as handle:
|
|
70
|
+
os.fchmod(handle.fileno(), _FILE_MODE)
|
|
71
|
+
handle.write(payload)
|
|
72
|
+
handle.flush()
|
|
73
|
+
os.fsync(handle.fileno())
|
|
74
|
+
tmp.replace(self._path)
|
|
75
|
+
except BaseException:
|
|
76
|
+
with contextlib.suppress(FileNotFoundError):
|
|
77
|
+
tmp.unlink()
|
|
78
|
+
raise
|
|
79
|
+
|
|
80
|
+
def status(self) -> SinkStatus:
|
|
81
|
+
"""The target, the generation published there and whether the file mode is 0600."""
|
|
82
|
+
try:
|
|
83
|
+
mode_ok = stat.S_IMODE(self._path.stat().st_mode) & 0o077 == 0
|
|
84
|
+
except FileNotFoundError:
|
|
85
|
+
mode_ok = True
|
|
86
|
+
return SinkStatus(
|
|
87
|
+
name=_display(self._path), generation=_published_generation(self._path), mode_ok=mode_ok
|
|
88
|
+
)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""``FsHermesInventory``: lists the profiles and boards of a Hermes home on disk (read-only)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from hermes_access_client.domain.refs import BOARD_TYPE, PROFILE_TYPE, EntityRef
|
|
9
|
+
|
|
10
|
+
from hermes_access_admin.domain.errors import InventoryError
|
|
11
|
+
from hermes_access_admin.domain.reports import InventoryItem
|
|
12
|
+
|
|
13
|
+
log = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
DEFAULT_PROFILE = "default"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _subdirs(parent: Path) -> list[str]:
|
|
19
|
+
"""Names of the visible directories under ``parent`` (empty when it does not exist)."""
|
|
20
|
+
try:
|
|
21
|
+
return sorted(p.name for p in parent.iterdir() if p.is_dir() and not p.name.startswith("."))
|
|
22
|
+
except FileNotFoundError:
|
|
23
|
+
return []
|
|
24
|
+
except OSError as exc:
|
|
25
|
+
raise InventoryError(f"cannot list {parent}: {exc}") from exc
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FsHermesInventory:
|
|
29
|
+
"""``HermesInventory`` over ``<hermes_home>/profiles`` and ``<hermes_home>/kanban/boards``."""
|
|
30
|
+
|
|
31
|
+
def __init__(self, hermes_home: Path) -> None:
|
|
32
|
+
self._home = hermes_home
|
|
33
|
+
|
|
34
|
+
def profiles(self) -> tuple[InventoryItem, ...]:
|
|
35
|
+
"""Dirs under ``profiles/`` plus ``default`` when the home itself has a ``config.yaml``."""
|
|
36
|
+
names = _subdirs(self._home / "profiles")
|
|
37
|
+
if (self._home / "config.yaml").is_file() and DEFAULT_PROFILE not in names:
|
|
38
|
+
names = [DEFAULT_PROFILE, *names]
|
|
39
|
+
return tuple(InventoryItem(ref=EntityRef(PROFILE_TYPE, n)) for n in names)
|
|
40
|
+
|
|
41
|
+
def boards(self) -> tuple[InventoryItem, ...]:
|
|
42
|
+
"""Dirs under ``kanban/boards/``."""
|
|
43
|
+
names = _subdirs(self._home / "kanban" / "boards")
|
|
44
|
+
return tuple(InventoryItem(ref=EntityRef(BOARD_TYPE, n)) for n in names)
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""``SqliteAccessRepository``: the SQLite store. WAL; every write is ONE ``BEGIN IMMEDIATE`` transaction (the
|
|
2
|
+
change, generation + 1 and the audit row); schema-versioned with forward-only migrations."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import logging
|
|
7
|
+
import os
|
|
8
|
+
import sqlite3
|
|
9
|
+
import stat
|
|
10
|
+
from collections.abc import Callable, Generator
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from datetime import UTC, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from pydantic import TypeAdapter
|
|
17
|
+
|
|
18
|
+
from hermes_access_admin.adapters.sqlite_rows import WriteContext, read_generation, read_state, write_diff
|
|
19
|
+
from hermes_access_admin.adapters.sqlite_schema import CURRENT_VERSION, ensure_current, stored_version
|
|
20
|
+
from hermes_access_admin.domain.changes import Actor, ChangeSet
|
|
21
|
+
from hermes_access_admin.domain.errors import StoreError
|
|
22
|
+
from hermes_access_admin.domain.reports import AuditEntry, StoreHealth, StoreState
|
|
23
|
+
from hermes_access_admin.services.state_ops import apply_change
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
_CHANGE = TypeAdapter(ChangeSet)
|
|
28
|
+
_FILE_MODE = 0o600
|
|
29
|
+
_BUSY_TIMEOUT_S = 30.0
|
|
30
|
+
_Outcome = Literal["applied", "rejected", "dry-run", "denied"]
|
|
31
|
+
_OUTCOMES: dict[str, _Outcome] = {
|
|
32
|
+
"applied": "applied",
|
|
33
|
+
"rejected": "rejected",
|
|
34
|
+
"dry-run": "dry-run",
|
|
35
|
+
"denied": "denied",
|
|
36
|
+
}
|
|
37
|
+
_AuditRow = tuple[str, str, str, str | None, str, str, str, int, str, str]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _utc_now() -> datetime:
|
|
41
|
+
return datetime.now(UTC)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class SqliteAccessRepository:
|
|
45
|
+
"""``AccessRepository`` over a SQLite file (created 0600; one connection per operation)."""
|
|
46
|
+
|
|
47
|
+
def __init__(self, path: Path, *, now: Callable[[], datetime] = _utc_now) -> None:
|
|
48
|
+
self._path = path
|
|
49
|
+
self._now = now
|
|
50
|
+
self._create_file()
|
|
51
|
+
with self._write():
|
|
52
|
+
pass # the transaction itself runs the migrations and the version guard
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def path(self) -> Path:
|
|
56
|
+
"""The SQLite file."""
|
|
57
|
+
return self._path
|
|
58
|
+
|
|
59
|
+
def _create_file(self) -> None:
|
|
60
|
+
try:
|
|
61
|
+
self._path.parent.mkdir(parents=True, exist_ok=True)
|
|
62
|
+
os.close(os.open(self._path, os.O_CREAT | os.O_RDWR, _FILE_MODE))
|
|
63
|
+
except OSError as exc:
|
|
64
|
+
raise StoreError(f"cannot create the store at {self._path}: {exc}") from exc
|
|
65
|
+
|
|
66
|
+
def _connect(self) -> sqlite3.Connection:
|
|
67
|
+
try:
|
|
68
|
+
conn = sqlite3.connect(self._path, timeout=_BUSY_TIMEOUT_S, isolation_level=None)
|
|
69
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
70
|
+
except sqlite3.Error as exc:
|
|
71
|
+
raise StoreError(f"cannot open the store at {self._path}: {exc}") from exc
|
|
72
|
+
return conn
|
|
73
|
+
|
|
74
|
+
@contextmanager
|
|
75
|
+
def _write(self) -> Generator[sqlite3.Connection]:
|
|
76
|
+
"""One ``BEGIN IMMEDIATE`` transaction: migrations + version guard first; commit or roll back."""
|
|
77
|
+
conn = self._connect()
|
|
78
|
+
try:
|
|
79
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
80
|
+
ensure_current(conn)
|
|
81
|
+
yield conn
|
|
82
|
+
conn.execute("COMMIT")
|
|
83
|
+
except BaseException:
|
|
84
|
+
if conn.in_transaction:
|
|
85
|
+
conn.execute("ROLLBACK")
|
|
86
|
+
raise
|
|
87
|
+
finally:
|
|
88
|
+
conn.close()
|
|
89
|
+
|
|
90
|
+
@contextmanager
|
|
91
|
+
def _read(self) -> Generator[sqlite3.Connection]:
|
|
92
|
+
conn = self._connect()
|
|
93
|
+
try:
|
|
94
|
+
conn.execute("BEGIN")
|
|
95
|
+
if stored_version(conn) > CURRENT_VERSION:
|
|
96
|
+
ensure_current(conn) # raises SchemaVersionError
|
|
97
|
+
yield conn
|
|
98
|
+
finally:
|
|
99
|
+
if conn.in_transaction:
|
|
100
|
+
conn.execute("ROLLBACK")
|
|
101
|
+
conn.close()
|
|
102
|
+
|
|
103
|
+
def load_state(self) -> StoreState:
|
|
104
|
+
"""See ``AccessRepository.load_state``."""
|
|
105
|
+
with self._read() as conn:
|
|
106
|
+
return read_state(conn)
|
|
107
|
+
|
|
108
|
+
def apply(self, change: ChangeSet, *, actor: Actor, reason: str) -> int:
|
|
109
|
+
"""See ``AccessRepository.apply``."""
|
|
110
|
+
now = self._now()
|
|
111
|
+
with self._write() as conn:
|
|
112
|
+
old = read_state(conn)
|
|
113
|
+
new = apply_change(old, change)
|
|
114
|
+
before, after = write_diff(conn, old, new, WriteContext(actor=actor.name, at=now.isoformat()))
|
|
115
|
+
generation = old.generation + 1
|
|
116
|
+
conn.execute("UPDATE meta SET value = ? WHERE key = 'generation'", (str(generation),))
|
|
117
|
+
entry = AuditEntry(
|
|
118
|
+
at=now, actor=actor, reason=reason, change=change, generation=generation, outcome="applied"
|
|
119
|
+
)
|
|
120
|
+
_insert_audit(conn, _row(entry, (before, after)))
|
|
121
|
+
log.debug("applied %d ops as generation %d", len(change.ops), generation)
|
|
122
|
+
return generation
|
|
123
|
+
|
|
124
|
+
def record(self, entry: AuditEntry) -> None:
|
|
125
|
+
"""See ``AccessRepository.record``."""
|
|
126
|
+
with self._write() as conn:
|
|
127
|
+
generation = entry.generation if entry.generation is not None else read_generation(conn)
|
|
128
|
+
stamped = AuditEntry(
|
|
129
|
+
at=entry.at,
|
|
130
|
+
actor=entry.actor,
|
|
131
|
+
reason=entry.reason,
|
|
132
|
+
change=entry.change,
|
|
133
|
+
generation=generation,
|
|
134
|
+
outcome=entry.outcome,
|
|
135
|
+
)
|
|
136
|
+
_insert_audit(conn, _row(stamped, ("{}", "{}")))
|
|
137
|
+
|
|
138
|
+
def audit(self, since: datetime | None, who: str | None) -> tuple[AuditEntry, ...]:
|
|
139
|
+
"""See ``AccessRepository.audit``."""
|
|
140
|
+
sql = (
|
|
141
|
+
"SELECT at, actor_kind, actor_name, session_id, what, reason, generation, outcome FROM audit"
|
|
142
|
+
" WHERE (? IS NULL OR at >= ?) AND (? IS NULL OR actor_name = ?) ORDER BY id DESC"
|
|
143
|
+
)
|
|
144
|
+
floor = since.replace(tzinfo=UTC) if since is not None and since.tzinfo is None else since
|
|
145
|
+
floor_text = floor.isoformat() if floor is not None else None
|
|
146
|
+
with self._read() as conn:
|
|
147
|
+
rows = conn.execute(sql, (floor_text, floor_text, who, who)).fetchall()
|
|
148
|
+
return tuple(_entry(r) for r in rows)
|
|
149
|
+
|
|
150
|
+
def health(self) -> StoreHealth:
|
|
151
|
+
"""See ``AccessRepository.health``."""
|
|
152
|
+
mode = stat.S_IMODE(self._path.stat().st_mode)
|
|
153
|
+
with self._read() as conn:
|
|
154
|
+
generation, version = read_generation(conn), stored_version(conn)
|
|
155
|
+
return StoreHealth(
|
|
156
|
+
path=str(self._path),
|
|
157
|
+
generation=generation,
|
|
158
|
+
schema_version=version,
|
|
159
|
+
code_version=CURRENT_VERSION,
|
|
160
|
+
writable=os.access(self._path, os.W_OK) and os.access(self._path.parent, os.W_OK),
|
|
161
|
+
mode_ok=mode & 0o077 == 0,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _row(entry: AuditEntry, delta: tuple[str, str]) -> _AuditRow:
|
|
166
|
+
what = _CHANGE.dump_json(entry.change).decode()
|
|
167
|
+
actor = entry.actor
|
|
168
|
+
generation = entry.generation if entry.generation is not None else -1
|
|
169
|
+
at = entry.at.isoformat()
|
|
170
|
+
return (
|
|
171
|
+
at,
|
|
172
|
+
actor.kind,
|
|
173
|
+
actor.name,
|
|
174
|
+
actor.session_id,
|
|
175
|
+
what,
|
|
176
|
+
*delta,
|
|
177
|
+
generation,
|
|
178
|
+
entry.reason,
|
|
179
|
+
entry.outcome,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _insert_audit(conn: sqlite3.Connection, row: _AuditRow) -> None:
|
|
184
|
+
conn.execute(
|
|
185
|
+
"INSERT INTO audit (at, actor_kind, actor_name, session_id, what, before, after, generation, reason,"
|
|
186
|
+
" outcome) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
187
|
+
row,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _entry(row: tuple[str, str, str, str | None, str, str, int, str]) -> AuditEntry:
|
|
192
|
+
at, kind, name, session, what, reason, generation, outcome = row
|
|
193
|
+
return AuditEntry(
|
|
194
|
+
at=datetime.fromisoformat(at),
|
|
195
|
+
actor=Actor(kind="agent" if kind == "agent" else "cli", name=name, session_id=session),
|
|
196
|
+
reason=reason,
|
|
197
|
+
change=_CHANGE.validate_json(what),
|
|
198
|
+
generation=generation,
|
|
199
|
+
outcome=_OUTCOMES[outcome],
|
|
200
|
+
)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Row mapping of the SQLite store: read a whole ``StoreState``, write the difference between two states."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import sqlite3
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from typing import TypeVar
|
|
10
|
+
|
|
11
|
+
from hermes_access_client.domain.manifest import parse_manifest
|
|
12
|
+
from hermes_access_client.domain.refs import (
|
|
13
|
+
BOARD_TYPE,
|
|
14
|
+
GROUP_TYPE,
|
|
15
|
+
PROFILE_TYPE,
|
|
16
|
+
ROLE_TYPE,
|
|
17
|
+
USER_TYPE,
|
|
18
|
+
CedarValue,
|
|
19
|
+
EntityRef,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
from hermes_access_admin.domain.reports import AppRecord, EntityRecord, PolicyRecord, StoreState
|
|
23
|
+
|
|
24
|
+
K = TypeVar("K")
|
|
25
|
+
V = TypeVar("V")
|
|
26
|
+
|
|
27
|
+
_TABLE_OF = {USER_TYPE: "users", GROUP_TYPE: "groups", ROLE_TYPE: "roles"}
|
|
28
|
+
_INVENTORY_TYPES = (PROFILE_TYPE, BOARD_TYPE)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def read_generation(conn: sqlite3.Connection) -> int:
|
|
32
|
+
"""The store's current generation."""
|
|
33
|
+
row = conn.execute("SELECT value FROM meta WHERE key='generation'").fetchone()
|
|
34
|
+
return int(row[0]) if row else 0
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _entity_refs(conn: sqlite3.Connection) -> dict[EntityRef, bool]:
|
|
38
|
+
"""Every stored entity ref, with its ``gone`` flag."""
|
|
39
|
+
refs: dict[EntityRef, bool] = {}
|
|
40
|
+
for type_, table in _TABLE_OF.items():
|
|
41
|
+
refs.update({EntityRef(type_, row[0]): False for row in conn.execute(f"SELECT id FROM {table}")})
|
|
42
|
+
for row in conn.execute("SELECT type, id, state FROM inventory"):
|
|
43
|
+
refs[EntityRef(row[0], row[1])] = row[2] == "gone"
|
|
44
|
+
return refs
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def read_state(conn: sqlite3.Connection) -> StoreState:
|
|
48
|
+
"""Everything in the store (call inside one read transaction for a consistent view)."""
|
|
49
|
+
attrs: dict[EntityRef, dict[str, CedarValue]] = {}
|
|
50
|
+
for type_, id_, name, value in conn.execute("SELECT type, id, name, value_json FROM entity_attrs"):
|
|
51
|
+
attrs.setdefault(EntityRef(type_, id_), {})[name] = json.loads(value)
|
|
52
|
+
parents: dict[EntityRef, list[EntityRef]] = {}
|
|
53
|
+
for mt, mi, pt, pi in conn.execute(
|
|
54
|
+
"SELECT member_type, member_id, parent_type, parent_id FROM memberships"
|
|
55
|
+
):
|
|
56
|
+
parents.setdefault(EntityRef(mt, mi), []).append(EntityRef(pt, pi))
|
|
57
|
+
entities = tuple(
|
|
58
|
+
EntityRecord(
|
|
59
|
+
ref=ref,
|
|
60
|
+
attrs=attrs.get(ref, {}),
|
|
61
|
+
parents=tuple(sorted(parents.get(ref, ()), key=_ref_key)),
|
|
62
|
+
gone=gone,
|
|
63
|
+
)
|
|
64
|
+
for ref, gone in sorted(_entity_refs(conn).items(), key=lambda kv: _ref_key(kv[0]))
|
|
65
|
+
)
|
|
66
|
+
policies = tuple(
|
|
67
|
+
PolicyRecord(id=r[0], text=r[1], owner=r[2], enabled=bool(r[3]))
|
|
68
|
+
for r in conn.execute("SELECT id, text, owner, enabled FROM policies ORDER BY id")
|
|
69
|
+
)
|
|
70
|
+
apps = tuple(
|
|
71
|
+
AppRecord(name=r[0], namespace=r[1], manifest_json=r[2])
|
|
72
|
+
for r in conn.execute("SELECT name, namespace, manifest_json FROM apps ORDER BY name")
|
|
73
|
+
)
|
|
74
|
+
return StoreState(generation=read_generation(conn), entities=entities, policies=policies, apps=apps)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _ref_key(ref: EntityRef) -> tuple[str, str]:
|
|
78
|
+
return (ref.type, ref.id)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
82
|
+
class WriteContext:
|
|
83
|
+
"""Who/when the rows being written are attributed to."""
|
|
84
|
+
|
|
85
|
+
actor: str
|
|
86
|
+
at: str
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _delete_entity(conn: sqlite3.Connection, ref: EntityRef) -> None:
|
|
90
|
+
table = _TABLE_OF.get(ref.type)
|
|
91
|
+
if table is not None:
|
|
92
|
+
conn.execute(f"DELETE FROM {table} WHERE id = ?", (ref.id,))
|
|
93
|
+
else:
|
|
94
|
+
conn.execute("DELETE FROM inventory WHERE type = ? AND id = ?", (ref.type, ref.id))
|
|
95
|
+
conn.execute("DELETE FROM entity_attrs WHERE type = ? AND id = ?", (ref.type, ref.id))
|
|
96
|
+
conn.execute("DELETE FROM memberships WHERE member_type = ? AND member_id = ?", (ref.type, ref.id))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _write_entity(conn: sqlite3.Connection, rec: EntityRecord, ctx: WriteContext) -> None:
|
|
100
|
+
ref = rec.ref
|
|
101
|
+
if ref.type == USER_TYPE:
|
|
102
|
+
conn.execute("INSERT OR IGNORE INTO users (id) VALUES (?)", (ref.id,))
|
|
103
|
+
elif ref.type == ROLE_TYPE:
|
|
104
|
+
conn.execute("INSERT OR IGNORE INTO roles (id) VALUES (?)", (ref.id,))
|
|
105
|
+
elif ref.type == GROUP_TYPE:
|
|
106
|
+
kind = rec.attrs.get("kind")
|
|
107
|
+
conn.execute("INSERT OR REPLACE INTO groups (id, kind) VALUES (?, ?)", (ref.id, kind or "local"))
|
|
108
|
+
else:
|
|
109
|
+
conn.execute(
|
|
110
|
+
"INSERT INTO inventory (type, id, state, seen_at) VALUES (?, ?, ?, ?) "
|
|
111
|
+
"ON CONFLICT(type, id) DO UPDATE SET state = excluded.state",
|
|
112
|
+
(ref.type, ref.id, "gone" if rec.gone else "seen", ctx.at),
|
|
113
|
+
)
|
|
114
|
+
conn.execute("DELETE FROM entity_attrs WHERE type = ? AND id = ?", (ref.type, ref.id))
|
|
115
|
+
conn.executemany(
|
|
116
|
+
"INSERT INTO entity_attrs (type, id, name, value_json) VALUES (?, ?, ?, ?)",
|
|
117
|
+
[(ref.type, ref.id, k, json.dumps(v, sort_keys=True)) for k, v in rec.attrs.items()],
|
|
118
|
+
)
|
|
119
|
+
conn.execute("DELETE FROM memberships WHERE member_type = ? AND member_id = ?", (ref.type, ref.id))
|
|
120
|
+
conn.executemany(
|
|
121
|
+
"INSERT INTO memberships (member_type, member_id, parent_type, parent_id) VALUES (?, ?, ?, ?)",
|
|
122
|
+
[(ref.type, ref.id, p.type, p.id) for p in rec.parents],
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _write_policy(conn: sqlite3.Connection, rec: PolicyRecord, ctx: WriteContext) -> None:
|
|
127
|
+
conn.execute(
|
|
128
|
+
"INSERT INTO policies (id, text, owner, enabled, created_by) VALUES (?, ?, ?, ?, ?) "
|
|
129
|
+
"ON CONFLICT(id) DO UPDATE SET text = excluded.text, owner = excluded.owner, "
|
|
130
|
+
"enabled = excluded.enabled",
|
|
131
|
+
(rec.id, rec.text, rec.owner, int(rec.enabled), ctx.actor),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _write_app(conn: sqlite3.Connection, rec: AppRecord, ctx: WriteContext) -> None:
|
|
136
|
+
manifest = parse_manifest(json.loads(rec.manifest_json))
|
|
137
|
+
conn.execute(
|
|
138
|
+
"INSERT INTO apps (name, namespace, manifest_v, schema, manifest_json, registered_at) "
|
|
139
|
+
"VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(name) DO UPDATE SET namespace = excluded.namespace, "
|
|
140
|
+
"manifest_v = excluded.manifest_v, schema = excluded.schema, manifest_json = excluded.manifest_json",
|
|
141
|
+
(rec.name, rec.namespace, manifest.v, manifest.schema_text, rec.manifest_json, ctx.at),
|
|
142
|
+
)
|
|
143
|
+
conn.execute("DELETE FROM policy_tests WHERE app = ?", (rec.name,))
|
|
144
|
+
conn.executemany(
|
|
145
|
+
"INSERT INTO policy_tests (app, name, test_json) VALUES (?, ?, ?)",
|
|
146
|
+
[(rec.name, t.name, t.model_dump_json(by_alias=True)) for t in manifest.tests],
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _delete_app(conn: sqlite3.Connection, name: str) -> None:
|
|
151
|
+
conn.execute("DELETE FROM apps WHERE name = ?", (name,))
|
|
152
|
+
conn.execute("DELETE FROM policy_tests WHERE app = ?", (name,))
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _sync_table(
|
|
156
|
+
old: Mapping[K, V],
|
|
157
|
+
new: Mapping[K, V],
|
|
158
|
+
delete: Callable[[K], object],
|
|
159
|
+
write: Callable[[V], None],
|
|
160
|
+
) -> tuple[list[V], list[V]]:
|
|
161
|
+
"""Apply the difference ``old`` -> ``new`` through ``delete``/``write``; returns the (before, after)
|
|
162
|
+
values of every key that changed."""
|
|
163
|
+
before = [v for k, v in old.items() if new.get(k) != v]
|
|
164
|
+
after = [v for k, v in new.items() if old.get(k) != v]
|
|
165
|
+
for key in old:
|
|
166
|
+
if key not in new:
|
|
167
|
+
delete(key)
|
|
168
|
+
for value in after:
|
|
169
|
+
write(value)
|
|
170
|
+
return before, after
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def write_diff(
|
|
174
|
+
conn: sqlite3.Connection, old: StoreState, new: StoreState, ctx: WriteContext
|
|
175
|
+
) -> tuple[str, str]:
|
|
176
|
+
"""Make the rows equal ``new`` touching only what differs from ``old``; returns the (before, after) JSON
|
|
177
|
+
of the changed entities, policies and apps for the audit row."""
|
|
178
|
+
ent_before, ent_after = _sync_table(
|
|
179
|
+
{e.ref: e for e in old.entities},
|
|
180
|
+
{e.ref: e for e in new.entities},
|
|
181
|
+
lambda ref: _delete_entity(conn, ref),
|
|
182
|
+
lambda rec: _write_entity(conn, rec, ctx),
|
|
183
|
+
)
|
|
184
|
+
pol_before, pol_after = _sync_table(
|
|
185
|
+
{p.id: p for p in old.policies},
|
|
186
|
+
{p.id: p for p in new.policies},
|
|
187
|
+
lambda pid: conn.execute("DELETE FROM policies WHERE id = ?", (pid,)),
|
|
188
|
+
lambda rec: _write_policy(conn, rec, ctx),
|
|
189
|
+
)
|
|
190
|
+
app_before, app_after = _sync_table(
|
|
191
|
+
{a.name: a for a in old.apps},
|
|
192
|
+
{a.name: a for a in new.apps},
|
|
193
|
+
lambda name: _delete_app(conn, name),
|
|
194
|
+
lambda rec: _write_app(conn, rec, ctx),
|
|
195
|
+
)
|
|
196
|
+
return (
|
|
197
|
+
_delta_json(ent_before, pol_before, app_before),
|
|
198
|
+
_delta_json(ent_after, pol_after, app_after),
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _delta_json(entities: list[EntityRecord], policies: list[PolicyRecord], apps: list[AppRecord]) -> str:
|
|
203
|
+
return json.dumps(
|
|
204
|
+
{
|
|
205
|
+
"entities": [_entity_json(e) for e in entities],
|
|
206
|
+
"policies": [_policy_json(p) for p in policies],
|
|
207
|
+
"apps": [a.name for a in apps],
|
|
208
|
+
},
|
|
209
|
+
sort_keys=True,
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _entity_json(rec: EntityRecord) -> dict[str, object]:
|
|
214
|
+
return {
|
|
215
|
+
"ref": str(rec.ref),
|
|
216
|
+
"attrs": dict(rec.attrs),
|
|
217
|
+
"parents": [str(p) for p in rec.parents],
|
|
218
|
+
"gone": rec.gone,
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _policy_json(rec: PolicyRecord) -> dict[str, object]:
|
|
223
|
+
return {"id": rec.id, "owner": rec.owner, "enabled": rec.enabled, "text": rec.text}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""SQLite schema of the admin store: ordered, forward-only migrations and the version guard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import sqlite3
|
|
6
|
+
|
|
7
|
+
from hermes_access_admin.domain.errors import SchemaVersionError
|
|
8
|
+
|
|
9
|
+
_V1 = (
|
|
10
|
+
"CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)",
|
|
11
|
+
"CREATE TABLE users (id TEXT PRIMARY KEY)",
|
|
12
|
+
"CREATE TABLE groups (id TEXT PRIMARY KEY, kind TEXT NOT NULL CHECK (kind IN ('entra', 'local')))",
|
|
13
|
+
"CREATE TABLE roles (id TEXT PRIMARY KEY)",
|
|
14
|
+
"""CREATE TABLE inventory (
|
|
15
|
+
type TEXT NOT NULL, id TEXT NOT NULL,
|
|
16
|
+
state TEXT NOT NULL CHECK (state IN ('seen', 'gone')), seen_at TEXT NOT NULL,
|
|
17
|
+
PRIMARY KEY (type, id))""",
|
|
18
|
+
"""CREATE TABLE entity_attrs (
|
|
19
|
+
type TEXT NOT NULL, id TEXT NOT NULL, name TEXT NOT NULL, value_json TEXT NOT NULL,
|
|
20
|
+
PRIMARY KEY (type, id, name))""",
|
|
21
|
+
"""CREATE TABLE memberships (
|
|
22
|
+
member_type TEXT NOT NULL, member_id TEXT NOT NULL,
|
|
23
|
+
parent_type TEXT NOT NULL, parent_id TEXT NOT NULL,
|
|
24
|
+
PRIMARY KEY (member_type, member_id, parent_type, parent_id))""",
|
|
25
|
+
"""CREATE TABLE policies (
|
|
26
|
+
id TEXT PRIMARY KEY, text TEXT NOT NULL, owner TEXT NOT NULL, enabled INTEGER NOT NULL,
|
|
27
|
+
created_by TEXT NOT NULL)""",
|
|
28
|
+
"""CREATE TABLE policy_tests (
|
|
29
|
+
app TEXT NOT NULL, name TEXT NOT NULL, test_json TEXT NOT NULL, PRIMARY KEY (app, name))""",
|
|
30
|
+
"""CREATE TABLE apps (
|
|
31
|
+
name TEXT PRIMARY KEY, namespace TEXT NOT NULL UNIQUE, manifest_v INTEGER NOT NULL,
|
|
32
|
+
schema TEXT NOT NULL, manifest_json TEXT NOT NULL, registered_at TEXT NOT NULL)""",
|
|
33
|
+
"""CREATE TABLE audit (
|
|
34
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT, at TEXT NOT NULL, actor_kind TEXT NOT NULL,
|
|
35
|
+
actor_name TEXT NOT NULL, session_id TEXT, what TEXT NOT NULL, before TEXT NOT NULL,
|
|
36
|
+
after TEXT NOT NULL, reason TEXT NOT NULL, generation INTEGER NOT NULL, outcome TEXT NOT NULL)""",
|
|
37
|
+
"INSERT INTO meta (key, value) VALUES ('generation', '0')",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
MIGRATIONS: tuple[tuple[int, tuple[str, ...]], ...] = ((1, _V1),)
|
|
41
|
+
"""Ordered ``(version, statements)``; a migration is never edited once released, only appended to."""
|
|
42
|
+
|
|
43
|
+
CURRENT_VERSION = MIGRATIONS[-1][0]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def stored_version(conn: sqlite3.Connection) -> int:
|
|
47
|
+
"""The schema version recorded in the file (0 for a fresh database)."""
|
|
48
|
+
has_meta = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='meta'").fetchone()
|
|
49
|
+
if has_meta is None:
|
|
50
|
+
return 0
|
|
51
|
+
row = conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()
|
|
52
|
+
return int(row[0]) if row else 0
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def ensure_current(conn: sqlite3.Connection) -> None:
|
|
56
|
+
"""Inside an open write transaction: refuse a newer schema, run any missing migrations in order."""
|
|
57
|
+
version = stored_version(conn)
|
|
58
|
+
if version > CURRENT_VERSION:
|
|
59
|
+
raise SchemaVersionError(
|
|
60
|
+
f"store schema v{version} is newer than this hermes-access (v{CURRENT_VERSION}); upgrade it"
|
|
61
|
+
)
|
|
62
|
+
for number, statements in MIGRATIONS:
|
|
63
|
+
if number <= version:
|
|
64
|
+
continue
|
|
65
|
+
for statement in statements:
|
|
66
|
+
conn.execute(statement)
|
|
67
|
+
conn.execute(
|
|
68
|
+
"INSERT INTO meta (key, value) VALUES ('schema_version', ?) "
|
|
69
|
+
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
|
70
|
+
(str(number),),
|
|
71
|
+
)
|