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

9 downloads

dbbasic-object-server/object_permission_status.py
Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 8 minutes ago History
object_permission_status.py · 16.2 KB · 411 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
10import object_permissions
11
12
13def build_permissions_status(
14 *,
15 base_dir: Path | str,
16 permissions: Mapping[str, Any],
17 require_known_identity_users_env: str,
18) -> dict[str, Any]:
19 """Return a read-only summary of permission rollout readiness."""
20 identity = identity_status(base_dir=base_dir)
21 policy = policy_status(base_dir=base_dir, with_findings=True)
22 readiness = readiness_status(policy, identity=identity, permissions=permissions)
23 warnings = status_warnings(
24 permissions=permissions,
25 identity=identity,
26 policy=policy,
27 require_known_identity_users_env=require_known_identity_users_env,
28 )
29
30 return {
31 "status": "ok" if policy["valid"] and identity["valid"] else "degraded",
32 "permissions": dict(permissions),
33 "identity": identity,
34 "policy": policy,
35 "coverage": coverage_status(),
36 "readiness": readiness,
37 "warnings": warnings,
38 }
39
40
41def identity_status(*, base_dir: Path | str) -> dict[str, Any]:
42 """Return counts for the local identity store."""
43 try:
44 accounts = object_identity.list_accounts(base_dir=base_dir)
45 users = object_identity.list_users(base_dir=base_dir)
46 sessions = object_identity.list_sessions(base_dir=base_dir)
47 except (OSError, ValueError) as exc:
48 return {
49 "valid": False,
50 "error": str(exc),
51 "accounts": {"count": 0, "active": 0, "disabled": 0},
52 "users": {"count": 0, "active": 0, "disabled": 0},
53 "sessions": {"count": 0, "active": 0, "revoked": 0},
54 }
55
56 return {
57 "valid": True,
58 "accounts": {
59 "count": len(accounts),
60 "active": _count_status(accounts, "active"),
61 "disabled": _count_status(accounts, "disabled"),
62 },
63 "users": {
64 "count": len(users),
65 "active": _count_status(users, "active"),
66 "disabled": _count_status(users, "disabled"),
67 },
68 "sessions": {
69 "count": len(sessions),
70 "active": sum(1 for session in sessions if session.get("active") is True),
71 "revoked": sum(1 for session in sessions if session.get("revoked_at")),
72 },
73 }
74
75
76def policy_status(*, base_dir: Path | str, with_findings: bool = False) -> dict[str, Any]:
77 """Return a compact summary of the active permission policy.
78
79 `findings` (the stored file's DRON mistakes) is computed only when asked
80 for: it reads the file again, and the readiness checks that also call
81 this do not need it."""
82 try:
83 policy_file_exists = object_permission_store.policy_path(base_dir).exists()
84 except (OSError, ValueError) as exc:
85 return _empty_policy_status(error=str(exc), policy_file_exists=False)
86
87 try:
88 policy = object_permission_store.load_policy(base_dir)
89 except (OSError, ValueError) as exc:
90 # A file that cannot be read (a directory, no permission) is as
91 # unusable as one that does not parse: report it, never raise.
92 what = "could not be read" if isinstance(exc, OSError) else "is invalid"
93 return _empty_policy_status(
94 error=f"Permission policy {what}: {exc}",
95 policy_file_exists=policy_file_exists,
96 )
97
98 rules = policy.rules
99 return {
100 "valid": True,
101 "policy_file_exists": policy_file_exists,
102 "access_mode": policy.access_mode,
103 "rules_count": len(rules),
104 "allow_rules": sum(1 for rule in rules if rule.effect == "allow"),
105 "deny_rules": sum(1 for rule in rules if rule.effect == "deny"),
106 "roles_count": len(policy.roles),
107 "user_roles_count": len(policy.user_roles),
108 "admin_roles": list(policy.admin_roles),
109 "principals": sorted({rule.principal for rule in rules}),
110 "actions": sorted({action for rule in rules for action in rule.actions}),
111 "collections": sorted({rule.collection for rule in rules if rule.collection is not None}),
112 "objects": sorted({rule.object_id for rule in rules if rule.object_id is not None}),
113 "temporary_rules": sum(
114 1 for rule in rules if rule.valid_from is not None or rule.expires_at is not None
115 ),
116 # DRON mistakes in the stored file the engine reads loosely, each with
117 # what the engine does with it today and how to fix it; `serious` ones
118 # make the policy allow more than written. Report only: nothing here
119 # changes a decision (object_permissions.stored_policy_findings). A
120 # serious one on an allow rule also carries `applied`: False while
121 # DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS stops the rule applying.
122 "findings": object_permission_store.stored_policy_findings(base_dir) if with_findings else [],
123 }
124
125
126def enforcement_readiness(
127 *,
128 base_dir: Path | str,
129 permissions: Mapping[str, Any] | None = None,
130) -> dict[str, Any]:
131 """Return the same readiness gate used by the HTTP server."""
132 identity = identity_status(base_dir=base_dir)
133 policy = policy_status(base_dir=base_dir)
134 return readiness_status(policy, identity=identity, permissions=permissions)
135
136
137NO_SIGN_IN_PATH_PROBLEM = (
138 "No non-admin sign-in path: only the admin token and public grants reach this server."
139)
140PASSWORD_MODE_PROBLEM = (
141 "Password access mode has no verifier; non-admin requests not matched by an allow "
142 "rule are refused."
143)
144
145
146def enforced_problems(
147 policy: Mapping[str, Any],
148 *,
149 identity: Mapping[str, Any],
150 permissions: Mapping[str, Any],
151) -> list[str]:
152 """What an enforced box does about each readiness blocker, one sentence each.
153
154 Readiness used to be a switch: any blocker turned a requested
155 enforcement off, per request, and the box served everything. It is now
156 diagnostics only. Enforcement stays on, and each of these says what the
157 affected callers get instead, so the operator can tell a fenced box with
158 a problem from an open one. Same order and conditions as readiness_status.
159 """
160 problems: list[str] = []
161 if not permissions.get("admin_token_configured", False):
162 problems.append(
163 "No admin token (DBBASIC_ADMIN_TOKEN): nobody can use the permissions, identity "
164 "or package APIs over HTTP; set it and restart."
165 )
166 if not identity["valid"]:
167 problems.append(
168 f"The identity store is unreadable ({identity.get('error')}): signed-in users get "
169 "503 identity_store_unavailable until it is fixed on disk; requests without a "
170 "credential get only what the policy grants anonymous callers."
171 )
172 if not policy["valid"]:
173 problems.append(
174 f"The permission policy cannot be used ({policy.get('error')}): non-admin requests "
175 "get 503 permission_policy_unavailable until it is repaired (PUT /permissions/policy "
176 "with the admin token)."
177 )
178 return problems
179 access_mode = policy["access_mode"]
180 if access_mode == "password":
181 problems.append(PASSWORD_MODE_PROBLEM)
182 if access_mode in {"registered", "subscription", "role_based", "private"} and (
183 identity["valid"]
184 and not _has_non_admin_identity_path(identity=identity, permissions=permissions)
185 ):
186 problems.append(NO_SIGN_IN_PATH_PROBLEM)
187 return problems
188
189
190def readiness_status(
191 policy: Mapping[str, Any],
192 *,
193 identity: Mapping[str, Any] | None = None,
194 permissions: Mapping[str, Any] | None = None,
195) -> dict[str, Any]:
196 """Return what would hurt if permission enforcement were on now.
197
198 Advisory only. These were once blockers that switched a requested
199 enforcement off (and the box open); enforcement no longer reads them.
200 enforced_problems says what each one does to requests while enforced.
201 """
202 blockers: list[str] = []
203 runtime = dict(permissions or {})
204
205 if runtime and not runtime.get("admin_token_configured", False):
206 blockers.append(
207 "Admin recovery token must be configured before enforcement rollout."
208 )
209
210 if identity is not None and not identity["valid"]:
211 blockers.append("Identity store must be readable before enforcement rollout.")
212
213 if not policy["valid"]:
214 blockers.append("Permission policy must be valid before enforcement rollout.")
215 else:
216 access_mode = policy["access_mode"]
217 if access_mode == "password":
218 blockers.append(
219 "Password access mode needs a password verifier before enforcement rollout."
220 )
221 # A role-based policy with no allow grants is NOT a blocker: enforced, it denies
222 # every non-admin request, which is the safe outcome, and it is the state of
223 # every fresh box before its first policy or package (the admin token is the way
224 # in). It blocked once, and a blocked enforcement used to run every request
225 # unenforced -- the open box this gate exists to prevent. status_warnings says it.
226 if (
227 identity is not None
228 and access_mode in {"registered", "subscription", "role_based", "private"}
229 and not _has_non_admin_identity_path(identity=identity, permissions=runtime)
230 ):
231 blockers.append(
232 "No non-admin identity path is available; enable trusted headers, "
233 "guarded session login, password login, or create an active session "
234 "before enforcement."
235 )
236
237 return {
238 "can_enable_enforcement": not blockers,
239 "blockers": blockers,
240 }
241
242
243def status_warnings(
244 *,
245 permissions: Mapping[str, Any],
246 identity: Mapping[str, Any],
247 policy: Mapping[str, Any],
248 require_known_identity_users_env: str,
249) -> list[str]:
250 """Return non-blocking warnings for the active permission setup."""
251 warnings: list[str] = []
252 enforcement_requested = bool(
253 permissions.get("enforcement_requested", permissions.get("enforcement_enabled", False))
254 )
255 enforcement_enabled = bool(permissions.get("enforcement_enabled", False))
256 if not enforcement_requested and not enforcement_enabled:
257 warnings.append("Permission enforcement is off.")
258 if permissions.get("allow_unready_enforcement"):
259 warnings.append(
260 "DBBASIC_ALLOW_UNREADY_PERMISSION_ENFORCEMENT no longer does anything: requested "
261 "enforcement is always enforced. Remove it."
262 )
263 if not permissions["audit_enabled"]:
264 warnings.append("Permission audit is off; enable audit mode before enforcement rollout.")
265 if permissions.get("identity_source_refused"):
266 warnings.append(
267 f"Identity source refused, none is in use: {permissions['identity_source_refused']}. "
268 "Sign-ins from it are treated as anonymous."
269 )
270 if permissions["trusted_headers_enabled"]:
271 warnings.append(
272 "Trusted identity headers are enabled; the reverse proxy must strip client-supplied identity headers."
273 )
274 elif (
275 identity["valid"]
276 and identity["sessions"]["active"] == 0
277 and not permissions.get("identity_source_configured")
278 and not _session_login_available(identity=identity, permissions=permissions)
279 and not _password_login_available(identity=identity, permissions=permissions)
280 ):
281 warnings.append(
282 "Trusted headers are off and no active DBBASIC sessions exist; non-admin requests will be anonymous."
283 )
284 if not permissions["require_known_identity_users"]:
285 warnings.append(
286 f"{require_known_identity_users_env} is off; admin code can mint sessions for unregistered users."
287 )
288 if identity["valid"] and identity["users"]["count"] == 0:
289 warnings.append("No identity users are registered yet.")
290 if policy["valid"] and denies_all_non_admin(policy):
291 warnings.append(
292 "Role-based policy has no allow grants; non-admin traffic is denied "
293 "(save a policy with PUT /permissions/policy, or install packages)."
294 )
295 if policy["valid"]:
296 findings = policy.get("findings") or []
297 for finding in findings:
298 if finding["serious"] and finding.get("applied") is False:
299 # DBBASIC_POLICY_FAIL_CLOSED_WIDENED_ALLOWS is on.
300 warnings.append(
301 "Permission policy has an allow rule that would allow more than written, "
302 f"{object_permissions.finding_text(finding)}."
303 )
304 elif finding["serious"]:
305 warnings.append(
306 "Permission policy allows more than written, "
307 f"{object_permissions.finding_text(finding)}."
308 )
309 smaller = sum(1 for finding in findings if not finding["serious"])
310 if smaller:
311 warnings.append(
312 f"Permission policy has {smaller} smaller mistake(s) the engine reads loosely; "
313 "see policy.findings."
314 )
315 if policy["valid"] and policy["access_mode"] == "public":
316 warnings.append("Public access mode allows read/execute without identity.")
317 if policy["valid"] and policy["access_mode"] == "password":
318 warnings.append(PASSWORD_MODE_PROBLEM)
319 return warnings
320
321
322def _has_non_admin_identity_path(
323 *,
324 identity: Mapping[str, Any],
325 permissions: Mapping[str, Any],
326) -> bool:
327 if permissions.get("trusted_headers_enabled"):
328 return True
329 if permissions.get("identity_source_configured"):
330 return True
331 if _session_login_available(identity=identity, permissions=permissions):
332 return True
333 if _password_login_available(identity=identity, permissions=permissions):
334 return True
335 return bool(identity["sessions"]["active"])
336
337
338def _session_login_available(
339 *,
340 identity: Mapping[str, Any],
341 permissions: Mapping[str, Any],
342) -> bool:
343 return bool(
344 permissions.get("session_login_enabled")
345 and permissions.get("session_login_token_configured")
346 and identity["users"]["active"] > 0
347 )
348
349
350def _password_login_available(
351 *,
352 identity: Mapping[str, Any],
353 permissions: Mapping[str, Any],
354) -> bool:
355 """Password login is a sign-in path as soon as it is on, users or not.
356
357 It used to require an active user, which made a one-click box (starter
358 policy, password login, enforcement, no users until the owner opens
359 /setup) "blocked" and, since 7994543, unable to start. The first user
360 arrives through /setup, signup or the admin token; until then
361 enforcement denies non-admins, which is what an empty box should do.
362 """
363 del identity
364 return bool(permissions.get("password_login_enabled"))
365
366
367def denies_all_non_admin(policy: Mapping[str, Any]) -> bool:
368 return policy.get("access_mode") == "role_based" and policy.get("allow_rules") == 0
369
370
371def coverage_status() -> dict[str, list[str]]:
372 """Return route groups covered by permission policy checks."""
373 return {
374 "policy_checked": [
375 "object execution and mutation routes",
376 "object source, state, logs, files, metadata, and versions",
377 "collection record read, create, update, and delete routes",
378 ],
379 "admin_gated": [
380 "permissions policy, status, check, and audit routes",
381 "identity account, user, and session routes",
382 "schema metadata routes",
383 "package install and restore routes",
384 "event publish, retention, and subscription routes",
385 ],
386 }
387
388
389def _empty_policy_status(*, error: str, policy_file_exists: bool) -> dict[str, Any]:
390 return {
391 "valid": False,
392 "error": error,
393 "policy_file_exists": policy_file_exists,
394 "access_mode": None,
395 "rules_count": 0,
396 "allow_rules": 0,
397 "deny_rules": 0,
398 "roles_count": 0,
399 "user_roles_count": 0,
400 "admin_roles": [],
401 "principals": [],
402 "actions": [],
403 "collections": [],
404 "objects": [],
405 "temporary_rules": 0,
406 "findings": [],
407 }
408
409
410def _count_status(items: list[dict[str, Any]], status: str) -> int:
411 return sum(1 for item in items if item.get("status") == status)