vaultdb-client 0.4.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.
- vaultdb_client-0.4.0/PKG-INFO +111 -0
- vaultdb_client-0.4.0/README.md +102 -0
- vaultdb_client-0.4.0/pyproject.toml +17 -0
- vaultdb_client-0.4.0/vaultdb/__init__.py +44 -0
- vaultdb_client-0.4.0/vaultdb/_version.py +4 -0
- vaultdb_client-0.4.0/vaultdb/client.py +199 -0
- vaultdb_client-0.4.0/vaultdb/conform.py +564 -0
- vaultdb_client-0.4.0/vaultdb/crypto.py +97 -0
- vaultdb_client-0.4.0/vaultdb/data/errors.json +36 -0
- vaultdb_client-0.4.0/vaultdb/data/normalize-1.json +7254 -0
- vaultdb_client-0.4.0/vaultdb/envelope.py +167 -0
- vaultdb_client-0.4.0/vaultdb/errors.py +38 -0
- vaultdb_client-0.4.0/vaultdb/frames.py +145 -0
- vaultdb_client-0.4.0/vaultdb/grammar.py +37 -0
- vaultdb_client-0.4.0/vaultdb/keys.py +42 -0
- vaultdb_client-0.4.0/vaultdb/noise.py +150 -0
- vaultdb_client-0.4.0/vaultdb/normalize.py +113 -0
- vaultdb_client-0.4.0/vaultdb/parts.py +157 -0
- vaultdb_client-0.4.0/vaultdb/plain.py +124 -0
- vaultdb_client-0.4.0/vaultdb/records.py +212 -0
- vaultdb_client-0.4.0/vaultdb/session.py +420 -0
- vaultdb_client-0.4.0/vaultdb/tokens.py +74 -0
- vaultdb_client-0.4.0/vaultdb/vault.py +708 -0
- vaultdb_client-0.4.0/vaultdb/wirecheck.py +62 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: vaultdb-client
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Python client for hosted VaultDB (wire 3)
|
|
5
|
+
Requires-Python: >=3.14
|
|
6
|
+
Requires-Dist: cryptography>=48
|
|
7
|
+
Requires-Dist: websockets>=16
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
|
|
10
|
+
# VaultDB for Python
|
|
11
|
+
|
|
12
|
+
Keep your app's data in a hosted VaultDB, and keep the key to yourself. This package seals
|
|
13
|
+
everything on your side before it leaves: the service stores bytes it cannot read, and still
|
|
14
|
+
lets you search them and see exactly who did what.
|
|
15
|
+
|
|
16
|
+
What it does for you:
|
|
17
|
+
|
|
18
|
+
- **Put and get** records, with the fields you want to search on.
|
|
19
|
+
- **Search** with exact or prefix matches. The search is made from a key only you hold.
|
|
20
|
+
- **Files of any size** up to 1 GiB, sent and read in 4 MiB parts, so a big file never sits whole
|
|
21
|
+
in memory. A put that breaks half way can be repeated and sends only what is missing.
|
|
22
|
+
- **An audit trail** of who read and wrote what.
|
|
23
|
+
|
|
24
|
+
It needs Python 3.14 and the `cryptography` package (it brings `websockets` along). It is
|
|
25
|
+
written with `asyncio`: every call is a coroutine, and many can run at once on one connection.
|
|
26
|
+
|
|
27
|
+
Install it:
|
|
28
|
+
|
|
29
|
+
```
|
|
30
|
+
pip install vaultdb-client
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Try it without an account
|
|
34
|
+
|
|
35
|
+
The test server keeps everything in memory and prints its service card on its first line:
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
vaultdb-hosted --memory
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Copy that line into `service-card.json`. Make your service key once with
|
|
42
|
+
`vaultdb.generate_service_key()`, and keep its `secret` in `service-key.hex` as hex. Then:
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
import asyncio
|
|
46
|
+
import io
|
|
47
|
+
import json
|
|
48
|
+
|
|
49
|
+
import vaultdb
|
|
50
|
+
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
async def main(card: dict, secret: bytes) -> None:
|
|
54
|
+
# Your vault's key: 32 bytes made on your side. The service never sees it.
|
|
55
|
+
k = Scrypt(salt=b"my app, vault 1", length=32, n=2**14, r=8, p=1).derive(
|
|
56
|
+
b"a long passphrase only the app knows")
|
|
57
|
+
|
|
58
|
+
async with await vaultdb.connect(card, secret) as conn:
|
|
59
|
+
declaration = {"types": {"note": {"parents": [""], "fields": {"title": {"exact": True}, "text": {}}}}}
|
|
60
|
+
vault = await conn.create_vault(k, declaration, actor="alice")
|
|
61
|
+
|
|
62
|
+
# Put a note: "indexed" values can be searched, the bytes are yours.
|
|
63
|
+
note = vaultdb.Item("note", {"title": "Hello"}, b"my first note")
|
|
64
|
+
put = await vault.put(note, actor="alice")
|
|
65
|
+
|
|
66
|
+
# Search it back.
|
|
67
|
+
found = await vault.search("note", [vaultdb.Condition("title", "exact", "Hello")], actor="alice")
|
|
68
|
+
print("found:", found.items[0].app.decode())
|
|
69
|
+
|
|
70
|
+
# Put a file on the note, and read it back into any file-like object.
|
|
71
|
+
data = b"the contents of a file" * 1000
|
|
72
|
+
await vault.file_put(put.id, note.crid, io.BytesIO(data), len(data),
|
|
73
|
+
name="hello.txt", type="text/plain", actor="alice")
|
|
74
|
+
listing = await vault.file_list(put.id, note.crid, actor="alice")
|
|
75
|
+
out = io.BytesIO()
|
|
76
|
+
await vault.file_read(listing.items[0].info, note.crid, out, actor="alice")
|
|
77
|
+
print("file:", listing.items[0].meta.name, len(out.getvalue()), "bytes")
|
|
78
|
+
|
|
79
|
+
# Who did what: the audit trail.
|
|
80
|
+
for event in (await vault.audit_read(actor="alice")).events:
|
|
81
|
+
print("audit:", event.actor, event.op)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
if __name__ == "__main__":
|
|
85
|
+
card = json.load(open("service-card.json")) # the card your service gave you
|
|
86
|
+
secret = bytes.fromhex(open("service-key.hex").read().strip()) # from vaultdb.generate_service_key()
|
|
87
|
+
asyncio.run(main(card, secret))
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
This example is also one of our tests, so it keeps working.
|
|
91
|
+
|
|
92
|
+
## Good to know
|
|
93
|
+
|
|
94
|
+
- **Every call takes `actor=`**, the name of whoever does it in your app (1 to 128 bytes). It lands
|
|
95
|
+
in the audit trail.
|
|
96
|
+
- **Files:** `file_put(entry, record_crid, source, size, ...)` takes a seekable binary file object
|
|
97
|
+
and its size. To be able to repeat a put that broke, pass `resume=vaultdb.FileUpload()` and give
|
|
98
|
+
the same object again. `file_read` writes into any object with `write(bytes)`. When it raises,
|
|
99
|
+
throw away what it wrote: the bytes are good only when it returns.
|
|
100
|
+
- **A new node key needs no new card.** When the service's key changes, or the service moves to its
|
|
101
|
+
replica, `connect` follows by itself. To keep the change for next time, pass
|
|
102
|
+
`on_card_change=` to `vaultdb.connect(...)`: it is called once with the whole card as JSON
|
|
103
|
+
bytes, and `conn.card()` gives the current card at any time. Save it where you keep your card;
|
|
104
|
+
the library writes and fetches nothing. A card may also name a `replica` (`url` and `server_key`).
|
|
105
|
+
- **Errors** are `vaultdb.VaultDBError`, with a `code` (such as `CLAV-STOR-INTEGRITY`), a `detail`
|
|
106
|
+
and a `next` that says what to do.
|
|
107
|
+
- **A sync program** wraps a call in `asyncio.run(...)`.
|
|
108
|
+
- **Keep your key safe.** Whoever holds it can read the vault, and nobody, including us, can
|
|
109
|
+
get it back for you.
|
|
110
|
+
|
|
111
|
+
The contract this client follows is `wire/SPEC.md` in the VaultDB folder.
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# VaultDB for Python
|
|
2
|
+
|
|
3
|
+
Keep your app's data in a hosted VaultDB, and keep the key to yourself. This package seals
|
|
4
|
+
everything on your side before it leaves: the service stores bytes it cannot read, and still
|
|
5
|
+
lets you search them and see exactly who did what.
|
|
6
|
+
|
|
7
|
+
What it does for you:
|
|
8
|
+
|
|
9
|
+
- **Put and get** records, with the fields you want to search on.
|
|
10
|
+
- **Search** with exact or prefix matches. The search is made from a key only you hold.
|
|
11
|
+
- **Files of any size** up to 1 GiB, sent and read in 4 MiB parts, so a big file never sits whole
|
|
12
|
+
in memory. A put that breaks half way can be repeated and sends only what is missing.
|
|
13
|
+
- **An audit trail** of who read and wrote what.
|
|
14
|
+
|
|
15
|
+
It needs Python 3.14 and the `cryptography` package (it brings `websockets` along). It is
|
|
16
|
+
written with `asyncio`: every call is a coroutine, and many can run at once on one connection.
|
|
17
|
+
|
|
18
|
+
Install it:
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
pip install vaultdb-client
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Try it without an account
|
|
25
|
+
|
|
26
|
+
The test server keeps everything in memory and prints its service card on its first line:
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
vaultdb-hosted --memory
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Copy that line into `service-card.json`. Make your service key once with
|
|
33
|
+
`vaultdb.generate_service_key()`, and keep its `secret` in `service-key.hex` as hex. Then:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
import asyncio
|
|
37
|
+
import io
|
|
38
|
+
import json
|
|
39
|
+
|
|
40
|
+
import vaultdb
|
|
41
|
+
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
async def main(card: dict, secret: bytes) -> None:
|
|
45
|
+
# Your vault's key: 32 bytes made on your side. The service never sees it.
|
|
46
|
+
k = Scrypt(salt=b"my app, vault 1", length=32, n=2**14, r=8, p=1).derive(
|
|
47
|
+
b"a long passphrase only the app knows")
|
|
48
|
+
|
|
49
|
+
async with await vaultdb.connect(card, secret) as conn:
|
|
50
|
+
declaration = {"types": {"note": {"parents": [""], "fields": {"title": {"exact": True}, "text": {}}}}}
|
|
51
|
+
vault = await conn.create_vault(k, declaration, actor="alice")
|
|
52
|
+
|
|
53
|
+
# Put a note: "indexed" values can be searched, the bytes are yours.
|
|
54
|
+
note = vaultdb.Item("note", {"title": "Hello"}, b"my first note")
|
|
55
|
+
put = await vault.put(note, actor="alice")
|
|
56
|
+
|
|
57
|
+
# Search it back.
|
|
58
|
+
found = await vault.search("note", [vaultdb.Condition("title", "exact", "Hello")], actor="alice")
|
|
59
|
+
print("found:", found.items[0].app.decode())
|
|
60
|
+
|
|
61
|
+
# Put a file on the note, and read it back into any file-like object.
|
|
62
|
+
data = b"the contents of a file" * 1000
|
|
63
|
+
await vault.file_put(put.id, note.crid, io.BytesIO(data), len(data),
|
|
64
|
+
name="hello.txt", type="text/plain", actor="alice")
|
|
65
|
+
listing = await vault.file_list(put.id, note.crid, actor="alice")
|
|
66
|
+
out = io.BytesIO()
|
|
67
|
+
await vault.file_read(listing.items[0].info, note.crid, out, actor="alice")
|
|
68
|
+
print("file:", listing.items[0].meta.name, len(out.getvalue()), "bytes")
|
|
69
|
+
|
|
70
|
+
# Who did what: the audit trail.
|
|
71
|
+
for event in (await vault.audit_read(actor="alice")).events:
|
|
72
|
+
print("audit:", event.actor, event.op)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
if __name__ == "__main__":
|
|
76
|
+
card = json.load(open("service-card.json")) # the card your service gave you
|
|
77
|
+
secret = bytes.fromhex(open("service-key.hex").read().strip()) # from vaultdb.generate_service_key()
|
|
78
|
+
asyncio.run(main(card, secret))
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
This example is also one of our tests, so it keeps working.
|
|
82
|
+
|
|
83
|
+
## Good to know
|
|
84
|
+
|
|
85
|
+
- **Every call takes `actor=`**, the name of whoever does it in your app (1 to 128 bytes). It lands
|
|
86
|
+
in the audit trail.
|
|
87
|
+
- **Files:** `file_put(entry, record_crid, source, size, ...)` takes a seekable binary file object
|
|
88
|
+
and its size. To be able to repeat a put that broke, pass `resume=vaultdb.FileUpload()` and give
|
|
89
|
+
the same object again. `file_read` writes into any object with `write(bytes)`. When it raises,
|
|
90
|
+
throw away what it wrote: the bytes are good only when it returns.
|
|
91
|
+
- **A new node key needs no new card.** When the service's key changes, or the service moves to its
|
|
92
|
+
replica, `connect` follows by itself. To keep the change for next time, pass
|
|
93
|
+
`on_card_change=` to `vaultdb.connect(...)`: it is called once with the whole card as JSON
|
|
94
|
+
bytes, and `conn.card()` gives the current card at any time. Save it where you keep your card;
|
|
95
|
+
the library writes and fetches nothing. A card may also name a `replica` (`url` and `server_key`).
|
|
96
|
+
- **Errors** are `vaultdb.VaultDBError`, with a `code` (such as `CLAV-STOR-INTEGRITY`), a `detail`
|
|
97
|
+
and a `next` that says what to do.
|
|
98
|
+
- **A sync program** wraps a call in `asyncio.run(...)`.
|
|
99
|
+
- **Keep your key safe.** Whoever holds it can read the vault, and nobody, including us, can
|
|
100
|
+
get it back for you.
|
|
101
|
+
|
|
102
|
+
The contract this client follows is `wire/SPEC.md` in the VaultDB folder.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "vaultdb-client"
|
|
7
|
+
version = "0.4.0"
|
|
8
|
+
description = "Python client for hosted VaultDB (wire 3)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.14"
|
|
11
|
+
dependencies = ["cryptography>=48", "websockets>=16"]
|
|
12
|
+
|
|
13
|
+
[tool.setuptools]
|
|
14
|
+
packages = ["vaultdb"]
|
|
15
|
+
|
|
16
|
+
[tool.setuptools.package-data]
|
|
17
|
+
vaultdb = ["data/*.json"]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Python client for hosted VaultDB, wire 3 (SPEC.md in core/vaultdb/wire).
|
|
2
|
+
|
|
3
|
+
`connect` a service card with the service key's secret, then `open_vault` or `create_vault`; every
|
|
4
|
+
operation is a coroutine of the vault handle (asyncio) and takes the `actor`. Keys, the seal,
|
|
5
|
+
search tokens, parts and frames are public too, for the apps that need them."""
|
|
6
|
+
|
|
7
|
+
from ._version import VERSION as __version__
|
|
8
|
+
from .client import Connection, ServiceKey, connect, generate_service_key
|
|
9
|
+
from .envelope import (
|
|
10
|
+
event_subject,
|
|
11
|
+
file_meta_subject,
|
|
12
|
+
file_part_subject,
|
|
13
|
+
open_envelope,
|
|
14
|
+
open_record,
|
|
15
|
+
record_subject,
|
|
16
|
+
seal,
|
|
17
|
+
seal_record,
|
|
18
|
+
)
|
|
19
|
+
from .errors import VaultDBError
|
|
20
|
+
from .frames import FRAME_MAX, Frame, decode_frame, encode_frame
|
|
21
|
+
from .keys import event_key, file_key, generate_id, index_key, outer_key, record_key
|
|
22
|
+
from .normalize import TABLE_SHA256_HEX, normalize
|
|
23
|
+
from .parts import PART_SIZE, check_file, open_part, part_count, seal_part, split_parts
|
|
24
|
+
from .records import (
|
|
25
|
+
AppEvent, AuditEvent, AuditHead, AuditPage, BatchResult, Condition, FileEntry, FileInfo, FilePut,
|
|
26
|
+
FileUpload, Grant, Item, Page, PutResult, Record, SearchPage, VaultInfo, VaultRef,
|
|
27
|
+
)
|
|
28
|
+
from .parts import FileMeta
|
|
29
|
+
from .plain import PlainStatement, PlainTable, PlainValue
|
|
30
|
+
from .session import Card
|
|
31
|
+
from .tokens import bucket_token, exact_token, final_check, search_token
|
|
32
|
+
from .vault import Vault
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"FRAME_MAX", "PART_SIZE", "TABLE_SHA256_HEX", "AppEvent", "AuditEvent", "AuditHead", "AuditPage",
|
|
36
|
+
"BatchResult", "Card", "Condition", "Connection", "FileEntry", "FileInfo", "FileMeta", "FilePut",
|
|
37
|
+
"FileUpload", "Frame", "Grant", "Item", "Page", "PlainStatement", "PlainTable", "PlainValue", "PutResult",
|
|
38
|
+
"Record", "SearchPage", "ServiceKey", "Vault", "VaultDBError", "VaultInfo", "VaultRef",
|
|
39
|
+
"bucket_token", "check_file", "connect", "decode_frame", "encode_frame", "event_key", "event_subject",
|
|
40
|
+
"exact_token", "file_key", "file_meta_subject", "file_part_subject", "final_check", "generate_id",
|
|
41
|
+
"generate_service_key", "index_key", "normalize", "open_envelope", "open_part", "open_record",
|
|
42
|
+
"outer_key", "part_count", "record_key", "record_subject", "seal", "seal_part", "seal_record",
|
|
43
|
+
"search_token", "split_parts",
|
|
44
|
+
]
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""A connection to hosted VaultDB: the service card, the secret, the session behind it, and the
|
|
2
|
+
calls that need no vault (SPEC §1, §3, §8.1).
|
|
3
|
+
|
|
4
|
+
Calls are safe to make at the same time from many tasks: they share one session (one WebSocket,
|
|
5
|
+
one Noise session) and run independently. When the session has dropped, the next call opens a
|
|
6
|
+
new one (§1, §6); callers that race that share one handshake. A call is never retried here:
|
|
7
|
+
`retry_after_ms` is on the error, and every write is idempotent by its ids (§1)."""
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from dataclasses import dataclass, replace
|
|
11
|
+
from typing import Any, AsyncIterator, Callable
|
|
12
|
+
|
|
13
|
+
from . import crypto, keys
|
|
14
|
+
from .errors import VaultDBError
|
|
15
|
+
from .records import Page, VaultRef
|
|
16
|
+
from .session import HOME, REKEYED, Card, KeyAnswer, Replica, Session, card_json, check_followed_key, check_secret, parse_card
|
|
17
|
+
from .vault import Vault, check_actor, check_declaration
|
|
18
|
+
from .wirecheck import b64e, integer, items, obj, optional_text, text
|
|
19
|
+
from .grammar import check_uint, check_vault
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class ServiceKey:
|
|
24
|
+
"""A service key (§2): `secret` is the 32 bytes the app keeps; `public` is the 65-byte
|
|
25
|
+
identity the operator registers (SERVER.md §6)."""
|
|
26
|
+
|
|
27
|
+
secret: bytes
|
|
28
|
+
public: bytes
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def generate_service_key() -> ServiceKey:
|
|
32
|
+
"""GenerateServiceKey (§2): a fresh P-256 key from the platform's randomness."""
|
|
33
|
+
key = crypto.p256_generate()
|
|
34
|
+
return ServiceKey(crypto.p256_secret(key), crypto.p256_public_bytes(key))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Connection:
|
|
38
|
+
"""The channel to one POP. Make one with `connect`."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self, card: Card, secret: bytes, on_card_change: Callable[[bytes], Any] | None = None,
|
|
42
|
+
) -> None:
|
|
43
|
+
self._card = card # this connection's own copy; the app's card is never touched (§3.5)
|
|
44
|
+
self._secret = secret
|
|
45
|
+
self._on_card_change = on_card_change
|
|
46
|
+
self._session: Session | None = None
|
|
47
|
+
self._connect_lock = asyncio.Lock()
|
|
48
|
+
self._closed = False
|
|
49
|
+
|
|
50
|
+
def card(self) -> bytes:
|
|
51
|
+
"""The connection's current card as JSON text (§3.5): the one to save after the hook."""
|
|
52
|
+
return card_json(self._card)
|
|
53
|
+
|
|
54
|
+
async def _ready(self) -> Session:
|
|
55
|
+
if self._closed:
|
|
56
|
+
raise VaultDBError("CLAV-NET-DROPPED", retry_after_ms=1000)
|
|
57
|
+
session = self._session
|
|
58
|
+
if session is None or session.closed:
|
|
59
|
+
changed: bytes | None = None
|
|
60
|
+
async with self._connect_lock:
|
|
61
|
+
session = self._session
|
|
62
|
+
if session is None or session.closed:
|
|
63
|
+
before = card_json(self._card)
|
|
64
|
+
session, card = await self._dial(self._card)
|
|
65
|
+
self._session = session
|
|
66
|
+
self._card = card
|
|
67
|
+
if card_json(card) != before:
|
|
68
|
+
changed = card_json(card)
|
|
69
|
+
if changed is not None and self._on_card_change is not None:
|
|
70
|
+
# after the new card is in place, outside the lock; the hook's failure is the app's (§3.5)
|
|
71
|
+
try:
|
|
72
|
+
self._on_card_change(changed)
|
|
73
|
+
except Exception:
|
|
74
|
+
pass
|
|
75
|
+
return session
|
|
76
|
+
|
|
77
|
+
async def _dial(self, card: Card) -> tuple[Session, Card]:
|
|
78
|
+
"""Connect's steps 1 to 5 (§3.5): at most one new key and three handshakes, all before any
|
|
79
|
+
call. Nothing of a failed Connect is kept: the caller sets the card only on success."""
|
|
80
|
+
try:
|
|
81
|
+
session, replica = await Session.open(card.url, card.server_key, card.service, self._secret)
|
|
82
|
+
return session, _with_welcome_replica(card, replica)
|
|
83
|
+
except KeyAnswer as answer:
|
|
84
|
+
if answer.code == HOME:
|
|
85
|
+
raise VaultDBError("CLAV-NET-HANDSHAKE") from None # §15 [rs 1]
|
|
86
|
+
key = check_followed_key(answer.server_key, card.server_key) # step 2
|
|
87
|
+
followed = replace(card, server_key=key)
|
|
88
|
+
return await self._after_key(followed, followed.url, key)
|
|
89
|
+
except VaultDBError as first:
|
|
90
|
+
if first.code not in ("CLAV-NET-HANDSHAKE", "CLAV-NET-UNREACHABLE") or card.replica is None:
|
|
91
|
+
raise
|
|
92
|
+
via = await self._via_replica(card, card.replica)
|
|
93
|
+
if via is None:
|
|
94
|
+
raise first # step 3: "Connect fails with step 1's error"
|
|
95
|
+
return via
|
|
96
|
+
|
|
97
|
+
async def _after_key(self, card: Card, url: str, key: bytes) -> tuple[Session, Card]:
|
|
98
|
+
"""Step 4: the handshake after a key was taken must end in Welcome; anything else, an
|
|
99
|
+
unreachable socket included, is CLAV-NET-HANDSHAKE (§15 [rs 4])."""
|
|
100
|
+
try:
|
|
101
|
+
session, replica = await Session.open(url, key, card.service, self._secret)
|
|
102
|
+
except VaultDBError:
|
|
103
|
+
raise VaultDBError("CLAV-NET-HANDSHAKE") from None
|
|
104
|
+
return session, _with_welcome_replica(card, replica)
|
|
105
|
+
|
|
106
|
+
async def _via_replica(self, card: Card, replica: Replica) -> tuple[Session, Card] | None:
|
|
107
|
+
"""Step 3: one handshake with the replica. None is "anything else, or a check that fails"
|
|
108
|
+
(the caller then fails with step 1's error); once a key is taken, step 4 rules."""
|
|
109
|
+
try:
|
|
110
|
+
session, welcome_replica = await Session.open(replica.url, replica.server_key, card.service, self._secret)
|
|
111
|
+
except KeyAnswer as answer:
|
|
112
|
+
if answer.code == REKEYED:
|
|
113
|
+
return None
|
|
114
|
+
try:
|
|
115
|
+
key = check_followed_key(answer.server_key, card.server_key) # §15 [46]
|
|
116
|
+
except VaultDBError:
|
|
117
|
+
return None
|
|
118
|
+
return await self._after_key(replace(card, server_key=key), card.url, key)
|
|
119
|
+
except VaultDBError:
|
|
120
|
+
return None
|
|
121
|
+
# promoted (SERVER §6): the replica is the home now; its Welcome's replica, or none (§15 [46])
|
|
122
|
+
return session, Card(replica.url, replica.server_key, card.service, welcome_replica)
|
|
123
|
+
|
|
124
|
+
async def request(self, head: dict[str, Any]) -> dict[str, Any]:
|
|
125
|
+
"""One call; the result's head."""
|
|
126
|
+
result, _tail = await (await self._ready()).request(head)
|
|
127
|
+
return result
|
|
128
|
+
|
|
129
|
+
async def request_tail(self, head: dict[str, Any], tail: bytes) -> tuple[dict[str, Any], bytes]:
|
|
130
|
+
"""One call with a tail (file.part) and the result's tail (file.read)."""
|
|
131
|
+
return await (await self._ready()).request(head, tail)
|
|
132
|
+
|
|
133
|
+
async def stream(self, head: dict[str, Any]) -> AsyncIterator[dict[str, Any]]:
|
|
134
|
+
async for item in (await self._ready()).stream(head):
|
|
135
|
+
yield item
|
|
136
|
+
|
|
137
|
+
async def close(self) -> None:
|
|
138
|
+
"""End the session for good; calls in flight fail with CLAV-NET-DROPPED."""
|
|
139
|
+
self._closed = True
|
|
140
|
+
if self._session is not None:
|
|
141
|
+
await self._session.close()
|
|
142
|
+
|
|
143
|
+
async def __aenter__(self) -> "Connection":
|
|
144
|
+
return self
|
|
145
|
+
|
|
146
|
+
async def __aexit__(self, *exc: object) -> None:
|
|
147
|
+
await self.close()
|
|
148
|
+
|
|
149
|
+
# ---- calls that need no vault ----------------------------------------------------------
|
|
150
|
+
|
|
151
|
+
async def ping(self, *, actor: str) -> int:
|
|
152
|
+
"""ping: the server's time, unix ms."""
|
|
153
|
+
result = obj(await self.request({"op": "ping", "actor": check_actor(actor)}), frozenset({"time"}))
|
|
154
|
+
return integer(result, "time")
|
|
155
|
+
|
|
156
|
+
async def list_vaults(self, *, actor: str, after: str | None = None) -> Page[VaultRef]:
|
|
157
|
+
"""vault.list: this service's vaults on this POP, and those it holds a grant in."""
|
|
158
|
+
head: dict[str, Any] = {"op": "vault.list", "actor": check_actor(actor)}
|
|
159
|
+
if after is not None:
|
|
160
|
+
head["after"] = after
|
|
161
|
+
result = obj(await self.request(head), frozenset({"vaults", "next"}))
|
|
162
|
+
refs = []
|
|
163
|
+
for raw in items(result, "vaults"):
|
|
164
|
+
ref = obj(raw, frozenset({"vault", "role"}))
|
|
165
|
+
refs.append(VaultRef(check_vault(text(ref, "vault")), text(ref, "role")))
|
|
166
|
+
return Page(refs, optional_text(result, "next"))
|
|
167
|
+
|
|
168
|
+
async def open_vault(self, vault_id: str, k: bytes, *, actor: str) -> Vault:
|
|
169
|
+
"""OpenVault (§1): checks `K`, reads vault.info, holds the declaration and revision."""
|
|
170
|
+
vault = Vault(self, vault_id, k, {}, 0)
|
|
171
|
+
await vault.info(actor=actor)
|
|
172
|
+
return vault
|
|
173
|
+
|
|
174
|
+
async def create_vault(self, k: bytes, declaration: dict[str, Any], *, actor: str) -> Vault:
|
|
175
|
+
"""CreateVault (§1): vault.create with this vault's L1, the same handle as OpenVault."""
|
|
176
|
+
check_declaration(declaration)
|
|
177
|
+
head = {"op": "vault.create", "actor": check_actor(actor), "declaration": declaration,
|
|
178
|
+
"key": b64e(keys.outer_key(k))}
|
|
179
|
+
result = obj(await self.request(head), frozenset({"vault", "revision"}))
|
|
180
|
+
return Vault(self, check_vault(text(result, "vault")), k, declaration, check_uint(integer(result, "revision"), 53))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _with_welcome_replica(card: Card, replica: Replica | None) -> Card:
|
|
184
|
+
"""Step 5: a Welcome without `replica` leaves the card's as it is (§15 [rs 3])."""
|
|
185
|
+
return card if replica is None else replace(card, replica=replica)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
async def connect(
|
|
189
|
+
card: "str | bytes | dict[str, Any] | Card", secret: bytes,
|
|
190
|
+
on_card_change: Callable[[bytes], Any] | None = None,
|
|
191
|
+
) -> Connection:
|
|
192
|
+
"""Connect (§3.1, §3.5): checks the card, opens the WebSocket, handshakes, and follows a new
|
|
193
|
+
node key or the replica. `secret` is the service key's 32 bytes (`generate_service_key`).
|
|
194
|
+
`on_card_change(card_json_bytes)` is called once, before this returns, when the card changed;
|
|
195
|
+
save what it gets where you keep your card. The library writes and fetches no card."""
|
|
196
|
+
parsed = parse_card(card)
|
|
197
|
+
connection = Connection(parsed, check_secret(secret), on_card_change)
|
|
198
|
+
await connection._ready()
|
|
199
|
+
return connection
|