Skip to content

Commit b4efdbe

Browse files
rustyconoverclaude
andcommitted
fix: seal framework payloads before they reach FunctionStorage
The buffered-table init (the whole InitRequest, including bind_call.secrets and the attach/transaction context), aggregate constant arguments and the streaming-aggregate session were written to shared storage (SQLite file, Azure SQL, Cloudflare DO) in plaintext, and the init was pickled, so a value tampered with in a network store reached pickle.loads. They are now sealed with sealed framework payload v1, the format every SDK shares: AES-256-GCM under HKDF-SHA256(signing key, info "vgi.storage.payload.v1") (host-local key file without a signing key), AAD binding shard, execution id, namespace and key, wire 0x01 || nonce || ct || tag. A payload that fails to open is an OSError (StoragePayloadError), never a plaintext fallback. The init now uses a length-prefixed framing instead of pickle; the streaming session still pickles the user's opaque state object, but only unpickles after the AEAD check. The init cache holds sealed bytes and opens them per use. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzrG3FzSh28NiZ8UnVtRbk
1 parent 32e1df6 commit b4efdbe

5 files changed

Lines changed: 506 additions & 38 deletions

File tree

‎docs/shared-storage.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,3 +201,28 @@ Assign it to your function classes:
201201
class MyFunction(TableFunctionGenerator):
202202
storage = MyCustomStorage()
203203
```
204+
205+
## Sealed Framework Payloads
206+
207+
The framework stores some of its own context so that any worker process can
208+
serve any RPC of an execution:
209+
210+
- a buffered table function's init request, including its resolved secrets and the attach and transaction context;
211+
- aggregate constant arguments;
212+
- the streaming-aggregate session.
213+
214+
These are always written sealed (`vgi._storage_seal`, sealed framework payload v1):
215+
216+
- **Cipher:** AES-256-GCM under `HKDF-SHA256(signing key, info="vgi.storage.payload.v1")`.
217+
- **Associated data:** bound to the shard, execution id, namespace and key.
218+
- **Envelope:** `0x01 || nonce(12) || ciphertext || tag(16)`.
219+
220+
A worker with no signing key (subprocess and unix transports) uses the
221+
per-user host-local key file that secret ATTACH options use. Every process
222+
serving one deployment must therefore share `VGI_SIGNING_KEY`, which
223+
multi-machine HTTP deployments already require. A payload that fails to
224+
open is an error, never a plaintext fallback.
225+
226+
What your functions write themselves (`process()` appends, aggregate states,
227+
window partitions, finalize output, work-queue items) is your data and is
228+
stored as written, unsealed.

‎tests/test_storage_seal.py‎

Lines changed: 189 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,189 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Framework payloads are sealed before they reach FunctionStorage."""
4+
5+
from __future__ import annotations
6+
7+
import pickle
8+
from pathlib import Path
9+
from typing import Any
10+
11+
import pyarrow as pa
12+
import pytest
13+
14+
import vgi.worker as worker_mod
15+
from vgi import attach_secret_options
16+
from vgi._storage_seal import StoragePayloadError, open_payload, seal_payload
17+
from vgi.function_storage import BoundStorage, FrameworkNS, FunctionStorageSqlite
18+
19+
_SIGNING_KEY = b"k" * 43
20+
_OTHER_KEY = b"z" * 43
21+
_SLOT: dict[str, Any] = {"shard_key": "att-0123", "scope_id": b"\x01" * 16, "ns": b"_vgi/buffering_init", "key": b"k"}
22+
23+
24+
@pytest.fixture(autouse=True)
25+
def _host_local_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
26+
"""Point the host-local key at a private temp file and forget cached roots."""
27+
monkeypatch.setenv("VGI_ATTACH_SECRET_KEY_FILE", str(tmp_path / "host.key"))
28+
monkeypatch.setattr(attach_secret_options, "_host_local_cache", {})
29+
monkeypatch.setattr(attach_secret_options, "_explicit_root", None)
30+
monkeypatch.setattr(attach_secret_options, "_signing_root", None)
31+
32+
33+
@pytest.mark.parametrize("signing_key", [_SIGNING_KEY, None], ids=["signing-key", "host-local"])
34+
def test_round_trip(signing_key: bytes | None) -> None:
35+
"""A payload opens for the same slot and key."""
36+
sealed = seal_payload(b"secret context", signing_key=signing_key, **_SLOT)
37+
assert b"secret context" not in sealed
38+
assert sealed[0] == 0x01
39+
assert len(sealed) == 1 + 12 + len(b"secret context") + 16
40+
assert open_payload(sealed, signing_key=signing_key, **_SLOT) == b"secret context"
41+
42+
43+
def test_tampered_refused() -> None:
44+
"""Flipping any byte fails authentication."""
45+
sealed = bytearray(seal_payload(b"payload", signing_key=_SIGNING_KEY, **_SLOT))
46+
sealed[-1] ^= 1
47+
with pytest.raises(StoragePayloadError, match="failed authentication"):
48+
open_payload(bytes(sealed), signing_key=_SIGNING_KEY, **_SLOT)
49+
50+
51+
@pytest.mark.parametrize(
52+
"field,value",
53+
[("scope_id", b"\x02" * 16), ("key", b"other"), ("ns", b"_vgi/aggregate_state"), ("shard_key", "att-9999")],
54+
)
55+
def test_moved_payload_refused(field: str, value: Any) -> None:
56+
"""The AAD binds the slot: another execution, key, namespace or shard fails."""
57+
sealed = seal_payload(b"payload", signing_key=_SIGNING_KEY, **_SLOT)
58+
with pytest.raises(StoragePayloadError):
59+
open_payload(sealed, signing_key=_SIGNING_KEY, **{**_SLOT, field: value})
60+
61+
62+
def test_wrong_key_refused() -> None:
63+
"""A payload sealed under another signing key fails."""
64+
sealed = seal_payload(b"payload", signing_key=_SIGNING_KEY, **_SLOT)
65+
with pytest.raises(StoragePayloadError):
66+
open_payload(sealed, signing_key=_OTHER_KEY, **_SLOT)
67+
68+
69+
def test_unknown_version_and_short_refused() -> None:
70+
"""An unknown version byte or a truncated envelope is refused, never treated as plaintext."""
71+
sealed = seal_payload(b"payload", signing_key=_SIGNING_KEY, **_SLOT)
72+
with pytest.raises(StoragePayloadError, match="unknown seal version"):
73+
open_payload(b"\x02" + sealed[1:], signing_key=_SIGNING_KEY, **_SLOT)
74+
with pytest.raises(StoragePayloadError, match="too short"):
75+
open_payload(sealed[:20], signing_key=_SIGNING_KEY, **_SLOT)
76+
77+
78+
def test_host_local_and_signing_keys_do_not_cross() -> None:
79+
"""A payload sealed with the host-local key does not open under a signing key."""
80+
sealed = seal_payload(b"payload", signing_key=None, **_SLOT)
81+
with pytest.raises(StoragePayloadError):
82+
open_payload(sealed, signing_key=_SIGNING_KEY, **_SLOT)
83+
84+
85+
# Cross-SDK test vector for sealed framework payload v1 (Go/Java/TS/Rust check
86+
# the same bytes). AES-256-GCM is deterministic for a fixed key and nonce.
87+
VECTOR: dict[str, Any] = {
88+
"ikm": b"vgi-test-signing-key-0123456789abcdef",
89+
"shard_key": "att-00112233445566778899aabbccddeeff",
90+
"scope_id": bytes(range(16)),
91+
"ns": b"_vgi/buffering_init",
92+
"key": BoundStorage.pack_int_key(-1),
93+
"nonce": bytes(range(12)),
94+
"plaintext": b"vgi sealed framework payload v1",
95+
}
96+
VECTOR_DERIVED_KEY_HEX = "f5f759ad2009e91cf4b963a20b524a800224d2ac4e01472396dc1a2dab78bea9"
97+
VECTOR_AAD_HEX = (
98+
"7667692e73746f726167652e7061796c6f61642e7631000000246174742d30303131323233333434353536363737383839396161"
99+
"6262636364646565666600000010000102030405060708090a0b0c0d0e0f000000135f7667692f627566666572696e675f696e6974"
100+
"00000008ffffffffffffffff"
101+
)
102+
VECTOR_WIRE_HEX = (
103+
"01000102030405060708090a0bc79698647483a87eb533cf7332d1c527275cc7470dc6a3bdf1f72f624a97e246416d4de55281bd0eee"
104+
"6d6491796a40"
105+
)
106+
107+
108+
def test_cross_sdk_vector() -> None:
109+
"""The fixed vector seals to the published bytes and opens back."""
110+
from vgi._storage_seal import aad, derive_key, open_with, seal_with
111+
112+
v = VECTOR
113+
slot = {"shard_key": v["shard_key"], "scope_id": v["scope_id"], "ns": v["ns"], "key": v["key"]}
114+
assert derive_key(v["ikm"]).hex() == VECTOR_DERIVED_KEY_HEX
115+
assert aad(**slot).hex() == VECTOR_AAD_HEX
116+
wire = seal_with(v["plaintext"], v["ikm"], nonce=v["nonce"], **slot)
117+
assert wire.hex() == VECTOR_WIRE_HEX
118+
assert open_with(bytes.fromhex(VECTOR_WIRE_HEX), v["ikm"], **slot) == v["plaintext"]
119+
120+
121+
def test_unsealed_legacy_payload_refused() -> None:
122+
"""An old pickled (unsealed) payload fails cleanly, never reaching pickle."""
123+
legacy = pickle.dumps({"init_call_bytes": b"x", "init_response_bytes": b"y"})
124+
with pytest.raises(StoragePayloadError):
125+
open_payload(legacy, signing_key=_SIGNING_KEY, **_SLOT)
126+
with pytest.raises(StoragePayloadError):
127+
open_payload(b"", signing_key=_SIGNING_KEY, **_SLOT)
128+
129+
130+
def _init_payload(secret_value: str) -> tuple[Any, Any]:
131+
"""An InitRequest whose bind_call carries a resolved secret."""
132+
from vgi.arguments import Arguments
133+
from vgi.invocation import FunctionType, GlobalInitResponse
134+
from vgi.protocol import BindRequest, InitRequest
135+
136+
secrets = pa.RecordBatch.from_pydict({"api_token": [secret_value]})
137+
bind = BindRequest(function_name="f", arguments=Arguments(), function_type=FunctionType.TABLE, secrets=secrets)
138+
req = InitRequest(bind_call=bind, output_schema=pa.schema([("a", pa.int64())]))
139+
return req, GlobalInitResponse(execution_id=b"\x03" * 16)
140+
141+
142+
def test_init_framing_has_no_pickle(monkeypatch: pytest.MonkeyPatch) -> None:
143+
"""The buffering-init payload round-trips without pickle."""
144+
145+
def no_pickle(*_a: Any, **_k: Any) -> Any:
146+
raise AssertionError("pickle used on the storage path")
147+
148+
monkeypatch.setattr(pickle, "loads", no_pickle)
149+
monkeypatch.setattr(pickle, "dumps", no_pickle)
150+
req, resp = _init_payload("dummy")
151+
call, response = worker_mod._decode_table_buffering_init(worker_mod._encode_table_buffering_init(req, resp))
152+
assert call.bind_call.function_name == "f"
153+
assert response.execution_id == b"\x03" * 16
154+
with pytest.raises(StoragePayloadError):
155+
worker_mod._decode_table_buffering_init(b"\x80\x05junk")
156+
157+
158+
def test_secret_never_plaintext_in_sqlite(tmp_path: Path) -> None:
159+
"""A sealed init with a dummy secret leaves no plaintext in the SQLite file."""
160+
marker = "DUMMY-SECRET-7f3c9e1d"
161+
db = tmp_path / "storage.db"
162+
backend = FunctionStorageSqlite(db_path=str(db))
163+
storage = BoundStorage(backend, b"\x04" * 16)
164+
req, resp = _init_payload(marker)
165+
plain = worker_mod._encode_table_buffering_init(req, resp)
166+
assert marker.encode() in plain # the secret really is in the payload
167+
key = BoundStorage.pack_int_key(-1)
168+
storage.sealed_put(FrameworkNS.BUFFERING_INIT, key, plain, signing_key=_SIGNING_KEY)
169+
assert storage.sealed_get(FrameworkNS.BUFFERING_INIT, key, signing_key=_SIGNING_KEY) == plain
170+
backend.close()
171+
blob = b"".join(p.read_bytes() for p in tmp_path.glob("storage.db*"))
172+
assert blob # the file (and any WAL) was written
173+
assert marker.encode() not in blob
174+
175+
176+
def test_bound_storage_refuses_payload_from_other_execution(tmp_path: Path) -> None:
177+
"""A sealed value copied between executions in the same backend fails to open."""
178+
backend = FunctionStorageSqlite(db_path=str(tmp_path / "s.db"))
179+
a = BoundStorage(backend, b"\x05" * 16)
180+
b = BoundStorage(backend, b"\x06" * 16)
181+
key = BoundStorage.pack_int_key(-2)
182+
sealed = a.sealed_put(FrameworkNS.AGGREGATE_STATE, key, b"const args", signing_key=_SIGNING_KEY)
183+
b.state_put(FrameworkNS.AGGREGATE_STATE, key, sealed)
184+
with pytest.raises(StoragePayloadError):
185+
b.sealed_get(FrameworkNS.AGGREGATE_STATE, key, signing_key=_SIGNING_KEY)
186+
# An unsealed value written directly is refused too, not passed through.
187+
b.state_put(FrameworkNS.AGGREGATE_STATE, key, b"plain")
188+
with pytest.raises(StoragePayloadError):
189+
b.sealed_get(FrameworkNS.AGGREGATE_STATE, key, signing_key=_SIGNING_KEY)

‎vgi/_storage_seal.py‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
# Copyright 2025, 2026 Query Farm LLC - https://query.farm
2+
3+
"""Authenticated encryption of framework payloads written to FunctionStorage.
4+
5+
The framework persists some of its own context to shared storage so that any
6+
worker process can serve any RPC of an execution: the buffered-table init
7+
(the whole ``InitRequest``, including ``bind_call.secrets``, the resolved
8+
secret values, and the sealed attach and transaction blobs), aggregate
9+
constant arguments, and the streaming-aggregate session. Storage may be a
10+
SQLite file, Azure SQL or a Cloudflare Durable Object reached over the
11+
network, so none of that may sit there in plaintext, and nothing read back
12+
may be trusted unauthenticated.
13+
14+
Sealed framework payload v1 (the same format in every VGI SDK):
15+
16+
* ``K = HKDF-SHA256(ikm, salt=b"", info=b"vgi.storage.payload.v1", L=32)``.
17+
``ikm`` is the worker's signing key exactly as it resolved it (the UTF-8
18+
bytes of ``VGI_SIGNING_KEY``, or of the key ``vgi-serve`` minted and
19+
exported to its children, so a pre-fork pool agrees). A worker with no
20+
signing key (subprocess and unix transports) uses the host-local key file
21+
shared by every VGI worker process of the user on the host, the one secret
22+
ATTACH options use (`vgi.attach_secret_options.host_local_key_path`):
23+
one query's RPCs are spread over several worker processes that share one
24+
SQLite file, so a per-process key would not do.
25+
* AES-256-GCM, random 12-byte nonce, 16-byte tag.
26+
* ``AAD = "vgi.storage.payload.v1" || u32be(len) || shard_key ||
27+
u32be(len) || scope_id || u32be(len) || namespace || u32be(len) || key``:
28+
a payload copied to another execution, slot or attach shard fails to open.
29+
* Wire: ``0x01 || nonce(12) || ciphertext || tag(16)``.
30+
31+
A payload that fails to open (unknown version, wrong length, tampered, wrong
32+
key, moved, or an unsealed value written by an older release) raises
33+
`StoragePayloadError`, an ``OSError`` like the "unknown execution_id" error
34+
the same reads raise when the payload is missing. There is no plaintext
35+
fallback. Executions are short-lived and their ids are never reused, so no
36+
migration of previously stored payloads is needed.
37+
38+
Data user code writes to storage (``process()`` appends, aggregate group
39+
states, window partitions, finalize output, table-in-out state, work queue
40+
items) is the function's own data and is not sealed.
41+
"""
42+
43+
from __future__ import annotations
44+
45+
import functools
46+
import os
47+
48+
from vgi import attach_secret_options as _aso
49+
50+
__all__ = ["INFO", "StoragePayloadError", "open_payload", "seal_payload"]
51+
52+
INFO = b"vgi.storage.payload.v1"
53+
VERSION = 0x01
54+
_KEY_LEN = 32
55+
_NONCE_LEN = 12
56+
_TAG_LEN = 16
57+
58+
59+
class StoragePayloadError(OSError):
60+
"""A framework payload read from storage could not be authenticated."""
61+
62+
63+
@functools.lru_cache(maxsize=16)
64+
def derive_key(ikm: bytes) -> bytes:
65+
"""``HKDF-SHA256(ikm, salt="", info="vgi.storage.payload.v1", 32)``."""
66+
from Crypto.Hash import SHA256
67+
from Crypto.Protocol.KDF import HKDF
68+
69+
key = HKDF(ikm, _KEY_LEN, b"", SHA256, context=INFO)
70+
assert isinstance(key, bytes)
71+
return key
72+
73+
74+
def _lp(b: bytes) -> bytes:
75+
return len(b).to_bytes(4, "big") + b
76+
77+
78+
def aad(shard_key: str, scope_id: bytes, ns: bytes, key: bytes) -> bytes:
79+
"""The associated data binding a payload to its storage slot."""
80+
return INFO + _lp(shard_key.encode()) + _lp(bytes(scope_id)) + _lp(bytes(ns)) + _lp(bytes(key))
81+
82+
83+
def _ikm(signing_key: bytes | None) -> bytes:
84+
if signing_key is not None:
85+
return bytes(signing_key)
86+
return _aso._load_host_local_key()
87+
88+
89+
def seal_with(
90+
payload: bytes, ikm: bytes, *, shard_key: str, scope_id: bytes, ns: bytes, key: bytes, nonce: bytes | None = None
91+
) -> bytes:
92+
"""Seal under an explicit ``ikm`` (``nonce`` only for test vectors)."""
93+
from Crypto.Cipher import AES
94+
95+
nonce = os.urandom(_NONCE_LEN) if nonce is None else nonce
96+
if len(nonce) != _NONCE_LEN:
97+
raise ValueError("nonce must be 12 bytes")
98+
cipher = AES.new(derive_key(ikm), AES.MODE_GCM, nonce=nonce, mac_len=_TAG_LEN)
99+
cipher.update(aad(shard_key, scope_id, ns, key))
100+
ciphertext, tag = cipher.encrypt_and_digest(payload)
101+
return bytes([VERSION]) + nonce + ciphertext + tag
102+
103+
104+
def open_with(blob: bytes, ikm: bytes, *, shard_key: str, scope_id: bytes, ns: bytes, key: bytes) -> bytes:
105+
"""Open under an explicit ``ikm`` (`StoragePayloadError` on any failure)."""
106+
from Crypto.Cipher import AES
107+
108+
what = f"framework storage payload {bytes(ns)!r} for execution {bytes(scope_id).hex()}"
109+
if len(blob) < 1 + _NONCE_LEN + _TAG_LEN:
110+
raise StoragePayloadError(f"{what} is too short to be a sealed payload")
111+
if blob[0] != VERSION:
112+
raise StoragePayloadError(f"{what} has unknown seal version {blob[0]:#04x}")
113+
nonce, body = blob[1 : 1 + _NONCE_LEN], blob[1 + _NONCE_LEN :]
114+
cipher = AES.new(derive_key(ikm), AES.MODE_GCM, nonce=nonce, mac_len=_TAG_LEN)
115+
cipher.update(aad(shard_key, scope_id, ns, key))
116+
try:
117+
return bytes(cipher.decrypt_and_verify(body[:-_TAG_LEN], body[-_TAG_LEN:]))
118+
except ValueError as exc:
119+
msg = f"{what} failed authentication (tampered, moved, or sealed under another key)"
120+
raise StoragePayloadError(msg) from exc
121+
122+
123+
def seal_payload(
124+
payload: bytes,
125+
*,
126+
signing_key: bytes | None,
127+
shard_key: str,
128+
scope_id: bytes,
129+
ns: bytes,
130+
key: bytes,
131+
) -> bytes:
132+
"""Seal a framework payload bound to its storage slot.
133+
134+
Args:
135+
payload: The plaintext bytes.
136+
signing_key: The worker's signing key, or None (subprocess / unix).
137+
shard_key: The attach shard the slot lives in.
138+
scope_id: The execution (or transaction) id.
139+
ns: The storage namespace.
140+
key: The key within the namespace.
141+
142+
Returns:
143+
The envelope to store.
144+
"""
145+
return seal_with(payload, _ikm(signing_key), shard_key=shard_key, scope_id=scope_id, ns=ns, key=key)
146+
147+
148+
def open_payload(
149+
blob: bytes,
150+
*,
151+
signing_key: bytes | None,
152+
shard_key: str,
153+
scope_id: bytes,
154+
ns: bytes,
155+
key: bytes,
156+
) -> bytes:
157+
"""Open an envelope from `seal_payload` for the same slot.
158+
159+
Args:
160+
blob: The stored envelope.
161+
signing_key: The worker's signing key, or None.
162+
shard_key: The attach shard the slot lives in.
163+
scope_id: The execution (or transaction) id.
164+
ns: The storage namespace.
165+
key: The key within the namespace.
166+
167+
Returns:
168+
The plaintext payload.
169+
170+
Raises:
171+
StoragePayloadError: On any failure to authenticate, or when the
172+
host-local key (the no-signing-key case) is unusable.
173+
"""
174+
try:
175+
ikm = _ikm(signing_key)
176+
except _aso.AttachSecretKeyError as exc:
177+
raise StoragePayloadError(f"no key to open framework storage payloads: {exc}") from exc
178+
return open_with(blob, ikm, shard_key=shard_key, scope_id=scope_id, ns=ns, key=key)

0 commit comments

Comments
 (0)