tba-protocol-ucan 0.4.0.dev2__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.
- tba_protocol_ucan-0.4.0.dev2/PKG-INFO +96 -0
- tba_protocol_ucan-0.4.0.dev2/README.md +76 -0
- tba_protocol_ucan-0.4.0.dev2/pyproject.toml +29 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/__init__.py +27 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/codec.py +173 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/policy.py +41 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/protocol.py +116 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/py.typed +0 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/schemas.py +118 -0
- tba_protocol_ucan-0.4.0.dev2/src/tba_protocol_ucan/versions.py +5 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: tba-protocol-ucan
|
|
3
|
+
Version: 0.4.0.dev2
|
|
4
|
+
Summary: UCAN delegation and invocation verification for the TBA Ed25519 development profile.
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Requires-Python: >=3.10,<3.16
|
|
7
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.15
|
|
13
|
+
Requires-Dist: cryptography (>=45)
|
|
14
|
+
Requires-Dist: tba-codec-cid (==0.4.0.dev2)
|
|
15
|
+
Requires-Dist: tba-codec-dag-cbor (==0.4.0.dev2)
|
|
16
|
+
Requires-Dist: tba-codec-multibase (==0.4.0.dev2)
|
|
17
|
+
Requires-Dist: tba-contracts-replay (==0.4.0.dev2)
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# tba-protocol-ucan
|
|
21
|
+
|
|
22
|
+
<!-- BEGIN TBA README HEADER -->
|
|
23
|
+
<p align="center">
|
|
24
|
+
<a href="https://github.com/tigrbl/tigrbl_auth#readme"><img src="https://raw.githubusercontent.com/tigrbl/tigrbl_auth/master/docs/assets/tba-brand.png" alt="TBA · Tigrbl Auth" width="240"></a>
|
|
25
|
+
</p>
|
|
26
|
+
<p align="center">
|
|
27
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="Checkout: 0.4.0.dev2" src="https://img.shields.io/badge/Checkout-0.4.0.dev2-1f6feb"></a>
|
|
28
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="Python: >=3.10,<3.16" src="https://img.shields.io/badge/Python-%3E%3D3.10%2C%3C3.16-3776ab"></a>
|
|
29
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/License-Apache--2.0-525252"></a>
|
|
30
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/tree/master/pkgs/50-protocols"><img alt="Layer: 50 protocols" src="https://img.shields.io/badge/Layer-50%20protocols-0a7f5a"></a>
|
|
31
|
+
<a href="https://pypi.org/project/tba-protocol-ucan/"><img alt="PyPI version for tba-protocol-ucan" src="https://img.shields.io/pypi/v/tba-protocol-ucan?label=tba-protocol-ucan%20PyPI"></a>
|
|
32
|
+
</p>
|
|
33
|
+
<p align="center">
|
|
34
|
+
<a href="https://pepy.tech/project/tba-protocol-ucan"><img alt="Monthly PyPI downloads for tba-protocol-ucan" src="https://static.pepy.tech/badge/tba-protocol-ucan/month"></a>
|
|
35
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/README.md#verification"><img alt="Evidence: verification" src="https://img.shields.io/badge/Evidence-verification-8250df"></a>
|
|
36
|
+
</p>
|
|
37
|
+
<!-- END TBA README HEADER -->
|
|
38
|
+
|
|
39
|
+
UCAN delegation and invocation signing and verification for the TBA Ed25519
|
|
40
|
+
development profile. The wire tags are `ucan/dlg@1.0.0` and `ucan/inv@1.0.0`.
|
|
41
|
+
|
|
42
|
+
- [UCAN envelope](https://github.com/ucan-wg/spec/blob/8072f3f23f451eaa1271269fe763aebcf294f4db/README.md#envelope)
|
|
43
|
+
- [UCAN delegation](https://github.com/ucan-wg/delegation/blob/1cb32dbc9d4d15a23bf9844a02515d760b81e816/README.md)
|
|
44
|
+
- [UCAN invocation](https://github.com/ucan-wg/invocation/blob/0f4c11325af6aca298b565cc19e90009d10e0197/README.md)
|
|
45
|
+
|
|
46
|
+
This profile supports bare Ed25519 `did:key` identifiers, canonical DAG-CBOR
|
|
47
|
+
with integers in the interoperable 53-bit range, linear proof chains of up to
|
|
48
|
+
16 grants, finite expiries, and equality predicates on top-level arguments.
|
|
49
|
+
Invocations have a maximum remaining lifetime of five minutes. The profile
|
|
50
|
+
rejects unsupported algorithms, fields, and policy operators. It covers a
|
|
51
|
+
subset of the UCAN specifications.
|
|
52
|
+
|
|
53
|
+
## Verifying a call
|
|
54
|
+
|
|
55
|
+
Use `sign_delegation` and `sign_invocation` with the issuer's Ed25519 private
|
|
56
|
+
key. Index signed delegations with `content_id` and list their CIDs in
|
|
57
|
+
`UcanInvocation.prf` from root to leaf. Configure `UcanVerifier` with a
|
|
58
|
+
proof lookup, a revocation check, and a TBA replay reservation provider.
|
|
59
|
+
Call `verify_invocation` with the trusted subject, the local executor, and the
|
|
60
|
+
expected command. Dispatch the command with the arguments in the returned
|
|
61
|
+
invocation. The verifier checks every delegation's policy against those
|
|
62
|
+
arguments and atomically reserves the invocation CID before returning.
|
|
63
|
+
|
|
64
|
+
The caller supplies the mapping from trusted subjects and commands to local
|
|
65
|
+
resources. A deployment with multiple workers needs a shared replay store
|
|
66
|
+
with atomic reservations. Revocation storage is supplied by the caller.
|
|
67
|
+
|
|
68
|
+
## Wire codec
|
|
69
|
+
|
|
70
|
+
**DAG-CBOR** produces deterministic binary bytes for the signed map. The
|
|
71
|
+
verifier rejects duplicate keys, noncanonical encodings, and values outside
|
|
72
|
+
the profile. **Varsig** is the header inside that map identifying Ed25519 and
|
|
73
|
+
DAG-CBOR. The signature covers both the header and the versioned payload.
|
|
74
|
+
|
|
75
|
+
A **CID** identifies the complete signed envelope. Its binary representation
|
|
76
|
+
contains CIDv1, the DAG-CBOR codec code, the SHA-256 multihash code and length,
|
|
77
|
+
and the digest. The text form uses base58btc. In the invocation proof list,
|
|
78
|
+
each CID is a DAG-CBOR tag 42 link with a leading zero byte followed by the
|
|
79
|
+
binary CID. The verifier recomputes the CID of every resolved proof before
|
|
80
|
+
accepting it.
|
|
81
|
+
|
|
82
|
+
See [DAG-CBOR](https://ipld.io/specs/codecs/dag-cbor/spec/) and
|
|
83
|
+
[Varsig](https://github.com/ChainAgnostic/varsig).
|
|
84
|
+
|
|
85
|
+
## Quick start
|
|
86
|
+
|
|
87
|
+
Build the package from the repository root.
|
|
88
|
+
|
|
89
|
+
```bash
|
|
90
|
+
uv build --wheel pkgs/50-protocols/tba-protocol-ucan
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Verification
|
|
94
|
+
|
|
95
|
+
Check that the build produces a wheel with the package version declared in `pyproject.toml`.
|
|
96
|
+
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# tba-protocol-ucan
|
|
2
|
+
|
|
3
|
+
<!-- BEGIN TBA README HEADER -->
|
|
4
|
+
<p align="center">
|
|
5
|
+
<a href="https://github.com/tigrbl/tigrbl_auth#readme"><img src="https://raw.githubusercontent.com/tigrbl/tigrbl_auth/master/docs/assets/tba-brand.png" alt="TBA · Tigrbl Auth" width="240"></a>
|
|
6
|
+
</p>
|
|
7
|
+
<p align="center">
|
|
8
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="Checkout: 0.4.0.dev2" src="https://img.shields.io/badge/Checkout-0.4.0.dev2-1f6feb"></a>
|
|
9
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="Python: >=3.10,<3.16" src="https://img.shields.io/badge/Python-%3E%3D3.10%2C%3C3.16-3776ab"></a>
|
|
10
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/pyproject.toml"><img alt="License: Apache-2.0" src="https://img.shields.io/badge/License-Apache--2.0-525252"></a>
|
|
11
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/tree/master/pkgs/50-protocols"><img alt="Layer: 50 protocols" src="https://img.shields.io/badge/Layer-50%20protocols-0a7f5a"></a>
|
|
12
|
+
<a href="https://pypi.org/project/tba-protocol-ucan/"><img alt="PyPI version for tba-protocol-ucan" src="https://img.shields.io/pypi/v/tba-protocol-ucan?label=tba-protocol-ucan%20PyPI"></a>
|
|
13
|
+
</p>
|
|
14
|
+
<p align="center">
|
|
15
|
+
<a href="https://pepy.tech/project/tba-protocol-ucan"><img alt="Monthly PyPI downloads for tba-protocol-ucan" src="https://static.pepy.tech/badge/tba-protocol-ucan/month"></a>
|
|
16
|
+
<a href="https://github.com/tigrbl/tigrbl_auth/blob/master/pkgs/50-protocols/tba-protocol-ucan/README.md#verification"><img alt="Evidence: verification" src="https://img.shields.io/badge/Evidence-verification-8250df"></a>
|
|
17
|
+
</p>
|
|
18
|
+
<!-- END TBA README HEADER -->
|
|
19
|
+
|
|
20
|
+
UCAN delegation and invocation signing and verification for the TBA Ed25519
|
|
21
|
+
development profile. The wire tags are `ucan/dlg@1.0.0` and `ucan/inv@1.0.0`.
|
|
22
|
+
|
|
23
|
+
- [UCAN envelope](https://github.com/ucan-wg/spec/blob/8072f3f23f451eaa1271269fe763aebcf294f4db/README.md#envelope)
|
|
24
|
+
- [UCAN delegation](https://github.com/ucan-wg/delegation/blob/1cb32dbc9d4d15a23bf9844a02515d760b81e816/README.md)
|
|
25
|
+
- [UCAN invocation](https://github.com/ucan-wg/invocation/blob/0f4c11325af6aca298b565cc19e90009d10e0197/README.md)
|
|
26
|
+
|
|
27
|
+
This profile supports bare Ed25519 `did:key` identifiers, canonical DAG-CBOR
|
|
28
|
+
with integers in the interoperable 53-bit range, linear proof chains of up to
|
|
29
|
+
16 grants, finite expiries, and equality predicates on top-level arguments.
|
|
30
|
+
Invocations have a maximum remaining lifetime of five minutes. The profile
|
|
31
|
+
rejects unsupported algorithms, fields, and policy operators. It covers a
|
|
32
|
+
subset of the UCAN specifications.
|
|
33
|
+
|
|
34
|
+
## Verifying a call
|
|
35
|
+
|
|
36
|
+
Use `sign_delegation` and `sign_invocation` with the issuer's Ed25519 private
|
|
37
|
+
key. Index signed delegations with `content_id` and list their CIDs in
|
|
38
|
+
`UcanInvocation.prf` from root to leaf. Configure `UcanVerifier` with a
|
|
39
|
+
proof lookup, a revocation check, and a TBA replay reservation provider.
|
|
40
|
+
Call `verify_invocation` with the trusted subject, the local executor, and the
|
|
41
|
+
expected command. Dispatch the command with the arguments in the returned
|
|
42
|
+
invocation. The verifier checks every delegation's policy against those
|
|
43
|
+
arguments and atomically reserves the invocation CID before returning.
|
|
44
|
+
|
|
45
|
+
The caller supplies the mapping from trusted subjects and commands to local
|
|
46
|
+
resources. A deployment with multiple workers needs a shared replay store
|
|
47
|
+
with atomic reservations. Revocation storage is supplied by the caller.
|
|
48
|
+
|
|
49
|
+
## Wire codec
|
|
50
|
+
|
|
51
|
+
**DAG-CBOR** produces deterministic binary bytes for the signed map. The
|
|
52
|
+
verifier rejects duplicate keys, noncanonical encodings, and values outside
|
|
53
|
+
the profile. **Varsig** is the header inside that map identifying Ed25519 and
|
|
54
|
+
DAG-CBOR. The signature covers both the header and the versioned payload.
|
|
55
|
+
|
|
56
|
+
A **CID** identifies the complete signed envelope. Its binary representation
|
|
57
|
+
contains CIDv1, the DAG-CBOR codec code, the SHA-256 multihash code and length,
|
|
58
|
+
and the digest. The text form uses base58btc. In the invocation proof list,
|
|
59
|
+
each CID is a DAG-CBOR tag 42 link with a leading zero byte followed by the
|
|
60
|
+
binary CID. The verifier recomputes the CID of every resolved proof before
|
|
61
|
+
accepting it.
|
|
62
|
+
|
|
63
|
+
See [DAG-CBOR](https://ipld.io/specs/codecs/dag-cbor/spec/) and
|
|
64
|
+
[Varsig](https://github.com/ChainAgnostic/varsig).
|
|
65
|
+
|
|
66
|
+
## Quick start
|
|
67
|
+
|
|
68
|
+
Build the package from the repository root.
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
uv build --wheel pkgs/50-protocols/tba-protocol-ucan
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Verification
|
|
75
|
+
|
|
76
|
+
Check that the build produces a wheel with the package version declared in `pyproject.toml`.
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "tba-protocol-ucan"
|
|
3
|
+
version = "0.4.0.dev2"
|
|
4
|
+
description = "UCAN delegation and invocation verification for the TBA Ed25519 development profile."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.10,<3.16"
|
|
7
|
+
classifiers = [
|
|
8
|
+
"Programming Language :: Python :: 3.10",
|
|
9
|
+
"Programming Language :: Python :: 3.11",
|
|
10
|
+
"Programming Language :: Python :: 3.12",
|
|
11
|
+
"Programming Language :: Python :: 3.13",
|
|
12
|
+
"Programming Language :: Python :: 3.14",
|
|
13
|
+
"Programming Language :: Python :: 3.15",
|
|
14
|
+
]
|
|
15
|
+
license = "Apache-2.0"
|
|
16
|
+
dependencies = [
|
|
17
|
+
"cryptography>=45",
|
|
18
|
+
"tba-codec-cid==0.4.0.dev2",
|
|
19
|
+
"tba-codec-dag-cbor==0.4.0.dev2",
|
|
20
|
+
"tba-codec-multibase==0.4.0.dev2",
|
|
21
|
+
"tba-contracts-replay==0.4.0.dev2",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[build-system]
|
|
25
|
+
requires = ["poetry-core>=1.0.0"]
|
|
26
|
+
build-backend = "poetry.core.masonry.api"
|
|
27
|
+
|
|
28
|
+
[tool.poetry]
|
|
29
|
+
packages = [{ include = "tba_protocol_ucan", from = "src" }]
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""UCAN delegation and invocation in the TBA Ed25519 development profile."""
|
|
2
|
+
|
|
3
|
+
from .codec import UcanEnvelopeCodec, UcanError, content_id, did_key
|
|
4
|
+
from .protocol import (
|
|
5
|
+
UcanVerifier,
|
|
6
|
+
VerifiedUcanInvocation,
|
|
7
|
+
sign_delegation,
|
|
8
|
+
sign_invocation,
|
|
9
|
+
)
|
|
10
|
+
from .schemas import UcanDelegation, UcanInvocation
|
|
11
|
+
from .versions import DELEGATION_TAG, INVOCATION_TAG, PROFILE
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DELEGATION_TAG",
|
|
15
|
+
"INVOCATION_TAG",
|
|
16
|
+
"PROFILE",
|
|
17
|
+
"UcanDelegation",
|
|
18
|
+
"UcanEnvelopeCodec",
|
|
19
|
+
"UcanError",
|
|
20
|
+
"UcanInvocation",
|
|
21
|
+
"UcanVerifier",
|
|
22
|
+
"VerifiedUcanInvocation",
|
|
23
|
+
"content_id",
|
|
24
|
+
"did_key",
|
|
25
|
+
"sign_delegation",
|
|
26
|
+
"sign_invocation",
|
|
27
|
+
]
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Canonical UCAN encoding for the Ed25519 development profile."""
|
|
2
|
+
|
|
3
|
+
from hashlib import sha256
|
|
4
|
+
|
|
5
|
+
from cryptography.exceptions import InvalidSignature
|
|
6
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
|
|
7
|
+
Ed25519PrivateKey,
|
|
8
|
+
Ed25519PublicKey,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
import tba_codec_dag_cbor as dag_cbor
|
|
12
|
+
from tba_codec_cid import Cid
|
|
13
|
+
from tba_codec_dag_cbor import CBORTag
|
|
14
|
+
from tba_codec_multibase import decode_base58btc, encode_base58btc
|
|
15
|
+
|
|
16
|
+
from .versions import DELEGATION_TAG, INVOCATION_TAG
|
|
17
|
+
|
|
18
|
+
# Varsig v1, EdDSA, Ed25519 public key, SHA-512, DAG-CBOR.
|
|
19
|
+
VARSIG_HEADER = bytes.fromhex("3401ed01ed011371")
|
|
20
|
+
# CIDv1, dag-cbor, sha2-256, digest length 32.
|
|
21
|
+
_CID_CODEC = 0x71
|
|
22
|
+
_CID_HASH = 0x12
|
|
23
|
+
_ED25519_PREFIX = bytes.fromhex("ed01")
|
|
24
|
+
_MAX_BYTES = 64 * 1024
|
|
25
|
+
_MAX_DEPTH = 32
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class UcanError(ValueError):
|
|
29
|
+
"""Malformed or unauthorized UCAN within the supported profile."""
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _decode_multibase(text: str, prefix: bytes, size: int) -> bytes:
|
|
33
|
+
if not isinstance(text, str) or not text.startswith("z") or len(text) > 60:
|
|
34
|
+
raise UcanError("expected base58btc multibase")
|
|
35
|
+
try:
|
|
36
|
+
data = decode_base58btc(text)
|
|
37
|
+
except ValueError as exc:
|
|
38
|
+
raise UcanError("invalid base58btc character") from exc
|
|
39
|
+
if not data.startswith(prefix) or len(data) != size:
|
|
40
|
+
raise UcanError("unexpected multicodec or key/digest length")
|
|
41
|
+
return data
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def did_key(public_key: Ed25519PublicKey) -> str:
|
|
45
|
+
"""Return the self-certifying DID for an Ed25519 public key."""
|
|
46
|
+
return "did:key:" + encode_base58btc(
|
|
47
|
+
_ED25519_PREFIX + public_key.public_bytes_raw()
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _public_key(did: str) -> Ed25519PublicKey:
|
|
52
|
+
if not isinstance(did, str) or not did.startswith("did:key:"):
|
|
53
|
+
raise UcanError("expected an Ed25519 did:key")
|
|
54
|
+
data = _decode_multibase(did[8:], _ED25519_PREFIX, 34)
|
|
55
|
+
return Ed25519PublicKey.from_public_bytes(data[2:])
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def validate_did(did: str) -> None:
|
|
59
|
+
_public_key(did)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def content_id(wire: bytes) -> str:
|
|
63
|
+
"""Compute the CID of canonical bytes, without verifying their signature."""
|
|
64
|
+
return Cid(1, _CID_CODEC, _CID_HASH, sha256(wire).digest()).to_text()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _validate_cid(cid: Cid) -> Cid:
|
|
68
|
+
if (cid.version, cid.codec, cid.hash_code, len(cid.digest)) != (
|
|
69
|
+
1,
|
|
70
|
+
_CID_CODEC,
|
|
71
|
+
_CID_HASH,
|
|
72
|
+
32,
|
|
73
|
+
):
|
|
74
|
+
raise UcanError("expected a UCAN CIDv1 with DAG-CBOR and SHA-256")
|
|
75
|
+
return cid
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def cid_link(cid: str) -> CBORTag:
|
|
79
|
+
if not isinstance(cid, str) or len(cid) > 60:
|
|
80
|
+
raise UcanError("expected a bounded UCAN CID")
|
|
81
|
+
try:
|
|
82
|
+
decoded = Cid.from_text(cid)
|
|
83
|
+
except ValueError as exc:
|
|
84
|
+
raise UcanError("invalid UCAN CID") from exc
|
|
85
|
+
return dag_cbor.cid_link(_validate_cid(decoded))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def link_cid(link: object) -> str:
|
|
89
|
+
try:
|
|
90
|
+
cid = dag_cbor.link_cid(link)
|
|
91
|
+
except ValueError as exc:
|
|
92
|
+
raise UcanError("expected a DAG-CBOR link to a UCAN CID") from exc
|
|
93
|
+
return _validate_cid(cid).to_text()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _validate_node(value: object, depth: int = 0) -> None:
|
|
97
|
+
if depth >= _MAX_DEPTH:
|
|
98
|
+
raise UcanError("DAG-CBOR nesting limit exceeded")
|
|
99
|
+
if value is None or type(value) in (bool, str, bytes):
|
|
100
|
+
return
|
|
101
|
+
if type(value) is int and -(2**53 - 1) <= value <= 2**53 - 1:
|
|
102
|
+
return
|
|
103
|
+
if type(value) in (list, tuple):
|
|
104
|
+
for item in value:
|
|
105
|
+
_validate_node(item, depth + 1)
|
|
106
|
+
return
|
|
107
|
+
if type(value) is dict and all(type(key) is str for key in value):
|
|
108
|
+
for item in value.values():
|
|
109
|
+
_validate_node(item, depth + 1)
|
|
110
|
+
return
|
|
111
|
+
if isinstance(value, CBORTag):
|
|
112
|
+
link_cid(value)
|
|
113
|
+
return
|
|
114
|
+
raise UcanError("unsupported DAG-CBOR value in the development profile")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def canonical_bytes(value: object) -> bytes:
|
|
118
|
+
_validate_node(value)
|
|
119
|
+
try:
|
|
120
|
+
wire = dag_cbor.encode(value, max_depth=_MAX_DEPTH)
|
|
121
|
+
except ValueError as exc:
|
|
122
|
+
raise UcanError("cannot encode DAG-CBOR value") from exc
|
|
123
|
+
if len(wire) > _MAX_BYTES:
|
|
124
|
+
raise UcanError("UCAN byte limit exceeded")
|
|
125
|
+
return wire
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _decode(wire: bytes) -> object:
|
|
129
|
+
if type(wire) is not bytes or len(wire) > _MAX_BYTES:
|
|
130
|
+
raise UcanError("expected a bounded UCAN byte string")
|
|
131
|
+
try:
|
|
132
|
+
value = dag_cbor.decode(wire, max_depth=_MAX_DEPTH)
|
|
133
|
+
except ValueError as exc:
|
|
134
|
+
raise UcanError(str(exc)) from exc
|
|
135
|
+
_validate_node(value)
|
|
136
|
+
return value
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class UcanEnvelopeCodec:
|
|
140
|
+
"""Sign and verify the two supported UCAN v1 wire envelopes."""
|
|
141
|
+
|
|
142
|
+
def sign(self, tag: str, payload: dict, key: Ed25519PrivateKey) -> bytes:
|
|
143
|
+
if tag not in (DELEGATION_TAG, INVOCATION_TAG):
|
|
144
|
+
raise UcanError("unsupported UCAN envelope tag")
|
|
145
|
+
if payload.get("iss") != did_key(key.public_key()):
|
|
146
|
+
raise UcanError("signing key does not match issuer")
|
|
147
|
+
signed = {"h": VARSIG_HEADER, tag: payload}
|
|
148
|
+
return canonical_bytes([key.sign(canonical_bytes(signed)), signed])
|
|
149
|
+
|
|
150
|
+
def verify(self, wire: bytes, tag: str) -> dict:
|
|
151
|
+
envelope = _decode(wire)
|
|
152
|
+
if (
|
|
153
|
+
type(envelope) is not list
|
|
154
|
+
or len(envelope) != 2
|
|
155
|
+
or type(envelope[0]) is not bytes
|
|
156
|
+
or len(envelope[0]) != 64
|
|
157
|
+
or type(envelope[1]) is not dict
|
|
158
|
+
or tag not in (DELEGATION_TAG, INVOCATION_TAG)
|
|
159
|
+
):
|
|
160
|
+
raise UcanError("invalid UCAN envelope")
|
|
161
|
+
signature, signed = envelope
|
|
162
|
+
if (
|
|
163
|
+
set(signed) != {"h", tag}
|
|
164
|
+
or signed["h"] != VARSIG_HEADER
|
|
165
|
+
or type(signed[tag]) is not dict
|
|
166
|
+
):
|
|
167
|
+
raise UcanError("unexpected UCAN tag or Varsig header")
|
|
168
|
+
payload = signed[tag]
|
|
169
|
+
try:
|
|
170
|
+
_public_key(payload.get("iss")).verify(signature, canonical_bytes(signed))
|
|
171
|
+
except InvalidSignature as exc:
|
|
172
|
+
raise UcanError("invalid UCAN signature") from exc
|
|
173
|
+
return payload
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Command paths and top-level equality predicates for this profile."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
|
|
5
|
+
from .codec import UcanError, canonical_bytes
|
|
6
|
+
|
|
7
|
+
_COMMAND = re.compile(r"/(?:[A-Za-z0-9_.-]+(?:/[A-Za-z0-9_.-]+)*)?")
|
|
8
|
+
_SELECTOR = re.compile(r"\.[A-Za-z_][A-Za-z0-9_]*")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_command(command: str) -> None:
|
|
12
|
+
if (
|
|
13
|
+
not isinstance(command, str)
|
|
14
|
+
or not _COMMAND.fullmatch(command)
|
|
15
|
+
or any(segment in {".", ".."} for segment in command.split("/"))
|
|
16
|
+
):
|
|
17
|
+
raise UcanError("unsupported command path")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def covers_command(granted: str, requested: str) -> bool:
|
|
21
|
+
return granted == "/" or requested == granted or requested.startswith(granted + "/")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def validate_policy(policy: tuple) -> None:
|
|
25
|
+
for predicate in policy:
|
|
26
|
+
if (
|
|
27
|
+
not isinstance(predicate, (tuple, list))
|
|
28
|
+
or len(predicate) != 3
|
|
29
|
+
or predicate[0] != "=="
|
|
30
|
+
or not isinstance(predicate[1], str)
|
|
31
|
+
or not _SELECTOR.fullmatch(predicate[1])
|
|
32
|
+
):
|
|
33
|
+
raise UcanError("unsupported UCAN policy predicate")
|
|
34
|
+
canonical_bytes(predicate[2])
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def enforce_policy(policy: tuple, arguments: dict) -> None:
|
|
38
|
+
for _, selector, expected in policy:
|
|
39
|
+
# An absent top-level map key resolves to null in UCAN selectors.
|
|
40
|
+
if canonical_bytes(arguments.get(selector[1:])) != canonical_bytes(expected):
|
|
41
|
+
raise UcanError("invocation arguments do not satisfy delegation policy")
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""UCAN signing and delegated invocation verification."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
|
|
7
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
|
|
8
|
+
from tba_contracts_replay import (
|
|
9
|
+
ReplayKey,
|
|
10
|
+
ReplayReservationPort,
|
|
11
|
+
ReplayReservationRequest,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
from .codec import UcanEnvelopeCodec, UcanError, content_id
|
|
15
|
+
from .policy import covers_command, enforce_policy
|
|
16
|
+
from .schemas import UcanDelegation, UcanInvocation
|
|
17
|
+
from .versions import DELEGATION_TAG, INVOCATION_TAG, PROFILE
|
|
18
|
+
|
|
19
|
+
_MAX_INVOCATION_LIFETIME = 300
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def sign_delegation(delegation: UcanDelegation, key: Ed25519PrivateKey) -> bytes:
|
|
23
|
+
return UcanEnvelopeCodec().sign(DELEGATION_TAG, delegation.to_payload(), key)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def sign_invocation(invocation: UcanInvocation, key: Ed25519PrivateKey) -> bytes:
|
|
27
|
+
return UcanEnvelopeCodec().sign(INVOCATION_TAG, invocation.to_payload(), key)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True, slots=True)
|
|
31
|
+
class VerifiedUcanInvocation:
|
|
32
|
+
invocation: UcanInvocation
|
|
33
|
+
cid: str
|
|
34
|
+
profile: str = PROFILE
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class UcanVerifier:
|
|
38
|
+
"""Verify a closed delegation chain and reserve the invocation before execution."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
*,
|
|
43
|
+
resolve_proof: Callable[[str], bytes | None],
|
|
44
|
+
is_revoked: Callable[[str], bool],
|
|
45
|
+
replay: ReplayReservationPort,
|
|
46
|
+
) -> None:
|
|
47
|
+
self._resolve_proof = resolve_proof
|
|
48
|
+
self._is_revoked = is_revoked
|
|
49
|
+
self._replay = replay
|
|
50
|
+
self._codec = UcanEnvelopeCodec()
|
|
51
|
+
|
|
52
|
+
async def verify_invocation(
|
|
53
|
+
self,
|
|
54
|
+
wire: bytes,
|
|
55
|
+
*,
|
|
56
|
+
expected_subject: str,
|
|
57
|
+
expected_executor: str,
|
|
58
|
+
expected_command: str,
|
|
59
|
+
now: datetime | None = None,
|
|
60
|
+
) -> VerifiedUcanInvocation:
|
|
61
|
+
now = datetime.now(timezone.utc) if now is None else now
|
|
62
|
+
if now.utcoffset() is None:
|
|
63
|
+
raise UcanError("verification time must include a timezone")
|
|
64
|
+
timestamp = now.timestamp()
|
|
65
|
+
invocation = UcanInvocation.from_payload(
|
|
66
|
+
self._codec.verify(wire, INVOCATION_TAG)
|
|
67
|
+
)
|
|
68
|
+
if (
|
|
69
|
+
invocation.sub != expected_subject
|
|
70
|
+
or invocation.executor != expected_executor
|
|
71
|
+
):
|
|
72
|
+
raise UcanError("unexpected invocation subject or executor")
|
|
73
|
+
if invocation.cmd != expected_command:
|
|
74
|
+
raise UcanError("unexpected invocation command")
|
|
75
|
+
if not timestamp < invocation.exp <= timestamp + _MAX_INVOCATION_LIFETIME:
|
|
76
|
+
raise UcanError("invocation expired or exceeds the allowed lifetime")
|
|
77
|
+
self._verify_chain(invocation, timestamp)
|
|
78
|
+
cid = content_id(wire)
|
|
79
|
+
reservation = await self._replay.check_and_reserve(
|
|
80
|
+
ReplayReservationRequest(
|
|
81
|
+
ReplayKey(PROFILE, cid),
|
|
82
|
+
datetime.fromtimestamp(invocation.exp, timezone.utc),
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
if not reservation.accepted:
|
|
86
|
+
raise UcanError("invocation replay reservation rejected")
|
|
87
|
+
return VerifiedUcanInvocation(invocation, cid)
|
|
88
|
+
|
|
89
|
+
def _verify_chain(self, invocation: UcanInvocation, now: float) -> None:
|
|
90
|
+
next_issuer = invocation.sub
|
|
91
|
+
parent_command = "/"
|
|
92
|
+
for cid in invocation.prf:
|
|
93
|
+
wire = self._resolve_proof(cid)
|
|
94
|
+
if wire is None:
|
|
95
|
+
raise UcanError("missing delegation proof")
|
|
96
|
+
delegation = UcanDelegation.from_payload(
|
|
97
|
+
self._codec.verify(wire, DELEGATION_TAG)
|
|
98
|
+
)
|
|
99
|
+
if content_id(wire) != cid:
|
|
100
|
+
raise UcanError("resolved proof does not match its CID")
|
|
101
|
+
if self._is_revoked(cid):
|
|
102
|
+
raise UcanError("delegation is revoked")
|
|
103
|
+
if delegation.iss != next_issuer or delegation.sub != invocation.sub:
|
|
104
|
+
raise UcanError("broken delegation chain")
|
|
105
|
+
if delegation.exp <= now or (
|
|
106
|
+
delegation.nbf is not None and delegation.nbf > now
|
|
107
|
+
):
|
|
108
|
+
raise UcanError("delegation is outside its validity window")
|
|
109
|
+
if not covers_command(parent_command, delegation.cmd):
|
|
110
|
+
raise UcanError("delegation widens the command path")
|
|
111
|
+
if not covers_command(delegation.cmd, invocation.cmd):
|
|
112
|
+
raise UcanError("invocation command is outside the delegation")
|
|
113
|
+
enforce_policy(delegation.pol, invocation.args)
|
|
114
|
+
next_issuer, parent_command = delegation.aud, delegation.cmd
|
|
115
|
+
if next_issuer != invocation.iss:
|
|
116
|
+
raise UcanError("delegation chain does not reach the invoker")
|
|
File without changes
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""Typed payloads for the supported UCAN wire profile."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from .codec import UcanError, cid_link, link_cid, validate_did
|
|
7
|
+
from .policy import validate_command, validate_policy
|
|
8
|
+
|
|
9
|
+
_MAX_CHAIN = 16
|
|
10
|
+
_MAX_TIMESTAMP = 2**53 - 1
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _timestamp(value: object) -> None:
|
|
14
|
+
if type(value) is not int or not 0 <= value <= _MAX_TIMESTAMP:
|
|
15
|
+
raise UcanError("profile requires a finite Unix timestamp")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _fields(payload: dict, required: set[str], optional: set[str]) -> None:
|
|
19
|
+
if required - payload.keys() or payload.keys() - required - optional:
|
|
20
|
+
raise UcanError("unexpected UCAN payload fields")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class UcanDelegation:
|
|
25
|
+
iss: str
|
|
26
|
+
aud: str
|
|
27
|
+
sub: str
|
|
28
|
+
cmd: str
|
|
29
|
+
pol: tuple[tuple[str, str, Any], ...]
|
|
30
|
+
nonce: bytes
|
|
31
|
+
exp: int
|
|
32
|
+
nbf: int | None = None
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def from_payload(cls, payload: dict) -> "UcanDelegation":
|
|
36
|
+
_fields(payload, {"iss", "aud", "sub", "cmd", "pol", "nonce", "exp"}, {"nbf"})
|
|
37
|
+
for key in ("iss", "aud", "sub"):
|
|
38
|
+
validate_did(payload[key])
|
|
39
|
+
validate_command(payload["cmd"])
|
|
40
|
+
_timestamp(payload["exp"])
|
|
41
|
+
if "nbf" in payload:
|
|
42
|
+
_timestamp(payload["nbf"])
|
|
43
|
+
if payload["nbf"] >= payload["exp"]:
|
|
44
|
+
raise UcanError("invalid delegation time window")
|
|
45
|
+
if type(payload["nonce"]) is not bytes or type(payload["pol"]) is not list:
|
|
46
|
+
raise UcanError("invalid delegation nonce or policy")
|
|
47
|
+
validate_policy(tuple(payload["pol"]))
|
|
48
|
+
values = dict(payload)
|
|
49
|
+
values["pol"] = tuple(tuple(predicate) for predicate in payload["pol"])
|
|
50
|
+
return cls(**values)
|
|
51
|
+
|
|
52
|
+
def to_payload(self) -> dict:
|
|
53
|
+
payload = {
|
|
54
|
+
"iss": self.iss,
|
|
55
|
+
"aud": self.aud,
|
|
56
|
+
"sub": self.sub,
|
|
57
|
+
"cmd": self.cmd,
|
|
58
|
+
"pol": list(self.pol),
|
|
59
|
+
"nonce": self.nonce,
|
|
60
|
+
"exp": self.exp,
|
|
61
|
+
}
|
|
62
|
+
if self.nbf is not None:
|
|
63
|
+
payload["nbf"] = self.nbf
|
|
64
|
+
self.from_payload(payload)
|
|
65
|
+
return payload
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True, slots=True)
|
|
69
|
+
class UcanInvocation:
|
|
70
|
+
iss: str
|
|
71
|
+
sub: str
|
|
72
|
+
cmd: str
|
|
73
|
+
args: dict[str, Any]
|
|
74
|
+
nonce: bytes
|
|
75
|
+
exp: int
|
|
76
|
+
prf: tuple[str, ...]
|
|
77
|
+
aud: str | None = None
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def executor(self) -> str:
|
|
81
|
+
return self.sub if self.aud is None else self.aud
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def from_payload(cls, payload: dict) -> "UcanInvocation":
|
|
85
|
+
_fields(payload, {"iss", "sub", "cmd", "args", "nonce", "exp", "prf"}, {"aud"})
|
|
86
|
+
validate_did(payload["iss"])
|
|
87
|
+
validate_did(payload["sub"])
|
|
88
|
+
if "aud" in payload:
|
|
89
|
+
validate_did(payload["aud"])
|
|
90
|
+
if payload["aud"] == payload["sub"]:
|
|
91
|
+
raise UcanError("omit audience when the subject is the executor")
|
|
92
|
+
validate_command(payload["cmd"])
|
|
93
|
+
_timestamp(payload["exp"])
|
|
94
|
+
if type(payload["args"]) is not dict or type(payload["nonce"]) is not bytes:
|
|
95
|
+
raise UcanError("invalid invocation arguments or nonce")
|
|
96
|
+
links = payload["prf"]
|
|
97
|
+
if type(links) is not list or not 1 <= len(links) <= _MAX_CHAIN:
|
|
98
|
+
raise UcanError("expected a bounded nonempty delegation chain")
|
|
99
|
+
values = dict(payload)
|
|
100
|
+
values["prf"] = tuple(link_cid(link) for link in links)
|
|
101
|
+
if len(set(values["prf"])) != len(links):
|
|
102
|
+
raise UcanError("duplicate delegation proof")
|
|
103
|
+
return cls(**values)
|
|
104
|
+
|
|
105
|
+
def to_payload(self) -> dict:
|
|
106
|
+
payload = {
|
|
107
|
+
"iss": self.iss,
|
|
108
|
+
"sub": self.sub,
|
|
109
|
+
"cmd": self.cmd,
|
|
110
|
+
"args": self.args,
|
|
111
|
+
"nonce": self.nonce,
|
|
112
|
+
"exp": self.exp,
|
|
113
|
+
"prf": [cid_link(cid) for cid in self.prf],
|
|
114
|
+
}
|
|
115
|
+
if self.aud is not None:
|
|
116
|
+
payload["aud"] = self.aud
|
|
117
|
+
self.from_payload(payload)
|
|
118
|
+
return payload
|