gamlastan 0.9.0

SAML 2.0 library - types, XML, crypto, metadata, bindings, security, profiles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
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
//! IdP attribute release policy engine.
//!
//! [`ReleasePolicy`] is the PySAML2 `Policy` analogue. It holds per-SP entries,
//! registration-authority entries, and a `default` entry. Each entry can
//! constrain:
//!
//! - which attributes, and optionally which values, are released;
//! - entity-category based release through [`crate::idp::entity_category`];
//! - assertion lifetime;
//! - NameID format and attribute NameFormat;
//! - signing behavior for response/assertion/on-demand signing;
//! - whether missing SP-required attributes are an error.
//!
//! Attribute names are matched on local names, case-insensitively, resolved
//! through [`crate::attribute_map::AttributeConverterSet`] so OIDs and local
//! names can meet at a single policy surface.

use std::collections::HashMap;

use chrono::{DateTime, TimeDelta, Utc};
use regex::Regex;

use crate::attribute_map::AttributeConverterSet;
use crate::core::assertion::attribute::{Attribute, AttributeValue};
use crate::core::constants;
use crate::idp::entity_category::{
    releasable_attributes_owned, EntityCategoryPolicy, OwnedEntityCategoryPolicy, SubjectIdReq,
};
use crate::metadata::types::entity_descriptor::EntityDescriptor;
use crate::metadata::types::sp::{RequestedAttribute, SpSsoDescriptor};

/// Errors raised by policy evaluation.
#[derive(Debug, thiserror::Error)]
pub enum PolicyError {
    /// A required attribute is missing (pysaml2 `MissingValue`).
    #[error("required attribute missing: '{0}'")]
    MissingRequiredAttribute(String),

    /// A required attribute value is missing (pysaml2 `MissingValue`).
    #[error("required value missing for attribute '{attribute}'")]
    MissingRequiredValue {
        /// The attribute whose required values could not be satisfied.
        attribute: String,
    },

    /// An attribute value restriction pattern failed to compile.
    #[error("invalid restriction pattern '{pattern}': {message}")]
    InvalidPattern {
        /// The offending pattern.
        pattern: String,
        /// The regex error.
        message: String,
    },
}

/// Which messages the IdP signs for an SP (`"sign"` in pysaml2 policy).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SignTargets {
    /// Always sign the Response envelope.
    pub response: bool,
    /// Always sign the Assertion.
    pub assertion: bool,
    /// Sign the assertion when the SP asks for it (`WantAssertionsSigned`
    /// in SP metadata) — pysaml2's `"on_demand"`.
    pub on_demand: bool,
}

impl SignTargets {
    /// Resolve the on-demand part against the SP's metadata flag.
    pub fn resolve(self, sp_wants_assertions_signed: bool) -> ResolvedSignTargets {
        ResolvedSignTargets {
            sign_response: self.response,
            sign_assertion: self.assertion || (self.on_demand && sp_wants_assertions_signed),
        }
    }
}

/// The concrete signing decision for one response.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedSignTargets {
    /// Sign the Response envelope.
    pub sign_response: bool,
    /// Sign the Assertion.
    pub sign_assertion: bool,
}

/// Per-value restriction: `None` releases any value, otherwise a value is
/// released when at least one regex matches at the start of the value
/// (Python `re.match` semantics).
type ValueRestriction = Option<Vec<Regex>>;

/// One policy entry (per SP, or the `default`).
#[derive(Debug, Clone, Default)]
pub struct PolicyEntry {
    attribute_restrictions: Option<HashMap<String, ValueRestriction>>,
    lifetime: Option<TimeDelta>,
    nameid_format: Option<String>,
    name_form: Option<String>,
    sign: Option<SignTargets>,
    fail_on_missing_requested: Option<bool>,
    entity_categories: Option<Vec<OwnedEntityCategoryPolicy>>,
}

impl PolicyEntry {
    /// Create an empty entry (everything inherited / default).
    pub fn new() -> Self {
        PolicyEntry::default()
    }

    /// Restrict release to the given attributes. Each `(name, patterns)`
    /// pair names a local attribute (case-insensitive) and optionally a
    /// list of value patterns (anchored at the start of the value, like
    /// Python's `re.match`); `None` releases all values.
    pub fn with_attribute_restrictions(
        mut self,
        restrictions: &[(&str, Option<&[&str]>)],
    ) -> Result<Self, PolicyError> {
        let mut map = HashMap::new();
        for (name, patterns) in restrictions {
            let compiled = match patterns {
                None => None,
                Some(pats) => {
                    let mut regexes = Vec::with_capacity(pats.len());
                    for pat in *pats {
                        let anchored = format!("^(?:{pat})");
                        regexes.push(Regex::new(&anchored).map_err(|e| {
                            PolicyError::InvalidPattern {
                                pattern: (*pat).to_string(),
                                message: e.to_string(),
                            }
                        })?);
                    }
                    Some(regexes)
                }
            };
            map.insert(name.to_lowercase(), compiled);
        }
        self.attribute_restrictions = Some(map);
        Ok(self)
    }

    /// Set the assertion lifetime.
    pub fn with_lifetime(mut self, lifetime: TimeDelta) -> Self {
        self.lifetime = Some(lifetime);
        self
    }

    /// Set the NameID format issued to this SP.
    pub fn with_nameid_format(mut self, format: impl Into<String>) -> Self {
        self.nameid_format = Some(format.into());
        self
    }

    /// Set the attribute NameFormat used in assertions for this SP.
    pub fn with_name_form(mut self, name_form: impl Into<String>) -> Self {
        self.name_form = Some(name_form.into());
        self
    }

    /// Set the signing targets.
    pub fn with_sign(mut self, sign: SignTargets) -> Self {
        self.sign = Some(sign);
        self
    }

    /// Set whether missing SP-required attributes abort response building.
    pub fn with_fail_on_missing_requested(mut self, fail: bool) -> Self {
        self.fail_on_missing_requested = Some(fail);
        self
    }

    /// Enable entity-category based release with the given shipped policies
    /// (e.g. [`crate::idp::entity_category::SWAMID`]). Each is cloned into its
    /// owned form; to mix in deployment-defined categories use
    /// [`PolicyEntry::with_owned_entity_categories`].
    pub fn with_entity_categories(mut self, policies: Vec<&'static EntityCategoryPolicy>) -> Self {
        self.entity_categories = Some(policies.iter().map(|p| p.as_owned()).collect());
        self
    }

    /// Enable entity-category based release with caller-built, runtime
    /// [`OwnedEntityCategoryPolicy`] values - the path for developer-defined
    /// custom entity categories. Start from scratch with
    /// [`OwnedEntityCategoryPolicy::new`], or extend a shipped policy with
    /// [`OwnedEntityCategoryPolicy::extend_from_static`].
    pub fn with_owned_entity_categories(
        mut self,
        policies: Vec<OwnedEntityCategoryPolicy>,
    ) -> Self {
        self.entity_categories = Some(policies);
        self
    }
}

/// The IdP-side attribute release policy (pysaml2 `Policy`).
///
/// Entry resolution per knob: the SP-specific entry first; if the SP has no
/// entry of its own, the entry keyed on its registration authority (when one is
/// recorded, see [`ReleasePolicy::set_registration_authority`]); then
/// `"default"`; then a built-in default (transient NameID, URI name format, 1h
/// lifetime, no signing, fail on missing required attributes). An SP that has
/// its own entry is unaffected by the registration-authority entry (ADR 0027).
#[derive(Debug, Default)]
pub struct ReleasePolicy {
    entries: HashMap<String, PolicyEntry>,
    converters: AttributeConverterSet,
    /// SP entity ID -> its `registrationAuthority`. When an SP has no entry of
    /// its own, policy resolution falls back to the entry keyed on its
    /// registration authority (pysaml2 `Policy.get`: SP > registration
    /// authority > default) before the global `default`.
    registration_authorities: HashMap<String, String>,
    /// pysaml2-compatibility switch for attribute-release matching. Default
    /// `false` (the secure default): an SP-supplied `RequestedAttribute` is
    /// matched only by its trusted converter mapping or its exact wire `Name`,
    /// never by its non-unique, attacker-controllable `FriendlyName`
    /// (Finding #7, ADR 0032). Set `true` (see
    /// [`allow_friendly_name_release_matching`](ReleasePolicy::allow_friendly_name_release_matching))
    /// to restore strict pysaml2 behaviour, where an unmappable `Name` falls
    /// back to `FriendlyName` for matching (pysaml2 `_identify_attribute`).
    allow_friendly_name_match: bool,
}

/// The key under which the fallback entry is stored.
pub const DEFAULT_ENTRY: &str = "default";

impl ReleasePolicy {
    /// An empty policy (built-in defaults for every SP).
    pub fn new() -> Self {
        ReleasePolicy {
            entries: HashMap::new(),
            converters: AttributeConverterSet::with_default_maps(),
            registration_authorities: HashMap::new(),
            allow_friendly_name_match: false,
        }
    }

    /// Create a policy with a `default` entry.
    pub fn with_default(entry: PolicyEntry) -> Self {
        let mut policy = ReleasePolicy::new();
        policy.entries.insert(DEFAULT_ENTRY.to_string(), entry);
        policy
    }

    /// Add or replace the entry for an SP entity ID (or `"default"`).
    pub fn insert(&mut self, sp_entity_id: impl Into<String>, entry: PolicyEntry) {
        self.entries.insert(sp_entity_id.into(), entry);
    }

    /// Use a custom attribute converter set for local-name resolution.
    pub fn with_converters(mut self, converters: AttributeConverterSet) -> Self {
        self.converters = converters;
        self
    }

    /// Enable strict pysaml2-compatible attribute-release matching (builder
    /// style). **Off by default**, and you should leave it off unless migrating
    /// a deployment that depends on the legacy behaviour.
    ///
    /// With the flag **off** (default, secure — ADR 0032), an SP's
    /// `RequestedAttribute` is matched against the IdP's held attributes only by
    /// its trusted converter mapping or its exact wire `Name`. The SP-supplied
    /// `FriendlyName` is never used as a match key, so it cannot serve as an
    /// attribute-release authorization token (Finding #7).
    ///
    /// With the flag **on**, an SP `RequestedAttribute` whose `Name`/`NameFormat`
    /// cannot be resolved through the configured converters falls back to
    /// matching on its `FriendlyName`, reproducing pysaml2's `_identify_attribute`
    /// (`src/saml2/assertion.py`) behaviour added in pysaml2 7.1.2. This is
    /// required only for SPs that request **unmapped** attributes and rely on the
    /// `FriendlyName` to bind to a locally-keyed held attribute. Enabling it
    /// re-opens the Finding #7 surface: a non-unique, attacker-controllable
    /// `FriendlyName` becomes sufficient to request a locally-mapped attribute,
    /// so use it only when the SP metadata feed is trusted.
    ///
    /// # Examples
    ///
    /// ```
    /// # use gamlastan::idp::policy::ReleasePolicy;
    /// // Strict pysaml2 parity for a migration where SPs request unmapped
    /// // attributes by FriendlyName:
    /// let policy = ReleasePolicy::new().allow_friendly_name_release_matching(true);
    /// ```
    pub fn allow_friendly_name_release_matching(mut self, allow: bool) -> Self {
        self.allow_friendly_name_match = allow;
        self
    }

    /// Record an SP's `registrationAuthority` so policy resolution can fall back
    /// to a per-registration-authority entry (keyed on the authority URI) when
    /// the SP has no entry of its own.
    pub fn set_registration_authority(
        &mut self,
        sp_entity_id: impl Into<String>,
        registration_authority: impl Into<String>,
    ) {
        self.registration_authorities
            .insert(sp_entity_id.into(), registration_authority.into());
    }

    /// Builder form of [`ReleasePolicy::set_registration_authority`].
    pub fn with_registration_authority(
        mut self,
        sp_entity_id: impl Into<String>,
        registration_authority: impl Into<String>,
    ) -> Self {
        self.set_registration_authority(sp_entity_id, registration_authority);
        self
    }

    /// Record an SP's registration authority straight from its metadata (reads
    /// `mdrpi:RegistrationInfo/@registrationAuthority`). No-op when the metadata
    /// declares none.
    pub fn register_sp_metadata(&mut self, entity: &EntityDescriptor) {
        if let Some(ra) = entity.registration_authority() {
            self.set_registration_authority(entity.entity_id.clone(), ra);
        }
    }

    /// Resolve a knob: SP entry first, then the SP's registration-authority
    /// entry, then `default` (pysaml2 `Policy.get` precedence).
    fn get<T, F: Fn(&PolicyEntry) -> Option<T>>(&self, sp_entity_id: &str, f: F) -> Option<T> {
        self.get_ref(sp_entity_id, f)
    }

    /// Borrowing form of [`ReleasePolicy::get`]: resolves with the same
    /// SP > registration authority > default precedence but lets `f` return a
    /// borrow into the resolved [`PolicyEntry`], so large fields (the owned
    /// entity-category policies, the restriction map) are read by reference
    /// instead of cloned on every request.
    fn get_ref<'a, T, F: Fn(&'a PolicyEntry) -> Option<T>>(
        &'a self,
        sp_entity_id: &str,
        f: F,
    ) -> Option<T> {
        let sp_entry = self.entries.get(sp_entity_id);

        // The registration-authority entry is consulted only when the SP has
        // *no entry of its own* - an SP with its own entry is unaffected by it
        // (ADR 0027), so a knob the SP leaves unset falls straight through to
        // `default`/built-in rather than to the registration-authority entry.
        if sp_entry.is_none() {
            if let Some(value) = self
                .registration_authorities
                .get(sp_entity_id)
                .and_then(|ra| self.entries.get(ra))
                .and_then(&f)
            {
                return Some(value);
            }
        }

        sp_entry
            .and_then(&f)
            .or_else(|| self.entries.get(DEFAULT_ENTRY).and_then(&f))
    }

    /// NameID format for the SP (default: transient).
    pub fn nameid_format(&self, sp_entity_id: &str) -> String {
        self.get(sp_entity_id, |e| e.nameid_format.clone())
            .unwrap_or_else(|| constants::NAMEID_TRANSIENT.to_string())
    }

    /// Attribute NameFormat for the SP (default: URI).
    pub fn name_form(&self, sp_entity_id: &str) -> String {
        self.get(sp_entity_id, |e| e.name_form.clone())
            .unwrap_or_else(|| constants::ATTRNAME_FORMAT_URI.to_string())
    }

    /// Assertion lifetime for the SP (default: 1 hour).
    pub fn lifetime(&self, sp_entity_id: &str) -> TimeDelta {
        self.get(sp_entity_id, |e| e.lifetime)
            .unwrap_or_else(|| TimeDelta::hours(1))
    }

    /// Assertion NotOnOrAfter for the SP (pysaml2 `not_on_or_after`).
    pub fn not_on_or_after(&self, sp_entity_id: &str, now: DateTime<Utc>) -> DateTime<Utc> {
        now + self.lifetime(sp_entity_id)
    }

    /// Signing targets for the SP (default: nothing).
    pub fn sign(&self, sp_entity_id: &str) -> SignTargets {
        self.get(sp_entity_id, |e| e.sign).unwrap_or_default()
    }

    /// Whether a missing required attribute is an error (default: true).
    pub fn fail_on_missing_requested(&self, sp_entity_id: &str) -> bool {
        self.get(sp_entity_id, |e| e.fail_on_missing_requested)
            .unwrap_or(true)
    }

    /// The local (lowercased) name of a wire attribute.
    ///
    /// Used for *held* attributes (the IdP's own, trusted data), where the
    /// `FriendlyName` fallback in [`AttributeMap::local_name`] is acceptable.
    /// For matching an SP-supplied `RequestedAttribute`, use
    /// [`trusted_local_key`](Self::trusted_local_key) instead.
    fn local_key(&self, attribute: &Attribute) -> String {
        self.converters
            .local_name(attribute)
            .unwrap_or_else(|| attribute.name.clone())
            .to_lowercase()
    }

    /// The trusted local key of a wire attribute: its local name resolved
    /// through registered converters only, lowercased; `None` when no converter
    /// maps it.
    ///
    /// Unlike [`local_key`](Self::local_key) this never derives the key from the
    /// attribute's `FriendlyName`, so an untrusted, non-unique SP-supplied
    /// `FriendlyName` cannot be used as an attribute-release authorization key
    /// (Finding #7, CWE-345). Release matching keys the *requested* attribute on
    /// this value (or, failing that, the exact wire `Name`).
    fn trusted_local_key(&self, attribute: &Attribute) -> Option<String> {
        self.converters
            .local_name_via_converters(attribute)
            .map(|name| name.to_lowercase())
    }

    /// The local match key for an SP-supplied `RequestedAttribute`.
    ///
    /// Always the trusted converter mapping when one resolves. When
    /// [`allow_friendly_name_match`](ReleasePolicy::allow_friendly_name_match) is
    /// set (pysaml2-compat, off by default), an unmappable attribute falls back
    /// to its `FriendlyName` — mirroring pysaml2's
    /// `local_name = get_local_name(...) or friendly_name`. With the flag off the
    /// `FriendlyName` is never used, so it cannot authorize release (Finding #7,
    /// ADR 0032).
    fn requested_match_key(&self, attribute: &Attribute) -> Option<String> {
        self.trusted_local_key(attribute).or_else(|| {
            self.allow_friendly_name_match
                .then(|| attribute.friendly_name.clone())
                .flatten()
                .map(|friendly| friendly.to_lowercase())
        })
    }

    fn matching_requested_attribute(
        &self,
        attributes: &[Attribute],
        requested: &RequestedAttribute,
    ) -> Option<Attribute> {
        // Resolve the requested attribute to a match key. By default this is the
        // trusted converter mapping only — never its SP-supplied FriendlyName
        // (Finding #7). A request matches a held attribute by that key or by exact
        // wire Name. With the pysaml2-compat flag set, an unmappable Name may fall
        // back to its FriendlyName (see `requested_match_key`).
        let req_local = self.requested_match_key(&requested.attribute);
        let req_wire = requested.attribute.name.to_lowercase();

        // Assertion parsing does not merge duplicate Attribute elements,
        // so collect every input attribute mapping to this requested name
        // (by local or wire name) rather than just the first.
        let mut matched = attributes.iter().filter(|attr| {
            req_local
                .as_ref()
                .is_some_and(|rl| &self.local_key(attr) == rl)
                || attr.name.to_lowercase() == req_wire
        });

        let mut released = matched.next()?.clone();
        for extra in matched {
            for v in &extra.values {
                if !released.values.contains(v) {
                    released.values.push(v.clone());
                }
            }
        }

        Some(released)
    }

    fn validate_required_attributes(
        &self,
        attributes: &[Attribute],
        required: &[RequestedAttribute],
    ) -> Result<(), PolicyError> {
        for requested in required {
            let Some(mut matched) = self.matching_requested_attribute(attributes, requested) else {
                return Err(PolicyError::MissingRequiredAttribute(
                    requested.attribute.name.clone(),
                ));
            };

            let wanted: Vec<String> = requested
                .attribute
                .values
                .iter()
                .filter_map(value_text)
                .collect();
            if !wanted.is_empty() {
                matched
                    .values
                    .retain(|v| value_text(v).is_some_and(|t| wanted.contains(&t)));
                if matched.values.is_empty() {
                    return Err(PolicyError::MissingRequiredValue {
                        attribute: requested.attribute.name.clone(),
                    });
                }
            }
        }

        Ok(())
    }

    /// Filter attributes for release to `sp_entity_id`
    /// (pysaml2 `Policy.filter`).
    ///
    /// Pipeline:
    /// 1. entity-category release rules, when configured for this SP
    ///    (`sp_entity_categories` are the SP's published categories);
    /// 2. otherwise, required/optional matching against the SP's
    ///    `RequestedAttribute`s (honoring `fail_on_missing_requested`);
    /// 3. the entry's attribute/value restrictions;
    /// 4. subject-id / pairwise-id mutual exclusion when the SP's
    ///    `subject-id:req` is `any` (pysaml2 PR #987).
    ///
    /// `subject_id_req` is the SP's requested subject identifier, read from its
    /// `subject-id:req` metadata entity attribute
    /// (see [`SubjectIdReq::from_metadata_values`]).
    pub fn filter(
        &self,
        attributes: Vec<Attribute>,
        sp_entity_id: &str,
        sp_entity_categories: &[String],
        required: &[RequestedAttribute],
        optional: &[RequestedAttribute],
        subject_id_req: SubjectIdReq,
    ) -> Result<Vec<Attribute>, PolicyError> {
        let mut result = attributes;
        let fail_on_missing_requested = self.fail_on_missing_requested(sp_entity_id);

        // Step 1: entity-category release rules take precedence over
        // per-attribute requested/optional matching when configured. Borrow the
        // resolved policy set rather than cloning it on every request.
        let categories = self.get_ref(sp_entity_id, |e| e.entity_categories.as_deref());
        if let Some(policies) = categories {
            // Key the SP's required attributes for the entity-category release
            // set on their trusted local mapping and exact wire Name (and, only
            // under the pysaml2-compat flag, their FriendlyName) — by default
            // never the SP-supplied FriendlyName (Finding #7), otherwise the same
            // FriendlyName confusion could steer which category attributes are
            // released. Extra wire-name keys are harmless: they only match held
            // attributes that genuinely carry that Name.
            let required_local: Vec<String> = required
                .iter()
                .flat_map(|r| {
                    self.requested_match_key(&r.attribute)
                        .into_iter()
                        .chain(std::iter::once(r.attribute.name.to_lowercase()))
                })
                .collect();
            let released =
                releasable_attributes_owned(policies, sp_entity_categories, &required_local);
            result.retain(|attr| released.contains(&self.local_key(attr)));
        } else if !required.is_empty() || !optional.is_empty() {
            // Step 2: release only what the SP asked for in its
            // AttributeConsumingService (or the explicit lists given here).
            result =
                self.filter_on_attributes(result, required, optional, fail_on_missing_requested)?;
        }

        // Step 3: the IdP's own attribute/value restrictions always apply.
        if let Some(restrictions) =
            self.get_ref(sp_entity_id, |e| e.attribute_restrictions.as_ref())
        {
            result = self.filter_attribute_value_assertions(result, restrictions);
        }

        // Step 4: pysaml2 PR #987 — when the SP requests subject-id with
        // requirement "any" and both subject-id and pairwise-id are about to be
        // released, keep only the privacy-preserving pairwise-id. Other
        // metadata values are intentionally left unchanged; the profile defines
        // the signal but leaves asserting-party response unspecified.
        if subject_id_req == SubjectIdReq::Any {
            let mut has_subject_id = false;
            let mut has_pairwise_id = false;

            for attr in &result {
                match self.local_key(attr).as_str() {
                    "subject-id" => has_subject_id = true,
                    "pairwise-id" => has_pairwise_id = true,
                    _ => {}
                }

                if has_subject_id && has_pairwise_id {
                    break;
                }
            }

            if has_subject_id && has_pairwise_id {
                result.retain(|a| self.local_key(a) != "subject-id");
            }
        }

        if fail_on_missing_requested && !required.is_empty() {
            self.validate_required_attributes(&result, required)?;
        }

        Ok(result)
    }

    /// Filter against the SP's metadata-declared attribute requirements
    /// (pysaml2 `Policy.restrict`).
    ///
    /// Extracts required/optional `RequestedAttribute`s from the SP's
    /// `AttributeConsumingService` (the indexed one when `acs_index` is
    /// given, else the default) and calls [`ReleasePolicy::filter`].
    pub fn restrict(
        &self,
        attributes: Vec<Attribute>,
        sp_entity_id: &str,
        sp_metadata: Option<&SpSsoDescriptor>,
        sp_entity_categories: &[String],
        acs_index: Option<u16>,
        subject_id_req: SubjectIdReq,
    ) -> Result<Vec<Attribute>, PolicyError> {
        let (required, optional) = match sp_metadata {
            Some(sp) => sp_attribute_requirements(sp, acs_index),
            None => (vec![], vec![]),
        };
        self.filter(
            attributes,
            sp_entity_id,
            sp_entity_categories,
            &required,
            &optional,
            subject_id_req,
        )
    }

    /// Match attributes against required/optional `RequestedAttribute`s
    /// (pysaml2 `filter_on_attributes`). Only requested attributes are
    /// released; requested values (when present) narrow the released values.
    pub fn filter_on_attributes(
        &self,
        attributes: Vec<Attribute>,
        required: &[RequestedAttribute],
        optional: &[RequestedAttribute],
        fail_on_unfulfilled: bool,
    ) -> Result<Vec<Attribute>, PolicyError> {
        let mut result: Vec<Attribute> = Vec::new();

        for (requested, must) in required
            .iter()
            .map(|r| (r, true))
            .chain(optional.iter().map(|r| (r, false)))
        {
            let Some(mut released) = self.matching_requested_attribute(&attributes, requested)
            else {
                if must && fail_on_unfulfilled {
                    return Err(PolicyError::MissingRequiredAttribute(
                        requested.attribute.name.clone(),
                    ));
                }
                continue;
            };

            let wanted: Vec<String> = requested
                .attribute
                .values
                .iter()
                .filter_map(value_text)
                .collect();
            if !wanted.is_empty() {
                released
                    .values
                    .retain(|v| value_text(v).is_some_and(|t| wanted.contains(&t)));
                if must && released.values.is_empty() {
                    return Err(PolicyError::MissingRequiredValue {
                        attribute: requested.attribute.name.clone(),
                    });
                }
            }

            // Merge duplicate RequestedAttribute entries for the same
            // attribute instead of releasing it twice.
            match result
                .iter_mut()
                .find(|a| self.local_key(a) == self.local_key(&released))
            {
                Some(existing) => {
                    for v in released.values {
                        if !existing.values.contains(&v) {
                            existing.values.push(v);
                        }
                    }
                }
                None => result.push(released),
            }
        }

        Ok(result)
    }

    /// Apply attribute/value restrictions (pysaml2
    /// `filter_attribute_value_assertions`): attributes not named are
    /// dropped; a `None` restriction keeps all values; regex restrictions
    /// keep matching values and drop the attribute if none remain.
    pub fn filter_attribute_value_assertions(
        &self,
        attributes: Vec<Attribute>,
        restrictions: &HashMap<String, ValueRestriction>,
    ) -> Vec<Attribute> {
        let mut result = Vec::new();
        for mut attr in attributes {
            // Attributes not named in the restrictions map are never released.
            let Some(restriction) = restrictions.get(&self.local_key(&attr)) else {
                continue;
            };
            match restriction {
                None => result.push(attr),
                Some(regexes) => {
                    attr.values.retain(|v| {
                        value_text(v).is_some_and(|t| regexes.iter().any(|re| re.is_match(&t)))
                    });
                    dedup_values(&mut attr.values);
                    if !attr.values.is_empty() {
                        result.push(attr);
                    }
                }
            }
        }
        result
    }

    /// Release no more than the receiver asked for (pysaml2
    /// `filter_on_demands`): every required attribute (and value) must be
    /// present, and everything not required or optional is dropped.
    ///
    /// `required`/`optional` map local names to required values.
    pub fn filter_on_demands(
        &self,
        mut attributes: Vec<Attribute>,
        required: &HashMap<String, Vec<String>>,
        optional: &HashMap<String, Vec<String>>,
    ) -> Result<Vec<Attribute>, PolicyError> {
        for (name, values) in required {
            let key = name.to_lowercase();
            let Some(attr) = attributes.iter().find(|a| self.local_key(a) == key) else {
                return Err(PolicyError::MissingRequiredAttribute(name.clone()));
            };
            let have: Vec<String> = attr.values.iter().filter_map(value_text).collect();
            for v in values {
                if !have.contains(v) {
                    return Err(PolicyError::MissingRequiredValue {
                        attribute: name.clone(),
                    });
                }
            }
        }

        let allowed: Vec<String> = required
            .keys()
            .chain(optional.keys())
            .map(|k| k.to_lowercase())
            .collect();
        attributes.retain(|a| allowed.contains(&self.local_key(a)));
        Ok(attributes)
    }

    /// Keep only attributes whose wire representation the SP asked for
    /// (pysaml2 `filter_on_wire_representation`).
    pub fn filter_on_wire_representation(
        &self,
        attributes: Vec<Attribute>,
        required: &[Attribute],
        optional: &[Attribute],
    ) -> Vec<Attribute> {
        attributes
            .into_iter()
            .filter(|attr| {
                required
                    .iter()
                    .chain(optional.iter())
                    .any(|req| req.name.eq_ignore_ascii_case(&attr.name))
            })
            .collect()
    }
}

/// Extract (required, optional) `RequestedAttribute`s from the SP's
/// `AttributeConsumingService` (pysaml2 `Server.wants` /
/// `attribute_requirement`).
///
/// Selects the service with the given index, else the default one, else the
/// lowest index.
pub fn sp_attribute_requirements(
    sp: &SpSsoDescriptor,
    index: Option<u16>,
) -> (Vec<RequestedAttribute>, Vec<RequestedAttribute>) {
    let services = &sp.attribute_consuming_services;
    let service = match index {
        Some(i) => services.iter().find(|s| s.index == i),
        None => services
            .iter()
            .find(|s| s.is_default == Some(true))
            .or_else(|| services.iter().min_by_key(|s| s.index)),
    };

    let Some(service) = service else {
        return (vec![], vec![]);
    };

    let (required, optional): (Vec<_>, Vec<_>) = service
        .requested_attributes
        .iter()
        .cloned()
        .partition(|ra| ra.is_required == Some(true));
    (required, optional)
}

/// Textual rendering of an attribute value for comparison/matching.
fn value_text(value: &AttributeValue) -> Option<String> {
    match value {
        AttributeValue::String(s) => Some(s.clone()),
        AttributeValue::Integer(i) => Some(i.to_string()),
        AttributeValue::Boolean(b) => Some(b.to_string()),
        AttributeValue::DateTime(s) => Some(s.clone()),
        AttributeValue::NameId(n) => Some(n.value.clone()),
        AttributeValue::Base64(_) | AttributeValue::Xml(_) | AttributeValue::Null => None,
    }
}

fn dedup_values(values: &mut Vec<AttributeValue>) {
    let mut seen: Vec<AttributeValue> = Vec::new();
    values.retain(|v| {
        if seen.contains(v) {
            false
        } else {
            seen.push(v.clone());
            true
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::idp::entity_category::{COCO_V1, EDUGAIN, REFEDS, REFEDS_RESEARCH_AND_SCHOLARSHIP};
    use crate::profiles::attribute::x500::{eppn_attribute, mail_attribute};

    fn requested(name: &str, friendly: Option<&str>, required: bool) -> RequestedAttribute {
        RequestedAttribute {
            attribute: Attribute {
                name: name.to_string(),
                name_format: Some(constants::ATTRNAME_FORMAT_URI.to_string()),
                friendly_name: friendly.map(str::to_string),
                values: vec![],
            },
            is_required: Some(required),
        }
    }

    fn requested_with_values(
        name: &str,
        friendly: Option<&str>,
        required: bool,
        values: &[&str],
    ) -> RequestedAttribute {
        RequestedAttribute {
            attribute: Attribute {
                name: name.to_string(),
                name_format: Some(constants::ATTRNAME_FORMAT_URI.to_string()),
                friendly_name: friendly.map(str::to_string),
                values: values
                    .iter()
                    .map(|value| AttributeValue::String((*value).to_string()))
                    .collect(),
            },
            is_required: Some(required),
        }
    }

    #[test]
    fn test_friendly_name_cannot_authorize_release() {
        // Finding #7 regression: an SP must not be able to obtain a
        // locally-mapped attribute by placing its local name in the (untrusted,
        // non-unique) FriendlyName of a RequestedAttribute whose wire Name does
        // not map. Only the correct wire Name (or a converter-mapped Name)
        // releases the attribute.
        let policy = ReleasePolicy::new();
        let held = vec![mail_attribute(&["alice@example.com"])];

        // Attack: bogus, unmapped wire Name; FriendlyName falsely claims "mail".
        let attack = requested("urn:example:not-a-real-attribute", Some("mail"), true);
        let out = policy
            .filter_on_attributes(held.clone(), std::slice::from_ref(&attack), &[], false)
            .unwrap();
        assert!(
            out.is_empty(),
            "FriendlyName must not authorize release of a differently-named attribute; got {out:?}"
        );

        // Legit: naming the attribute by its actual wire Name still releases it.
        let legit = requested(&mail_attribute(&[]).name, Some("mail"), true);
        let out = policy
            .filter_on_attributes(held, std::slice::from_ref(&legit), &[], false)
            .unwrap();
        assert_eq!(
            out.len(),
            1,
            "the correct wire Name must still release the attribute"
        );
    }

    #[test]
    fn test_friendly_name_release_matching_pysaml2_compat() {
        // ADR 0032 opt-in: with the pysaml2-compatibility flag enabled, an SP
        // that requests an *unmapped* Name and relies on FriendlyName to bind to
        // a held attribute is matched (pysaml2 `_identify_attribute`). The secure
        // default rejects exactly the same request.
        let held = vec![mail_attribute(&["alice@example.com"])];
        // Unmappable wire Name; the FriendlyName names the held "mail" attribute.
        let req = requested("urn:myown:unmapped", Some("mail"), true);

        // Default (secure): the FriendlyName cannot authorize release.
        let strict = ReleasePolicy::new();
        assert!(
            strict
                .filter_on_attributes(held.clone(), std::slice::from_ref(&req), &[], false)
                .unwrap()
                .is_empty(),
            "default policy must not match by FriendlyName"
        );

        // pysaml2-compat: the unmappable Name falls back to FriendlyName matching.
        let compat = ReleasePolicy::new().allow_friendly_name_release_matching(true);
        let out = compat
            .filter_on_attributes(held, std::slice::from_ref(&req), &[], false)
            .unwrap();
        assert_eq!(out.len(), 1, "pysaml2-compat must match by FriendlyName");
    }

    #[test]
    fn test_defaults() {
        let policy = ReleasePolicy::new();
        assert_eq!(
            policy.nameid_format("https://sp.example.com"),
            constants::NAMEID_TRANSIENT
        );
        assert_eq!(
            policy.name_form("https://sp.example.com"),
            constants::ATTRNAME_FORMAT_URI
        );
        assert_eq!(
            policy.lifetime("https://sp.example.com"),
            TimeDelta::hours(1)
        );
        assert!(policy.fail_on_missing_requested("https://sp.example.com"));
        assert_eq!(
            policy.sign("https://sp.example.com"),
            SignTargets::default()
        );
    }

    #[test]
    fn test_entry_resolution_sp_overrides_default() {
        let mut policy = ReleasePolicy::with_default(
            PolicyEntry::new().with_nameid_format(constants::NAMEID_PERSISTENT),
        );
        policy.insert(
            "https://sp2.example.com",
            PolicyEntry::new().with_nameid_format(constants::NAMEID_EMAIL),
        );

        assert_eq!(
            policy.nameid_format("https://sp1.example.com"),
            constants::NAMEID_PERSISTENT
        );
        assert_eq!(
            policy.nameid_format("https://sp2.example.com"),
            constants::NAMEID_EMAIL
        );
    }

    #[test]
    fn test_attribute_restrictions_value_regex() {
        let policy = ReleasePolicy::with_default(
            PolicyEntry::new()
                .with_attribute_restrictions(&[
                    ("mail", Some(&[r".*@example\.com"])),
                    ("givenName", None),
                ])
                .unwrap(),
        );

        let attrs = vec![
            mail_attribute(&["alice@example.com", "alice@evil.org"]),
            eppn_attribute("alice@example.com"),
        ];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &[],
                &[],
                &[],
                SubjectIdReq::None,
            )
            .unwrap();

        // eppn is not listed -> dropped; mail keeps only the matching value
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].friendly_name.as_deref(), Some("mail"));
        assert_eq!(out[0].values.len(), 1);
        assert_eq!(out[0].values[0].as_str(), Some("alice@example.com"));
    }

    #[test]
    fn test_regex_is_anchored_like_python_match() {
        let policy = ReleasePolicy::with_default(
            PolicyEntry::new()
                .with_attribute_restrictions(&[("mail", Some(&["alice"]))])
                .unwrap(),
        );
        let attrs = vec![mail_attribute(&["alice@example.com", "malice@example.com"])];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &[],
                &[],
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        // re.match semantics: only values starting with "alice"
        assert_eq!(out[0].values.len(), 1);
        assert_eq!(out[0].values[0].as_str(), Some("alice@example.com"));
    }

    #[test]
    fn test_filter_on_attributes_required_missing_fails() {
        let policy = ReleasePolicy::new();
        let required = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
        )];
        let err = policy
            .filter(
                vec![eppn_attribute("a@example.org")],
                "https://sp.example.com",
                &[],
                &required,
                &[],
                SubjectIdReq::None,
            )
            .unwrap_err();
        assert!(matches!(err, PolicyError::MissingRequiredAttribute(_)));
    }

    #[test]
    fn test_filter_on_attributes_releases_only_requested() {
        let policy = ReleasePolicy::new();
        let required = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
        )];
        let optional = vec![requested(
            "urn:oid:1.3.6.1.4.1.5923.1.1.1.6",
            None, // resolved through the shipped saml_uri map
            false,
        )];
        let attrs = vec![
            mail_attribute(&["a@example.com"]),
            eppn_attribute("a@example.org"),
            crate::profiles::attribute::x500::cn_attribute(&["Alice"]),
        ];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &[],
                &required,
                &optional,
                SubjectIdReq::None,
            )
            .unwrap();
        let names: Vec<_> = out
            .iter()
            .map(|a| a.friendly_name.clone().unwrap_or_default())
            .collect();
        assert_eq!(out.len(), 2);
        assert!(names.contains(&"mail".to_string()));
        assert!(names.contains(&"eduPersonPrincipalName".to_string()));
    }

    #[test]
    fn test_filter_on_attributes_unions_duplicate_input_attributes() {
        // Two separate Attribute elements both mapping to `mail` (assertion
        // parsing does not merge them) must contribute all their values.
        let policy = ReleasePolicy::new();
        let optional = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            false,
        )];
        let attrs = vec![
            mail_attribute(&["alice@example.com"]),
            mail_attribute(&["alice@work.example"]),
        ];
        let out = policy
            .filter_on_attributes(attrs, &[], &optional, false)
            .unwrap();
        assert_eq!(out.len(), 1);
        let vals: Vec<&str> = out[0].values.iter().filter_map(|v| v.as_str()).collect();
        assert_eq!(vals, vec!["alice@example.com", "alice@work.example"]);
    }

    #[test]
    fn test_filter_no_fail_when_disabled() {
        let policy =
            ReleasePolicy::with_default(PolicyEntry::new().with_fail_on_missing_requested(false));
        let required = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
        )];
        let out = policy
            .filter(
                vec![],
                "https://sp.example.com",
                &[],
                &required,
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn test_filter_rechecks_required_attributes_after_restrictions() {
        let policy = ReleasePolicy::with_default(
            PolicyEntry::new()
                .with_attribute_restrictions(&[("mail", Some(&[r".*@other\.example"]))])
                .unwrap(),
        );
        let required = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
        )];

        let err = policy
            .filter(
                vec![mail_attribute(&["alice@example.com"])],
                "https://sp.example.com",
                &[],
                &required,
                &[],
                SubjectIdReq::None,
            )
            .unwrap_err();

        assert!(matches!(
            err,
            PolicyError::MissingRequiredAttribute(ref attribute)
                if attribute == "urn:oid:0.9.2342.19200300.100.1.3"
        ));
    }

    #[test]
    fn test_filter_rechecks_required_values_after_entity_category_restrictions() {
        let policy = ReleasePolicy::with_default(
            PolicyEntry::new()
                .with_entity_categories(vec![&REFEDS])
                .with_attribute_restrictions(&[("mail", Some(&[r".*@work\.example"]))])
                .unwrap(),
        );
        let required = vec![requested_with_values(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
            &["alice@example.com"],
        )];

        let err = policy
            .filter(
                vec![mail_attribute(&["alice@example.com", "alice@work.example"])],
                "https://sp.example.com",
                &[REFEDS_RESEARCH_AND_SCHOLARSHIP.to_string()],
                &required,
                &[],
                SubjectIdReq::None,
            )
            .unwrap_err();

        assert!(matches!(
            err,
            PolicyError::MissingRequiredValue { ref attribute }
                if attribute == "urn:oid:0.9.2342.19200300.100.1.3"
        ));
    }

    #[test]
    fn test_entity_category_release_refeds() {
        let policy =
            ReleasePolicy::with_default(PolicyEntry::new().with_entity_categories(vec![&REFEDS]));
        let attrs = vec![
            mail_attribute(&["a@example.com"]),
            crate::profiles::attribute::x500::cn_attribute(&["Alice"]),
        ];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &[REFEDS_RESEARCH_AND_SCHOLARSHIP.to_string()],
                &[],
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        // mail is in R&S, cn is not
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].friendly_name.as_deref(), Some("mail"));
    }

    #[test]
    fn test_entity_category_coco_only_required() {
        let policy =
            ReleasePolicy::with_default(PolicyEntry::new().with_entity_categories(vec![&EDUGAIN]));
        let required = vec![requested(
            "urn:oid:0.9.2342.19200300.100.1.3",
            Some("mail"),
            true,
        )];
        let attrs = vec![
            mail_attribute(&["a@example.com"]),
            eppn_attribute("a@example.org"),
        ];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &[COCO_V1.to_string()],
                &required,
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        // CoCo + only_required: eppn (not required by the SP) is withheld
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].friendly_name.as_deref(), Some("mail"));
    }

    #[test]
    fn test_registration_authority_resolution_precedence() {
        // default releases nothing extra; the registration-authority entry
        // signs responses; the SP-specific entry overrides the RA entry.
        let mut policy = ReleasePolicy::new();
        policy.insert(
            DEFAULT_ENTRY,
            PolicyEntry::new().with_lifetime(TimeDelta::hours(1)),
        );
        policy.insert(
            "http://www.swamid.se/",
            PolicyEntry::new().with_lifetime(TimeDelta::minutes(10)),
        );
        policy.insert(
            "https://special.example.com",
            PolicyEntry::new().with_lifetime(TimeDelta::minutes(5)),
        );

        // SP with a SWAMID registration authority but no own entry -> RA entry.
        policy.set_registration_authority("https://sp.swamid.example", "http://www.swamid.se/");
        assert_eq!(
            policy.lifetime("https://sp.swamid.example"),
            TimeDelta::minutes(10)
        );

        // SP with its own entry -> own entry wins over the RA entry.
        policy.set_registration_authority("https://special.example.com", "http://www.swamid.se/");
        assert_eq!(
            policy.lifetime("https://special.example.com"),
            TimeDelta::minutes(5)
        );

        // SP with an unknown registration authority -> falls through to default.
        policy.set_registration_authority("https://other.example", "http://other.federation/");
        assert_eq!(
            policy.lifetime("https://other.example"),
            TimeDelta::hours(1)
        );
    }

    #[test]
    fn test_registration_authority_not_consulted_when_sp_has_entry() {
        // An SP with its own entry is unaffected by the registration-authority
        // entry (ADR 0027): a knob it leaves unset falls through to `default`,
        // not to the RA entry, even though the SP is mapped to that authority.
        let mut policy = ReleasePolicy::new();
        policy.insert(
            DEFAULT_ENTRY,
            PolicyEntry::new().with_lifetime(TimeDelta::hours(1)),
        );
        policy.insert(
            "http://www.swamid.se/",
            PolicyEntry::new().with_lifetime(TimeDelta::minutes(10)),
        );
        // SP entry exists but sets only the NameID format, not the lifetime.
        policy.insert(
            "https://sp.swamid.example",
            PolicyEntry::new().with_nameid_format(constants::NAMEID_PERSISTENT),
        );
        policy.set_registration_authority("https://sp.swamid.example", "http://www.swamid.se/");

        // Its own knob is honored.
        assert_eq!(
            policy.nameid_format("https://sp.swamid.example"),
            constants::NAMEID_PERSISTENT
        );
        // The unset lifetime falls through to `default` (1h), NOT the RA's 10m.
        assert_eq!(
            policy.lifetime("https://sp.swamid.example"),
            TimeDelta::hours(1)
        );
    }

    #[test]
    fn test_register_sp_metadata_reads_registration_authority() {
        use crate::metadata::types::entity_descriptor::{EntityDescriptor, EntityRoles};
        use crate::metadata::types::extensions::Extensions;

        let entity = EntityDescriptor {
            entity_id: "https://sp.swamid.example".to_string(),
            id: None,
            valid_until: None,
            cache_duration: None,
            has_signature: false,
            extensions: Some(Extensions::new(
                r#"<mdrpi:RegistrationInfo xmlns:mdrpi="urn:oasis:names:tc:SAML:metadata:rpi" registrationAuthority="http://www.swamid.se/"/>"#
                    .to_string(),
            )),
            roles: EntityRoles::Roles {
                idp_sso: vec![],
                sp_sso: vec![],
                authn_authority: vec![],
                attr_authority: vec![],
                pdp: vec![],
            },
            organization: None,
            contact_persons: vec![],
            additional_metadata_locations: vec![],
        };

        let mut policy = ReleasePolicy::new();
        policy.insert(
            "http://www.swamid.se/",
            PolicyEntry::new().with_lifetime(TimeDelta::minutes(10)),
        );
        policy.register_sp_metadata(&entity);
        assert_eq!(
            policy.lifetime("https://sp.swamid.example"),
            TimeDelta::minutes(10)
        );
    }

    #[test]
    fn test_custom_owned_entity_category_release() {
        use crate::idp::entity_category::{OwnedEntityCategoryPolicy, OwnedEntityCategoryRule};

        // A deployment-defined entity category, built entirely at runtime.
        let custom = OwnedEntityCategoryPolicy::new("eduid-local").with_rule(
            OwnedEntityCategoryRule::new(["https://eduid.se/category/staff"], ["mail"]),
        );
        let policy = ReleasePolicy::with_default(
            PolicyEntry::new().with_owned_entity_categories(vec![custom]),
        );
        let attrs = vec![
            mail_attribute(&["a@example.com"]),
            crate::profiles::attribute::x500::cn_attribute(&["Alice"]),
        ];
        let out = policy
            .filter(
                attrs,
                "https://sp.example.com",
                &["https://eduid.se/category/staff".to_string()],
                &[],
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].friendly_name.as_deref(), Some("mail"));
    }

    fn subject_identifier(name: &str, friendly: &str, value: &str) -> Attribute {
        Attribute {
            name: name.to_string(),
            name_format: Some(constants::ATTRNAME_FORMAT_URI.to_string()),
            friendly_name: Some(friendly.to_string()),
            values: vec![AttributeValue::String(value.to_string())],
        }
    }

    #[test]
    fn test_subject_id_req_any_prefers_pairwise() {
        use crate::idp::entity_category::{PAIRWISE_ID_ATTR, SUBJECT_ID_ATTR};
        let policy = ReleasePolicy::new();
        let attrs = || {
            vec![
                subject_identifier(SUBJECT_ID_ATTR, "subject-id", "alice@example.com"),
                subject_identifier(PAIRWISE_ID_ATTR, "pairwise-id", "opaque@example.com"),
                mail_attribute(&["alice@example.com"]),
            ]
        };

        // req == any: subject-id dropped, pairwise-id (and mail) kept.
        let out = policy
            .filter(
                attrs(),
                "https://sp.example.com",
                &[],
                &[],
                &[],
                SubjectIdReq::Any,
            )
            .unwrap();
        let names: Vec<_> = out.iter().filter_map(|a| a.friendly_name.clone()).collect();
        assert!(names.contains(&"pairwise-id".to_string()));
        assert!(names.contains(&"mail".to_string()));
        assert!(!names.contains(&"subject-id".to_string()));

        // Non-`any` leaves the release set unchanged by design: the metadata
        // signal does not define asserting-party behavior for those values.
        let out = policy
            .filter(
                attrs(),
                "https://sp.example.com",
                &[],
                &[],
                &[],
                SubjectIdReq::None,
            )
            .unwrap();
        assert_eq!(out.len(), 3);
    }

    #[test]
    fn test_subject_id_req_any_keeps_lone_subject_id() {
        use crate::idp::entity_category::SUBJECT_ID_ATTR;
        let policy = ReleasePolicy::new();
        // Only subject-id present: nothing to prefer, so it is kept.
        let out = policy
            .filter(
                vec![subject_identifier(
                    SUBJECT_ID_ATTR,
                    "subject-id",
                    "alice@example.com",
                )],
                "https://sp.example.com",
                &[],
                &[],
                &[],
                SubjectIdReq::Any,
            )
            .unwrap();
        assert_eq!(out.len(), 1);
        assert_eq!(out[0].friendly_name.as_deref(), Some("subject-id"));
    }

    #[test]
    fn test_sign_targets_on_demand() {
        let targets = SignTargets {
            response: true,
            assertion: false,
            on_demand: true,
        };
        let resolved = targets.resolve(true);
        assert!(resolved.sign_response);
        assert!(resolved.sign_assertion);
        let resolved = targets.resolve(false);
        assert!(!resolved.sign_assertion);
    }

    #[test]
    fn test_filter_on_demands() {
        let policy = ReleasePolicy::new();
        let mut required = HashMap::new();
        required.insert("mail".to_string(), vec!["a@example.com".to_string()]);
        let optional = HashMap::new();

        let attrs = vec![
            mail_attribute(&["a@example.com"]),
            eppn_attribute("a@example.org"),
        ];
        let out = policy
            .filter_on_demands(attrs.clone(), &required, &optional)
            .unwrap();
        assert_eq!(out.len(), 1);

        let mut bad = HashMap::new();
        bad.insert("mail".to_string(), vec!["other@example.com".to_string()]);
        assert!(policy.filter_on_demands(attrs, &bad, &optional).is_err());
    }

    #[test]
    fn test_invalid_pattern_is_error() {
        let err = PolicyEntry::new()
            .with_attribute_restrictions(&[("mail", Some(&["("]))])
            .unwrap_err();
        assert!(matches!(err, PolicyError::InvalidPattern { .. }));
    }
}