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

9 downloads

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, 49 minutes ago History
ledger_integrity.py · 12.5 KB · 335 lines
1"""site_ledger_integrity -- the page somebody opens when they have been
2asked whether the records can be trusted.
3
4 GET /ledger-integrity every anchored ledger, checked
5 GET /ledger-integrity.json the same fold, for a monitor
6
7## It verifies; it does not anchor
8
9Kept separate from system_publish_head on purpose. A pass that both took
10anchors and pronounced them sound would be marking its own homework, and
11the failure would be invisible: the digest it wrote is trivially the
12digest it recomputes.
13
14## The banner is the page
15
16Everything below the banner is detail. The banner answers the only
17question that matters -- **is any of this held by somebody other than this
18server** -- and it answers it in plain words rather than a colour. With no
19notary configured, an anchor is a bookkeeping entry: anybody able to
20rewrite a ledger here can rewrite the row that describes it, sitting in
21the same directory, with the same permissions. Rendering that as a green
22tick would be the most misleading thing this package could do, so it
23renders as a warning that says exactly what is missing and what to set.
24
25The distinction the banner draws is not verified-versus-broken. It is
26**checkable-by-a-stranger versus checkable-only-by-us**, because the first
27is evidence and the second is a claim.
28
29## What "verified" means here, exactly
30
31That the first N rows of a ledger still hash to what an anchor recorded.
32Not that the ledger is complete, not that the rows are true, not that
33nothing was appended since -- appending is what a ledger is for and never
34disturbs an earlier prefix. See object_ledger_head for the three outcomes
35and why truncation is reported separately from a content mismatch.
36"""
37
38import html
39import json
40import os
41
42import object_ledger_head
43import object_notary
44import object_records
45import object_schemas
46
47ANCHORS = "anchors"
48SETTINGS_COLLECTION = "app_settings"
49ENDPOINTS_KEY = "notary.endpoints"
50
51_STYLE = """
52.li { max-width: 52rem; }
53.li h2 { font-size: 1rem; margin: 1.6rem 0 .4rem; }
54.li .banner { border: 1px solid var(--line, #38384a); border-radius: 8px;
55 padding: .9rem 1.1rem; margin: 1rem 0 1.6rem; }
56.li .banner.weak { border-color: var(--accent, #b5713a); }
57.li .banner h2 { margin: 0 0 .3rem; font-size: 1.05rem; }
58.li table { width: 100%; border-collapse: collapse; margin: .4rem 0 1.2rem; }
59.li th, .li td { text-align: left; padding: .35rem .5rem; vertical-align: top;
60 border-bottom: 1px solid var(--line, #38384a); font-size: .87rem; }
61.li .digest { font-family: ui-monospace, Menlo, monospace; font-size: .76rem;
62 word-break: break-all; }
63.li .ok { color: var(--accent, #b5713a); font-weight: 600; }
64.li .bad { color: #d05a5a; font-weight: 600; }
65.li .note { border-left: 3px solid var(--line, #55556a); padding: .1rem 0 .1rem .7rem;
66 margin: .6rem 0 1.2rem; font-size: .87rem; opacity: .85; }
67"""
68
69
70def _esc(value):
71 return html.escape(str(value if value is not None else ""), quote=True)
72
73
74def _base_dir():
75 return os.environ.get("DBBASIC_DATA_DIR", "data")
76
77
78def _text(value):
79 return str(value if value is not None else "").strip()
80
81
82def _settings(base):
83 try:
84 # access: box configuration
85 rows = object_records.read_collection_records(SETTINGS_COLLECTION,
86 base_dir=base)
87 except Exception:
88 return {}
89 return {_text(row.get("key")): _text(row.get("value"))
90 for row in rows if _text(row.get("key"))}
91
92
93def _anchor_to_spec(row):
94 """An anchor row as object_ledger_head.verify() wants it.
95
96 The field list comes out of the ROW, which is the decision that lets a
97 schema migration happen without every historical anchor turning red.
98 """
99 try:
100 row_count = int(_text(row.get("row_count")) or 0)
101 except ValueError:
102 row_count = 0
103 return {
104 "collection": _text(row.get("collection")),
105 "digest": _text(row.get("digest")),
106 "row_count": row_count,
107 "fields": [name for name in _text(row.get("covered_fields")).split(",")
108 if name],
109 }
110
111
112def report(*, base=None):
113 """Every anchored ledger, its current head, and each anchor checked.
114
115 One fold, two surfaces, so the page and the JSON cannot disagree.
116 """
117 base = _base_dir() if base is None else base
118 settings = _settings(base)
119 # The SAME parser the pass uses (object_notary), not a second one
120 # spelled the same way. When these drifted, the page reported an
121 # endpoint the pass was correctly ignoring.
122 endpoints = object_notary.endpoints_from_setting(
123 settings.get(ENDPOINTS_KEY, ""))
124
125 try:
126 # access: chain verdicts and row counts only, no row is shown; registered-readable by design (the site_ledger_integrity grant reason)
127 anchor_rows = object_records.read_collection_records(ANCHORS,
128 base_dir=base)
129 except Exception:
130 anchor_rows = []
131
132 ledgers = {}
133 for row in anchor_rows:
134 ledgers.setdefault(_text(row.get("collection")), []).append(row)
135
136 entries = []
137 total_independent = 0
138 for collection in sorted(name for name in ledgers if name):
139 rows_for = ledgers[collection]
140 specs = [_anchor_to_spec(row) for row in rows_for]
141
142 try:
143 schema = object_schemas.get_schema(collection, base_dir=base)
144 fields = [_text(f.get("name")) for f in (schema or {}).get("fields") or []
145 if _text(f.get("name")) and _text(f.get("name")) != "_op"]
146 except Exception:
147 fields = []
148 try:
149 # access: chain verdicts and row counts only, no row is shown; registered-readable by design (the site_ledger_integrity grant reason)
150 live = object_records.read_collection_records(collection, base_dir=base)
151 except Exception:
152 live = []
153
154 checked = []
155 for row, spec in zip(rows_for, specs):
156 verdict = object_ledger_head.verify(live, spec)
157 try:
158 count = int(_text(row.get("notary_count")) or 0)
159 except ValueError:
160 count = 0
161 total_independent += count
162 checked.append({
163 "taken_at": _text(row.get("created_at")),
164 "row_count": spec["row_count"],
165 "digest": spec["digest"],
166 "notary_count": count,
167 "notaries": _text(row.get("notaries")),
168 "status": _text(row.get("status")),
169 "verdict": verdict,
170 })
171 checked.sort(key=lambda entry: entry["taken_at"], reverse=True)
172
173 entries.append({
174 "collection": collection,
175 "present_rows": len(live),
176 "current_head": (object_ledger_head.head(live, fields,
177 collection=collection)
178 if fields else None),
179 "anchors": checked,
180 "break": object_ledger_head.locate(live, specs),
181 "independent_copies": max((c["notary_count"] for c in checked),
182 default=0),
183 })
184
185 anchored_independently = [e for e in entries if e["independent_copies"] > 0]
186 return {
187 "endpoints": endpoints,
188 "ledgers": entries,
189 "ledger_count": len(entries),
190 "independently_anchored": len(anchored_independently),
191 "total_independent_lodgements": total_independent,
192 "broken": [e["collection"] for e in entries if e["break"]["broken"]],
193 "evidence": bool(anchored_independently),
194 }
195
196
197# --- rendering ---------------------------------------------------------------
198
199def _banner_html(fold):
200 broken = fold["broken"]
201 if broken:
202 names = ", ".join(_esc(name) for name in broken)
203 return f"""
204<div class="banner weak">
205<h2 class="bad">An anchor does not verify</h2>
206<p>{names} no longer hashes to what was recorded. That means rows an anchor
207was taken over have been changed or removed since. Read the ledger's own
208section below for the window it happened in.</p>
209</div>"""
210
211 if not fold["ledgers"]:
212 return """
213<div class="banner weak">
214<h2>Nothing is anchored yet</h2>
215<p>No anchors have been taken, so there is nothing to verify. The daily
216pass (<code>system_publish_head</code>) writes one per ledger; run it by
217hand to start.</p>
218</div>"""
219
220 if not fold["evidence"]:
221 return f"""
222<div class="banner weak">
223<h2>Anchored, but only here</h2>
224<p>Every anchor verifies — and <strong>no independent party holds any of
225them</strong>. These rows sit in the same data directory as the ledgers
226they describe, under the same permissions, so anybody able to rewrite a
227ledger can rewrite its anchor beside it.</p>
228<p>That makes this page a useful check against <em>accident</em> and no
229check at all against <em>intent</em>. To change that, set
230<code>{_esc(ENDPOINTS_KEY)}</code> in settings to one or more notaries run
231by somebody else. Then rewriting history means also rewriting a record on
232a machine this operator does not control.</p>
233</div>"""
234
235 return f"""
236<div class="banner">
237<h2 class="ok">Verified, and held elsewhere</h2>
238<p>Every anchor verifies, and
239<strong>{fold['independently_anchored']} of {fold['ledger_count']}</strong>
240ledgers have a digest lodged with an independent notary
241({fold['total_independent_lodgements']} lodgement{
242 '' if fold['total_independent_lodgements'] == 1 else 's'} in all).
243Altering the anchored history of those ledgers means also altering a
244record held by somebody else.</p>
245</div>"""
246
247
248def _ledger_html(entry):
249 head = entry["current_head"]
250 head_line = (f'<p class="muted">Now: <strong>{entry["present_rows"]:,}</strong> '
251 f'rows &middot; <span class="digest">{_esc(head["digest"])}'
252 f'</span></p>' if head else
253 '<p class="muted">No schema on this box, so no current head '
254 'can be computed.</p>')
255
256 rows = "".join(
257 f'<tr><td><time datetime="{_esc(anchor["taken_at"])}">'
258 f'{_esc(anchor["taken_at"])}</time></td>'
259 f'<td>{anchor["row_count"]:,}</td>'
260 f'<td class="digest">{_esc(anchor["digest"][:16])}&hellip;</td>'
261 f'<td>{anchor["notary_count"] or "&mdash;"}</td>'
262 f'<td class="{"ok" if anchor["verdict"]["verified"] else "bad"}">'
263 f'{_esc(anchor["verdict"]["status"])}</td></tr>'
264 for anchor in entry["anchors"][:20])
265
266 window = (f'<p class="note bad">{_esc(entry["break"]["detail"])}</p>'
267 if entry["break"]["broken"] else "")
268
269 return f"""
270<h2>{_esc(entry["collection"])}</h2>
271{head_line}
272{window}
273<table>
274<thead><tr><th>Taken</th><th>Rows</th><th>Digest</th>
275<th>Independent copies</th><th>Checked</th></tr></thead>
276<tbody>{rows}</tbody></table>
277"""
278
279
280def _page(fold):
281 body = "".join(_ledger_html(entry) for entry in fold["ledgers"])
282 return f"""
283<div class="breadcrumb"><a href="/">Home</a> / Ledger integrity</div>
284<h1>Ledger integrity</h1>
285<p>Each ledger below has been digested at various points and those digests
286recorded. This page recomputes them against the ledgers as they stand now.
287A ledger that has grown is expected — appending never disturbs an earlier
288prefix, which is what makes an anchor checkable a year later.</p>
289{_banner_html(fold)}
290{body}
291<p class="note">"Verified" means the first N rows still hash to what was
292anchored. It does not mean the rows are true, that the ledger is complete,
293or that nothing was added since. What it rules out is a row being edited
294or removed after the fact — and it rules that out only as far as the
295anchor itself is beyond reach of whoever would do the editing.</p>
296<p><a href="/ledger-integrity.json">This page as JSON</a> &middot;
297<a href="/anchors">every anchor</a></p>
298"""
299
300
301def GET(request):
302 request = request or {}
303 path = _text(request.get("_path") or "/ledger-integrity").lower()
304 fold = report()
305
306 if path.endswith(".json"):
307 return {"status": 200,
308 "content_type": "application/json; charset=utf-8",
309 "body": json.dumps(fold, indent=2, sort_keys=True, default=str)}
310
311 return {
312 "status": 200,
313 "content_type": "text/html; charset=utf-8",
314 "body": f"""<!doctype html>
315<html lang="en">
316<head>
317<meta charset="utf-8">
318<meta name="viewport" content="width=device-width, initial-scale=1">
319<title>Ledger integrity</title>
320<link rel="stylesheet" href="/style">
321<style>{_STYLE}</style>
322</head>
323<body>
324<div class="wrap li">
325<header class="app"><h1><a href="/">DBBASIC</a></h1></header>
326{_page(fold)}
327</div>
328<script src="/nav"></script>
329</body>
330</html>""",
331 }
332
333
334def POST(request):
335 return GET(request)