egzoscore 0.2.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.
- egzos/__init__.py +11 -0
- egzos/_ids.py +29 -0
- egzos/_signals.py +39 -0
- egzos/_term.py +33 -0
- egzos/_types.py +1023 -0
- egzos/api/__init__.py +150 -0
- egzos/api/app.py +1574 -0
- egzos/api/blobs.py +92 -0
- egzos/api/throttle.py +190 -0
- egzos/auth.py +176 -0
- egzos/authz/__init__.py +5 -0
- egzos/authz/presence.py +778 -0
- egzos/authz/values.py +32 -0
- egzos/backends/__init__.py +8 -0
- egzos/backends/base.py +91 -0
- egzos/backends/postgres.py +490 -0
- egzos/backends/sqlite.py +524 -0
- egzos/binding.py +309 -0
- egzos/cli/__init__.py +1092 -0
- egzos/cli/__main__.py +11 -0
- egzos/confirm.py +455 -0
- egzos/container.py +222 -0
- egzos/identity.py +1104 -0
- egzos/ledger.py +167 -0
- egzos/mcp/__init__.py +3 -0
- egzos/mcp/http.py +90 -0
- egzos/mcp/server.py +287 -0
- egzos/model.py +242 -0
- egzos/py.typed +0 -0
- egzos/resolver.py +115 -0
- egzos/store/__init__.py +10 -0
- egzos/store/autotitle.py +31 -0
- egzos/store/blobs.py +120 -0
- egzos/store/find.py +120 -0
- egzos/store/items.py +233 -0
- egzos/store/nodes.py +193 -0
- egzos/store/objects.py +143 -0
- egzos/store/uploads.py +369 -0
- egzos/trust.py +675 -0
- egzos/web/__init__.py +88 -0
- egzos/web/app.py +965 -0
- egzos/web/static/htmx.LICENSE +13 -0
- egzos/web/static/htmx.min.js +1 -0
- egzos/web/static/lifeboat.css +140 -0
- egzos/web/static/lifeboat.js +12 -0
- egzos/web/strings.py +133 -0
- egzos/web/templates/_manifest_row.html +3 -0
- egzos/web/templates/_shell.html +29 -0
- egzos/web/templates/_window.html +7 -0
- egzos/web/templates/base.html +24 -0
- egzos/web/templates/error.html +10 -0
- egzos/web/templates/home.html +39 -0
- egzos/web/templates/item.html +91 -0
- egzos/web/templates/notfound.html +6 -0
- egzos/web/templates/pending.html +107 -0
- egzos/web/tokens.css +294 -0
- egzoscore-0.2.0.dist-info/METADATA +135 -0
- egzoscore-0.2.0.dist-info/RECORD +62 -0
- egzoscore-0.2.0.dist-info/WHEEL +4 -0
- egzoscore-0.2.0.dist-info/entry_points.txt +2 -0
- egzoscore-0.2.0.dist-info/licenses/LICENSE +65 -0
- egzoscore-0.2.0.dist-info/licenses/NOTICE +6 -0
egzos/api/blobs.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""
|
|
4
|
+
`BlobGrant` redemption at the REST door (rest.md §6): `GET /v1/blobs/<sha256>?item=&token=
|
|
5
|
+
&expires_at=&sig=`.
|
|
6
|
+
|
|
7
|
+
The descriptor is the whole credential, so no `Authorization` header is read. The eight checks run
|
|
8
|
+
in the contract's order, and every failure is §3's one refusal, whichever check it was. A
|
|
9
|
+
descriptor that does not verify names no caller: the throttle counts it, and the window's
|
|
10
|
+
`rest.tally` tallies it under `forged`. One that verifies is its token's: that token's bucket is
|
|
11
|
+
read before check 3, and a refusal from check 3 on counts in it and appends `context.fetch` with
|
|
12
|
+
the check, attributed to the token. Check 4 spends the grant, so a later refusal still spends it.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import re
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from egzos._ids import is_ulid
|
|
21
|
+
from egzos._types import BLOB_GRANT_LIFETIME_SECONDS, BlobGrant
|
|
22
|
+
from egzos.api.throttle import Throttle
|
|
23
|
+
from egzos.container import Container
|
|
24
|
+
from egzos.ledger import attributed
|
|
25
|
+
from egzos.store.blobs import GRANT_QUERY, _is_digest
|
|
26
|
+
from egzos.trust import grant_expiry
|
|
27
|
+
|
|
28
|
+
#: §6: the headers the bytes go out under, and no others: never rendered on this origin.
|
|
29
|
+
PULL_HEADERS = {
|
|
30
|
+
"Content-Type": "application/octet-stream",
|
|
31
|
+
"Content-Disposition": "attachment",
|
|
32
|
+
"X-Content-Type-Options": "nosniff",
|
|
33
|
+
"Content-Security-Policy": "sandbox",
|
|
34
|
+
"Cache-Control": "no-store",
|
|
35
|
+
"Referrer-Policy": "no-referrer",
|
|
36
|
+
}
|
|
37
|
+
#: A `Token.id`, or a provider grant's `user:<sub>`, `agent:<client_id>:<sub>` or
|
|
38
|
+
#: `terminal:<client_id>:<sub>`, in either spelling (§6).
|
|
39
|
+
_TOKEN = re.compile(r"[\x21-\x7e]{1,512}")
|
|
40
|
+
_SIG = re.compile(r"[0-9a-f]{64}")
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def descriptor(sha256: str, params: Any) -> BlobGrant | None:
|
|
44
|
+
"""Check 1: the path's digest, and the four parameters, each once and well-formed."""
|
|
45
|
+
if set(params.keys()) != set(GRANT_QUERY) or len(params.multi_items()) != len(GRANT_QUERY):
|
|
46
|
+
return None
|
|
47
|
+
grant: BlobGrant = {"sha256": sha256, "item": params["item"], "token": params["token"],
|
|
48
|
+
"expires_at": params["expires_at"], "sig": params["sig"]}
|
|
49
|
+
if (_is_digest(sha256) and is_ulid(grant["item"]) and _TOKEN.fullmatch(grant["token"])
|
|
50
|
+
and _SIG.fullmatch(grant["sig"]) and grant_expiry(grant["expires_at"]) is not None):
|
|
51
|
+
return grant
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def redeem(
|
|
56
|
+
c: Container, throttle: Throttle, address: str | None, sha256: str, params: Any
|
|
57
|
+
) -> bytes | None:
|
|
58
|
+
"""The bytes a descriptor redeems, or None for §3's refusal."""
|
|
59
|
+
grant = descriptor(sha256, params) # 1
|
|
60
|
+
if grant is None or not c.trust.verify_grant(grant): # 2
|
|
61
|
+
throttle.count(address, refused=False, forged=True)
|
|
62
|
+
return None
|
|
63
|
+
if throttle.token_holds(grant["token"]):
|
|
64
|
+
# §2 item 7: counted and not evaluated, so neither spent nor traced; its release is.
|
|
65
|
+
throttle.count_token(grant["token"], refused=True)
|
|
66
|
+
return None
|
|
67
|
+
# The token as it stands now: never None, as an id no record holds is a revoked stand-in.
|
|
68
|
+
token, item, data = c.trust.named(grant["token"]), None, None
|
|
69
|
+
expires = grant_expiry(grant["expires_at"]) or 0.0
|
|
70
|
+
if expires <= c.trust.clock(): # 3
|
|
71
|
+
failed: int | None = 3
|
|
72
|
+
elif not c.trust.spend_grant(grant): # 4
|
|
73
|
+
failed = 4
|
|
74
|
+
else:
|
|
75
|
+
item = c.store.get(grant["item"])
|
|
76
|
+
failed = c.trust.pull_refusal( # 5, 6
|
|
77
|
+
token, item, minted=expires - BLOB_GRANT_LIFETIME_SECONDS)
|
|
78
|
+
# 7: the path's digest is the descriptor's own (check 1 read it there).
|
|
79
|
+
if failed is None and grant["sha256"] != item.content.get("sha256"):
|
|
80
|
+
failed = 7
|
|
81
|
+
if failed is None and (data := c.blobs.get(sha256)) is None:
|
|
82
|
+
failed = 8
|
|
83
|
+
with attributed(token):
|
|
84
|
+
if failed is not None:
|
|
85
|
+
throttle.count_token(grant["token"], refused=False)
|
|
86
|
+
c.ledger.append("context.fetch", actor=token.owner, principal=token.principal,
|
|
87
|
+
client=token.client, ref=grant["item"], token=grant["token"],
|
|
88
|
+
check=failed, items=[], layers=[], withheld=0)
|
|
89
|
+
return None
|
|
90
|
+
c.ledger.append("blob.pull", actor=token.owner, principal=token.principal,
|
|
91
|
+
subject=item.id, scope=item.scope, sha256=sha256, size=len(data))
|
|
92
|
+
return data
|
egzos/api/throttle.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""
|
|
4
|
+
The REST door's throttle (rest.md §2 item 7), on its own surface word, `rest`.
|
|
5
|
+
|
|
6
|
+
What counts is what a sweep looks like: every `401` the door answers, and every attempt refused
|
|
7
|
+
while a bucket holds. Two buckets, both enforced: one container-global, one keyed on the transport
|
|
8
|
+
source address (never on a value the caller supplies). A bucket that reaches its rate holds until
|
|
9
|
+
its window closes, and while either holds every request gets the route's uniform failure, counted
|
|
10
|
+
and not evaluated, a live token included (owner lockout is accepted, the Chief on #141).
|
|
11
|
+
|
|
12
|
+
No attempt appends an entry. When a window closes, each bucket that engaged appends `authz.release`
|
|
13
|
+
(`refused`, `refused: 0` included), and the container-global window that admitted any `401` appends
|
|
14
|
+
`rest.tally`. Both carry `principal: none` and `actor: rest`, and a `window_key` derived from the
|
|
15
|
+
bucket under a per-container secret: it pairs a release with its tally, rotates with the window,
|
|
16
|
+
and never discloses the bucket's key — a source address never reaches the chain.
|
|
17
|
+
|
|
18
|
+
A `BlobGrant` redemption whose descriptor does not verify counts as a `401` does, and the tally
|
|
19
|
+
counts it under `forged` (rest.md §6). A third bucket, keyed on the `Token.id` a verified
|
|
20
|
+
descriptor names, counts that token's refused redemptions alone (the Chief on #184).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import hashlib
|
|
26
|
+
import hmac
|
|
27
|
+
import time
|
|
28
|
+
from collections.abc import Callable
|
|
29
|
+
from contextlib import AbstractContextManager, nullcontext
|
|
30
|
+
from pathlib import Path
|
|
31
|
+
from typing import Any
|
|
32
|
+
|
|
33
|
+
from egzos._types import AS_THROTTLE_RATES, AS_THROTTLE_WINDOW_SECONDS, ThrottleState
|
|
34
|
+
from egzos.auth import home_secret
|
|
35
|
+
from egzos.ledger import Ledger
|
|
36
|
+
|
|
37
|
+
SURFACE = "rest"
|
|
38
|
+
RATE = AS_THROTTLE_RATES[SURFACE]
|
|
39
|
+
WINDOW_SECONDS = AS_THROTTLE_WINDOW_SECONDS
|
|
40
|
+
GLOBAL = "g"
|
|
41
|
+
#: How long a closed window's counters are kept after it closes: an hour. Older rows are forgotten,
|
|
42
|
+
#: so a sweep from many addresses cannot grow the table without bound.
|
|
43
|
+
KEEP_WINDOWS = 12
|
|
44
|
+
KEY_FILE = "throttle.key"
|
|
45
|
+
KEY_BYTES = 32
|
|
46
|
+
#: How many key names a container tries, `throttle.key` first, passing over short ones.
|
|
47
|
+
KEY_SLOTS = 4
|
|
48
|
+
#: rest.md §2 item 7: refused redemptions per token per window. a1p's proposal, the per-source
|
|
49
|
+
#: number; not in `_types.py` until the Chief confirms it (TODO(chief), #141).
|
|
50
|
+
PER_TOKEN = 30
|
|
51
|
+
|
|
52
|
+
_REFUSED = "!refused"
|
|
53
|
+
_ADMITTED_401 = "!401"
|
|
54
|
+
_FORGED = "!forged"
|
|
55
|
+
_CLOSED = "!closed"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def throttle_key(home: Path) -> bytes:
|
|
59
|
+
"""The per-container secret behind every `window_key` and source bucket: 32 bytes, 0600,
|
|
60
|
+
created once. It is written whole to a private file and linked into place, first writer wins,
|
|
61
|
+
so no reader ever sees a half-written key. A key file is never rewritten: a short one, left
|
|
62
|
+
by a crash under earlier code, is passed over for the next name, which every process reaches
|
|
63
|
+
the same way, so every process reads the same key. Should all `KEY_SLOTS` names be short, it
|
|
64
|
+
raises and the door does not start: it fails closed, never on an empty key."""
|
|
65
|
+
for slot in range(KEY_SLOTS):
|
|
66
|
+
name = KEY_FILE if slot == 0 else f"{KEY_FILE}.{slot}"
|
|
67
|
+
data = home_secret(Path(home) / name, KEY_BYTES)
|
|
68
|
+
if len(data) == KEY_BYTES:
|
|
69
|
+
return data
|
|
70
|
+
raise RuntimeError("the throttle key cannot be read")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Throttle:
|
|
74
|
+
def __init__(
|
|
75
|
+
self,
|
|
76
|
+
state: ThrottleState,
|
|
77
|
+
ledger: Ledger,
|
|
78
|
+
key: bytes,
|
|
79
|
+
*,
|
|
80
|
+
clock: Callable[[], float] = time.time,
|
|
81
|
+
atomic: Callable[[], AbstractContextManager[Any]] = nullcontext,
|
|
82
|
+
):
|
|
83
|
+
self.state = state
|
|
84
|
+
self.ledger = ledger
|
|
85
|
+
self._key = key
|
|
86
|
+
self._clock = clock
|
|
87
|
+
# A window's claim and its entries are one transaction: an append that fails rolls the
|
|
88
|
+
# claim back, so the next pass closes the window again and its record is never lost.
|
|
89
|
+
self._atomic = atomic
|
|
90
|
+
|
|
91
|
+
def _window(self) -> int:
|
|
92
|
+
return int(self._clock() // WINDOW_SECONDS)
|
|
93
|
+
|
|
94
|
+
def _digest(self, value: str) -> str:
|
|
95
|
+
raw = value.encode("utf-8", "surrogatepass")
|
|
96
|
+
return hmac.new(self._key, raw, hashlib.sha256).hexdigest()
|
|
97
|
+
|
|
98
|
+
def _source(self, address: str | None) -> str:
|
|
99
|
+
return "s:" + self._digest(f"source|{address or '-'}")[:32]
|
|
100
|
+
|
|
101
|
+
def window_key(self, bucket: str, window: int) -> str:
|
|
102
|
+
return self._digest(f"window|{bucket}|{window}")[:16]
|
|
103
|
+
|
|
104
|
+
# -- per request ------------------------------------------------------------------------------
|
|
105
|
+
def _token(self, token_id: str) -> str:
|
|
106
|
+
return "t:" + self._digest(f"token|{token_id}")[:32]
|
|
107
|
+
|
|
108
|
+
def holds(self, address: str | None) -> bool:
|
|
109
|
+
"""Whether either bucket holds in this window. Read first, for every request."""
|
|
110
|
+
w = str(self._window())
|
|
111
|
+
return (
|
|
112
|
+
self.state.throttle_count(SURFACE, GLOBAL, w) >= RATE.container_global
|
|
113
|
+
or self.state.throttle_count(SURFACE, self._source(address), w) >= RATE.per_source
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
def count(self, address: str | None, *, refused: bool, forged: bool = False) -> None:
|
|
117
|
+
"""One counted attempt: a `401` or a forged redemption the door admitted, or an attempt
|
|
118
|
+
refused while holding."""
|
|
119
|
+
w = str(self._window())
|
|
120
|
+
source = self._source(address)
|
|
121
|
+
for bucket in (GLOBAL, source):
|
|
122
|
+
self.state.throttle_incr(SURFACE, bucket, w)
|
|
123
|
+
if refused:
|
|
124
|
+
self.state.throttle_incr(SURFACE, bucket + _REFUSED, w)
|
|
125
|
+
if not refused:
|
|
126
|
+
self.state.throttle_incr(SURFACE, GLOBAL + (_FORGED if forged else _ADMITTED_401), w)
|
|
127
|
+
|
|
128
|
+
def token_holds(self, token_id: str) -> bool:
|
|
129
|
+
"""Whether the bucket of the token a verified descriptor names holds (§6: read between
|
|
130
|
+
checks 2 and 3)."""
|
|
131
|
+
return self.state.throttle_count(
|
|
132
|
+
SURFACE, self._token(token_id), str(self._window())) >= PER_TOKEN
|
|
133
|
+
|
|
134
|
+
def count_token(self, token_id: str, *, refused: bool) -> None:
|
|
135
|
+
"""A verified redemption refused at check 3 or later, or refused while its token's bucket
|
|
136
|
+
holds: the token's own bucket, never the two outer ones."""
|
|
137
|
+
w, bucket = str(self._window()), self._token(token_id)
|
|
138
|
+
self.state.throttle_incr(SURFACE, bucket, w)
|
|
139
|
+
if refused:
|
|
140
|
+
self.state.throttle_incr(SURFACE, bucket + _REFUSED, w)
|
|
141
|
+
|
|
142
|
+
# -- per window -------------------------------------------------------------------------------
|
|
143
|
+
def close(self) -> None:
|
|
144
|
+
"""Append the releases and the tally of every closed window not yet closed, however long
|
|
145
|
+
ago it closed, then forget the counters of windows closed more than `KEEP_WINDOWS` ago.
|
|
146
|
+
Safe from any process at any time: one claim per window, so each appends once."""
|
|
147
|
+
current = self._window()
|
|
148
|
+
for key in self.state.throttle_windows(SURFACE):
|
|
149
|
+
try:
|
|
150
|
+
w = int(key)
|
|
151
|
+
except ValueError:
|
|
152
|
+
continue
|
|
153
|
+
if w >= current:
|
|
154
|
+
continue
|
|
155
|
+
if not self.state.throttle_count(SURFACE, _CLOSED, key):
|
|
156
|
+
with self._atomic():
|
|
157
|
+
# The claim and the entries land together: a failed append rolls the claim
|
|
158
|
+
# back, and the next pass closes the window again (a6 on #288).
|
|
159
|
+
if self.state.throttle_incr(SURFACE, _CLOSED, key) == 1:
|
|
160
|
+
self._close(w)
|
|
161
|
+
if w < current - KEEP_WINDOWS:
|
|
162
|
+
self.state.throttle_forget(SURFACE, key)
|
|
163
|
+
|
|
164
|
+
def _close(self, w: int) -> None:
|
|
165
|
+
counts = dict(self.state.throttle_buckets(SURFACE, str(w)))
|
|
166
|
+
for bucket, total in sorted(counts.items()):
|
|
167
|
+
if "!" in bucket:
|
|
168
|
+
continue
|
|
169
|
+
rate = (RATE.container_global if bucket == GLOBAL
|
|
170
|
+
else PER_TOKEN if bucket.startswith("t:") else RATE.per_source)
|
|
171
|
+
if total >= rate:
|
|
172
|
+
self.ledger.append(
|
|
173
|
+
"authz.release",
|
|
174
|
+
actor=SURFACE,
|
|
175
|
+
principal="none",
|
|
176
|
+
surface=SURFACE,
|
|
177
|
+
refused=counts.get(bucket + _REFUSED, 0),
|
|
178
|
+
window_key=self.window_key(bucket, w),
|
|
179
|
+
)
|
|
180
|
+
admitted = counts.get(GLOBAL + _ADMITTED_401, 0)
|
|
181
|
+
forged = counts.get(GLOBAL + _FORGED, 0)
|
|
182
|
+
if admitted or forged:
|
|
183
|
+
self.ledger.append(
|
|
184
|
+
"rest.tally",
|
|
185
|
+
actor=SURFACE,
|
|
186
|
+
principal="none",
|
|
187
|
+
unauthorized=admitted,
|
|
188
|
+
forged=forged,
|
|
189
|
+
window_key=self.window_key(GLOBAL, w),
|
|
190
|
+
)
|
egzos/auth.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""
|
|
4
|
+
Principals and tokens, skeleton edition (v0.4 §5, v0.3 §5). Bearer tokens cannot prove a human;
|
|
5
|
+
tokens carry `principal: interactive | client`. Human-only acts demand the interactive principal
|
|
6
|
+
AND the step-up tap (`egzos.authz.presence`): the token says who may act, the tap that a person
|
|
7
|
+
is present and decided.
|
|
8
|
+
|
|
9
|
+
The OS keychain is stood in for by a mode-0600 file under the container home. Machine clients
|
|
10
|
+
never touch it; they receive their own client tokens.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import contextlib
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import secrets
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from egzos._ids import ulid
|
|
22
|
+
from egzos.authz.values import digest as _hash
|
|
23
|
+
from egzos.authz.values import same
|
|
24
|
+
from egzos.backends.base import Backend
|
|
25
|
+
from egzos.ledger import Ledger
|
|
26
|
+
from egzos.model import ROLE_BUNDLES, TOKEN_PRINCIPALS, Token, now_iso
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AuthError(Exception):
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
PREFIX = "egz_"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def new_secret(token_id: str) -> str:
|
|
37
|
+
"""The bearer value: `egz_<id>_<256 random bits>`. The id half finds the record; only the
|
|
38
|
+
sha256 of the whole value is stored, so the database and the audit chain never hold it."""
|
|
39
|
+
return f"{PREFIX}{token_id}_{secrets.token_urlsafe(32)}"
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def token_id_of(value: str) -> str | None:
|
|
43
|
+
"""The public id inside a bearer value, or None when the value is not one."""
|
|
44
|
+
if not value.startswith(PREFIX) or "\0" in value: # no id holds U+0000 (storage.md §3.7)
|
|
45
|
+
return None
|
|
46
|
+
rest = value[len(PREFIX):]
|
|
47
|
+
tid, sep, _ = rest.partition("_")
|
|
48
|
+
return tid if sep and len(tid) == 26 else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def home_secret(path: Path, size: int = 32) -> bytes:
|
|
52
|
+
"""A per-container secret in the home (the throttle's, the grant key): what the file holds,
|
|
53
|
+
created at first need as `size` bytes from `secrets`, 0600. It is written whole to a private
|
|
54
|
+
file and linked into place, first writer wins, so no reader ever sees half a key."""
|
|
55
|
+
try:
|
|
56
|
+
return path.read_bytes()
|
|
57
|
+
except FileNotFoundError:
|
|
58
|
+
pass
|
|
59
|
+
tmp = path.with_name(f".{path.name}.{secrets.token_hex(8)}")
|
|
60
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
61
|
+
try:
|
|
62
|
+
with os.fdopen(fd, "wb") as fh:
|
|
63
|
+
fh.write(secrets.token_bytes(size))
|
|
64
|
+
fh.flush()
|
|
65
|
+
os.fsync(fh.fileno())
|
|
66
|
+
with contextlib.suppress(FileExistsError):
|
|
67
|
+
os.link(tmp, path)
|
|
68
|
+
finally:
|
|
69
|
+
with contextlib.suppress(FileNotFoundError):
|
|
70
|
+
os.unlink(tmp)
|
|
71
|
+
return path.read_bytes()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Auth:
|
|
75
|
+
def __init__(self, home: Path, backend: Backend, ledger: Ledger):
|
|
76
|
+
self.home = Path(home)
|
|
77
|
+
self.backend = backend
|
|
78
|
+
self.ledger = ledger
|
|
79
|
+
self.keychain = self.home / "keychain.json"
|
|
80
|
+
|
|
81
|
+
def mint(
|
|
82
|
+
self,
|
|
83
|
+
*,
|
|
84
|
+
principal: str,
|
|
85
|
+
owner: str,
|
|
86
|
+
client: str,
|
|
87
|
+
role: str,
|
|
88
|
+
scopes: list[str],
|
|
89
|
+
actor: str,
|
|
90
|
+
by_principal: str,
|
|
91
|
+
) -> Token:
|
|
92
|
+
if by_principal != "interactive":
|
|
93
|
+
# Minting is the owner's act: a client principal never widens itself (or anyone).
|
|
94
|
+
raise AuthError("minting a token is the owner's act")
|
|
95
|
+
if role not in ROLE_BUNDLES:
|
|
96
|
+
raise AuthError(f"unknown role {role!r}")
|
|
97
|
+
if principal not in TOKEN_PRINCIPALS:
|
|
98
|
+
# `none` is an audit-only principal (events.md §2): no token is ever minted for it.
|
|
99
|
+
raise AuthError(f"unknown token principal {principal!r}")
|
|
100
|
+
token = Token(
|
|
101
|
+
id=ulid(),
|
|
102
|
+
principal=principal,
|
|
103
|
+
owner=owner,
|
|
104
|
+
client=client,
|
|
105
|
+
capabilities=sorted(ROLE_BUNDLES[role]),
|
|
106
|
+
scopes=scopes,
|
|
107
|
+
)
|
|
108
|
+
secret = new_secret(token.id)
|
|
109
|
+
token.secret_hash = _hash(secret)
|
|
110
|
+
with self.backend.atomic(): # the token and its entry, together (GHSA-2478-6jv5-83ff)
|
|
111
|
+
self.backend.put_token(token)
|
|
112
|
+
self.ledger.append(
|
|
113
|
+
"token.mint",
|
|
114
|
+
actor=actor,
|
|
115
|
+
principal=by_principal,
|
|
116
|
+
subject=token.id,
|
|
117
|
+
token_principal=principal,
|
|
118
|
+
client=client,
|
|
119
|
+
role=role,
|
|
120
|
+
scopes=scopes,
|
|
121
|
+
)
|
|
122
|
+
token.secret = secret
|
|
123
|
+
return token
|
|
124
|
+
|
|
125
|
+
def revoke(self, token_id: str, *, actor: str, principal: str) -> bool:
|
|
126
|
+
"""`token rm`. `True` when the token is revoked, whether by this call or before it; an
|
|
127
|
+
already-revoked token is not revoked twice and gets no second `token.revoke`
|
|
128
|
+
(authorization-server.md §9.2, as `authz.revoke`). The event carries no `family_id`:
|
|
129
|
+
`Backend` has no family read yet (#242). The read, the check, the write and the entry are
|
|
130
|
+
one `atomic()` block, which holds the write lock from before the read (storage.md §3.6;
|
|
131
|
+
GHSA-m955-fr24-frwq)."""
|
|
132
|
+
with self.backend.atomic():
|
|
133
|
+
token = self.backend.get_token(token_id)
|
|
134
|
+
if not token:
|
|
135
|
+
return False
|
|
136
|
+
if token.revoked:
|
|
137
|
+
return True
|
|
138
|
+
token.revoked = True
|
|
139
|
+
self.backend.put_token(token)
|
|
140
|
+
self.ledger.append("token.revoke", actor=actor, principal=principal, subject=token.id)
|
|
141
|
+
return True
|
|
142
|
+
|
|
143
|
+
# -- keychain stand-in -------------------------------------------------------------
|
|
144
|
+
def keychain_store(self, token: Token) -> None:
|
|
145
|
+
if not token.secret:
|
|
146
|
+
raise AuthError("only a freshly minted token can be stored; its value is not kept")
|
|
147
|
+
fd = os.open(self.keychain, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
148
|
+
with os.fdopen(fd, "w") as fh:
|
|
149
|
+
fh.write(json.dumps({"token": token.secret, "stored_at": now_iso()}))
|
|
150
|
+
os.chmod(self.keychain, 0o600)
|
|
151
|
+
|
|
152
|
+
def interactive_token(self) -> Token | None:
|
|
153
|
+
"""The owner's interactive token: `EGZOS_TOKEN` when set, else the keychain `init` wrote."""
|
|
154
|
+
env = os.environ.get("EGZOS_TOKEN")
|
|
155
|
+
if env:
|
|
156
|
+
return self.use(env)
|
|
157
|
+
if not self.keychain.exists():
|
|
158
|
+
return None
|
|
159
|
+
return self.use(json.loads(self.keychain.read_text())["token"])
|
|
160
|
+
|
|
161
|
+
def use(self, value: str) -> Token | None:
|
|
162
|
+
"""The token a bearer value proves, or None. Every failure looks the same to the caller.
|
|
163
|
+
The read, the check and the `last_used` write are one `atomic()` block, which holds the
|
|
164
|
+
write lock from before the read (storage.md §3.6; GHSA-m955-fr24-frwq)."""
|
|
165
|
+
tid = token_id_of(value or "")
|
|
166
|
+
if not tid:
|
|
167
|
+
return None
|
|
168
|
+
with self.backend.atomic():
|
|
169
|
+
token = self.backend.get_token(tid)
|
|
170
|
+
if not token or not token.live or not token.secret_hash:
|
|
171
|
+
return None
|
|
172
|
+
if not same(_hash(value), token.secret_hash):
|
|
173
|
+
return None
|
|
174
|
+
token.last_used = now_iso()
|
|
175
|
+
self.backend.put_token(token)
|
|
176
|
+
return token
|
egzos/authz/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Copyright 2026 Ali Sasanian
|
|
2
|
+
# SPDX-License-Identifier: LicenseRef-PolyForm-Strict-1.0.0
|
|
3
|
+
"""What is left here once the authorization server is retired (`identity.md` §9): the MVP step-up
|
|
4
|
+
tap (`presence`) and the two value helpers it shares with `auth.py` (`values`). The tap goes when
|
|
5
|
+
the confirm (`identity.md` §5) lands; until then it is what runs, a stated and dated gap."""
|