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
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
//! SAML 2.0 Response parsing and validation.
use core::fmt;
use crate::util::log::{debug, info, warn};
use crate::util::timestamp::Timestamp;
use crate::xml::{XmlElement, XmlParseError, parse_xml};
use super::SAML_NS;
use super::assertion::{SamlAssertion, parse_assertion};
use super::config::SamlConfig;
/// SAML protocol namespace URI.
const SAMLP_NS: &str = "urn:oasis:names:tc:SAML:2.0:protocol";
/// Top-level status code URIs.
const STATUS_SUCCESS: &str = "urn:oasis:names:tc:SAML:2.0:status:Success";
const STATUS_REQUESTER: &str = "urn:oasis:names:tc:SAML:2.0:status:Requester";
const STATUS_RESPONDER: &str = "urn:oasis:names:tc:SAML:2.0:status:Responder";
const STATUS_VERSION_MISMATCH: &str = "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch";
// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------
/// The category of SAML response parse/validation failure.
#[derive(Debug, Clone, PartialEq, Eq)]
enum SamlResponseErrorKind {
/// Base64 decoding failed.
Base64Decode(String),
/// The base64-decoded bytes are not valid UTF-8.
InvalidUtf8,
/// XML parsing failed.
XmlParse(XmlParseError),
/// The response structure is missing required elements.
MissingElement(String),
/// A `Response` or `Assertion` carried a `Version` attribute other than
/// the mandatory `"2.0"` (SAML Core §3.2.2 / §2.3.3), or omitted it.
InvalidVersion(String),
/// A single-occurrence element (`Issuer`, `Subject`, `NameID`,
/// `Conditions`) appeared more than once. First-match selection over a
/// duplicated element is a signature-wrapping surface, so it is rejected.
DuplicateElement(String),
/// The response destination does not match the expected ACS URL.
DestinationMismatch {
/// The expected ACS URL.
expected: String,
/// The actual destination in the response.
actual: String,
},
/// The assertion issuer does not match the expected `IdP` entity ID.
IssuerMismatch {
/// The expected `IdP` entity ID.
expected: String,
/// The actual issuer in the assertion.
actual: String,
},
/// The audience restriction does not include the SP entity ID (this
/// includes an assertion that omits `AudienceRestriction` entirely —
/// absence is treated as failure, not "valid for everyone").
AudienceMismatch {
/// The SP entity ID that was expected.
expected: String,
},
/// The response carried no usable assertion (none present, or the only
/// assertion(s) failed to parse).
NoAssertions,
/// The subject confirmation `Recipient` does not match this SP's ACS URL.
RecipientMismatch {
/// The expected ACS URL.
expected: String,
/// The `Recipient` the assertion was actually addressed to.
actual: String,
},
/// The SAML status indicates a non-success response.
NonSuccessStatus(SamlStatus),
/// The assertion is not yet valid (`NotBefore` is in the future).
NotYetValid {
/// The `NotBefore` timestamp from the assertion.
not_before: String,
},
/// The assertion has expired (`NotOnOrAfter` is in the past).
Expired {
/// The `NotOnOrAfter` timestamp from the assertion.
not_on_or_after: String,
},
/// A timestamp in the assertion could not be parsed.
InvalidTimestamp {
/// The field name (e.g. "`NotBefore`" or "`NotOnOrAfter`").
field: String,
/// The raw timestamp value that could not be parsed.
value: String,
},
}
/// Errors that can occur when parsing or validating a SAML response.
#[doc(alias = "saml_response_error")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SamlResponseError {
kind: SamlResponseErrorKind,
}
impl SamlResponseError {
/// Creates a new error from the given kind.
fn new(kind: SamlResponseErrorKind) -> Self {
Self { kind }
}
/// Creates a [`MissingElement`](SamlResponseErrorKind::MissingElement) error.
///
/// This is a convenience constructor used by the assertion parser to
/// report missing required child elements.
pub(crate) fn missing_element(name: &str) -> Self {
Self::new(SamlResponseErrorKind::MissingElement(name.to_string()))
}
/// Creates an [`InvalidVersion`](SamlResponseErrorKind::InvalidVersion)
/// error for the named element (`"Response"` or `"Assertion"`).
pub(crate) fn invalid_version(where_: &str) -> Self {
Self::new(SamlResponseErrorKind::InvalidVersion(where_.to_string()))
}
/// Creates a [`DuplicateElement`](SamlResponseErrorKind::DuplicateElement)
/// error for the named single-occurrence element.
pub(crate) fn duplicate_element(name: &str) -> Self {
Self::new(SamlResponseErrorKind::DuplicateElement(name.to_string()))
}
/// Returns `true` if this error is a base64 decoding failure.
#[must_use]
#[inline]
pub fn is_base64_decode(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::Base64Decode(_))
}
/// Returns `true` if the base64-decoded bytes were not valid UTF-8.
#[must_use]
#[inline]
pub fn is_invalid_utf8(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::InvalidUtf8)
}
/// Returns `true` if this error is an XML parsing failure.
#[must_use]
#[inline]
pub fn is_xml_parse(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::XmlParse(_))
}
/// Returns `true` if this error is a missing required element.
#[must_use]
#[inline]
pub fn is_missing_element(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::MissingElement(_))
}
/// Returns `true` if a `Response`/`Assertion` carried a `Version` other
/// than the mandatory `"2.0"` (or omitted it).
#[must_use]
pub fn is_invalid_version(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::InvalidVersion(_))
}
/// Returns `true` if a single-occurrence assertion element (`Issuer`,
/// `Subject`, `NameID`, `Conditions`) appeared more than once.
#[must_use]
pub fn is_duplicate_element(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::DuplicateElement(_))
}
/// Returns `true` if this error is a destination mismatch.
#[must_use]
#[inline]
pub fn is_destination_mismatch(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::DestinationMismatch { .. })
}
/// Returns `true` if this error is an issuer mismatch.
#[must_use]
#[inline]
pub fn is_issuer_mismatch(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::IssuerMismatch { .. })
}
/// Returns `true` if this error is an audience mismatch.
#[must_use]
#[inline]
pub fn is_audience_mismatch(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::AudienceMismatch { .. })
}
/// Returns `true` if this error is a non-success SAML status.
#[must_use]
#[inline]
pub fn is_non_success_status(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::NonSuccessStatus(_))
}
/// Returns `true` if the response carried no usable assertion.
#[must_use]
#[inline]
pub fn is_no_assertions(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::NoAssertions)
}
/// Returns `true` if the subject-confirmation `Recipient` did not match
/// this SP's ACS URL.
#[must_use]
#[inline]
pub fn is_recipient_mismatch(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::RecipientMismatch { .. })
}
/// Returns `true` if this error indicates the assertion is not yet valid.
#[must_use]
#[inline]
pub fn is_not_yet_valid(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::NotYetValid { .. })
}
/// Returns `true` if this error indicates the assertion has expired.
#[must_use]
#[inline]
pub fn is_expired(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::Expired { .. })
}
/// Returns `true` if this error indicates an unparseable timestamp.
#[must_use]
#[inline]
pub fn is_invalid_timestamp(&self) -> bool {
matches!(self.kind, SamlResponseErrorKind::InvalidTimestamp { .. })
}
}
impl fmt::Display for SamlResponseError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.kind {
SamlResponseErrorKind::Base64Decode(msg) => {
write!(f, "SAML response base64 decode error: {msg}")
}
SamlResponseErrorKind::InvalidUtf8 => f.write_str("SAML response is not valid UTF-8"),
SamlResponseErrorKind::XmlParse(err) => {
write!(f, "SAML response XML error: {err}")
}
SamlResponseErrorKind::MissingElement(name) => {
write!(f, "SAML response missing required element: {name}")
}
SamlResponseErrorKind::InvalidVersion(where_) => {
write!(f, "SAML {where_} has a Version other than \"2.0\"")
}
SamlResponseErrorKind::DuplicateElement(name) => {
write!(f, "SAML assertion has a duplicate {name} element")
}
SamlResponseErrorKind::DestinationMismatch { expected, actual } => {
write!(
f,
"SAML response destination mismatch: expected {expected}, got {actual}"
)
}
SamlResponseErrorKind::IssuerMismatch { expected, actual } => {
write!(
f,
"SAML assertion issuer mismatch: expected {expected}, got {actual}"
)
}
SamlResponseErrorKind::AudienceMismatch { expected } => {
write!(
f,
"SAML assertion audience restriction does not include {expected}"
)
}
SamlResponseErrorKind::NonSuccessStatus(status) => {
write!(f, "SAML response non-success status: {status}")
}
SamlResponseErrorKind::NoAssertions => {
f.write_str("SAML response contained no usable assertion")
}
SamlResponseErrorKind::RecipientMismatch { expected, actual } => {
write!(
f,
"SAML subject confirmation recipient mismatch: expected {expected}, got {actual}"
)
}
SamlResponseErrorKind::NotYetValid { not_before } => {
write!(f, "SAML assertion not yet valid (NotBefore={not_before})")
}
SamlResponseErrorKind::Expired { not_on_or_after } => {
write!(f, "SAML assertion expired (NotOnOrAfter={not_on_or_after})")
}
SamlResponseErrorKind::InvalidTimestamp { field, value } => {
write!(
f,
"SAML assertion contains unparseable timestamp: {field}={value}"
)
}
}
}
}
impl std::error::Error for SamlResponseError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
SamlResponseErrorKind::XmlParse(err) => Some(err),
SamlResponseErrorKind::Base64Decode(_)
| SamlResponseErrorKind::InvalidUtf8
| SamlResponseErrorKind::MissingElement(_)
| SamlResponseErrorKind::InvalidVersion(_)
| SamlResponseErrorKind::DuplicateElement(_)
| SamlResponseErrorKind::DestinationMismatch { .. }
| SamlResponseErrorKind::IssuerMismatch { .. }
| SamlResponseErrorKind::AudienceMismatch { .. }
| SamlResponseErrorKind::NonSuccessStatus(_)
| SamlResponseErrorKind::NoAssertions
| SamlResponseErrorKind::RecipientMismatch { .. }
| SamlResponseErrorKind::NotYetValid { .. }
| SamlResponseErrorKind::Expired { .. }
| SamlResponseErrorKind::InvalidTimestamp { .. } => None,
}
}
}
impl From<XmlParseError> for SamlResponseError {
fn from(err: XmlParseError) -> Self {
Self::new(SamlResponseErrorKind::XmlParse(err))
}
}
// ---------------------------------------------------------------------------
// SamlStatus
// ---------------------------------------------------------------------------
/// SAML 2.0 top-level status codes.
#[doc(alias = "saml_status")]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SamlStatus {
/// The request succeeded.
Success,
/// The request could not be performed due to an error by the requester.
Requester,
/// The request could not be performed due to an error at the responder.
Responder,
/// The responder could not process the request because the version was wrong.
VersionMismatch,
/// An unrecognized status code.
Unknown(String),
}
impl fmt::Display for SamlStatus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Success => f.write_str("Success"),
Self::Requester => f.write_str("Requester"),
Self::Responder => f.write_str("Responder"),
Self::VersionMismatch => f.write_str("VersionMismatch"),
Self::Unknown(uri) => {
write!(f, "Unknown({uri})")
}
}
}
}
// ---------------------------------------------------------------------------
// SamlResponse
// ---------------------------------------------------------------------------
/// A parsed SAML 2.0 `<samlp:Response>`.
#[doc(alias = "saml_response")]
#[derive(Debug, Clone)]
pub struct SamlResponse {
/// Unique identifier for this response.
id: String,
/// Timestamp when the response was issued.
issue_instant: String,
/// The intended destination URL (ACS URL).
destination: Option<String>,
/// The Response-level `<Issuer>`, if present (distinct from the
/// assertion's own Issuer).
issuer: Option<String>,
/// The response status.
status: SamlStatus,
/// Assertions contained in the response.
assertions: Vec<SamlAssertion>,
}
impl SamlResponse {
/// Returns the unique identifier for this response.
#[must_use]
#[inline]
pub fn id(&self) -> &str {
&self.id
}
/// Returns the timestamp when the response was issued.
#[must_use]
#[inline]
pub fn issue_instant(&self) -> &str {
&self.issue_instant
}
/// Returns the intended destination URL (ACS URL), if present.
#[must_use]
#[inline]
pub fn destination(&self) -> Option<&str> {
self.destination.as_deref()
}
/// Returns the Response-level `<Issuer>`, if present.
///
/// This is the issuer of the protocol `<Response>` envelope, which is
/// distinct from each assertion's own `<Issuer>`. It is optional in SAML;
/// when present, [`validate_conditions_only`](Self::validate_conditions_only)
/// checks it equals the configured `IdP` entity ID.
#[must_use]
#[inline]
pub fn issuer(&self) -> Option<&str> {
self.issuer.as_deref()
}
/// Returns the response status.
#[must_use]
#[inline]
pub fn status(&self) -> &SamlStatus {
&self.status
}
/// Returns the assertions contained in the response.
#[must_use]
#[inline]
pub fn assertions(&self) -> &[SamlAssertion] {
&self.assertions
}
}
/// Which end of a temporal validity window a [`check_window`] call enforces.
///
/// Selects both the comparison direction and the [`SamlResponseErrorKind`]
/// returned when the window is violated. Clock skew is always applied in the
/// direction that *widens* the acceptance window (subtracted from a lower
/// bound, added to an upper bound) so minor IdP/SP drift never causes a
/// spurious rejection.
#[derive(Clone, Copy)]
enum WindowBound {
/// Lower bound (`NotBefore`): the assertion is invalid *before* the value.
NotBefore,
/// Upper bound (`NotOnOrAfter`): the assertion is invalid *at or after*
/// the value.
NotOnOrAfter,
}
/// Enforces a single SAML temporal validity bound against `now`, allowing the
/// configured clock skew.
///
/// `field_name` names the attribute for diagnostics (it appears in the
/// [`SamlResponseErrorKind::InvalidTimestamp`] error on a parse failure).
/// `value` is the raw timestamp string; when absent the check is skipped
/// (every SAML temporal attribute here is optional). `warn_msg` is the log
/// line emitted on a window violation.
///
/// # Security
///
/// An unparseable timestamp is a hard failure ([`InvalidTimestamp`]) — never
/// a silent skip, which would grant an unbounded validity window. The skew is
/// applied with `saturating_add` so it cannot overflow.
///
/// [`InvalidTimestamp`]: SamlResponseErrorKind::InvalidTimestamp
fn check_window(
field_name: &str,
value: Option<&str>,
skew: u64,
now: &Timestamp,
bound: WindowBound,
warn_msg: &str,
) -> Result<(), SamlResponseError> {
let Some(value) = value else {
return Ok(());
};
// SECURITY: An unparseable timestamp MUST be treated as a validation
// failure — silently skipping the check would grant the assertion an
// effectively unlimited validity window.
let value_ts = Timestamp::parse_iso8601(value).ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::InvalidTimestamp {
field: field_name.to_string(),
value: value.to_string(),
})
})?;
match bound {
WindowBound::NotBefore => {
// Allow clock skew: fail only when now + skew < NotBefore.
let adjusted_now =
Timestamp::from_unix_secs(now.unix_epoch_secs().saturating_add(skew));
if adjusted_now.is_before(&value_ts) {
warn!(not_before = %value, "{warn_msg}");
return Err(SamlResponseError::new(SamlResponseErrorKind::NotYetValid {
not_before: value.to_string(),
}));
}
}
WindowBound::NotOnOrAfter => {
// Allow clock skew: fail only when NotOnOrAfter + skew <= now.
let adjusted =
Timestamp::from_unix_secs(value_ts.unix_epoch_secs().saturating_add(skew));
if adjusted.is_expired(now) {
warn!(not_on_or_after = %value, "{warn_msg}");
return Err(SamlResponseError::new(SamlResponseErrorKind::Expired {
not_on_or_after: value.to_string(),
}));
}
}
}
Ok(())
}
impl SamlResponse {
/// Parse a Base64-encoded SAML Response (as typically received via the
/// HTTP-POST binding) **without verifying its XML signature**.
///
/// # Security — the result is UNVERIFIED
///
/// The returned [`SamlResponse`] is parsed only; its `IdP` digital
/// signature is **not** checked (this crate does not implement XML-DSig).
/// Every field — issuer, audience, `NameID`, attributes — is therefore
/// attacker-controlled. The `_unverified` suffix is deliberate: a caller
/// MUST verify the XML signature against the `IdP` certificate (e.g. via an
/// external XML-DSig layer) before trusting anything in the result. See
/// the [`saml` module docs](super).
///
/// # Errors
///
/// Returns [`SamlResponseError`] if base64 decoding or XML parsing fails.
pub fn parse_base64_unverified(encoded: &str) -> Result<Self, SamlResponseError> {
// SECURITY: bound the input *before* decoding so an attacker cannot
// force a large heap allocation up front. base64 expands ~4/3, so an
// input under this ceiling can never decode to more than the
// `parse_xml` `MAX_XML_SIZE` limit applied afterwards. This bound
// relies on `base64_decode` rejecting embedded whitespace/newlines
// (it does); a future switch to a whitespace-tolerant decoder, where
// encoded length no longer tracks decoded length, must revisit it.
const MAX_ENCODED_LEN: usize = crate::xml::MAX_XML_SIZE / 3 * 4 + 4;
debug!("saml: decoding base64 response");
if encoded.len() > MAX_ENCODED_LEN {
return Err(SamlResponseError::new(SamlResponseErrorKind::XmlParse(
XmlParseError::InputTooLarge,
)));
}
let decoded = crate::encoding::base64_decode(encoded).map_err(|e| {
SamlResponseError::new(SamlResponseErrorKind::Base64Decode(e.to_string()))
})?;
let xml_str = String::from_utf8(decoded)
.map_err(|_| SamlResponseError::new(SamlResponseErrorKind::InvalidUtf8))?;
Self::parse_xml_unverified(&xml_str)
}
/// Parse raw SAML Response XML **without verifying its XML signature**.
///
/// # Security — the result is UNVERIFIED
///
/// See [`parse_base64_unverified`](Self::parse_base64_unverified): the
/// signature is not checked, so the result is fully attacker-controlled
/// until the caller verifies the `IdP` signature externally.
///
/// # Errors
///
/// Returns [`SamlResponseError`] if parsing or required-element
/// extraction fails.
pub fn parse_xml_unverified(xml: &str) -> Result<Self, SamlResponseError> {
let root = parse_xml(xml)?;
let response = Self::from_element(&root)?;
// SECURITY: Log response ID and status only — never log raw XML.
debug!(
id = %response.id,
status = ?response.status,
"saml: response parsed"
);
Ok(response)
}
/// Validate the response's **conditions** against the given SP/IdP
/// configuration. This is NOT a full SAML validation — it does not, and
/// cannot, verify the XML signature or prevent replay.
///
/// Checks:
/// - At least one assertion is present (an empty/zero-assertion response
/// is rejected)
/// - Status is `Success`
/// - Destination matches the ACS URL (if present)
/// - Response-level issuer matches the `IdP` entity ID (if present)
/// - Assertion issuer matches the `IdP` entity ID
/// - An `AudienceRestriction` is present **and** includes the SP entity
/// ID (an assertion with no audience restriction is rejected)
/// - Subject confirmation `Recipient` (when present) matches the ACS URL,
/// and its `NotOnOrAfter` has not passed
/// - Temporal conditions (`NotBefore`, `NotOnOrAfter`) against the
/// current wall-clock time
///
/// # Security — signature & replay are the CALLER's responsibility
///
/// The method name carries `_conditions_only` because this is **not** a
/// trust decision:
///
/// 1. **No signature check.** The XML digital signature is not verified
/// (this crate has no XML-DSig). An attacker who can deliver XML to
/// the ACS can satisfy every check here with a forged assertion. The
/// caller MUST verify the `IdP` signature externally first.
/// 2. **No replay protection.** The crate is storage-free, so it cannot
/// track consumed assertion IDs. The caller MUST keep a replay cache
/// keyed on the assertion ID (TTL ≥ the validity window) and reject
/// re-presentation.
/// 3. **No `InResponseTo` matching.** For SP-initiated SSO the caller
/// MUST confirm `subject().in_response_to()` equals an outstanding
/// `AuthnRequest` ID it issued (and reject unsolicited assertions
/// unless IdP-initiated SSO is explicitly supported).
/// 4. **Bearer confirmation is not required.** The `Recipient` /
/// `NotOnOrAfter` binding is checked only when a bearer
/// `SubjectConfirmationData` is present. An assertion with no bearer
/// confirmation passes these checks vacuously, so a caller relying on
/// the recipient binding MUST confirm `subject().recipient().is_some()`.
///
/// # Errors
///
/// Returns [`SamlResponseError`] describing the first validation failure.
pub fn validate_conditions_only(&self, config: &SamlConfig) -> Result<(), SamlResponseError> {
// Status must be Success.
if self.status != SamlStatus::Success {
warn!(status = ?self.status, "saml: non-success status");
return Err(SamlResponseError::new(
SamlResponseErrorKind::NonSuccessStatus(self.status.clone()),
));
}
self.validate_destination(config)?;
// Response-level Issuer, when present, must be the configured IdP
// (SAML Core §3.2.2). Absent is allowed (the element is optional and
// the assertion Issuer is independently checked per assertion).
if let Some(resp_issuer) = self.issuer.as_deref() {
if resp_issuer != config.idp_entity_id() {
warn!(
expected = %config.idp_entity_id(),
"saml: response issuer mismatch"
);
return Err(SamlResponseError::new(
SamlResponseErrorKind::IssuerMismatch {
expected: config.idp_entity_id().to_string(),
actual: resp_issuer.to_string(),
},
));
}
}
// SECURITY: a response with no usable assertion must NOT validate —
// otherwise a caller that treats Ok as "authenticated" would accept
// an empty (or all-malformed) response. `from_element` fails closed
// on malformed assertions, so an empty vec means "nothing usable".
if self.assertions.is_empty() {
warn!("saml: response carried no usable assertion");
return Err(SamlResponseError::new(SamlResponseErrorKind::NoAssertions));
}
for assertion in &self.assertions {
Self::validate_assertion(assertion, config)?;
}
info!(
assertions = self.assertions.len(),
"saml: conditions validated"
);
Ok(())
}
/// Validates destination matches ACS URL.
fn validate_destination(&self, config: &SamlConfig) -> Result<(), SamlResponseError> {
if let Some(ref dest) = self.destination {
if dest != config.acs_url() {
// SECURITY: Log expected and actual destinations — these are
// endpoint URLs, not secrets.
warn!(
expected = %config.acs_url(),
actual = %dest,
"saml: destination mismatch"
);
return Err(SamlResponseError::new(
SamlResponseErrorKind::DestinationMismatch {
expected: config.acs_url().to_string(),
actual: dest.clone(),
},
));
}
}
Ok(())
}
/// Validates a single assertion against the configuration.
fn validate_assertion(
assertion: &SamlAssertion,
config: &SamlConfig,
) -> Result<(), SamlResponseError> {
// Issuer must match IdP entity ID.
if assertion.issuer() != config.idp_entity_id() {
warn!(
expected = %config.idp_entity_id(),
actual = %assertion.issuer(),
"saml: issuer mismatch"
);
return Err(SamlResponseError::new(
SamlResponseErrorKind::IssuerMismatch {
expected: config.idp_entity_id().to_string(),
actual: assertion.issuer().to_string(),
},
));
}
// Audience restrictions must be PRESENT and admit this SP.
// SECURITY: an assertion with no AudienceRestriction is rejected —
// treating "absent" as "valid for every SP" would let an assertion
// minted for another SP be replayed here (confused deputy). Per SAML
// Core §2.5.1.4 the SP must appear in EVERY restriction (AND across,
// OR within): an issuer that scopes an assertion to the intersection
// of two restrictions must not have it accepted on one alone.
let entity_id = config.entity_id();
let restrictions = assertion.conditions().audience_restrictions();
let audience_ok = !restrictions.is_empty()
&& restrictions
.iter()
.all(|restriction| restriction.iter().any(|a| a == entity_id));
if !audience_ok {
warn!(expected = %entity_id, "saml: audience missing or mismatched");
return Err(SamlResponseError::new(
SamlResponseErrorKind::AudienceMismatch {
expected: entity_id.to_string(),
},
));
}
// Subject confirmation Recipient (when present) must address this SP's
// ACS URL — prevents an assertion captured for one endpoint being
// redirected to another (SAML Web Browser SSO §4.1.4.3).
if let Some(recipient) = assertion.subject().recipient() {
if recipient != config.acs_url() {
warn!(
expected = %config.acs_url(),
actual = %recipient,
"saml: subject confirmation recipient mismatch"
);
return Err(SamlResponseError::new(
SamlResponseErrorKind::RecipientMismatch {
expected: config.acs_url().to_string(),
actual: recipient.to_string(),
},
));
}
}
// Temporal conditions: parse SAML timestamps into `Timestamp`
// values and compare numerically via epoch seconds. This avoids
// relying on lexicographic string ordering which is fragile for
// non-UTC timezone offsets.
//
// Clock skew tolerance: IdP and SP clocks may be slightly out of
// sync. We allow a configurable tolerance (default 60 s) so that
// minor drift does not cause spurious validation failures.
let now_ts = Timestamp::now();
let skew = config.clock_skew_secs();
// SECURITY: require SOME upper bound. `check_window` returns Ok for an
// absent timestamp (correct in isolation — each bound is optional in
// the schema), and no caller required any of the three, so an assertion
// whose `<Conditions>` carried only an `AudienceRestriction` was valid
// forever. A captured bearer assertion with no deadline is replayable
// indefinitely.
if assertion.conditions().not_on_or_after().is_none()
&& assertion.subject().confirmation_not_on_or_after().is_none()
{
return Err(SamlResponseError::missing_element(
"Assertion NotOnOrAfter (Conditions or SubjectConfirmationData)",
));
}
check_window(
"NotBefore",
assertion.conditions().not_before(),
skew,
&now_ts,
WindowBound::NotBefore,
"saml: assertion not yet valid",
)?;
check_window(
"NotOnOrAfter",
assertion.conditions().not_on_or_after(),
skew,
&now_ts,
WindowBound::NotOnOrAfter,
"saml: assertion expired",
)?;
// SubjectConfirmationData/@NotOnOrAfter is the (usually tighter)
// delivery deadline for the assertion. Enforce it the same way as the
// Conditions deadline so a captured assertion can't be delivered late.
check_window(
"SubjectConfirmationData/NotOnOrAfter",
assertion.subject().confirmation_not_on_or_after(),
skew,
&now_ts,
WindowBound::NotOnOrAfter,
"saml: subject confirmation expired",
)?;
Ok(())
}
/// Build a `SamlResponse` from a parsed XML element tree.
fn from_element(root: &XmlElement) -> Result<Self, SamlResponseError> {
// SECURITY: the root must actually BE a samlp:Response. Version, ID,
// IssueInstant and a Status child were all validated while the element
// name and namespace were not, so any same-shaped document was
// accepted as a Response. Mirrors the root check in `idp.rs`.
if root.name() != "Response" || root.namespace().is_some_and(|ns| ns != SAMLP_NS) {
return Err(SamlResponseError::missing_element("Response"));
}
// SECURITY: `Version="2.0"` is mandatory (SAML Core §3.2.2). Reject a
// missing or mismatched version rather than processing a document of
// an unknown SAML version, consistent with the crate's fail-closed
// posture on every other structurally-required attribute.
if root.attribute("Version") != Some("2.0") {
return Err(SamlResponseError::new(
SamlResponseErrorKind::InvalidVersion("Response".to_string()),
));
}
// Response attributes.
let id = root
.attribute("ID")
.ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::MissingElement(
"Response/@ID".to_string(),
))
})?
.to_string();
let issue_instant = root
.attribute("IssueInstant")
.ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::MissingElement(
"Response/@IssueInstant".to_string(),
))
})?
.to_string();
let destination = root.attribute("Destination").map(String::from);
// Response-level Issuer (optional; SAML Core §3.2.2). Distinct from the
// assertion Issuer. Parsed and exposed so the caller — and
// `validate_conditions_only` — can cross-check it; an attacker shaping
// the unsigned envelope can set it arbitrarily, so validating it when
// present is defense-in-depth alongside the (caller-verified) signature.
let issuer = find_response_issuer(root).and_then(|el| el.text_content().map(String::from));
// Status
let status_el = find_protocol_child(root, "Status").ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::MissingElement("Status".to_string()))
})?;
let status_code_el = find_protocol_child(status_el, "StatusCode").ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::MissingElement(
"StatusCode".to_string(),
))
})?;
let status_value = status_code_el.attribute("Value").ok_or_else(|| {
SamlResponseError::new(SamlResponseErrorKind::MissingElement(
"StatusCode/@Value".to_string(),
))
})?;
let status = match status_value {
STATUS_SUCCESS => SamlStatus::Success,
STATUS_REQUESTER => SamlStatus::Requester,
STATUS_RESPONDER => SamlStatus::Responder,
STATUS_VERSION_MISMATCH => SamlStatus::VersionMismatch,
other => SamlStatus::Unknown(other.to_string()),
};
// Assertions. SECURITY: fail closed — a malformed assertion is a
// hard error, not a silently-dropped one. Dropping it could leave a
// response that parsed structurally but carries no usable subject,
// which a caller might misread as a benign empty result.
let mut assertions = Vec::new();
// SECURITY: match `Assertion` only in the SAML namespace (or no
// namespace) — never a foreign namespace — so an injected
// `<evil:Assertion>` decoy cannot be smuggled into the set.
let assertion_els: Vec<_> = root
.children()
.iter()
.filter(|c| c.name() == "Assertion" && c.namespace().is_none_or(|ns| ns == SAML_NS))
.collect();
for a_el in assertion_els {
assertions.push(parse_assertion(a_el)?);
}
Ok(Self {
id,
issue_instant,
destination,
issuer,
status,
assertions,
})
}
}
/// Find a child in the SAML protocol namespace (or `SAML_NS`, or no
/// namespace), never a foreign namespace — see [`find_response_issuer`] for
/// the rationale behind rejecting foreign-namespaced decoys.
fn find_protocol_child<'a>(parent: &'a XmlElement, local_name: &str) -> Option<&'a XmlElement> {
parent.children().iter().find(|c| {
c.name() == local_name
&& c.namespace()
.is_none_or(|ns| ns == SAMLP_NS || ns == SAML_NS)
})
}
/// Find the Response-level `<Issuer>` (SAML assertion namespace, or no
/// namespace). A foreign namespace is not matched, mirroring the
/// signature-wrapping defense applied to the assertion-level lookups.
fn find_response_issuer(parent: &XmlElement) -> Option<&XmlElement> {
parent
.children()
.iter()
.find(|c| c.name() == "Issuer" && c.namespace().is_none_or(|ns| ns == SAML_NS))
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
fn sample_response_xml() -> String {
// NOTE: Temporal conditions use a far-past NotBefore and far-future
// NotOnOrAfter so that validation passes regardless of wall-clock time.
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_resp123"
IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_assert456" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AttributeStatement>
<saml:Attribute Name="email">
<saml:AttributeValue>user@example.com</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>"#.to_string()
}
fn test_config() -> SamlConfig {
SamlConfig::new(
"https://sp.example.com",
"https://sp.example.com/acs",
"https://idp.example.com/sso",
"https://idp.example.com",
)
.unwrap()
}
// -- Response parsing -------------------------------------------------
#[test]
fn parse_valid_response() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
assert_eq!(resp.id(), "_resp123");
assert_eq!(resp.issue_instant(), "2025-01-15T12:00:00Z");
assert_eq!(resp.destination(), Some("https://sp.example.com/acs"));
assert_eq!(*resp.status(), SamlStatus::Success);
}
#[test]
fn parse_response_assertions() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
assert_eq!(resp.assertions().len(), 1);
let assertion = &resp.assertions()[0];
assert_eq!(assertion.issuer(), "https://idp.example.com");
assert_eq!(assertion.subject().name_id(), "user@example.com");
}
#[test]
fn parse_response_status_codes() {
let make_response = |status: &str| {
format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
ID="_r1" IssueInstant="2025-01-01T00:00:00Z">
<samlp:Status>
<samlp:StatusCode Value="{status}"/>
</samlp:Status>
</samlp:Response>"#
)
};
let resp = SamlResponse::parse_xml_unverified(&make_response(STATUS_SUCCESS)).unwrap();
assert_eq!(*resp.status(), SamlStatus::Success);
let resp = SamlResponse::parse_xml_unverified(&make_response(STATUS_REQUESTER)).unwrap();
assert_eq!(*resp.status(), SamlStatus::Requester);
let resp = SamlResponse::parse_xml_unverified(&make_response(STATUS_RESPONDER)).unwrap();
assert_eq!(*resp.status(), SamlStatus::Responder);
let resp =
SamlResponse::parse_xml_unverified(&make_response(STATUS_VERSION_MISMATCH)).unwrap();
assert_eq!(*resp.status(), SamlStatus::VersionMismatch);
}
// -- Base64 decoding --------------------------------------------------
#[test]
fn parse_base64_response() {
let xml = sample_response_xml();
let encoded = crate::encoding::base64_encode(xml.as_bytes());
let resp = SamlResponse::parse_base64_unverified(&encoded).unwrap();
assert_eq!(resp.id(), "_resp123");
assert_eq!(*resp.status(), SamlStatus::Success);
}
#[test]
fn parse_base64_invalid() {
let err = SamlResponse::parse_base64_unverified("not-valid-base64!!!").unwrap_err();
assert!(err.is_base64_decode());
}
#[test]
fn parse_base64_rejects_embedded_whitespace() {
// The pre-decode size bound (MAX_ENCODED_LEN) relies on the decoder
// rejecting embedded whitespace so encoded length tracks decoded
// length. Pin that invariant: base64 with interior whitespace/newlines
// must be rejected, not silently accepted (which a future
// whitespace-tolerant decoder would do, breaking the bound).
let xml = sample_response_xml();
let encoded = crate::encoding::base64_encode(xml.as_bytes());
let with_ws = format!("{}\n{}", &encoded[..8], &encoded[8..]);
let err = SamlResponse::parse_base64_unverified(&with_ws).unwrap_err();
assert!(err.is_base64_decode());
}
#[test]
fn parse_base64_oversized_input_rejected_before_decode() {
// An input larger than the base64 expansion of MAX_XML_SIZE must be
// rejected up front, without allocating the decoded buffer.
let oversized = "A".repeat(crate::xml::MAX_XML_SIZE / 3 * 4 + 8);
let err = SamlResponse::parse_base64_unverified(&oversized).unwrap_err();
assert!(err.is_xml_parse());
}
#[test]
fn parse_base64_invalid_utf8_is_distinct_error() {
// Valid base64 that decodes to non-UTF-8 bytes reports InvalidUtf8,
// not a (misleading) base64 decode error.
let encoded = crate::encoding::base64_encode(&[0xff, 0xfe, 0xfd]);
let err = SamlResponse::parse_base64_unverified(&encoded).unwrap_err();
assert!(err.is_invalid_utf8());
assert!(!err.is_base64_decode());
}
// -- Validation -------------------------------------------------------
#[test]
fn validate_success() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn validate_rejects_response_issuer_mismatch() {
// A Response-level <Issuer> that is not the configured IdP is rejected.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<saml:Issuer>https://evil.example.com</saml:Issuer>
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction><saml:Audience>https://sp.example.com</saml:Audience></saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
assert_eq!(resp.issuer(), Some("https://evil.example.com"));
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_issuer_mismatch(), "got: {err}");
}
#[test]
fn validate_accepts_matching_response_issuer() {
let xml = sample_response_xml().replace(
"<saml:Assertion",
"<saml:Issuer>https://idp.example.com</saml:Issuer><saml:Assertion",
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
assert_eq!(resp.issuer(), Some("https://idp.example.com"));
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn non_bearer_subject_confirmation_is_ignored() {
// A holder-of-key confirmation (explicitly non-bearer) carrying a
// mismatched Recipient must NOT be treated as the bearer binding —
// its Recipient is skipped, so validation does not fail on it.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:holder-of-key">
<saml:SubjectConfirmationData Recipient="https://evil.example.com/acs"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction><saml:Audience>https://sp.example.com</saml:Audience></saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
// The non-bearer confirmation's Recipient was ignored (None), so no
// recipient-mismatch failure.
assert_eq!(resp.assertions()[0].subject().recipient(), None);
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn foreign_namespace_assertion_is_not_collected() {
// An <evil:Assertion> in a non-SAML namespace must not be picked up as
// a real assertion (signature-wrapping decoy).
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:evil="urn:evil"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z">
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<evil:Assertion ID="_a1"><evil:Issuer>x</evil:Issuer></evil:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
assert_eq!(resp.assertions().len(), 0);
// With no usable assertion, validation fails closed.
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_no_assertions(), "got: {err}");
}
#[test]
fn validate_requires_sp_in_every_audience_restriction() {
// Two AudienceRestrictions: the SP is in the first but not the second.
// SAML Core §2.5.1.4 requires the SP in EVERY restriction, so this is
// rejected (the issuer scoped the assertion to the intersection).
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction><saml:Audience>https://sp.example.com</saml:Audience></saml:AudienceRestriction>
<saml:AudienceRestriction><saml:Audience>https://other.example.com</saml:Audience></saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_audience_mismatch(), "got: {err}");
}
#[test]
fn validate_accepts_sp_in_all_restrictions_with_multiple_audiences() {
// SP present in every restriction (OR within each) → accepted.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject><saml:NameID>user@example.com</saml:NameID></saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://other.example.com</saml:Audience>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
<saml:AudienceRestriction><saml:Audience>https://sp.example.com</saml:Audience></saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn validate_destination_mismatch() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
let cfg = SamlConfig::new(
"https://sp.example.com",
"https://other.example.com/acs",
"https://idp.example.com/sso",
"https://idp.example.com",
)
.unwrap();
let err = resp.validate_conditions_only(&cfg).unwrap_err();
assert!(err.is_destination_mismatch());
}
#[test]
fn validate_issuer_mismatch() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
let cfg = SamlConfig::new(
"https://sp.example.com",
"https://sp.example.com/acs",
"https://idp.example.com/sso",
"https://other-idp.example.com",
)
.unwrap();
let err = resp.validate_conditions_only(&cfg).unwrap_err();
assert!(err.is_issuer_mismatch());
}
#[test]
fn validate_audience_mismatch() {
let resp = SamlResponse::parse_xml_unverified(&sample_response_xml()).unwrap();
let cfg = SamlConfig::new(
"https://wrong-sp.example.com",
"https://sp.example.com/acs",
"https://idp.example.com/sso",
"https://idp.example.com",
)
.unwrap();
let err = resp.validate_conditions_only(&cfg).unwrap_err();
assert!(err.is_audience_mismatch());
}
#[test]
fn validate_non_success_status() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
ID="_r1" IssueInstant="2025-01-01T00:00:00Z">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Responder"/>
</samlp:Status>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_non_success_status());
assert!(
err.to_string().contains("Responder"),
"expected Responder in message, got: {err}",
);
}
// -- Hardening: no assertions / absent audience / recipient (H6/H7/H8) -
#[test]
fn validate_rejects_zero_assertion_success_response() {
// A Success response with no assertion must NOT validate.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
ID="_r1" IssueInstant="2025-01-01T00:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_no_assertions(), "expected NoAssertions, got: {err}");
}
#[test]
fn validate_rejects_absent_audience_restriction() {
// An assertion with NO AudienceRestriction must be rejected, not
// treated as valid for every SP.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z"/>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(
err.is_audience_mismatch(),
"expected AudienceMismatch, got: {err}"
);
}
#[test]
fn validate_rejects_recipient_mismatch() {
// A SubjectConfirmationData Recipient that is not our ACS URL fails.
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData Recipient="https://evil.example.com/acs"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(
err.is_recipient_mismatch(),
"expected RecipientMismatch, got: {err}"
);
}
#[test]
fn validate_accepts_matching_recipient_and_exposes_in_response_to() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
<saml:SubjectConfirmation>
<saml:SubjectConfirmationData Recipient="https://sp.example.com/acs" InResponseTo="_req42" NotOnOrAfter="2099-12-31T23:59:59Z"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
resp.validate_conditions_only(&test_config()).unwrap();
assert_eq!(
resp.assertions()[0].subject().in_response_to(),
Some("_req42"),
);
}
// -- XML parse errors -------------------------------------------------
#[test]
fn parse_invalid_xml_returns_xml_parse_error() {
let err = SamlResponse::parse_xml_unverified("<<<not xml>>>").unwrap_err();
assert!(err.is_xml_parse());
}
// -- Missing elements -------------------------------------------------
#[test]
fn parse_missing_id() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
IssueInstant="2025-01-01T00:00:00Z">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
</samlp:Response>"#;
let err = SamlResponse::parse_xml_unverified(xml).unwrap_err();
assert!(err.is_missing_element());
}
// -- Temporal validation -----------------------------------------------
#[test]
fn validate_expired_assertion() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="2020-01-01T00:00:01Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_expired(), "expected Expired, got: {err}");
}
#[test]
fn validate_not_yet_valid_assertion() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2099-12-31T23:59:59Z" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_not_yet_valid(), "expected NotYetValid, got: {err}");
}
#[test]
fn parse_response_unknown_status_code() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
ID="_r1" IssueInstant="2025-01-01T00:00:00Z">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:CustomError"/>
</samlp:Status>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
assert!(matches!(resp.status(), SamlStatus::Unknown(_)));
}
// -- SamlStatus Display ------------------------------------------------
#[test]
fn status_display_success() {
assert_eq!(SamlStatus::Success.to_string(), "Success");
}
#[test]
fn status_display_requester() {
assert_eq!(SamlStatus::Requester.to_string(), "Requester");
}
#[test]
fn status_display_responder() {
assert_eq!(SamlStatus::Responder.to_string(), "Responder");
}
#[test]
fn status_display_version_mismatch() {
assert_eq!(SamlStatus::VersionMismatch.to_string(), "VersionMismatch");
}
// -- Invalid timestamp (H3) --------------------------------------------
#[test]
fn validate_invalid_not_before_timestamp() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="not-a-timestamp" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(
err.is_invalid_timestamp(),
"expected InvalidTimestamp, got: {err}",
);
assert!(err.to_string().contains("NotBefore"), "got: {err}");
assert!(err.to_string().contains("not-a-timestamp"), "got: {err}");
}
#[test]
fn validate_invalid_not_on_or_after_timestamp() {
let xml = r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="garbage">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#;
let resp = SamlResponse::parse_xml_unverified(xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(
err.is_invalid_timestamp(),
"expected InvalidTimestamp, got: {err}",
);
assert!(err.to_string().contains("NotOnOrAfter"), "got: {err}");
assert!(err.to_string().contains("garbage"), "got: {err}");
}
// -- Clock skew tolerance (M4) -----------------------------------------
#[test]
fn validate_expired_within_skew_tolerance_passes() {
// An assertion whose NotOnOrAfter is 30 seconds in the past should
// still validate with the default 60-second skew tolerance.
let now = Timestamp::now();
let expired_30s_ago = now.unix_epoch_secs().saturating_sub(30);
let ts = Timestamp::from_unix_secs(expired_30s_ago);
let not_on_or_after = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second(),
);
let xml = format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="{not_on_or_after}">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
// Default clock_skew_secs=60 should tolerate 30s of drift.
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn validate_expired_beyond_skew_tolerance_fails() {
// An assertion whose NotOnOrAfter is 120 seconds in the past should
// fail even with the default 60-second skew tolerance.
let now = Timestamp::now();
let expired_120s_ago = now.unix_epoch_secs().saturating_sub(120);
let ts = Timestamp::from_unix_secs(expired_120s_ago);
let not_on_or_after = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second(),
);
let xml = format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="{not_on_or_after}">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_expired(), "expected Expired, got: {err}");
}
#[test]
fn validate_zero_skew_rejects_any_drift() {
// With clock_skew_secs=0, even 1 second past NotOnOrAfter should fail.
let now = Timestamp::now();
let expired_2s_ago = now.unix_epoch_secs().saturating_sub(2);
let ts = Timestamp::from_unix_secs(expired_2s_ago);
let not_on_or_after = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second(),
);
let xml = format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="2020-01-01T00:00:00Z" NotOnOrAfter="{not_on_or_after}">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
let cfg = test_config().with_clock_skew_secs(0);
let err = resp.validate_conditions_only(&cfg).unwrap_err();
assert!(err.is_expired(), "expected Expired, got: {err}");
}
#[test]
fn validate_not_before_within_skew_tolerance_passes() {
// An assertion whose NotBefore is 30 seconds in the future should
// still validate with the default 60-second skew tolerance.
let now = Timestamp::now();
let future_30s = now.unix_epoch_secs().saturating_add(30);
let ts = Timestamp::from_unix_secs(future_30s);
let not_before = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second(),
);
let xml = format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="{not_before}" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
// Default clock_skew_secs=60 should tolerate 30s of drift.
resp.validate_conditions_only(&test_config()).unwrap();
}
#[test]
fn validate_not_before_beyond_skew_tolerance_fails() {
// An assertion whose NotBefore is 120 seconds in the future should
// fail even with the default 60-second skew tolerance.
let now = Timestamp::now();
let future_120s = now.unix_epoch_secs().saturating_add(120);
let ts = Timestamp::from_unix_secs(future_120s);
let not_before = format!(
"{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
ts.year(),
ts.month(),
ts.day(),
ts.hour(),
ts.minute(),
ts.second(),
);
let xml = format!(
r#"<samlp:Response Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
ID="_r1" IssueInstant="2025-01-15T12:00:00Z"
Destination="https://sp.example.com/acs">
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion Version="2.0" ID="_a1" IssueInstant="2025-01-15T12:00:00Z">
<saml:Issuer>https://idp.example.com</saml:Issuer>
<saml:Subject>
<saml:NameID>user@example.com</saml:NameID>
</saml:Subject>
<saml:Conditions NotBefore="{not_before}" NotOnOrAfter="2099-12-31T23:59:59Z">
<saml:AudienceRestriction>
<saml:Audience>https://sp.example.com</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
</saml:Assertion>
</samlp:Response>"#
);
let resp = SamlResponse::parse_xml_unverified(&xml).unwrap();
let err = resp.validate_conditions_only(&test_config()).unwrap_err();
assert!(err.is_not_yet_valid(), "expected NotYetValid, got: {err}");
}
}