Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_permission_status.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_permission_status.py · 10.4 KB · 294 lines
1"""Permission rollout status summaries for DBBASIC operators and Scroll."""
2
3from __future__ import annotations
4
5from pathlib import Path
6from typing import Any, Mapping
7
8import object_identity
9import object_permission_store
10
11
12def build_permissions_status(
13 *,
14 base_dir: Path | str,
15 permissions: Mapping[str, Any],
16 require_known_identity_users_env: str,
17) -> dict[str, Any]:
18 """Return a read-only summary of permission rollout readiness."""
19 identity = identity_status(base_dir=base_dir)
20 policy = policy_status(base_dir=base_dir)
21 readiness = readiness_status(policy, identity=identity, permissions=permissions)
22 warnings = status_warnings(
23 permissions=permissions,
24 identity=identity,
25 policy=policy,
26 require_known_identity_users_env=require_known_identity_users_env,
27 )
28
29 return {
30 "status": "ok" if policy["valid"] and identity["valid"] else "degraded",
31 "permissions": dict(permissions),
32 "identity": identity,
33 "policy": policy,
34 "coverage": coverage_status(),
35 "readiness": readiness,
36 "warnings": warnings,
37 }
38
39
40def identity_status(*, base_dir: Path | str) -> dict[str, Any]:
41 """Return counts for the local identity store."""
42 try:
43 accounts = object_identity.list_accounts(base_dir=base_dir)
44 users = object_identity.list_users(base_dir=base_dir)
45 sessions = object_identity.list_sessions(base_dir=base_dir)
46 except (OSError, ValueError) as exc:
47 return {
48 "valid": False,
49 "error": str(exc),
50 "accounts": {"count": 0, "active": 0, "disabled": 0},
51 "users": {"count": 0, "active": 0, "disabled": 0},
52 "sessions": {"count": 0, "active": 0, "revoked": 0},
53 }
54
55 return {
56 "valid": True,
57 "accounts": {
58 "count": len(accounts),
59 "active": _count_status(accounts, "active"),
60 "disabled": _count_status(accounts, "disabled"),
61 },
62 "users": {
63 "count": len(users),
64 "active": _count_status(users, "active"),
65 "disabled": _count_status(users, "disabled"),
66 },
67 "sessions": {
68 "count": len(sessions),
69 "active": sum(1 for session in sessions if session.get("active") is True),
70 "revoked": sum(1 for session in sessions if session.get("revoked_at")),
71 },
72 }
73
74
75def policy_status(*, base_dir: Path | str) -> dict[str, Any]:
76 """Return a compact summary of the active permission policy."""
77 try:
78 policy_file_exists = object_permission_store.policy_path(base_dir).exists()
79 except ValueError as exc:
80 return _empty_policy_status(error=str(exc), policy_file_exists=False)
81
82 try:
83 policy = object_permission_store.load_policy(base_dir)
84 except ValueError as exc:
85 return _empty_policy_status(
86 error=f"Permission policy is invalid: {exc}",
87 policy_file_exists=policy_file_exists,
88 )
89
90 rules = policy.rules
91 return {
92 "valid": True,
93 "policy_file_exists": policy_file_exists,
94 "access_mode": policy.access_mode,
95 "rules_count": len(rules),
96 "allow_rules": sum(1 for rule in rules if rule.effect == "allow"),
97 "deny_rules": sum(1 for rule in rules if rule.effect == "deny"),
98 "roles_count": len(policy.roles),
99 "user_roles_count": len(policy.user_roles),
100 "admin_roles": list(policy.admin_roles),
101 "principals": sorted({rule.principal for rule in rules}),
102 "actions": sorted({action for rule in rules for action in rule.actions}),
103 "collections": sorted({rule.collection for rule in rules if rule.collection is not None}),
104 "objects": sorted({rule.object_id for rule in rules if rule.object_id is not None}),
105 "temporary_rules": sum(
106 1 for rule in rules if rule.valid_from is not None or rule.expires_at is not None
107 ),
108 }
109
110
111def enforcement_readiness(
112 *,
113 base_dir: Path | str,
114 permissions: Mapping[str, Any] | None = None,
115) -> dict[str, Any]:
116 """Return the same readiness gate used by the HTTP server."""
117 identity = identity_status(base_dir=base_dir)
118 policy = policy_status(base_dir=base_dir)
119 return readiness_status(policy, identity=identity, permissions=permissions)
120
121
122def readiness_status(
123 policy: Mapping[str, Any],
124 *,
125 identity: Mapping[str, Any] | None = None,
126 permissions: Mapping[str, Any] | None = None,
127) -> dict[str, Any]:
128 """Return blockers that make permission enforcement unsafe to enable."""
129 blockers: list[str] = []
130 runtime = dict(permissions or {})
131
132 if runtime and not runtime.get("admin_token_configured", False):
133 blockers.append(
134 "Admin recovery token must be configured before enforcement rollout."
135 )
136
137 if identity is not None and not identity["valid"]:
138 blockers.append("Identity store must be readable before enforcement rollout.")
139
140 if not policy["valid"]:
141 blockers.append("Permission policy must be valid before enforcement rollout.")
142 else:
143 access_mode = policy["access_mode"]
144 if access_mode == "password":
145 blockers.append(
146 "Password access mode needs a password verifier before enforcement rollout."
147 )
148 if access_mode == "role_based" and policy["allow_rules"] == 0:
149 blockers.append(
150 "Role-based policy has no allow grants; non-admin traffic will be denied."
151 )
152 if (
153 identity is not None
154 and access_mode in {"registered", "subscription", "role_based", "private"}
155 and not _has_non_admin_identity_path(identity=identity, permissions=runtime)
156 ):
157 blockers.append(
158 "No non-admin identity path is available; enable trusted headers, "
159 "guarded session login, password login, or create an active session "
160 "before enforcement."
161 )
162
163 return {
164 "can_enable_enforcement": not blockers,
165 "blockers": blockers,
166 }
167
168
169def status_warnings(
170 *,
171 permissions: Mapping[str, Any],
172 identity: Mapping[str, Any],
173 policy: Mapping[str, Any],
174 require_known_identity_users_env: str,
175) -> list[str]:
176 """Return non-blocking warnings for the active permission setup."""
177 warnings: list[str] = []
178 enforcement_requested = bool(
179 permissions.get("enforcement_requested", permissions.get("enforcement_enabled", False))
180 )
181 enforcement_enabled = bool(permissions.get("enforcement_enabled", False))
182 if permissions.get("enforcement_blocked"):
183 warnings.append(
184 "Permission enforcement was requested but readiness checks blocked rollout."
185 )
186 elif not enforcement_requested and not enforcement_enabled:
187 warnings.append("Permission enforcement is off.")
188 if permissions.get("allow_unready_enforcement"):
189 warnings.append(
190 "Unready permission enforcement override is enabled; use only for manual recovery or tests."
191 )
192 if not permissions["audit_enabled"]:
193 warnings.append("Permission audit is off; enable audit mode before enforcement rollout.")
194 if permissions["trusted_headers_enabled"]:
195 warnings.append(
196 "Trusted identity headers are enabled; the reverse proxy must strip client-supplied identity headers."
197 )
198 elif (
199 identity["valid"]
200 and identity["sessions"]["active"] == 0
201 and not _session_login_available(identity=identity, permissions=permissions)
202 and not _password_login_available(identity=identity, permissions=permissions)
203 ):
204 warnings.append(
205 "Trusted headers are off and no active DBBASIC sessions exist; non-admin requests will be anonymous."
206 )
207 if not permissions["require_known_identity_users"]:
208 warnings.append(
209 f"{require_known_identity_users_env} is off; admin code can mint sessions for unregistered users."
210 )
211 if identity["valid"] and identity["users"]["count"] == 0:
212 warnings.append("No identity users are registered yet.")
213 if policy["valid"] and policy["access_mode"] == "public":
214 warnings.append("Public access mode allows read/execute without identity.")
215 return warnings
216
217
218def _has_non_admin_identity_path(
219 *,
220 identity: Mapping[str, Any],
221 permissions: Mapping[str, Any],
222) -> bool:
223 if permissions.get("trusted_headers_enabled"):
224 return True
225 if _session_login_available(identity=identity, permissions=permissions):
226 return True
227 if _password_login_available(identity=identity, permissions=permissions):
228 return True
229 return bool(identity["sessions"]["active"])
230
231
232def _session_login_available(
233 *,
234 identity: Mapping[str, Any],
235 permissions: Mapping[str, Any],
236) -> bool:
237 return bool(
238 permissions.get("session_login_enabled")
239 and permissions.get("session_login_token_configured")
240 and identity["users"]["active"] > 0
241 )
242
243
244def _password_login_available(
245 *,
246 identity: Mapping[str, Any],
247 permissions: Mapping[str, Any],
248) -> bool:
249 return bool(
250 permissions.get("password_login_enabled")
251 and identity["users"]["active"] > 0
252 )
253
254
255def coverage_status() -> dict[str, list[str]]:
256 """Return route groups covered by permission policy checks."""
257 return {
258 "policy_checked": [
259 "object execution and mutation routes",
260 "object source, state, logs, files, metadata, and versions",
261 "collection record read, create, update, and delete routes",
262 ],
263 "admin_gated": [
264 "permissions policy, status, check, and audit routes",
265 "identity account, user, and session routes",
266 "schema metadata routes",
267 "package install and restore routes",
268 "event publish, retention, and subscription routes",
269 ],
270 }
271
272
273def _empty_policy_status(*, error: str, policy_file_exists: bool) -> dict[str, Any]:
274 return {
275 "valid": False,
276 "error": error,
277 "policy_file_exists": policy_file_exists,
278 "access_mode": None,
279 "rules_count": 0,
280 "allow_rules": 0,
281 "deny_rules": 0,
282 "roles_count": 0,
283 "user_roles_count": 0,
284 "admin_roles": [],
285 "principals": [],
286 "actions": [],
287 "collections": [],
288 "objects": [],
289 "temporary_rules": 0,
290 }
291
292
293def _count_status(items: list[dict[str, Any]], status: str) -> int:
294 return sum(1 for item in items if item.get("status") == status)