nomosprotocol 0.1.0__tar.gz
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.
- nomosprotocol-0.1.0/PKG-INFO +121 -0
- nomosprotocol-0.1.0/README.md +101 -0
- nomosprotocol-0.1.0/nomosprotocol/__init__.py +36 -0
- nomosprotocol-0.1.0/nomosprotocol/accept.py +312 -0
- nomosprotocol-0.1.0/nomosprotocol/act.py +462 -0
- nomosprotocol-0.1.0/nomosprotocol/carrier.py +178 -0
- nomosprotocol-0.1.0/nomosprotocol/chain.py +421 -0
- nomosprotocol-0.1.0/nomosprotocol/issuer.py +73 -0
- nomosprotocol-0.1.0/nomosprotocol/jcs.py +46 -0
- nomosprotocol-0.1.0/nomosprotocol/statements.py +191 -0
- nomosprotocol-0.1.0/nomosprotocol/suites.py +252 -0
- nomosprotocol-0.1.0/nomosprotocol/witness.py +72 -0
- nomosprotocol-0.1.0/nomosprotocol.egg-info/PKG-INFO +121 -0
- nomosprotocol-0.1.0/nomosprotocol.egg-info/SOURCES.txt +18 -0
- nomosprotocol-0.1.0/nomosprotocol.egg-info/dependency_links.txt +1 -0
- nomosprotocol-0.1.0/nomosprotocol.egg-info/requires.txt +5 -0
- nomosprotocol-0.1.0/nomosprotocol.egg-info/top_level.txt +1 -0
- nomosprotocol-0.1.0/pyproject.toml +25 -0
- nomosprotocol-0.1.0/setup.cfg +4 -0
- nomosprotocol-0.1.0/tests/test_sdk.py +169 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: nomosprotocol
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: NOMOS for Python: the reference verifiers for NOMOS-SPEC-007, -008 and -010, and accept(), act() and witness() for NOMOS-SPEC-009. Verify an Act, commit it exactly once, carry one, or sign the facts it needs.
|
|
5
|
+
Author-email: NOMOS Protocol <hello@nomosprotocol.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.computableauthority.com
|
|
8
|
+
Project-URL: Specification, https://github.com/nomos-spec/spec
|
|
9
|
+
Keywords: nomos,computable-authority,agents,authorization,verifier,ed25519,es256,webauthn
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Topic :: Security :: Cryptography
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
Requires-Dist: cryptography>=43
|
|
17
|
+
Provides-Extra: postgres
|
|
18
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == "postgres"
|
|
19
|
+
Requires-Dist: psycopg-pool>=3.2; extra == "postgres"
|
|
20
|
+
|
|
21
|
+
# nomosprotocol
|
|
22
|
+
|
|
23
|
+
NOMOS for Python. It includes the reference verifiers of the NOMOS specifications and the developer
|
|
24
|
+
layer built on them:
|
|
25
|
+
- `accept()`, for the system that makes a change;
|
|
26
|
+
- `act()`, for the agent that carries one;
|
|
27
|
+
- `witness()` and `issuer()`, for the systems that sign the facts and publish the rules.
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install nomosprotocol # cryptography is the only dependency
|
|
31
|
+
pip install "nomosprotocol[postgres]" # adds psycopg, for postgres_store()
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
Python 3.9+. The verifiers in this package are the same code the specification's published test
|
|
35
|
+
vectors are generated and checked with, so there is no second Python implementation to drift from
|
|
36
|
+
the reference.
|
|
37
|
+
|
|
38
|
+
## Be the system that makes the change
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import nomosprotocol as nomos
|
|
42
|
+
|
|
43
|
+
rp = nomos.accept(
|
|
44
|
+
relying_party_id="orders.acme.example",
|
|
45
|
+
root=ACME_ROOT_PEM, # the root you pin; there is no default
|
|
46
|
+
act_endpoint="https://orders.acme.example/nomos/acts",
|
|
47
|
+
authorities=[{"artifact_id": "acme-purchasing", "issuer": "https://policy.acme.example",
|
|
48
|
+
"actions": ["purchase"], "currency_policy": "record", "in_force_seal_hash": POLICY_SEAL_HASH}],
|
|
49
|
+
local_facts=lambda act, tx=None: {"vendor_blocked": is_blocked(act["action"]["params"]["vendor"])},
|
|
50
|
+
commit=lambda action, tx, act_id: create_order(tx, action), # your code, on the same transaction
|
|
51
|
+
store=nomos.postgres_store(pool.connection), # a psycopg_pool ConnectionPool
|
|
52
|
+
)
|
|
53
|
+
app = rp.wsgi # Flask, Django, gunicorn: any WSGI server
|
|
54
|
+
app = rp.asgi # FastAPI/Starlette mount, uvicorn: any ASGI server
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Every Act is verified locally (NOMOS-SPEC-008). If it is authorized, `accept()` does four things
|
|
58
|
+
in one transaction: records the nonce, re-reads your facts, hands `commit` exactly the verified
|
|
59
|
+
action, and stores the receipt with the Act.
|
|
60
|
+
|
|
61
|
+
| Verdict | Status |
|
|
62
|
+
|---|---|
|
|
63
|
+
| AUTHORIZED, committed | 201 |
|
|
64
|
+
| ESCALATED | 202 |
|
|
65
|
+
| INCOMPLETE | 422 |
|
|
66
|
+
| DENIED | 403 |
|
|
67
|
+
| REPLAYED | 409, with the original receipt |
|
|
68
|
+
| Any other refusal | 400 |
|
|
69
|
+
| Revocations unavailable | 503 |
|
|
70
|
+
|
|
71
|
+
If any number of copies of one Act arrive at once, exactly one commits and the rest get its
|
|
72
|
+
receipt. If revocation status can't be established, nothing commits.
|
|
73
|
+
|
|
74
|
+
## Be the agent
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
r = nomos.act(to="http://localhost:4747",
|
|
78
|
+
action={"type": "purchase", "subject": "DEPT-17", "params": {"amount": 500, "vendor": "paperco"}})
|
|
79
|
+
print(r["status"]) # committed | escalated | incomplete | denied | refused | replayed
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`act()` handles the whole round trip:
|
|
83
|
+
- discovers the system;
|
|
84
|
+
- fetches the rules it acts under;
|
|
85
|
+
- collects signed facts from the witnesses;
|
|
86
|
+
- presents exactly the certificates the Act relies on;
|
|
87
|
+
- submits;
|
|
88
|
+
- if a person must approve, waits for the approval and resubmits.
|
|
89
|
+
|
|
90
|
+
It uses only the standard library. To try it, run `npx @nomosprotocol/cli dev`.
|
|
91
|
+
|
|
92
|
+
## The other roles
|
|
93
|
+
|
|
94
|
+
- `witness(origin=…, witness_id=…, signer=…, claims={"budget_remaining": lambda about: …}, key_certs=…)` signs one fact about one subject on request.
|
|
95
|
+
- `issuer(origin=…, issuer_id=…, signer=…, authorities=[policy], key_certs=…, revocations=…)` publishes the sealed rules, the version in force, the certificate pool and the revocation list.
|
|
96
|
+
|
|
97
|
+
Keys are `Signer`s: anything with `kid`, `public_key_pem`, `algorithm` and `sign(payload) -> str`.
|
|
98
|
+
`local_signer(pem)` and `generate_signer()` are for development; for production, wrap your KMS.
|
|
99
|
+
|
|
100
|
+
## Verify directly
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
from nomosprotocol import verify_act, chain
|
|
104
|
+
v = verify_act(act, relying_party_id="…", root_pem=ROOT, now=datetime.now(timezone.utc),
|
|
105
|
+
seen_nonces=set(), currency_policy="record", in_force={"acme-purchasing": SEAL_HASH})
|
|
106
|
+
chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## Conformance
|
|
110
|
+
|
|
111
|
+
This package is checked against:
|
|
112
|
+
- every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.9, rev. 1.10 revocation sources), NOMOS-SPEC-008
|
|
113
|
+
0.6.0 and NOMOS-SPEC-010 0.2.0;
|
|
114
|
+
- the NOMOS-SPEC-009 selection vectors;
|
|
115
|
+
- the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
|
|
116
|
+
(`python/tests/conformance_rp.py`).
|
|
117
|
+
|
|
118
|
+
`act()` also interoperates with the JavaScript sandbox, escalation and approval included
|
|
119
|
+
(`python/tests/interop_sandbox.py`).
|
|
120
|
+
|
|
121
|
+
MIT licensed.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# nomosprotocol
|
|
2
|
+
|
|
3
|
+
NOMOS for Python. It includes the reference verifiers of the NOMOS specifications and the developer
|
|
4
|
+
layer built on them:
|
|
5
|
+
- `accept()`, for the system that makes a change;
|
|
6
|
+
- `act()`, for the agent that carries one;
|
|
7
|
+
- `witness()` and `issuer()`, for the systems that sign the facts and publish the rules.
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
pip install nomosprotocol # cryptography is the only dependency
|
|
11
|
+
pip install "nomosprotocol[postgres]" # adds psycopg, for postgres_store()
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Python 3.9+. The verifiers in this package are the same code the specification's published test
|
|
15
|
+
vectors are generated and checked with, so there is no second Python implementation to drift from
|
|
16
|
+
the reference.
|
|
17
|
+
|
|
18
|
+
## Be the system that makes the change
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import nomosprotocol as nomos
|
|
22
|
+
|
|
23
|
+
rp = nomos.accept(
|
|
24
|
+
relying_party_id="orders.acme.example",
|
|
25
|
+
root=ACME_ROOT_PEM, # the root you pin; there is no default
|
|
26
|
+
act_endpoint="https://orders.acme.example/nomos/acts",
|
|
27
|
+
authorities=[{"artifact_id": "acme-purchasing", "issuer": "https://policy.acme.example",
|
|
28
|
+
"actions": ["purchase"], "currency_policy": "record", "in_force_seal_hash": POLICY_SEAL_HASH}],
|
|
29
|
+
local_facts=lambda act, tx=None: {"vendor_blocked": is_blocked(act["action"]["params"]["vendor"])},
|
|
30
|
+
commit=lambda action, tx, act_id: create_order(tx, action), # your code, on the same transaction
|
|
31
|
+
store=nomos.postgres_store(pool.connection), # a psycopg_pool ConnectionPool
|
|
32
|
+
)
|
|
33
|
+
app = rp.wsgi # Flask, Django, gunicorn: any WSGI server
|
|
34
|
+
app = rp.asgi # FastAPI/Starlette mount, uvicorn: any ASGI server
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Every Act is verified locally (NOMOS-SPEC-008). If it is authorized, `accept()` does four things
|
|
38
|
+
in one transaction: records the nonce, re-reads your facts, hands `commit` exactly the verified
|
|
39
|
+
action, and stores the receipt with the Act.
|
|
40
|
+
|
|
41
|
+
| Verdict | Status |
|
|
42
|
+
|---|---|
|
|
43
|
+
| AUTHORIZED, committed | 201 |
|
|
44
|
+
| ESCALATED | 202 |
|
|
45
|
+
| INCOMPLETE | 422 |
|
|
46
|
+
| DENIED | 403 |
|
|
47
|
+
| REPLAYED | 409, with the original receipt |
|
|
48
|
+
| Any other refusal | 400 |
|
|
49
|
+
| Revocations unavailable | 503 |
|
|
50
|
+
|
|
51
|
+
If any number of copies of one Act arrive at once, exactly one commits and the rest get its
|
|
52
|
+
receipt. If revocation status can't be established, nothing commits.
|
|
53
|
+
|
|
54
|
+
## Be the agent
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
r = nomos.act(to="http://localhost:4747",
|
|
58
|
+
action={"type": "purchase", "subject": "DEPT-17", "params": {"amount": 500, "vendor": "paperco"}})
|
|
59
|
+
print(r["status"]) # committed | escalated | incomplete | denied | refused | replayed
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`act()` handles the whole round trip:
|
|
63
|
+
- discovers the system;
|
|
64
|
+
- fetches the rules it acts under;
|
|
65
|
+
- collects signed facts from the witnesses;
|
|
66
|
+
- presents exactly the certificates the Act relies on;
|
|
67
|
+
- submits;
|
|
68
|
+
- if a person must approve, waits for the approval and resubmits.
|
|
69
|
+
|
|
70
|
+
It uses only the standard library. To try it, run `npx @nomosprotocol/cli dev`.
|
|
71
|
+
|
|
72
|
+
## The other roles
|
|
73
|
+
|
|
74
|
+
- `witness(origin=…, witness_id=…, signer=…, claims={"budget_remaining": lambda about: …}, key_certs=…)` signs one fact about one subject on request.
|
|
75
|
+
- `issuer(origin=…, issuer_id=…, signer=…, authorities=[policy], key_certs=…, revocations=…)` publishes the sealed rules, the version in force, the certificate pool and the revocation list.
|
|
76
|
+
|
|
77
|
+
Keys are `Signer`s: anything with `kid`, `public_key_pem`, `algorithm` and `sign(payload) -> str`.
|
|
78
|
+
`local_signer(pem)` and `generate_signer()` are for development; for production, wrap your KMS.
|
|
79
|
+
|
|
80
|
+
## Verify directly
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
from nomosprotocol import verify_act, chain
|
|
84
|
+
v = verify_act(act, relying_party_id="…", root_pem=ROOT, now=datetime.now(timezone.utc),
|
|
85
|
+
seen_nonces=set(), currency_policy="record", in_force={"acme-purchasing": SEAL_HASH})
|
|
86
|
+
chain.verify_revocation_list(lst, ROOT, now) # NOMOS-SPEC-007 rev. 1.10
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Conformance
|
|
90
|
+
|
|
91
|
+
This package is checked against:
|
|
92
|
+
- every vector of NOMOS-SPEC-007 (1.7.0, rev. 1.9, rev. 1.10 revocation sources), NOMOS-SPEC-008
|
|
93
|
+
0.6.0 and NOMOS-SPEC-010 0.2.0;
|
|
94
|
+
- the NOMOS-SPEC-009 selection vectors;
|
|
95
|
+
- the NOMOS-SPEC-009 HTTP runner, 17 of 17, with `accept()` behind it
|
|
96
|
+
(`python/tests/conformance_rp.py`).
|
|
97
|
+
|
|
98
|
+
`act()` also interoperates with the JavaScript sandbox, escalation and approval included
|
|
99
|
+
(`python/tests/interop_sandbox.py`).
|
|
100
|
+
|
|
101
|
+
MIT licensed.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""nomosprotocol: NOMOS for Python.
|
|
2
|
+
|
|
3
|
+
The reference implementation of the NOMOS specifications and the developer layer on top of it.
|
|
4
|
+
The verifiers here are the same code the specification's published vectors are generated and
|
|
5
|
+
checked with, so there is no second implementation to drift from the reference.
|
|
6
|
+
|
|
7
|
+
verify_act(act, ...) NOMOS-SPEC-008 0.6.0: may this exact change be committed here?
|
|
8
|
+
chain.resolve(...) NOMOS-SPEC-007 rev. 1.9: resolve a key to a pinned root, for a purpose
|
|
9
|
+
chain.verify_revocation_list(...) NOMOS-SPEC-007 rev. 1.10: which revocations count, and since when
|
|
10
|
+
accept(...) be the relying party: verify, commit exactly once, receipt (NOMOS-SPEC-009)
|
|
11
|
+
act(...) be the carrier: discover, gather testimony, submit, get approval
|
|
12
|
+
witness(...) be a witness: sign one fact about one subject on request
|
|
13
|
+
issuer(...) publish authorities, the version in force, certificates and revocations
|
|
14
|
+
local_signer, generate_signer keys in this process (development); pass your own Signer for a KMS
|
|
15
|
+
|
|
16
|
+
Modules: jcs (RFC 8785), suites (NOMOS-SPEC-010), chain (NOMOS-SPEC-007), act (NOMOS-SPEC-008),
|
|
17
|
+
statements, accept, carrier, witness, issuer.
|
|
18
|
+
"""
|
|
19
|
+
from .act import verify_act, evaluate, binding_digest
|
|
20
|
+
from .chain import resolve, verify_revocation_list, fingerprint
|
|
21
|
+
from .jcs import jcs, sha256_hex
|
|
22
|
+
from .statements import (
|
|
23
|
+
Signer, LocalSigner, local_signer, generate_signer, seeded_signer,
|
|
24
|
+
certify, seal, sign_testimony, sign_consent, sign_in_force, sign_revocation, sign_revocation_list,
|
|
25
|
+
build_act, presented_certificates, relied_kids, MAX_PRESENTED,
|
|
26
|
+
)
|
|
27
|
+
from .accept import accept, RelyingParty, MemoryStore, postgres_store, RevocationUnavailable, status_for, ACT_MEDIA_TYPE
|
|
28
|
+
from .carrier import act, NomosActError, fetch_document
|
|
29
|
+
from .witness import witness, Witness
|
|
30
|
+
from .issuer import issuer, Issuer
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
SPECIFICATIONS = {
|
|
34
|
+
"NOMOS-SPEC-001": "2.2.0 + amendment 2.3.0", "NOMOS-SPEC-007": "rev. 1.10.0", "NOMOS-SPEC-008": "0.6.0",
|
|
35
|
+
"NOMOS-SPEC-009": "0.2.0", "NOMOS-SPEC-010": "0.2.0",
|
|
36
|
+
}
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
"""accept(): the relying party, the system that makes the change.
|
|
2
|
+
|
|
3
|
+
rp = accept(relying_party_id="orders.acme.example", root=ROOT_PEM, act_endpoint="https://orders.acme.example/nomos/acts",
|
|
4
|
+
authorities=[{"artifact_id": "acme-purchasing", "issuer": "https://policy.acme.example",
|
|
5
|
+
"actions": ["purchase"], "currency_policy": "record", "in_force_seal_hash": SEAL_HASH}],
|
|
6
|
+
local_facts=lambda act, tx=None: {"vendor_blocked": is_blocked(act["action"]["params"]["vendor"])},
|
|
7
|
+
commit=lambda action, tx, act_id: create_order(tx, action),
|
|
8
|
+
store=postgres_store(pool.connection)) # a psycopg_pool ConnectionPool
|
|
9
|
+
app = rp.wsgi # Flask, Django, any WSGI server
|
|
10
|
+
app = rp.asgi # FastAPI/Starlette mount, any ASGI server
|
|
11
|
+
|
|
12
|
+
For every Act it runs NOMOS-SPEC-008 §6 locally (nomosprotocol.act, the reference verifier) and on
|
|
13
|
+
AUTHORIZED applies §8 in one transaction: record the nonce, re-read its own facts (re-verifying if
|
|
14
|
+
they moved), hand `commit` exactly the verified action, store the receipt and the Act. It answers
|
|
15
|
+
with the NOMOS-SPEC-009 §6.2 statuses and serves its discovery document (§3.1), generated from
|
|
16
|
+
this same configuration.
|
|
17
|
+
|
|
18
|
+
The same behaviour as @nomosprotocol/sdk's accept(), including: a duplicate that loses the race for
|
|
19
|
+
the nonce reads the winner's receipt only after its own transaction has ended (so a burst of
|
|
20
|
+
duplicates cannot exhaust a connection pool), and revocations that cannot be read are refused
|
|
21
|
+
with 503, never treated as "nothing revoked" (NOMOS-SPEC-007 rev. 1.10 §5.6).
|
|
22
|
+
"""
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import copy
|
|
26
|
+
import json
|
|
27
|
+
import threading
|
|
28
|
+
from contextlib import contextmanager
|
|
29
|
+
from typing import Any, Callable, Dict, Iterator, List, Optional, Protocol, Tuple
|
|
30
|
+
|
|
31
|
+
from .act import verify_act
|
|
32
|
+
from .chain import ts
|
|
33
|
+
from .statements import iso, now_utc
|
|
34
|
+
from . import suites
|
|
35
|
+
|
|
36
|
+
ACT_MEDIA_TYPE = "application/nomos-act+json"
|
|
37
|
+
STATUS = {"AUTHORIZED": 201, "ESCALATED": 202, "INCOMPLETE": 422, "DENIED": 403, "REPLAYED": 409}
|
|
38
|
+
WELL_KNOWN = "/.well-known/nomos-relying-party"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def status_for(decision: str) -> int:
|
|
42
|
+
return STATUS.get(decision, 400)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RevocationUnavailable(Exception):
|
|
46
|
+
"""Raise from `revocations()` when current revocation status cannot be established."""
|
|
47
|
+
def __init__(self, message: str, retry_after_seconds: int = 60):
|
|
48
|
+
super().__init__(message); self.retry_after_seconds = retry_after_seconds
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Transaction(Protocol):
|
|
52
|
+
tx: Any
|
|
53
|
+
def claim_nonce(self, nonce: str) -> bool: ...
|
|
54
|
+
def put_receipt(self, nonce: str, receipt: dict, act: dict) -> None: ...
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class Store(Protocol):
|
|
58
|
+
def has_nonce(self, nonce: str) -> bool: ...
|
|
59
|
+
def receipt_for(self, nonce: str) -> Optional[dict]: ...
|
|
60
|
+
def transaction(self): ... # a context manager yielding a Transaction; rolls back on exception
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class MemoryStore:
|
|
64
|
+
"""Nonces and receipts in memory, one transaction at a time. Lost on restart, single process:
|
|
65
|
+
development and tests only. Use postgres_store() in production."""
|
|
66
|
+
def __init__(self):
|
|
67
|
+
self._lock = threading.Lock(); self.nonces: set = set(); self.receipts: Dict[str, dict] = {}; self.acts: Dict[str, dict] = {}
|
|
68
|
+
|
|
69
|
+
def has_nonce(self, nonce): return nonce in self.nonces
|
|
70
|
+
def receipt_for(self, nonce): return self.receipts.get(nonce)
|
|
71
|
+
|
|
72
|
+
@contextmanager
|
|
73
|
+
def transaction(self):
|
|
74
|
+
with self._lock:
|
|
75
|
+
staged, receipts, acts = set(), {}, {}
|
|
76
|
+
class T:
|
|
77
|
+
tx = None
|
|
78
|
+
def claim_nonce(s, n):
|
|
79
|
+
if n in self.nonces or n in staged: return False
|
|
80
|
+
staged.add(n); return True
|
|
81
|
+
def put_receipt(s, n, r, a): receipts[n] = r; acts[n] = a
|
|
82
|
+
yield T()
|
|
83
|
+
self.nonces |= staged; self.receipts.update(receipts); self.acts.update(acts) # only if the block completed
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def postgres_store(connection: Callable[[], Any], table: str = "nomos_acts"):
|
|
87
|
+
"""Nonces, receipts and Acts in your own Postgres, in the same transaction as your change.
|
|
88
|
+
|
|
89
|
+
`connection()` returns a context manager that yields a DB-API connection and releases it on
|
|
90
|
+
exit: a psycopg_pool pool's `pool.connection`, or `lambda: psycopg.connect(url)`. This store never
|
|
91
|
+
closes a connection itself, so a pool keeps its connections. `tx` passed to `commit` is that
|
|
92
|
+
connection, so your writes and the nonce commit together. The nonce is the primary key: any
|
|
93
|
+
number of concurrent duplicates commit exactly once."""
|
|
94
|
+
import re
|
|
95
|
+
if not re.match(r"^[a-z_][a-z0-9_]{0,62}$", table): raise ValueError(f'"{table}" is not a plain lower-case table name')
|
|
96
|
+
schema = f"""CREATE TABLE IF NOT EXISTS {table} (
|
|
97
|
+
nonce text PRIMARY KEY, act_id text NOT NULL, receipt json NOT NULL, act json NOT NULL, committed_at timestamptz NOT NULL DEFAULT now())"""
|
|
98
|
+
|
|
99
|
+
class PgStore:
|
|
100
|
+
def migrate(self):
|
|
101
|
+
with connection() as c:
|
|
102
|
+
with c.cursor() as cur: cur.execute(schema)
|
|
103
|
+
c.commit()
|
|
104
|
+
def _one(self, sql, args):
|
|
105
|
+
with connection() as c:
|
|
106
|
+
with c.cursor() as cur: cur.execute(sql, args); row = cur.fetchone()
|
|
107
|
+
c.rollback(); return row
|
|
108
|
+
def has_nonce(self, nonce): return self._one(f"SELECT 1 FROM {table} WHERE nonce = %s", (nonce,)) is not None
|
|
109
|
+
def receipt_for(self, nonce):
|
|
110
|
+
row = self._one(f"SELECT receipt::text FROM {table} WHERE nonce = %s", (nonce,))
|
|
111
|
+
return json.loads(row[0]) if row else None
|
|
112
|
+
@contextmanager
|
|
113
|
+
def transaction(self):
|
|
114
|
+
with connection() as c:
|
|
115
|
+
claimed = {"nonce": None, "done": False}
|
|
116
|
+
class T:
|
|
117
|
+
tx = c
|
|
118
|
+
def claim_nonce(s, n):
|
|
119
|
+
with c.cursor() as cur:
|
|
120
|
+
cur.execute(f"INSERT INTO {table} (nonce, act_id, receipt, act) VALUES (%s, '', '{{}}', '{{}}') ON CONFLICT (nonce) DO NOTHING RETURNING nonce", (n,))
|
|
121
|
+
won = cur.fetchone() is not None
|
|
122
|
+
if won: claimed["nonce"] = n
|
|
123
|
+
return won
|
|
124
|
+
def put_receipt(s, n, r, a):
|
|
125
|
+
if n != claimed["nonce"]: raise RuntimeError("put_receipt for a nonce this transaction did not claim")
|
|
126
|
+
with c.cursor() as cur:
|
|
127
|
+
cur.execute(f"UPDATE {table} SET act_id = %s, receipt = %s::json, act = %s::json WHERE nonce = %s",
|
|
128
|
+
(r["act_id"], json.dumps(r, separators=(",", ":")), json.dumps(a, separators=(",", ":")), n))
|
|
129
|
+
claimed["done"] = True
|
|
130
|
+
try:
|
|
131
|
+
yield T()
|
|
132
|
+
if claimed["nonce"] and not claimed["done"]: raise RuntimeError("the transaction claimed a nonce but stored no receipt")
|
|
133
|
+
c.commit()
|
|
134
|
+
except BaseException:
|
|
135
|
+
c.rollback(); raise
|
|
136
|
+
s = PgStore(); s.schema = schema
|
|
137
|
+
return s
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class _LostRace(Exception): pass
|
|
141
|
+
class _Rollback(Exception):
|
|
142
|
+
def __init__(self, answer): super().__init__("rollback"); self.answer = answer
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
HINTS: Dict[str, Callable[[dict], str]] = {
|
|
146
|
+
"INCOMPLETE": lambda v: f"Missing facts that could change the outcome: {', '.join(v.get('open_facts') or [])}. Bring them as testimony from a witness certified for each claim, or as the channel the authority declares.",
|
|
147
|
+
"ESCALATED": lambda v: f"Needs {v.get('consents_required')} approval(s) from role {v.get('role')}. Request consent over act_digest {v.get('act_digest')} and resubmit this same Act before {v.get('retry_until')}.",
|
|
148
|
+
"DENIED": lambda v: f"Rule {v.get('rule') or '(default)'} refuses this action. No approval can change a denial.",
|
|
149
|
+
"WRONG_RELYING_PARTY": lambda v: "The Act is addressed to another system. Build it with this relying_party_id.",
|
|
150
|
+
"EXPIRED": lambda v: "The Act's window has passed. Build a new Act.",
|
|
151
|
+
"REPLAYED": lambda v: "This Act was already committed; the original receipt is attached.",
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _answer(verdict: dict, **extra) -> Tuple[int, Dict[str, str], dict]:
|
|
156
|
+
body = {k: v for k, v in verdict.items() if k != "detail"}
|
|
157
|
+
body.update(extra)
|
|
158
|
+
hint = HINTS.get(verdict["decision"])
|
|
159
|
+
if hint: body["hint"] = hint({**verdict, **extra})
|
|
160
|
+
return status_for(verdict["decision"]), {"content-type": "application/json"}, body
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class RelyingParty:
|
|
164
|
+
def __init__(self, *, relying_party_id: str, root: str, authorities: List[dict], commit: Callable[..., Any], act_endpoint: str,
|
|
165
|
+
local_facts: Optional[Callable[..., dict]] = None, store: Optional[Store] = None,
|
|
166
|
+
max_window_seconds: int = 900, max_act_bytes: int = 1024 * 1024,
|
|
167
|
+
revocations: Optional[Callable[[], dict]] = None, mode: str = "enforce",
|
|
168
|
+
on_verdict: Optional[Callable[[dict, dict], None]] = None, document_ttl_seconds: int = 86400,
|
|
169
|
+
now: Callable[[], Any] = now_utc):
|
|
170
|
+
for a in authorities:
|
|
171
|
+
if a.get("currency_policy") not in ("record", "record_or_statement"): raise ValueError(f"{a.get('artifact_id')}: currency_policy must be record or record_or_statement (no default)")
|
|
172
|
+
if a["currency_policy"] == "record" and not a.get("in_force_seal_hash"): raise ValueError(f"{a['artifact_id']}: currency_policy record needs in_force_seal_hash")
|
|
173
|
+
if store is None:
|
|
174
|
+
import warnings
|
|
175
|
+
warnings.warn("nomosprotocol accept(): using the in-memory store. Nonces and receipts are lost on restart. Development only; use postgres_store() in production.")
|
|
176
|
+
self.relying_party_id, self.root, self.authorities, self.commit = relying_party_id, root, authorities, commit
|
|
177
|
+
self.act_endpoint, self.local_facts, self.store = act_endpoint, local_facts, store or MemoryStore()
|
|
178
|
+
self.max_window_seconds, self.max_act_bytes, self.revocations, self.mode = max_window_seconds, max_act_bytes, revocations, mode
|
|
179
|
+
self.on_verdict, self.document_ttl_seconds, self.now = on_verdict, document_ttl_seconds, now
|
|
180
|
+
from urllib.parse import urlparse
|
|
181
|
+
self.endpoint_path = urlparse(act_endpoint).path
|
|
182
|
+
self.root_kid = suites.compute_kid(root)
|
|
183
|
+
|
|
184
|
+
def document(self) -> dict:
|
|
185
|
+
from datetime import timedelta
|
|
186
|
+
return {
|
|
187
|
+
"nomos_document": "relying-party", "version": "1", "relying_party_id": self.relying_party_id, "act_endpoint": self.act_endpoint,
|
|
188
|
+
"roots": [{"kid": self.root_kid, "public_key_pem": self.root}],
|
|
189
|
+
"authorities": [{"artifact_id": a["artifact_id"], **({"issuer": a["issuer"]} if a.get("issuer") else {}), "actions": a["actions"],
|
|
190
|
+
"currency_policy": a["currency_policy"], **({"in_force_seal_hash": a["in_force_seal_hash"]} if a.get("in_force_seal_hash") else {})}
|
|
191
|
+
for a in self.authorities],
|
|
192
|
+
"max_window_seconds": self.max_window_seconds, "max_act_bytes": self.max_act_bytes,
|
|
193
|
+
"consent_suites": ["Ed25519", "ES256", "WebAuthn-ES256"],
|
|
194
|
+
"valid_until": iso(self.now() + timedelta(seconds=self.document_ttl_seconds)),
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
def _verify(self, act, authority, facts, at, seen, rev) -> dict:
|
|
198
|
+
return verify_act(act, relying_party_id=self.relying_party_id, root_pem=self.root, now=at,
|
|
199
|
+
seen_nonces={act["nonce"]} if seen else set(), currency_policy=authority["currency_policy"], local_facts=facts,
|
|
200
|
+
revoked_kids=rev.get("kids"), revoked_certs=rev.get("certs"), revoked_artifacts=rev.get("artifacts"),
|
|
201
|
+
in_force={authority["artifact_id"]: authority["in_force_seal_hash"]} if authority.get("in_force_seal_hash") else {},
|
|
202
|
+
max_window_seconds=self.max_window_seconds)
|
|
203
|
+
|
|
204
|
+
def handle(self, method: str, content_type: str, body: bytes) -> Tuple[int, Dict[str, str], dict]:
|
|
205
|
+
"""The framework-neutral core: one Act in, one NOMOS-SPEC-009 §6.2 answer out."""
|
|
206
|
+
if method.upper() != "POST": return 405, {"allow": "POST", "content-type": "application/json"}, {"error": "POST an Act here."}
|
|
207
|
+
if (content_type or "").split(";")[0].strip().lower() != ACT_MEDIA_TYPE:
|
|
208
|
+
return 415, {"content-type": "application/json"}, {"error": f"Content-Type must be {ACT_MEDIA_TYPE}."}
|
|
209
|
+
if len(body) > self.max_act_bytes: return 413, {"content-type": "application/json"}, {"error": f"The Act is larger than {self.max_act_bytes} bytes."}
|
|
210
|
+
try: act = json.loads(body.decode("utf-8"))
|
|
211
|
+
except (ValueError, UnicodeDecodeError): return _answer({"decision": "MALFORMED", "reason_code": "bad_json"})
|
|
212
|
+
artifact_id = (((act or {}).get("authority") or {}).get("artifact") or {}).get("meta", {}).get("artifact_id") if isinstance(act, dict) else None
|
|
213
|
+
authority = next((a for a in self.authorities if a["artifact_id"] == artifact_id), None)
|
|
214
|
+
if not authority: return _answer({"decision": "NOT_ACCEPTED", "reason_code": "authority_not_accepted", "artifact_id": artifact_id})
|
|
215
|
+
if (act.get("action") or {}).get("type") not in authority["actions"]:
|
|
216
|
+
return _answer({"decision": "NOT_ACCEPTED", "reason_code": "action_not_accepted", "action_type": (act.get("action") or {}).get("type")})
|
|
217
|
+
try: rev = (self.revocations() if self.revocations else None) or {}
|
|
218
|
+
except Exception as e:
|
|
219
|
+
retry = e.retry_after_seconds if isinstance(e, RevocationUnavailable) else 60
|
|
220
|
+
return 503, {"content-type": "application/json", "retry-after": str(retry)}, {
|
|
221
|
+
"error": "Revocation status is not current, so nothing is committed. Resubmit this same Act later.", "detail": str(e), "retry_after": retry}
|
|
222
|
+
at = self.now()
|
|
223
|
+
facts = self.local_facts(act) if self.local_facts else {}
|
|
224
|
+
verdict = self._verify(act, authority, facts, at, self.store.has_nonce(act["nonce"]), rev)
|
|
225
|
+
|
|
226
|
+
def receipt_of(v, f, committed_at=None):
|
|
227
|
+
r = {"act_id": act["act_id"], "act_digest": v.get("act_digest", ""), "decision": v["decision"], "rule": v.get("rule"),
|
|
228
|
+
**({"by_consent": True} if v.get("by_consent") else {}), "verified_at": iso(at),
|
|
229
|
+
**({"committed_at": iso(committed_at)} if committed_at else {}), "relying_party_facts": f,
|
|
230
|
+
**({"in_force_source": v["in_force_source"]} if v.get("in_force_source") else {}), "currency_policy": authority["currency_policy"]}
|
|
231
|
+
return r
|
|
232
|
+
|
|
233
|
+
if verdict["decision"] == "REPLAYED":
|
|
234
|
+
return _answer(verdict, act_id=act["act_id"], receipt=self.store.receipt_for(act["nonce"]))
|
|
235
|
+
if verdict["decision"] != "AUTHORIZED" or self.mode == "shadow":
|
|
236
|
+
if self.on_verdict: self.on_verdict(verdict, receipt_of(verdict, facts))
|
|
237
|
+
if verdict["decision"] == "ESCALATED":
|
|
238
|
+
esc = next((e for e in ((act["authority"]["artifact"].get("governance") or {}).get("escalations") or []) if e.get("id") == verdict.get("escalation_id")), None)
|
|
239
|
+
return _answer(verdict, role=(esc or {}).get("role_required"), retry_until=act["expires_at"])
|
|
240
|
+
if self.mode == "shadow":
|
|
241
|
+
s, h, b = _answer(verdict); return 200, h, {**b, "shadow": True}
|
|
242
|
+
return _answer(verdict)
|
|
243
|
+
|
|
244
|
+
# SPEC-008 §8, one atomic operation.
|
|
245
|
+
try:
|
|
246
|
+
with self.store.transaction() as t:
|
|
247
|
+
if not t.claim_nonce(act["nonce"]): raise _LostRace()
|
|
248
|
+
final, final_facts = verdict, facts
|
|
249
|
+
if self.local_facts:
|
|
250
|
+
fresh = self.local_facts(act, t.tx)
|
|
251
|
+
if fresh != facts: # step 3: our state moved since verification
|
|
252
|
+
final_facts = fresh
|
|
253
|
+
final = self._verify(act, authority, fresh, at, False, rev)
|
|
254
|
+
if final["decision"] != "AUTHORIZED": raise _Rollback(_answer(final))
|
|
255
|
+
a = act["action"]
|
|
256
|
+
action = copy.deepcopy({"type": a["type"], **({"subject": a["subject"]} if "subject" in a else {}), "params": a.get("params") or {}})
|
|
257
|
+
result = self.commit(action, t.tx, act["act_id"])
|
|
258
|
+
receipt = receipt_of(final, final_facts, self.now())
|
|
259
|
+
t.put_receipt(act["nonce"], receipt, act)
|
|
260
|
+
if self.on_verdict: self.on_verdict(final, receipt)
|
|
261
|
+
return _answer(final, receipt=receipt, **({"result": result} if result is not None else {}))
|
|
262
|
+
except _Rollback as r:
|
|
263
|
+
return r.answer
|
|
264
|
+
except _LostRace:
|
|
265
|
+
# Read only now, after the losing transaction has ended and released its connection.
|
|
266
|
+
return _answer({"decision": "REPLAYED"}, act_id=act["act_id"], receipt=self.store.receipt_for(act["nonce"]))
|
|
267
|
+
except Exception as e:
|
|
268
|
+
return 500, {"content-type": "application/json"}, {"error": "The commit failed and was rolled back; nothing was applied.", "detail": str(e)}
|
|
269
|
+
|
|
270
|
+
# ── WSGI and ASGI ──────────────────────────────────────────────────────────────────────
|
|
271
|
+
def wsgi(self, environ, start_response):
|
|
272
|
+
path, method = environ.get("PATH_INFO", ""), environ.get("REQUEST_METHOD", "GET")
|
|
273
|
+
def send(status, headers, body):
|
|
274
|
+
data = json.dumps(body).encode()
|
|
275
|
+
start_response(f"{status} {_REASON.get(status, '')}", [*headers.items(), ("content-length", str(len(data)))])
|
|
276
|
+
return [data]
|
|
277
|
+
if method == "GET" and path == WELL_KNOWN:
|
|
278
|
+
return send(200, {"content-type": "application/json", "cache-control": "max-age=300"}, self.document())
|
|
279
|
+
if path != self.endpoint_path: return send(404, {"content-type": "application/json"}, {"error": "Not found"})
|
|
280
|
+
try: length = int(environ.get("CONTENT_LENGTH") or 0)
|
|
281
|
+
except ValueError: length = 0
|
|
282
|
+
body = environ["wsgi.input"].read(min(length, self.max_act_bytes + 1)) if length else b""
|
|
283
|
+
if length > self.max_act_bytes: body = b"x" * (self.max_act_bytes + 1)
|
|
284
|
+
return send(*self.handle(method, environ.get("CONTENT_TYPE", ""), body))
|
|
285
|
+
|
|
286
|
+
async def asgi(self, scope, receive, send):
|
|
287
|
+
if scope["type"] != "http": return
|
|
288
|
+
path, method = scope["path"], scope["method"]
|
|
289
|
+
async def reply(status, headers, body):
|
|
290
|
+
data = json.dumps(body).encode()
|
|
291
|
+
await send({"type": "http.response.start", "status": status, "headers": [(k.encode(), v.encode()) for k, v in {**headers, "content-length": str(len(data))}.items()]})
|
|
292
|
+
await send({"type": "http.response.body", "body": data})
|
|
293
|
+
if method == "GET" and path == WELL_KNOWN:
|
|
294
|
+
return await reply(200, {"content-type": "application/json", "cache-control": "max-age=300"}, self.document())
|
|
295
|
+
if path != self.endpoint_path: return await reply(404, {"content-type": "application/json"}, {"error": "Not found"})
|
|
296
|
+
chunks, size = [], 0
|
|
297
|
+
while True:
|
|
298
|
+
m = await receive(); b = m.get("body", b""); size += len(b)
|
|
299
|
+
if size <= self.max_act_bytes: chunks.append(b)
|
|
300
|
+
if not m.get("more_body"): break
|
|
301
|
+
body = b"".join(chunks) if size <= self.max_act_bytes else b"x" * (self.max_act_bytes + 1)
|
|
302
|
+
ctype = next((v.decode() for k, v in scope.get("headers", []) if k.decode().lower() == "content-type"), "")
|
|
303
|
+
import asyncio
|
|
304
|
+
return await reply(*(await asyncio.get_running_loop().run_in_executor(None, self.handle, method, ctype, body)))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
_REASON = {200: "OK", 201: "Created", 202: "Accepted", 400: "Bad Request", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
|
|
308
|
+
409: "Conflict", 413: "Payload Too Large", 415: "Unsupported Media Type", 422: "Unprocessable Entity", 500: "Internal Server Error", 503: "Service Unavailable"}
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def accept(**options) -> RelyingParty:
|
|
312
|
+
return RelyingParty(**options)
|