Compare commits

...
Author SHA1 Message Date
sechmachine e58f1c7c48 feat(protocol): negotiate registered gateway profiles
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m29s
2026-07-30 04:47:52 +07:00
sechmachine d26f8b60f8 feat(protocol): carry stream policy and gateway telemetry 2026-07-30 01:45:48 +07:00
sechmachine 59741761ce docs(openspec): archive gateway input feedback contract 2026-07-29 23:02:19 +07:00
sechmachine ebfe07376d fix(protocol): harden gateway contract validation
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m12s
2026-07-29 21:16:53 +07:00
sechmachine 0ea21cd3f2 feat(protocol): define gateway control envelopes 2026-07-29 17:24:18 +07:00
sechmachine 36f6edffca feat(protocol): include Apollo client identity in session work
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m35s
2026-07-29 11:28:25 +07:00
sechmachine 357e5e0dbc feat(protocol): add gateway provider session work
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m30s
2026-07-29 11:10:32 +07:00
sechmachine 4a2772c053 feat(protocol): bind tunnel admission to device proof
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m11s
2026-07-29 10:32:08 +07:00
sechmachine be709724ba feat(protocol): validate generated gateway contracts
Verify Protocol / verify (push) Canceled after 0s
Verify Protocol / module (push) Successful in 2m14s
2026-07-29 10:03:37 +07:00
sechmachine 7c145001c0 docs(protocol): archive gateway contract 2026-07-29 07:00:02 +07:00
sechmachine 28a9aace24 docs(protocol): complete gateway candidate task 2026-07-29 06:43:34 +07:00
sechmachine b5558133e3 feat(protocol): add gateway transport authority contracts 2026-07-29 05:59:46 +07:00
51 changed files with 8187 additions and 366 deletions
+7 -2
View File
@@ -1,4 +1,4 @@
.PHONY: verify generate proto-lint proto-breaking source-verify scope-verify conformance frame-verify go-test binding-compile clean-generated
.PHONY: verify generate proto-lint proto-breaking source-verify scope-verify conformance frame-verify go-test binding-compile strict-contracts clean-generated
PYTHON ?= python3
PROTOC ?= protoc
@@ -20,6 +20,7 @@ source-verify:
$(PYTHON) -B tools/fixture_digest.py
scope-verify:
$(PYTHON) -B tools/test_check_scope.py
$(PYTHON) -B tools/check_scope.py
go-test:
@@ -29,6 +30,9 @@ binding-compile:
rustc --crate-type lib gen/rust/protocol.rs -o /tmp/versevdi-protocol-generated.rlib
swiftc -typecheck gen/swift/Protocol.swift
strict-contracts:
$(PYTHON) -B tools/test_generated_contracts.py
conformance:
$(PYTHON) -B tools/fixture_digest.py
go run ./tools/go-conformance
@@ -36,8 +40,9 @@ conformance:
frame-verify:
$(PYTHON) tools/validate_frames.py
$(PYTHON) tools/validate_gateway_envelopes.py
clean-generated:
$(PYTHON) tools/generate.py --check
verify: generate proto-lint proto-breaking source-verify scope-verify go-test binding-compile conformance frame-verify clean-generated
verify: generate proto-lint proto-breaking source-verify scope-verify go-test binding-compile strict-contracts conformance frame-verify clean-generated
+2
View File
@@ -4,3 +4,5 @@ invalid-short 1 datagram hex=564401 invalid:truncated
invalid-version 1 datagram hex=564402010000000000000000000000000000010000 invalid:unsupported_version
invalid-channel 1 datagram hex=564401990000000000000000000000000000010000 invalid:unknown_channel
invalid-length 1 datagram hex=564401010000000000000000000000000000010001 invalid:length_mismatch
valid-video-empty 1 datagram hex=5644010a0000000000000000000000000000010000 valid
invalid-media-channel 1 datagram hex=5644010d0000000000000000000000000000010000 invalid:unknown_channel
1 id version kind input expected
4 invalid-version 1 datagram hex=564402010000000000000000000000000000010000 invalid:unsupported_version
5 invalid-channel 1 datagram hex=564401990000000000000000000000000000010000 invalid:unknown_channel
6 invalid-length 1 datagram hex=564401010000000000000000000000000000010001 invalid:length_mismatch
7 valid-video-empty 1 datagram hex=5644010a0000000000000000000000000000010000 valid
8 invalid-media-channel 1 datagram hex=5644010d0000000000000000000000000000010000 invalid:unknown_channel
@@ -0,0 +1,6 @@
id version kind input expected
valid-forwarded 1 gateway_clipboard_audit direction=client_to_provider;outcome=forwarded;text_bytes=1024;reason=forwarded valid
valid-suppressed 1 gateway_clipboard_audit direction=provider_to_client;outcome=suppressed;text_bytes=12;reason=loop valid
audit-invalid-direction 1 gateway_clipboard_audit direction=bidirectional;outcome=forwarded;text_bytes=1;reason=forwarded invalid:clipboard_audit
invalid-bytes 1 gateway_clipboard_audit direction=client_to_provider;outcome=rejected;text_bytes=65537;reason=policy invalid:clipboard_audit
invalid-content 1 gateway_clipboard_audit direction=client_to_provider;outcome=rejected;text_bytes=1;reason=rate;text=forbidden invalid:forbidden
1 id version kind input expected
2 valid-forwarded 1 gateway_clipboard_audit direction=client_to_provider;outcome=forwarded;text_bytes=1024;reason=forwarded valid
3 valid-suppressed 1 gateway_clipboard_audit direction=provider_to_client;outcome=suppressed;text_bytes=12;reason=loop valid
4 audit-invalid-direction 1 gateway_clipboard_audit direction=bidirectional;outcome=forwarded;text_bytes=1;reason=forwarded invalid:clipboard_audit
5 invalid-bytes 1 gateway_clipboard_audit direction=client_to_provider;outcome=rejected;text_bytes=65537;reason=policy invalid:clipboard_audit
6 invalid-content 1 gateway_clipboard_audit direction=client_to_provider;outcome=rejected;text_bytes=1;reason=rate;text=forbidden invalid:forbidden
@@ -0,0 +1,12 @@
id version kind input expected
valid-client-to-provider 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop valid
valid-provider-to-client 1 gateway_clipboard direction=provider_to_client;text=host%20text;encoding=utf-8;loop_token=qrstuvwxyzABCDEF valid
valid-token-alphabet 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ valid
valid-token-max 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ valid
invalid-direction 1 gateway_clipboard direction=bidirectional;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop invalid:clipboard
invalid-token 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=short invalid:clipboard
invalid-token-15 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmno invalid:clipboard
invalid-token-129 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_A invalid:clipboard
invalid-token-character 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=!!!!!!!!!!!!!!!! invalid:clipboard
invalid-token-trailing-bits 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=AAAAAAAAAAAAAAAAAB invalid:clipboard
invalid-file 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop;file=file.txt invalid:forbidden
1 id version kind input expected
2 valid-client-to-provider 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop valid
3 valid-provider-to-client 1 gateway_clipboard direction=provider_to_client;text=host%20text;encoding=utf-8;loop_token=qrstuvwxyzABCDEF valid
4 valid-token-alphabet 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ valid
5 valid-token-max 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ valid
6 invalid-direction 1 gateway_clipboard direction=bidirectional;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop invalid:clipboard
7 invalid-token 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=short invalid:clipboard
8 invalid-token-15 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmno invalid:clipboard
9 invalid-token-129 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_A invalid:clipboard
10 invalid-token-character 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=!!!!!!!!!!!!!!!! invalid:clipboard
11 invalid-token-trailing-bits 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=AAAAAAAAAAAAAAAAAB invalid:clipboard
12 invalid-file 1 gateway_clipboard direction=client_to_provider;text=hello;encoding=utf-8;loop_token=abcdefghijklmnop;file=file.txt invalid:forbidden
@@ -0,0 +1,22 @@
id version kind input expected
valid-keyboard-press 1 gateway_input hex=5647493101040102001e valid
valid-keyboard-release 1 gateway_input hex=5647493101040000001e valid
valid-mouse-button 1 gateway_input hex=564749310203010100 valid
valid-mouse-release 1 gateway_input hex=564749310203000100 valid
valid-relative-mouse 1 gateway_input hex=564749310304fffe0003 valid
valid-utf8-scalar 1 gateway_input hex=564749310403e29883 valid
valid-controller 1 gateway_input hex=5647493105110200030004ffff00010002000300040005 valid
valid-controller-release 1 gateway_input hex=5647493105110200000000000000000000000000000000 valid
valid-idr 1 gateway_feedback hex=5647463100010000 valid
valid-fec 1 gateway_feedback hex=56474631000200150000002a000500030002000a000200080002140001 valid
valid-termination 1 gateway_feedback hex=564746310110000400000001 valid
valid-rumble 1 gateway_feedback hex=56474631011100050112345678 valid
valid-hdr 1 gateway_feedback hex=564746310112000101 valid
invalid-input-magic 1 gateway_input hex=494e503101040102001e invalid:magic
invalid-input-kind 1 gateway_input hex=564749317f00 invalid:kind
invalid-input-reserved 1 gateway_input hex=564749310203010101 invalid:reserved
invalid-input-utf8 1 gateway_input hex=564749310402c328 invalid:utf8
invalid-input-length 1 gateway_input hex=564749310104010200 invalid:length
invalid-feedback-direction 1 gateway_feedback hex=5647463101020000 invalid:direction
invalid-feedback-type 1 gateway_feedback hex=5647463100030000 invalid:type
invalid-feedback-length 1 gateway_feedback hex=5647463101100003000000 invalid:length
1 id version kind input expected
2 valid-keyboard-press 1 gateway_input hex=5647493101040102001e valid
3 valid-keyboard-release 1 gateway_input hex=5647493101040000001e valid
4 valid-mouse-button 1 gateway_input hex=564749310203010100 valid
5 valid-mouse-release 1 gateway_input hex=564749310203000100 valid
6 valid-relative-mouse 1 gateway_input hex=564749310304fffe0003 valid
7 valid-utf8-scalar 1 gateway_input hex=564749310403e29883 valid
8 valid-controller 1 gateway_input hex=5647493105110200030004ffff00010002000300040005 valid
9 valid-controller-release 1 gateway_input hex=5647493105110200000000000000000000000000000000 valid
10 valid-idr 1 gateway_feedback hex=5647463100010000 valid
11 valid-fec 1 gateway_feedback hex=56474631000200150000002a000500030002000a000200080002140001 valid
12 valid-termination 1 gateway_feedback hex=564746310110000400000001 valid
13 valid-rumble 1 gateway_feedback hex=56474631011100050112345678 valid
14 valid-hdr 1 gateway_feedback hex=564746310112000101 valid
15 invalid-input-magic 1 gateway_input hex=494e503101040102001e invalid:magic
16 invalid-input-kind 1 gateway_input hex=564749317f00 invalid:kind
17 invalid-input-reserved 1 gateway_input hex=564749310203010101 invalid:reserved
18 invalid-input-utf8 1 gateway_input hex=564749310402c328 invalid:utf8
19 invalid-input-length 1 gateway_input hex=564749310104010200 invalid:length
20 invalid-feedback-direction 1 gateway_feedback hex=5647463101020000 invalid:direction
21 invalid-feedback-type 1 gateway_feedback hex=5647463100030000 invalid:type
22 invalid-feedback-length 1 gateway_feedback hex=5647463101100003000000 invalid:length
+4 -1
View File
@@ -4,7 +4,10 @@
"fixtures/conformance/control-v1.tsv",
"fixtures/conformance/datagram-v1.tsv",
"fixtures/conformance/events-v1.tsv",
"fixtures/conformance/gateway-clipboard-audit-v1.tsv",
"fixtures/conformance/gateway-clipboard-v1.tsv",
"fixtures/conformance/gateway-input-feedback-v1.tsv",
"fixtures/conformance/tunnel-v1.tsv"
],
"corpus_sha256": "c91a512dc67aa9912b31b21144be2adfeacf0dc80dd8515bd3b4a8f52977e761"
"corpus_sha256": "69d5b12a533ff0d9786784b99aecc8a74a7ec2c6855b75c52e46ecff5bd3e6c5"
}
+17 -5
View File
@@ -1,7 +1,9 @@
# VerseVDI control datagram v1
Phase 3A reserves a bounded control-datagram envelope. It does not forward video,
audio, provider traffic, VM traffic, or arbitrary binary clipboard data.
Phase 3C adds bounded encoded video/audio and sequenced-input channels to the same
transport envelope. The gateway forwards encoded bytes; it does not decode, encode,
transcode, render, or expose provider traffic. Arbitrary binary clipboard data remains
rejected.
All multi-byte integers are unsigned big-endian. The fixed header is 21 bytes:
@@ -22,6 +24,16 @@ Truncated, oversized, unknown-version, unknown-channel, invalid-fragment, and
length-mismatch frames are rejected before allocation proportional to the claimed
payload. Media/provider identifiers are not registered channels.
Registered Phase 3A channels are `control.ack.v1`, `control.cancel.v1`, and
`clipboard.text.v1`. Clipboard payloads are UTF-8 JSON text contracts and remain
subject to the 65,536-byte text limit and explicit authorization.
Registered channels are `control.ack.v1`, `control.cancel.v1`, `clipboard.text.v1`,
`media.video.v1`, `media.audio.v1`, and `input.sequenced.v1`. Media/input frames use
application flow IDs 10, 11, and 12 and a path-MTU-safe payload limit of 1,179 bytes;
larger encoded units use at most 16 validated fragments. Clipboard payloads are UTF-8
JSON text contracts and remain subject to the 65,536-byte text limit and explicit
Server-owned direction, rate, and loop-token policy as defined in
`gateway-clipboard-v1.md`.
Within an active Phase 3C gateway session, `input.sequenced.v1` and the
bidirectional reliable `control.ack.v1` payloads additionally use the exact
provider-neutral grammars in [gateway-input-feedback-v1.md](gateway-input-feedback-v1.md).
Those grammars do not alter this datagram header or make provider traffic visible to
the Verse client.
+28
View File
@@ -0,0 +1,28 @@
# Gateway clipboard text v1
`clipboard.text.v1` is a reliable, authenticated gateway-only `ChannelFrame`
flow. Its UTF-8 JSON payload is a `GatewayClipboardText` object:
```json
{"direction":"client_to_provider","text":"text","encoding":"utf-8","loop_token":"base64url-token"}
```
`direction` is exact: the client may send only `client_to_provider`, and the
gateway may send only `provider_to_client`. The text contains no file name,
URL, binary value, or client-folder field and is at most the Server-owned
`clipboard_policy.max_text_bytes` value. `loop_token` is a 16--128 character
canonical unpadded ASCII base64url token generated by the originating endpoint. An endpoint MUST retain
recent token/value pairs only for the bounded policy window and MUST suppress a
matching reflected value; a mismatched, malformed, expired, or replayed token
is rejected without clipboard mutation.
The gateway receives the policy only in authenticated session work. A disabled
direction, a rate above `max_updates_per_minute`, invalid UTF-8, an oversized
payload, or an unknown field fails closed. Clipboard bytes are never emitted to
provider-state, audit, telemetry, or error payloads.
For every successfully delivered, loop-suppressed, or policy/rate/provider/malformed
rejection, the gateway sends an mTLS control-plane `GatewayClipboardAudit` record. It contains
only the session identifier, direction, bounded text-byte count, outcome, and a
fixed reason code; it contains neither text nor loop token. The Server persists it
against the broker session using the authenticated gateway identity.
+78
View File
@@ -0,0 +1,78 @@
# Gateway input and feedback v1
This grammar is carried only in an authenticated Phase 3C gateway session. It
is deliberately provider-neutral: it never carries provider routes,
certificates, credentials, opaque provider packets, clipboard bytes, files, or
client-folder data. It does not change the v1 datagram header or any existing
release candidate.
## `input.sequenced.v1` payload (`VGI1`)
All multibyte fields are unsigned big-endian. The payload has exactly six bytes
of header followed by the declared body:
| Offset | Size | Field | Rule |
|---:|---:|---|---|
| 0 | 4 | magic | ASCII `VGI1` |
| 4 | 1 | kind | one of the kinds below |
| 5 | 1 | payload length | exact body byte count |
| 6 | N | body | exact kind-specific body |
The decoder rejects an unknown kind, non-exact length, nonzero reserved byte,
unsupported controller index, malformed UTF-8, a non-scalar UTF-8 value, or a
payload larger than the channel limit before provider translation. A false
keyboard or mouse state and a zeroed controller state are explicit releases;
they are retained by the gateway and replayed as individual provider releases
during cleanup.
| Kind | Name | Exact body |
|---:|---|---|
| `0x01` | keyboard | `state` (`0` release, `1` press), `modifiers` (one byte), nonzero `scancode` (u16). |
| `0x02` | mouse button | `state` (`0` release, `1` press), `button` (`1` through `5`), reserved `0`. |
| `0x03` | relative mouse | `delta_x` (i16), `delta_y` (i16). |
| `0x04` | UTF-8 scalar | exactly one valid UTF-8 Unicode scalar, one through four bytes. |
| `0x05` | controller state | `controller` (0 through 15), `active_mask` (u16), `button_flags` (u16), `left_trigger` (u8), `right_trigger` (u8), `left_x` (i16), `left_y` (i16), `right_x` (i16), `right_y` (i16), `extra_button_flags` (u16). A zero `active_mask` and zero state is release. |
Keyboard, mouse button, UTF-8, and controller messages are delivered over the
gateway's reliable ordered input flow. Relative mouse is a state change, not a
pressed-state entry. The gateway maps the validated values to the provider's
separate keyboard, mouse, UTF-8, and controller control messages; it does not
forward this envelope to the provider.
## Reliable control payload (`VGF1`)
`control.ack.v1` remains the existing authenticated bidirectional reliable
control flow. Within an active gateway session, its provider-feedback payload
is the following exact envelope:
| Offset | Size | Field | Rule |
|---:|---:|---|---|
| 0 | 4 | magic | ASCII `VGF1` |
| 4 | 1 | direction | `0` client-to-gateway; `1` gateway-to-client |
| 5 | 1 | type | valid only for the stated direction |
| 6 | 2 | payload length | exact payload byte count |
| 8 | N | payload | exact type-specific body |
The client-to-gateway types are `0x01` IDR request (empty) and `0x02` FEC
status: `frame_index` (u32), `highest_received_sequence` (u16),
`next_contiguous_sequence` (u16), `missing_before_highest` (u16),
`total_data_packets` (u16), `total_parity_packets` (u16),
`received_data_packets` (u16), `received_parity_packets` (u16),
`fec_percentage` (u8), `multi_fec_block_index` (u8), and
`multi_fec_block_count` (u8). The gateway maps this fixed 21-byte structure to
the provider's unsequenced ENet FEC delivery; it does not put it on the reliable
provider input path.
The gateway-to-client types are `0x10` host termination (`exit_code` u32),
`0x11` rumble (`controller` u8, `low_frequency` u16,
`high_frequency` u16), and `0x12` HDR mode (`enabled` exactly `0` or `1`). The
gateway derives these from authenticated provider control messages, normalizes
their bounded fields, and rejects all unrecognized provider feedback. The HDR
envelope intentionally carries only the negotiated mode; provider-specific HDR
metadata remains behind the gateway boundary.
Apollo's pinned `src/stream.cpp` source defines separate termination, rumble,
and HDR control structures, while Moonlight common-C's `ControlStream.c` and
`InputStream.c` separate reliable input/control from UDP media. This Verse
grammar is a new normalized contract; it does not copy either implementation or
expose its wire format.
+6 -3
View File
@@ -4,9 +4,12 @@
"header_bytes": 21,
"maximum_frame_bytes": 65536,
"channels": [
{"id": 1, "name": "control.ack.v1", "direction": "bidirectional", "max_payload_bytes": 1024},
{"id": 1, "name": "control.ack.v1", "direction": "bidirectional", "max_payload_bytes": 1024, "payload_profile": "gateway-feedback-v1"},
{"id": 2, "name": "control.cancel.v1", "direction": "client-to-server", "max_payload_bytes": 2048},
{"id": 3, "name": "clipboard.text.v1", "direction": "bidirectional", "max_payload_bytes": 65515}
{"id": 3, "name": "clipboard.text.v1", "direction": "bidirectional", "max_payload_bytes": 65515},
{"id": 10, "name": "media.video.v1", "direction": "server-to-client", "max_payload_bytes": 1179},
{"id": 11, "name": "media.audio.v1", "direction": "server-to-client", "max_payload_bytes": 1179},
{"id": 12, "name": "input.sequenced.v1", "direction": "client-to-server", "max_payload_bytes": 1179, "payload_profile": "gateway-input-v1"}
],
"reserved_rejected": ["video", "audio", "provider", "vm", "file-transfer", "clipboard.binary"]
"reserved_rejected": ["provider", "vm", "file-transfer", "clipboard.binary"]
}
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -12,7 +12,7 @@
"2"
]
},
"generator_sha256": "cb975bcd42bf77641b6a0f44d5ec7a6fdba1858d6b8a865e0f04e53bad82648c",
"generator_sha256": "00fdba050eb924a54dd3d63aac0a38560341b675f0de4e3e9631ee895057a9b6",
"protocol_version": "1.0.0",
"schema_sha256": "36e4c8bac2eae674c1eba551c6ca8c64bf80fcc092ca63ec89a2c71c2bec86e1"
"schema_sha256": "3aec8dd72bdbb6b9657c8df3160252c93034c7c1032d471e01eae2ef91e47716"
}
Binary file not shown.
Binary file not shown.
+1648 -130
View File
File diff suppressed because it is too large Load Diff
+1870 -188
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
## Decisions
- Use the existing generated JSON binding pipeline and add only object definitions that
consumers need now.
- Keep registration/authority messages distinct from `ConnectionManifest`; the latter is
client-facing and contains no provider route, certificate, identity, or credential.
- Encode capability domains as bounded registered strings (`transport`, `framing`, `media`,
`audio`, `source_rate_control`, `client_decode`) so unknown or empty required domains
cannot silently fall back.
- Use a fixed 21-byte big-endian datagram header with application flow IDs and a payload
limit below the path MTU; control channels 1-3 remain compatible with Phase 3A.
## Bounds and failure behavior
All arrays, strings, payloads, fragments, and timestamps are bounded by the JSON schema or
frame registry. Generated decoders reject unknown fields, trailing values, invalid versions,
and missing required fields. Provider address, RTSP, credential, and private-key names are
not added to client-facing definitions.
## Compatibility
The current wire version remains `1`; current, N-1, and N-2 declarations remain unchanged.
New identifiers are additive. Consumers must reject an unknown major or no-overlap selection
before provider launch.
@@ -0,0 +1,32 @@
## Why
Phase 3A defines gateway-only manifests and control datagrams but has no versioned
contracts for the separately deployed gateway's registration, admission authority,
capability intersection, lifecycle, or encoded relay framing. Phase 3C-G needs those
contracts frozen before Data Plane or Connection Server consumers change.
## What Changes
- Add bounded JSON bindings for gateway registration, heartbeat/drain, tunnel admission,
session-scoped authority, capability selection, channel framing, provider state, and
stable errors.
- Extend the tunnel protobuf descriptor with the same versioned control messages.
- Register only gateway-owned media/input flow identifiers; keep provider endpoints and
credentials out of client-facing manifests.
## Ownership and provenance
Protocol owns the wire contract. The contract is original VerseVDI work derived from the
Phase 3A schemas and public Apollo/Moonlight behavior recorded in the Planning Hub. No
GPL source is copied into this repository.
## Non-goals
- Provider implementation, database policy, QUIC implementation, media decoding, or client
rendering.
- Direct client-to-Apollo routing, provider endpoint exposure, or a speculative plugin ABI.
## Stop conditions
Unknown versions, malformed bounds, no capability overlap, downgrade without explicit
acknowledgement, forbidden provider fields, and oversized frames fail closed.
@@ -0,0 +1,37 @@
## ADDED Requirements
### Requirement: Versioned gateway authority contracts
Gateway registration, heartbeat, drain, admission, capability selection, channel framing,
provider state, and stable errors SHALL use bounded versioned objects with strict decoding.
#### Scenario: Unknown or malformed gateway message
- **WHEN** a consumer receives an unknown version, missing required field, unknown field,
invalid bound, or trailing JSON value
- **THEN** it rejects the message before allocating provider or media state with a stable
validation error.
### Requirement: Gateway-only client manifest
Client-facing manifests SHALL expose only the selected gateway, tunnel/profile identifiers,
policy bounds, opaque grant, audience, expiry, session, and correlation data.
#### Scenario: Provider route injection
- **WHEN** a manifest or client-facing authority contains a provider address, RTSP URL,
certificate, pairing identity, credential, or private key field
- **THEN** schema validation rejects it and no generated client binding accepts it.
### Requirement: Explicit capability intersection
Transport, framing, media, audio, source-rate-control, and client-decode capabilities SHALL
remain separate and no-overlap or unknown-required-profile results SHALL fail closed.
#### Scenario: No capability overlap
- **WHEN** policy, gateway, provider, and client capabilities have no allowed intersection
- **THEN** negotiation returns a stable no-overlap error before provider launch or media flow.
### Requirement: Bounded encoded datagrams
Encoded media and approved sequenced input SHALL use registered application flow identifiers,
validated fixed headers, bounded fragments, and payload bytes that are not codec-transformed.
#### Scenario: Malformed or oversized datagram
- **WHEN** a datagram is truncated, has an unknown flow, invalid fragment, length mismatch,
or exceeds its registered payload limit
- **THEN** the datagram is rejected without allocation proportional to the claimed payload.
@@ -0,0 +1,5 @@
- [x] Add versioned gateway and authority definitions to the schema and tunnel descriptor.
- [x] Add registered media/audio/sequenced-input flow identifiers and positive/negative fixtures.
- [x] Regenerate Go/Rust/Swift bindings and descriptor outputs.
- [x] Run strict validation, cross-language conformance, and deterministic fixture hashing.
- [x] Freeze the local Protocol candidate commit and record its hash for consumers.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-07-29
@@ -0,0 +1,50 @@
## Context
The registered `input.sequenced.v1` flow has a payload bound but no typed
payload grammar. RC5 also has no provider-to-client envelope for host
termination, rumble, or HDR feedback. The Data Plane must translate these
states to the provider without exposing Apollo packet formats or credentials.
## Goals / Non-Goals
**Goals:**
- Define fixed, bounded, endian-explicit gateway payloads for keyboard, mouse,
UTF-8 text, and controller state.
- Define a reliable control envelope for provider feedback and termination.
- Define an explicit release operation for every pressed key/button/controller.
- Keep provider packet encodings and endpoint details internal to the Data Plane.
**Non-Goals:**
- Touch, pen, motion, file transfer, binary clipboard, or provider-specific
packets.
- Changing RC5, moving an existing tag, or making the Connection Server parse
streaming input.
## Decisions
- Define a new binary payload grammar beneath the existing registered flows.
This avoids changing the authenticated tunnel header while removing the
untyped `device`/opaque-payload ambiguity. JSON was rejected because input is
latency-sensitive and fixed binary bounds are simpler to validate before
allocation.
- Input events use explicit event kinds and fixed payload lengths except UTF-8
text, which is limited to one valid Unicode scalar value. This permits exact
provider translation and deterministic cleanup.
- Provider feedback and termination use the existing bidirectional reliable
control channel with a distinct magic, direction, type, and length. A new
channel was rejected because the existing channel is already authenticated,
reliable, and versioned.
- Protocol contents and fixtures are finalized before a new immutable release
candidate is created. RC5 remains an unchanged dependency for current
consumers until they explicitly adopt the new revision.
## Risks / Trade-offs
- [New client adoption is required] -> retain RC5 unchanged and publish an
explicit capability/version mismatch before any provider allocation.
- [Provider feedback can be high rate] -> allow only termination, rumble, and
HDR payload types with fixed maximum sizes; other types reject.
- [Pressed-state loss during disconnect] -> gateway records accepted presses
and emits typed releases during cleanup before provider disconnect.
@@ -0,0 +1,40 @@
## Why
The RC5 tunnel register identifies a bounded sequenced-input flow but does not
define typed input state or provider-to-client feedback. The native Apollo
adapter cannot safely translate keyboard, mouse, UTF-8, controller, termination,
rumble, or HDR state from an untyped payload.
## What Changes
- Define a typed, versioned gateway input envelope for keyboard, mouse, UTF-8,
and controller state.
- Define bounded provider-feedback and provider-termination envelopes on the
existing reliable control direction.
- Define a separate typed clipboard envelope and Server-owned per-session
direction, size, and rate policy so the gateway can prevent reflected loops
without exposing provider management material.
- Define release semantics so gateway cleanup can emit real provider key/button
releases without a synthetic provider command.
- Preserve RC5 unchanged; this change requires a new immutable Protocol version
after its fixtures and consumers are final.
## Capabilities
### New Capabilities
- `gateway-input-feedback`: Typed Phase 3C gateway input, provider feedback,
termination, and release envelopes.
### Modified Capabilities
- None.
## Impact
- Protocol control and datagram registries, schemas, fixtures, and generated
Go/Rust/Swift bindings.
- Data Plane gateway input/clipboard translation and host-feedback forwarding.
- Connection Server mints only immutable clipboard policy in authenticated
provider work; it neither receives clipboard bytes nor inspects provider
packet payloads.
@@ -0,0 +1,79 @@
## ADDED Requirements
### Requirement: Typed sequenced input envelope
The `input.sequenced.v1` payload SHALL begin with ASCII `VGI1`, a one-byte
event kind, and one-byte payload length. It SHALL contain exactly one bounded
keyboard, mouse-button, relative-mouse, UTF-8 scalar, or controller-state
event. False keyboard/mouse state and zeroed controller state are explicit
releases. Multibyte integer fields SHALL be big-endian. Unknown kinds,
length mismatches, malformed UTF-8, unsupported controller indices, and
reserved fields SHALL be rejected before provider translation.
#### Scenario: Keyboard state change
- **WHEN** a client sends a valid keyboard press or release envelope
- **THEN** the gateway forwards the corresponding typed provider input on its
reliable keyboard channel and records the pressed state for cleanup.
#### Scenario: Invalid input envelope
- **WHEN** a client sends an envelope with an unknown event kind, invalid
length, malformed UTF-8 scalar, or nonzero reserved field
- **THEN** the gateway rejects it without sending provider input or changing
pressed state.
### Requirement: Explicit input release
The typed input envelope SHALL represent release of each keyboard key,
mouse button, and controller state. Gateway cleanup SHALL send a typed release
for every accepted pressed state before provider disconnect; it SHALL NOT use
an implementation-specific release-all provider command.
#### Scenario: Tunnel cleanup with pressed input
- **WHEN** a tunnel closes after accepted pressed keyboard, mouse, or
controller input
- **THEN** the gateway emits the corresponding individual provider release
packets reliably before starting provider disconnect.
### Requirement: Bounded provider feedback control envelope
The registered bidirectional reliable `control.ack.v1` flow SHALL define an ASCII `VGF1` envelope
with a direction byte, type byte, big-endian payload length, and exact payload
bytes. Only host termination, rumble, and HDR feedback SHALL be valid from the
gateway to the client; only IDR and FEC/loss feedback SHALL be valid from the
client to the gateway. The envelope SHALL contain no provider address,
certificate, credential, or opaque provider packet.
#### Scenario: Host termination forwarding
- **WHEN** the Apollo adapter receives an authenticated host termination
packet
- **THEN** the gateway forwards a bounded `VGF1` termination envelope over
reliable Verse control and reports the provider state separately.
#### Scenario: Unauthorized or malformed feedback
- **WHEN** feedback is disabled by policy, has an invalid direction/type/length,
or contains a forbidden provider field
- **THEN** the gateway rejects it without forwarding or provider mutation.
### Requirement: Policy-bound text clipboard envelope
The reliable `clipboard.text.v1` flow SHALL carry only a typed UTF-8 text
envelope with exact direction and a 16--128 character canonical unpadded ASCII
base64url loop token. The Server SHALL mint
the enabled directions, maximum text bytes, and maximum updates per minute in
authenticated provider work. The gateway SHALL reject disabled direction,
unknown fields, files, file URLs, client folders, binary data, malformed UTF-8,
oversized values, rates above policy, and reflected/replayed loop tokens. It
SHALL not put clipboard content, provider routes, or credentials in telemetry,
audit, state, or errors.
#### Scenario: Clipboard audit metadata
- **WHEN** the gateway successfully delivers, suppresses, or rejects a clipboard update
- **THEN** it sends an authenticated Server audit record with only direction,
bounded byte count, outcome, and a fixed reason; it never includes text or
the loop token.
#### Scenario: Clipboard delivery failure
- **WHEN** provider-to-client control delivery fails
- **THEN** the gateway does not report the update as forwarded.
#### Scenario: Reflected clipboard value
- **WHEN** a client-originated text value returns from the provider with the
matching retained token/value pair
- **THEN** the gateway suppresses the reflected update without a second
provider mutation or client delivery.
@@ -0,0 +1,29 @@
## 1. Contract and fixtures
- [x] 1.1 Define the exact typed input and provider-feedback binary layouts in
the canonical frame documentation and registries.
- [x] 1.2 Add positive and negative fixed-byte conformance fixtures for every
input, release, feedback, termination, reserved, and malformed case.
- [x] 1.3 Update only source Protocol artifacts, regenerate bindings and the
manifest, and prove no generated drift.
- [x] 1.4 Define policy-bound clipboard direction/rate/loop-token envelopes and
positive/negative deterministic conformance fixtures without adding provider
fields to a client-facing frame.
## 2. Consumer qualification
- [x] 2.1 Run Protocol validation and the Go, Rust, and Swift conformance
consumers against the new fixtures.
- [x] 2.2 Advance the Data Plane to the final immutable Protocol revision and
translate only the typed envelopes to provider control packets.
- [x] 2.3 Add deterministic host-feedback forwarding and input-release tests
without provider endpoint or credential disclosure.
- [x] 2.4 Advance the Data Plane and Connection Server to the final clipboard
contract and prove disabled direction, malformed/oversized text, rate, loop,
and file/binary rejection against the authenticated provider path.
## 3. Freeze
- [x] 3.1 Reconcile the canonical specification, OpenSpec tasks, source
provenance, and consumer fixture digest before creating a new immutable
Protocol release candidate.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-07-29
@@ -0,0 +1,38 @@
## Context
The Data Plane already collects process-wide atomic counters and gauges. Only active connections and egress Kbps cross the authenticated heartbeat boundary.
## Goals / Non-Goals
**Goals:**
- Carry the existing low-cardinality observations with explicit units.
- Bound every numeric field and enumerate provider state.
- Keep registration capacity distinct from measured traffic.
**Non-Goals:**
- Add session, route, endpoint, credential, label, or payload fields.
- Define a new telemetry transport.
- Publish a Protocol version.
## Decisions
- Nest the values in required `GatewayTelemetry` so heartbeat telemetry is one strict atomic contract.
- Use cumulative counters and microsecond delay totals plus one processing sample per complete provider media unit; consumers can derive rates/averages without losing raw observations.
- Define queue delay as residence in the bounded provider queue, processing as active recovery/framing/QUIC work excluding queue and scheduler waits, and pacing as scheduler wait only.
- Derive measured egress from transmitted-byte deltas over monotonic elapsed time; configured capacity remains registration data.
- Keep loss as parts per million and provider state as a bounded enum.
## Risks / Trade-offs
- [Cumulative counters approach signed integer limits] → Bound at signed 64-bit and saturate consumer conversions.
- [New required object breaks RC6] → Test locally and publish only under separate immutable-version authorization.
## Migration Plan
Regenerate all bindings locally, update both consumers through the temporary workspace, and stop at the immutable publication boundary.
## Open Questions
None.
@@ -0,0 +1,23 @@
## Why
Gateway heartbeat currently carries active sessions and one egress rate but cannot transport the required observed process and provider-path telemetry.
## What Changes
- Add one required bounded low-cardinality telemetry object to authenticated gateway heartbeat.
- Cover counters, delay totals/samples, control RTT/loss/jitter, pending reliability, reconnects, and provider state.
- Keep configured capacity exclusively in registration and measured egress in heartbeat.
## Capabilities
### New Capabilities
- `gateway-heartbeat-telemetry`: Authenticated heartbeats carry bounded observed gateway telemetry without routes, sessions, credentials, or payload data.
### Modified Capabilities
None.
## Impact
The control-v1 schema, generated Go/Rust/Swift bindings, conformance checks, and both unpublished consumers require coordinated local updates. RC6 remains unchanged.
@@ -0,0 +1,22 @@
## ADDED Requirements
### Requirement: Heartbeat carries observed gateway telemetry
Every authenticated `GatewayHeartbeat` SHALL carry the bounded process-level counters, delay totals and samples, control RTT/loss/jitter, pending reliable work, reconnect count, and provider state defined by `GatewayTelemetry`.
#### Scenario: Valid telemetry heartbeat
- **WHEN** a gateway reports its current observed snapshot
- **THEN** Go, Rust, and Swift bindings accept the same bounded low-cardinality values and units
### Requirement: Heartbeat telemetry excludes sensitive dimensions
Heartbeat telemetry MUST reject unknown fields and MUST NOT include session, route, endpoint, credential, label, or payload values.
#### Scenario: Secret or high-cardinality field is attempted
- **WHEN** a heartbeat contains an unregistered session, route, endpoint, credential, or payload field
- **THEN** strict contract validation rejects it before authenticated transport
### Requirement: Delay and egress observations have one canonical meaning
Queue delay SHALL measure provider-queue residence, processing delay SHALL measure active gateway recovery/framing/QUIC work excluding queue and pacing, and pacing delay SHALL measure scheduler waiting only. Processing samples SHALL count complete provider media units rather than Verse fragments. Measured egress SHALL derive from transmitted-byte deltas over monotonic elapsed time and MUST NOT be copied from configured capacity.
#### Scenario: One provider unit becomes multiple Verse frames
- **WHEN** one complete provider unit waits in the queue, traverses gateway processing, waits for pacing, and fragments into multiple Verse frames
- **THEN** each delay total includes only its defined interval and the heartbeat advances processing samples exactly once
@@ -0,0 +1,12 @@
## 1. Contract
- [x] 1.1 Add bounded GatewayTelemetry to every heartbeat
- [x] 1.2 Add Go, Rust, and Swift strict conformance checks
- [x] 1.3 Regenerate bindings and prove deterministic output
- [x] 1.4 Specify queue, processing, pacing, sample, and measured-egress semantics
## 2. Consumer Boundary
- [x] 2.1 Verify local Data Plane and Server consumers through a temporary workspace
- [ ] 2.2 Publish one new never-reused immutable Protocol version under separate authorization
- [ ] 2.3 Resolve from empty caches and pin exact checksums in both consumers
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-07-29
@@ -0,0 +1,42 @@
## Context
The Server resolves an immutable stream-policy version, but RC6 provider work carries only its identifier. The Data Plane consequently cannot distinguish the authorized settings from local defaults.
## Goals / Non-Goals
**Goals:**
- Carry only the effective launch settings required by the provider boundary.
- Express client decode support as an ordered set of existing registered profiles.
- Generate the same ordered registered-profile intersection for every consumer.
- Generate identical validation from the canonical schema for all bindings.
- Preserve the policy-version identifier for audit correlation.
**Non-Goals:**
- Publish or mutate RC6.
- Add a provider-specific token grammar or generic capability framework.
- Expose provider work or policy internals to Verse clients.
## Decisions
- Use one required nested `ProviderStreamPolicy` value in `ProviderSessionWork`; this keeps the policy settings atomic and avoids repeating validation.
- Carry the Server-selected target bitrate rather than all policy bounds because Apollo ANNOUNCE consumes one configured bitrate.
- Permit canonical `H264`, `HEVC`, and `AV1` values in the contract. A provider implementation must reject values it cannot honor rather than silently downgrade them.
- Carry `audio_enabled` even though the current Apollo path cannot truthfully disable audio; the Data Plane must fail closed for that combination.
- Change `client_decode` from one opaque string to a non-empty ordered unique array of registered profile identifiers. Preference belongs to the first peer's order.
- Generate `IntersectCapabilityProfiles` from the canonical schema so Protocol, Server, and Data Plane do not maintain separate interpretations.
## Risks / Trade-offs
- [New required field breaks RC6 consumers] → Publish only under a separately authorized new immutable version and pin both consumers after empty-cache resolution.
- [Provider capabilities differ] → Validate the effective policy against the selected provider before readiness.
- [Peers advertise no common registered profile] → Reject admission instead of inventing a combined token or silently downgrading.
## Migration Plan
Regenerate and verify bindings locally, update both consumers through a temporary workspace only, then stop at the publication boundary. RC6 remains unchanged.
## Open Questions
None.
@@ -0,0 +1,24 @@
## Why
Provider work identifies an immutable stream-policy version but omits the effective settings, allowing a gateway to launch Apollo with unrelated hard-coded media parameters.
## What Changes
- Add the effective resolution, frame rate, codec, selected bitrate, and audio policy to authenticated provider work.
- Represent decode support as an ordered set of registered profiles and generate one canonical intersection operation for consumers.
- Require generated Go, Rust, and Swift bindings to validate the same bounded stream-policy contract.
- Keep the new contract unpublished until a new immutable Protocol version is separately authorized.
## Capabilities
### New Capabilities
- `provider-stream-policy`: Authenticated provider work carries the exact effective stream policy consumed by the provider launch, and registered peers negotiate that policy through the shared ordered profile intersection.
### Modified Capabilities
None.
## Impact
The control-v1 schema, generated bindings, conformance fixtures, and downstream Server and Data Plane consumers require coordinated local updates. RC6 remains immutable and unchanged.
@@ -0,0 +1,33 @@
## ADDED Requirements
### Requirement: Provider work carries the effective stream policy
Authenticated `ProviderSessionWork` SHALL carry the immutable policy version and its effective resolution, frame rate, codec, target bitrate, and audio-enabled decision.
#### Scenario: Gateway receives an effective policy
- **WHEN** the Server issues provider work for an admitted session
- **THEN** the work identifies the policy version and includes the effective bounded stream-policy values
### Requirement: Stream-policy bindings share one strict contract
Generated Go, Rust, and Swift bindings MUST reject missing, unknown, out-of-range, or unsupported stream-policy wire values according to the canonical schema.
#### Scenario: Invalid policy is rejected consistently
- **WHEN** provider work contains an unknown codec or a value outside the canonical bounds
- **THEN** every generated binding rejects the work before it can reach provider setup
### Requirement: Decode capabilities use registered ordered profiles
`CapabilityProfile.client_decode` SHALL be a non-empty ordered unique set containing only registered `h264-opus` and `hevc-opus` profile identifiers. It MUST NOT encode multiple capabilities in an opaque private token.
#### Scenario: Independent peer advertises one registered profile
- **WHEN** an independent peer advertises one registered decode profile
- **THEN** canonical validation accepts that profile without requiring a combined private token
### Requirement: Consumers share one ordered registered-profile intersection
Generated Protocol behavior SHALL select common registered profiles in the first peer's preference order. Provider consumers SHALL separately reject the resulting intersection when it cannot honor the immutable stream policy.
#### Scenario: Policy-compatible profile overlaps
- **WHEN** the gateway advertises HEVC then H.264 and the client advertises only H.264
- **THEN** the shared intersection selects `h264-opus`
#### Scenario: No policy-compatible profile overlaps
- **WHEN** peers have no registered common profile
- **THEN** the shared intersection rejects admission without inventing a private combined token
@@ -0,0 +1,13 @@
## 1. Contract
- [x] 1.1 Add bounded effective stream policy to ProviderSessionWork
- [x] 1.2 Add Go, Rust, and Swift conformance coverage
- [x] 1.3 Regenerate bindings and prove deterministic output
- [x] 1.4 Replace the opaque decode token with an ordered unique set of registered profiles
- [x] 1.5 Generate and cross-check canonical ordered registered-profile intersection behavior
## 2. Consumer Boundary
- [x] 2.1 Verify local Server and Data Plane consumers through a temporary workspace
- [ ] 2.2 Publish one new never-reused immutable Protocol version under separate authorization
- [ ] 2.3 Resolve from empty caches and pin exact checksums in both consumers
@@ -0,0 +1,83 @@
# gateway-input-feedback Specification
## Purpose
Define the provider-neutral typed input, feedback, and text-clipboard envelopes
used across the authenticated Verse gateway boundary.
## Requirements
### Requirement: Typed sequenced input envelope
The `input.sequenced.v1` payload SHALL begin with ASCII `VGI1`, a one-byte
event kind, and one-byte payload length. It SHALL contain exactly one bounded
keyboard, mouse-button, relative-mouse, UTF-8 scalar, or controller-state
event. False keyboard/mouse state and zeroed controller state are explicit
releases. Multibyte integer fields SHALL be big-endian. Unknown kinds,
length mismatches, malformed UTF-8, unsupported controller indices, and
reserved fields SHALL be rejected before provider translation.
#### Scenario: Keyboard state change
- **WHEN** a client sends a valid keyboard press or release envelope
- **THEN** the gateway forwards the corresponding typed provider input on its
reliable keyboard channel and records the pressed state for cleanup.
#### Scenario: Invalid input envelope
- **WHEN** a client sends an envelope with an unknown event kind, invalid
length, malformed UTF-8 scalar, or nonzero reserved field
- **THEN** the gateway rejects it without sending provider input or changing
pressed state.
### Requirement: Explicit input release
The typed input envelope SHALL represent release of each keyboard key,
mouse button, and controller state. Gateway cleanup SHALL send a typed release
for every accepted pressed state before provider disconnect; it SHALL NOT use
an implementation-specific release-all provider command.
#### Scenario: Tunnel cleanup with pressed input
- **WHEN** a tunnel closes after accepted pressed keyboard, mouse, or
controller input
- **THEN** the gateway emits the corresponding individual provider release
packets reliably before starting provider disconnect.
### Requirement: Bounded provider feedback control envelope
The registered bidirectional reliable `control.ack.v1` flow SHALL define an ASCII `VGF1` envelope
with a direction byte, type byte, big-endian payload length, and exact payload
bytes. Only host termination, rumble, and HDR feedback SHALL be valid from the
gateway to the client; only IDR and FEC/loss feedback SHALL be valid from the
client to the gateway. The envelope SHALL contain no provider address,
certificate, credential, or opaque provider packet.
#### Scenario: Host termination forwarding
- **WHEN** the Apollo adapter receives an authenticated host termination
packet
- **THEN** the gateway forwards a bounded `VGF1` termination envelope over
reliable Verse control and reports the provider state separately.
#### Scenario: Unauthorized or malformed feedback
- **WHEN** feedback is disabled by policy, has an invalid direction/type/length,
or contains a forbidden provider field
- **THEN** the gateway rejects it without forwarding or provider mutation.
### Requirement: Policy-bound text clipboard envelope
The reliable `clipboard.text.v1` flow SHALL carry only a typed UTF-8 text
envelope with exact direction and a 16--128 character canonical unpadded ASCII
base64url loop token. The Server SHALL mint
the enabled directions, maximum text bytes, and maximum updates per minute in
authenticated provider work. The gateway SHALL reject disabled direction,
unknown fields, files, file URLs, client folders, binary data, malformed UTF-8,
oversized values, rates above policy, and reflected/replayed loop tokens. It
SHALL not put clipboard content, provider routes, or credentials in telemetry,
audit, state, or errors.
#### Scenario: Clipboard audit metadata
- **WHEN** the gateway successfully delivers, suppresses, or rejects a clipboard update
- **THEN** it sends an authenticated Server audit record with only direction,
bounded byte count, outcome, and a fixed reason; it never includes text or
the loop token.
#### Scenario: Clipboard delivery failure
- **WHEN** provider-to-client control delivery fails
- **THEN** the gateway does not report the update as forwarded.
#### Scenario: Reflected clipboard value
- **WHEN** a client-originated text value returns from the provider with the
matching retained token/value pair
- **THEN** the gateway suppresses the reflected update without a second
provider mutation or client delivery.
+7
View File
@@ -32,3 +32,10 @@ message ClipboardText {
string text = 1;
string encoding = 2;
}
message GatewayClipboardText {
string direction = 1;
string text = 2;
string encoding = 3;
string loop_token = 4;
}
+131
View File
@@ -49,3 +49,134 @@ message ChannelOpen {
string direction = 2;
uint32 maximum_frame_bytes = 3;
}
message CapabilityProfile {
string transport = 1;
string framing = 2;
string media = 3;
string audio = 4;
string source_rate_control = 5;
repeated string client_decode = 6;
}
message GatewayRegistration {
string version = 1;
string gateway_id = 2;
string instance_identity = 3;
string certificate_identity = 4;
string public_identity = 5;
string address = 6;
uint32 protocol_min_version = 7;
uint32 protocol_max_version = 8;
uint32 connection_capacity = 9;
uint64 bandwidth_capacity_kbps = 10;
repeated string features = 11;
CapabilityProfile capabilities = 12;
string provider_identity = 13;
}
message GatewayHeartbeat {
string version = 1;
string gateway_id = 2;
uint64 sequence = 3;
google.protobuf.Timestamp observed_at = 4;
uint32 active_connections = 5;
uint64 egress_kbps = 6;
string state = 7;
}
message GatewayDrain {
string version = 1;
string gateway_id = 2;
uint64 sequence = 3;
string reason = 4;
google.protobuf.Timestamp deadline = 5;
}
message TunnelAdmissionRequest {
string version = 1;
string session_id = 2;
string gateway_id = 3;
string audience = 4;
string grant = 5;
uint64 reconnect_sequence = 6;
string client_nonce = 7;
CapabilityProfile capabilities = 8;
string device_signature = 9;
}
message SessionAuthority {
string version = 1;
string session_id = 2;
string gateway_id = 3;
string audience = 4;
uint64 reconnect_sequence = 5;
google.protobuf.Timestamp expires_at = 6;
CapabilityProfile capabilities = 7;
string provider_profile = 8;
string provider_identity = 9;
}
message ProviderSessionWork {
string version = 1;
string session_id = 2;
string gateway_id = 3;
uint64 reconnect_sequence = 4;
google.protobuf.Timestamp expires_at = 5;
string provider_profile = 6;
string provider_identity = 7;
string policy_version_id = 8;
string application_id = 9;
string management_host = 10;
uint32 management_port = 11;
string stream_host = 12;
uint32 stream_port = 13;
string client_certificate_pem = 14;
string client_private_key_pem = 15;
string server_certificate_pem = 16;
string client_id = 17;
ClipboardPolicy clipboard_policy = 18;
bool provider_application_termination_allowed = 19;
}
message ClipboardPolicy {
bool client_to_provider_enabled = 1;
bool provider_to_client_enabled = 2;
uint32 max_text_bytes = 3;
uint32 max_updates_per_minute = 4;
}
message ChannelFrame {
string version = 1;
string flow_id = 2;
uint64 sequence = 3;
uint32 flags = 4;
uint32 fragment_index = 5;
uint32 fragment_count = 6;
uint64 timestamp_ms = 7;
bytes payload = 8;
}
message ProviderState {
string version = 1;
string session_id = 2;
string state = 3;
bool cleanup_pending = 4;
repeated string channels = 5;
}
message GatewayClipboardAudit {
string version = 1;
string session_id = 2;
string direction = 3;
string outcome = 4;
uint32 text_bytes = 5;
string reason = 6;
}
message StableError {
string version = 1;
string code = 2;
string message = 3;
bool retryable = 4;
}
+5 -2
View File
@@ -2,8 +2,11 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"max_frame_bytes": 65536,
"datagrams": [
{"id": "control.ack.v1", "direction": "bidirectional", "max_payload_bytes": 1024},
{"id": "control.ack.v1", "direction": "bidirectional", "max_payload_bytes": 1024, "payload_profile": "gateway-feedback-v1"},
{"id": "control.cancel.v1", "direction": "client-to-server", "max_payload_bytes": 2048},
{"id": "clipboard.text.v1", "direction": "bidirectional", "max_payload_bytes": 65536}
{"id": "clipboard.text.v1", "direction": "bidirectional", "max_payload_bytes": 65536},
{"id": "media.video.v1", "direction": "server-to-client", "max_payload_bytes": 1200},
{"id": "media.audio.v1", "direction": "server-to-client", "max_payload_bytes": 1200},
{"id": "input.sequenced.v1", "direction": "client-to-server", "max_payload_bytes": 1200, "payload_profile": "gateway-input-v1"}
]
}
+236
View File
@@ -335,6 +335,28 @@
"encoding": {"type": "string", "const": "utf-8"}
}
},
"ClipboardPolicy": {
"type": "object",
"additionalProperties": false,
"required": ["client_to_provider_enabled", "provider_to_client_enabled", "max_text_bytes", "max_updates_per_minute"],
"properties": {
"client_to_provider_enabled": {"type": "boolean"},
"provider_to_client_enabled": {"type": "boolean"},
"max_text_bytes": {"type": "integer", "minimum": 1, "maximum": 65536},
"max_updates_per_minute": {"type": "integer", "minimum": 1, "maximum": 120}
}
},
"GatewayClipboardText": {
"type": "object",
"additionalProperties": false,
"required": ["direction", "text", "encoding", "loop_token"],
"properties": {
"direction": {"type": "string", "enum": ["client_to_provider", "provider_to_client"]},
"text": {"type": "string", "maxLength": 65536, "x-max-bytes": 65536},
"encoding": {"type": "string", "const": "utf-8"},
"loop_token": {"type": "string", "format": "base64url", "minLength": 16, "maxLength": 128}
}
},
"VersionNegotiation": {
"type": "object",
"additionalProperties": false,
@@ -343,6 +365,220 @@
"supported_versions": {"type": "array", "minItems": 1, "maxItems": 3, "items": {"type": "string", "maxLength": 16}},
"features": {"type": "array", "maxItems": 64, "items": {"type": "string", "maxLength": 64}}
}
},
"CapabilityProfile": {
"type": "object",
"additionalProperties": false,
"required": ["transport", "framing", "media", "audio", "source_rate_control", "client_decode"],
"properties": {
"transport": {"type": "string", "minLength": 1, "maxLength": 64},
"framing": {"type": "string", "minLength": 1, "maxLength": 64},
"media": {"type": "string", "minLength": 1, "maxLength": 64},
"audio": {"type": "string", "minLength": 1, "maxLength": 64},
"source_rate_control": {"type": "string", "minLength": 1, "maxLength": 64},
"client_decode": {
"type": "array",
"minItems": 1,
"maxItems": 2,
"uniqueItems": true,
"items": {"type": "string", "enum": ["h264-opus", "hevc-opus"]}
}
}
},
"GatewayRegistration": {
"type": "object",
"additionalProperties": false,
"required": ["version", "gateway_id", "instance_identity", "certificate_identity", "public_identity", "address", "provider_identity", "protocol_min_version", "protocol_max_version", "connection_capacity", "bandwidth_capacity_kbps", "features", "capabilities"],
"properties": {
"version": {"type": "string", "const": "1"},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"instance_identity": {"type": "string", "minLength": 1, "maxLength": 512},
"certificate_identity": {"type": "string", "minLength": 1, "maxLength": 512},
"public_identity": {"type": "string", "minLength": 1, "maxLength": 256},
"address": {"type": "string", "minLength": 1, "maxLength": 256},
"provider_identity": {"type": "string", "minLength": 1, "maxLength": 256},
"protocol_min_version": {"type": "integer", "minimum": 1, "maximum": 100},
"protocol_max_version": {"type": "integer", "minimum": 1, "maximum": 100},
"connection_capacity": {"type": "integer", "minimum": 1, "maximum": 1000000},
"bandwidth_capacity_kbps": {"type": "integer", "minimum": 1, "maximum": 1000000000},
"features": {"type": "array", "maxItems": 64, "items": {"type": "string", "minLength": 1, "maxLength": 64}},
"capabilities": {"$ref": "#/$defs/CapabilityProfile"}
}
},
"GatewayTelemetry": {
"type": "object",
"additionalProperties": false,
"required": ["admitted_sessions", "admission_rejects", "reconnects", "drain_transitions", "media_drops", "media_packets", "media_bytes", "queue_delay_micros", "processing_delay_micros", "processing_samples", "pacing_delay_micros", "provider_errors", "input_rejected", "control_rtt_micros", "control_jitter_micros", "control_loss_ppm", "pending_reliable", "provider_state"],
"properties": {
"admitted_sessions": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"admission_rejects": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"reconnects": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"drain_transitions": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"media_drops": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"media_packets": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"media_bytes": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"queue_delay_micros": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"processing_delay_micros": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"processing_samples": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"pacing_delay_micros": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"provider_errors": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"input_rejected": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"control_rtt_micros": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"control_jitter_micros": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"control_loss_ppm": {"type": "integer", "minimum": 0, "maximum": 1000000},
"pending_reliable": {"type": "integer", "minimum": 0, "maximum": 9223372036854775807},
"provider_state": {"type": "string", "enum": ["unknown", "starting", "ready", "disconnected", "terminating", "terminated", "cleanup_pending", "failed"]}
}
},
"GatewayHeartbeat": {
"type": "object",
"additionalProperties": false,
"required": ["version", "gateway_id", "sequence", "observed_at", "active_connections", "egress_kbps", "state", "telemetry"],
"properties": {
"version": {"type": "string", "const": "1"},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"sequence": {"type": "integer", "minimum": 1},
"observed_at": {"type": "string", "format": "date-time", "maxLength": 64},
"active_connections": {"type": "integer", "minimum": 0, "maximum": 1000000},
"egress_kbps": {"type": "integer", "minimum": 0, "maximum": 1000000000},
"state": {"type": "string", "enum": ["ready", "draining", "offline"]},
"telemetry": {"$ref": "#/$defs/GatewayTelemetry"}
}
},
"GatewayDrain": {
"type": "object",
"additionalProperties": false,
"required": ["version", "gateway_id", "sequence", "reason", "deadline"],
"properties": {
"version": {"type": "string", "const": "1"},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"sequence": {"type": "integer", "minimum": 1},
"reason": {"type": "string", "minLength": 1, "maxLength": 256},
"deadline": {"type": "string", "format": "date-time", "maxLength": 64}
}
},
"TunnelAdmissionRequest": {
"type": "object",
"additionalProperties": false,
"required": ["version", "session_id", "gateway_id", "audience", "grant", "reconnect_sequence", "client_nonce", "device_signature", "capabilities"],
"properties": {
"version": {"type": "string", "const": "1"},
"session_id": {"type": "string", "minLength": 1, "maxLength": 128},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"audience": {"type": "string", "minLength": 1, "maxLength": 256},
"grant": {"type": "string", "minLength": 43, "maxLength": 256},
"reconnect_sequence": {"type": "integer", "minimum": 0},
"client_nonce": {"type": "string", "minLength": 16, "maxLength": 128},
"device_signature": {"type": "string", "minLength": 86, "maxLength": 86},
"capabilities": {"$ref": "#/$defs/CapabilityProfile"}
}
},
"SessionAuthority": {
"type": "object",
"additionalProperties": false,
"required": ["version", "session_id", "gateway_id", "audience", "reconnect_sequence", "expires_at", "capabilities", "provider_profile", "provider_identity"],
"properties": {
"version": {"type": "string", "const": "1"},
"session_id": {"type": "string", "minLength": 1, "maxLength": 128},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"audience": {"type": "string", "minLength": 1, "maxLength": 256},
"reconnect_sequence": {"type": "integer", "minimum": 0},
"expires_at": {"type": "string", "format": "date-time", "maxLength": 64},
"capabilities": {"$ref": "#/$defs/CapabilityProfile"},
"provider_profile": {"type": "string", "enum": ["apollo"]},
"provider_identity": {"type": "string", "minLength": 1, "maxLength": 256}
}
},
"ProviderStreamPolicy": {
"type": "object",
"additionalProperties": false,
"required": ["resolution_width", "resolution_height", "fps", "codec", "bitrate_kbps", "audio_enabled"],
"properties": {
"resolution_width": {"type": "integer", "minimum": 320, "maximum": 16384},
"resolution_height": {"type": "integer", "minimum": 200, "maximum": 8640},
"fps": {"type": "integer", "minimum": 1, "maximum": 240},
"codec": {"type": "string", "enum": ["H264", "HEVC", "AV1"]},
"bitrate_kbps": {"type": "integer", "minimum": 100, "maximum": 1000000},
"audio_enabled": {"type": "boolean"}
}
},
"ProviderSessionWork": {
"type": "object",
"additionalProperties": false,
"required": ["version", "session_id", "gateway_id", "reconnect_sequence", "expires_at", "provider_profile", "provider_identity", "policy_version_id", "stream_policy", "application_id", "client_id", "management_host", "management_port", "stream_host", "stream_port", "client_certificate_pem", "client_private_key_pem", "server_certificate_pem", "clipboard_policy", "provider_application_termination_allowed"],
"properties": {
"version": {"type": "string", "const": "1"},
"session_id": {"type": "string", "minLength": 1, "maxLength": 128},
"gateway_id": {"type": "string", "minLength": 1, "maxLength": 128},
"reconnect_sequence": {"type": "integer", "minimum": 0},
"expires_at": {"type": "string", "format": "date-time", "maxLength": 64},
"provider_profile": {"type": "string", "const": "apollo"},
"provider_identity": {"type": "string", "minLength": 1, "maxLength": 256},
"policy_version_id": {"type": "string", "minLength": 1, "maxLength": 128},
"stream_policy": {"$ref": "#/$defs/ProviderStreamPolicy"},
"application_id": {"type": "string", "minLength": 1, "maxLength": 128},
"client_id": {"type": "string", "minLength": 1, "maxLength": 128},
"management_host": {"type": "string", "minLength": 1, "maxLength": 256},
"management_port": {"type": "integer", "minimum": 1, "maximum": 65535},
"stream_host": {"type": "string", "minLength": 1, "maxLength": 256},
"stream_port": {"type": "integer", "minimum": 1, "maximum": 65535},
"client_certificate_pem": {"type": "string", "minLength": 1, "maxLength": 32768},
"client_private_key_pem": {"type": "string", "minLength": 1, "maxLength": 32768},
"server_certificate_pem": {"type": "string", "minLength": 1, "maxLength": 32768},
"clipboard_policy": {"$ref": "#/$defs/ClipboardPolicy"},
"provider_application_termination_allowed": {"type": "boolean"}
}
},
"ChannelFrame": {
"type": "object",
"additionalProperties": false,
"required": ["version", "flow_id", "sequence", "flags", "fragment_index", "fragment_count", "timestamp_ms", "payload"],
"properties": {
"version": {"type": "string", "const": "1"},
"flow_id": {"type": "string", "minLength": 1, "maxLength": 64},
"sequence": {"type": "integer", "minimum": 0},
"flags": {"type": "integer", "minimum": 0, "maximum": 255},
"fragment_index": {"type": "integer", "minimum": 0, "maximum": 15},
"fragment_count": {"type": "integer", "minimum": 1, "maximum": 16},
"timestamp_ms": {"type": "integer", "minimum": 0},
"payload": {"type": "string", "maxLength": 87384, "x-max-bytes": 65536}
}
},
"ProviderState": {
"type": "object",
"additionalProperties": false,
"required": ["version", "session_id", "state", "cleanup_pending", "channels"],
"properties": {
"version": {"type": "string", "const": "1"},
"session_id": {"type": "string", "minLength": 1, "maxLength": 128},
"state": {"type": "string", "enum": ["starting", "ready", "disconnected", "terminating", "terminated", "cleanup_pending", "failed"]},
"cleanup_pending": {"type": "boolean"},
"channels": {"type": "array", "maxItems": 8, "items": {"type": "string", "minLength": 1, "maxLength": 64}}
}
},
"GatewayClipboardAudit": {
"type": "object",
"additionalProperties": false,
"required": ["version", "session_id", "direction", "outcome", "text_bytes", "reason"],
"properties": {
"version": {"type": "string", "const": "1"},
"session_id": {"type": "string", "minLength": 1, "maxLength": 128},
"direction": {"type": "string", "enum": ["client_to_provider", "provider_to_client"]},
"outcome": {"type": "string", "enum": ["forwarded", "suppressed", "rejected"]},
"text_bytes": {"type": "integer", "minimum": 0, "maximum": 65536},
"reason": {"type": "string", "enum": ["forwarded", "loop", "policy", "rate", "provider", "malformed"]}
}
},
"StableError": {
"type": "object",
"additionalProperties": false,
"required": ["version", "code", "message", "retryable"],
"properties": {
"version": {"type": "string", "const": "1"},
"code": {"type": "string", "minLength": 1, "maxLength": 128},
"message": {"type": "string", "minLength": 1, "maxLength": 512},
"retryable": {"type": "boolean"}
}
}
}
}
+198
View File
@@ -1,6 +1,7 @@
package protocol_test
import (
"reflect"
"strings"
"testing"
@@ -35,3 +36,200 @@ func TestGeneratedDecodersRejectMissingRequiredFieldsAndTrailingValues(t *testin
t.Fatal("DecodeErrorEnvelope accepted a missing required boolean")
}
}
func TestGatewayContractsRejectUnknownVersionsAndFields(t *testing.T) {
registration := `{"version":"1","gateway_id":"gateway-1","instance_identity":"instance-1","certificate_identity":"cert-1","public_identity":"public-1","address":"gateway.test:443","provider_identity":"apollo-provider-1","protocol_min_version":1,"protocol_max_version":1,"connection_capacity":8,"bandwidth_capacity_kbps":100000,"features":["datagram.media"],"capabilities":{"transport":"quic","framing":"datagram-v1","media":"encoded","audio":"encoded","source_rate_control":"server","client_decode":["h264-opus"]}}`
if _, err := protocol.DecodeGatewayRegistration([]byte(registration)); err != nil {
t.Fatalf("valid gateway registration rejected: %v", err)
}
for _, invalid := range []string{
strings.Replace(registration, `"version":"1"`, `"version":"2"`, 1),
strings.Replace(registration, `"version":"1"`, `"version":"0"`, 1),
strings.Replace(registration, `"features":["datagram.media"]`, `"features":["datagram.media"],"provider_url":"https://provider.invalid"`, 1),
} {
if _, err := protocol.DecodeGatewayRegistration([]byte(invalid)); err == nil {
t.Fatalf("invalid gateway registration accepted: %s", invalid)
}
}
if _, err := protocol.DecodeGatewayRegistration([]byte("{")); err == nil {
t.Fatal("DecodeGatewayRegistration accepted malformed JSON")
}
}
func TestGatewayRegistrationRejectsInvertedProtocolBounds(t *testing.T) {
registration := `{"version":"1","gateway_id":"gateway-1","instance_identity":"instance-1","certificate_identity":"cert-1","public_identity":"public-1","address":"gateway.test:443","provider_identity":"apollo-provider-1","protocol_min_version":2,"protocol_max_version":1,"connection_capacity":8,"bandwidth_capacity_kbps":100000,"features":["datagram.media"],"capabilities":{"transport":"quic","framing":"datagram-v1","media":"encoded","audio":"encoded","source_rate_control":"server","client_decode":["h264-opus"]}}`
if _, err := protocol.DecodeGatewayRegistration([]byte(registration)); err == nil {
t.Fatal("DecodeGatewayRegistration accepted inverted protocol bounds")
}
}
func TestGatewayHeartbeatCarriesBoundedObservedTelemetry(t *testing.T) {
valid := `{"version":"1","gateway_id":"gateway-1","sequence":1,"observed_at":"2099-01-01T00:00:00Z","active_connections":1,"egress_kbps":64,"state":"ready","telemetry":{"admitted_sessions":2,"admission_rejects":3,"reconnects":4,"drain_transitions":5,"media_drops":6,"media_packets":7,"media_bytes":8000,"queue_delay_micros":9,"processing_delay_micros":10,"processing_samples":11,"pacing_delay_micros":12,"provider_errors":13,"input_rejected":14,"control_rtt_micros":15,"control_jitter_micros":16,"control_loss_ppm":17,"pending_reliable":18,"provider_state":"ready"}}`
if _, err := protocol.DecodeGatewayHeartbeat([]byte(valid)); err != nil {
t.Fatalf("valid gateway heartbeat rejected: %v", err)
}
for _, invalid := range []string{
strings.Replace(valid, `,"telemetry":{`, `,"session_id":"forbidden","telemetry":{`, 1),
strings.Replace(valid, `"control_loss_ppm":17`, `"control_loss_ppm":1000001`, 1),
strings.Replace(valid, `"provider_state":"ready"`, `"provider_state":"provider.example:47984"`, 1),
} {
if _, err := protocol.DecodeGatewayHeartbeat([]byte(invalid)); err == nil {
t.Fatalf("invalid gateway heartbeat accepted: %s", invalid)
}
}
}
func TestCapabilityIntersectionRejectsNoOverlap(t *testing.T) {
first := protocol.CapabilityProfile{Transport: "quic-tls13", Framing: "datagram-v1", Media: "encoded", Audio: "encoded", SourceRateControl: "server", ClientDecode: []string{"h264-opus"}}
if got, err := protocol.IntersectCapabilityProfiles(first, first); err != nil || !reflect.DeepEqual(got, first) {
t.Fatalf("IntersectCapabilityProfiles matching profiles = %+v, %v", got, err)
}
second := first
second.ClientDecode = []string{"hevc-opus"}
if _, err := protocol.IntersectCapabilityProfiles(first, second); err == nil {
t.Fatal("IntersectCapabilityProfiles accepted profiles without a common codec profile")
}
}
func TestCapabilityIntersectionSelectsRegisteredOrderedProfiles(t *testing.T) {
gateway := protocol.CapabilityProfile{
Transport: "quic-tls13", Framing: "datagram-v1", Media: "encoded", Audio: "encoded",
SourceRateControl: "server", ClientDecode: []string{"hevc-opus", "h264-opus"},
}
h264Client := gateway
h264Client.ClientDecode = []string{"h264-opus"}
selected, err := protocol.IntersectCapabilityProfiles(gateway, h264Client)
if err != nil || !reflect.DeepEqual(selected.ClientDecode, []string{"h264-opus"}) {
t.Fatalf("H.264 profile intersection = %+v, %v", selected, err)
}
hevcClient := gateway
hevcClient.ClientDecode = []string{"hevc-opus"}
selected, err = protocol.IntersectCapabilityProfiles(gateway, hevcClient)
if err != nil || !reflect.DeepEqual(selected.ClientDecode, []string{"hevc-opus"}) {
t.Fatalf("HEVC profile intersection = %+v, %v", selected, err)
}
noOverlap := gateway
noOverlap.ClientDecode = []string{"h264-opus"}
if _, err := protocol.IntersectCapabilityProfiles(noOverlap, hevcClient); err == nil {
t.Fatal("intersection accepted registered profiles without overlap")
}
for _, invalid := range [][]string{{"h264-hevc-opus"}, {"h264-opus", "h264-opus"}} {
profile := gateway
profile.ClientDecode = invalid
if err := profile.Validate(); err == nil {
t.Fatalf("CapabilityProfile accepted invalid registered profile set %q", invalid)
}
}
}
func TestTunnelAdmissionRequiresDeviceSignature(t *testing.T) {
request := protocol.TunnelAdmissionRequest{
Version: "1", SessionID: "session-1", GatewayID: "gateway-1", Audience: "versevdi-gateway",
Grant: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_", ReconnectSequence: 0,
ClientNonce: "0123456789abcdef", Capabilities: protocol.CapabilityProfile{
Transport: "quic-tls13", Framing: "datagram-v1", Media: "encoded", Audio: "encoded",
SourceRateControl: "server", ClientDecode: []string{"h264-opus"},
},
}
if _, err := protocol.EncodeTunnelAdmissionRequest(request); err == nil {
t.Fatal("EncodeTunnelAdmissionRequest accepted an unsigned device admission")
}
}
func TestTunnelAdmissionTranscriptIsDomainSeparatedAndLengthDelimited(t *testing.T) {
request := protocol.TunnelAdmissionRequest{
Version: "1", SessionID: "session", GatewayID: "gateway", Audience: "audience",
Grant: strings.Repeat("g", 43), ReconnectSequence: 0, ClientNonce: strings.Repeat("n", 16),
DeviceSignature: strings.Repeat("s", 86), Capabilities: protocol.CapabilityProfile{
Transport: "quic-tls13", Framing: "datagram-v1", Media: "encoded", Audio: "encoded",
SourceRateControl: "server", ClientDecode: []string{"h264-opus"},
},
}
want := "versevdi/tunnel-admission/v17:session7:gateway8:audience43:" + strings.Repeat("g", 43) + "1:016:" + strings.Repeat("n", 16) + "10:quic-tls1311:datagram-v17:encoded7:encoded6:server1:19:h264-opus"
if got := string(request.DeviceAdmissionTranscript()); got != want {
t.Fatalf("DeviceAdmissionTranscript() = %q, want %q", got, want)
}
}
func TestSessionAuthorityRejectsProviderRoute(t *testing.T) {
valid := `{"version":"1","session_id":"session-1","gateway_id":"gateway-1","audience":"versevdi-gateway","reconnect_sequence":0,"expires_at":"2099-01-01T00:00:00Z","capabilities":{"transport":"quic","framing":"datagram-v1","media":"encoded","audio":"encoded","source_rate_control":"server","client_decode":["h264-opus"]},"provider_profile":"apollo","provider_identity":"provider-1"}`
if _, err := protocol.DecodeSessionAuthority([]byte(valid)); err != nil {
t.Fatalf("valid session authority rejected: %v", err)
}
if _, err := protocol.DecodeSessionAuthority([]byte(strings.Replace(valid, `"provider_identity":"provider-1"`, `"provider_identity":"provider-1","rtsp_url":"rtsp://provider.invalid"`, 1))); err == nil {
t.Fatal("session authority accepted a provider route")
}
}
func TestProviderSessionWorkIsStrictAndSessionBound(t *testing.T) {
valid := `{"version":"1","session_id":"session-1","gateway_id":"gateway-1","reconnect_sequence":0,"expires_at":"2099-01-01T00:00:00Z","provider_profile":"apollo","provider_identity":"provider-1","policy_version_id":"policy-1","stream_policy":{"resolution_width":2560,"resolution_height":1440,"fps":120,"codec":"HEVC","bitrate_kbps":40000,"audio_enabled":true},"application_id":"42","client_id":"paired-client-1","management_host":"apollo.test","management_port":47990,"stream_host":"apollo.test","stream_port":47984,"client_certificate_pem":"certificate","client_private_key_pem":"private-key","server_certificate_pem":"server-certificate","clipboard_policy":{"client_to_provider_enabled":false,"provider_to_client_enabled":false,"max_text_bytes":65536,"max_updates_per_minute":30},"provider_application_termination_allowed":false}`
if _, err := protocol.DecodeProviderSessionWork([]byte(valid)); err != nil {
t.Fatalf("valid provider work rejected: %v", err)
}
if _, err := protocol.DecodeProviderSessionWork([]byte(strings.Replace(valid, `"application_id":"42"`, `"application_id":"42","management_password":"forbidden"`, 1))); err == nil {
t.Fatal("provider work accepted a management credential")
}
if _, err := protocol.DecodeProviderSessionWork([]byte(strings.Replace(valid, `,"clipboard_policy":{"client_to_provider_enabled":false,"provider_to_client_enabled":false,"max_text_bytes":65536,"max_updates_per_minute":30}`, "", 1))); err == nil {
t.Fatal("provider work accepted missing clipboard policy")
}
for _, invalid := range []string{
strings.Replace(valid, `,"stream_policy":{"resolution_width":2560,"resolution_height":1440,"fps":120,"codec":"HEVC","bitrate_kbps":40000,"audio_enabled":true}`, "", 1),
strings.Replace(valid, `"fps":120`, `"fps":241`, 1),
strings.Replace(valid, `"codec":"HEVC"`, `"codec":"VP9"`, 1),
strings.Replace(valid, `"audio_enabled":true`, `"audio_enabled":true,"unknown":false`, 1),
} {
if _, err := protocol.DecodeProviderSessionWork([]byte(invalid)); err == nil {
t.Fatalf("provider work accepted invalid stream policy: %s", invalid)
}
}
}
func TestGatewayClipboardAuditIsMetadataOnlyAndStrict(t *testing.T) {
valid := `{"version":"1","session_id":"session-1","direction":"client_to_provider","outcome":"rejected","text_bytes":64,"reason":"rate"}`
if _, err := protocol.DecodeGatewayClipboardAudit([]byte(valid)); err != nil {
t.Fatalf("valid clipboard audit rejected: %v", err)
}
for _, invalid := range []string{
strings.Replace(valid, `"reason":"rate"`, `"reason":"text"`, 1),
strings.Replace(valid, `"text_bytes":64`, `"text_bytes":65537`, 1),
strings.Replace(valid, `"reason":"rate"`, `"reason":"rate","text":"forbidden"`, 1),
} {
if _, err := protocol.DecodeGatewayClipboardAudit([]byte(invalid)); err == nil {
t.Fatalf("invalid clipboard audit accepted: %s", invalid)
}
}
}
func TestGatewayClipboardTextMeasuresDecodedUTF8Bytes(t *testing.T) {
for name, text := range map[string]string{
"ascii-boundary": strings.Repeat("a", 65536),
"utf8-boundary": strings.Repeat("é", 32768),
"escape-heavy": strings.Repeat(`"`, 32768),
} {
t.Run(name, func(t *testing.T) {
value := protocol.GatewayClipboardText{
Direction: "client_to_provider",
Text: text,
Encoding: "utf-8",
LoopToken: "abcdefghijklmnop",
}
encoded, err := protocol.EncodeGatewayClipboardText(value)
if err != nil {
t.Fatalf("EncodeGatewayClipboardText() error = %v", err)
}
decoded, err := protocol.DecodeGatewayClipboardText(encoded)
if err != nil || decoded.Text != text {
t.Fatalf("DecodeGatewayClipboardText() = %d bytes, %v", len(decoded.Text), err)
}
})
}
tooLarge := protocol.GatewayClipboardText{
Direction: "client_to_provider",
Text: strings.Repeat("a", 65537),
Encoding: "utf-8",
LoopToken: "abcdefghijklmnop",
}
if _, err := protocol.EncodeGatewayClipboardText(tooLarge); err == nil {
t.Fatal("EncodeGatewayClipboardText() accepted 65,537 decoded UTF-8 bytes")
}
}
+28 -15
View File
@@ -30,6 +30,9 @@ SECRET_PATTERNS = (
re.compile(rb"\bgh[pousr]_[A-Za-z0-9]{20,}\b"),
re.compile(rb"\bsk-[A-Za-z0-9]{20,}\b"),
)
ALLOWED_SECRET_PROPERTIES = {
("ProviderSessionWork", "client_private_key_pem"),
}
def fail(message: str) -> None:
@@ -53,19 +56,36 @@ def check_generated_provenance() -> None:
def check_manifest_schema() -> None:
schema = json.loads((ROOT / "schemas/control-v1.schema.json").read_text(encoding="utf-8"))
definitions = schema.get("$defs", {})
for name in ("ConnectionManifest", "ManifestGateway", "ManifestTunnel", "ManifestProfile", "ManifestBounds", "GrantReference"):
properties = definitions.get(name, {}).get("properties", {})
forbidden = sorted(FORBIDDEN_WIRE_FIELDS.intersection(properties))
if forbidden:
fail(f"{name} exposes forbidden wire fields: {forbidden}")
for name, definition in definitions.items():
for field in definition.get("properties", {}):
if any(forbidden in field.lower() for forbidden in FORBIDDEN_WIRE_FIELDS):
if (name, field) not in ALLOWED_SECRET_PROPERTIES:
fail(f"{name} exposes forbidden wire field {field}")
def check_proto_boundaries(path: pathlib.Path) -> None:
message = ""
depth = 0
for line in path.read_text(encoding="utf-8").splitlines():
match = re.match(r"\s*message\s+([A-Za-z0-9_]+)\s*\{", line)
if match and depth == 0:
message = match.group(1)
if any(field in line.lower() for field in FORBIDDEN_WIRE_FIELDS):
allowed = (
message == "ProviderSessionWork"
and re.fullmatch(r"\s*string\s+client_private_key_pem\s*=\s*[0-9]+;\s*", line)
)
if not allowed:
fail(f"{path.relative_to(ROOT)} exposes forbidden wire field in {message or 'file scope'}")
depth += line.count("{") - line.count("}")
if depth == 0:
message = ""
def check_text_boundaries() -> None:
paths = [
ROOT / "openapi/control-v1.yaml",
ROOT / "schemas/control-v1.schema.json",
ROOT / "proto/versevdi/control/v1/control.proto",
ROOT / "proto/versevdi/tunnel/v1/tunnel.proto",
ROOT / "frames/datagram-v1.md",
ROOT / "frames/registry.json",
ROOT / "registries/features.json",
@@ -77,14 +97,7 @@ def check_text_boundaries() -> None:
if field in text:
fail(f"{path.relative_to(ROOT)} contains forbidden wire field {field}")
generated_paths = list((ROOT / "gen").rglob("*"))
for path in generated_paths:
if not path.is_file() or path.name == "manifest.json" or path.suffix in {".pb", ".binpb"}:
continue
text = path.read_text(encoding="utf-8").lower()
for field in FORBIDDEN_WIRE_FIELDS:
if field in text:
fail(f"generated output {path.relative_to(ROOT)} contains forbidden wire field {field}")
check_proto_boundaries(ROOT / "proto/versevdi/tunnel/v1/tunnel.proto")
def check_secret_canaries() -> None:
+313 -7
View File
@@ -125,6 +125,8 @@ def go_validation(definition: dict[str, Any]) -> list[str]:
lines.append(f"\tif len(v.{field}) < {prop['minLength']} && v.{field} != \"\" {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"min_length\"}}) }}")
if "maxLength" in prop:
lines.append(f"\tif len(v.{field}) > {prop['maxLength']} {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"max_length\"}}) }}")
if "x-max-bytes" in prop:
lines.append(f"\tif len(v.{field}) > {prop['x-max-bytes']} {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"max_bytes\"}}) }}")
if "const" in prop:
lines.append(f"\tif v.{field} != \"{prop['const']}\" && v.{field} != \"\" {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"invalid_value\"}}) }}")
if "enum" in prop:
@@ -135,6 +137,8 @@ def go_validation(definition: dict[str, Any]) -> list[str]:
'\tif v.%s != "" { if parsed, err := time.Parse(time.RFC3339Nano, v.%s); err != nil || parsed.UTC().Format(time.RFC3339Nano) != v.%s { violations = append(violations, FieldViolation{Field: "%s", Code: "invalid_time"}) } }'
% (field, field, field, prop_name)
)
if prop.get("format") == "base64url":
lines.append(f"\tif v.{field} != \"\" {{ if _, err := base64.RawURLEncoding.Strict().DecodeString(v.{field}); err != nil {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"invalid_format\"}}) }} }}")
if prop.get("type") == "integer":
if "minimum" in prop:
lines.append(f"\tif v.{field} != 0 && v.{field} < {prop['minimum']} {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"minimum\"}}) }}")
@@ -145,12 +149,24 @@ def go_validation(definition: dict[str, Any]) -> list[str]:
lines.append(f"\tif len(v.{field}) < {prop['minItems']} {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"min_items\"}}) }}")
if "maxItems" in prop:
lines.append(f"\tif len(v.{field}) > {prop['maxItems']} {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"max_items\"}}) }}")
item_ref = ref_name(prop.get("items", {}))
items = prop.get("items", {})
if "enum" in items:
allowed = " || ".join(f'item == "{value}"' for value in items["enum"])
lines.append(f"\tfor _, item := range v.{field} {{ if !({allowed}) {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"invalid_item\"}}) }} }}")
if prop.get("uniqueItems") and items.get("type") == "string":
lines.append(f"\tfor index, item := range v.{field} {{ for prior := 0; prior < index; prior++ {{ if item == v.{field}[prior] {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"duplicate_item\"}}) }} }} }}")
item_ref = ref_name(items)
if item_ref:
lines.append(f"\tfor index := range v.{field} {{ if err := v.{field}[index].Validate(); err != nil {{ violations = append(violations, FieldViolation{{Field: fmt.Sprintf(\"{prop_name}[%d]\", index), Code: \"invalid_item\"}}) }} }}")
reference = ref_name(prop)
if reference:
lines.append(f"\tif err := v.{field}.Validate(); err != nil {{ violations = append(violations, FieldViolation{{Field: \"{prop_name}\", Code: \"invalid_object\"}}) }}")
if name in {"AllocationPolicy", "ManifestBounds"}:
lines.append("\tif v.MinimumKbps > v.TargetKbps || v.TargetKbps > v.MaximumKbps { violations = append(violations, FieldViolation{Field: \"bounds\", Code: \"invalid_order\"}) }")
if name == "GatewayRegistration":
lines.append("\tif v.ProtocolMinVersion > v.ProtocolMaxVersion { violations = append(violations, FieldViolation{Field: \"protocol_version\", Code: \"invalid_order\"}) }")
if name == "ChannelFrame":
lines.append("\tif v.FragmentIndex >= v.FragmentCount { violations = append(violations, FieldViolation{Field: \"fragment_index\", Code: \"invalid_order\"}) }")
return lines
@@ -161,10 +177,12 @@ def generate_go(defs: dict[str, dict[str, Any]], schema_hash: str, version: str,
"",
"import (",
"\"bytes\"",
"\"encoding/base64\"",
"\"encoding/json\"",
"\"errors\"",
"\"fmt\"",
"\"reflect\"",
"\"strings\"",
"\"time\"",
")",
"",
@@ -216,7 +234,7 @@ def generate_go(defs: dict[str, dict[str, Any]], schema_hash: str, version: str,
% (prop_name, prop_name)
)
for prop_name, prop in defs[name].get("properties", {}).items():
if "x-max-bytes" in prop:
if "x-max-bytes" in prop and prop.get("type") != "string":
out.append(
'\tif raw, ok := fields["%s"]; ok && len(raw) > %d { return value, ValidationError{Violations: []FieldViolation{{Field: "%s", Code: "max_bytes"}}} }'
% (prop_name, prop["x-max-bytes"], prop_name)
@@ -235,6 +253,37 @@ def generate_go(defs: dict[str, dict[str, Any]], schema_hash: str, version: str,
out.append("\treturn json.Marshal(value)")
out.append("}")
out.append("")
out.extend([
"var ErrNoCapabilityOverlap = errors.New(\"no capability overlap\")",
"",
"func IntersectCapabilityProfiles(profiles ...CapabilityProfile) (CapabilityProfile, error) {",
"\tif len(profiles) == 0 { return CapabilityProfile{}, ErrNoCapabilityOverlap }",
"\tselected := profiles[0]",
"\tif err := selected.Validate(); err != nil { return CapabilityProfile{}, ErrNoCapabilityOverlap }",
"\tcommon := append([]string(nil), selected.ClientDecode...)",
"\tfor _, profile := range profiles[1:] {",
"\t\tif err := profile.Validate(); err != nil || profile.Transport != selected.Transport || profile.Framing != selected.Framing || profile.Media != selected.Media || profile.Audio != selected.Audio || profile.SourceRateControl != selected.SourceRateControl { return CapabilityProfile{}, ErrNoCapabilityOverlap }",
"\t\tnext := common[:0]",
"\t\tfor _, candidate := range common { for _, offered := range profile.ClientDecode { if candidate == offered { next = append(next, candidate); break } } }",
"\t\tcommon = next",
"\t\tif len(common) == 0 { return CapabilityProfile{}, ErrNoCapabilityOverlap }",
"\t}",
"\tselected.ClientDecode = common",
"\treturn selected, nil",
"}",
"",
])
out.extend([
"func (v TunnelAdmissionRequest) DeviceAdmissionTranscript() []byte {",
"\tfields := []string{v.SessionID, v.GatewayID, v.Audience, v.Grant, fmt.Sprintf(\"%d\", v.ReconnectSequence), v.ClientNonce, v.Capabilities.Transport, v.Capabilities.Framing, v.Capabilities.Media, v.Capabilities.Audio, v.Capabilities.SourceRateControl, fmt.Sprintf(\"%d\", len(v.Capabilities.ClientDecode))}",
"\tfields = append(fields, v.Capabilities.ClientDecode...)",
"\tvar transcript strings.Builder",
"\ttranscript.WriteString(\"versevdi/tunnel-admission/v1\")",
"\tfor _, field := range fields { fmt.Fprintf(&transcript, \"%d:%s\", len(field), field) }",
"\treturn []byte(transcript.String())",
"}",
"",
])
# Use io.EOF in generated code without making every generated decoder depend on
# error-string comparison; replace the deliberately compact placeholder.
text = "\n".join(out).replace('"errors"\n"fmt"', '"errors"\n"fmt"\n\"io"')
@@ -272,6 +321,68 @@ def swift_type(prop: dict[str, Any]) -> str:
return "String"
def rust_validation(definition: dict[str, Any]) -> list[str]:
lines: list[str] = []
required = set(definition.get("required", []))
for prop_name, prop in definition.get("properties", {}).items():
field = rust_field(prop_name)
value = f"self.{field}"
if prop_name not in required:
value = f"value"
lines.append(f" if let Some(value) = &self.{field} {{")
prefix, suffix = " ", " }"
else:
prefix, suffix = "", ""
if prop.get("type") == "string":
if prop_name in required and prop.get("minLength", 0) > 0:
lines.append(f" {prefix}if {value}.is_empty() {{ return Err(ValidationError::new(\"{prop_name}\", \"required\")); }}")
if "minLength" in prop:
lines.append(f" {prefix}if !{value}.is_empty() && {value}.len() < {prop['minLength']} {{ return Err(ValidationError::new(\"{prop_name}\", \"min_length\")); }}")
if "maxLength" in prop:
lines.append(f" {prefix}if {value}.len() > {prop['maxLength']} {{ return Err(ValidationError::new(\"{prop_name}\", \"max_length\")); }}")
if "x-max-bytes" in prop:
lines.append(f" {prefix}if {value}.as_bytes().len() > {prop['x-max-bytes']} {{ return Err(ValidationError::new(\"{prop_name}\", \"max_bytes\")); }}")
if "const" in prop:
lines.append(f" {prefix}if {value} != \"{prop['const']}\" {{ return Err(ValidationError::new(\"{prop_name}\", \"invalid_value\")); }}")
if "enum" in prop:
allowed = " && ".join(f'{value} != \"{item}\"' for item in prop["enum"])
lines.append(f" {prefix}if {allowed} {{ return Err(ValidationError::new(\"{prop_name}\", \"invalid_value\")); }}")
if prop.get("format") == "base64url":
lines.append(f" {prefix}if !valid_base64_url({value}.as_str()) {{ return Err(ValidationError::new(\"{prop_name}\", \"invalid_format\")); }}")
if prop.get("type") == "integer":
if "minimum" in prop:
lines.append(f" {prefix}if {value} < {prop['minimum']} {{ return Err(ValidationError::new(\"{prop_name}\", \"minimum\")); }}")
if "maximum" in prop:
lines.append(f" {prefix}if {value} > {prop['maximum']} {{ return Err(ValidationError::new(\"{prop_name}\", \"maximum\")); }}")
if prop.get("type") == "array":
if "minItems" in prop:
lines.append(f" {prefix}if {value}.len() < {prop['minItems']} {{ return Err(ValidationError::new(\"{prop_name}\", \"min_items\")); }}")
if "maxItems" in prop:
lines.append(f" {prefix}if {value}.len() > {prop['maxItems']} {{ return Err(ValidationError::new(\"{prop_name}\", \"max_items\")); }}")
items = prop.get("items", {})
if "enum" in items:
allowed = " && ".join(f'item != \"{item}\"' for item in items["enum"])
lines.append(f" {prefix}for item in {value}.iter() {{ if {allowed} {{ return Err(ValidationError::new(\"{prop_name}\", \"invalid_item\")); }} }}")
if prop.get("uniqueItems") and items.get("type") == "string":
lines.append(f" {prefix}for (index, item) in {value}.iter().enumerate() {{ if {value}[..index].contains(item) {{ return Err(ValidationError::new(\"{prop_name}\", \"duplicate_item\")); }} }}")
item_ref = ref_name(items)
if item_ref:
lines.append(f" {prefix}for item in {value}.iter() {{ item.validate().map_err(|_| ValidationError::new(\"{prop_name}\", \"invalid_item\"))?; }}")
reference = ref_name(prop)
if reference:
lines.append(f" {prefix}{value}.validate().map_err(|_| ValidationError::new(\"{prop_name}\", \"invalid_object\"))?;")
if suffix:
lines.append(suffix)
name = definition["name"]
if name in {"AllocationPolicy", "ManifestBounds"}:
lines.append(" if self.minimumKbps > self.targetKbps || self.targetKbps > self.maximumKbps { return Err(ValidationError::new(\"bounds\", \"invalid_order\")); }")
if name == "GatewayRegistration":
lines.append(" if self.protocolMinVersion > self.protocolMaxVersion { return Err(ValidationError::new(\"protocol_version\", \"invalid_order\")); }")
if name == "ChannelFrame":
lines.append(" if self.fragmentIndex >= self.fragmentCount { return Err(ValidationError::new(\"fragment_index\", \"invalid_order\")); }")
return lines
def generate_rust(defs: dict[str, dict[str, Any]], schema_hash: str, compatibility: dict[str, Any]) -> str:
out = [
"// Code generated by tools/generate.py; DO NOT EDIT.",
@@ -282,6 +393,31 @@ def generate_rust(defs: dict[str, dict[str, Any]], schema_hash: str, compatibili
f'pub const N_MINUS_2_WIRE_VERSION: &str = "{compatibility["n_minus_2"]}";',
"pub type JsonObject = std::collections::BTreeMap<String, String>;",
"",
"#[derive(Debug, Clone, PartialEq, Eq)]",
"pub struct ValidationError { pub field: &'static str, pub code: &'static str }",
"impl ValidationError { pub const fn new(field: &'static str, code: &'static str) -> Self { Self { field, code } } }",
"",
"fn base64url_value(value: u8) -> Option<u8> {",
" match value {",
" b'A'..=b'Z' => Some(value - b'A'),",
" b'a'..=b'z' => Some(value - b'a' + 26),",
" b'0'..=b'9' => Some(value - b'0' + 52),",
" b'-' => Some(62),",
" b'_' => Some(63),",
" _ => None,",
" }",
"}",
"fn valid_base64_url(value: &str) -> bool {",
" let bytes = value.as_bytes();",
" if bytes.is_empty() || bytes.iter().any(|byte| base64url_value(*byte).is_none()) { return false; }",
" match bytes.len() % 4 {",
" 0 => true,",
" 2 => base64url_value(*bytes.last().unwrap()).unwrap() & 0x0f == 0,",
" 3 => base64url_value(*bytes.last().unwrap()).unwrap() & 0x03 == 0,",
" _ => false,",
" }",
"}",
"",
]
for name in sorted(defs):
definition = defs[name]
@@ -292,11 +428,127 @@ def generate_rust(defs: dict[str, dict[str, Any]], schema_hash: str, compatibili
typ = rust_type(prop)
if prop_name not in required:
typ = f"Option<{typ}>"
out.append(f" pub {field}: {typ},")
out.append(f" {field}: {typ},")
out.extend(["}", ""])
parameters: list[str] = []
assignments: list[str] = []
for prop_name, prop in definition.get("properties", {}).items():
field = rust_field(prop_name)
typ = rust_type(prop)
if prop_name not in required:
typ = f"Option<{typ}>"
parameters.append(f"{field}: {typ}")
assignments.append(field)
out.append(f"impl {name} {{")
out.append(f" pub fn new({', '.join(parameters)}) -> Result<Self, ValidationError> {{")
out.append(f" let value = Self {{ {', '.join(assignments)} }};")
out.append(" value.validate()?;")
out.append(" Ok(value)")
out.append(" }")
out.append(" pub fn validate(&self) -> Result<(), ValidationError> {")
out.extend(rust_validation(definition))
out.append(" Ok(())")
out.append(" }")
for prop_name, prop in definition.get("properties", {}).items():
field = rust_field(prop_name)
typ = rust_type(prop)
if prop_name not in required:
typ = f"Option<{typ}>"
out.append(f" pub fn {field}(&self) -> &{typ} {{ &self.{field} }}")
if name == "TunnelAdmissionRequest":
out.extend([
" pub fn device_admission_transcript(&self) -> Vec<u8> {",
" let reconnect_sequence = self.reconnectSequence.to_string();",
" let client_decode_count = self.capabilities.clientDecode.len().to_string();",
" let mut fields = vec![self.sessionId.as_str(), self.gatewayId.as_str(), self.audience.as_str(), self.grant.as_str(), reconnect_sequence.as_str(), self.clientNonce.as_str(), self.capabilities.transport.as_str(), self.capabilities.framing.as_str(), self.capabilities.media.as_str(), self.capabilities.audio.as_str(), self.capabilities.sourceRateControl.as_str(), client_decode_count.as_str()];",
" fields.extend(self.capabilities.clientDecode.iter().map(String::as_str));",
" let mut transcript = String::from(\"versevdi/tunnel-admission/v1\");",
" for field in fields { transcript.push_str(&format!(\"{}:{}\", field.as_bytes().len(), field)); }",
" transcript.into_bytes()",
" }",
])
out.extend(["}", ""])
out.extend([
"pub fn intersect_capability_profiles(profiles: &[CapabilityProfile]) -> Result<CapabilityProfile, ValidationError> {",
" let mut selected = profiles.first().ok_or_else(|| ValidationError::new(\"capabilities\", \"no_overlap\"))?.clone();",
" selected.validate().map_err(|_| ValidationError::new(\"capabilities\", \"no_overlap\"))?;",
" for profile in &profiles[1..] {",
" profile.validate().map_err(|_| ValidationError::new(\"capabilities\", \"no_overlap\"))?;",
" if profile.transport != selected.transport || profile.framing != selected.framing || profile.media != selected.media || profile.audio != selected.audio || profile.sourceRateControl != selected.sourceRateControl { return Err(ValidationError::new(\"capabilities\", \"no_overlap\")); }",
" selected.clientDecode.retain(|candidate| profile.clientDecode.contains(candidate));",
" if selected.clientDecode.is_empty() { return Err(ValidationError::new(\"capabilities\", \"no_overlap\")); }",
" }",
" Ok(selected)",
"}",
"",
])
return "\n".join(out)
def swift_validation(definition: dict[str, Any]) -> list[str]:
lines: list[str] = []
required = set(definition.get("required", []))
for prop_name, prop in definition.get("properties", {}).items():
field = swift_field(prop_name)
value = f"self.{field}"
if prop_name not in required:
value = "value"
lines.append(f" if let value = self.{field} {{")
prefix, suffix = " ", " }"
else:
prefix, suffix = "", ""
if prop.get("type") == "string":
if prop_name in required and prop.get("minLength", 0) > 0:
lines.append(f" {prefix}if {value}.isEmpty {{ throw ContractValidationError(field: \"{prop_name}\", code: \"required\") }}")
if "minLength" in prop:
lines.append(f" {prefix}if !{value}.isEmpty && {value}.utf8.count < {prop['minLength']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"min_length\") }}")
if "maxLength" in prop:
lines.append(f" {prefix}if {value}.utf8.count > {prop['maxLength']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"max_length\") }}")
if "x-max-bytes" in prop:
lines.append(f" {prefix}if {value}.utf8.count > {prop['x-max-bytes']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"max_bytes\") }}")
if "const" in prop:
lines.append(f" {prefix}if {value} != \"{prop['const']}\" {{ throw ContractValidationError(field: \"{prop_name}\", code: \"invalid_value\") }}")
if "enum" in prop:
allowed = ", ".join(f'\"{item}\"' for item in prop["enum"])
lines.append(f" {prefix}if ![{allowed}].contains({value}) {{ throw ContractValidationError(field: \"{prop_name}\", code: \"invalid_value\") }}")
if prop.get("format") == "date-time":
lines.append(f" {prefix}if ISO8601DateFormatter().date(from: {value}) == nil {{ throw ContractValidationError(field: \"{prop_name}\", code: \"invalid_time\") }}")
if prop.get("format") == "base64url":
lines.append(f" {prefix}if !validBase64URL({value}) {{ throw ContractValidationError(field: \"{prop_name}\", code: \"invalid_format\") }}")
if prop.get("type") == "integer":
if "minimum" in prop:
lines.append(f" {prefix}if {value} < {prop['minimum']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"minimum\") }}")
if "maximum" in prop:
lines.append(f" {prefix}if {value} > {prop['maximum']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"maximum\") }}")
if prop.get("type") == "array":
if "minItems" in prop:
lines.append(f" {prefix}if {value}.count < {prop['minItems']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"min_items\") }}")
if "maxItems" in prop:
lines.append(f" {prefix}if {value}.count > {prop['maxItems']} {{ throw ContractValidationError(field: \"{prop_name}\", code: \"max_items\") }}")
items = prop.get("items", {})
if "enum" in items:
allowed = ", ".join(f'\"{item}\"' for item in items["enum"])
lines.append(f" {prefix}for item in {value} where ![{allowed}].contains(item) {{ throw ContractValidationError(field: \"{prop_name}\", code: \"invalid_item\") }}")
if prop.get("uniqueItems") and items.get("type") == "string":
lines.append(f" {prefix}if Set({value}).count != {value}.count {{ throw ContractValidationError(field: \"{prop_name}\", code: \"duplicate_item\") }}")
item_ref = ref_name(items)
if item_ref:
lines.append(f" {prefix}for item in {value} {{ try item.validate() }}")
reference = ref_name(prop)
if reference:
lines.append(f" {prefix}try {value}.validate()")
if suffix:
lines.append(suffix)
name = definition["name"]
if name in {"AllocationPolicy", "ManifestBounds"}:
lines.append(" if minimumKbps > targetKbps || targetKbps > maximumKbps { throw ContractValidationError(field: \"bounds\", code: \"invalid_order\") }")
if name == "GatewayRegistration":
lines.append(" if protocolMinVersion > protocolMaxVersion { throw ContractValidationError(field: \"protocol_version\", code: \"invalid_order\") }")
if name == "ChannelFrame":
lines.append(" if fragmentIndex >= fragmentCount { throw ContractValidationError(field: \"fragment_index\", code: \"invalid_order\") }")
return lines
def generate_swift(defs: dict[str, dict[str, Any]], schema_hash: str, compatibility: dict[str, Any]) -> str:
out = [
"// Code generated by tools/generate.py; DO NOT EDIT.",
@@ -306,6 +558,17 @@ def generate_swift(defs: dict[str, dict[str, Any]], schema_hash: str, compatibil
f'public let currentWireVersion = "{compatibility["current"]}"',
f'public let nMinus1WireVersion = "{compatibility["n_minus_1"]}"',
f'public let nMinus2WireVersion = "{compatibility["n_minus_2"]}"',
"public struct ContractValidationError: Error, Equatable { public let field: String; public let code: String }",
"private struct AnyCodingKey: CodingKey { let stringValue: String; let intValue: Int?; init?(stringValue: String) { self.stringValue = stringValue; self.intValue = nil }; init?(intValue: Int) { self.stringValue = String(intValue); self.intValue = intValue } }",
"private func validBase64URL(_ value: String) -> Bool {",
" guard !value.isEmpty, value.utf8.allSatisfy({ byte in",
" (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122) || (byte >= 48 && byte <= 57) || byte == 45 || byte == 95",
" }) else { return false }",
" let padding = String(repeating: \"=\", count: (4 - value.utf8.count % 4) % 4)",
" let standard = value.replacingOccurrences(of: \"-\", with: \"+\").replacingOccurrences(of: \"_\", with: \"/\") + padding",
" guard let decoded = Data(base64Encoded: standard) else { return false }",
" return decoded.base64EncodedString().replacingOccurrences(of: \"+\", with: \"-\").replacingOccurrences(of: \"/\", with: \"_\").replacingOccurrences(of: \"=\", with: \"\") == value",
"}",
"",
]
for name in sorted(defs):
@@ -320,16 +583,59 @@ def generate_swift(defs: dict[str, dict[str, Any]], schema_hash: str, compatibil
out.append(" enum CodingKeys: String, CodingKey {")
for prop_name in definition.get("properties", {}):
out.append(f" case {swift_field(prop_name)} = \"{prop_name}\"")
out.extend([" }", "", " public init(from decoder: Decoder) throws {",])
parameters: list[str] = []
for prop_name, prop in definition.get("properties", {}).items():
typ = swift_type(prop)
if prop_name not in required:
typ += "?"
parameters.append(f"{swift_field(prop_name)}: {typ}")
out.extend([" }", "", f" public init({', '.join(parameters)}) throws {{"])
for prop_name in definition.get("properties", {}):
field = swift_field(prop_name)
out.append(f" self.{field} = {field}")
out.extend([" try validate()", " }", "", " public init(from decoder: Decoder) throws {"])
out.append(" let all = try decoder.container(keyedBy: AnyCodingKey.self)")
out.append(" for key in all.allKeys where CodingKeys(stringValue: key.stringValue) == nil { throw ContractValidationError(field: key.stringValue, code: \"unknown_field\") }")
out.append(" let c = try decoder.container(keyedBy: CodingKeys.self)")
decoded: list[str] = []
for prop_name, prop in definition.get("properties", {}).items():
field = swift_field(prop_name)
typ = swift_type(prop)
if prop_name in required:
out.append(f" {field} = try c.decode({typ}.self, forKey: .{field})")
decoded.append(f"{field}: try c.decode({typ}.self, forKey: .{field})")
else:
out.append(f" {field} = try c.decodeIfPresent({typ}.self, forKey: .{field})")
out.extend([" }", "}", ""])
decoded.append(f"{field}: try c.decodeIfPresent({typ}.self, forKey: .{field})")
out.append(f" try self.init({', '.join(decoded)})")
out.extend([" }", "", " public func validate() throws {"])
out.extend(swift_validation(definition))
out.extend([" }", "", " public static func decodeJSON(_ data: Data) throws -> Self { try JSONDecoder().decode(Self.self, from: data) }", " public func encodeJSON() throws -> Data { try validate(); return try JSONEncoder().encode(self) }", "}", ""])
out.extend([
"public extension TunnelAdmissionRequest {",
" func deviceAdmissionTranscript() -> Data {",
" var fields = [sessionId, gatewayId, audience, grant, String(reconnectSequence), clientNonce, capabilities.transport, capabilities.framing, capabilities.media, capabilities.audio, capabilities.sourceRateControl, String(capabilities.clientDecode.count)]",
" fields.append(contentsOf: capabilities.clientDecode)",
" var transcript = \"versevdi/tunnel-admission/v1\"",
" for field in fields { transcript += \"\\(field.utf8.count):\\(field)\" }",
" return Data(transcript.utf8)",
" }",
"}",
"",
"public extension CapabilityProfile {",
" static func intersection(_ profiles: [CapabilityProfile]) throws -> CapabilityProfile {",
" guard let selected = profiles.first else { throw ContractValidationError(field: \"capabilities\", code: \"no_overlap\") }",
" try selected.validate()",
" var common = selected.clientDecode",
" for profile in profiles.dropFirst() {",
" try profile.validate()",
" if profile.transport != selected.transport || profile.framing != selected.framing || profile.media != selected.media || profile.audio != selected.audio || profile.sourceRateControl != selected.sourceRateControl { throw ContractValidationError(field: \"capabilities\", code: \"no_overlap\") }",
" common = common.filter { profile.clientDecode.contains($0) }",
" if common.isEmpty { throw ContractValidationError(field: \"capabilities\", code: \"no_overlap\") }",
" }",
" return try CapabilityProfile(transport: selected.transport, framing: selected.framing, media: selected.media, audio: selected.audio, sourceRateControl: selected.sourceRateControl, clientDecode: common)",
" }",
"}",
"",
])
return "\n".join(out)
+173 -5
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strconv"
"strings"
"unicode/utf8"
protocol "git.sechmachine.io.vn/sechmachine/VerseVDI-Protocol/gen/go/protocol"
)
@@ -87,9 +88,9 @@ func evaluate(kind, input string) string {
Gateway: protocol.ManifestGateway{
ID: parts["gateway_id"], Addresses: []string{"gateway.control.test:443"}, PublicIdentity: parts["gateway_id"],
},
Tunnel: protocol.ManifestTunnel{Versions: []string{parts["protocol"] + "/1"}, Features: []string{"control.v1"}},
Profile: protocol.ManifestProfile{ID: "standard", Bounds: protocol.ManifestBounds{MinimumKbps: 1, TargetKbps: 2, MaximumKbps: 3}},
Grant: protocol.GrantReference{OpaqueValue: parts["grant"], ExpiresAt: parts["expires_at"], Audience: parts["audience"]},
Tunnel: protocol.ManifestTunnel{Versions: []string{parts["protocol"] + "/1"}, Features: []string{"control.v1"}},
Profile: protocol.ManifestProfile{ID: "standard", Bounds: protocol.ManifestBounds{MinimumKbps: 1, TargetKbps: 2, MaximumKbps: 3}},
Grant: protocol.GrantReference{OpaqueValue: parts["grant"], ExpiresAt: parts["expires_at"], Audience: parts["audience"]},
CorrelationID: "correlation-1",
}
if value.Validate() == nil {
@@ -118,7 +119,7 @@ func evaluate(kind, input string) string {
}
value := protocol.EventEnvelope{
EventID: "event-1", Sequence: sequence, Type: "broker.session.changed", Version: 1,
Resource: protocol.ResourceLink{Type: "broker_session", ID: "session-1", Version: 1},
Resource: protocol.ResourceLink{Type: "broker_session", ID: "session-1", Version: 1},
OccurredAt: "2099-01-01T00:00:00Z", CorrelationID: parts["correlation_id"], Payload: map[string]any{},
}
if payloadErr != nil || payloadBytes > 16384 {
@@ -138,11 +139,178 @@ func evaluate(kind, input string) string {
return "invalid:unsupported_version"
case "datagram":
return classifyDatagram(parts["hex"])
case "gateway_input":
return classifyGatewayInput(parts["hex"])
case "gateway_feedback":
return classifyGatewayFeedback(parts["hex"])
case "gateway_clipboard":
if _, hasFile := parts["file"]; hasFile {
return "invalid:forbidden"
}
value := protocol.GatewayClipboardText{Direction: parts["direction"], Text: parts["text"], Encoding: parts["encoding"], LoopToken: parts["loop_token"]}
if value.Validate() != nil {
return "invalid:clipboard"
}
return "valid"
case "gateway_clipboard_audit":
if _, hasText := parts["text"]; hasText {
return "invalid:forbidden"
}
textBytes, err := strconv.ParseInt(parts["text_bytes"], 10, 64)
if err != nil {
return "invalid:clipboard_audit"
}
value := protocol.GatewayClipboardAudit{Version: "1", SessionID: "fixture-session", Direction: parts["direction"], Outcome: parts["outcome"], TextBytes: textBytes, Reason: parts["reason"]}
if value.Validate() != nil {
return "invalid:clipboard_audit"
}
return "valid"
default:
return "invalid:unknown_kind"
}
}
func decodeGatewayHex(encoded string) ([]byte, string) {
raw, err := hex.DecodeString(encoded)
if err != nil {
return nil, "invalid:hex"
}
return raw, ""
}
func classifyGatewayInput(encoded string) string {
raw, invalid := decodeGatewayHex(encoded)
if invalid != "" {
return invalid
}
if len(raw) < 6 {
return "invalid:truncated"
}
if string(raw[:4]) != "VGI1" {
return "invalid:magic"
}
kind, length := raw[4], int(raw[5])
if len(raw) != 6+length {
return "invalid:length"
}
body := raw[6:]
switch kind {
case 1:
if len(body) != 4 || body[0] > 1 || (body[2] == 0 && body[3] == 0) {
return "invalid:field"
}
case 2:
if len(body) != 3 {
return "invalid:length"
}
if body[0] > 1 || body[1] < 1 || body[1] > 5 {
return "invalid:field"
}
if body[2] != 0 {
return "invalid:reserved"
}
case 3:
if len(body) != 4 {
return "invalid:length"
}
case 4:
if len(body) < 1 || len(body) > 4 || !utf8.Valid(body) || utf8.RuneCount(body) != 1 {
return "invalid:utf8"
}
case 5:
if len(body) != 17 {
return "invalid:length"
}
if body[0] > 15 {
return "invalid:field"
}
if body[1] == 0 && body[2] == 0 {
for _, value := range body[3:] {
if value != 0 {
return "invalid:field"
}
}
}
default:
return "invalid:kind"
}
return "valid"
}
func classifyGatewayFeedback(encoded string) string {
raw, invalid := decodeGatewayHex(encoded)
if invalid != "" {
return invalid
}
if len(raw) < 8 {
return "invalid:truncated"
}
if string(raw[:4]) != "VGF1" {
return "invalid:magic"
}
direction, kind := raw[4], raw[5]
if len(raw) != 8+(int(raw[6])<<8)+int(raw[7]) {
return "invalid:length"
}
if direction != 0 && direction != 1 {
return "invalid:direction"
}
body := raw[8:]
if direction == 0 {
if kind >= 0x10 && kind <= 0x12 {
return "invalid:direction"
}
switch kind {
case 1:
if len(body) == 0 {
return "valid"
}
case 2:
if validFECStatus(body) {
return "valid"
}
return "invalid:field"
default:
return "invalid:type"
}
return "invalid:length"
}
if kind == 1 || kind == 2 {
return "invalid:direction"
}
switch kind {
case 0x10:
if len(body) == 4 {
return "valid"
}
return "invalid:length"
case 0x11:
if len(body) != 5 {
return "invalid:length"
}
if body[0] <= 15 {
return "valid"
}
case 0x12:
if len(body) != 1 {
return "invalid:length"
}
if body[0] <= 1 {
return "valid"
}
default:
return "invalid:type"
}
return "invalid:field"
}
func validFECStatus(body []byte) bool {
if len(body) != 21 || int(body[10])<<8|int(body[11]) == 0 || int(body[14])<<8|int(body[15]) > int(body[10])<<8|int(body[11]) || int(body[16])<<8|int(body[17]) > int(body[12])<<8|int(body[13]) || body[18] > 100 || body[20] == 0 || body[19] >= body[20] {
return false
}
return true
}
func classifyDatagram(encoded string) string {
raw, err := hex.DecodeString(encoded)
if err != nil {
@@ -157,7 +325,7 @@ func classifyDatagram(encoded string) string {
if raw[2] != 1 {
return "invalid:unsupported_version"
}
limits := map[byte]int{1: 1024, 2: 2048, 3: 65515}
limits := map[byte]int{1: 1024, 2: 2048, 3: 65515, 10: 1179, 11: 1179, 12: 1179}
limit, ok := limits[raw[3]]
if !ok {
return "invalid:unknown_channel"
+116
View File
@@ -53,10 +53,125 @@ fn evaluate(kind: &str, input: &str) -> &'static str {
}
"tunnel" => "invalid:unsupported_version",
"datagram" => classify_datagram(values.get("hex").map(String::as_str).unwrap_or_default()),
"gateway_input" => classify_gateway_input(values.get("hex").map(String::as_str).unwrap_or_default()),
"gateway_feedback" => classify_gateway_feedback(values.get("hex").map(String::as_str).unwrap_or_default()),
"gateway_clipboard" if values.contains_key("file") => "invalid:forbidden",
"gateway_clipboard" => match (
values.get("direction"),
values.get("text"),
values.get("encoding"),
values.get("loop_token"),
) {
(Some(direction), Some(text), Some(encoding), Some(token))
if GatewayClipboardText::new(
direction.clone(), text.clone(), encoding.clone(), token.clone(),
).is_ok() => "valid",
_ => "invalid:clipboard",
},
"gateway_clipboard_audit" if values.contains_key("text") => "invalid:forbidden",
"gateway_clipboard_audit"
if matches!(values.get("direction").map(String::as_str), Some("client_to_provider") | Some("provider_to_client"))
&& matches!(values.get("outcome").map(String::as_str), Some("forwarded") | Some("suppressed") | Some("rejected"))
&& matches!(values.get("reason").map(String::as_str), Some("forwarded") | Some("loop") | Some("policy") | Some("rate") | Some("provider") | Some("malformed"))
&& values.get("text_bytes").and_then(|value| value.parse::<usize>().ok()).map_or(false, |size| size <= 65536) => "valid",
"gateway_clipboard_audit" => "invalid:clipboard_audit",
_ => "invalid:unknown_kind",
}
}
fn classify_gateway_input(encoded: &str) -> &'static str {
let raw = match decode_hex(encoded) {
Some(raw) => raw,
None => return "invalid:hex",
};
if raw.len() < 6 {
return "invalid:truncated";
}
if raw[0..4] != *b"VGI1" {
return "invalid:magic";
}
let kind = raw[4];
let body = &raw[6..];
if body.len() != raw[5] as usize {
return "invalid:length";
}
match kind {
1 if body.len() == 4 && body[0] <= 1 && (body[2] != 0 || body[3] != 0) => "valid",
1 => "invalid:field",
2 if body.len() != 3 => "invalid:length",
2 if body[0] > 1 || !(1..=5).contains(&body[1]) => "invalid:field",
2 if body[2] != 0 => "invalid:reserved",
2 => "valid",
3 if body.len() == 4 => "valid",
3 => "invalid:length",
4 if (1..=4).contains(&body.len()) && std::str::from_utf8(body).ok().map_or(false, |value| value.chars().count() == 1) => "valid",
4 => "invalid:utf8",
5 if body.len() != 17 => "invalid:length",
5 if body[0] > 15 => "invalid:field",
5 if body[1] == 0 && body[2] == 0 && body[3..].iter().any(|value| *value != 0) => "invalid:field",
5 => "valid",
_ => "invalid:kind",
}
}
fn classify_gateway_feedback(encoded: &str) -> &'static str {
let raw = match decode_hex(encoded) {
Some(raw) => raw,
None => return "invalid:hex",
};
if raw.len() < 8 {
return "invalid:truncated";
}
if raw[0..4] != *b"VGF1" {
return "invalid:magic";
}
let direction = raw[4];
let kind = raw[5];
let body = &raw[8..];
if body.len() != ((raw[6] as usize) << 8 | raw[7] as usize) {
return "invalid:length";
}
if direction > 1 {
return "invalid:direction";
}
if direction == 0 {
if (0x10..=0x12).contains(&kind) {
return "invalid:direction";
}
return match kind {
1 if body.is_empty() => "valid",
1 => "invalid:length",
2 if valid_fec_status(body) => "valid",
2 => "invalid:field",
_ => "invalid:type",
};
}
if kind == 1 || kind == 2 {
return "invalid:direction";
}
match kind {
0x10 if body.len() == 4 => "valid",
0x10 => "invalid:length",
0x11 if body.len() != 5 => "invalid:length",
0x11 if body[0] <= 15 => "valid",
0x11 => "invalid:field",
0x12 if body.len() != 1 => "invalid:length",
0x12 if body[0] <= 1 => "valid",
0x12 => "invalid:field",
_ => "invalid:type",
}
}
fn valid_fec_status(body: &[u8]) -> bool {
body.len() == 21
&& ((body[10] as u16) << 8 | body[11] as u16) > 0
&& ((body[14] as u16) << 8 | body[15] as u16) <= ((body[10] as u16) << 8 | body[11] as u16)
&& ((body[16] as u16) << 8 | body[17] as u16) <= ((body[12] as u16) << 8 | body[13] as u16)
&& body[18] <= 100
&& body[20] > 0
&& body[19] < body[20]
}
fn decode_hex(input: &str) -> Option<Vec<u8>> {
if input.len() % 2 != 0 {
return None;
@@ -85,6 +200,7 @@ fn classify_datagram(encoded: &str) -> &'static str {
1 => 1024,
2 => 2048,
3 => 65515,
10 | 11 | 12 => 1179,
_ => return "invalid:unknown_channel",
};
if raw[4] != 0 {
+90 -3
View File
@@ -30,18 +30,104 @@ func evaluate(_ kind: String, _ input: String) -> String {
if ["1", "0", "-1"].contains(values["offered"] ?? "") && values["feature"] == "control.v1" { return "valid" }
return values["feature"] == "control.v1" ? "invalid:unsupported_version" : "invalid:unsupported_feature"
case "datagram": return classifyDatagram(values["hex"] ?? "")
case "gateway_input": return classifyGatewayInput(values["hex"] ?? "")
case "gateway_feedback": return classifyGatewayFeedback(values["hex"] ?? "")
case "gateway_clipboard":
if values["file"] != nil { return "invalid:forbidden" }
guard let direction = values["direction"], let text = values["text"],
let encoding = values["encoding"], let token = values["loop_token"],
(try? GatewayClipboardText(
direction: direction, text: text, encoding: encoding, loopToken: token
)) != nil else { return "invalid:clipboard" }
return "valid"
case "gateway_clipboard_audit":
if values["text"] != nil { return "invalid:forbidden" }
guard ["client_to_provider", "provider_to_client"].contains(values["direction"] ?? ""), ["forwarded", "suppressed", "rejected"].contains(values["outcome"] ?? ""), ["forwarded", "loop", "policy", "rate", "provider", "malformed"].contains(values["reason"] ?? ""), let textBytes = Int(values["text_bytes"] ?? ""), (0...65536).contains(textBytes) else { return "invalid:clipboard_audit" }
return "valid"
default: return "invalid:unknown_kind"
}
}
func classifyDatagram(_ encoded: String) -> String {
func decodeHex(_ encoded: String) -> [UInt8]? {
let characters = Array(encoded)
guard characters.count % 2 == 0 else { return "invalid:hex" }
guard characters.count % 2 == 0 else { return nil }
var raw: [UInt8] = []
for index in stride(from: 0, to: characters.count, by: 2) {
guard let byte = UInt8(String(characters[index...index + 1]), radix: 16) else { return "invalid:hex" }
guard let byte = UInt8(String(characters[index...index + 1]), radix: 16) else { return nil }
raw.append(byte)
}
return raw
}
func classifyGatewayInput(_ encoded: String) -> String {
guard let raw = decodeHex(encoded) else { return "invalid:hex" }
guard raw.count >= 6 else { return "invalid:truncated" }
guard Array(raw[0..<4]) == Array("VGI1".utf8) else { return "invalid:magic" }
let kind = raw[4]
let body = Array(raw.dropFirst(6))
guard body.count == Int(raw[5]) else { return "invalid:length" }
switch kind {
case 1:
return body.count == 4 && body[0] <= 1 && (body[2] != 0 || body[3] != 0) ? "valid" : "invalid:field"
case 2:
guard body.count == 3 else { return "invalid:length" }
guard body[0] <= 1 && (1...5).contains(body[1]) else { return "invalid:field" }
return body[2] == 0 ? "valid" : "invalid:reserved"
case 3: return body.count == 4 ? "valid" : "invalid:length"
case 4:
guard (1...4).contains(body.count), let scalar = String(bytes: body, encoding: .utf8), scalar.unicodeScalars.count == 1 else { return "invalid:utf8" }
return "valid"
case 5:
guard body.count == 17 else { return "invalid:length" }
guard body[0] <= 15 else { return "invalid:field" }
guard body[1] != 0 || body[2] != 0 || body.dropFirst(3).allSatisfy({ $0 == 0 }) else { return "invalid:field" }
return "valid"
default: return "invalid:kind"
}
}
func classifyGatewayFeedback(_ encoded: String) -> String {
guard let raw = decodeHex(encoded) else { return "invalid:hex" }
guard raw.count >= 8 else { return "invalid:truncated" }
guard Array(raw[0..<4]) == Array("VGF1".utf8) else { return "invalid:magic" }
let direction = raw[4]
let kind = raw[5]
let body = Array(raw.dropFirst(8))
guard body.count == Int(raw[6]) * 256 + Int(raw[7]) else { return "invalid:length" }
guard direction <= 1 else { return "invalid:direction" }
if direction == 0 {
if (0x10...0x12).contains(kind) { return "invalid:direction" }
switch kind {
case 1: return body.isEmpty ? "valid" : "invalid:length"
case 2:
return validFECStatus(body) ? "valid" : "invalid:field"
default: return "invalid:type"
}
}
if kind == 1 || kind == 2 { return "invalid:direction" }
switch kind {
case 0x10: return body.count == 4 ? "valid" : "invalid:length"
case 0x11:
guard body.count == 5 else { return "invalid:length" }
return body[0] <= 15 ? "valid" : "invalid:field"
case 0x12:
guard body.count == 1 else { return "invalid:length" }
return body[0] <= 1 ? "valid" : "invalid:field"
default: return "invalid:type"
}
}
func validFECStatus(_ body: [UInt8]) -> Bool {
guard body.count == 21 else { return false }
let totalData = Int(body[10]) * 256 + Int(body[11])
let totalParity = Int(body[12]) * 256 + Int(body[13])
let receivedData = Int(body[14]) * 256 + Int(body[15])
let receivedParity = Int(body[16]) * 256 + Int(body[17])
return totalData > 0 && receivedData <= totalData && receivedParity <= totalParity && body[18] <= 100 && body[20] > 0 && body[19] < body[20]
}
func classifyDatagram(_ encoded: String) -> String {
guard let raw = decodeHex(encoded) else { return "invalid:hex" }
guard raw.count >= 21 else { return "invalid:truncated" }
guard raw[0] == 0x56 && raw[1] == 0x44 else { return "invalid:magic" }
guard raw[2] == 1 else { return "invalid:unsupported_version" }
@@ -50,6 +136,7 @@ func classifyDatagram(_ encoded: String) -> String {
case 1: limit = 1024
case 2: limit = 2048
case 3: limit = 65515
case 10, 11, 12: limit = 1179
default: return "invalid:unknown_channel"
}
guard raw[4] == 0 else { return "invalid:flags" }
+8 -1
View File
@@ -20,7 +20,14 @@ def main() -> int:
temp = pathlib.Path(directory)
rust_bin = temp / "rust-conformance"
swift_bin = temp / "swift-conformance"
run(["rustc", "tools/native_conformance.rs", "-O", "-o", str(rust_bin)])
rust_source = temp / "main.rs"
rust_source.write_text(
(ROOT / "gen/rust/protocol.rs").read_text(encoding="utf-8")
+ "\n"
+ (ROOT / "tools/native_conformance.rs").read_text(encoding="utf-8"),
encoding="utf-8",
)
run(["rustc", str(rust_source), "-O", "-o", str(rust_bin)])
run([str(rust_bin)])
main_source = temp / "main.swift"
main_source.write_text((ROOT / "tools/native_conformance.swift").read_text(encoding="utf-8"), encoding="utf-8")
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Focused contract-boundary regressions for check_scope.py."""
from __future__ import annotations
import json
import pathlib
import tempfile
import check_scope
TEXT_PATHS = (
"openapi/control-v1.yaml",
"proto/versevdi/control/v1/control.proto",
"proto/versevdi/tunnel/v1/tunnel.proto",
"frames/datagram-v1.md",
"frames/registry.json",
"registries/features.json",
"registries/datagrams.json",
)
PROVIDER_WORK_PROTO = """
message ProviderSessionWork {
string client_private_key_pem = 15;
}
"""
def schema_with_private_key(owner: str) -> dict[str, object]:
definitions = {
name: {"type": "object", "properties": {}}
for name in (
"ConnectionManifest",
"ManifestGateway",
"ManifestTunnel",
"ManifestProfile",
"ManifestBounds",
"GrantReference",
"ProviderSessionWork",
)
}
definitions[owner]["properties"] = {
"client_private_key_pem": {"type": "string"},
}
return {"$defs": definitions}
def run_scope(schema: dict[str, object], overrides: dict[str, str] | None = None) -> None:
with tempfile.TemporaryDirectory() as directory:
root = pathlib.Path(directory)
schema_path = root / "schemas/control-v1.schema.json"
schema_path.parent.mkdir(parents=True)
schema_path.write_text(json.dumps(schema), encoding="utf-8")
for relative in TEXT_PATHS:
path = root / relative
path.parent.mkdir(parents=True, exist_ok=True)
default = PROVIDER_WORK_PROTO if relative == "proto/versevdi/tunnel/v1/tunnel.proto" else ""
path.write_text((overrides or {}).get(relative, default), encoding="utf-8")
(root / "gen").mkdir()
original_root = check_scope.ROOT
check_scope.ROOT = root
try:
check_scope.check_manifest_schema()
check_scope.check_text_boundaries()
finally:
check_scope.ROOT = original_root
def expect_rejected(schema: dict[str, object], overrides: dict[str, str] | None = None) -> None:
try:
run_scope(schema, overrides)
except ValueError:
return
raise AssertionError("client-visible private-key material was accepted")
def main() -> None:
run_scope(schema_with_private_key("ProviderSessionWork"))
expect_rejected(schema_with_private_key("ConnectionManifest"))
expect_rejected(schema_with_private_key("ManifestProfile"))
expect_rejected(
schema_with_private_key("ProviderSessionWork"),
{
"proto/versevdi/tunnel/v1/tunnel.proto": """
message ConnectionManifest {
string client_private_key_pem = 1;
}
"""
},
)
expect_rejected(
schema_with_private_key("ProviderSessionWork"),
{"frames/datagram-v1.md": "client_private_key_pem"},
)
print("Protocol contract-aware scope regression passed")
if __name__ == "__main__":
main()
+251
View File
@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""Compile and exercise strict generated Swift and Rust gateway contracts."""
from __future__ import annotations
import pathlib
import shutil
import subprocess
import tempfile
ROOT = pathlib.Path(__file__).resolve().parents[1]
def run(command: list[str], directory: pathlib.Path) -> None:
result = subprocess.run(command, cwd=directory, text=True, capture_output=True, check=False)
if result.returncode != 0:
raise RuntimeError("%s\n%s%s" % (" ".join(command), result.stdout, result.stderr))
def run_failure(command: list[str], directory: pathlib.Path, expected: str) -> None:
result = subprocess.run(command, cwd=directory, text=True, capture_output=True, check=False)
if result.returncode == 0 or expected not in result.stdout + result.stderr:
raise RuntimeError("expected failure: %s\n%s%s" % (" ".join(command), result.stdout, result.stderr))
def main() -> int:
with tempfile.TemporaryDirectory(prefix="versevdi-generated-contracts-") as temporary:
workspace = pathlib.Path(temporary)
swift = workspace / "main.swift"
swift.write_text(
"""import Foundation
let capability = try CapabilityProfile(
transport: "quic-tls13", framing: "datagram-v1", media: "encoded",
audio: "encoded", sourceRateControl: "server", clientDecode: ["h264-opus"]
)
let request = try TunnelAdmissionRequest(
version: "1", sessionId: "session", gatewayId: "gateway", audience: "audience",
grant: String(repeating: "g", count: 43), reconnectSequence: 0,
clientNonce: String(repeating: "n", count: 16), deviceSignature: String(repeating: "s", count: 86), capabilities: capability
)
_ = request
let transcript = "versevdi/tunnel-admission/v17:session7:gateway8:audience43:" + String(repeating: "g", count: 43) + "1:016:" + String(repeating: "n", count: 16) + "10:quic-tls1311:datagram-v17:encoded7:encoded6:server1:19:h264-opus"
guard String(data: request.deviceAdmissionTranscript(), encoding: .utf8) == transcript else {
fatalError("unexpected device admission transcript")
}
let incompatible = try CapabilityProfile(
transport: "quic-tls13", framing: "datagram-v1", media: "encoded",
audio: "encoded", sourceRateControl: "server", clientDecode: ["hevc-opus"]
)
let gatewayCapability = try CapabilityProfile(
transport: "quic-tls13", framing: "datagram-v1", media: "encoded",
audio: "encoded", sourceRateControl: "server", clientDecode: ["hevc-opus", "h264-opus"]
)
do {
guard try CapabilityProfile.intersection([capability, capability]) == capability else {
fatalError("matching capability profiles did not intersect")
}
} catch { fatalError("matching capability profiles did not intersect") }
guard try CapabilityProfile.intersection([gatewayCapability, capability]).clientDecode == ["h264-opus"] else {
fatalError("ordered registered profile intersection changed")
}
do {
_ = try CapabilityProfile.intersection([capability, incompatible])
fatalError("profiles without overlap were accepted")
} catch { }
let valid = try request.encodeJSON()
var unsupported = try JSONSerialization.jsonObject(with: valid) as! [String: Any]
unsupported["version"] = "2"
var downgrade = try JSONSerialization.jsonObject(with: valid) as! [String: Any]
downgrade["version"] = "0"
var unknown = try JSONSerialization.jsonObject(with: valid) as! [String: Any]
unknown["unknown"] = true
for invalid in [
try JSONSerialization.data(withJSONObject: unsupported),
try JSONSerialization.data(withJSONObject: downgrade),
try JSONSerialization.data(withJSONObject: unknown),
Data("{".utf8),
valid + Data(" {}".utf8),
] {
do {
_ = try TunnelAdmissionRequest.decodeJSON(invalid)
fatalError("invalid tunnel admission request was accepted")
} catch { }
}
do {
_ = try AllocationPolicy(
minimumKbps: 100, targetKbps: 50, maximumKbps: 25, tier: "standard",
audience: "audience", protocolValue: "verse", protocolVersion: 1,
grantTtlSeconds: 60, reservationLeaseSeconds: 300
)
fatalError("invalid allocation bounds were accepted")
} catch { }
let streamPolicy = try ProviderStreamPolicy(
resolutionWidth: 2560, resolutionHeight: 1440, fps: 120,
codec: "HEVC", bitrateKbps: 40000, audioEnabled: true
)
guard streamPolicy.codec == "HEVC" else { fatalError("stream policy changed") }
for invalid in [
{ try ProviderStreamPolicy(resolutionWidth: 319, resolutionHeight: 1440, fps: 120, codec: "HEVC", bitrateKbps: 40000, audioEnabled: true) },
{ try ProviderStreamPolicy(resolutionWidth: 2560, resolutionHeight: 1440, fps: 241, codec: "HEVC", bitrateKbps: 40000, audioEnabled: true) },
{ try ProviderStreamPolicy(resolutionWidth: 2560, resolutionHeight: 1440, fps: 120, codec: "VP9", bitrateKbps: 40000, audioEnabled: true) },
] {
do {
_ = try invalid()
fatalError("invalid stream policy was accepted")
} catch { }
}
let telemetry = try GatewayTelemetry(
admittedSessions: 1, admissionRejects: 2, reconnects: 3, drainTransitions: 4,
mediaDrops: 5, mediaPackets: 6, mediaBytes: 7, queueDelayMicros: 8,
processingDelayMicros: 9, processingSamples: 10, pacingDelayMicros: 11,
providerErrors: 12, inputRejected: 13, controlRttMicros: 14,
controlJitterMicros: 15, controlLossPpm: 16, pendingReliable: 17,
providerState: "ready"
)
guard telemetry.mediaBytes == 7 else { fatalError("gateway telemetry changed") }
do {
_ = try GatewayTelemetry(
admittedSessions: 1, admissionRejects: 2, reconnects: 3, drainTransitions: 4,
mediaDrops: 5, mediaPackets: 6, mediaBytes: 7, queueDelayMicros: 8,
processingDelayMicros: 9, processingSamples: 10, pacingDelayMicros: 11,
providerErrors: 12, inputRejected: 13, controlRttMicros: 14,
controlJitterMicros: 15, controlLossPpm: 1000001, pendingReliable: 17,
providerState: "ready"
)
fatalError("invalid gateway telemetry was accepted")
} catch { }
for text in [
String(repeating: "a", count: 65536),
String(repeating: "é", count: 32768),
String(repeating: "\\\"", count: 32768),
] {
let clipboard = try GatewayClipboardText(
direction: "client_to_provider", text: text, encoding: "utf-8",
loopToken: "abcdefghijklmnop"
)
let decoded = try GatewayClipboardText.decodeJSON(clipboard.encodeJSON())
guard decoded.text == text else { fatalError("clipboard text changed during round-trip") }
}
do {
_ = try GatewayClipboardText(
direction: "client_to_provider", text: String(repeating: "a", count: 65537),
encoding: "utf-8", loopToken: "abcdefghijklmnop"
)
fatalError("oversized clipboard text was accepted")
} catch { }
""",
encoding="utf-8",
)
run(["swiftc", str(ROOT / "gen/swift/Protocol.swift"), str(swift), "-o", str(workspace / "swift-contracts")], ROOT)
run([str(workspace / "swift-contracts")], ROOT)
rust = workspace / "protocol.rs"
shutil.copyfile(ROOT / "gen/rust/protocol.rs", rust)
with rust.open("a", encoding="utf-8") as output:
output.write(
"""
fn main() {
let capabilities = CapabilityProfile::new(
"quic-tls13".into(), "datagram-v1".into(), "encoded".into(),
"encoded".into(), "server".into(), vec!["h264-opus".into()],
).unwrap();
let request = TunnelAdmissionRequest::new(
"1".into(), "session".into(), "gateway".into(), "audience".into(),
"g".repeat(43), 0, "n".repeat(16), "s".repeat(86), capabilities.clone(),
).unwrap();
let transcript = "versevdi/tunnel-admission/v17:session7:gateway8:audience43:".to_string()
+ &"g".repeat(43) + "1:016:" + &"n".repeat(16)
+ "10:quic-tls1311:datagram-v17:encoded7:encoded6:server1:19:h264-opus";
assert_eq!(request.device_admission_transcript(), transcript.into_bytes());
assert!(TunnelAdmissionRequest::new(
"2".into(), "session".into(), "gateway".into(), "audience".into(),
"g".repeat(43), 0, "n".repeat(16), "s".repeat(86), capabilities.clone(),
).is_err());
assert!(TunnelAdmissionRequest::new(
"0".into(), "session".into(), "gateway".into(), "audience".into(),
"g".repeat(43), 0, "n".repeat(16), "s".repeat(86), capabilities.clone(),
).is_err());
assert!(TunnelAdmissionRequest::new(
"1".into(), "session".into(), "gateway".into(), "audience".into(),
"g".repeat(43), 0, "short".into(), "s".repeat(86), capabilities.clone(),
).is_err());
assert!(intersect_capability_profiles(&[capabilities.clone(), capabilities.clone()]).is_ok());
let incompatible = CapabilityProfile::new(
"quic-tls13".into(), "datagram-v1".into(), "encoded".into(),
"encoded".into(), "server".into(), vec!["hevc-opus".into()],
).unwrap();
let gateway_capability = CapabilityProfile::new(
"quic-tls13".into(), "datagram-v1".into(), "encoded".into(),
"encoded".into(), "server".into(), vec!["hevc-opus".into(), "h264-opus".into()],
).unwrap();
assert_eq!(
intersect_capability_profiles(&[gateway_capability, capabilities.clone()]).unwrap().clientDecode(),
&vec!["h264-opus".to_string()],
);
assert!(intersect_capability_profiles(&[capabilities, incompatible]).is_err());
assert!(AllocationPolicy::new(
100, 50, 25, "standard".into(), "audience".into(), "verse".into(), 1, 60, 300,
).is_err());
assert!(ProviderStreamPolicy::new(
2560, 1440, 120, "HEVC".into(), 40000, true,
).is_ok());
assert!(ProviderStreamPolicy::new(
319, 1440, 120, "HEVC".into(), 40000, true,
).is_err());
assert!(ProviderStreamPolicy::new(
2560, 1440, 241, "HEVC".into(), 40000, true,
).is_err());
assert!(ProviderStreamPolicy::new(
2560, 1440, 120, "VP9".into(), 40000, true,
).is_err());
assert!(GatewayTelemetry::new(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, "ready".into(),
).is_ok());
assert!(GatewayTelemetry::new(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 1000001, 17, "ready".into(),
).is_err());
assert!(GatewayTelemetry::new(
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, "provider.example:47984".into(),
).is_err());
for text in [
"a".repeat(65536),
"é".repeat(32768),
"\\\"".repeat(32768),
] {
assert!(GatewayClipboardText::new(
"client_to_provider".into(), text, "utf-8".into(), "abcdefghijklmnop".into(),
).is_ok());
}
assert!(GatewayClipboardText::new(
"client_to_provider".into(), "a".repeat(65537), "utf-8".into(),
"abcdefghijklmnop".into(),
).is_err());
}
"""
)
run(["rustc", str(rust), "-o", str(workspace / "rust-contracts")], ROOT)
run([str(workspace / "rust-contracts")], ROOT)
rust_unknown = workspace / "unknown.rs"
shutil.copyfile(ROOT / "gen/rust/protocol.rs", rust_unknown)
with rust_unknown.open("a", encoding="utf-8") as output:
output.write("\nfn main() { let _ = CapabilityProfile { unknown: String::new() }; }\n")
run_failure(["rustc", str(rust_unknown), "-o", str(workspace / "rust-unknown")], ROOT, "no field named `unknown`")
print("Generated strict contract checks passed")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+1 -1
View File
@@ -9,7 +9,7 @@ import pathlib
ROOT = pathlib.Path(__file__).resolve().parents[1]
HEADER_BYTES = 21
MAX_FRAME_BYTES = 65536
CHANNEL_LIMITS = {1: 1024, 2: 2048, 3: 65515}
CHANNEL_LIMITS = {1: 1024, 2: 2048, 3: 65515, 10: 1179, 11: 1179, 12: 1179}
def classify(raw: bytes) -> str:
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
"""Validate fixed-byte Phase 3C gateway input and feedback envelopes."""
from __future__ import annotations
import binascii
import pathlib
ROOT = pathlib.Path(__file__).resolve().parents[1]
def classify_input(raw: bytes) -> str:
if len(raw) < 6:
return "invalid:truncated"
if raw[:4] != b"VGI1":
return "invalid:magic"
kind, length = raw[4], raw[5]
if len(raw) != 6 + length:
return "invalid:length"
body = raw[6:]
if kind == 1:
return "valid" if len(body) == 4 and body[0] <= 1 and body[2:4] != b"\0\0" else "invalid:field"
if kind == 2:
return "valid" if len(body) == 3 and body[0] <= 1 and 1 <= body[1] <= 5 and body[2] == 0 else "invalid:reserved"
if kind == 3:
return "valid" if len(body) == 4 else "invalid:length"
if kind == 4:
try:
decoded = body.decode("utf-8")
except UnicodeDecodeError:
return "invalid:utf8"
return "valid" if 1 <= len(body) <= 4 and len(decoded) == 1 else "invalid:utf8"
if kind == 5:
if len(body) != 17:
return "invalid:length"
if body[0] > 15:
return "invalid:field"
active_mask = int.from_bytes(body[1:3], "big")
return "valid" if active_mask or not any(body[3:]) else "invalid:field"
return "invalid:kind"
def classify_feedback(raw: bytes) -> str:
if len(raw) < 8:
return "invalid:truncated"
if raw[:4] != b"VGF1":
return "invalid:magic"
direction, kind = raw[4], raw[5]
length = int.from_bytes(raw[6:8], "big")
if len(raw) != 8 + length:
return "invalid:length"
if direction not in (0, 1):
return "invalid:direction"
body = raw[8:]
if direction == 0:
if kind in (0x10, 0x11, 0x12):
return "invalid:direction"
if kind == 1:
return "valid" if not body else "invalid:length"
if kind == 2:
return "valid" if valid_fec_status(body) else "invalid:field"
return "invalid:type"
if kind in (1, 2):
return "invalid:direction"
if kind == 0x10:
return "valid" if len(body) == 4 else "invalid:length"
if kind == 0x11:
return "valid" if len(body) == 5 and body[0] <= 15 else "invalid:field"
if kind == 0x12:
return "valid" if len(body) == 1 and body[0] <= 1 else "invalid:field"
return "invalid:type"
def valid_fec_status(body: bytes) -> bool:
return len(body) == 21 and int.from_bytes(body[10:12], "big") > 0 and int.from_bytes(body[14:16], "big") <= int.from_bytes(body[10:12], "big") and int.from_bytes(body[16:18], "big") <= int.from_bytes(body[12:14], "big") and body[18] <= 100 and body[20] > 0 and body[19] < body[20]
def main() -> None:
lines = (ROOT / "fixtures/conformance/gateway-input-feedback-v1.tsv").read_text(encoding="utf-8").splitlines()
assert lines[0] == "id\tversion\tkind\tinput\texpected"
for line in lines[1:]:
identifier, version, kind, input_value, expected = line.split("\t")
assert version == "1"
try:
raw = binascii.unhexlify(input_value.removeprefix("hex="))
except binascii.Error:
actual = "invalid:hex"
else:
actual = classify_input(raw) if kind == "gateway_input" else classify_feedback(raw)
assert actual == expected, f"{identifier}: {actual} != {expected}"
print("Gateway input/feedback envelope validation passed")
if __name__ == "__main__":
main()