|
| 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) |
0 commit comments