1mod values;
6pub use values::*;
7
8use std::num::{NonZeroU32, NonZeroU64};
9
10use serde::{Deserialize, Serialize};
11use serde_json::value::{RawValue, to_raw_value};
12use thiserror::Error;
13
14use crate::{DestinationScope, Origin};
15
16pub const SUBPROTOCOL: &str = "countersign.v1";
17pub const VERSION: u16 = 1;
18pub const MAX_FRAME_BYTES: usize = 1024 * 1024;
19pub const MAX_JSON_DEPTH: usize = 24;
20
21#[derive(Debug, Error)]
22pub enum FrameError {
23 #[error("frame exceeds the v1 byte limit")]
24 FrameTooLarge,
25 #[error("frame exceeds the v1 JSON depth limit")]
26 TooDeep,
27 #[error("unsupported control protocol version")]
28 UnsupportedVersion,
29 #[error("unexpected message for this channel and direction")]
30 UnexpectedMessage,
31 #[error("malformed control frame")]
32 Malformed(#[source] serde_json::Error),
33}
34impl From<serde_json::Error> for FrameError {
35 fn from(e: serde_json::Error) -> Self {
36 Self::Malformed(e)
37 }
38}
39
40#[derive(Deserialize, Serialize)]
41#[serde(deny_unknown_fields)]
42struct Envelope<'a> {
43 version: u16,
44 request_id: Id,
45 #[serde(rename = "type")]
46 kind: &'a str,
47 #[serde(borrow)]
48 body: &'a RawValue,
49}
50
51pub struct Frame<M> {
52 pub request_id: Id,
53 pub message: M,
54}
55
56mod sealed {
57 pub trait Sealed {}
58}
59pub trait Message: sealed::Sealed + Sized {
60 #[doc(hidden)]
61 fn parse(kind: &str, body: &RawValue) -> Result<Self, FrameError>;
62 #[doc(hidden)]
63 fn body(&self) -> Result<(&'static str, Box<RawValue>), FrameError>;
64}
65
66impl<M: Message> Frame<M> {
67 pub fn decode(bytes: &[u8]) -> Result<Self, FrameError> {
68 check_bounds(bytes)?;
69 let envelope: Envelope = serde_json::from_slice(bytes)?;
70 if envelope.version != VERSION {
71 return Err(FrameError::UnsupportedVersion);
72 }
73 Ok(Self {
76 request_id: envelope.request_id,
77 message: M::parse(envelope.kind, envelope.body)?,
78 })
79 }
80
81 pub fn encode(&self) -> Result<Vec<u8>, FrameError> {
82 let (kind, body) = self.message.body()?;
83 let bytes = serde_json::to_vec(&Envelope {
84 version: VERSION,
85 request_id: self.request_id.clone(),
86 kind,
87 body: &body,
88 })?;
89 check_bounds(&bytes)?;
90 Ok(bytes)
91 }
92}
93
94fn check_bounds(bytes: &[u8]) -> Result<(), FrameError> {
97 if bytes.len() > MAX_FRAME_BYTES {
98 return Err(FrameError::FrameTooLarge);
99 }
100 let mut depth = 0usize;
101 let mut quoted = false;
102 let mut escaped = false;
103 for &b in bytes {
104 if quoted {
105 if escaped {
106 escaped = false;
107 } else if b == b'\\' {
108 escaped = true;
109 } else if b == b'"' {
110 quoted = false;
111 }
112 } else {
113 match b {
114 b'"' => quoted = true,
115 b'{' | b'[' => {
116 depth += 1;
117 if depth > MAX_JSON_DEPTH {
118 return Err(FrameError::TooDeep);
119 }
120 }
121 b'}' | b']' => depth = depth.saturating_sub(1),
122 _ => {}
123 }
124 }
125 }
126 Ok(())
127}
128
129#[derive(Clone, Debug, Deserialize, Serialize)]
130#[serde(deny_unknown_fields)]
131pub struct DevicePresence {
132 pub binding: DeviceBinding,
133 pub connected: bool,
134 pub connected_at_ms: u64,
135 pub observed_address: Option<String>,
136}
137
138#[derive(Clone, Debug, Deserialize, Serialize)]
139#[serde(deny_unknown_fields)]
140pub struct Devices {
141 pub devices: Vec<DevicePresence>,
142}
143
144#[derive(Clone, Debug, Deserialize, Serialize)]
145#[serde(deny_unknown_fields)]
146pub struct ForgetDevices {
147 pub targets: Vec<DeviceBinding>,
148 pub all_others: bool,
149}
150
151#[derive(Clone, Debug, Deserialize, Serialize)]
152#[serde(deny_unknown_fields)]
153pub struct SecurityEvent {
154 pub id: Id,
155 pub kind: String,
156 pub actor: Option<DeviceBinding>,
157 pub targets: Vec<DeviceBinding>,
158 pub occurred_at_ms: u64,
159 pub observed_address: Option<String>,
160}
161
162#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
163#[serde(deny_unknown_fields)]
164pub struct WorkloadBinding {
165 pub integrator: Id,
166 pub user: Id,
167 pub context: Id,
168 pub workload: Id,
169 pub workload_generation: NonZeroU64,
170}
171
172#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
173#[serde(deny_unknown_fields)]
174pub struct DeviceBinding {
175 pub pairing: Id,
176 pub key: Id,
177 pub channel_generation: NonZeroU64,
178}
179
180#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
181#[serde(deny_unknown_fields)]
182pub struct GrantBinding {
183 pub workload: WorkloadBinding,
184 pub grant: Id,
185 pub grant_version: NonZeroU64,
186 pub worker: Id,
187 pub worker_generation: NonZeroU64,
188 pub scope: DestinationScope,
189 pub device: DeviceBinding,
190 pub cert_sha256: Fingerprint,
191}
192
193#[derive(Clone, Debug, Deserialize, Serialize)]
194#[serde(deny_unknown_fields)]
195pub struct Notice {
196 pub id: Id,
197}
198
199#[derive(Clone, Debug, Deserialize, Serialize)]
200#[serde(deny_unknown_fields)]
201pub struct Empty {}
202
203#[derive(Clone, Debug, Deserialize, Serialize)]
204#[serde(deny_unknown_fields)]
205pub struct Inbox {
206 pub ids: Vec<Id>,
207}
208
209#[derive(Clone, Debug, Deserialize, Serialize)]
210#[serde(deny_unknown_fields)]
211pub struct PairingPending {
212 pub attempt: Id,
213 pub code: Id,
214 pub expires_at_ms: u64,
215}
216
217#[derive(Clone, Debug, Deserialize, Serialize)]
218#[serde(deny_unknown_fields)]
219pub struct GatewayActivation {
220 pub activation: Activate,
221 pub chain: PublicChain,
222}
223
224#[derive(Clone, Debug, Deserialize, Serialize)]
225#[serde(deny_unknown_fields)]
226pub struct Enroll {
227 pub public_sec1: FixedBytes<65>,
229}
230
231#[derive(Clone, Debug, Deserialize, Serialize)]
232#[serde(deny_unknown_fields)]
233pub struct Authenticate {
234 pub pairing: Id,
235 pub key: Id,
236}
237
238#[derive(Clone, Debug, Deserialize, Serialize)]
239#[serde(rename_all = "snake_case", deny_unknown_fields)]
240pub enum ProofPurpose {
241 Pair { attempt: Id },
242 Reconnect { pairing: Id },
243}
244
245#[derive(Clone, Debug, Deserialize, Serialize)]
246#[serde(deny_unknown_fields)]
247pub struct Challenge {
248 pub purpose: ProofPurpose,
249 pub integrator_origin: Origin,
250 pub broker_origin: Origin,
251 pub user: Id,
252 pub key: Id,
253 pub connection: Id,
254 pub nonce: FixedBytes<32>,
255 pub issued_at_ms: u64,
256 pub expires_at_ms: u64,
257}
258
259#[derive(Clone, Debug, Deserialize, Serialize)]
260#[serde(deny_unknown_fields)]
261pub struct DeviceProof {
262 pub connection: Id,
263 pub compact_jws: CompactJws,
266}
267
268#[derive(Clone, Debug, Deserialize, Serialize)]
269#[serde(deny_unknown_fields)]
270pub struct OfferBinding {
271 pub approval: Id,
272 pub approval_version: NonZeroU64,
273 pub offer: Id,
274 pub device: DeviceBinding,
275}
276
277pub type DistinguishedName = Bytes<16384>;
279
280#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
281#[serde(default, deny_unknown_fields)]
282pub struct IdentityHints {
283 pub issuer_names: Vec<DistinguishedName>,
284 pub cert_fingerprints: Option<Vec<Fingerprint>>,
286 pub signature_schemes: Vec<SignatureScheme>,
287}
288
289impl IdentityHints {
290 fn is_empty(&self) -> bool {
291 self.issuer_names.is_empty()
292 && self.cert_fingerprints.is_none()
293 && self.signature_schemes.is_empty()
294 }
295}
296
297#[derive(Clone, Debug, Deserialize, Serialize)]
298#[serde(deny_unknown_fields)]
299pub struct Offer {
300 #[serde(default, skip_serializing_if = "IdentityHints::is_empty")]
301 pub identity_hints: IdentityHints,
302 pub binding: OfferBinding,
303 pub workload: WorkloadBinding,
304 pub initiating_host: Origin,
305 pub scope: DestinationScope,
306 pub default_duration_s: NonZeroU32,
307 pub max_duration_s: NonZeroU32,
308 pub expires_at_ms: u64,
309}
310
311#[derive(Clone, Debug, Deserialize, Serialize)]
312#[serde(rename_all = "snake_case", deny_unknown_fields)]
313pub enum Answer {
314 Approve {
315 duration_s: NonZeroU32,
316 chain: PublicChain,
317 cert_sha256: Fingerprint,
318 },
319 Deny,
320 Cancel,
321}
322
323#[derive(Clone, Debug, Deserialize, Serialize)]
324#[serde(deny_unknown_fields)]
325pub struct Decide {
326 pub binding: OfferBinding,
327 pub answer: Answer,
328}
329
330#[derive(Clone, Debug, Deserialize, Serialize)]
331#[serde(deny_unknown_fields)]
332pub struct Activate {
333 pub grant: GrantBinding,
334 pub approval: Id,
335 pub offer: Id,
336 pub expires_at_ms: u64,
337}
338
339#[derive(Clone, Debug, Deserialize, Serialize)]
340#[serde(deny_unknown_fields)]
341pub struct Connect {
342 pub workload: WorkloadBinding,
343 pub host: Origin,
344}
345
346#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
347#[serde(rename_all = "snake_case")]
348pub enum Enforcer {
349 Ingress,
350 Egress,
351 SigningRelay,
352}
353
354#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
355#[serde(deny_unknown_fields)]
356pub struct LeaseRequest {
357 pub grant: GrantBinding,
358 pub enforcer: Enforcer,
359 pub instance: Id,
360 pub generation: NonZeroU64,
361 pub sequence: NonZeroU64,
362}
363
364#[derive(Clone, Debug, Deserialize, Serialize)]
365#[serde(rename_all = "snake_case", deny_unknown_fields)]
366pub enum LeaseDisposition {
367 Granted {
368 budget_ms: NonZeroU32,
369 valid_until_ms: u64,
370 },
371 Refused,
372}
373
374#[derive(Clone, Debug, Deserialize, Serialize)]
375#[serde(deny_unknown_fields)]
376pub struct LeaseReply {
377 pub binding: LeaseRequest,
378 pub disposition: LeaseDisposition,
379}
380
381#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
382#[serde(deny_unknown_fields)]
383pub struct Operation {
384 pub grant: GrantBinding,
385 pub host: Origin,
386 pub tls_connection: Id,
387 pub operation: Id,
388}
389
390#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
391#[serde(rename_all = "snake_case")]
392pub enum TlsVersion {
393 Tls12,
394 Tls13,
395}
396
397#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)]
398#[serde(rename_all = "snake_case")]
399pub enum SignatureScheme {
400 EcdsaNistp256Sha256,
401 EcdsaNistp384Sha384,
402 RsaPssSha256,
403 RsaPssSha384,
404 RsaPssSha512,
405 RsaPkcs1Sha256,
406 RsaPkcs1Sha384,
407 RsaPkcs1Sha512,
408}
409
410#[derive(Clone, Debug, Deserialize, Serialize)]
411#[serde(deny_unknown_fields)]
412pub struct Sign {
413 pub binding: Operation,
414 pub tls: TlsVersion,
415 pub scheme: SignatureScheme,
416 pub certificate_verify: SigningInput,
417 pub deadline_ms: u64,
418}
419
420#[derive(Clone, Debug, Deserialize, Serialize)]
421#[serde(deny_unknown_fields)]
422pub struct Signed {
423 pub binding: Operation,
424 pub signature: SignatureBytes,
425}
426
427#[derive(Clone, Debug, Deserialize, Serialize)]
428#[serde(rename_all = "snake_case")]
429pub enum ErrorCode {
430 Unauthenticated,
431 Unavailable,
432 Denied,
433 Expired,
434 AlreadyResolved,
435 InvalidRequest,
436 Busy,
437 Cancelled,
438}
439
440#[derive(Clone, Debug, Deserialize, Serialize)]
441#[serde(deny_unknown_fields)]
442pub struct Rejection {
443 pub code: ErrorCode,
444}
445
446macro_rules! messages {
447 ($family:ident { $($variant:ident ($data:ty) => $name:literal),+ $(,)? }) => {
448 #[derive(Clone, Debug)]
449 pub enum $family { $( $variant($data), )+ }
450 impl sealed::Sealed for $family {}
451 impl Message for $family {
452 fn parse(kind: &str, body: &RawValue) -> Result<Self, FrameError> {
453 match kind {
454 $($name => Ok(Self::$variant(serde_json::from_str(body.get())?)),)+
455 _ => Err(FrameError::UnexpectedMessage),
456 }
457 }
458
459 fn body(&self) -> Result<(&'static str, Box<RawValue>), FrameError> {
460 match self { $( Self::$variant(value) => Ok(($name, to_raw_value(value)?)), )+ }
461 }
462 }
463 }
464}
465
466messages!(CompanionToBroker {
467 RevokeApproval(Notice) => "revoke_approval",
468 Devices(Empty) => "devices",
469 ForgetDevices(ForgetDevices) => "forget_devices",
470 Enroll(Enroll) => "enroll",
471 Authenticate(Authenticate) => "authenticate",
472 Proof(DeviceProof) => "proof",
473 Fetch(Notice) => "fetch",
474 Inbox(Empty) => "inbox",
475 Decide(Decide) => "decide",
476 Activated(Activate) => "activated",
477 Signed(Signed) => "signed",
478 Cancel(Operation) => "cancel",
479 Error(Rejection) => "error",
480});
481
482messages!(BrokerToCompanion {
483 RevokeRecorded(Notice) => "revoke_recorded",
484 Devices(Devices) => "devices",
485 SecurityEvent(SecurityEvent) => "security_event",
486 PairingPending(PairingPending) => "pairing_pending",
487 Inbox(Inbox) => "inbox",
488 Challenge(Challenge) => "challenge",
489 Authenticated(DeviceBinding) => "authenticated",
490 Notify(Notice) => "notify",
491 Offer(Offer) => "offer",
492 Activate(Activate) => "activate",
493 Retire(GrantBinding) => "retire",
494 Sign(Sign) => "sign",
495 Cancel(Operation) => "cancel",
496 Error(Rejection) => "error",
497});
498
499#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
502#[serde(rename_all = "snake_case")]
503pub enum ObservationKind {
504 MtlsAccepted,
505 IngressClosed,
506 EgressClosed,
507}
508
509#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
510#[serde(deny_unknown_fields)]
511pub struct Observed {
512 pub grant: GrantBinding,
513 pub host: Origin,
514 pub tls_connection: Id,
515 pub enforcer_instance: Id,
516 pub observation: ObservationKind,
517}
518
519messages!(GatewayToBroker {
520 Watch(GrantBinding) => "watch",
521 Observed(Observed) => "observed",
522 Connect(Connect) => "connect",
523 Lookup(Connect) => "lookup",
524 RenewLease(LeaseRequest) => "renew_lease",
525 Sign(Sign) => "sign",
526 Cancel(Operation) => "cancel",
527});
528
529messages!(BrokerToGateway {
530 NoChange(GrantBinding) => "no_change",
531 Observed(Observed) => "observed",
532 Pending(Notice) => "pending",
533 Activate(GatewayActivation) => "activate",
534 Retire(GrantBinding) => "retire",
535 Lease(LeaseReply) => "lease",
536 Signed(Signed) => "signed",
537 Cancel(Operation) => "cancel",
538 Error(Rejection) => "error",
539});