-
Notifications
You must be signed in to change notification settings - Fork 112
/
tests.rs
1455 lines (1225 loc) · 49 KB
/
tests.rs
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// rstest_reuse template functions have unused variables
#![allow(unused_variables)]
use rand::{
self,
distributions::{self, Distribution as _},
rngs, Rng as _, SeedableRng as _,
};
use rstest::rstest;
use rstest_reuse::{apply, template};
use std::{collections, fmt};
use crate::{
alphabet::{Alphabet, STANDARD},
encode::add_padding,
encoded_len,
engine::{general_purpose, naive, Config, DecodeEstimate, DecodePaddingMode, Engine},
tests::{assert_encode_sanity, random_alphabet, random_config},
DecodeError, PAD_BYTE,
};
// the case::foo syntax includes the "foo" in the generated test method names
#[template]
#[rstest(engine_wrapper,
case::general_purpose(GeneralPurposeWrapper {}),
case::naive(NaiveWrapper {}),
)]
fn all_engines<E: EngineWrapper>(engine_wrapper: E) {}
#[apply(all_engines)]
fn rfc_test_vectors_std_alphabet<E: EngineWrapper>(engine_wrapper: E) {
let data = vec![
("", ""),
("f", "Zg=="),
("fo", "Zm8="),
("foo", "Zm9v"),
("foob", "Zm9vYg=="),
("fooba", "Zm9vYmE="),
("foobar", "Zm9vYmFy"),
];
let engine = E::standard();
let engine_no_padding = E::standard_unpadded();
for (orig, encoded) in &data {
let encoded_without_padding = encoded.trim_end_matches('=');
// unpadded
{
let mut encode_buf = [0_u8; 8];
let mut decode_buf = [0_u8; 6];
let encode_len =
engine_no_padding.internal_encode(orig.as_bytes(), &mut encode_buf[..]);
assert_eq!(
&encoded_without_padding,
&std::str::from_utf8(&encode_buf[0..encode_len]).unwrap()
);
let decode_len = engine_no_padding
.decode_slice_unchecked(encoded_without_padding.as_bytes(), &mut decode_buf[..])
.unwrap();
assert_eq!(orig.len(), decode_len);
assert_eq!(
orig,
&std::str::from_utf8(&decode_buf[0..decode_len]).unwrap()
);
// if there was any padding originally, the no padding engine won't decode it
if encoded.as_bytes().contains(&PAD_BYTE) {
assert_eq!(
Err(DecodeError::InvalidPadding),
engine_no_padding.decode(encoded)
)
}
}
// padded
{
let mut encode_buf = [0_u8; 8];
let mut decode_buf = [0_u8; 6];
let encode_len = engine.internal_encode(orig.as_bytes(), &mut encode_buf[..]);
assert_eq!(
// doesn't have padding added yet
&encoded_without_padding,
&std::str::from_utf8(&encode_buf[0..encode_len]).unwrap()
);
let pad_len = add_padding(encode_len, &mut encode_buf[encode_len..]);
assert_eq!(encoded.as_bytes(), &encode_buf[..encode_len + pad_len]);
let decode_len = engine
.decode_slice_unchecked(encoded.as_bytes(), &mut decode_buf[..])
.unwrap();
assert_eq!(orig.len(), decode_len);
assert_eq!(
orig,
&std::str::from_utf8(&decode_buf[0..decode_len]).unwrap()
);
// if there was (canonical) padding, and we remove it, the standard engine won't decode
if encoded.as_bytes().contains(&PAD_BYTE) {
assert_eq!(
Err(DecodeError::InvalidPadding),
engine.decode(encoded_without_padding)
)
}
}
}
}
#[apply(all_engines)]
fn roundtrip_random<E: EngineWrapper>(engine_wrapper: E) {
let mut rng = seeded_rng();
let mut orig_data = Vec::<u8>::new();
let mut encode_buf = Vec::<u8>::new();
let mut decode_buf = Vec::<u8>::new();
let len_range = distributions::Uniform::new(1, 1_000);
for _ in 0..10_000 {
let engine = E::random(&mut rng);
orig_data.clear();
encode_buf.clear();
decode_buf.clear();
let (orig_len, _, encoded_len) = generate_random_encoded_data(
&engine,
&mut orig_data,
&mut encode_buf,
&mut rng,
&len_range,
);
// exactly the right size
decode_buf.resize(orig_len, 0);
let dec_len = engine
.decode_slice_unchecked(&encode_buf[0..encoded_len], &mut decode_buf[..])
.unwrap();
assert_eq!(orig_len, dec_len);
assert_eq!(&orig_data[..], &decode_buf[..dec_len]);
}
}
#[apply(all_engines)]
fn encode_doesnt_write_extra_bytes<E: EngineWrapper>(engine_wrapper: E) {
let mut rng = seeded_rng();
let mut orig_data = Vec::<u8>::new();
let mut encode_buf = Vec::<u8>::new();
let mut encode_buf_backup = Vec::<u8>::new();
let input_len_range = distributions::Uniform::new(0, 1000);
for _ in 0..10_000 {
let engine = E::random(&mut rng);
let padded = engine.config().encode_padding();
orig_data.clear();
encode_buf.clear();
encode_buf_backup.clear();
let orig_len = fill_rand(&mut orig_data, &mut rng, &input_len_range);
let prefix_len = 1024;
// plenty of prefix and suffix
fill_rand_len(&mut encode_buf, &mut rng, prefix_len * 2 + orig_len * 2);
encode_buf_backup.extend_from_slice(&encode_buf[..]);
let expected_encode_len_no_pad = encoded_len(orig_len, false).unwrap();
let encoded_len_no_pad =
engine.internal_encode(&orig_data[..], &mut encode_buf[prefix_len..]);
assert_eq!(expected_encode_len_no_pad, encoded_len_no_pad);
// no writes past what it claimed to write
assert_eq!(&encode_buf_backup[..prefix_len], &encode_buf[..prefix_len]);
assert_eq!(
&encode_buf_backup[(prefix_len + encoded_len_no_pad)..],
&encode_buf[(prefix_len + encoded_len_no_pad)..]
);
let encoded_data = &encode_buf[prefix_len..(prefix_len + encoded_len_no_pad)];
assert_encode_sanity(
std::str::from_utf8(encoded_data).unwrap(),
// engines don't pad
false,
orig_len,
);
// pad so we can decode it in case our random engine requires padding
let pad_len = if padded {
add_padding(
encoded_len_no_pad,
&mut encode_buf[prefix_len + encoded_len_no_pad..],
)
} else {
0
};
assert_eq!(
orig_data,
engine
.decode(&encode_buf[prefix_len..(prefix_len + encoded_len_no_pad + pad_len)],)
.unwrap()
);
}
}
#[apply(all_engines)]
fn encode_engine_slice_fits_into_precisely_sized_slice<E: EngineWrapper>(engine_wrapper: E) {
let mut orig_data = Vec::new();
let mut encoded_data = Vec::new();
let mut decoded = Vec::new();
let input_len_range = distributions::Uniform::new(0, 1000);
let mut rng = rngs::SmallRng::from_entropy();
for _ in 0..10_000 {
orig_data.clear();
encoded_data.clear();
decoded.clear();
let input_len = input_len_range.sample(&mut rng);
for _ in 0..input_len {
orig_data.push(rng.gen());
}
let engine = E::random(&mut rng);
let encoded_size = encoded_len(input_len, engine.config().encode_padding()).unwrap();
encoded_data.resize(encoded_size, 0);
assert_eq!(
encoded_size,
engine.encode_slice(&orig_data, &mut encoded_data).unwrap()
);
assert_encode_sanity(
std::str::from_utf8(&encoded_data[0..encoded_size]).unwrap(),
engine.config().encode_padding(),
input_len,
);
engine
.decode_vec(&encoded_data[0..encoded_size], &mut decoded)
.unwrap();
assert_eq!(orig_data, decoded);
}
}
#[apply(all_engines)]
fn decode_doesnt_write_extra_bytes<E>(engine_wrapper: E)
where
E: EngineWrapper,
<<E as EngineWrapper>::Engine as Engine>::Config: fmt::Debug,
{
let mut rng = seeded_rng();
let mut orig_data = Vec::<u8>::new();
let mut encode_buf = Vec::<u8>::new();
let mut decode_buf = Vec::<u8>::new();
let mut decode_buf_backup = Vec::<u8>::new();
let len_range = distributions::Uniform::new(1, 1_000);
for _ in 0..10_000 {
let engine = E::random(&mut rng);
orig_data.clear();
encode_buf.clear();
decode_buf.clear();
decode_buf_backup.clear();
let orig_len = fill_rand(&mut orig_data, &mut rng, &len_range);
encode_buf.resize(orig_len * 2 + 100, 0);
let encoded_len = engine
.encode_slice(&orig_data[..], &mut encode_buf[..])
.unwrap();
encode_buf.truncate(encoded_len);
// oversize decode buffer so we can easily tell if it writes anything more than
// just the decoded data
let prefix_len = 1024;
// plenty of prefix and suffix
fill_rand_len(&mut decode_buf, &mut rng, prefix_len * 2 + orig_len * 2);
decode_buf_backup.extend_from_slice(&decode_buf[..]);
let dec_len = engine
.decode_slice_unchecked(&encode_buf, &mut decode_buf[prefix_len..])
.unwrap();
assert_eq!(orig_len, dec_len);
assert_eq!(
&orig_data[..],
&decode_buf[prefix_len..prefix_len + dec_len]
);
assert_eq!(&decode_buf_backup[..prefix_len], &decode_buf[..prefix_len]);
assert_eq!(
&decode_buf_backup[prefix_len + dec_len..],
&decode_buf[prefix_len + dec_len..]
);
}
}
#[apply(all_engines)]
fn decode_detect_invalid_last_symbol<E: EngineWrapper>(engine_wrapper: E) {
// 0xFF -> "/w==", so all letters > w, 0-9, and '+', '/' should get InvalidLastSymbol
let engine = E::standard();
assert_eq!(Ok(vec![0x89, 0x85]), engine.decode("iYU="));
assert_eq!(Ok(vec![0xFF]), engine.decode("/w=="));
for (suffix, offset) in vec![
// suffix, offset of bad byte from start of suffix
("/x==", 1_usize),
("/z==", 1_usize),
("/0==", 1_usize),
("/9==", 1_usize),
("/+==", 1_usize),
("//==", 1_usize),
// trailing 01
("iYV=", 2_usize),
// trailing 10
("iYW=", 2_usize),
// trailing 11
("iYX=", 2_usize),
] {
for prefix_quads in 0..256 {
let mut encoded = "AAAA".repeat(prefix_quads);
encoded.push_str(suffix);
assert_eq!(
Err(DecodeError::InvalidLastSymbol(
encoded.len() - 4 + offset,
suffix.as_bytes()[offset],
)),
engine.decode(encoded.as_str())
);
}
}
}
#[apply(all_engines)]
fn decode_detect_invalid_last_symbol_when_length_is_also_invalid<E: EngineWrapper>(
engine_wrapper: E,
) {
let mut rng = seeded_rng();
// check across enough lengths that it would likely cover any implementation's various internal
// small/large input division
for len in (0_usize..256).map(|len| len * 4 + 1) {
let engine = E::random_alphabet(&mut rng, &STANDARD);
let mut input = vec![b'A'; len];
// with a valid last char, it's InvalidLength
assert_eq!(Err(DecodeError::InvalidLength), engine.decode(&input));
// after mangling the last char, it's InvalidByte
input[len - 1] = b'"';
assert_eq!(
Err(DecodeError::InvalidByte(len - 1, b'"')),
engine.decode(&input)
);
}
}
#[apply(all_engines)]
fn decode_detect_invalid_last_symbol_every_possible_two_symbols<E: EngineWrapper>(
engine_wrapper: E,
) {
let engine = E::standard();
let mut base64_to_bytes = collections::HashMap::new();
for b in 0_u8..=255 {
let mut b64 = vec![0_u8; 4];
assert_eq!(2, engine.internal_encode(&[b], &mut b64[..]));
let _ = add_padding(2, &mut b64[2..]);
assert!(base64_to_bytes.insert(b64, vec![b]).is_none());
}
// every possible combination of trailing symbols must either decode to 1 byte or get InvalidLastSymbol, with or without any leading chunks
let mut prefix = Vec::new();
for _ in 0..256 {
let mut clone = prefix.clone();
let mut symbols = [0_u8; 4];
for &s1 in STANDARD.symbols.iter() {
symbols[0] = s1;
for &s2 in STANDARD.symbols.iter() {
symbols[1] = s2;
symbols[2] = PAD_BYTE;
symbols[3] = PAD_BYTE;
// chop off previous symbols
clone.truncate(prefix.len());
clone.extend_from_slice(&symbols[..]);
let decoded_prefix_len = prefix.len() / 4 * 3;
match base64_to_bytes.get(&symbols[..]) {
Some(bytes) => {
let res = engine
.decode(&clone)
// remove prefix
.map(|decoded| decoded[decoded_prefix_len..].to_vec());
assert_eq!(Ok(bytes.clone()), res);
}
None => assert_eq!(
Err(DecodeError::InvalidLastSymbol(1, s2)),
engine.decode(&symbols[..])
),
}
}
}
prefix.extend_from_slice(b"AAAA");
}
}
#[apply(all_engines)]
fn decode_detect_invalid_last_symbol_every_possible_three_symbols<E: EngineWrapper>(
engine_wrapper: E,
) {
let engine = E::standard();
let mut base64_to_bytes = collections::HashMap::new();
let mut bytes = [0_u8; 2];
for b1 in 0_u8..=255 {
bytes[0] = b1;
for b2 in 0_u8..=255 {
bytes[1] = b2;
let mut b64 = vec![0_u8; 4];
assert_eq!(3, engine.internal_encode(&bytes, &mut b64[..]));
let _ = add_padding(3, &mut b64[3..]);
let mut v = Vec::with_capacity(2);
v.extend_from_slice(&bytes[..]);
assert!(base64_to_bytes.insert(b64, v).is_none());
}
}
// every possible combination of symbols must either decode to 2 bytes or get InvalidLastSymbol, with or without any leading chunks
let mut prefix = Vec::new();
for _ in 0..256 {
let mut input = prefix.clone();
let mut symbols = [0_u8; 4];
for &s1 in STANDARD.symbols.iter() {
symbols[0] = s1;
for &s2 in STANDARD.symbols.iter() {
symbols[1] = s2;
for &s3 in STANDARD.symbols.iter() {
symbols[2] = s3;
symbols[3] = PAD_BYTE;
// chop off previous symbols
input.truncate(prefix.len());
input.extend_from_slice(&symbols[..]);
let decoded_prefix_len = prefix.len() / 4 * 3;
match base64_to_bytes.get(&symbols[..]) {
Some(bytes) => {
let res = engine
.decode(&input)
// remove prefix
.map(|decoded| decoded[decoded_prefix_len..].to_vec());
assert_eq!(Ok(bytes.clone()), res);
}
None => assert_eq!(
Err(DecodeError::InvalidLastSymbol(2, s3)),
engine.decode(&symbols[..])
),
}
}
}
}
prefix.extend_from_slice(b"AAAA");
}
}
#[apply(all_engines)]
fn decode_invalid_trailing_bits_ignored_when_configured<E: EngineWrapper>(engine_wrapper: E) {
let strict = E::standard();
let forgiving = E::standard_allow_trailing_bits();
fn assert_tolerant_decode<E: Engine>(
engine: &E,
input: &mut String,
b64_prefix_len: usize,
expected_decode_bytes: Vec<u8>,
data: &str,
) {
let prefixed = prefixed_data(input, b64_prefix_len, data);
let decoded = engine.decode(prefixed);
// prefix is always complete chunks
let decoded_prefix_len = b64_prefix_len / 4 * 3;
assert_eq!(
Ok(expected_decode_bytes),
decoded.map(|v| v[decoded_prefix_len..].to_vec())
);
}
let mut prefix = String::new();
for _ in 0..256 {
let mut input = prefix.clone();
// example from https://github.com/marshallpierce/rust-base64/issues/75
assert!(strict
.decode(prefixed_data(&mut input, prefix.len(), "/w=="))
.is_ok());
assert!(strict
.decode(prefixed_data(&mut input, prefix.len(), "iYU="))
.is_ok());
// trailing 01
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![255], "/x==");
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![137, 133], "iYV=");
// trailing 10
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![255], "/y==");
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![137, 133], "iYW=");
// trailing 11
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![255], "/z==");
assert_tolerant_decode(&forgiving, &mut input, prefix.len(), vec![137, 133], "iYX=");
prefix.push_str("AAAA");
}
}
#[apply(all_engines)]
fn decode_invalid_byte_error<E: EngineWrapper>(engine_wrapper: E) {
let mut rng = seeded_rng();
let mut orig_data = Vec::<u8>::new();
let mut encode_buf = Vec::<u8>::new();
let mut decode_buf = Vec::<u8>::new();
let len_range = distributions::Uniform::new(1, 1_000);
for _ in 0..10_000 {
let alphabet = random_alphabet(&mut rng);
let engine = E::random_alphabet(&mut rng, alphabet);
orig_data.clear();
encode_buf.clear();
decode_buf.clear();
let (orig_len, encoded_len_just_data, encoded_len_with_padding) =
generate_random_encoded_data(
&engine,
&mut orig_data,
&mut encode_buf,
&mut rng,
&len_range,
);
// exactly the right size
decode_buf.resize(orig_len, 0);
// replace one encoded byte with an invalid byte
let invalid_byte: u8 = loop {
let byte: u8 = rng.gen();
if alphabet.symbols.contains(&byte) {
continue;
} else {
break byte;
}
};
let invalid_range = distributions::Uniform::new(0, orig_len);
let invalid_index = invalid_range.sample(&mut rng);
encode_buf[invalid_index] = invalid_byte;
assert_eq!(
Err(DecodeError::InvalidByte(invalid_index, invalid_byte)),
engine.decode_slice_unchecked(
&encode_buf[0..encoded_len_with_padding],
&mut decode_buf[..],
)
);
}
}
/// Any amount of padding anywhere before the final non padding character = invalid byte at first
/// pad byte.
/// From this, we know padding must extend to the end of the input.
#[apply(all_engines)]
fn decode_padding_before_final_non_padding_char_error_invalid_byte<E: EngineWrapper>(
engine_wrapper: E,
) {
let mut rng = seeded_rng();
// the different amounts of proper padding, w/ offset from end for the last non-padding char
let suffixes = vec![("/w==", 2), ("iYu=", 1), ("zzzz", 0)];
let prefix_quads_range = distributions::Uniform::from(0..=256);
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for _ in 0..100_000 {
for (suffix, offset) in suffixes.iter() {
let mut s = "ABCD".repeat(prefix_quads_range.sample(&mut rng));
s.push_str(suffix);
let mut encoded = s.into_bytes();
// calculate a range to write padding into that leaves at least one non padding char
let last_non_padding_offset = encoded.len() - 1 - offset;
// don't include last non padding char as it must stay not padding
let padding_end = rng.gen_range(0..last_non_padding_offset);
// don't use more than 100 bytes of padding, but also use shorter lengths when
// padding_end is near the start of the encoded data to avoid biasing to padding
// the entire prefix on short lengths
let padding_len = rng.gen_range(1..=usize::min(100, padding_end + 1));
let padding_start = padding_end.saturating_sub(padding_len);
encoded[padding_start..=padding_end].fill(PAD_BYTE);
assert_eq!(
Err(DecodeError::InvalidByte(padding_start, PAD_BYTE)),
engine.decode(&encoded),
);
}
}
}
}
/// Any amount of padding before final chunk that crosses over into final chunk with 1-4 bytes =
/// invalid byte at first pad byte (except for 1 byte suffix = invalid length).
/// From this we know the padding must start in the final chunk.
#[apply(all_engines)]
fn decode_padding_starts_before_final_chunk_error_invalid_byte<E: EngineWrapper>(
engine_wrapper: E,
) {
let mut rng = seeded_rng();
// must have at least one prefix quad
let prefix_quads_range = distributions::Uniform::from(1..256);
// including 1 just to make sure that it really does produce invalid length
let suffix_pad_len_range = distributions::Uniform::from(1..=4);
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for _ in 0..100_000 {
let suffix_len = suffix_pad_len_range.sample(&mut rng);
let mut encoded = "ABCD"
.repeat(prefix_quads_range.sample(&mut rng))
.into_bytes();
encoded.resize(encoded.len() + suffix_len, PAD_BYTE);
// amount of padding must be long enough to extend back from suffix into previous
// quads
let padding_len = rng.gen_range(suffix_len + 1..encoded.len());
// no non-padding after padding in this test, so padding goes to the end
let padding_start = encoded.len() - padding_len;
encoded[padding_start..].fill(PAD_BYTE);
if suffix_len == 1 {
assert_eq!(Err(DecodeError::InvalidLength), engine.decode(&encoded),);
} else {
assert_eq!(
Err(DecodeError::InvalidByte(padding_start, PAD_BYTE)),
engine.decode(&encoded),
);
}
}
}
}
/// 0-1 bytes of data before any amount of padding in final chunk = invalid byte, since padding
/// is not valid data (consistent with error for pad bytes in earlier chunks).
/// From this we know there must be 2-3 bytes of data before padding
#[apply(all_engines)]
fn decode_too_little_data_before_padding_error_invalid_byte<E: EngineWrapper>(engine_wrapper: E) {
let mut rng = seeded_rng();
// want to test no prefix quad case, so start at 0
let prefix_quads_range = distributions::Uniform::from(0_usize..256);
let suffix_data_len_range = distributions::Uniform::from(0_usize..=1);
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for _ in 0..100_000 {
let suffix_data_len = suffix_data_len_range.sample(&mut rng);
let prefix_quad_len = prefix_quads_range.sample(&mut rng);
// ensure there is a suffix quad
let min_padding = usize::from(suffix_data_len == 0);
// for all possible padding lengths
for padding_len in min_padding..=(4 - suffix_data_len) {
let mut encoded = "ABCD".repeat(prefix_quad_len).into_bytes();
encoded.resize(encoded.len() + suffix_data_len, b'A');
encoded.resize(encoded.len() + padding_len, PAD_BYTE);
if suffix_data_len + padding_len == 1 {
assert_eq!(Err(DecodeError::InvalidLength), engine.decode(&encoded),);
} else {
assert_eq!(
Err(DecodeError::InvalidByte(
prefix_quad_len * 4 + suffix_data_len,
PAD_BYTE,
)),
engine.decode(&encoded),
"suffix data len {} pad len {}",
suffix_data_len,
padding_len
);
}
}
}
}
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 1
#[apply(all_engines)]
fn decode_malleability_test_case_3_byte_suffix_valid<E: EngineWrapper>(engine_wrapper: E) {
assert_eq!(
b"Hello".as_slice(),
&E::standard().decode("SGVsbG8=").unwrap()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 2
#[apply(all_engines)]
fn decode_malleability_test_case_3_byte_suffix_invalid_trailing_symbol<E: EngineWrapper>(
engine_wrapper: E,
) {
assert_eq!(
DecodeError::InvalidLastSymbol(6, 0x39),
E::standard().decode("SGVsbG9=").unwrap_err()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 3
#[apply(all_engines)]
fn decode_malleability_test_case_3_byte_suffix_no_padding<E: EngineWrapper>(engine_wrapper: E) {
assert_eq!(
DecodeError::InvalidPadding,
E::standard().decode("SGVsbG9").unwrap_err()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 4
#[apply(all_engines)]
fn decode_malleability_test_case_2_byte_suffix_valid_two_padding_symbols<E: EngineWrapper>(
engine_wrapper: E,
) {
assert_eq!(
b"Hell".as_slice(),
&E::standard().decode("SGVsbA==").unwrap()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 5
#[apply(all_engines)]
fn decode_malleability_test_case_2_byte_suffix_short_padding<E: EngineWrapper>(engine_wrapper: E) {
assert_eq!(
DecodeError::InvalidPadding,
E::standard().decode("SGVsbA=").unwrap_err()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 6
#[apply(all_engines)]
fn decode_malleability_test_case_2_byte_suffix_no_padding<E: EngineWrapper>(engine_wrapper: E) {
assert_eq!(
DecodeError::InvalidPadding,
E::standard().decode("SGVsbA").unwrap_err()
);
}
// https://eprint.iacr.org/2022/361.pdf table 2, test 7
#[apply(all_engines)]
fn decode_malleability_test_case_2_byte_suffix_too_much_padding<E: EngineWrapper>(
engine_wrapper: E,
) {
assert_eq!(
DecodeError::InvalidByte(6, PAD_BYTE),
E::standard().decode("SGVsbA====").unwrap_err()
);
}
/// Requires canonical padding -> accepts 2 + 2, 3 + 1, 4 + 0 final quad configurations
#[apply(all_engines)]
fn decode_pad_mode_requires_canonical_accepts_canonical<E: EngineWrapper>(engine_wrapper: E) {
assert_all_suffixes_ok(
E::standard_with_pad_mode(true, DecodePaddingMode::RequireCanonical),
vec!["/w==", "iYU=", "AAAA"],
);
}
/// Requires canonical padding -> rejects 2 + 0-1, 3 + 0 final chunk configurations
#[apply(all_engines)]
fn decode_pad_mode_requires_canonical_rejects_non_canonical<E: EngineWrapper>(engine_wrapper: E) {
let engine = E::standard_with_pad_mode(true, DecodePaddingMode::RequireCanonical);
let suffixes = vec!["/w", "/w=", "iYU"];
for num_prefix_quads in 0..256 {
for &suffix in suffixes.iter() {
let mut encoded = "AAAA".repeat(num_prefix_quads);
encoded.push_str(suffix);
let res = engine.decode(&encoded);
assert_eq!(Err(DecodeError::InvalidPadding), res);
}
}
}
/// Requires no padding -> accepts 2 + 0, 3 + 0, 4 + 0 final chunk configuration
#[apply(all_engines)]
fn decode_pad_mode_requires_no_padding_accepts_no_padding<E: EngineWrapper>(engine_wrapper: E) {
assert_all_suffixes_ok(
E::standard_with_pad_mode(true, DecodePaddingMode::RequireNone),
vec!["/w", "iYU", "AAAA"],
);
}
/// Requires no padding -> rejects 2 + 1-2, 3 + 1 final chunk configuration
#[apply(all_engines)]
fn decode_pad_mode_requires_no_padding_rejects_any_padding<E: EngineWrapper>(engine_wrapper: E) {
let engine = E::standard_with_pad_mode(true, DecodePaddingMode::RequireNone);
let suffixes = vec!["/w=", "/w==", "iYU="];
for num_prefix_quads in 0..256 {
for &suffix in suffixes.iter() {
let mut encoded = "AAAA".repeat(num_prefix_quads);
encoded.push_str(suffix);
let res = engine.decode(&encoded);
assert_eq!(Err(DecodeError::InvalidPadding), res);
}
}
}
/// Indifferent padding accepts 2 + 0-2, 3 + 0-1, 4 + 0 final chunk configuration
#[apply(all_engines)]
fn decode_pad_mode_indifferent_padding_accepts_anything<E: EngineWrapper>(engine_wrapper: E) {
assert_all_suffixes_ok(
E::standard_with_pad_mode(true, DecodePaddingMode::Indifferent),
vec!["/w", "/w=", "/w==", "iYU", "iYU=", "AAAA"],
);
}
//this is a MAY in the rfc: https://tools.ietf.org/html/rfc4648#section-3.3
#[apply(all_engines)]
fn decode_pad_byte_in_penultimate_quad_error<E: EngineWrapper>(engine_wrapper: E) {
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for num_prefix_quads in 0..256 {
// leave room for at least one pad byte in penultimate quad
for num_valid_bytes_penultimate_quad in 0..4 {
// can't have 1 or it would be invalid length
for num_pad_bytes_in_final_quad in 2..=4 {
let mut s: String = "ABCD".repeat(num_prefix_quads);
// varying amounts of padding in the penultimate quad
for _ in 0..num_valid_bytes_penultimate_quad {
s.push('A');
}
// finish penultimate quad with padding
for _ in num_valid_bytes_penultimate_quad..4 {
s.push('=');
}
// and more padding in the final quad
for _ in 0..num_pad_bytes_in_final_quad {
s.push('=');
}
// padding should be an invalid byte before the final quad.
// Could argue that the *next* padding byte (in the next quad) is technically the first
// erroneous one, but reporting that accurately is more complex and probably nobody cares
assert_eq!(
DecodeError::InvalidByte(
num_prefix_quads * 4 + num_valid_bytes_penultimate_quad,
b'=',
),
engine.decode(&s).unwrap_err()
);
}
}
}
}
}
#[apply(all_engines)]
fn decode_bytes_after_padding_in_final_quad_error<E: EngineWrapper>(engine_wrapper: E) {
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for num_prefix_quads in 0..256 {
// leave at least one byte in the quad for padding
for bytes_after_padding in 1..4 {
let mut s: String = "ABCD".repeat(num_prefix_quads);
// every invalid padding position with a 3-byte final quad: 1 to 3 bytes after padding
for _ in 0..(3 - bytes_after_padding) {
s.push('A');
}
s.push('=');
for _ in 0..bytes_after_padding {
s.push('A');
}
// First (and only) padding byte is invalid.
assert_eq!(
DecodeError::InvalidByte(
num_prefix_quads * 4 + (3 - bytes_after_padding),
b'='
),
engine.decode(&s).unwrap_err()
);
}
}
}
}
#[apply(all_engines)]
fn decode_absurd_pad_error<E: EngineWrapper>(engine_wrapper: E) {
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for num_prefix_quads in 0..256 {
let mut s: String = "ABCD".repeat(num_prefix_quads);
s.push_str("==Y=Wx===pY=2U=====");
// first padding byte
assert_eq!(
DecodeError::InvalidByte(num_prefix_quads * 4, b'='),
engine.decode(&s).unwrap_err()
);
}
}
}
#[apply(all_engines)]
fn decode_too_much_padding_returns_error<E: EngineWrapper>(engine_wrapper: E) {
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for num_prefix_quads in 0..256 {
// add enough padding to ensure that we'll hit all decode stages at the different lengths
for pad_bytes in 1..=64 {
let mut s: String = "ABCD".repeat(num_prefix_quads);
let padding: String = "=".repeat(pad_bytes);
s.push_str(&padding);
if pad_bytes % 4 == 1 {
assert_eq!(DecodeError::InvalidLength, engine.decode(&s).unwrap_err());
} else {
assert_eq!(
DecodeError::InvalidByte(num_prefix_quads * 4, b'='),
engine.decode(&s).unwrap_err()
);
}
}
}
}
}
#[apply(all_engines)]
fn decode_padding_followed_by_non_padding_returns_error<E: EngineWrapper>(engine_wrapper: E) {
for mode in all_pad_modes() {
// we don't encode so we don't care about encode padding
let engine = E::standard_with_pad_mode(true, mode);
for num_prefix_quads in 0..256 {
for pad_bytes in 0..=32 {
let mut s: String = "ABCD".repeat(num_prefix_quads);
let padding: String = "=".repeat(pad_bytes);
s.push_str(&padding);
s.push('E');
if pad_bytes % 4 == 0 {