structured-asn1 0.6.3

Borrowed BER/DER parsing with shared work budgets and exact byte ranges
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
//! Original-source and current-operation ceilings fund deferred readers once.

use std::sync::Arc;
use structured_asn1::{
    Encoding, ErrorCode, Limit, Limits, Parser,
    memory::{Memory, MemoryAccount, Work},
};

fn memory() -> Memory {
    Memory::new(Arc::new(MemoryAccount::new(65536, 65536)))
}

fn oid_after_temporary_operation<'source>(
    source: &'source Parser,
    bytes: &'source [u8],
    current: &Memory,
) -> structured_asn1::Oid<'source> {
    let operation = Parser::der(current.clone());
    let query = operation.read(&[], 900).unwrap();
    let execution = query.execution();
    let mut reader = execution
        .read_scoped_source(source, bytes, 400, Encoding::Der, 0)
        .unwrap();
    reader.read_oid().unwrap()
}

#[test]
fn original_input_view_outlives_scoped_reader_and_operation_without_copy_or_reparse() {
    // The bytes remain original while the operation/source parser budget
    // borrows end independently. No owning budget clone or input projection
    // allocation is required to return a parsed scalar from a local operation.
    let bytes = [6, 2, 42, 3];
    let source = Parser::der(memory());
    let current = memory();
    let oid = oid_after_temporary_operation(&source, &bytes, &current);
    assert_eq!(oid.as_bytes(), &[42, 3]);
    assert_eq!(oid.as_bytes().as_ptr(), bytes[2..].as_ptr());
    assert!(current.work_used() > 0);
    assert_eq!(source.memory().work_used(), 0);
    assert_eq!(current.used(), 0);
}

#[test]
fn metadata_query_preserves_both_work_ceilings_without_payload_depth_or_old_sources() {
    // Metadata does not descend into ASN.1. It still funds source+current work,
    // deduplicates one session and cannot retain an old foreign source instead
    // of the actual root operation.
    for (source_work, query_work, succeeds) in [(0, 100, false), (100, 0, false), (100, 100, true)]
    {
        let original = memory();
        let current = memory();
        let source = Parser::new(
            Encoding::Der,
            Limits {
                max_work: source_work,
                max_depth: 0,
                ..Limits::default()
            },
            original.clone(),
        );
        let operation = Parser::new(
            Encoding::Der,
            Limits {
                max_work: query_work,
                max_depth: 0,
                ..Limits::default()
            },
            current.clone(),
        );
        let origin = source.read(&[], 400).unwrap();
        let query = operation.read(&[], 900).unwrap();
        assert_eq!(
            origin.execution_query(&query).charge_work(7).is_ok(),
            succeeds
        );
        assert_eq!(original.work_used(), 0);
        assert_eq!(current.work_used(), if succeeds { 7 } else { 0 });
        assert_eq!(current.used(), 0);
    }
    let current = memory();
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 7,
            ..Limits::default()
        },
        current.clone(),
    );
    let original = root.read(&[], 400).unwrap();
    let query = root.read(&[], 900).unwrap();
    original.execution_query(&query).charge_work(7).unwrap();
    assert!(original.execution_query(&query).charge_work(1).is_err());
    assert_eq!(current.work_used(), 7);

    let current = memory();
    let root = Parser::der(current.clone());
    let root_query = root.read(&[], 900).unwrap();
    let past = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 1,
            ..Limits::default()
        },
        memory(),
    );
    let past_query = past
        .read_query_in(&root_query, &[], 800, Encoding::Der, 0)
        .unwrap();
    let fresh = Parser::der(memory());
    let origin = fresh.read(&[], 400).unwrap();
    origin.execution_query(&past_query).charge_work(7).unwrap();
    assert_eq!(current.work_used(), 8);
    assert_eq!(past.memory().work_used(), 0);
    assert_eq!(fresh.memory().work_used(), 0);
}

fn lazy_from_work<'source, W: Work + 'source>(
    execution: &W,
    source: &'source Parser,
    bytes: &'source [u8],
) -> structured_asn1::Result<structured_asn1::Reader<'source>> {
    execution.read_nested(source, bytes, 400, Encoding::Ber, 2)
}

#[test]
fn generic_work_fresh_source_uses_actual_depth_zero_without_a_fake_carrier() {
    // Retained original windows (e.g. BER Name string preparation) can need a
    // fresh depth-zero view. A generic Work route must preserve the operation,
    // not replace it with a new Memory-only parser or an extra nesting level.
    let current = memory();
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 0,
            ..Limits::default()
        },
        current.clone(),
    );
    let source = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 0,
            ..Limits::default()
        },
        memory(),
    );
    let query = root.read(&[], 900).unwrap();
    let mut fresh = query
        .execution()
        .read_source(&source, &[2, 1, 7], 400, Encoding::Der, 0)
        .unwrap();
    assert_eq!(fresh.depth(), 0);
    assert_eq!(fresh.offset(), 400);
    assert_eq!(fresh.next_element().unwrap().unwrap().contents(), &[7]);
    assert_eq!(current.work_used(), 3);
    assert_eq!(
        query
            .execution()
            .read_nested(&source, &[2, 1, 7], 400, Encoding::Der, 0)
            .unwrap_err()
            .code(),
        ErrorCode::LimitExceeded(Limit::Depth)
    );
    assert_eq!(current.work_used(), 3);
}

#[test]
fn generic_work_lazy_reader_does_not_borrow_the_temporary_execution_object() {
    // The caller keeps the actual source/root budgets, not the stack-local
    // execution wrapper. Data, account, encoding and actual depth stay original.
    let storage = memory();
    let current = memory();
    let source = Parser::ber(storage.clone());
    let root = Parser::der(current.clone());
    let query = root.read(&[], 900).unwrap();
    let bytes = [0x30, 0x80, 2, 1, 7, 0, 0];
    let mut lazy = lazy_from_work(&query.execution(), &source, &bytes).unwrap();
    assert_eq!(lazy.offset(), 400);
    assert_eq!(lazy.depth(), 3);
    assert_eq!(lazy.encoding(), Encoding::Ber);
    assert!(core::ptr::eq(lazy.parser(), &raw const source));
    assert!(lazy.memory().same_account(&current));
    let value = lazy.next_element().unwrap().unwrap();
    assert_eq!(value.as_bytes().as_ptr(), bytes.as_ptr());
    assert_eq!(value.span().start, 400);
    assert_eq!(storage.work_used(), 0);
    assert!(current.work_used() > 0);
    drop(lazy);
    assert_eq!(current.used(), 0);
}

#[test]
fn generic_work_lazy_reader_enforces_each_local_and_aggregate_boundary() {
    // Original parsing, operation admission and aggregate work remain three
    // independent checks; no result is created by falling back to Memory.
    for (source_work, operation_work, aggregate_work) in
        [(0, 100, 100), (100, 0, 100), (100, 100, 0)]
    {
        let source = Parser::new(
            Encoding::Ber,
            Limits {
                max_work: source_work,
                ..Limits::default()
            },
            memory(),
        );
        let current = Memory::new(Arc::new(MemoryAccount::new(65536, aggregate_work)));
        let root = Parser::new(
            Encoding::Ber,
            Limits {
                max_work: operation_work,
                ..Limits::default()
            },
            current.clone(),
        );
        let query = root.read(&[], 900).unwrap();
        let error = lazy_from_work(&query.execution(), &source, &[2, 1, 7]).unwrap_err();
        assert_eq!(error.code(), ErrorCode::LimitExceeded(Limit::Work));
        assert_eq!(error.offset(), 400);
        drop(error);
        assert_eq!(current.work_used(), 0);
        assert_eq!(current.used(), 0);
    }
}

#[test]
fn generic_work_lazy_reader_deduplicates_same_session_and_drops_past_foreign_ceiling() {
    // Same-session admission charges once. A foreign transition replaces its
    // previous source ceiling while retaining the actual root operation.
    let current = memory();
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 3,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = root.read(&[], 900).unwrap();
    let middle = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 1,
            ..Limits::default()
        },
        memory(),
    );
    let first = query
        .execution()
        .read_nested(&middle, &[], 400, Encoding::Der, 0)
        .unwrap();
    let last = Parser::der(memory());
    let second = first
        .execution()
        .read_nested(&last, &[], 700, Encoding::Der, 0)
        .unwrap();
    second.execution().charge_work(1).unwrap();
    assert_eq!(current.work_used(), 3);
    assert!(second.execution().charge_work(1).is_err());
    assert_eq!(current.work_used(), 3);

    let account = memory();
    let same = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 1,
            ..Limits::default()
        },
        account.clone(),
    );
    let original = same.read(&[], 0).unwrap();
    let lazy = original
        .execution()
        .read_nested(&same, &[], 400, Encoding::Der, 0)
        .unwrap();
    assert_eq!(account.work_used(), 1);
    assert!(lazy.execution().charge_work(1).is_err());
    assert_eq!(account.work_used(), 1);
}

#[test]
fn aggregate_work_reader_keeps_the_existing_memory_only_source_semantics() {
    // Default Memory callers keep their existing source lifetime/admission,
    // rather than obtaining an invented additional parser/operation budget.
    let current = memory();
    let source = Parser::ber(memory());
    let lazy = lazy_from_work(&current, &source, &[2, 1, 7]).unwrap();
    let original = source
        .read_nested_in(&[2, 1, 7], 400, Encoding::Ber, 2, &current)
        .unwrap();
    assert_eq!(lazy.depth(), original.depth());
    assert_eq!(lazy.offset(), original.offset());
    assert_eq!(lazy.encoding(), original.encoding());
    assert_eq!(current.work_used(), 0);
    assert!(lazy.memory().same_account(&current));
}

#[test]
fn fresh_foreign_document_uses_depth_zero_under_the_same_query_limits() {
    // A non-ASN carrier adds no ASN container. Root primitives fit depth0,
    // while descending into a root SEQUENCE still requires depth1 permission.
    let storage = memory();
    let current = memory();
    let source = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 0,
            ..Limits::default()
        },
        storage.clone(),
    );
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 0,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = root.read(&[], 900).unwrap();
    let mut primitive = source
        .read_query_in(&query, &[2, 1, 7], 400, Encoding::Der, 0)
        .unwrap();
    assert_eq!(primitive.depth(), 0);
    assert_eq!(primitive.next_element().unwrap().unwrap().contents(), &[7]);
    assert_eq!(current.work_used(), 3);
    assert_eq!(storage.work_used(), 0);
    let mut constructed = source
        .read_query_in(&query, &[48, 3, 2, 1, 7], 700, Encoding::Der, 0)
        .unwrap();
    let sequence = constructed.next_element().unwrap().unwrap();
    let error = constructed.enter(&sequence).unwrap_err();
    assert_eq!(error.code(), ErrorCode::LimitExceeded(Limit::Depth));
    // Descent refusal is located at the original contents start, after its
    // two-byte SEQUENCE header, as Reader::enter documents/implements.
    assert_eq!(error.offset(), sequence.contents_span().start);
    assert_eq!(error.offset(), 702);
    // The located diagnostic itself retains its admitted path capacity until
    // the error is dropped; that charge belongs to the current account.
    assert!(current.used() > 0);
    assert_eq!(storage.used(), 0);
    drop(error);
    assert_eq!(current.used(), 0);
}

#[test]
fn actual_depth_query_and_nested_query_have_identical_provenance_and_admission() {
    // Both entry points must share the same original/current budget core;
    // nested computes outer+1, while a decoded window already knows its depth.
    let current = memory();
    let root = Parser::der(current.clone());
    let source = Parser::der(memory());
    let query = root.read(&[], 900).unwrap();
    let actual = source
        .read_query_in(&query, &[], 400, Encoding::Der, 2)
        .unwrap();
    let nested = source
        .read_nested_query_in(&query, &[], 400, Encoding::Der, 1)
        .unwrap();
    assert_eq!(actual.depth(), nested.depth());
    assert_eq!(actual.offset(), nested.offset());
    assert!(core::ptr::eq(actual.parser(), nested.parser()));
    assert_eq!(current.work_used(), 2);
    assert_eq!(
        source
            .read_nested_query_in(&query, &[], 400, Encoding::Der, u32::MAX)
            .unwrap_err()
            .code(),
        ErrorCode::LimitExceeded(Limit::Depth)
    );
    assert_eq!(current.work_used(), 2);
}

#[test]
fn actual_depth_query_refuses_both_source_and_current_limits_before_work() {
    // Explicit depth cannot reset the original source or bypass a narrower
    // current operation. Refused creation has no storage or aggregate charge.
    let current = memory();
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 1,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = root.read(&[], 900).unwrap();
    let source = Parser::der(memory());
    assert_eq!(
        source
            .read_query_in(&query, &[], 400, Encoding::Der, 2)
            .unwrap_err()
            .code(),
        ErrorCode::LimitExceeded(Limit::Depth)
    );
    let source = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 0,
            ..Limits::default()
        },
        memory(),
    );
    assert_eq!(
        source
            .read_query_in(&query, &[], 700, Encoding::Der, 0)
            .unwrap_err()
            .code(),
        ErrorCode::LimitExceeded(Limit::Work)
    );
    let source = Parser::new(
        Encoding::Der,
        Limits {
            max_depth: 0,
            ..Limits::default()
        },
        memory(),
    );
    assert_eq!(
        source
            .read_query_in(&query, &[], 1100, Encoding::Der, 1)
            .unwrap_err()
            .code(),
        ErrorCode::LimitExceeded(Limit::Depth)
    );
    assert_eq!(current.work_used(), 0);
    assert_eq!(current.used(), 0);
}

#[test]
fn foreign_source_scan_and_scratch_obey_current_query_ceiling() {
    // The stored document's generous budget is not credit for a zero-budget
    // later query. Current account and local ceiling are both checked before
    // reader creation, scanning and scratch allocation/copy.
    let storage = memory();
    let current = memory();
    let origin = Parser::der(storage.clone());
    let none = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 0,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = none.read(&[], 900).unwrap();
    let error = origin
        .read_nested_query_in(&query, &[2, 1, 7], 400, Encoding::Der, 0)
        .unwrap_err();
    assert_eq!(error.code(), ErrorCode::LimitExceeded(Limit::Work));
    assert_eq!(error.offset(), 400);
    assert_eq!(current.work_used(), 0);
    assert_eq!(storage.work_used(), 0);
    let limited = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 3,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = limited.read(&[], 900).unwrap();
    let mut reader = origin
        .read_nested_query_in(&query, &[2, 1, 7], 400, Encoding::Der, 0)
        .unwrap();
    assert!(reader.next_element().unwrap().is_some());
    assert_eq!(current.work_used(), 3);
    assert_eq!(storage.work_used(), 0);
    let mut scratch = reader.execution().vector();
    assert!(scratch.try_push(7_u8).is_err());
    assert_eq!(current.used(), 0);
    assert_eq!(current.work_used(), 3);
}

#[test]
fn same_source_operation_deduplicates_local_and_aggregate_accounting() {
    // One creation plus one short header costs exactly three units, even when
    // the source and current-operation Budget are the very same object.
    let current = memory();
    let parser = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 3,
            ..Limits::default()
        },
        current.clone(),
    );
    let query = parser.read(&[], 900).unwrap();
    let mut reader = parser
        .read_nested_query_in(&query, &[2, 1, 7], 400, Encoding::Der, 0)
        .unwrap();
    assert!(reader.next_element().unwrap().is_some());
    assert_eq!(current.work_used(), 3);
    assert!(reader.charge(1).unwrap_err().is_resource());
    assert_eq!(current.work_used(), 3);
}

#[test]
fn foreign_transition_retains_root_operation_and_original_depth() {
    // The intermediate source is not a fresh operation ceiling. A second
    // foreign source must retain the root's remaining one unit and its depth.
    let current = memory();
    let root = Parser::new(
        Encoding::Der,
        Limits {
            max_work: 2,
            max_depth: 2,
            ..Limits::default()
        },
        current.clone(),
    );
    let first = Parser::der(memory());
    let second = Parser::der(memory());
    let query = root.read(&[], 900).unwrap();
    let first_reader = first
        .read_nested_query_in(&query, &[], 400, Encoding::Der, 0)
        .unwrap();
    let mut second_reader = second
        .read_nested_query_in(&first_reader, &[2, 1, 7], 700, Encoding::Der, 0)
        .unwrap();
    assert!(core::ptr::eq(
        second_reader.parser(),
        core::ptr::from_ref(&second)
    ));
    assert_eq!(second_reader.depth(), 1);
    assert_eq!(second_reader.next_element().unwrap_err().offset(), 700);
    assert_eq!(current.work_used(), 2);
    let error = second
        .read_nested_query_in(&query, &[], 700, Encoding::Der, 2)
        .unwrap_err();
    assert_eq!(error.code(), ErrorCode::LimitExceeded(Limit::Depth));
    assert_eq!(current.work_used(), 2);
}

#[test]
fn clone_reread_and_descent_keep_current_element_ceiling() {
    // Cursor copying, rereading and entering must not reset the later query's
    // element counter, even though the stored source permits many elements.
    let current = memory();
    let root = Parser::new(
        Encoding::Ber,
        Limits {
            max_elements: 1,
            ..Limits::default()
        },
        current.clone(),
    );
    let source = Parser::ber(memory());
    let query = root.read(&[], 900).unwrap();
    let mut reader = source
        .read_nested_query_in(&query, &[0x30, 3, 2, 1, 7], 400, Encoding::Ber, 0)
        .unwrap();
    let sequence = reader.next_element().unwrap().unwrap();
    let mut copied = reader.try_clone().unwrap();
    assert!(copied.next_element().unwrap().is_none());
    let mut repeated = copied.reread(&sequence, Encoding::Ber).unwrap();
    assert_eq!(
        repeated.next_element().unwrap_err().code(),
        ErrorCode::LimitExceeded(Limit::Elements)
    );
    let mut child = copied.enter(&sequence).unwrap();
    assert_eq!(
        child.next_element().unwrap_err().code(),
        ErrorCode::LimitExceeded(Limit::Elements)
    );
    assert_eq!(child.depth(), 2);
    assert!(core::ptr::eq(child.parser(), core::ptr::from_ref(&source)));
}

#[test]
fn query_length_refusal_precedes_indefinite_descendant_scan() {
    // Both definite contents and BER indefinite scanning must obey the current
    // query's length ceiling, not only the source's original large allowance.
    let current = memory();
    let root = Parser::new(
        Encoding::Ber,
        Limits {
            max_element_length: 2,
            ..Limits::default()
        },
        current.clone(),
    );
    let source = Parser::ber(memory());
    let query = root.read(&[], 900).unwrap();
    let mut definite = source
        .read_nested_query_in(&query, &[4, 3, 1, 2, 3], 400, Encoding::Ber, 0)
        .unwrap();
    assert_eq!(
        definite.next_element().unwrap_err().code(),
        ErrorCode::LimitExceeded(Limit::ElementLength)
    );
    let mut indefinite = source
        .read_nested_query_in(
            &query,
            &[0x30, 0x80, 4, 3, 1, 2, 3, 0, 0],
            700,
            Encoding::Ber,
            0,
        )
        .unwrap();
    assert_eq!(
        indefinite.next_element().unwrap_err().code(),
        ErrorCode::LimitExceeded(Limit::ElementLength)
    );
    assert_eq!(current.used(), 0);
}