bloop-protocol 1.1.0

Core implementation of the Bloop wire protocol
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! The standard protocol messages and their dispatch sets.
//!
//! Every message is a standalone struct carrying its opcode via
//! [`Payload`](crate::set::Payload); [`ClientMessage`] and [`ServerMessage`]
//! group them into the two wire directions. Both sets take an extension
//! parameter (any [`MessageSet`](crate::set::MessageSet)) whose messages are
//! dispatched through the `Custom` variant, defaulting to the uninhabited
//! [`NoExtension`] for endpoints without protocol extensions.
//!
//! Standard messages always win dispatch: an extension claiming a reserved
//! opcode (below `0x80`) never decodes, and the `MessageSet` derive rejects
//! such opcodes at compile time.

mod client;
mod error;
mod record;
mod server;

pub use client::{Authentication, Bloop, ClientHandshake, Ping, PreloadCheck, Quit, RetrieveAudio};
pub use error::ErrorResponse;
pub use record::AchievementRecord;
pub use server::{
    AudioData, AuthenticationAccepted, BloopAccepted, Pong, PreloadMatch, PreloadMismatch,
    ServerHandshake,
};

use crate::set::NoExtension;
use bloop_protocol_derive::MessageSet;

/// Messages sent from the client to the server.
#[derive(Clone, Debug, MessageSet, PartialEq)]
pub enum ClientMessage<Ext = NoExtension> {
    /// See [`ClientHandshake`].
    Handshake(ClientHandshake),

    /// See [`Authentication`].
    Authentication(Authentication),

    /// See [`Ping`].
    Ping(Ping),

    /// See [`Quit`].
    Quit(Quit),

    /// See [`Bloop`].
    Bloop(Bloop),

    /// See [`RetrieveAudio`].
    RetrieveAudio(RetrieveAudio),

    /// See [`PreloadCheck`].
    PreloadCheck(PreloadCheck),

    /// An extension message.
    Custom(Ext),
}

/// Messages sent from the server to the client.
#[derive(Clone, Debug, MessageSet, PartialEq)]
pub enum ServerMessage<Ext = NoExtension> {
    /// See [`ErrorResponse`].
    Error(ErrorResponse),

    /// See [`ServerHandshake`].
    Handshake(ServerHandshake),

    /// See [`AuthenticationAccepted`].
    AuthenticationAccepted(AuthenticationAccepted),

    /// See [`Pong`].
    Pong(Pong),

    /// See [`BloopAccepted`].
    BloopAccepted(BloopAccepted),

    /// See [`AudioData`].
    AudioData(AudioData),

    /// See [`PreloadMatch`].
    PreloadMatch(PreloadMatch),

    /// See [`PreloadMismatch`].
    PreloadMismatch(PreloadMismatch),

    /// An extension message.
    Custom(Ext),
}

#[cfg(test)]
mod tests {
    use std::net::{IpAddr, Ipv4Addr};

    use uuid::Uuid;

    use super::*;
    use crate::capabilities::Capabilities;
    use crate::codec::DecodeError;
    use crate::data_hash::DataHash;
    use crate::frame::RawMessage;
    use crate::nfc_uid::NfcUid;
    use crate::set::{MessageSet, MessageSetError};

    // The byte vectors in this module are ported from bloop-server-framework
    // 1.10.6 (src/message.rs) so this crate provably speaks the same wire
    // format.

    fn decode_client(message_type: u8, payload: &[u8]) -> Result<ClientMessage, MessageSetError> {
        ClientMessage::<NoExtension>::decode(&RawMessage::new(message_type, payload.to_vec()))
    }

    #[test]
    fn client_handshake_decodes() {
        let decoded = decode_client(0x01, &[1, 5]).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::Handshake(ClientHandshake {
                min_version: 1,
                max_version: 5,
            })
        );
    }

    #[test]
    fn authentication_decodes() {
        let mut payload = vec![3];
        payload.extend(b"foo");
        payload.push(3);
        payload.extend(b"bar");
        payload.push(4);
        payload.extend(&[127, 0, 0, 1]);

        let decoded = decode_client(0x03, &payload).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::Authentication(Authentication {
                client_id: "foo".to_string(),
                client_secret: "bar".to_string(),
                ip_address: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
            })
        );
    }

    #[test]
    fn empty_client_messages_decode() {
        assert_eq!(decode_client(0x05, &[]).unwrap(), ClientMessage::Ping(Ping));
        assert_eq!(decode_client(0x07, &[]).unwrap(), ClientMessage::Quit(Quit));
    }

    #[test]
    fn bloop_decodes_single_nfc_uid() {
        let decoded = decode_client(0x08, &[4, 1, 2, 3, 4]).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::Bloop(Bloop {
                nfc_uid: NfcUid::try_from(&[1u8, 2, 3, 4][..]).unwrap(),
            })
        );
    }

    #[test]
    fn retrieve_audio_decodes_uuid() {
        let uuid = Uuid::from_bytes([9; 16]);
        let decoded = decode_client(0x0a, uuid.as_bytes()).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::RetrieveAudio(RetrieveAudio {
                achievement_id: uuid,
            })
        );
    }

    #[test]
    fn preload_check_decodes_with_some_hash() {
        let mut payload = vec![16];
        payload.extend_from_slice(&[0u8; 16]);

        let decoded = decode_client(0x0c, &payload).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::PreloadCheck(PreloadCheck {
                audio_manifest_hash: Some(DataHash::try_from(vec![0u8; 16]).unwrap()),
            })
        );
    }

    #[test]
    fn preload_check_decodes_with_none_hash() {
        let decoded = decode_client(0x0c, &[0]).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::PreloadCheck(PreloadCheck {
                audio_manifest_hash: None,
            })
        );
    }

    #[test]
    fn preload_check_accepts_arbitrary_hash_lengths() {
        // Deliberate divergence from framework 1.10.6, which hard-required 16
        // bytes: the spec's hash type is variable-length, so a 1-byte hash is
        // valid.
        let decoded = decode_client(0x0c, &[1, 0]).unwrap();

        assert_eq!(
            decoded,
            ClientMessage::PreloadCheck(PreloadCheck {
                audio_manifest_hash: Some(DataHash::try_from(vec![0u8]).unwrap()),
            })
        );
    }

    #[test]
    fn unknown_opcode_is_reported_without_extension() {
        let error = decode_client(0xff, &[1, 2, 3]).unwrap_err();
        assert!(matches!(error, MessageSetError::UnknownOpcode(0xff)));
    }

    #[test]
    fn unknown_opcode_reaches_the_extension_set() {
        let raw = RawMessage::new(0xff, vec![1, 2, 3]);
        let decoded = ClientMessage::<RawMessage>::decode(&raw).unwrap();

        assert_eq!(decoded, ClientMessage::Custom(raw));
    }

    #[test]
    fn short_handshake_is_malformed() {
        let error = decode_client(0x01, &[1]).unwrap_err();

        assert!(matches!(
            error,
            MessageSetError::Malformed {
                opcode: 0x01,
                source: DecodeError::UnexpectedEof,
            }
        ));
    }

    #[test]
    fn trailing_bytes_are_malformed() {
        let error = decode_client(0x05, &[1]).unwrap_err();

        assert!(matches!(
            error,
            MessageSetError::Malformed {
                opcode: 0x05,
                source: DecodeError::TrailingBytes { remaining: 1 },
            }
        ));
    }

    #[test]
    fn authentication_with_invalid_utf8_is_malformed() {
        let mut payload = vec![2];
        payload.extend(&[0xff, 0xff]);
        payload.push(3);
        payload.extend(b"bar");
        payload.push(4);
        payload.extend(&[127, 0, 0, 1]);

        assert!(decode_client(0x03, &payload).is_err());
    }

    #[test]
    fn authentication_with_invalid_utf8_secret_is_malformed() {
        let mut payload = vec![3];
        payload.extend(b"foo");
        payload.push(2);
        payload.extend(&[0xff, 0xff]);
        payload.push(4);
        payload.extend(&[127, 0, 0, 1]);

        assert!(decode_client(0x03, &payload).is_err());
    }

    #[test]
    fn authentication_with_invalid_ip_version_is_malformed() {
        let mut payload = vec![3];
        payload.extend(b"foo");
        payload.push(3);
        payload.extend(b"bar");
        payload.push(0xff);
        payload.extend(&[1, 2, 3, 4]);

        assert!(decode_client(0x03, &payload).is_err());
    }

    #[test]
    fn bloop_with_invalid_uid_length_is_malformed() {
        assert!(decode_client(0x08, &[5, 1, 2, 3, 4]).is_err());
    }

    #[test]
    fn retrieve_audio_with_short_uuid_is_malformed() {
        assert!(decode_client(0x0a, &[0; 15]).is_err());
    }

    fn encode_server(message: ServerMessage) -> RawMessage {
        message.encode().unwrap()
    }

    #[test]
    fn error_response_encodes() {
        let raw = encode_server(ServerMessage::Error(ErrorResponse::InvalidCredentials));

        assert_eq!(raw.message_type, 0x00);
        assert_eq!(raw.payload, [3]);
    }

    #[test]
    fn server_handshake_encodes() {
        let raw = encode_server(ServerMessage::Handshake(ServerHandshake {
            accepted_version: 7,
            capabilities: Capabilities::none(),
        }));

        assert_eq!(raw.message_type, 0x02);
        assert_eq!(raw.payload, [7, 0, 0, 0, 0, 0, 0, 0, 0]);
    }

    #[test]
    fn empty_server_messages_encode() {
        let raw = encode_server(ServerMessage::AuthenticationAccepted(
            AuthenticationAccepted,
        ));
        assert_eq!(raw.message_type, 0x04);
        assert!(raw.payload.is_empty());

        let raw = encode_server(ServerMessage::Pong(Pong));
        assert_eq!(raw.message_type, 0x06);
        assert!(raw.payload.is_empty());

        let raw = encode_server(ServerMessage::PreloadMatch(PreloadMatch));
        assert_eq!(raw.message_type, 0x0d);
        assert!(raw.payload.is_empty());
    }

    #[test]
    fn bloop_accepted_encodes_with_achievements() {
        let uuid = Uuid::from_bytes([7; 16]);
        let raw = encode_server(ServerMessage::BloopAccepted(BloopAccepted {
            achievements: vec![AchievementRecord {
                id: uuid,
                audio_hash: None,
            }],
        }));

        assert_eq!(raw.message_type, 0x09);
        assert_eq!(raw.payload[0], 1);
        assert_eq!(&raw.payload[1..17], uuid.as_bytes());
        assert_eq!(raw.payload.len(), 1 + 16 + 1);
        assert_eq!(raw.payload[17], 0);
    }

    #[test]
    fn audio_data_encodes() {
        let raw = encode_server(ServerMessage::AudioData(AudioData {
            data: vec![1, 2, 3, 4, 5],
        }));

        assert_eq!(raw.message_type, 0x0b);
        assert_eq!(raw.payload, [5, 0, 0, 0, 1, 2, 3, 4, 5]);
    }

    #[test]
    fn preload_mismatch_encodes() {
        let uuid = Uuid::from_bytes([3; 16]);
        let raw = encode_server(ServerMessage::PreloadMismatch(PreloadMismatch {
            audio_manifest_hash: DataHash::try_from(vec![1u8; 16]).unwrap(),
            achievements: vec![AchievementRecord {
                id: uuid,
                audio_hash: None,
            }],
        }));

        assert_eq!(raw.message_type, 0x0e);
        assert_eq!(raw.payload[0], 16);
        assert_eq!(&raw.payload[1..17], &[1; 16]);
        assert_eq!(
            u32::from_le_bytes(raw.payload[17..21].try_into().unwrap()),
            1
        );
        assert_eq!(&raw.payload[21..37], uuid.as_bytes());
    }

    #[test]
    fn custom_server_message_passes_through() {
        let original = RawMessage::new(0xab, vec![9, 8, 7]);
        let raw = ServerMessage::Custom(original.clone()).encode().unwrap();

        assert_eq!(raw, original);
    }

    #[test]
    fn server_messages_round_trip() {
        let messages: Vec<ServerMessage> = vec![
            ErrorResponse::UnknownNfcUid.into(),
            ServerHandshake {
                accepted_version: 3,
                capabilities: Capabilities::PreloadCheck,
            }
            .into(),
            BloopAccepted {
                achievements: vec![AchievementRecord {
                    id: Uuid::from_bytes([1; 16]),
                    audio_hash: Some(DataHash::try_from(vec![2u8; 16]).unwrap()),
                }],
            }
            .into(),
            AudioData {
                data: vec![1, 2, 3],
            }
            .into(),
        ];

        for message in messages {
            let raw = message.clone().encode().unwrap();
            assert_eq!(ServerMessage::<NoExtension>::decode(&raw).unwrap(), message);
        }
    }

    #[test]
    fn client_messages_round_trip() {
        let messages: Vec<ClientMessage> = vec![
            ClientHandshake {
                min_version: 3,
                max_version: 3,
            }
            .into(),
            Authentication {
                client_id: "client".to_string(),
                client_secret: "secret".to_string(),
                ip_address: IpAddr::V4(Ipv4Addr::new(10, 0, 0, 7)),
            }
            .into(),
            Bloop {
                nfc_uid: NfcUid::try_from(&[1u8, 2, 3, 4, 5, 6, 7][..]).unwrap(),
            }
            .into(),
            PreloadCheck {
                audio_manifest_hash: Some(DataHash::try_from(vec![9u8; 16]).unwrap()),
            }
            .into(),
        ];

        for message in messages {
            let raw = message.clone().encode().unwrap();
            assert_eq!(ClientMessage::<NoExtension>::decode(&raw).unwrap(), message);
        }
    }
}