summaryrefslogtreecommitdiff
path: root/jose/apr_jose_decode.c
blob: 24017c82472f0ec504448b8143b2c880b0736918 (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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
/* Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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
 * levelations under the License.
 */

#include "apr_jose.h"
#include "apr_lib.h"
#include "apr_encode.h"

static
apr_status_t apr_jose_flatten(apr_bucket_brigade *bb, apr_jose_text_t *in,
        apr_pool_t *pool)
{
    apr_bucket *e;

    /* most common case - one pool bucket, avoid unnecessary duplication */
    e = APR_BRIGADE_FIRST(bb);
    if (e != APR_BRIGADE_SENTINEL(bb)) {
        if (!APR_BUCKET_NEXT(e) && APR_BUCKET_IS_POOL(e)) {
            apr_bucket_pool *p = e->data;
            if (pool == p->pool) {
                return apr_bucket_read(e, &in->text, &in->len, APR_BLOCK_READ);
            }
        }
    }

    return apr_brigade_pflatten(bb, (char **)&in->text, &in->len, pool);
}

static
apr_status_t apr_jose_decode_jwk(apr_jose_t **jose,
        const char *typ, apr_bucket_brigade *bb, apr_jose_cb_t *cb,
        int level, int flags, apr_pool_t *pool)
{
    apr_json_value_t *key;
    apr_jose_text_t in;
    apr_off_t offset;
    apr_status_t status;

    status = apr_jose_flatten(bb, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_json_decode(&key, in.text, in.len, &offset,
            APR_JSON_FLAGS_WHITESPACE, level, pool);

    *jose = apr_jose_jwk_make(NULL, key, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    if (APR_SUCCESS != status) {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWK decoding failed at offset %" APR_OFF_T_FMT ": %s",
                                        offset, buf);

        return status;
    }

    return APR_SUCCESS;
}

static
apr_status_t apr_jose_decode_jwks(apr_jose_t **jose,
        const char *typ, apr_bucket_brigade *bb, apr_jose_cb_t *cb,
        int level, int flags, apr_pool_t *pool)
{
    apr_json_value_t *keys;
    apr_jose_text_t in;
    apr_off_t offset;
    apr_status_t status;

    status = apr_jose_flatten(bb, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_json_decode(&keys, in.text, in.len,
            &offset, APR_JSON_FLAGS_WHITESPACE, level, pool);

    *jose = apr_jose_jwks_make(NULL, keys, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    if (APR_SUCCESS != status) {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWKS decoding failed at offset %" APR_OFF_T_FMT ": %s",
                offset, buf);

        return status;
    }

    if (keys->type != APR_JSON_ARRAY) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWKS 'keys' is not an array");
        return APR_EINVAL;
    }

    return APR_SUCCESS;
}

static
apr_status_t apr_jose_decode_jwt(apr_jose_t **jose,
        const char *typ, apr_bucket_brigade *bb, apr_jose_cb_t *cb,
        int level, int flags, apr_pool_t *pool)
{
    apr_json_value_t *claims;
    apr_jose_text_t in;
    apr_off_t offset;
    apr_status_t status;

    status = apr_jose_flatten(bb, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_json_decode(&claims, in.text, in.len, &offset,
            APR_JSON_FLAGS_WHITESPACE, level, pool);

    *jose = apr_jose_jwt_make(NULL, claims, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    if (APR_SUCCESS != status) {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWT decoding failed at offset %" APR_OFF_T_FMT ": %s",
                offset, buf);

        return status;
    }

    return APR_SUCCESS;
}

static
apr_status_t apr_jose_decode_data(apr_jose_t **jose, const char *typ,
        apr_bucket_brigade *brigade, apr_jose_cb_t *cb, int level, int flags,
        apr_pool_t *pool)
{
    apr_jose_text_t in;
    apr_status_t status;

    status = apr_jose_flatten(brigade, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    *jose = apr_jose_data_make(NULL, typ, (const unsigned char *) in.text,
            in.len, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    return status;
}

static
apr_status_t apr_jose_decode_jws_signature(apr_jose_t **jose,
        apr_jose_signature_t *signature, const char *typ, const char *cty,
        apr_jose_text_t *ph64, apr_jose_text_t *sig64, apr_jose_text_t *pl64,
        apr_json_value_t *uh, apr_jose_cb_t *cb, int level, int *flags,
        apr_pool_t *pool, apr_bucket_brigade *bb)
{
    const char *phs;
    apr_size_t phlen;
    apr_off_t offset;
    apr_status_t status = APR_SUCCESS;

    /*
     * Base64url-decode the encoded representation of the JWS Protected
     * Header, following the restriction that no line breaks,
     * whitespace, or other additional characters have been used.
     */

    phs = apr_pdecode_base64(pool, ph64->text, ph64->len, APR_ENCODE_BASE64URL,
            &phlen);

    if (!phs) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'protected' is not valid base64url");
        return APR_EINVAL;
    }

    /*
     * Verify that the resulting octet sequence is a UTF-8-encoded
     * representation of a completely valid JSON object conforming to
     * RFC 7159 [RFC7159]; let the JWS Protected Header be this JSON
     * object.
     */

    status = apr_json_decode(&signature->protected_header, phs, phlen, &offset,
    APR_JSON_FLAGS_WHITESPACE, level, pool);
    if (APR_SUCCESS != status) {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'protected' decoding failed at %" APR_OFF_T_FMT ": %s",
                offset, buf);

        return status;
    }

    /*
     * If using the JWS Compact Serialization, let the JOSE Header be
     * the JWS Protected Header.  Otherwise, when using the JWS JSON
     * Serialization, let the JOSE Header be the union of the members of
     * the corresponding JWS Protected Header and JWS Unprotected
     * Header, all of which must be completely valid JSON objects.
     * During this step, verify that the resulting JOSE Header does not
     * contain duplicate Header Parameter names.  When using the JWS
     * JSON Serialization, this restriction includes that the same
     * Header Parameter name also MUST NOT occur in distinct JSON object
     * values that together comprise the JOSE Header.
     */

    if (uh) {
        signature->header = apr_json_overlay(pool, signature->protected_header,
                uh, APR_JSON_FLAGS_STRICT);
    } else {
        signature->header = signature->protected_header;
    }

    /*
     * Verify that the implementation understands and can process all
     * fields that it is required to support, whether required by this
     * specification, by the algorithm being used, or by the "crit"
     * Header Parameter value, and that the values of those parameters
     * are also understood and supported.
     */

    /*
     * Base64url-decode the encoded representation of the JWS Signature,
     * following the restriction that no line breaks, whitespace, or
     * other additional characters have been used.
     */

    signature->sig.data = apr_pdecode_base64_binary(pool, sig64->text,
            sig64->len,
            APR_ENCODE_BASE64URL, &signature->sig.len);
    if (!signature->sig.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS signature decoding failed: bad character");
        return APR_BADCH;
    }

    /*
     * The verify function is expected to perform some or all of the
     * following steps:
     *
     * FIXME fill in from RFC
     */

    status = cb->verify(bb, *jose, signature, cb->ctx, flags, pool);

    return status;
}

static
apr_status_t apr_jose_decode_jwe_recipient(apr_jose_t **jose,
        apr_bucket_brigade *bb, apr_jose_recipient_t *recipient,
        apr_jose_encryption_t *encryption, const char *typ, const char *cty,
        apr_jose_text_t *ph64, apr_jose_text_t *aad64, apr_jose_cb_t *cb,
        int level, int *dflags, apr_pool_t *pool)
{
    apr_json_value_t *header;
    apr_status_t status;

    /*
     * If using the JWE Compact Serialization, let the JOSE Header be
     * the JWE Protected Header.  Otherwise, when using the JWE JSON
     * Serialization, let the JOSE Header be the union of the members
     * of the JWE Protected Header, the JWE Shared Unprotected Header
     * and the corresponding JWE Per-Recipient Unprotected Header, all
     * of which must be completely valid JSON objects.  During this
     * step, verify that the resulting JOSE Header does not contain
     * duplicate Header Parameter names.  When using the JWE JSON
     * Serialization, this restriction includes that the same Header
     * Parameter name also MUST NOT occur in distinct JSON object
     * values that together comprise the JOSE Header.
     */

    header = apr_json_overlay(pool, recipient->header,
            apr_json_overlay(pool, encryption->protected,
                    encryption->unprotected, APR_JSON_FLAGS_STRICT),
            APR_JSON_FLAGS_STRICT);

    if (!header) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "JWE decryption failed: protected, unprotected and per "
                "recipient headers had an overlapping element, or were all missing");
        return APR_EINVAL;
    }

    /*
     * Verify that the implementation understands and can process all
     * fields that it is required to support, whether required by this
     * specification, by the algorithms being used, or by the "crit"
     * Header Parameter value, and that the values of those parameters
     * are also understood and supported.
     */

    /*
     * The decrypt function is expected to perform some or all of the
     * following steps:
     *
     * 6.   Determine the Key Management Mode employed by the algorithm
     * specified by the "alg" (algorithm) Header Parameter.
     *
     * 7.   Verify that the JWE uses a key known to the recipient.
     *
     * 8.   When Direct Key Agreement or Key Agreement with Key Wrapping are
     *      employed, use the key agreement algorithm to compute the value
     *      of the agreed upon key.  When Direct Key Agreement is employed,
     *      let the CEK be the agreed upon key.  When Key Agreement with Key
     *      Wrapping is employed, the agreed upon key will be used to
     *      decrypt the JWE Encrypted Key.
     *
     * 9.   When Key Wrapping, Key Encryption, or Key Agreement with Key
     *      Wrapping are employed, decrypt the JWE Encrypted Key to produce
     *      the CEK.  The CEK MUST have a length equal to that required for
     *      the content encryption algorithm.  Note that when there are
     *       multiple recipients, each recipient will only be able to decrypt
     *       JWE Encrypted Key values that were encrypted to a key in that
     *       recipient's possession.  It is therefore normal to only be able
     *       to decrypt one of the per-recipient JWE Encrypted Key values to
     *       obtain the CEK value.  Also, see Section 11.5 for security
     *       considerations on mitigating timing attacks.
     *
     *  10.  When Direct Key Agreement or Direct Encryption are employed,
     *       verify that the JWE Encrypted Key value is an empty octet
     *       sequence.
     *
     *  11.  When Direct Encryption is employed, let the CEK be the shared
     *       symmetric key.
     *
     *  12.  Record whether the CEK could be successfully determined for this
     *       recipient or not.
     *
     *  13.  If the JWE JSON Serialization is being used, repeat this process
     *       (steps 4-12) for each recipient contained in the representation.
     *
     *  14.  Compute the Encoded Protected Header value BASE64URL(UTF8(JWE
     *       Protected Header)).  If the JWE Protected Header is not present
     *       (which can only happen when using the JWE JSON Serialization and
     *       no "protected" member is present), let this value be the empty
     *       string.
     *
     *  15.  Let the Additional Authenticated Data encryption parameter be
     *       ASCII(Encoded Protected Header).  However, if a JWE AAD value is
     *       present (which can only be the case when using the JWE JSON
     *       Serialization), instead let the Additional Authenticated Data
     *       encryption parameter be ASCII(Encoded Protected Header || '.' ||
     *       BASE64URL(JWE AAD)).
     *
     *  16.  Decrypt the JWE Ciphertext using the CEK, the JWE Initialization
     *       Vector, the Additional Authenticated Data value, and the JWE
     *       Authentication Tag (which is the Authentication Tag input to the
     *       calculation) using the specified content encryption algorithm,
     *       returning the decrypted plaintext and validating the JWE
     *       Authentication Tag in the manner specified for the algorithm,
     *       rejecting the input without emitting any decrypted output if the
     *       JWE Authentication Tag is incorrect.
     *
     *  17.  If a "zip" parameter was included, uncompress the decrypted
     *       plaintext using the specified compression algorithm.
     */

    status = cb->decrypt(bb, *jose, recipient, encryption, header, ph64, aad64,
            cb->ctx, dflags, pool);

    recipient->status = status;

    return status;
}

static
apr_status_t apr_jose_decode_compact_jws(apr_jose_t **jose,
        const char *left, const char *right,
        apr_json_value_t *ph, const char *typ, const char *cty,
        apr_jose_text_t *in, apr_jose_text_t *ph64, apr_jose_cb_t *cb,
        int level, int flags, apr_pool_t *pool, apr_bucket_brigade *bb)
{
    apr_jose_jws_t *jws;
    apr_jose_text_t sig64;
    apr_jose_text_t pl64;
    apr_jose_text_t pls;
    const char *dot;
    apr_bucket *e;
    apr_status_t status = APR_EINVAL;
    int vflags = APR_JOSE_FLAG_NONE;

    if (!cb || !cb->verify) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Verification failed: no verify callback provided");
        return APR_EINIT;
    }

    *jose = apr_jose_jws_make(*jose, NULL, NULL, NULL, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }
    jws = (*jose)->jose.jws;

    /*
     * If using the JWS Compact Serialization, let the JOSE Header be
     * the JWS Protected Header.
     */

    jws->signature = apr_jose_signature_make(NULL, NULL, ph, pool);
    if (!jws->signature) {
        return APR_ENOMEM;
    }

    dot = memchr(left, '.', right - left);
    if (!dot) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS compact decoding failed: one lonely dot");
        return APR_BADCH;
    }

    pl64.text = left;
    pl64.len = dot - left;

    left = dot + 1;

    sig64.text = left;
    sig64.len = right - left;

    /*
     * Validate the JWS Signature against the JWS Signing Input
     * ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' ||
     * BASE64URL(JWS Payload)) in the manner defined for the algorithm
     * being used, which MUST be accurately represented by the value of
     * the "alg" (algorithm) Header Parameter, which MUST be present.
     * See Section 10.6 for security considerations on algorithm
     * validation.  Record whether the validation succeeded or not.
     */

    status = apr_brigade_write(bb, NULL, NULL, in->text,
            sig64.text - in->text - 1);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_jose_decode_jws_signature(jose, jws->signature,
            typ, cty, ph64, &sig64, &pl64, NULL, cb, level, &vflags, pool, bb);

    if (APR_SUCCESS != status) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "JWS verification failed: signature rejected");
        return status;
    }

    /*
     * Base64url-decode the encoded representation of the JWS Payload,
     * following the restriction that no line breaks, whitespace, or
     * other additional characters have been used.
     */

    pls.text = apr_pdecode_base64(pool, pl64.text,
            pl64.len, APR_ENCODE_BASE64URL, &pls.len);
    if (!pls.text) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'payload' is not valid base64url");
        return APR_BADCH;
    }


    apr_brigade_cleanup(bb);
    e = apr_bucket_pool_create(pls.text, pls.len, pool,
            bb->bucket_alloc);
    APR_BRIGADE_INSERT_TAIL(bb, e);

    return APR_SUCCESS;
}

static
apr_status_t apr_jose_decode_compact_jwe(apr_jose_t **jose, const char *left,
        const char *right, apr_json_value_t *ph, apr_json_value_t *enc,
        const char *typ, const char *cty, apr_jose_text_t *ph64,
        apr_jose_cb_t *cb, int level, int flags, apr_pool_t *pool,
        apr_bucket_brigade *bb)
{
    const char *dot;
    apr_jose_jwe_t *jwe;
    apr_jose_text_t aad64;
    apr_status_t status;
    int dflags = APR_JOSE_FLAG_NONE;

    if (!cb || !cb->decrypt) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Decryption failed: no decrypt callback provided");
        return APR_EINIT;
    }

    *jose = apr_jose_jwe_make(*jose, NULL, NULL, NULL, NULL, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }
    jwe = (*jose)->jose.jwe;

    jwe->encryption = apr_jose_encryption_make(NULL, NULL,
            NULL, pool);
    if (!jwe->encryption) {
        return APR_ENOMEM;
    }

    jwe->recipient = apr_jose_recipient_make(NULL, NULL, pool);
    if (!jwe->recipient) {
        return APR_ENOMEM;
    }

    /*
     * Parse the JWE representation to extract the serialized values
     * for the components of the JWE.  When using the JWE Compact
     * Serialization, these components are the base64url-encoded
     * representations of the JWE Protected Header, the JWE Encrypted
     * Key, the JWE Initialization Vector, the JWE Ciphertext, and the
     * JWE Authentication Tag, and when using the JWE JSON
     * Serialization, these components also include the base64url-
     * encoded representation of the JWE AAD and the unencoded JWE
     * Shared Unprotected Header and JWE Per-Recipient Unprotected
     * Header values.  When using the JWE Compact Serialization, the
     * JWE Protected Header, the JWE Encrypted Key, the JWE
     * Initialization Vector, the JWE Ciphertext, and the JWE
     * Authentication Tag are represented as base64url-encoded values
     * in that order, with each value being separated from the next by
     * a single period ('.') character, resulting in exactly four
     * delimiting period characters being used.  The JWE JSON
     * Serialization is described in Section 7.2.
     */

    /* protected header */
    if (ph) {
        jwe->encryption->protected = ph;
    }

    /* encrypted key */
    dot = memchr(left, '.', right - left);
    if (!dot) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: compact JWE decoding failed: one lonely dot");
        return APR_BADCH;
    }

    jwe->recipient->ekey.data = apr_pdecode_base64_binary(pool, left,
            dot - left, APR_ENCODE_BASE64URL, &jwe->recipient->ekey.len);
    if (!jwe->recipient->ekey.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE ekey base64url decoding failed at %" APR_SIZE_T_FMT "",
                jwe->recipient->ekey.len);
        return APR_BADCH;
    }

    left = dot + 1;

    /* iv */
    dot = memchr(left, '.', right - left);
    if (!dot) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE compact decoding failed: only two dots");
        return APR_BADCH;
    }

    jwe->encryption->iv.data = apr_pdecode_base64_binary(pool, left,
            dot - left, APR_ENCODE_BASE64URL, &jwe->encryption->iv.len);
    if (!jwe->encryption->iv.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE iv base64url decoding failed at %" APR_SIZE_T_FMT "",
                                        jwe->encryption->iv.len);
        return APR_BADCH;
    }

    left = dot + 1;

    /* ciphertext */
    dot = memchr(left, '.', right - left);
    if (!dot) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE compact JWE decoding failed: only three dots");

        return APR_BADCH;
    }

    jwe->encryption->cipher.data = apr_pdecode_base64_binary(pool, left,
            dot - left, APR_ENCODE_BASE64URL, &jwe->encryption->cipher.len);
    if (!jwe->encryption->cipher.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE ciphertext base64url decoding failed at %" APR_SIZE_T_FMT "",
                jwe->encryption->cipher.len);

        return APR_BADCH;
    }

    left = dot + 1;

    /* tag */
    jwe->encryption->tag.data = apr_pdecode_base64_binary(pool, left,
            dot - left, APR_ENCODE_BASE64URL, &jwe->encryption->tag.len);
    if (!jwe->encryption->tag.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE tag base64url decoding failed at %" APR_SIZE_T_FMT "",
                jwe->encryption->tag.len);

        return APR_BADCH;
    }

    /* aad is the empty string in compact serialisation */
    memset(&aad64, 0, sizeof(apr_jose_text_t));

    status = apr_jose_decode_jwe_recipient(jose,
            bb, jwe->recipient, jwe->encryption, typ, cty, ph64, &aad64, cb,
            level, &dflags, pool);

    if (APR_SUCCESS != status) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Decryption failed: JWE decryption failed");

        return status;
    }

    return APR_SUCCESS;
}

static
apr_status_t apr_jose_decode_compact(apr_jose_t **jose, const char *typ,
        apr_bucket_brigade *brigade, apr_jose_cb_t *cb, int level, int flags,
        apr_pool_t *pool)
{
    apr_bucket_brigade *bb;
    apr_jose_text_t in;
    apr_jose_text_t ph64;
    apr_jose_text_t phs;
    apr_json_kv_t *kv;
    apr_json_value_t *header;
    const char *left;
    const char *right;
    const char *dot;
    const char *cty = NULL;
    apr_off_t offset;
    apr_status_t status = APR_ENOTIMPL;

    status = apr_jose_flatten(brigade, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    left = in.text;
    right = in.text + in.len;

    *jose = apr_jose_make(NULL, APR_JOSE_TYPE_NONE, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    bb = apr_brigade_create(pool, brigade->bucket_alloc);
    if (!bb) {
        return APR_ENOMEM;
    }

    /*
     * Use a heuristic to see whether this is a JWT, JWE or JWS.
     *
     * This is described in https://tools.ietf.org/html/rfc7519#section-7.2
     */

    /* Verify that the JWT contains at least one period ('.')
     * character.
     */
    dot = memchr(left, '.', in.len);
    if (!dot) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE compact decoding failed: no dots found");

        return APR_BADCH;
    }

    ph64.text = in.text;
    ph64.len = dot - in.text;

    left = dot + 1;

    /*
     * Let the Encoded JOSE Header be the portion of the JWT before the
     * first period ('.') character.
     *
     * Base64url decode the Encoded JOSE Header following the
     * restriction that no line breaks, whitespace, or other additional
     * characters have been used.
     */

    phs.text = apr_pdecode_base64(pool, ph64.text, ph64.len, APR_ENCODE_BASE64URL,
            &phs.len);
    if (!phs.text) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE header base64url decoding failed at %" APR_SIZE_T_FMT "",
                phs.len);

        return APR_BADCH;
    }

    /*
     * Verify that the resulting octet sequence is a UTF-8-encoded
     * representation of a completely valid JSON object conforming to
     * RFC 7159 [RFC7159]; let the JOSE Header be this JSON object.
     */

    status = apr_json_decode(&header, phs.text, phs.len, &offset,
            APR_JSON_FLAGS_WHITESPACE, level, pool);

    if (APR_SUCCESS != status) {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE header decoding failed at %" APR_OFF_T_FMT ": %s",
                offset, buf);

        return status;
    }

    kv = apr_json_object_get(header, APR_JOSE_JWSE_CONTENT_TYPE,
            APR_JSON_VALUE_STRING);
    if (kv) {
        if (kv->v->type == APR_JSON_STRING) {
            cty = apr_pstrndup(pool, kv->v->value.string.p,
                    kv->v->value.string.len);
        }
    }

    if (cty) {
        if (!strcasecmp(cty, "JWT") || !strcasecmp(cty, "application/jwt")) {
            typ = "JWT";
        }
    }

    kv = apr_json_object_get(header, APR_JOSE_JWSE_TYPE, APR_JSON_VALUE_STRING);
    if (kv) {
        if (kv->v->type == APR_JSON_STRING) {
            typ = apr_pstrndup(pool, kv->v->value.string.p,
                    kv->v->value.string.len);
        }
    }

    /*
     * Determine whether the JWT is a JWS or a JWE using any of the
     * methods described in Section 9 of [JWE].
     *
     * The JOSE Header for a JWS can also be distinguished from the JOSE
     * Header for a JWE by determining whether an "enc" (encryption
     * algorithm) member exists.  If the "enc" member exists, it is a
     * JWE; otherwise, it is a JWS.
     */

    kv = apr_json_object_get(header, APR_JOSE_JWE_ENCRYPTION,
            APR_JSON_VALUE_STRING);
    if (kv) {
        status = apr_jose_decode_compact_jwe(jose, left, right, header, kv->v,
                typ, cty, &ph64, cb, level, flags, pool, bb);
    } else {
        status = apr_jose_decode_compact_jws(jose, left, right, header, typ, cty, &in, &ph64,
                cb, level, flags, pool, bb);
    }

    if (APR_SUCCESS == status) {

        /*
         * JWT is an anomaly.
         *
         * If we have stripped off one level of JOSE, and the content-type
         * is present and set to JWT, our payload is a next level JOSE.
         *
         * If we have stripped off one level of JOSE, and the content-type
         * is not present but the type is present and set to JWT, our payload
         * is a JSON object containing claims.
         */

        if (!cty && typ
                && (!strcasecmp(typ, "JWT")
                        || !strcasecmp(typ, "application/jwt"))) {

            status = apr_jose_decode_jwt(
                    flags & APR_JOSE_FLAG_DECODE_ALL ?
                            &(*jose)->jose.jws->payload : jose, typ, bb, cb,
                    level, flags, pool);

        }
        else {

            if (level <= 0) {
                apr_errprintf(&(*jose)->result, pool, NULL, 0,
                        "Syntax error: too many nested JOSE payloads");
                return APR_EINVAL;
            }
            level--;

            status = apr_jose_decode(
                    flags & APR_JOSE_FLAG_DECODE_ALL ?
                            &(*jose)->jose.jws->payload : jose, typ, bb, cb,
                    level, flags, pool);
        }

    }

    return status;
}

static
apr_status_t apr_jose_decode_json_jws(apr_jose_t **jose, apr_json_value_t *val,
        const char *typ, const char *cty, apr_json_value_t *pl,
        apr_jose_cb_t *cb, int level, int flags, apr_pool_t *pool,
        apr_bucket_brigade *bb)
{
    apr_jose_text_t ph64;
    apr_jose_text_t sig64;
    apr_jose_text_t pl64;
    apr_jose_text_t pls;
    apr_jose_jws_t *jws;
    apr_json_kv_t *kv;
    apr_json_value_t *uh;
    apr_bucket *e;
    apr_status_t status = APR_EINVAL;
    int vflags = APR_JOSE_FLAG_NONE;

    if (!cb || !cb->verify) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Verification failed: no verify callback provided");

        return APR_EINIT;
    }

    if (pl->type != APR_JSON_STRING) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'payload' is not a string");

        return APR_EINVAL;
    }

    pl64.text = pl->value.string.p;
    pl64.len = pl->value.string.len;

    /*
     * Base64url-decode the encoded representation of the JWS Payload,
     * following the restriction that no line breaks, whitespace, or
     * other additional characters have been used.
     */

    pls.text = apr_pdecode_base64(pool, pl64.text,
            pl64.len, APR_ENCODE_BASE64URL, &pls.len);
    if (!pls.text) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'payload' is not valid base64url");

        return APR_BADCH;
    }

    *jose = apr_jose_jws_json_make(*jose, NULL, NULL, NULL, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }
    jws = (*jose)->jose.jws;

    /* for each signature in signatures... */
    kv = apr_json_object_get(val, APR_JOSE_JWS_SIGNATURES,
            APR_JSON_VALUE_STRING);
    if (kv) {
        apr_json_value_t *sigs = kv->v;
        int i;
        int verified = 0;

        if (sigs->type != APR_JSON_ARRAY) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWS 'signatures' is not an array");

            return APR_EINVAL;
        }

        jws->signatures = apr_array_make(pool, sigs->value.array->array->nelts,
                sizeof(apr_jose_signature_t *));
        if (!jws->signatures) {
            return APR_ENOMEM;
        }

        /*
         * If the JWS JSON Serialization is being used, repeat this process
         * (steps 4-8) for each digital signature or MAC value contained in
         * the representation.
         */

        for (i = 0; i < sigs->value.array->array->nelts; i++) {
            apr_json_value_t *sig = apr_json_array_get(sigs, i);

            if (sig) {
                apr_jose_signature_t **sp;

                if (sig->type != APR_JSON_OBJECT) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWS 'signatures' array contains a non-object");

                    return APR_EINVAL;
                }

                sp = apr_array_push(jws->signatures);
                *sp = apr_pcalloc(pool, sizeof(apr_jose_signature_t));
                if (!*sp) {
                    return APR_ENOMEM;
                }

                kv = apr_json_object_get(sig, APR_JOSE_JWSE_PROTECTED,
                        APR_JSON_VALUE_STRING);
                if (!kv) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWS 'protected' header is missing");

                    return APR_EINVAL;
                }

                if (kv->v->type != APR_JSON_STRING) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWS 'protected' is not a string");

                    return APR_EINVAL;
                }

                ph64.text = kv->v->value.string.p;
                ph64.len = kv->v->value.string.len;

                kv = apr_json_object_get(sig, APR_JOSE_JWSE_HEADER,
                        APR_JSON_VALUE_STRING);
                if (kv) {

                    if (kv->v->type != APR_JSON_OBJECT) {
                        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                "Syntax error: JWS 'header' is not an object");

                        return APR_EINVAL;
                    }

                    uh = kv->v;
                }
                else {
                    uh = NULL;
                }

                kv = apr_json_object_get(sig, APR_JOSE_JWS_SIGNATURE,
                        APR_JSON_VALUE_STRING);
                if (!kv) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWS 'signature' header is missing");

                    return APR_EINVAL;
                }

                if (kv->v->type != APR_JSON_STRING) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWS 'signature' is not a string");

                    return APR_EINVAL;
                }

                sig64.text = kv->v->value.string.p;
                sig64.len = kv->v->value.string.len;

                /*
                 * Validate the JWS Signature against the JWS Signing Input
                 * ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' ||
                 * BASE64URL(JWS Payload)) in the manner defined for the algorithm
                 * being used, which MUST be accurately represented by the value of
                 * the "alg" (algorithm) Header Parameter, which MUST be present.
                 * See Section 10.6 for security considerations on algorithm
                 * validation.  Record whether the validation succeeded or not.
                 */

                apr_brigade_cleanup(bb);

                status = apr_brigade_write(bb, NULL, NULL, ph64.text,
                        ph64.len);
                if (APR_SUCCESS != status) {
                    return status;
                }

                status = apr_brigade_putc(bb, NULL, NULL, '.');
                if (APR_SUCCESS != status) {
                    return status;
                }

                status = apr_brigade_write(bb, NULL, NULL, pl64.text,
                        pl64.len);
                if (APR_SUCCESS != status) {
                    return status;
                }

                status = apr_jose_decode_jws_signature(jose, *sp, typ, cty,
                        &ph64, &sig64, &pl64, uh, cb, level, &vflags, pool, bb);

                if (APR_SUCCESS == status) {

                    verified++;

                    if (verified == 1) {

                        apr_brigade_cleanup(bb);
                        e = apr_bucket_pool_create(pls.text, pls.len, pool,
                                bb->bucket_alloc);
                        APR_BRIGADE_INSERT_TAIL(bb, e);

                        if (level <= 0) {
                            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                    "Syntax error: too many nested JOSE payloads");
                            return APR_EINVAL;
                        }
                        level--;

                        status = apr_jose_decode(
                                flags & APR_JOSE_FLAG_DECODE_ALL ?
                                        &(*jose)->jose.jwe->payload : jose, typ,
                                bb, cb, level, flags, pool);

                        if (APR_SUCCESS != status) {
                            return status;
                        }

                    }

                }

                if (!(vflags & APR_JOSE_FLAG_BREAK)) {
                    break;
                }

            }

        }

        if (!verified) {
            apr_jose_t *j = *jose;

            if (!j->result.msg) {
                apr_errprintf(&(*jose)->result, pool, NULL, 0,
                        "JWS verification failed: no signatures matched");
            }

            return APR_ENOVERIFY;
        }

        return APR_SUCCESS;
    }

    jws->signature = apr_jose_signature_make(NULL, NULL, NULL,
            pool);
    if (!jws->signature) {
        return APR_ENOMEM;
    }

    kv = apr_json_object_get(val, APR_JOSE_JWSE_PROTECTED,
            APR_JSON_VALUE_STRING);
    if (!kv) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'protected' header is missing");

        return APR_EINVAL;
    }

    if (kv->v->type != APR_JSON_STRING) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'protected' is not a string");

        return APR_EINVAL;
    }

    ph64.text = kv->v->value.string.p;
    ph64.len = kv->v->value.string.len;

    kv = apr_json_object_get(val, APR_JOSE_JWSE_HEADER, APR_JSON_VALUE_STRING);
    if (kv) {

        if (kv->v->type != APR_JSON_OBJECT) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWS 'header' is not an object");

            return APR_EINVAL;
        }

        uh = kv->v;
    }
    else {
        uh = NULL;
    }

    kv = apr_json_object_get(val, APR_JOSE_JWS_SIGNATURE,
            APR_JSON_VALUE_STRING);
    if (!kv) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'signature' header is missing");

        return APR_EINVAL;
    }

    if (kv->v->type != APR_JSON_STRING) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWS 'signature' is not a string");

        return APR_EINVAL;
    }

    sig64.text = kv->v->value.string.p;
    sig64.len = kv->v->value.string.len;

    /*
     * Validate the JWS Signature against the JWS Signing Input
     * ASCII(BASE64URL(UTF8(JWS Protected Header)) || '.' ||
     * BASE64URL(JWS Payload)) in the manner defined for the algorithm
     * being used, which MUST be accurately represented by the value of
     * the "alg" (algorithm) Header Parameter, which MUST be present.
     * See Section 10.6 for security considerations on algorithm
     * validation.  Record whether the validation succeeded or not.
     */

    apr_brigade_cleanup(bb);

    status = apr_brigade_write(bb, NULL, NULL, ph64.text,
            ph64.len);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_brigade_putc(bb, NULL, NULL, '.');
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_brigade_write(bb, NULL, NULL, pl64.text,
            pl64.len);
    if (APR_SUCCESS != status) {
        return status;
    }

    status = apr_jose_decode_jws_signature(jose, jws->signature, typ, cty,
            &ph64, &sig64, &pl64, uh, cb, level, &vflags, pool, bb);

    if (APR_SUCCESS != status) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "JWS verification failed: signature rejected");

        return status;
    }

    apr_brigade_cleanup(bb);
    e = apr_bucket_pool_create(pls.text, pls.len, pool,
            bb->bucket_alloc);
    APR_BRIGADE_INSERT_TAIL(bb, e);

    if (level <= 0) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: too many nested JOSE payloads");
        return APR_EINVAL;
    }
    level--;

    return apr_jose_decode(
            flags & APR_JOSE_FLAG_DECODE_ALL ?
                    &(*jose)->jose.jws->payload : jose, typ, bb, cb,
            level, flags, pool);
}

static
apr_status_t apr_jose_decode_json_jwe(apr_jose_t **jose, apr_json_value_t *val,
        const char *typ, const char *cty, apr_json_value_t *ct,
        apr_jose_cb_t *cb, int level, int flags, apr_pool_t *pool,
        apr_bucket_brigade *bb)
{
    apr_jose_text_t ph64;
    apr_jose_text_t aad64;
    apr_jose_jwe_t *jwe;
    apr_json_kv_t *kv;
    apr_status_t status = APR_EGENERAL;
    int dflags = APR_JOSE_FLAG_NONE;

    if (!cb || !cb->decrypt) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Decryption failed: no decrypt callback provided");

        return APR_EINIT;
    }

    if (ct->type != APR_JSON_STRING) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE 'ciphertext' is not a string");

        return APR_EINVAL;
    }

    *jose = apr_jose_jwe_json_make(*jose, NULL, NULL, NULL, NULL, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }
    jwe = (*jose)->jose.jwe;

    jwe->encryption = apr_jose_encryption_make(NULL, NULL,
            NULL, pool);
    if (!jwe->encryption) {
        return APR_ENOMEM;
    }

    /*
     * Base64url decode the encoded representations of the JWE
     * Protected Header, the JWE Encrypted Key, the JWE Initialization
     * Vector, the JWE Ciphertext, the JWE Authentication Tag, and the
     * JWE AAD, following the restriction that no line breaks,
     * whitespace, or other additional characters have been used.
     */

    kv = apr_json_object_get(val, APR_JOSE_JWSE_PROTECTED,
            APR_JSON_VALUE_STRING);
    if (kv) {
        const char *phs;
        apr_size_t phlen;
        apr_off_t offset;

        if (kv->v->type != APR_JSON_STRING) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'protected' is not a string");

            return APR_EINVAL;
        }

        /*
         * Verify that the octet sequence resulting from decoding the
         * encoded JWE Protected Header is a UTF-8-encoded representation
         * of a completely valid JSON object conforming to RFC 7159
         * [RFC7159]; let the JWE Protected Header be this JSON object.
         */

        ph64.text = kv->v->value.string.p;
        ph64.len = kv->v->value.string.len;

        phs = apr_pdecode_base64(pool, ph64.text,
                ph64.len, APR_ENCODE_BASE64URL, &phlen);

        if (!phs) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'protected' is not valid base64url");

            return APR_EINVAL;
        }

        status = apr_json_decode(&jwe->encryption->protected, phs, phlen, &offset,
                APR_JSON_FLAGS_WHITESPACE, level, pool);
        if (APR_SUCCESS != status) {
            char buf[1024];
            apr_strerror(status, buf, sizeof(buf));
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'protected' decoding failed at %" APR_OFF_T_FMT ": %s",
                    offset, buf);

            return status;
        }

    }
    else {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE 'protected' header is missing");

        return APR_EINVAL;
    }

    /* unprotected */
    kv = apr_json_object_get(val, APR_JOSE_JWE_UNPROTECTED,
            APR_JSON_VALUE_STRING);
    if (kv) {

        if (kv->v->type != APR_JSON_OBJECT) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'unprotected' is not an object");

            return APR_EINVAL;
        }

        jwe->encryption->unprotected = kv->v;
    }

    /* ciphertext */
    jwe->encryption->cipher.data = apr_pdecode_base64_binary(pool,
            ct->value.string.p, ct->value.string.len, APR_ENCODE_BASE64URL,
            &jwe->encryption->cipher.len);
    if (!jwe->encryption->cipher.data) {
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JWE 'ciphertext' is not valid base64url");

        return APR_BADCH;
    }

    /* iv */
    kv = apr_json_object_get(val, APR_JOSE_JWE_IV, APR_JSON_VALUE_STRING);
    if (kv) {

        if (kv->v->type != APR_JSON_STRING) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'iv' is not a string");

            return APR_EINVAL;
        }

        jwe->encryption->iv.data = apr_pdecode_base64_binary(pool,
                kv->v->value.string.p, kv->v->value.string.len, APR_ENCODE_BASE64URL,
                &jwe->encryption->iv.len);
        if (!jwe->encryption->iv.data) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'iv' is not valid base64url");

            return APR_BADCH;
        }

    }

    /* tag */
    kv = apr_json_object_get(val, APR_JOSE_JWE_TAG, APR_JSON_VALUE_STRING);
    if (kv) {

        if (kv->v->type != APR_JSON_STRING) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'tag' is not a string");

            return APR_EINVAL;
        }

        jwe->encryption->tag.data = apr_pdecode_base64_binary(pool,
                kv->v->value.string.p, kv->v->value.string.len, APR_ENCODE_BASE64URL,
                &jwe->encryption->tag.len);
        if (!jwe->encryption->tag.data) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'tag' is not valid base64url");

            return APR_BADCH;
        }

    }

    /* aad */
    kv = apr_json_object_get(val, APR_JOSE_JWE_AAD, APR_JSON_VALUE_STRING);
    if (kv) {

        if (kv->v->type != APR_JSON_STRING) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'aad' is not a string");

            return APR_EINVAL;
        }

        aad64.text = kv->v->value.string.p;
        aad64.len = kv->v->value.string.len;

        jwe->encryption->aad.data = apr_pdecode_base64_binary(pool,
                aad64.text, aad64.len, APR_ENCODE_BASE64URL,
                &jwe->encryption->aad.len);
        if (!jwe->encryption->aad.data) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'add' is not valid base64url");

            return APR_BADCH;
        }

    }
    else {
        memset(&aad64, 0, sizeof(apr_jose_text_t));
    }

    /* for each recipient in recipients... */
    kv = apr_json_object_get(val, APR_JOSE_JWE_RECIPIENTS,
            APR_JSON_VALUE_STRING);
    if (kv) {
        apr_json_value_t *recips = kv->v;
        int i;
        int decrypt = 0;

        if (recips->type != APR_JSON_ARRAY) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'recipients' is not an array");

            return APR_EINVAL;
        }

        (*jose)->jose.jwe->recipients = apr_array_make(pool,
                recips->value.array->array->nelts, sizeof(apr_jose_recipient_t *));
        if (!(*jose)->jose.jwe->recipients) {
            return APR_ENOMEM;
        }

        for (i = 0; i < recips->value.array->array->nelts; i++) {
            apr_json_value_t *recip = apr_json_array_get(recips, i);

            if (recip) {
                apr_jose_recipient_t **rp;
                apr_jose_recipient_t *recipient;

                if (recip->type != APR_JSON_OBJECT) {
                    apr_errprintf(&(*jose)->result, pool, NULL, 0,
                            "Syntax error: JWE 'recipients' array contains a non-object");

                    return APR_EINVAL;
                }

                rp = apr_array_push((*jose)->jose.jwe->recipients);
                *rp = recipient = apr_pcalloc(pool, sizeof(apr_jose_recipient_t));
                if (!recipient) {
                    return APR_ENOMEM;
                }

                /* unprotected */
                kv = apr_json_object_get(recip, APR_JOSE_JWSE_HEADER,
                        APR_JSON_VALUE_STRING);
                if (kv) {

                    if (kv->v->type != APR_JSON_OBJECT) {
                        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                "Syntax error: JWE 'header' is not an object");

                        return APR_EINVAL;
                    }

                    recipient->header = kv->v;
                }

                kv = apr_json_object_get(recip, APR_JOSE_JWE_EKEY,
                        APR_JSON_VALUE_STRING);
                if (kv) {

                    if (kv->v->type != APR_JSON_STRING) {
                        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                "Syntax error: JWE 'encrypted_key' element must be a string");

                        return APR_EINVAL;
                    }

                    recipient->ekey.data = apr_pdecode_base64_binary(pool,
                            kv->v->value.string.p, kv->v->value.string.len, APR_ENCODE_BASE64URL,
                            &recipient->ekey.len);
                    if (!recipient->ekey.data) {
                        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                "Syntax error: JWE 'encrypted_key' is not valid base64url");

                        return APR_BADCH;
                    }

                }

                apr_brigade_cleanup(bb);

                status = apr_jose_decode_jwe_recipient(jose, bb, recipient,
                        jwe->encryption, typ, cty, &ph64, &aad64, cb, level,
                        &dflags, pool);

                if (APR_SUCCESS == status) {

                    decrypt++;

                    if (decrypt == 1) {

                        if (level <= 0) {
                            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                                    "Syntax error: too many nested JOSE payloads");
                            return APR_EINVAL;
                        }
                        level--;

                        status = apr_jose_decode(
                                flags & APR_JOSE_FLAG_DECODE_ALL ?
                                        &(*jose)->jose.jwe->payload : jose, typ,
                                        bb, cb, level, flags, pool);

                        if (APR_SUCCESS != status) {
                            return status;
                        }

                    }

                }

                if (!(dflags & APR_JOSE_FLAG_BREAK)) {
                    break;
                }

            }

        }

        if (!decrypt) {
            apr_jose_t *j = *jose;

            if (!j->result.msg) {
                apr_errprintf(&(*jose)->result, pool, NULL, 0,
                        "JWE decryption failed: no recipients matched");
            }

            return APR_ECRYPT;
        }

        return APR_SUCCESS;
    }

    /* ok, just one recipient */
    kv = apr_json_object_get(val, APR_JOSE_JWE_EKEY, APR_JSON_VALUE_STRING);
    if (kv) {
        apr_json_value_t *ekey = kv->v;
        apr_jose_recipient_t *recipient;

        if (ekey->type != APR_JSON_STRING) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Syntax error: JWE 'encrypted_key' element must be a string");

            return APR_EINVAL;
        }

        recipient = apr_pcalloc(pool, sizeof(apr_jose_recipient_t));
        if (!recipient) {
            return APR_ENOMEM;
        }

        /* unprotected */
        kv = apr_json_object_get(val, APR_JOSE_JWSE_HEADER,
                APR_JSON_VALUE_STRING);
        if (kv) {

            if (kv->v->type != APR_JSON_OBJECT) {
                apr_errprintf(&(*jose)->result, pool, NULL, 0,
                        "Syntax error: JWE 'header' is not an object");

                return APR_EINVAL;
            }

            recipient->header = kv->v;
        }

        apr_brigade_cleanup(bb);

        status = apr_jose_decode_jwe_recipient(jose, bb, recipient,
                jwe->encryption, typ, cty, &ph64, &aad64, cb, level, &dflags,
                pool);

        if (APR_SUCCESS == status) {

            if (level <= 0) {
                apr_errprintf(&(*jose)->result, pool, NULL, 0,
                        "Syntax error: too many nested JOSE payloads");
                return APR_EINVAL;
            }
            level--;

            return apr_jose_decode(
                    flags & APR_JOSE_FLAG_DECODE_ALL ?
                            &(*jose)->jose.jwe->payload : jose, typ, bb,
                    cb, level, flags, pool);

        }

        if (APR_SUCCESS != status) {
            apr_errprintf(&(*jose)->result, pool, NULL, 0,
                    "Decryption failed: JWE decryption failed");
        }

    }

    /* no recipient at all */
    apr_errprintf(&(*jose)->result, pool, NULL, 0,
            "Syntax error: No 'recipients' or 'encrypted_key' present");

    return APR_EINVAL;

}

static
apr_status_t apr_jose_decode_json(apr_jose_t **jose, const char *typ,
        apr_bucket_brigade *brigade, apr_jose_cb_t *cb, int level,
        int flags, apr_pool_t *pool)
{
    apr_json_value_t *val;
    apr_bucket_brigade *bb;
    apr_jose_text_t in;
    apr_off_t offset;
    apr_status_t status;

    *jose = apr_jose_make(NULL, APR_JOSE_TYPE_NONE, pool);
    if (!*jose) {
        return APR_ENOMEM;
    }

    status = apr_jose_flatten(brigade, &in, pool);
    if (APR_SUCCESS != status) {
        return status;
    }

    bb = apr_brigade_create(pool, brigade->bucket_alloc);
    if (!bb) {
        return APR_ENOMEM;
    }

    /*
     * Parse the JWS representation to extract the serialized values for
     * the components of the JWS.  When using the JWS Compact
     * Serialization, these components are the base64url-encoded
     * representations of the JWS Protected Header, the JWS Payload, and
     * the JWS Signature, and when using the JWS JSON Serialization,
     * these components also include the unencoded JWS Unprotected
     * Header value.  When using the JWS Compact Serialization, the JWS
     * Protected Header, the JWS Payload, and the JWS Signature are
     * represented as base64url-encoded values in that order, with each
     * value being separated from the next by a single period ('.')
     * character, resulting in exactly two delimiting period characters
     * being used.  The JWS JSON Serialization is described in
     * Section 7.2.
     */

    status = apr_json_decode(&val, in.text, in.len, &offset,
            APR_JSON_FLAGS_WHITESPACE, level, pool);
    if (APR_SUCCESS == status) {
        apr_json_kv_t *kv;
        const char *cty = NULL;

        /*
         * 9.  Distinguishing between JWS and JWE Objects
         *
         * If the object is using the JWS JSON Serialization or the JWE JSON
         * Serialization, the members used will be different.  JWSs have a
         * "payload" member and JWEs do not.  JWEs have a "ciphertext" member
         * and JWSs do not.
         */

        /* are we JWS? */
        kv = apr_json_object_get(val, APR_JOSE_JWS_PAYLOAD,
                APR_JSON_VALUE_STRING);
        if (kv) {

            return apr_jose_decode_json_jws(jose, val, typ, cty,
                    kv->v, cb, level, flags, pool, bb);

        }

        /* are we JWE? */
        kv = apr_json_object_get(val, APR_JOSE_JWE_CIPHERTEXT,
                APR_JSON_VALUE_STRING);
        if (kv) {

            return apr_jose_decode_json_jwe(jose, val, typ, cty,
                    kv->v, cb, level, flags, pool, bb);

        }

        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE JSON contained neither a 'payload' nor a 'ciphertext'");

        return APR_EINVAL;

    }
    else {
        char buf[1024];
        apr_strerror(status, buf, sizeof(buf));
        apr_errprintf(&(*jose)->result, pool, NULL, 0,
                "Syntax error: JOSE JSON decoding failed at character %" APR_OFF_T_FMT ": %s",
                offset, buf);
    }

    return status;
}

APR_DECLARE(apr_status_t) apr_jose_decode(apr_jose_t **jose, const char *typ,
                                          apr_bucket_brigade *brigade,
                                          apr_jose_cb_t *cb, int level,
                                          int flags, apr_pool_t *pool)
{

    /* handle JOSE and JOSE+JSON */
    if (typ) {
        switch (typ[0]) {
        case 'a':
        case 'A': {

            if (!strncasecmp(typ, "application/", 12)) {
                const char *sub = typ + 12;

                if (!strcasecmp(sub, "jwt")) {
                    return apr_jose_decode_compact(jose, typ, brigade, cb,
                            level, flags, pool);
                } else if (!strcasecmp(sub, "jose")) {
                    return apr_jose_decode_compact(jose, NULL, brigade, cb,
                            level, flags, pool);
                } else if (!strcasecmp(sub, "jose+json")) {
                    return apr_jose_decode_json(jose, NULL, brigade, cb, level,
                            flags, pool);
                } else if (!strcasecmp(sub, "jwk+json")) {
                    return apr_jose_decode_jwk(jose, typ, brigade, cb, level,
                            flags, pool);
                } else if (!strcasecmp(sub, "jwk-set+json")) {
                    return apr_jose_decode_jwks(jose, typ, brigade, cb, level,
                            flags, pool);
                }

            }

            break;
        }
        case 'J':
        case 'j': {

            if (!strcasecmp(typ, "JWT")) {
                return apr_jose_decode_compact(jose, typ, brigade, cb, level, flags,
                        pool);
            } else if (!strcasecmp(typ, "JOSE")) {
                return apr_jose_decode_compact(jose, NULL, brigade, cb, level,
                        flags, pool);
            } else if (!strcasecmp(typ, "JOSE+JSON")) {
                return apr_jose_decode_json(jose, NULL, brigade, cb, level, flags,
                        pool);
            } else if (!strcasecmp(typ, "JWK+JSON")) {
                return apr_jose_decode_jwk(jose, typ, brigade, cb, level, flags,
                        pool);
            } else if (!strcasecmp(typ, "JWK-SET+JSON")) {
                return apr_jose_decode_jwks(jose, typ, brigade, cb, level, flags,
                        pool);
            }

            break;
        }
        }
    }

    return apr_jose_decode_data(jose, typ, brigade, cb, level, flags, pool);
}