summaryrefslogtreecommitdiff
path: root/lib/stdlib/test/property_test/base64_prop.erl
blob: f4d7f264f10b82aa418a6e47707b74a4830d7378 (plain)
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
%%
%% %CopyrightBegin%
%%
%% Copyright Ericsson AB 2021-2023. All Rights Reserved.
%%
%% Licensed under the Apache License, Version 2.0 (the "License");
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%%     http://www.apache.org/licenses/LICENSE-2.0
%%
%% Unless required by applicable law or agreed to in writing, software
%% distributed under the License is distributed on an "AS IS" BASIS,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(base64_prop).

-compile([export_all, nowarn_export_all]).

-proptest(eqc).
-proptest([triq, proper]).

-ifndef(EQC).
-ifndef(PROPER).
-ifndef(TRIQ).
-define(EQC, true).
-endif.
-endif.
-endif.

-ifdef(EQC).
-include_lib("eqc/include/eqc.hrl").
-define(MOD_eqc,eqc).

-else.
-ifdef(PROPER).
-include_lib("proper/include/proper.hrl").
-define(MOD_eqc,proper).

-else.
-ifdef(TRIQ).
-define(MOD_eqc,triq).
-include_lib("triq/include/triq.hrl").

-endif.
-endif.
-endif.

%%%%%%%%%%%%%%%%%%
%%% Properties %%%
%%%%%%%%%%%%%%%%%%

prop_encode_1() ->
    ?FORALL(
        Str,
        oneof([list(byte()), binary()]),
        begin
            Enc = base64:encode(Str),
            Dec = base64:decode(Enc),
            is_b64_binary(standard, Enc) andalso str_equals(Str, Dec)
        end
    ).

prop_encode_2() ->
    ?FORALL(
        {Str, Mode},
        {oneof([list(byte()), binary()]), mode()},
        begin
            Enc = base64:encode(Str, #{mode => Mode}),
            Dec = base64:decode(Enc, #{mode => Mode}),
            is_b64_binary(Mode, Enc) andalso str_equals(Str, Dec)
        end
    ).

prop_encode_to_string_1() ->
    ?FORALL(
        Str,
        oneof([list(byte()), binary()]),
        begin
            Enc = base64:encode_to_string(Str),
            Dec = base64:decode_to_string(Enc),
            is_b64_string(standard, Enc) andalso str_equals(Str, Dec)
        end
    ).

prop_encode_to_string_2() ->
    ?FORALL(
        {Str, Mode},
        {oneof([list(byte()), binary()]), mode()},
        begin
            Enc = base64:encode_to_string(Str, #{mode => Mode}),
            Dec = base64:decode_to_string(Enc, #{mode => Mode}),
            is_b64_string(Mode, Enc) andalso str_equals(Str, Dec)
        end
    ).

prop_decode_1() ->
    ?FORALL(
        {NormalizedB64, WspedB64},
        wsped_b64(standard),
        begin
            Dec = base64:decode(WspedB64),
            Enc = base64:encode(Dec),
            is_binary(Dec) andalso b64_equals(standard, NormalizedB64, Enc)
        end
    ).

prop_decode_2() ->
    ?FORALL(
        {{NormalizedB64, WspedB64}, Mode},
        ?LET(
            Mode,
            mode(),
            {wsped_b64(Mode), Mode}
        ),
        begin
            Dec = base64:decode(WspedB64, #{mode => Mode}),
            Enc = base64:encode(Dec, #{mode => Mode}),
            is_binary(Dec) andalso b64_equals(Mode, NormalizedB64, Enc)
        end
    ).

prop_decode_1_malformed() ->
    common_decode_malformed(fun wsped_b64/1, standard, fun(Data, _) -> base64:decode(Data) end).

prop_decode_2_malformed() ->
    common_decode_malformed(fun wsped_b64/1, mode(), fun base64:decode/2).

prop_decode_1_noisy() ->
    common_decode_noisy(standard, fun(Data, _) -> base64:decode(Data) end).

prop_decode_2_noisy() ->
    common_decode_noisy(mode(), fun base64:decode/2).

prop_decode_to_string_1() ->
    ?FORALL(
        {NormalizedB64, WspedB64},
        wsped_b64(standard),
        begin
            Dec = base64:decode_to_string(WspedB64),
            Enc = base64:encode(Dec),
            is_bytelist(Dec) andalso b64_equals(standard, NormalizedB64, Enc)
        end
    ).

prop_decode_to_string_2() ->
    ?FORALL(
        {{NormalizedB64, WspedB64}, Mode},
        ?LET(
            Mode,
            mode(),
            {wsped_b64(Mode), Mode}
        ),
        begin
            Dec = base64:decode_to_string(WspedB64, #{mode => Mode}),
            Enc = base64:encode(Dec, #{mode => Mode}),
            is_bytelist(Dec) andalso b64_equals(Mode, NormalizedB64, Enc)
        end
    ).

prop_decode_to_string_1_malformed() ->
    common_decode_malformed(fun wsped_b64/1, standard, fun(Data, _) -> base64:decode_to_string(Data) end).

prop_decode_to_string_2_malformed() ->
    common_decode_malformed(fun wsped_b64/1, mode(), fun base64:decode_to_string/2).

prop_decode_to_string_1_noisy() ->
    common_decode_noisy(standard, fun(Data, _) -> base64:decode_to_string(Data) end).

prop_decode_to_string_2_noisy() ->
    common_decode_noisy(mode(), fun base64:decode_to_string/2).

prop_mime_decode_1() ->
    ?FORALL(
        {NormalizedB64, NoisyB64},
        noisy_b64(standard),
        begin
            Dec = base64:mime_decode(NoisyB64),
            Enc = base64:encode(Dec),
            is_binary(Dec) andalso b64_equals(standard, NormalizedB64, Enc)
        end
    ).

prop_mime_decode_2() ->
    ?FORALL(
        {{NormalizedB64, NoisyB64}, Mode},
        ?LET(
            Mode,
            mode(),
            {wsped_b64(Mode), Mode}
        ),
        begin
            Dec = base64:mime_decode(NoisyB64, #{mode => Mode}),
            Enc = base64:encode(Dec, #{mode => Mode}),
            is_binary(Dec) andalso b64_equals(Mode, NormalizedB64, Enc)
        end
    ).

prop_mime_decode_1_malformed() ->
    common_decode_malformed(fun noisy_b64/1, standard, fun(Data, _) -> base64:mime_decode(Data) end).

prop_mime_decode_2_malformed() ->
    common_decode_malformed(fun noisy_b64/1, mode(), fun base64:mime_decode/2).

prop_mime_decode_to_string_1() ->
    ?FORALL(
        {NormalizedB64, NoisyB64},
        noisy_b64(standard),
        begin
            Dec = base64:mime_decode_to_string(NoisyB64),
            Enc = base64:encode(Dec),
            is_bytelist(Dec) andalso b64_equals(standard, NormalizedB64, Enc)
        end
    ).

prop_mime_decode_to_string_2() ->
    ?FORALL(
        {{NormalizedB64, NoisyB64}, Mode},
        ?LET(
            Mode,
            mode(),
            {wsped_b64(Mode), Mode}
        ),
        begin
            Dec = base64:mime_decode_to_string(NoisyB64, #{mode => Mode}),
            Enc = base64:encode(Dec, #{mode => Mode}),
            is_bytelist(Dec) andalso b64_equals(Mode, NormalizedB64, Enc)
        end
    ).

prop_mime_decode_to_string_1_malformed() ->
    common_decode_malformed(fun noisy_b64/1, standard, fun(Data, _) -> base64:mime_decode_to_string(Data) end).

prop_mime_decode_to_string_2_malformed() ->
    common_decode_malformed(fun noisy_b64/1, mode(), fun base64:mime_decode_to_string/2).

common_decode_noisy(ModeGen, Fn) ->
    ?FORALL(
        {{_, NoisyB64}, Mode},
        ?LET(
            Mode,
            ModeGen,
            {?SUCHTHAT({NormalizedB64, NoisyB64}, noisy_b64(Mode), NormalizedB64 =/= NoisyB64), Mode}
        ),
        try
            Fn(NoisyB64, #{mode => Mode})
        of
            _ ->
                false
        catch
            error:_ ->
                true
        end
    ).

common_decode_malformed(DataGen, ModeGen, Fn) ->
    ?FORALL(
        {MalformedB64, Mode},
        ?LET(
            Mode,
            ModeGen,
            ?LET(
                {{NormalizedB64, NoisyB64}, Malformings, InsertFn},
                {
                    DataGen(Mode),
                    oneof(
                        [
                            [b64_char(Mode)],
                            [b64_char(Mode), b64_char(Mode)],
                            [b64_char(Mode), b64_char(Mode), b64_char(Mode)]
                        ]
                    ),
                    function1(boolean())
                },
                {{NormalizedB64, insert_noise(NoisyB64, Malformings, InsertFn)}, Mode}
            )
        ),
        try
            Fn(MalformedB64, #{mode => Mode})
        of
            _ ->
                false
        catch
            error:_ ->
                true
        end
    ).

%%%%%%%%%%%%%%%%%%
%%% Generators %%%
%%%%%%%%%%%%%%%%%%

%% Generate base64 encoding mode.
mode() ->
    oneof([standard, urlsafe]).

%% Generate a single character from the base64 alphabet.
b64_char(Mode) ->
    oneof(b64_chars(Mode)).

%% Generate a string of characters from the base64 alphabet,
%% including padding if needed.
b64_string(Mode) ->
    ?LET(
        {L, Filler},
        {list(b64_char(Mode)), b64_char(Mode)},
        case length(L) rem 4 of
            0 -> L;
            1 -> L ++ [Filler, $=, $=];
            2 -> L ++ [$=, $=];
            3 -> L ++ [$=]
        end
    ).

%% Generate a binary of characters from the base64 alphabet,
%% including padding if needed.
b64_binary(Mode) ->
    ?LET(
        L,
        b64_string(Mode),
        list_to_binary(L)
    ).

%% Generate a string or binary of characters from the
%% base64 alphabet, including padding if needed.
b64(Mode) ->
    oneof([b64_string(Mode), b64_binary(Mode)]).

%% Generate a string or binary of characters from the
%% base64 alphabet, including padding if needed, with
%% whitespaces inserted at random indexes.
wsped_b64(Mode) ->
    ?LET(
        {B64, Wsps, InsertFn},
        {b64(Mode), list(oneof([$\t, $\r, $\n, $\s])), function1(boolean())},
        {B64, insert_noise(B64, Wsps, InsertFn)}
    ).

%% Generate a single character outside of the base64 alphabet.
%% As whitespaces are allowed but ignored in base64, this generator
%% will produce no whitespaces, either.
non_b64_char(Mode) ->
    oneof(lists:seq(16#00, 16#FF) -- b64_allowed_chars(Mode)).

%% Generate a string or binary of characters from the
%% base64 alphabet, including padding if needed, with
%% whitespaces and non-base64 ("invalid") characters
%% inserted at random indexes.
noisy_b64(Mode) ->
    ?LET(
        {{B64, WspedB64}, Noise, InsertFn},
        {wsped_b64(Mode), non_empty(list(non_b64_char(Mode))), function1(boolean())},
        {B64, insert_noise(WspedB64, Noise, InsertFn)}
    ).

%%%%%%%%%%%%%%%
%%% Helpers %%%
%%%%%%%%%%%%%%%

%% The characters of the base64 alphabet.
%% "=" is not included, as it is special in that it
%% may only appear at the end of a base64 encoded string
%% for padding.
b64_chars_common() ->
    lists:seq($0, $9) ++
    lists:seq($a, $z) ++
    lists:seq($A, $Z).

b64_chars(standard) ->
    b64_chars_common() ++ [$+, $/];
b64_chars(urlsafe) ->
    b64_chars_common() ++ [$-, $_].

%% In addition to the above, the whitespace characters
%% HTAB, CR, LF and SP are allowed to appear in a base64
%% encoded string and should be ignored.
b64_allowed_chars(Mode) ->
    [$\t, $\r, $\n, $\s | b64_chars(Mode)].

%% Insert the given list of noise characters at random
%% places into the given base64 string.
insert_noise(B64, Noise, InsertFn) ->
    insert_noise(B64, Noise, InsertFn, 0).

insert_noise(B64, [], _, _) ->
    B64;
insert_noise([], Noise, _, _) ->
    Noise;
insert_noise(<<>>, Noise, _, _) ->
    list_to_binary(Noise);
insert_noise([B|Bs] = B64, [N|Ns] = Noise, InsertFn, Idx) ->
    case InsertFn(Idx) of
        true ->
            [B|insert_noise(Bs, Noise, InsertFn, Idx + 1)];
        false ->
            [N|insert_noise(B64, Ns, InsertFn, Idx + 1)]
    end;
insert_noise(<<B, Bs/binary>> = B64, [N|Ns] = Noise, InsertFn, Idx) ->
    case InsertFn(Idx) of
        true ->
            <<B, (insert_noise(Bs, Noise, InsertFn, Idx + 1))/binary>>;
        false ->
            <<N, (insert_noise(B64, Ns, InsertFn, Idx + 1))/binary>>
    end.

%% Check if the given character is in the base64 alphabet.
%% This does not include the padding character "=".
is_b64_char(standard, $+) ->
    true;
is_b64_char(standard, $/) ->
    true;
is_b64_char(urlsafe, $-) ->
    true;
is_b64_char(urlsafe, $_) ->
    true;
is_b64_char(_, C) when C >= $0, C =< $9 ->
    true;
is_b64_char(_, C) when C >= $A, C =< $Z ->
    true;
is_b64_char(_, C) when C >= $a, C =< $z ->
    true;
is_b64_char(_, _) ->
    false.

%% Check if the given argument is a base64 binary,
%% ie that it consists of quadruplets of characters
%% from the base64 alphabet, whereas the last quadruplet
%% may be padded with one or two "="s
is_b64_binary(Mode, B) ->
    is_b64_binary(Mode, B, 0).

is_b64_binary(_, <<>>, N) ->
    N rem 4 =:= 0;
is_b64_binary(_, <<$=>>, N) ->
    N rem 4 =:= 3;
is_b64_binary(_, <<$=, $=>>, N) ->
    N rem 4 =:= 2;
is_b64_binary(Mode, <<C, More/binary>>, N) ->
    case is_b64_char(Mode, C) of
        true ->
            is_b64_binary(Mode, More, N + 1);
        false ->
            false
    end.

%% Check if the given argument is a base64 string
%% (see is_b64_binary/1)
is_b64_string(Mode, S) ->
    is_b64_binary(Mode, list_to_binary(S)).

%% Check if the argument is a list of bytes.
is_bytelist(L) ->
    lists:all(
        fun (B) ->
            is_integer(B) andalso B >= 16#00 andalso B =< 16#FF
        end,
        L
    ).

%% Check two byte-lists or binaries for equality.
str_equals(Str1, Str2) when is_list(Str1) ->
    str_equals(list_to_binary(Str1), Str2);
str_equals(Str1, Str2) when is_list(Str2) ->
    str_equals(Str1, list_to_binary(Str2));
str_equals(Str1, Str2) when is_binary(Str1), is_binary(Str2) ->
    Str1 =:= Str2.

%% Check two base64-encoded byte-lists or binaries for equality.
%% Assumes that the given arguments are in a normalized form,
%% ie that they consist only of characters from the base64
%% alphabet and possible padding ("=").
b64_equals(Mode, L, B) when is_list(L) ->
    b64_equals(Mode, list_to_binary(L), B);
b64_equals(Mode, B, L) when is_list(L) ->
    b64_equals(Mode, B, list_to_binary(L));
b64_equals(Mode, B1, B2) when is_binary(B1), is_binary(B2) ->
    b64_equals1(Mode, B1, B2).

b64_equals1(Mode, <<Eq:4/bytes>>, <<Eq:4/bytes>>) ->
    is_b64_binary(Mode, Eq);
b64_equals1(Mode, <<Eq:4/bytes, More1/binary>>, <<Eq:4/bytes, More2/binary>>) ->
    case lists:all(fun(C) -> is_b64_char(Mode, C) end, binary_to_list(Eq)) of
        true ->
            b64_equals1(Mode, More1, More2);
        false ->
            false
    end;
b64_equals1(Mode, <<Eq, B1, $=, $=>>, <<Eq, B2, $=, $=>>) ->
    %% If the encoded string ends with "==", there exist multiple
    %% possibilities for the character preceding the "==" as only the
    %% 3rd and 4th bits of the encoded byte represented by that
    %% character are significant.
    %%
    %% For example, all of the encoded strings "QQ==", "QR==", ..., "QZ=="
    %% decode to the string "A", since all the bytes represented by Q to Z
    %% are the same in the significant 3rd and 4th bit.
    case is_b64_char(Mode, Eq) of
        true ->
            Normalize = fun
                (C) when C >= $A, C =< $P -> $A;
                (C) when C >= $Q, C =< $Z -> $Q;
                (C) when C >= $a, C =< $f -> $Q;
                (C) when C >= $g, C =< $v -> $g;
                (C) when C >= $w, C =< $z -> $w;
                (C) when C >= $0, C =< $9 -> $w;
                ($+) when Mode =:= standard -> $w;
                ($-) when Mode =:= urlsafe -> $w;
                ($/) when Mode =:= standard -> $w;
                ($_) when Mode =:= urlsafe -> $w
            end,
            Normalize(B1) =:= Normalize(B2);
        false ->
            false
    end;
b64_equals1(Mode, <<Eq1, Eq2, B1, $=>>, <<Eq1, Eq2, B2, $=>>) ->
    %% Similar to the above, but with the encoded string ending with a
    %% single "=" the 3rd to 6th bits of the encoded byte are significant,
    %% such that, for example, all the encoded strings "QUE=" to "QUH="
    %% decode to the same string "AA".
    case is_b64_char(Mode, Eq1) andalso is_b64_char(Mode, Eq2) of
        true ->
            Normalize = fun
                (C) when C >= $A, C =< $D -> $A;
                (C) when C >= $E, C =< $H -> $E;
                (C) when C >= $I, C =< $L -> $I;
                (C) when C >= $M, C =< $P -> $M;
                (C) when C >= $Q, C =< $T -> $Q;
                (C) when C >= $U, C =< $X -> $U;
                (C) when C >= $Y, C =< $Z -> $Y;
                (C) when C >= $a, C =< $b -> $Y;
                (C) when C >= $c, C =< $f -> $c;
                (C) when C >= $g, C =< $j -> $g;
                (C) when C >= $k, C =< $n -> $k;
                (C) when C >= $o, C =< $r -> $o;
                (C) when C >= $s, C =< $v -> $s;
                (C) when C >= $w, C =< $z -> $w;
                (C) when C >= $0, C =< $3 -> $0;
                (C) when C >= $4, C =< $7 -> $4;
                (C) when C >= $8, C =< $9 -> $8;
                ($+) when Mode =:= standard -> $8;
                ($-) when Mode =:= urlsafe -> $8;
                ($/) when Mode =:= standard -> $8;
                ($_) when Mode =:= urlsafe -> $8
            end,
            Normalize(B1) =:= Normalize(B2);
        false ->
            false
    end;
b64_equals1(_, <<>>, <<>>) ->
    true;
b64_equals1(_, _, _) ->
    false.