1pub mod reference;
33
34pub const WIRE_VERSION: u32 = 1;
36
37pub const ACCEPTED_WIRE_VERSIONS: &[u32] = &[1];
40
41pub const CALL_PATH_PREFIX: &str = "/_bynk/call/";
43
44pub const CALL_METHOD: &str = "POST";
46
47pub const CONTRACT_HEADER: &str = "X-Bynk-Contract";
49
50pub const CALLER_HEADER: &str = "X-Bynk-Caller";
52
53pub const WIRE_HEADER: &str = "X-Bynk-Wire";
55
56pub const TIMESTAMP_HEADER: &str = "X-Bynk-Timestamp";
59
60pub const SIGNATURE_HEADER: &str = "X-Bynk-Signature";
63
64pub const SIGNATURE_WINDOW_SECONDS: u64 = 300;
69
70pub const MAX_BODY_BYTES: usize = 1_048_576;
74
75pub const SIGNING_SCHEME: &str = "BYNK-CALL-1";
78
79pub use bynk_project::env_protocol::CALL_FROM_PREFIX as EDGE_FROM_PREFIX;
82
83pub use bynk_project::env_protocol::CALL_TO_PREFIX as EDGE_TO_PREFIX;
86
87pub const MIGRATE_PATH_PREFIX: &str = "/_bynk/migrate/";
91
92pub const MIGRATE_CALLER: &str = "bynk.migrate";
95
96pub use bynk_project::env_protocol::MIGRATE_KEY;
99
100pub 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
118pub fn edge_suffix(context: &str) -> Option<String> {
122 is_edge_name(context).then(|| context.to_ascii_uppercase().replace('.', "__"))
123}
124
125pub fn edge_key_from(caller: &str) -> Option<String> {
129 edge_suffix(caller).map(|s| format!("{EDGE_FROM_PREFIX}{s}"))
130}
131
132pub fn edge_key_to(callee: &str) -> Option<String> {
136 edge_suffix(callee).map(|s| format!("{EDGE_TO_PREFIX}{s}"))
137}
138
139#[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
182pub const MALFORMED_JSON_DETAILS: &str = "Invalid request body";
184
185pub struct Header {
187 pub name: &'static str,
188 pub required: &'static str,
189 pub meaning: &'static str,
190}
191
192pub 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#[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
240pub 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 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 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 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 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 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 assert_ne!(edge_suffix("a.b"), edge_suffix("a_b"));
381 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 #[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}