zlink-core 0.4.1

The core crate of the zlink project
Documentation
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#![cfg(test)]

use crate::{
    connection::{read_connection::ReadConnection, socket::Socket},
    test_utils::mock_socket::MockSocket,
};
use serde::{Deserialize, Serialize};

// Test method and reply types for deserialization testing.
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(tag = "method", content = "parameters")]
enum TestMethod {
    #[serde(rename = "org.example.Test")]
    Test { value: u32 },
}

#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct TestReply {
    result: String,
}

// DOS Attack Protection Tests.

#[tokio::test]
async fn malformed_json_extremely_long_string() {
    // Create a malicious JSON with a string close to MAX_BUFFER_SIZE.
    // This tests that the deserializer handles large strings without panicking and returns proper
    // errors.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    // Create a very long string (10MB worth of 'A's).
    malicious.push_str(&"A".repeat(10 * 1024 * 1024));
    malicious.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail with JSON deserialization error, not panic.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_deeply_nested_objects() {
    // Create deeply nested JSON objects to test for stack overflow or excessive memory usage in
    // the deserializer.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    // Add 10000 nested objects.
    for _ in 0..10000 {
        malicious.push_str(r#"{"a":"#);
    }
    malicious.push_str("0");
    for _ in 0..10000 {
        malicious.push('}');
    }
    malicious.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail gracefully, not cause stack overflow.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_deeply_nested_arrays() {
    // Similar to nested objects but with arrays.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    // Add 10000 nested arrays.
    for _ in 0..10000 {
        malicious.push('[');
    }
    malicious.push_str("0");
    for _ in 0..10000 {
        malicious.push(']');
    }
    malicious.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail gracefully.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_unterminated_string() {
    // Test unterminated string in JSON.
    let malicious = r#"{"method":"org.example.Test","parameters":{"value":"#;

    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should return UnexpectedEof or Json error.
    assert!(matches!(
        result,
        Err(crate::Error::Json(_)) | Err(crate::Error::UnexpectedEof)
    ));
}

#[tokio::test]
async fn malformed_json_unterminated_object() {
    // Test unterminated JSON object.
    let malicious = r#"{"method":"org.example.Test","parameters":{"value":42"#;

    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    assert!(matches!(
        result,
        Err(crate::Error::Json(_)) | Err(crate::Error::UnexpectedEof)
    ));
}

#[tokio::test]
async fn malformed_json_invalid_escape_sequences() {
    // Test invalid escape sequences that might cause excessive backtracking.
    let malicious = r#"{"method":"org.example.Test","parameters":{"value":"\x\x\x\x\x\x"}}"#;

    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_invalid_utf8_sequences() {
    // Test invalid UTF-8 sequences in JSON string.
    // Note: JSON requires valid UTF-8, so this should fail.
    // We use escaped form since MockSocket::new requires &str.
    // Using invalid escape sequences will trigger JSON parsing errors.
    let malicious = r#"{"method":"org.example.Test","parameters":{"value":"\xFF\xFE\xFD"}}"#;

    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail with JSON error due to invalid escape sequences.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn buffer_overflow_near_max_size() {
    // Test a message with a large payload to verify buffer handling.
    // Using 10MB to keep test fast while still testing large messages.
    let size = 10 * 1024 * 1024;
    let mut large_msg = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    large_msg.push_str(&"X".repeat(size));
    large_msg.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&large_msg]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    // This should fail with Json error due to type mismatch, but shouldn't panic.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(result.is_err());
}

#[tokio::test]
async fn buffer_overflow_exceeds_max_size() {
    // Test a message that definitely exceeds MAX_BUFFER_SIZE.
    // Since MockSocket reads all data at once, we need to simulate multiple reads that would
    // exceed the limit.
    let size = 50 * 1024 * 1024; // 50MB chunk.
    let chunk = "X".repeat(size);
    let mut large_msg = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    large_msg.push_str(&chunk);
    large_msg.push_str(&chunk);
    large_msg.push_str(&chunk); // Total > 150MB.
    large_msg.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&large_msg]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should return BufferOverflow error.
    assert!(matches!(result, Err(crate::Error::BufferOverflow)));
}

#[tokio::test]
async fn missing_null_terminator() {
    // Test message without proper null byte termination.
    // MockSocket automatically adds null bytes, so we need to test the read_from_socket logic
    // indirectly by ensuring empty stream case.
    let valid_msg = r#"{"method":"org.example.Test","parameters":{"value":42}}"#;
    let socket = MockSocket::with_responses(&[valid_msg]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    // First read should succeed.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(result.is_ok());

    // Second read should fail with UnexpectedEof.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(matches!(result, Err(crate::Error::UnexpectedEof)));
}

#[tokio::test]
async fn multiple_null_bytes_in_message() {
    // Test message with embedded null bytes (which shouldn't happen in valid JSON).
    let malicious = "{\0\"method\":\"org.example.Test\"\0}";
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail due to invalid JSON structure.
    assert!(matches!(
        result,
        Err(crate::Error::Json(_)) | Err(crate::Error::UnexpectedEof)
    ));
}

#[tokio::test]
async fn stream_deserializer_empty_buffer() {
    // Test the None case from StreamDeserializer when buffer is effectively empty.
    // Note: read_from_socket will return UnexpectedEof before we even get to the deserializer
    // since the socket returns 0 bytes on first read.
    let malicious = "";
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // MockSocket with empty string results in immediate EOF from socket.
    // This will trigger UnexpectedEof in read_from_socket, which happens before deserialization.
    assert!(result.is_err());
    // The actual error could be UnexpectedEof from socket or from deserializer.
    match result {
        Err(crate::Error::UnexpectedEof) => {}
        Err(crate::Error::Json(_)) => {}
        other => panic!("Expected error, got {:?}", other),
    }
}

#[tokio::test]
async fn stream_deserializer_whitespace_only() {
    // Test StreamDeserializer with only whitespace.
    let malicious = "     \n\n\t\t   ";
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should return UnexpectedEof or Json error.
    assert!(matches!(
        result,
        Err(crate::Error::Json(_)) | Err(crate::Error::UnexpectedEof)
    ));
}

#[tokio::test]
async fn malformed_json_repeated_keys() {
    // Test JSON with many repeated keys to stress the parser.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"#.to_string();
    for i in 0..10000 {
        malicious.push_str(&format!(r#""key{i}":"value{i}","#));
    }
    malicious.push_str(r#""value":42}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should either succeed or fail gracefully.
    // The TestMethod type expects only a "value" field, so this will likely fail during
    // deserialization to TestMethod.
    // But it shouldn't panic.
    if let Err(e) = result {
        assert!(matches!(e, crate::Error::Json(_)));
    }
}

#[tokio::test]
async fn malformed_json_very_long_array() {
    // Test very long array in parameters.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"value":["#.to_string();
    for i in 0..100000 {
        if i > 0 {
            malicious.push(',');
        }
        malicious.push_str(&i.to_string());
    }
    malicious.push_str(r#"]}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail with type error but not panic.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn byte_offset_calculation_with_valid_json() {
    // Verify that stream.byte_offset() correctly identifies the end of valid JSON.
    let valid_msg = r#"{"method":"org.example.Test","parameters":{"value":42}}"#;
    let socket = MockSocket::with_responses(&[valid_msg]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    assert!(result.is_ok());
    #[cfg(feature = "std")]
    let (call, _fds) = result.unwrap();
    #[cfg(not(feature = "std"))]
    let call = result.unwrap();
    assert_eq!(call.method, TestMethod::Test { value: 42 });
}

#[tokio::test]
async fn byte_offset_calculation_with_trailing_data() {
    // Test that byte_offset correctly handles when there's trailing data after valid JSON.
    let valid_msg1 = r#"{"method":"org.example.Test","parameters":{"value":42}}"#;
    let valid_msg2 = r#"{"method":"org.example.Test","parameters":{"value":99}}"#;
    let socket = MockSocket::with_responses(&[valid_msg1, valid_msg2]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    // First message.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(result.is_ok());
    #[cfg(feature = "std")]
    let (call, _fds) = result.unwrap();
    #[cfg(not(feature = "std"))]
    let call = result.unwrap();
    assert_eq!(call.method, TestMethod::Test { value: 42 });

    // Second message.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(result.is_ok());
    #[cfg(feature = "std")]
    let (call, _fds) = result.unwrap();
    #[cfg(not(feature = "std"))]
    let call = result.unwrap();
    assert_eq!(call.method, TestMethod::Test { value: 99 });
}

#[tokio::test]
async fn error_propagation_json_to_error() {
    // Verify JSON deserialization errors are properly converted to crate::Error::Json.
    let invalid_json = r#"{"method":"org.example.Test","parameters":{"value":"not_a_number"}}"#;
    let socket = MockSocket::with_responses(&[invalid_json]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    match result {
        Err(crate::Error::Json(e)) => {
            // Verify it's a proper JSON error.
            assert!(!e.to_string().is_empty());
        }
        _ => panic!("Expected Error::Json, got {:?}", result),
    }
}

#[tokio::test]
async fn receive_reply_with_malformed_json() {
    // Test receive_reply with malformed JSON.
    let malformed = r#"{"parameters":{"result":"incomplete"#;
    let socket = MockSocket::with_responses(&[malformed]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_reply::<TestReply, TestReply>().await;
    assert!(matches!(
        result,
        Err(crate::Error::Json(_)) | Err(crate::Error::UnexpectedEof)
    ));
}

#[tokio::test]
async fn receive_reply_with_large_payload() {
    // Test receive_reply with very large but valid reply.
    let large_result = "X".repeat(1024 * 1024); // 1MB string.
    let reply = format!(r#"{{"parameters":{{"result":"{}"}}}}"#, large_result);
    let socket = MockSocket::with_responses(&[&reply]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_reply::<TestReply, TestReply>().await;
    // Should succeed and return the large payload.
    assert!(result.is_ok());
}

#[tokio::test]
async fn malformed_json_mixed_control_characters() {
    // Test JSON with unusual control characters.
    let malicious = "{\x01\"method\"\x02:\x03\"org.example.Test\"}";
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_number_overflow() {
    // Test with extremely large numbers that might cause overflow.
    let malicious = r#"{"method":"org.example.Test","parameters":{"value":999999999999999999999999999999999999999999999999999}}"#;
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should fail with JSON deserialization error.
    assert!(matches!(result, Err(crate::Error::Json(_))));
}

#[tokio::test]
async fn malformed_json_duplicate_keys() {
    // Test JSON with duplicate keys in the same object.
    let malicious =
        r#"{"method":"org.example.Test","method":"org.example.Other","parameters":{"value":42}}"#;
    let socket = MockSocket::with_responses(&[malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // serde_json typically accepts the last duplicate key, so this might succeed or fail
    // depending on the "Other" method name.
    // The important part is it doesn't panic.
    let _ = result;
}

#[tokio::test]
async fn malformed_json_unicode_escapes() {
    // Test excessive unicode escape sequences.
    let mut malicious = r#"{"method":"org.example.Test","parameters":{"value":"#.to_string();
    for _ in 0..10000 {
        malicious.push_str(r#"\u0041"#); // 'A' in unicode.
    }
    malicious.push_str(r#"}}"#);

    let socket = MockSocket::with_responses(&[&malicious]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    let result = conn.receive_call::<TestMethod>().await;
    // Should handle unicode escapes gracefully.
    assert!(result.is_err()); // Will fail type checking.
}

#[tokio::test]
async fn partial_message_at_buffer_boundary() {
    // Test handling of partial messages that arrive at buffer boundaries.
    // MockSocket reads everything at once, so we test the logic by ensuring the connection
    // properly handles the end of data.
    let valid_msg = r#"{"method":"org.example.Test","parameters":{"value":42}}"#;
    let socket = MockSocket::with_responses(&[valid_msg]);
    let (read, _write) = socket.split();
    let mut conn = ReadConnection::new(read, 0);

    // First read succeeds.
    assert!(conn.receive_call::<TestMethod>().await.is_ok());

    // Second read should fail with UnexpectedEof.
    let result = conn.receive_call::<TestMethod>().await;
    assert!(matches!(result, Err(crate::Error::UnexpectedEof)));
}