Skip to main content

bynk_check/
wire_format.rs

1//! #1969: the cross-context wire format, version 1, as a published surface.
2//!
3//! The interop track's D1 (`design/archive/retired-tracks.md`, interop track) makes the format a
4//! caller outside the project can speak a contract with its own version,
5//! apart from the compiler's: the path, method and headers of a call; the
6//! order of the callee's checks, with their status codes and error bodies; the
7//! JSON encoding of each boundary type; and the contract hash.
8//!
9//! This module is the single source for the parts that are constants. The
10//! emitter builds the `/_bynk/call/` dispatch from [`CallCheck`] and the header
11//! names below, and [`mod@reference`] renders `reference/wire-format.md` from the
12//! same values plus [`crate::wire`]'s encoding model and [`crate::contract`]'s
13//! hash. `bynk-tests/tests/wire_reference.rs` holds the page, the emitted dispatch,
14//! the runtime's `callService` and the generated codecs to it.
15//!
16//! **Stability (version 1).** Additive only: a new status code, a new error
17//! `kind` or a new optional header may be added within the version. Changing an
18//! existing encoding, check, status or the hash's normal form is a new wire
19//! version, which a callee accepts beside the old one for an overlap window
20//! ([`ACCEPTED_WIRE_VERSIONS`]). That includes the request signature
21//! ([`signing_input`]): its canonical input and its headers are part of the
22//! version, the keys are not.
23//!
24//! **`from http` bodies (#3508).** The JSON encoding of a boundary type on a
25//! `from http` route is the same encoding, so it follows this version too: a
26//! change to it is a new wire version, and `bynk client` embeds [`WIRE_VERSION`]
27//! for that reason. The per-route contract hash a generated client carries
28//! ([`crate::contract::http_route_contract_hash`]) is informational and is not
29//! part of the version; a `from http` call has no handshake and nothing rejects
30//! a mismatch.
31
32pub mod reference;
33
34/// The wire version this compiler's callers speak.
35pub const WIRE_VERSION: u32 = 1;
36
37/// The wire versions this compiler's callees accept. A request without
38/// [`WIRE_HEADER`] is version 1.
39pub const ACCEPTED_WIRE_VERSIONS: &[u32] = &[1];
40
41/// The path prefix a call is addressed to; the service name follows it.
42pub const CALL_PATH_PREFIX: &str = "/_bynk/call/";
43
44/// The only method a call may use.
45pub const CALL_METHOD: &str = "POST";
46
47/// The caller's compiled hash of the callee's contract.
48pub const CONTRACT_HEADER: &str = "X-Bynk-Contract";
49
50/// The calling context's qualified name.
51pub const CALLER_HEADER: &str = "X-Bynk-Caller";
52
53/// The wire version the caller speaks; absent means 1.
54pub const WIRE_HEADER: &str = "X-Bynk-Wire";
55
56/// I2 (#1971): when the caller signed the request, in whole seconds since the
57/// Unix epoch, as a decimal integer.
58pub const TIMESTAMP_HEADER: &str = "X-Bynk-Timestamp";
59
60/// I2 (#1971): the request's signature, HMAC-SHA256 over [`signing_input`]
61/// under the edge's key, as 64 lowercase hex digits.
62pub const SIGNATURE_HEADER: &str = "X-Bynk-Signature";
63
64/// I2 (#1971): how far, in seconds, a request's timestamp may be from the
65/// callee's clock, either way. A requirement, not a tuning knob (ADR
66/// `per-edge-call-signature`): it bounds how long a captured request can be
67/// replayed, and nothing else does.
68pub const SIGNATURE_WINDOW_SECONDS: u64 = 300;
69
70/// I2 (#1971): the largest body a callee reads, in bytes. The body is read
71/// under this cap before it is hashed, so a sender without a key cannot make
72/// the callee buffer and hash an unbounded one.
73pub const MAX_BODY_BYTES: usize = 1_048_576;
74
75/// I2 (#1971): the first line of [`signing_input`], naming the scheme, so a
76/// signature over this input can never verify as one over another format's.
77pub const SIGNING_SCHEME: &str = "BYNK-CALL-1";
78
79/// I2 (#1971): the secret a callee holds for the edge from one caller,
80/// [`edge_key_from`].
81pub use bynk_project::env_protocol::CALL_FROM_PREFIX as EDGE_FROM_PREFIX;
82
83/// I2 (#1971): the secret a caller holds for the edge to one callee,
84/// [`edge_key_to`].
85pub use bynk_project::env_protocol::CALL_TO_PREFIX as EDGE_TO_PREFIX;
86
87/// State-migrations S4 (#2259 Decision D): the prefix of `bynk migrate
88/// sweep`'s wake route, `/_bynk/migrate/<Class>`. Not part of the published
89/// call wire format: only the toolchain calls it.
90pub const MIGRATE_PATH_PREFIX: &str = "/_bynk/migrate/";
91
92/// State-migrations S4 (#2259): the caller name a sweep signs as. The route
93/// admits no other caller, so a context's edge key cannot wake instances.
94pub const MIGRATE_CALLER: &str = "bynk.migrate";
95
96/// State-migrations S4 (#2259): the secret a sweep's key is set under for the
97/// sweep's duration. Without it the route answers `404`.
98pub use bynk_project::env_protocol::MIGRATE_KEY;
99
100/// I2 (#1971): whether `context` is a name an edge key can be derived from:
101/// dot-separated segments, each a lowercase letter, then lowercase letters
102/// and digits, with single underscores between runs of them (`shop.orders`,
103/// `a_b.c2`). On that domain [`edge_suffix`] is injective, which is what
104/// keeps one caller's key from verifying another's name.
105pub fn is_edge_name(context: &str) -> bool {
106    !context.is_empty()
107        && context.split('.').all(|segment| {
108            let bytes = segment.as_bytes();
109            bytes.first().is_some_and(u8::is_ascii_lowercase)
110                && bytes.last() != Some(&b'_')
111                && !segment.contains("__")
112                && bytes
113                    .iter()
114                    .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_')
115        })
116}
117
118/// I2 (#1971): the part of an edge key's name that names the context at its
119/// other end: upper case, a dot written `__` (`shop.orders` → `SHOP__ORDERS`).
120/// `None` for a name outside [`is_edge_name`]'s domain.
121pub fn edge_suffix(context: &str) -> Option<String> {
122    is_edge_name(context).then(|| context.to_ascii_uppercase().replace('.', "__"))
123}
124
125/// I2 (#1971): the secret the **callee** holds for calls from `caller`
126/// (`BYNK_CALL_FROM_SHOP__ORDERS`). The callee picks it by the request's
127/// [`CALLER_HEADER`], so an undeclared caller finds no key and is refused.
128pub fn edge_key_from(caller: &str) -> Option<String> {
129    edge_suffix(caller).map(|s| format!("{EDGE_FROM_PREFIX}{s}"))
130}
131
132/// I2 (#1971): the secret the **caller** holds for calls to `callee`
133/// (`BYNK_CALL_TO_SHOP__PAYMENT`). Same value as the callee's
134/// [`edge_key_from`] for the same edge.
135pub fn edge_key_to(callee: &str) -> Option<String> {
136    edge_suffix(callee).map(|s| format!("{EDGE_TO_PREFIX}{s}"))
137}
138
139/// I2 (#1971): the bytes a request's signature is computed over. One field
140/// per line, `\n`-separated, no trailing newline:
141///
142/// 1. [`SIGNING_SCHEME`];
143/// 2. the caller, as sent in [`CALLER_HEADER`];
144/// 3. the callee's qualified context name, so a signature verifies at one
145///    callee only;
146/// 4. the method;
147/// 5. the URL's pathname exactly as sent, with no query string and no
148///    percent-normalisation;
149/// 6. [`CONTRACT_HEADER`] as sent, empty when absent;
150/// 7. [`WIRE_HEADER`] as sent, `1` when absent, so the version a callee
151///    decodes under is the one that was signed;
152/// 8. [`TIMESTAMP_HEADER`] as sent;
153/// 9. the SHA-256 of the body's bytes, 64 lowercase hex digits.
154///
155/// Every header the callee acts on is in it. Header values cannot hold a
156/// newline, so no field can forge another's line.
157#[allow(clippy::too_many_arguments)]
158pub fn signing_input(
159    caller: &str,
160    callee: &str,
161    method: &str,
162    path: &str,
163    contract: &str,
164    wire: &str,
165    timestamp: &str,
166    body_sha256_hex: &str,
167) -> String {
168    [
169        SIGNING_SCHEME,
170        caller,
171        callee,
172        method,
173        path,
174        contract,
175        wire,
176        timestamp,
177        body_sha256_hex,
178    ]
179    .join("\n")
180}
181
182/// The `details` of a `MalformedJson` refusal. The HTTP routes use the same.
183pub const MALFORMED_JSON_DETAILS: &str = "Invalid request body";
184
185/// One header of a call request, as the reference documents it.
186pub struct Header {
187    pub name: &'static str,
188    pub required: &'static str,
189    pub meaning: &'static str,
190}
191
192/// Every header a call carries, in the order the reference lists them.
193pub const HEADERS: &[Header] = &[
194    Header {
195        name: CONTRACT_HEADER,
196        required: "yes",
197        meaning: "The caller's hash of the service's contract, 16 lowercase hex digits. Must equal the callee's, or one the callee declares it still accepts ([Contract skew](/book/guides/projects-build-and-deployment/contract-skew/#deploying-a-callee-ahead-of-its-callers)); a missing header does not.",
198    },
199    Header {
200        name: CALLER_HEADER,
201        required: "yes",
202        meaning: "The calling context's qualified name (`shop.orders`), which the handler reads as `c.identity`, or a foreign caller's actor name (`Legacy`). Selects the key the signature is checked under, so it is proved, not claimed.",
203    },
204    Header {
205        name: TIMESTAMP_HEADER,
206        required: "yes",
207        meaning: "When the caller signed the request, in whole seconds since the Unix epoch.",
208    },
209    Header {
210        name: SIGNATURE_HEADER,
211        required: "yes",
212        meaning: "HMAC-SHA256 of the signing input under the edge's key, 64 lowercase hex digits. See *Authentication* below.",
213    },
214    Header {
215        name: WIRE_HEADER,
216        required: "no",
217        meaning: "The wire version the caller speaks, exactly the decimal digits of an accepted version (`1`, not `01` or `+1`). Absent means `1`.",
218    },
219    Header {
220        name: "content-type",
221        required: "no",
222        meaning: "Bynk callers send `application/json`. The callee does not check it.",
223    },
224];
225
226/// One check the callee makes on a call, in the published order.
227#[derive(Debug, Clone, Copy, PartialEq, Eq)]
228pub enum CallCheck {
229    Method,
230    BodyTooLarge,
231    Authentication,
232    WireVersion,
233    UnknownService,
234    NotAdmitted,
235    Contract,
236    MalformedJson,
237    Arguments,
238}
239
240/// The callee's checks, in the order it makes them. The first that fails
241/// answers the request.
242///
243/// I2 (#1971): a signature is checked under the key the caller header
244/// selects, so a call without a caller fails [`CallCheck::Authentication`];
245/// there is no separate missing-caller check after it.
246pub const CALL_CHECKS: [CallCheck; 9] = [
247    CallCheck::Method,
248    CallCheck::BodyTooLarge,
249    CallCheck::Authentication,
250    CallCheck::WireVersion,
251    CallCheck::UnknownService,
252    CallCheck::NotAdmitted,
253    CallCheck::Contract,
254    CallCheck::MalformedJson,
255    CallCheck::Arguments,
256];
257
258impl CallCheck {
259    /// The status a failure of this check answers with.
260    pub fn status(self) -> u16 {
261        match self {
262            CallCheck::Method => 405,
263            CallCheck::BodyTooLarge => 413,
264            CallCheck::Authentication => 401,
265            CallCheck::WireVersion => 400,
266            CallCheck::UnknownService => 404,
267            CallCheck::NotAdmitted => 403,
268            CallCheck::Contract => 409,
269            CallCheck::MalformedJson => 400,
270            CallCheck::Arguments => 400,
271        }
272    }
273
274    /// The `kind` of the JSON error body, for a check that answers with one.
275    /// `Arguments` answers with the codec's own `StructuralMismatch` or
276    /// `RefinementViolation`, so it has no single kind.
277    pub fn kind(self) -> Option<&'static str> {
278        match self {
279            CallCheck::WireVersion => Some("UnsupportedWireVersion"),
280            CallCheck::Contract => Some("ContractMismatch"),
281            CallCheck::MalformedJson => Some("MalformedJson"),
282            CallCheck::Method
283            | CallCheck::BodyTooLarge
284            | CallCheck::Authentication
285            | CallCheck::UnknownService
286            | CallCheck::NotAdmitted
287            | CallCheck::Arguments => None,
288        }
289    }
290
291    /// The plain-text body of a check that answers with one.
292    pub fn text_body(self) -> Option<&'static str> {
293        match self {
294            CallCheck::BodyTooLarge => Some("Payload Too Large"),
295            CallCheck::Authentication => Some("Unauthorized"),
296            CallCheck::UnknownService => Some("Not found"),
297            CallCheck::NotAdmitted => Some("Forbidden"),
298            _ => None,
299        }
300    }
301
302    /// What the check tests, for the reference.
303    pub fn condition(self) -> &'static str {
304        match self {
305            CallCheck::Method => "The method is `POST`.",
306            CallCheck::BodyTooLarge => {
307                "The body is at most 1 MiB (1048576 bytes). Read under the cap, before anything is hashed."
308            }
309            CallCheck::Authentication => {
310                "`X-Bynk-Signature` verifies, under the key the callee holds for the edge from `X-Bynk-Caller`, over the signing input, and `X-Bynk-Timestamp` is within 300 seconds of the callee's clock. Compared in constant time."
311            }
312            CallCheck::WireVersion => {
313                "`X-Bynk-Wire` is absent or names a version the callee accepts."
314            }
315            CallCheck::UnknownService => {
316                "The path names a service of the callee's context with an `on call` handler."
317            }
318            CallCheck::NotAdmitted => {
319                "The service's handler admits the caller the signature proved: a Bynk context by `Caller` (the default), a foreign caller only by its own `Foreign` actor."
320            }
321            CallCheck::Contract => {
322                "`X-Bynk-Contract` equals the callee's hash of that service, or one of the older hashes the callee accepts for it."
323            }
324            CallCheck::MalformedJson => "The body parses as JSON.",
325            CallCheck::Arguments => {
326                "The body decodes as the handler's parameters (see *Encoding*)."
327            }
328        }
329    }
330
331    /// The response a failure gives, for the reference.
332    pub fn response(self) -> String {
333        let text = match self {
334            CallCheck::Method => "empty body, `Allow: POST`",
335            CallCheck::BodyTooLarge => "text `Payload Too Large`",
336            CallCheck::Authentication => "text `Unauthorized`",
337            CallCheck::WireVersion => {
338                let accepted: Vec<String> =
339                    ACCEPTED_WIRE_VERSIONS.iter().map(u32::to_string).collect();
340                return format!(
341                    "`{{\"kind\":\"UnsupportedWireVersion\",\"accepted\":[{}]}}`",
342                    accepted.join(",")
343                );
344            }
345            CallCheck::UnknownService => "text `Not found`",
346            CallCheck::NotAdmitted => "text `Forbidden`",
347            CallCheck::Contract => {
348                r#"`{"kind":"ContractMismatch","service":"…","expected":"…","actual":"…"}`"#
349            }
350            CallCheck::MalformedJson => {
351                r#"`{"kind":"MalformedJson","details":"Invalid request body"}`"#
352            }
353            CallCheck::Arguments => "a `StructuralMismatch` or `RefinementViolation` body",
354        };
355        text.to_string()
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn edge_keys_name_the_context_at_the_other_end() {
365        assert_eq!(
366            edge_key_from("shop.orders").as_deref(),
367            Some("BYNK_CALL_FROM_SHOP__ORDERS")
368        );
369        assert_eq!(
370            edge_key_to("shop.payment").as_deref(),
371            Some("BYNK_CALL_TO_SHOP__PAYMENT")
372        );
373        assert_eq!(edge_suffix("a_b.c2").as_deref(), Some("A_B__C2"));
374    }
375
376    #[test]
377    fn edge_suffixes_never_collide_on_their_domain() {
378        // A dot and an underscore stay apart, which a plain
379        // `replace('.', "_")` would merge.
380        assert_ne!(edge_suffix("a.b"), edge_suffix("a_b"));
381        // Names that would make the encoding ambiguous are outside it.
382        for bad in [
383            "", "a..b", ".a", "a.", "a__b", "_a", "a_", "a._b", "A.b", "a-b", "1a", "a b",
384        ] {
385            assert!(!is_edge_name(bad), "{bad:?} is not an edge name");
386            assert_eq!(edge_key_from(bad), None);
387        }
388        for good in ["integration", "shop.orders", "a_b.c2", "x1.y_2_z"] {
389            assert!(is_edge_name(good), "{good:?} is an edge name");
390        }
391    }
392
393    /// I3 (#1971): the invariant that keeps foreign callers and contexts apart
394    /// on the wire. A foreign actor's name starts with a capital letter
395    /// (`bynk.actor.foreign_name_is_context_name`), and no name that does is
396    /// an edge name, so no foreign caller's name selects an edge key. The
397    /// runtime's `edgeSuffix` pins the same property.
398    #[test]
399    fn no_capitalised_name_is_an_edge_name() {
400        for name in ["Legacy", "L", "Legacy.orders", "LEGACY", "Ledger_2"] {
401            assert!(!is_edge_name(name), "{name:?}");
402            assert_eq!(edge_key_from(name), None, "{name:?}");
403        }
404    }
405
406    #[test]
407    fn the_signing_input_is_one_field_per_line() {
408        assert_eq!(
409            signing_input(
410                "shop.orders",
411                "shop.payment",
412                "POST",
413                "/_bynk/call/authorise",
414                "0123456789abcdef",
415                "1",
416                "1700000000",
417                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
418            ),
419            "BYNK-CALL-1\nshop.orders\nshop.payment\nPOST\n/_bynk/call/authorise\n0123456789abcdef\n1\n1700000000\ne3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
420        );
421    }
422
423    #[test]
424    fn the_checks_state_the_published_limits() {
425        assert!(
426            CallCheck::BodyTooLarge
427                .condition()
428                .contains(&MAX_BODY_BYTES.to_string())
429        );
430        assert!(
431            CallCheck::Authentication
432                .condition()
433                .contains(&format!("{SIGNATURE_WINDOW_SECONDS} seconds"))
434        );
435    }
436}