entropy-auth 2026.7.31

Authentication and authorization for Entropy Softworks server and API projects
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
//! SAML 2.0 **Identity Provider** side: build a signed `<Response>` /
//! `<Assertion>`, generate IdP metadata, and parse an `<AuthnRequest>`.
//!
//! The crate's SP side ([`super::response`]) parses + validates responses; this
//! is the mirror the IdP needs to ISSUE them. It is transport- and
//! storage-free: the caller supplies the request context + pre-formatted
//! timestamps + a signing key, and gets back XML.
//!
//! # XML signing
//!
//! Signing uses an **enveloped** XML-DSig ([w3.org XML-DSig]) over the
//! `<Assertion>` (the SAML-standard "sign the assertion" mode), with
//! **exclusive canonicalization** ([xml-exc-c14n]) and SHA-256 digests,
//! signed with the deployment's existing asymmetric key (EdDSA / ES256 — the
//! same keys the OIDC JWKS publishes). Rather than canonicalize a parsed tree
//! (a signature-wrapping minefield), the builder EMITS already-canonical XML:
//! every element is written with sorted namespace declarations + sorted
//! attributes, explicit close tags, and C14N escaping, so the produced bytes
//! ARE their own exclusive-C14N form. `<Assertion>` uses the assertion
//! namespace as the default (no prefix); `<ds:Signature>` and `<ds:SignedInfo>`
//! each carry the `ds` declaration so each is stable when canonicalized as a
//! standalone subtree.
//!
//! # Security
//!
//! * The `<ds:Signature>` is inserted as a single contiguous block right after
//!   `<Issuer>`; the digest is computed over the assertion BEFORE insertion
//!   (the enveloped-signature transform), and [`verify_signed_response`]
//!   removes exactly that block to recover the digested bytes.
//! * [`verify_signed_response`] is the in-crate self-check: it re-derives the
//!   digest and verifies the signature with the public key. Interop with a
//!   third-party SP's own canonicalizer is validated separately (deferred).
//!
//! [w3.org XML-DSig]: https://www.w3.org/TR/xmldsig-core/
//! [xml-exc-c14n]: https://www.w3.org/TR/xml-exc-c14n/

// The SAML prose here is dense with proper protocol terms (IdP, NameID,
// AuthnRequest, SignatureValue, InResponseTo, …) that read correctly without
// backticks; blanket doc-backticking them would hurt legibility.
#![allow(clippy::doc_markdown)]

use core::fmt;

use crate::crypto::Sha256;
use crate::encoding::{base64_decode, base64_encode};
use crate::jwt::{AsymmetricAlgorithm, AsymmetricSigningKey, AsymmetricVerifyingKey};
use crate::xml::{XmlElement, parse_xml};

const NS_ASSERTION: &str = "urn:oasis:names:tc:SAML:2.0:assertion";
const NS_PROTOCOL: &str = "urn:oasis:names:tc:SAML:2.0:protocol";
const NS_METADATA: &str = "urn:oasis:names:tc:SAML:2.0:metadata";
const NS_DSIG: &str = "http://www.w3.org/2000/09/xmldsig#";
const C14N_EXCLUSIVE: &str = "http://www.w3.org/2001/10/xml-exc-c14n#";
const TRANSFORM_ENVELOPED: &str = "http://www.w3.org/2000/09/xmldsig#enveloped-signature";
const DIGEST_SHA256: &str = "http://www.w3.org/2001/04/xmlenc#sha256";
const STATUS_SUCCESS: &str = "urn:oasis:names:tc:SAML:2.0:status:Success";
const BINDING_POST: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";

// ---------------------------------------------------------------------------
// Canonical XML escaping helpers (exclusive C14N)
// ---------------------------------------------------------------------------

/// Escape a text node per C14N: `&`, `<`, `>` and CR.
fn canon_text(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '\r' => out.push_str("&#xD;"),
            _ => out.push(c),
        }
    }
    out
}

/// Escape an attribute value per C14N: `&`, `<`, `"`, and TAB/LF/CR.
/// Render `Name="value" ` (with a trailing space) for a non-empty value, or an
/// empty string so the attribute is OMITTED entirely. SAML unsolicited /
/// IdP-initiated responses must omit `InResponseTo` rather than emit an empty
/// one — an empty string is not equivalent to absence and strict SPs reject it.
/// The caller places this immediately before the next (alphabetically later)
/// attribute so canonical attribute ordering is preserved.
fn opt_attr(name: &str, value: &str) -> String {
    if value.is_empty() {
        String::new()
    } else {
        format!(r#"{name}="{}" "#, canon_attr(value))
    }
}

fn canon_attr(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '"' => out.push_str("&quot;"),
            '\t' => out.push_str("&#x9;"),
            '\n' => out.push_str("&#xA;"),
            '\r' => out.push_str("&#xD;"),
            _ => out.push(c),
        }
    }
    out
}

/// The XML-DSig `SignatureMethod` algorithm URI for a signing key.
fn signature_method(alg: AsymmetricAlgorithm) -> &'static str {
    match alg {
        AsymmetricAlgorithm::Es256 => "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256",
        AsymmetricAlgorithm::EdDsa => "http://www.w3.org/2001/04/xmldsig-more#eddsa",
        // RSA is verify-only in this crate; the IdP never signs with it, so the
        // RSA-SHA256 URI is only a nominal fallback for the exhaustiveness of
        // this (#[non_exhaustive]) enum.
        _ => "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256",
    }
}

// ---------------------------------------------------------------------------
// Builder inputs
// ---------------------------------------------------------------------------

/// The claims for a single SAML `<Assertion>`. Timestamps are pre-formatted
/// ISO-8601 UTC strings (`2024-01-01T00:00:00Z`) — the crate is time-source
/// free, so the caller formats them.
#[derive(Debug, Clone)]
pub struct AssertionParams<'a> {
    /// Unique assertion `ID` (must start with a letter/underscore per xsd:ID).
    pub id: &'a str,
    /// The IdP entity id (`<Issuer>`).
    pub issuer: &'a str,
    /// `IssueInstant`.
    pub issue_instant: &'a str,
    /// The authenticated user's `NameID` value.
    pub subject_name_id: &'a str,
    /// The `NameID` `Format` URI.
    pub subject_name_id_format: &'a str,
    /// The SP's original `AuthnRequest` `ID` (`InResponseTo`).
    pub in_response_to: &'a str,
    /// The SP's ACS URL (subject-confirmation `Recipient`).
    pub recipient: &'a str,
    /// `Conditions/@NotBefore`.
    pub not_before: &'a str,
    /// `Conditions/@NotOnOrAfter` (also the subject-confirmation deadline).
    pub not_on_or_after: &'a str,
    /// The SP entity id (`<AudienceRestriction>`).
    pub audience: &'a str,
    /// `AuthnStatement/@AuthnInstant`.
    pub authn_instant: &'a str,
    /// `AuthnStatement/@SessionIndex`.
    pub session_index: &'a str,
    /// Attribute `(Name, Value)` pairs for the `<AttributeStatement>`.
    /// Attribute `(Name, values)` pairs. SAML attributes are multi-valued
    /// (`<Attribute>` holds zero or more `<AttributeValue>`), so a set-valued
    /// claim like `roles` must emit one element per value — flattening it into
    /// a single delimited string forces every SP to guess the delimiter, and
    /// emitting an empty `<AttributeValue>` for an empty set asserts "one
    /// blank value" rather than "no values". An attribute with no values is
    /// omitted entirely.
    pub attributes: &'a [(&'a str, &'a [&'a str])],
}

/// The envelope for a SAML `<Response>` carrying one signed assertion.
#[derive(Debug, Clone)]
pub struct ResponseParams<'a> {
    /// Unique response `ID`.
    pub id: &'a str,
    /// `IssueInstant`.
    pub issue_instant: &'a str,
    /// `Destination` (the SP ACS URL the response is POSTed to).
    pub destination: &'a str,
    /// The SP's `AuthnRequest` `ID` (`InResponseTo`).
    pub in_response_to: &'a str,
    /// The IdP entity id (`<Issuer>`).
    pub issuer: &'a str,
}

// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------

/// A failure building or verifying a SAML IdP artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SamlIdpError {
    /// The signed document is structurally malformed (missing element).
    Malformed(&'static str),
    /// A base64 field (`SignatureValue`/`DigestValue`) did not decode.
    BadEncoding,
    /// The recomputed digest did not match `DigestValue`.
    DigestMismatch,
    /// The signature did not verify against the key.
    SignatureInvalid,
}

impl fmt::Display for SamlIdpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Malformed(what) => write!(f, "malformed signed document: {what}"),
            Self::BadEncoding => write!(f, "invalid base64 in signature/digest"),
            Self::DigestMismatch => write!(f, "assertion digest mismatch"),
            Self::SignatureInvalid => write!(f, "signature verification failed"),
        }
    }
}

impl std::error::Error for SamlIdpError {}

// ---------------------------------------------------------------------------
// Assertion + Response building
// ---------------------------------------------------------------------------

/// Emit the canonical `<Assertion>` WITHOUT its signature (the bytes the
/// enveloped-signature transform digests). `<Assertion>` declares the
/// assertion namespace as the default, so every child is unprefixed.
fn assertion_canonical(p: &AssertionParams<'_>) -> String {
    use core::fmt::Write as _;
    let mut s = String::new();
    // Attributes sorted by local name: ID, IssueInstant, Version.
    let _ = write!(
        s,
        r#"<Assertion xmlns="{ns}" ID="{id}" IssueInstant="{ii}" Version="2.0"><Issuer>{issuer}</Issuer>"#,
        ns = NS_ASSERTION,
        id = canon_attr(p.id),
        ii = canon_attr(p.issue_instant),
        issuer = canon_text(p.issuer),
    );
    // Subject.
    let _ = write!(
        s,
        concat!(
            r#"<Subject><NameID Format="{fmt}">{nid}</NameID>"#,
            r#"<SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">"#,
            r#"<SubjectConfirmationData {irt}NotOnOrAfter="{noa}" Recipient="{rcp}"></SubjectConfirmationData>"#,
            r#"</SubjectConfirmation></Subject>"#,
        ),
        fmt = canon_attr(p.subject_name_id_format),
        nid = canon_text(p.subject_name_id),
        irt = opt_attr("InResponseTo", p.in_response_to),
        noa = canon_attr(p.not_on_or_after),
        rcp = canon_attr(p.recipient),
    );
    // Conditions.
    let _ = write!(
        s,
        concat!(
            r#"<Conditions NotBefore="{nb}" NotOnOrAfter="{noa}">"#,
            r#"<AudienceRestriction><Audience>{aud}</Audience></AudienceRestriction>"#,
            r#"</Conditions>"#,
        ),
        nb = canon_attr(p.not_before),
        noa = canon_attr(p.not_on_or_after),
        aud = canon_text(p.audience),
    );
    // AuthnStatement.
    let _ = write!(
        s,
        concat!(
            r#"<AuthnStatement AuthnInstant="{ai}" SessionIndex="{si}">"#,
            r#"<AuthnContext><AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef></AuthnContext>"#,
            r#"</AuthnStatement>"#,
        ),
        ai = canon_attr(p.authn_instant),
        si = canon_attr(p.session_index),
    );
    // AttributeStatement (omitted entirely when there are no attributes).
    if p.attributes.iter().any(|(_, v)| !v.is_empty()) {
        s.push_str("<AttributeStatement>");
        for (name, values) in p.attributes {
            if values.is_empty() {
                continue;
            }
            let _ = write!(s, r#"<Attribute Name="{n}">"#, n = canon_attr(name));
            for value in *values {
                let _ = write!(
                    s,
                    "<AttributeValue>{v}</AttributeValue>",
                    v = canon_text(value)
                );
            }
            s.push_str("</Attribute>");
        }
        s.push_str("</AttributeStatement>");
    }
    s.push_str("</Assertion>");
    s
}

/// Emit the canonical `<ds:SignedInfo>` referencing `#assertion_id` with the
/// given base64 digest. Declares `xmlns:ds` on itself so its standalone
/// exclusive-C14N form (what is signed) matches its in-document bytes.
fn signed_info_canonical(assertion_id: &str, digest_b64: &str, sig_method: &str) -> String {
    format!(
        concat!(
            r#"<ds:SignedInfo xmlns:ds="{ns}">"#,
            r#"<ds:CanonicalizationMethod Algorithm="{c14n}"></ds:CanonicalizationMethod>"#,
            r#"<ds:SignatureMethod Algorithm="{sm}"></ds:SignatureMethod>"#,
            r##"<ds:Reference URI="#{refid}">"##,
            r#"<ds:Transforms>"#,
            r#"<ds:Transform Algorithm="{env}"></ds:Transform>"#,
            r#"<ds:Transform Algorithm="{c14n}"></ds:Transform>"#,
            r#"</ds:Transforms>"#,
            r#"<ds:DigestMethod Algorithm="{dm}"></ds:DigestMethod>"#,
            r#"<ds:DigestValue>{dv}</ds:DigestValue>"#,
            r#"</ds:Reference></ds:SignedInfo>"#,
        ),
        ns = NS_DSIG,
        c14n = C14N_EXCLUSIVE,
        sm = sig_method,
        refid = canon_attr(assertion_id),
        env = TRANSFORM_ENVELOPED,
        dm = DIGEST_SHA256,
        dv = digest_b64,
    )
}

/// Build a signed SAML `<Response>` (base64-decodable by an SP) carrying one
/// enveloped-signed `<Assertion>`. The assertion is signed; the response
/// envelope is not (the SAML-standard "sign the assertion" profile).
#[must_use]
pub fn build_signed_response(
    response: &ResponseParams<'_>,
    assertion: &AssertionParams<'_>,
    key: &AsymmetricSigningKey,
) -> String {
    let sig_method = signature_method(key.algorithm());

    // 1. Canonical assertion (pre-signature) → digest.
    let assertion_canon = assertion_canonical(assertion);
    let digest = Sha256::digest(assertion_canon.as_bytes());
    let digest_b64 = base64_encode(&digest);

    // 2. SignedInfo → signature.
    let signed_info = signed_info_canonical(assertion.id, &digest_b64, sig_method);
    let signature = key.sign(signed_info.as_bytes());
    let signature_b64 = base64_encode(&signature);

    // 3. The <ds:Signature> block (SignedInfo verbatim so its in-document
    //    bytes equal what was signed). KeyInfo carries the key id.
    let signature_block = format!(
        concat!(
            r#"<ds:Signature xmlns:ds="{ns}">"#,
            "{signed_info}",
            r#"<ds:SignatureValue>{sv}</ds:SignatureValue>"#,
            r#"<ds:KeyInfo><ds:KeyName>{kid}</ds:KeyName></ds:KeyInfo>"#,
            r#"</ds:Signature>"#,
        ),
        ns = NS_DSIG,
        signed_info = signed_info,
        sv = signature_b64,
        kid = canon_text(key.verifying_key().kid()),
    );

    // 4. Insert the signature into the assertion right after </Issuer>.
    let issuer_close = "</Issuer>";
    let insert_at = assertion_canon
        .find(issuer_close)
        .map_or(assertion_canon.len(), |i| i + issuer_close.len());
    let mut signed_assertion = String::with_capacity(assertion_canon.len() + signature_block.len());
    signed_assertion.push_str(&assertion_canon[..insert_at]);
    signed_assertion.push_str(&signature_block);
    signed_assertion.push_str(&assertion_canon[insert_at..]);

    // 5. Wrap in the <samlp:Response> envelope.
    format!(
        concat!(
            r#"<samlp:Response xmlns:samlp="{nsp}" Destination="{dest}" ID="{id}" "#,
            r#"{irt}IssueInstant="{ii}" Version="2.0">"#,
            r#"<Issuer xmlns="{nsa}">{issuer}</Issuer>"#,
            r#"<samlp:Status><samlp:StatusCode Value="{success}"></samlp:StatusCode></samlp:Status>"#,
            "{assertion}",
            r#"</samlp:Response>"#,
        ),
        nsp = NS_PROTOCOL,
        dest = canon_attr(response.destination),
        id = canon_attr(response.id),
        irt = opt_attr("InResponseTo", response.in_response_to),
        ii = canon_attr(response.issue_instant),
        nsa = NS_ASSERTION,
        issuer = canon_text(response.issuer),
        success = STATUS_SUCCESS,
        assertion = signed_assertion,
    )
}

/// Verify a `<Response>` produced by [`build_signed_response`]: recompute the
/// enveloped digest over the assertion and verify the signature over the
/// `SignedInfo`. This is the in-crate self-check (same-canonicalizer);
/// third-party-SP interop is validated separately.
///
/// # Errors
///
/// [`SamlIdpError`] if the document is malformed, a field mis-decodes, the
/// digest mismatches, or the signature fails to verify.
pub fn verify_signed_response(xml: &str, key: &AsymmetricVerifyingKey) -> Result<(), SamlIdpError> {
    // Locate the assertion.
    let (a_start, a_end) = span_of(xml, "<Assertion ", "</Assertion>")
        .ok_or(SamlIdpError::Malformed("no Assertion"))?;
    let assertion = &xml[a_start..a_end];

    // Extract the (contiguous) signature block and the SignedInfo within it.
    let (sig_start, sig_end) = span_of(assertion, "<ds:Signature ", "</ds:Signature>")
        .ok_or(SamlIdpError::Malformed("no Signature"))?;
    let signature_block = &assertion[sig_start..sig_end];

    let signed_info = slice_between(signature_block, "<ds:SignedInfo ", "</ds:SignedInfo>")
        .ok_or(SamlIdpError::Malformed("no SignedInfo"))?;
    let digest_b64 = slice_between(signed_info, "<ds:DigestValue>", "</ds:DigestValue>")
        .ok_or(SamlIdpError::Malformed("no DigestValue"))?;
    let signature_b64 = slice_between(
        signature_block,
        "<ds:SignatureValue>",
        "</ds:SignatureValue>",
    )
    .ok_or(SamlIdpError::Malformed("no SignatureValue"))?;

    // Enveloped transform: the digested bytes are the assertion with the
    // signature block removed (it was inserted after </Issuer> as one block).
    let mut enveloped = String::with_capacity(assertion.len());
    enveloped.push_str(&assertion[..sig_start]);
    enveloped.push_str(&assertion[sig_end..]);
    let recomputed = base64_encode(&Sha256::digest(enveloped.as_bytes()));
    if recomputed != digest_b64 {
        return Err(SamlIdpError::DigestMismatch);
    }

    // The signature is over the SignedInfo element bytes (with its <ds: markup).
    let (info_from, info_to) = span_of(signature_block, "<ds:SignedInfo ", "</ds:SignedInfo>")
        .ok_or(SamlIdpError::Malformed("no SignedInfo"))?;
    let signed_info_full = &signature_block[info_from..info_to];
    let sig = base64_decode(signature_b64).map_err(|_| SamlIdpError::BadEncoding)?;
    if key.verify(signed_info_full.as_bytes(), &sig) {
        Ok(())
    } else {
        Err(SamlIdpError::SignatureInvalid)
    }
}

/// Byte range from the first `open` marker to the end of the first `close`
/// marker that **follows** it.
///
/// Locating the two markers independently (`find(open)` and `find(close)`)
/// lets a crafted document place the close tag before the open one, yielding a
/// reversed `start > end` range that panics the subsequent slice. `xml` here is
/// attacker-supplied, so the close search is anchored to the text after `open`
/// and a reversed document becomes a clean `Malformed` error.
fn span_of(haystack: &str, open: &str, close: &str) -> Option<(usize, usize)> {
    let start = haystack.find(open)?;
    let after = start + open.len();
    let end = after + haystack[after..].find(close)? + close.len();
    Some((start, end))
}

/// Return the substring strictly between the first `open` and the following
/// `close` (exclusive of both markers).
fn slice_between<'a>(haystack: &'a str, open: &str, close: &str) -> Option<&'a str> {
    let start = haystack.find(open)? + open.len();
    let rest = &haystack[start..];
    let end = rest.find(close)?;
    Some(&rest[..end])
}

// ---------------------------------------------------------------------------
// AuthnRequest parsing
// ---------------------------------------------------------------------------

/// The fields an IdP reads from an SP's `<AuthnRequest>`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AuthnRequest {
    /// Request `ID` (echoed as the response's `InResponseTo`).
    pub id: String,
    /// The SP entity id (`<Issuer>`).
    pub issuer: String,
    /// The SP's requested ACS URL, if present.
    pub acs_url: Option<String>,
    /// The request `Destination`, if present.
    pub destination: Option<String>,
}

/// Parse an SP `<AuthnRequest>` (already base64/inflate-decoded to XML) into
/// its IdP-relevant fields. Per-SP policy checks (issuer allow-list, ACS match)
/// are the caller's — this only extracts + requires the mandatory fields.
///
/// # Errors
///
/// [`SamlIdpError::Malformed`] when a required element/attribute is absent.
pub fn parse_authn_request(xml: &str) -> Result<AuthnRequest, SamlIdpError> {
    let root = parse_xml(xml).map_err(|_| SamlIdpError::Malformed("unparseable AuthnRequest"))?;
    // Namespace-constrained like the child <Issuer> two lines below, and for
    // the same anti-decoy reason: a same-named element in another namespace
    // must not be mistaken for the protocol element.
    if root.namespace().is_some_and(|ns| ns != NS_PROTOCOL) || root.name() != "AuthnRequest" {
        return Err(SamlIdpError::Malformed("root is not AuthnRequest"));
    }
    if root.attribute("Version") != Some("2.0") {
        return Err(SamlIdpError::Malformed("AuthnRequest Version is not 2.0"));
    }
    let id = root
        .attribute("ID")
        .ok_or(SamlIdpError::Malformed("AuthnRequest has no ID"))?
        .to_string();
    // Resolve <Issuer> in the SAML assertion namespace (or no namespace),
    // never a foreign namespace — mirroring response.rs `find_response_issuer`
    // and assertion.rs `is_saml_named`, so a foreign-namespaced decoy cannot
    // supply the issuer (signature-wrapping defense).
    let issuer = root
        .children()
        .iter()
        .find(|c| c.name() == "Issuer" && c.namespace().is_none_or(|ns| ns == NS_ASSERTION))
        .and_then(XmlElement::text_content)
        .ok_or(SamlIdpError::Malformed("AuthnRequest has no Issuer"))?
        .to_string();
    Ok(AuthnRequest {
        id,
        issuer,
        acs_url: root
            .attribute("AssertionConsumerServiceURL")
            .map(str::to_string),
        destination: root.attribute("Destination").map(str::to_string),
    })
}

// ---------------------------------------------------------------------------
// IdP metadata
// ---------------------------------------------------------------------------

/// Generate this IdP's SAML metadata `<EntityDescriptor>` advertising the
/// signing key (by name) and the HTTP-POST SSO binding.
///
/// Only the POST binding is advertised: this IdP accepts an `AuthnRequest` via
/// the HTTP-POST binding only (the redirect binding carries a DEFLATE-compressed
/// request this IdP does not inflate), so advertising HTTP-Redirect would make a
/// spec-conformant SP default to a binding that is then rejected.
///
/// NOTE: `<KeyInfo>` carries a `<KeyName>` (the signing-key id) rather than an
/// `<X509Certificate>`; SPs that require an X.509 cert in metadata are the
/// deferred interop follow-up.
#[must_use]
pub fn generate_idp_metadata(entity_id: &str, sso_url: &str, signing_key_id: &str) -> String {
    format!(
        concat!(
            r#"<md:EntityDescriptor xmlns:md="{nsm}" entityID="{eid}">"#,
            r#"<md:IDPSSODescriptor WantAuthnRequestsSigned="false" protocolSupportEnumeration="{nsp}">"#,
            r#"<md:KeyDescriptor use="signing">"#,
            r#"<ds:KeyInfo xmlns:ds="{nsd}"><ds:KeyName>{kid}</ds:KeyName></ds:KeyInfo>"#,
            r#"</md:KeyDescriptor>"#,
            r#"<md:NameIDFormat>urn:oasis:names:tc:SAML:2.0:nameid-format:persistent</md:NameIDFormat>"#,
            r#"<md:SingleSignOnService Binding="{post}" Location="{sso}"></md:SingleSignOnService>"#,
            r#"</md:IDPSSODescriptor></md:EntityDescriptor>"#,
        ),
        nsm = NS_METADATA,
        eid = canon_attr(entity_id),
        nsp = NS_PROTOCOL,
        nsd = NS_DSIG,
        kid = canon_text(signing_key_id),
        post = BINDING_POST,
        sso = canon_attr(sso_url),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jwt::{AsymmetricAlgorithm, AsymmetricSigningKey};

    /// `'static` so the borrows outlive the returned params.
    const TEST_ATTRS: &[(&str, &[&str])] =
        &[("email", &["frodo@example.com"]), ("role", &["user"])];

    fn params<'a>() -> (ResponseParams<'a>, AssertionParams<'a>) {
        (
            ResponseParams {
                id: "_resp1",
                issue_instant: "2024-01-01T00:00:00Z",
                destination: "https://sp.example.com/acs",
                in_response_to: "_req1",
                issuer: "https://idp.example.com",
            },
            AssertionParams {
                id: "_assert1",
                issuer: "https://idp.example.com",
                issue_instant: "2024-01-01T00:00:00Z",
                subject_name_id: "frodo@example.com",
                subject_name_id_format: "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
                in_response_to: "_req1",
                recipient: "https://sp.example.com/acs",
                not_before: "2024-01-01T00:00:00Z",
                not_on_or_after: "2024-01-01T01:00:00Z",
                audience: "https://sp.example.com",
                authn_instant: "2024-01-01T00:00:00Z",
                session_index: "_sess1",
                attributes: TEST_ATTRS,
            },
        )
    }

    #[test]
    fn signed_response_round_trips_es256() {
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::Es256).unwrap();
        let (resp, assertion) = params();
        let xml = build_signed_response(&resp, &assertion, &key);
        // Structurally well-formed + parseable.
        assert!(
            crate::xml::parse_xml(&xml).is_ok(),
            "produced XML must parse"
        );
        assert!(xml.contains("urn:oasis:names:tc:SAML:2.0:status:Success"));
        assert!(xml.contains("frodo@example.com"));
        // The in-crate verifier accepts it.
        verify_signed_response(&xml, key.verifying_key()).unwrap();
    }

    #[test]
    fn signed_response_round_trips_eddsa() {
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::EdDsa).unwrap();
        let (resp, assertion) = params();
        let xml = build_signed_response(&resp, &assertion, &key);
        verify_signed_response(&xml, key.verifying_key()).unwrap();
    }

    #[test]
    fn idp_initiated_omits_empty_in_response_to() {
        // Unsolicited (IdP-initiated) responses pass an empty in_response_to;
        // the attribute must be OMITTED, never emitted as InResponseTo="".
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::EdDsa).unwrap();
        let (mut resp, mut assertion) = params();
        resp.in_response_to = "";
        assertion.in_response_to = "";
        let xml = build_signed_response(&resp, &assertion, &key);
        assert!(
            !xml.contains(r#"InResponseTo="""#),
            "must not emit an empty InResponseTo: {xml}"
        );
        assert!(
            !xml.contains("InResponseTo"),
            "IdP-initiated response must omit InResponseTo entirely"
        );
        // Still valid + signature verifies with the attribute omitted.
        verify_signed_response(&xml, key.verifying_key()).unwrap();
    }

    #[test]
    fn solicited_keeps_in_response_to() {
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::EdDsa).unwrap();
        let (resp, assertion) = params();
        let xml = build_signed_response(&resp, &assertion, &key);
        assert!(xml.contains(r#"InResponseTo="_req1""#));
        verify_signed_response(&xml, key.verifying_key()).unwrap();
    }

    #[test]
    fn tampered_assertion_fails_digest() {
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::Es256).unwrap();
        let (resp, assertion) = params();
        let xml = build_signed_response(&resp, &assertion, &key);
        // Flip the subject NameID after signing → digest must no longer match.
        let tampered = xml.replace("frodo@example.com", "evil@example.com");
        assert_ne!(tampered, xml);
        assert_eq!(
            verify_signed_response(&tampered, key.verifying_key()),
            Err(SamlIdpError::DigestMismatch)
        );
    }

    #[test]
    fn wrong_key_fails_signature() {
        let key = AsymmetricSigningKey::generate(AsymmetricAlgorithm::Es256).unwrap();
        let other = AsymmetricSigningKey::generate(AsymmetricAlgorithm::Es256).unwrap();
        let (resp, assertion) = params();
        let xml = build_signed_response(&resp, &assertion, &key);
        assert_eq!(
            verify_signed_response(&xml, other.verifying_key()),
            Err(SamlIdpError::SignatureInvalid)
        );
    }

    #[test]
    fn canonical_output_is_deterministic() {
        let (_r, assertion) = params();
        assert_eq!(
            assertion_canonical(&assertion),
            assertion_canonical(&assertion)
        );
    }

    #[test]
    fn parse_authn_request_extracts_fields() {
        let xml = concat!(
            r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" "#,
            r#"xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_req42" Version="2.0" "#,
            r#"Destination="https://idp.example.com/sso" "#,
            r#"AssertionConsumerServiceURL="https://sp.example.com/acs">"#,
            r#"<saml:Issuer>https://sp.example.com</saml:Issuer>"#,
            r#"</samlp:AuthnRequest>"#,
        );
        let req = parse_authn_request(xml).unwrap();
        assert_eq!(req.id, "_req42");
        assert_eq!(req.issuer, "https://sp.example.com");
        assert_eq!(req.acs_url.as_deref(), Some("https://sp.example.com/acs"));
        assert_eq!(
            req.destination.as_deref(),
            Some("https://idp.example.com/sso")
        );
    }

    #[test]
    fn parse_authn_request_rejects_non_2_0_version() {
        // Missing Version and Version != "2.0" must both be rejected, matching
        // the rest of the SAML module's Version=="2.0" enforcement.
        let missing = concat!(
            r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" "#,
            r#"xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_req42">"#,
            r#"<saml:Issuer>https://sp.example.com</saml:Issuer>"#,
            r#"</samlp:AuthnRequest>"#,
        );
        assert!(matches!(
            parse_authn_request(missing),
            Err(SamlIdpError::Malformed(_))
        ));
        let wrong = concat!(
            r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" "#,
            r#"xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_req42" Version="1.1">"#,
            r#"<saml:Issuer>https://sp.example.com</saml:Issuer>"#,
            r#"</samlp:AuthnRequest>"#,
        );
        assert!(matches!(
            parse_authn_request(wrong),
            Err(SamlIdpError::Malformed(_))
        ));
    }

    #[test]
    fn parse_authn_request_rejects_foreign_namespaced_issuer() {
        // A foreign-namespaced <Issuer> decoy must not supply the issuer.
        let xml = concat!(
            r#"<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" "#,
            r#"xmlns:evil="urn:evil" ID="_req42" Version="2.0">"#,
            r#"<evil:Issuer>https://attacker.example.com</evil:Issuer>"#,
            r#"</samlp:AuthnRequest>"#,
        );
        assert!(matches!(
            parse_authn_request(xml),
            Err(SamlIdpError::Malformed(_))
        ));
    }

    #[test]
    fn idp_metadata_contains_bindings_and_key() {
        let md = generate_idp_metadata(
            "https://idp.example.com",
            "https://idp.example.com/sso",
            "key-1",
        );
        assert!(crate::xml::parse_xml(&md).is_ok());
        assert!(md.contains("IDPSSODescriptor"));
        // Only the POST binding is advertised; the redirect binding is not
        // supported and must not be listed (else SPs default to it and fail).
        assert!(!md.contains("HTTP-Redirect"));
        assert!(md.contains("HTTP-POST"));
        assert!(md.contains("key-1"));
    }
}