pb-mapper-protocol 0.9.0

Message framing and authenticated sessions for pb-mapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use serde::{Deserialize, Serialize};
use snafu::ResultExt;

use pb_mapper_auth::{
    AuthStatus, IssuedTemporaryKey, KeyPage, LegacyProtocolPolicy, TemporaryKeyMetadata,
};
use pb_mapper_core::checksum::AesKeyType;
use pb_mapper_core::error::{MsgSerializeSnafu, Result};

pub const CONTROL_PROTOCOL_V2: u16 = 2;

pub trait MessageSerializer {
    fn encode(&self) -> Result<Vec<u8>>;
    fn decode(msg: &[u8]) -> Result<Self>
    where
        Self: Sized;
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum PbConnStatusReq {
    RemoteId,
    Keys,
    Service {
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        direct_query: Option<bool>,
    },
    Sessions,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum PbConnStatusResp {
    Sessions(Vec<crate::direct::SessionObservation>),
    RemoteId {
        server_map: String,
        active: String,
        idle: String,
    },
    Keys(Vec<String>),
    Service {
        key: String,
        connections: Vec<PbServiceConnStatus>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        direct: Option<crate::direct::DirectCapability>,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct PbServiceConnStatus {
    pub conn_id: u32,
    pub generation: u64,
    pub protocol_version: u16,
    pub healthy: bool,
    pub last_rx_age_ms: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum PbConnRequest {
    DirectControl {
        namespace: Option<u64>,
    },
    DirectRelay {
        id: crate::direct::SessionId,
        secret: crate::direct::SessionSecret,
        namespace: Option<u64>,
        data_protocol: Option<u16>,
    },
    Register {
        need_codec: bool,
        is_datagram: bool,
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        protocol_version: Option<u16>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        client_instance_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        heartbeat_interval_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        heartbeat_tolerance_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        direct: Option<u16>,
    },
    RegisterScoped {
        need_codec: bool,
        is_datagram: bool,
        key: String,
        namespace: u64,
        force_namespace: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        protocol_version: Option<u16>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        client_instance_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        heartbeat_interval_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        heartbeat_tolerance_ms: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        direct: Option<u16>,
    },
    Subcribe {
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
    },
    SubcribeScoped {
        key: String,
        namespace: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
    },
    Status(PbConnStatusReq),
    StatusScoped {
        status: PbConnStatusReq,
        namespace: u64,
    },
    Stream {
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
        dst_id: u32,
        #[serde(default)]
        server_generation: u64,
    },
    StreamScoped {
        key: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
        namespace: u64,
        dst_id: u32,
        #[serde(default)]
        server_generation: u64,
    },
    Admin(AdminRequest),
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum AdminRequest {
    KeyIssue {
        ttl_seconds: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        label: Option<String>,
    },
    KeyList {
        #[serde(default)]
        page: u32,
        #[serde(default = "default_page_size")]
        page_size: u16,
    },
    KeyShow {
        key_id: u64,
    },
    KeyReveal {
        key_id: u64,
    },
    KeyRenew {
        key_id: u64,
        ttl_seconds: u64,
    },
    KeyRevoke {
        key_id: u64,
    },
    KeyGc,
    AuthStatus,
    AuthStateReset {
        confirm: bool,
    },
    RootKeyRotate {
        new_admin_key: String,
    },
    LegacyProtocolSet {
        policy: LegacyProtocolPolicy,
    },
    ConnectionList {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        key_id: Option<u64>,
        #[serde(default)]
        page: u32,
        #[serde(default = "default_page_size")]
        page_size: u16,
    },
    ServiceList {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        key_id: Option<u64>,
        #[serde(default)]
        page: u32,
        #[serde(default = "default_page_size")]
        page_size: u16,
    },
    /// Drop registered control connections the relay is still holding.
    ///
    /// The manual counterpart to the relay's own lease sweep, for the case an
    /// operator can see but the relay cannot: a registration that answers its
    /// heartbeat yet no longer forwards, or a service whose connection quota is
    /// full of connections that should have gone away.
    ConnectionRetire {
        /// Namespace owning the service. Absent means the unscoped namespace,
        /// which is where an administrator's own registrations live.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        key_id: Option<u64>,
        service_name: String,
        /// Retire only this connection. Absent retires every connection the
        /// service has, which is what frees a full quota in one call.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        conn_id: Option<u32>,
    },
}

impl AdminRequest {
    pub fn is_mutating(&self) -> bool {
        matches!(
            self,
            Self::KeyIssue { .. }
                | Self::KeyRenew { .. }
                | Self::KeyRevoke { .. }
                | Self::KeyGc
                | Self::AuthStateReset { .. }
                | Self::RootKeyRotate { .. }
                | Self::LegacyProtocolSet { .. }
                | Self::ConnectionRetire { .. }
        )
    }
}

const fn default_page_size() -> u16 {
    100
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PbErrorResponse {
    pub code: String,
    pub message: String,
    pub retryable: bool,
    pub server_time: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AdminServiceInfo {
    pub key_id: u64,
    pub namespace: u64,
    pub service_name: String,
    pub transport: String,
    pub codec_enabled: bool,
    pub connection_count: u32,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AdminConnectionInfo {
    pub key_id: u64,
    pub namespace: u64,
    pub service_name: String,
    pub conn_id: u32,
    pub generation: u64,
    pub protocol_version: u16,
    pub healthy: bool,
    pub transport: String,
    pub codec_enabled: bool,
    pub last_rx_age_ms: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AdminServicePage {
    pub schema_version: u16,
    pub items: Vec<AdminServiceInfo>,
    pub next_page: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AdminConnectionPage {
    pub schema_version: u16,
    pub items: Vec<AdminConnectionInfo>,
    pub next_page: Option<u32>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum AdminResponse {
    KeyIssued(IssuedTemporaryKey),
    KeyList(KeyPage),
    KeyShown(IssuedTemporaryKey),
    KeyRenewed(IssuedTemporaryKey),
    KeyRevoked(TemporaryKeyMetadata),
    KeyGc {
        removed: u64,
    },
    AuthStatus(AuthStatus),
    Services(AdminServicePage),
    Connections(AdminConnectionPage),
    /// How many registered connections `ConnectionRetire` actually dropped. Zero
    /// is a normal answer: the target may have unwound on its own first.
    ConnectionsRetired {
        retired: u32,
    },
    Ok {
        action: String,
    },
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum PbConnResponse {
    Direct(crate::direct::DirectEvent),
    Register(u32),
    RegisterV2 {
        conn_id: u32,
        generation: u64,
        lease_ttl_ms: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        direct: Option<crate::direct::DirectCapability>,
    },
    Subcribe {
        codec_key: Option<AesKeyType>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
        client_id: u32,
        server_id: u32,
    },
    Stream {
        codec_key: Option<AesKeyType>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        data_protocol: Option<u16>,
    },
    Status(PbConnStatusResp),
    Admin(AdminResponse),
    Error(PbErrorResponse),
}

impl PbConnResponse {
    pub fn error(code: impl Into<String>, message: impl Into<String>, retryable: bool) -> Self {
        Self::Error(PbErrorResponse {
            code: code.into(),
            message: message.into(),
            retryable,
            server_time: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        })
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum PbServerRequest {
    Direct(crate::direct::DirectProviderMessage),
    Ping,
    PingV2 {
        seq: u64,
    },
    StreamAck {
        client_id: u32,
        #[serde(default)]
        server_generation: u64,
    },
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum LocalServer {
    Direct(Box<crate::direct::DirectEvent>),
    /// pb server makes a stream request to local server
    Stream {
        client_id: u32,
        #[serde(default)]
        server_generation: u64,
    },
    /// pb server response a pong msg when it receive a ping request
    Pong,
    PongV2 {
        seq: u64,
    },
    Retire {
        reason: String,
        conn_id: u32,
        #[serde(default)]
        server_generation: u64,
    },
}

macro_rules! gen_impl_msg_serializer {
    ($struct_name:ident) => {
        impl MessageSerializer for $struct_name {
            fn encode(&self) -> Result<Vec<u8>> {
                serde_json::to_vec(self).with_context(|_| MsgSerializeSnafu {
                    action: "encode",
                    struct_name: stringify!($struct_name),
                    content: "payload redacted".to_string(),
                })
            }

            fn decode(msg: &[u8]) -> Result<Self> {
                serde_json::from_slice(msg).with_context(|_| MsgSerializeSnafu {
                    action: "decode",
                    struct_name: stringify!($struct_name),
                    content: format!("{}-byte payload redacted", msg.len()),
                })
            }
        }
    };
}

gen_impl_msg_serializer!(PbConnRequest);
gen_impl_msg_serializer!(PbConnResponse);
gen_impl_msg_serializer!(PbServerRequest);
gen_impl_msg_serializer!(LocalServer);

#[cfg(test)]
mod tests {
    use super::PbConnRequest;

    /// The wire form of `Register` is load-bearing: a running peer on the other
    /// side of an upgrade has to keep parsing it. The `None` fields must stay
    /// absent from the JSON rather than serialise as null.
    #[test]
    fn test_serde_mapper_header() {
        let mapper = PbConnRequest::Register {
            direct: None,
            key: "test".into(),
            need_codec: false,
            is_datagram: false,
            protocol_version: None,
            client_instance_id: None,
            heartbeat_interval_ms: None,
            heartbeat_tolerance_ms: None,
        };
        let json_value = serde_json::to_string(&mapper).unwrap();
        let raw_json_str =
            r##"{"Register":{"need_codec":false,"is_datagram":false,"key":"test"}}"##;
        assert_eq!(raw_json_str, json_value);

        let value: PbConnRequest = serde_json::from_str(raw_json_str).unwrap();
        assert_eq!(mapper, value)
    }
}