feat(saml): wire SAML 2.0 SSO end-to-end (pure-Rust) + Settings/Storage UI consolidation (v0.5.1)
SAML SSO (the config was storage-only since v0.4.5; now it logs you in):
- New openpxe-core::saml — pure-Rust SP built on bergshamra (XML-DSig +
exclusive c14n via RustCrypto, no OpenSSL/xmlsec/libxml2). The static
musl binary stays C-free; samael was rejected for hard-requiring OpenSSL.
* metadata.rs — parse IdP EntityDescriptor (SSO URLs + signing certs),
build our SP metadata.
* authn_request.rs — build + HTTP-Redirect-encode AuthnRequests.
* response.rs — verify the signature against the pinned IdP cert
(trusted_keys_only + strict_verification for XSW),
then enforce Status/Destination/Audience/time-bounds/
signature-scope. Stateless; returns the IDs the HTTP
layer needs.
- http-api saml_routes: GET /api/sso/login (302 to IdP), POST /api/sso/acs
(verify -> InResponseTo correlation / IdP-initiated gating / assertion
replay guard -> mint operator session -> 302), GET /api/sso/metadata.
Added to the pre-auth allowlist; /api/sso config stays gated.
- SsoConfig gains entity_id (SP Entity ID, defaults to public base URL)
and allow_idp_initiated (default off), mirroring FleetDM.
- Access model: any IdP-authenticated, cryptographically-verified user gets
an operator session (single-tier; local admin remains the fallback owner).
- Login page: the "Sign in with <IdP>" button now drives the real flow and
surfaces sso_error redirects.
UI consolidation:
- Removed the Advanced sidebar tab; folded its webhook-notifications +
API-reference cards into a collapsible "Advanced" disclosure at the
bottom of Settings.
- Merged the Storage tab's separate SMB and NFS cards into one "Remote
shares" card with a protocol dropdown and a unified, protocol-badged
table. No backend changes — same /api/smb-shares + /api/nfs-shares.
Tests: 17 SAML core tests (accept + reject tampered/unsigned/wrong-key/
wrong-audience/expired/future/wrong-issuer/non-success) and 6 ACS
integration tests (happy path, IdP-initiated gating, SP correlation,
replay, garbage). Full workspace: 206 tests green, clippy clean.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
252b557b9c
commit
cbcd63bb14
@@ -25,5 +25,19 @@ tokio = { workspace = true, features = ["sync", "rt", "macros", "time"] }
|
||||
# for per-ISO boot passwords; just re-exported here.
|
||||
bcrypt.workspace = true
|
||||
|
||||
# v0.5.1: pure-Rust SAML 2.0 SP. bergshamra = XML-DSig verify + exclusive
|
||||
# c14n (no OpenSSL/C). roxmltree/quick-xml parse + build SAML XML;
|
||||
# x509-parser pulls the IdP signing cert out of metadata; flate2+base64
|
||||
# encode the HTTP-Redirect binding's SAMLRequest.
|
||||
bergshamra.workspace = true
|
||||
roxmltree.workspace = true
|
||||
quick-xml.workspace = true
|
||||
x509-parser.workspace = true
|
||||
flate2.workspace = true
|
||||
base64.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.12"
|
||||
# v0.5.1: generate a throwaway self-signed signing cert/key so SAML
|
||||
# verification tests can produce genuinely signed SAMLResponses.
|
||||
rcgen = "0.13"
|
||||
|
||||
@@ -14,6 +14,7 @@ pub mod log_bus;
|
||||
pub mod metrics;
|
||||
pub mod notify;
|
||||
pub mod queue;
|
||||
pub mod saml;
|
||||
pub mod settings;
|
||||
pub mod sso;
|
||||
pub mod wol;
|
||||
@@ -23,7 +24,6 @@ pub use auth::{AdminAccount, AdminPublic, AdminStore};
|
||||
pub use boot_log::{BootEvent, BootLog};
|
||||
pub use branding::{ext_for_mime, BrandingStore, ALLOWED_LOGO_MIMES, MAX_LOGO_BYTES};
|
||||
pub use client::{ClientEvent, ClientRegistry, ClientSnapshot};
|
||||
pub use sso::{SsoConfig, SsoStore};
|
||||
pub use config::{Config, DhcpMode, NetworkConfig, Paths, ServerConfig};
|
||||
pub use error::{Error, Result};
|
||||
pub use host_bindings::{normalize_mac, HostBinding, HostBindings};
|
||||
@@ -31,4 +31,6 @@ pub use log_bus::{LogBus, LogBusLayer, LogLine};
|
||||
pub use metrics::{HttpRoute, Metrics};
|
||||
pub use notify::{NotifyConfig, NotifyKind, NotifyStore};
|
||||
pub use queue::{DeploymentQueue, QueueEntry};
|
||||
pub use saml::{IdpMetadata, SamlError, SpParams, VerifiedPrincipal, VerifiedResponse};
|
||||
pub use settings::{Settings, SettingsStore, TimeoutAction};
|
||||
pub use sso::{SsoConfig, SsoStore};
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
//! AuthnRequest construction + HTTP-Redirect binding encoding.
|
||||
//!
|
||||
//! For SP-initiated login we build an `<AuthnRequest>`, then encode it for the
|
||||
//! HTTP-Redirect binding: raw DEFLATE (RFC 1951) → base64 → percent-encode,
|
||||
//! appended as the `SAMLRequest` query parameter. AuthnRequests are sent
|
||||
//! unsigned in this release (the IdP must not require client signatures).
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
|
||||
use base64::Engine;
|
||||
use flate2::write::DeflateEncoder;
|
||||
use flate2::Compression;
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::{SamlError, SpParams};
|
||||
|
||||
const NS_PROTOCOL: &str = "urn:oasis:names:tc:SAML:2.0:protocol";
|
||||
const NS_ASSERTION: &str = "urn:oasis:names:tc:SAML:2.0:assertion";
|
||||
const NAMEID_EMAIL: &str = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
|
||||
const BINDING_POST: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
|
||||
|
||||
/// A built AuthnRequest, ready to redirect the browser to the IdP.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthnRequest {
|
||||
/// The request `ID` — the caller records this so the matching response's
|
||||
/// `InResponseTo` can be correlated (replay/CSRF protection).
|
||||
pub id: String,
|
||||
/// The full IdP URL to 302 the browser to (includes `SAMLRequest` and,
|
||||
/// when supplied, `RelayState`).
|
||||
pub location: String,
|
||||
}
|
||||
|
||||
/// Build an AuthnRequest targeting `idp_sso_url` and encode it for the
|
||||
/// HTTP-Redirect binding. `relay_state`, if given, round-trips back to us via
|
||||
/// the response (we use it to send the operator to their intended page).
|
||||
pub fn build(
|
||||
sp: &SpParams,
|
||||
idp_sso_url: &str,
|
||||
relay_state: Option<&str>,
|
||||
) -> Result<AuthnRequest, SamlError> {
|
||||
let id = format!("_{}", uuid::Uuid::new_v4().simple());
|
||||
let issue_instant = OffsetDateTime::now_utc()
|
||||
.replace_nanosecond(0)
|
||||
.unwrap_or_else(|_| OffsetDateTime::now_utc())
|
||||
.format(&Rfc3339)
|
||||
.map_err(|e| SamlError::Timestamp(e.to_string()))?;
|
||||
|
||||
let xml = format!(
|
||||
r#"<samlp:AuthnRequest xmlns:samlp="{NS_PROTOCOL}" xmlns:saml="{NS_ASSERTION}" ID="{id}" Version="2.0" IssueInstant="{instant}" Destination="{dest}" ProtocolBinding="{BINDING_POST}" AssertionConsumerServiceURL="{acs}"><saml:Issuer>{issuer}</saml:Issuer><samlp:NameIDPolicy Format="{NAMEID_EMAIL}" AllowCreate="true"/></samlp:AuthnRequest>"#,
|
||||
instant = issue_instant,
|
||||
dest = xml_escape(idp_sso_url),
|
||||
acs = xml_escape(&sp.acs_url),
|
||||
issuer = xml_escape(&sp.entity_id),
|
||||
);
|
||||
|
||||
let encoded = deflate_base64(&xml)?;
|
||||
|
||||
let sep = if idp_sso_url.contains('?') { '&' } else { '?' };
|
||||
let mut location = format!("{idp_sso_url}{sep}SAMLRequest={}", pct_encode(&encoded));
|
||||
if let Some(rs) = relay_state {
|
||||
location.push_str("&RelayState=");
|
||||
location.push_str(&pct_encode(rs));
|
||||
}
|
||||
|
||||
Ok(AuthnRequest { id, location })
|
||||
}
|
||||
|
||||
/// Raw-DEFLATE then base64 — the HTTP-Redirect binding's `SAMLRequest` payload.
|
||||
fn deflate_base64(xml: &str) -> Result<String, SamlError> {
|
||||
let mut enc = DeflateEncoder::new(Vec::new(), Compression::default());
|
||||
enc.write_all(xml.as_bytes())
|
||||
.and_then(|()| enc.try_finish())
|
||||
.map_err(|e| SamlError::Xml(format!("deflate: {e}")))?;
|
||||
let compressed = enc
|
||||
.finish()
|
||||
.map_err(|e| SamlError::Xml(format!("deflate: {e}")))?;
|
||||
Ok(base64::engine::general_purpose::STANDARD.encode(compressed))
|
||||
}
|
||||
|
||||
/// Percent-encode a query-string component (RFC 3986 unreserved set passes
|
||||
/// through; everything else is `%XX`).
|
||||
fn pct_encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len() * 3);
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
|
||||
out.push(b as char);
|
||||
}
|
||||
_ => {
|
||||
let _ = write!(out, "%{b:02X}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn xml_escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use flate2::read::DeflateDecoder;
|
||||
use std::io::Read;
|
||||
|
||||
fn sp() -> SpParams {
|
||||
SpParams {
|
||||
entity_id: "https://pxe.example.com".into(),
|
||||
acs_url: "https://pxe.example.com/api/sso/acs".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn pct_decode(s: &str) -> Vec<u8> {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' && i + 2 < bytes.len() {
|
||||
let hi = (bytes[i + 1] as char).to_digit(16).unwrap();
|
||||
let lo = (bytes[i + 2] as char).to_digit(16).unwrap();
|
||||
out.push((hi * 16 + lo) as u8);
|
||||
i += 3;
|
||||
} else {
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn id_is_ncname_and_location_has_request() {
|
||||
let req = build(&sp(), "https://idp.example.com/sso", Some("/dashboard")).unwrap();
|
||||
assert!(req.id.starts_with('_'));
|
||||
assert!(req
|
||||
.location
|
||||
.starts_with("https://idp.example.com/sso?SAMLRequest="));
|
||||
assert!(req.location.contains("&RelayState=%2Fdashboard"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redirect_payload_round_trips_to_our_authn_request() {
|
||||
let req = build(&sp(), "https://idp.example.com/sso", None).unwrap();
|
||||
// Pull SAMLRequest value out of the query string.
|
||||
let q = req.location.split("SAMLRequest=").nth(1).unwrap();
|
||||
let val = q.split('&').next().unwrap();
|
||||
let compressed = base64::engine::general_purpose::STANDARD
|
||||
.decode(pct_decode(val))
|
||||
.unwrap();
|
||||
let mut inflate = DeflateDecoder::new(&compressed[..]);
|
||||
let mut xml = String::new();
|
||||
inflate.read_to_string(&mut xml).unwrap();
|
||||
|
||||
let doc = roxmltree::Document::parse(&xml).unwrap();
|
||||
let root = doc.root_element();
|
||||
assert_eq!(root.tag_name().name(), "AuthnRequest");
|
||||
assert_eq!(root.attribute("ID").unwrap(), req.id);
|
||||
assert_eq!(
|
||||
root.attribute("AssertionConsumerServiceURL").unwrap(),
|
||||
"https://pxe.example.com/api/sso/acs"
|
||||
);
|
||||
let issuer = root
|
||||
.descendants()
|
||||
.find(|n| n.tag_name().name() == "Issuer")
|
||||
.unwrap();
|
||||
assert_eq!(issuer.text().unwrap(), "https://pxe.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_query_uses_ampersand_separator() {
|
||||
let req = build(&sp(), "https://idp.example.com/sso?foo=bar", None).unwrap();
|
||||
assert!(req.location.contains("?foo=bar&SAMLRequest="));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
//! IdP metadata parsing + SP metadata generation.
|
||||
//!
|
||||
//! We parse only what the SP flow needs: the IdP Entity ID, its
|
||||
//! `SingleSignOnService` endpoints (HTTP-Redirect / HTTP-POST), and the
|
||||
//! X.509 signing certificate(s). Everything else in the document is ignored.
|
||||
|
||||
use base64::Engine;
|
||||
|
||||
use super::{SamlError, SpParams};
|
||||
|
||||
/// SAML 2.0 binding URIs.
|
||||
pub const BINDING_REDIRECT: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect";
|
||||
pub const BINDING_POST: &str = "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST";
|
||||
|
||||
/// The subset of an IdP's `EntityDescriptor` the SP flow consumes.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct IdpMetadata {
|
||||
/// The IdP's Entity ID — we require incoming assertions to be issued by it.
|
||||
pub entity_id: String,
|
||||
/// SSO endpoint for the HTTP-Redirect binding (where we send AuthnRequests).
|
||||
pub sso_redirect_url: Option<String>,
|
||||
/// SSO endpoint for the HTTP-POST binding (fallback target).
|
||||
pub sso_post_url: Option<String>,
|
||||
/// DER-encoded X.509 signing certificate(s). More than one appears during
|
||||
/// key rotation; verification tries each.
|
||||
pub signing_certs_der: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl IdpMetadata {
|
||||
/// Parse an IdP `EntityDescriptor` document.
|
||||
///
|
||||
/// Robust to namespace-prefix variation (matches on local element names),
|
||||
/// since IdPs disagree on prefixes (`md:`, `ns0:`, default, …).
|
||||
pub fn parse(xml: &str) -> Result<Self, SamlError> {
|
||||
let doc = roxmltree::Document::parse(xml).map_err(|e| SamlError::Xml(e.to_string()))?;
|
||||
let root = doc.root_element();
|
||||
|
||||
// The signing IDP descriptor. Some metadata wraps multiple
|
||||
// descriptors (AA, SP) in one document; we want IDPSSODescriptor.
|
||||
let idp_desc = root
|
||||
.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == "IDPSSODescriptor")
|
||||
.ok_or_else(|| SamlError::Metadata("IDPSSODescriptor".into()))?;
|
||||
|
||||
// Entity ID lives on the EntityDescriptor (root, or an ancestor of the
|
||||
// IDPSSODescriptor when several are nested).
|
||||
let entity_id = idp_desc
|
||||
.ancestors()
|
||||
.find_map(|n| {
|
||||
if n.tag_name().name() == "EntityDescriptor" {
|
||||
n.attribute("entityID")
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.or_else(|| root.attribute("entityID"))
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| SamlError::Metadata("entityID".into()))?;
|
||||
|
||||
let mut sso_redirect_url = None;
|
||||
let mut sso_post_url = None;
|
||||
for sso in idp_desc
|
||||
.children()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "SingleSignOnService")
|
||||
{
|
||||
let binding = sso.attribute("Binding").unwrap_or("");
|
||||
let location = sso.attribute("Location").map(str::to_owned);
|
||||
match binding {
|
||||
BINDING_REDIRECT if sso_redirect_url.is_none() => sso_redirect_url = location,
|
||||
BINDING_POST if sso_post_url.is_none() => sso_post_url = location,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
// Signing certs: KeyDescriptor with use="signing" or no use attribute
|
||||
// (a bare KeyDescriptor is valid for both signing and encryption).
|
||||
let mut signing_certs_der = Vec::new();
|
||||
for kd in idp_desc
|
||||
.children()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "KeyDescriptor")
|
||||
{
|
||||
match kd.attribute("use") {
|
||||
Some("signing") | None => {}
|
||||
Some(_) => continue, // encryption-only key — skip
|
||||
}
|
||||
for cert_node in kd
|
||||
.descendants()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "X509Certificate")
|
||||
{
|
||||
let b64: String = node_text(&cert_node)
|
||||
.chars()
|
||||
.filter(|c| !c.is_whitespace())
|
||||
.collect();
|
||||
if b64.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let der = base64::engine::general_purpose::STANDARD
|
||||
.decode(b64.as_bytes())
|
||||
.map_err(|e| SamlError::Base64(e.to_string()))?;
|
||||
signing_certs_der.push(der);
|
||||
}
|
||||
}
|
||||
|
||||
if signing_certs_der.is_empty() {
|
||||
return Err(SamlError::NoSigningCert);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
entity_id,
|
||||
sso_redirect_url,
|
||||
sso_post_url,
|
||||
signing_certs_der,
|
||||
})
|
||||
}
|
||||
|
||||
/// Preferred SSO destination for an outbound AuthnRequest: HTTP-Redirect
|
||||
/// if advertised, otherwise HTTP-POST.
|
||||
pub fn sso_destination(&self) -> Option<&str> {
|
||||
self.sso_redirect_url
|
||||
.as_deref()
|
||||
.or(self.sso_post_url.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
/// Build our SP `EntityDescriptor` XML so an IdP admin can import OpenPXE as a
|
||||
/// relying party. Advertises the ACS URL (HTTP-POST binding) and an emailAddress
|
||||
/// NameID format — matching what the response path expects.
|
||||
pub fn build_sp_metadata(sp: &SpParams) -> String {
|
||||
let entity = xml_escape(&sp.entity_id);
|
||||
let acs = xml_escape(&sp.acs_url);
|
||||
format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="{entity}">
|
||||
<SPSSODescriptor AuthnRequestsSigned="false" WantAssertionsSigned="true" protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
|
||||
<NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</NameIDFormat>
|
||||
<AssertionConsumerService Binding="{BINDING_POST}" Location="{acs}" index="0" isDefault="true"/>
|
||||
</SPSSODescriptor>
|
||||
</EntityDescriptor>
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
/// Collect the concatenated text of an element's direct text children.
|
||||
fn node_text(n: &roxmltree::Node<'_, '_>) -> String {
|
||||
n.children()
|
||||
.filter(roxmltree::Node::is_text)
|
||||
.filter_map(|c| c.text())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Minimal XML attribute/text escaping for the values we interpolate.
|
||||
fn xml_escape(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for c in s.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// A trimmed-down Keycloak-style IdP descriptor (cert body is a stand-in;
|
||||
// signing tests build real certs in the parent module's tests).
|
||||
const SAMPLE: &str = r#"<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"
|
||||
xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
|
||||
entityID="https://idp.example.com/realms/fleet">
|
||||
<md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
|
||||
<md:KeyDescriptor use="signing">
|
||||
<ds:KeyInfo><ds:X509Data><ds:X509Certificate>
|
||||
QUJDREVG
|
||||
</ds:X509Certificate></ds:X509Data></ds:KeyInfo>
|
||||
</md:KeyDescriptor>
|
||||
<md:KeyDescriptor use="encryption">
|
||||
<ds:KeyInfo><ds:X509Data><ds:X509Certificate>WlpaWg==</ds:X509Certificate></ds:X509Data></ds:KeyInfo>
|
||||
</md:KeyDescriptor>
|
||||
<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
|
||||
Location="https://idp.example.com/realms/fleet/protocol/saml"/>
|
||||
<md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
|
||||
Location="https://idp.example.com/realms/fleet/protocol/saml"/>
|
||||
</md:IDPSSODescriptor>
|
||||
</md:EntityDescriptor>"#;
|
||||
|
||||
#[test]
|
||||
fn parses_entity_sso_and_signing_cert() {
|
||||
let m = IdpMetadata::parse(SAMPLE).unwrap();
|
||||
assert_eq!(m.entity_id, "https://idp.example.com/realms/fleet");
|
||||
assert_eq!(
|
||||
m.sso_redirect_url.as_deref(),
|
||||
Some("https://idp.example.com/realms/fleet/protocol/saml")
|
||||
);
|
||||
assert!(m.sso_post_url.is_some());
|
||||
// Only the signing KeyDescriptor's cert is collected (ABCDEF), not the
|
||||
// encryption one (ZZZZ).
|
||||
assert_eq!(m.signing_certs_der.len(), 1);
|
||||
assert_eq!(m.signing_certs_der[0], b"ABCDEF");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_signing_cert_is_rejected() {
|
||||
let xml = r#"<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="x">
|
||||
<IDPSSODescriptor>
|
||||
<SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://x/sso"/>
|
||||
</IDPSSODescriptor></EntityDescriptor>"#;
|
||||
assert!(matches!(
|
||||
IdpMetadata::parse(xml),
|
||||
Err(SamlError::NoSigningCert)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_idp_descriptor_is_rejected() {
|
||||
let xml = r#"<EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="x"></EntityDescriptor>"#;
|
||||
assert!(matches!(
|
||||
IdpMetadata::parse(xml),
|
||||
Err(SamlError::Metadata(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sp_metadata_contains_entity_and_acs() {
|
||||
let sp = SpParams {
|
||||
entity_id: "https://pxe.example.com".into(),
|
||||
acs_url: "https://pxe.example.com/api/sso/acs".into(),
|
||||
};
|
||||
let xml = build_sp_metadata(&sp);
|
||||
assert!(xml.contains(r#"entityID="https://pxe.example.com""#));
|
||||
assert!(xml.contains("https://pxe.example.com/api/sso/acs"));
|
||||
assert!(xml.contains(BINDING_POST));
|
||||
// Must be well-formed.
|
||||
roxmltree::Document::parse(&xml).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Pure-Rust SAML 2.0 Service Provider (v0.5.1).
|
||||
//!
|
||||
//! This module implements the SP half of a SAML Web-Browser-SSO profile:
|
||||
//!
|
||||
//! * [`metadata`] — parse the IdP's `EntityDescriptor` (SSO URLs + signing
|
||||
//! certificates) and build *our* SP metadata for the IdP admin to import.
|
||||
//! * [`authn_request`] — build an `AuthnRequest` and encode it for the
|
||||
//! HTTP-Redirect binding.
|
||||
//! * [`response`] — decode a `SAMLResponse`, **verify its XML signature**
|
||||
//! against the IdP's pinned certificate (via the pure-Rust `bergshamra`
|
||||
//! crate — no OpenSSL/libxml2/xmlsec, so the static musl binary stays
|
||||
//! C-free), then enforce the SP-side semantic checks (Status, Destination,
|
||||
//! Audience, time bounds) that are where SAML SPs actually get attacked.
|
||||
//!
|
||||
//! Stateful checks (replay of assertion IDs, correlating `InResponseTo`
|
||||
//! against requests *we* issued, gating IdP-initiated login) live in the
|
||||
//! HTTP layer — [`response::consume`] is deliberately stateless and returns
|
||||
//! the IDs the caller needs to perform them.
|
||||
//!
|
||||
//! Access model: any assertion the IdP authenticates and we cryptographically
|
||||
//! verify yields an operator [`VerifiedPrincipal`]. OpenPXE is single-tier —
|
||||
//! there is no per-user role table — and the local admin account remains a
|
||||
//! guaranteed fallback owner regardless of SSO state.
|
||||
|
||||
pub mod authn_request;
|
||||
pub mod metadata;
|
||||
pub mod response;
|
||||
|
||||
pub use authn_request::AuthnRequest;
|
||||
pub use metadata::IdpMetadata;
|
||||
pub use response::{VerifiedPrincipal, VerifiedResponse};
|
||||
|
||||
use thiserror::Error;
|
||||
|
||||
/// Default clock-skew tolerance applied to assertion time bounds. SAML IdPs
|
||||
/// and SPs rarely have perfectly synced clocks; 60s matches common practice
|
||||
/// (Shibboleth/FleetDM defaults are in this ballpark).
|
||||
pub const DEFAULT_CLOCK_SKEW_SECS: i64 = 60;
|
||||
|
||||
/// Runtime SP parameters, derived from [`crate::SsoConfig`] + the advertised
|
||||
/// public base URL by the HTTP layer.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SpParams {
|
||||
/// Our SP Entity ID (the `<Issuer>` we send and the `Audience` we require
|
||||
/// in responses). Defaults to the public base URL when the operator left
|
||||
/// the Entity ID field blank.
|
||||
pub entity_id: String,
|
||||
/// The Assertion Consumer Service URL the IdP POSTs the response to —
|
||||
/// `<public_base_url>/api/sso/acs`.
|
||||
pub acs_url: String,
|
||||
}
|
||||
|
||||
/// Everything that can go wrong consuming a SAML response. Kept coarse on
|
||||
/// purpose: the HTTP layer logs the detail and shows the operator a generic
|
||||
/// "SSO sign-in failed" — we never leak which specific check tripped to the
|
||||
/// browser, since that aids an attacker probing the SP.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum SamlError {
|
||||
#[error("SAML XML parse error: {0}")]
|
||||
Xml(String),
|
||||
#[error("IdP metadata is missing a required element: {0}")]
|
||||
Metadata(String),
|
||||
#[error("no usable IdP signing certificate in metadata")]
|
||||
NoSigningCert,
|
||||
#[error("signature verification failed: {0}")]
|
||||
Signature(String),
|
||||
#[error("the signature does not cover the assertion we read")]
|
||||
SignatureScope,
|
||||
#[error("SAML response status was not Success: {0}")]
|
||||
Status(String),
|
||||
#[error("response is missing a required element: {0}")]
|
||||
MissingElement(String),
|
||||
#[error("encrypted assertions are not supported in this release")]
|
||||
EncryptedAssertionUnsupported,
|
||||
#[error("expected exactly one assertion, found {0}")]
|
||||
AssertionCount(usize),
|
||||
#[error("issuer mismatch: response was not issued by the configured IdP")]
|
||||
IssuerMismatch,
|
||||
#[error("audience mismatch: assertion is not addressed to this service provider")]
|
||||
AudienceMismatch,
|
||||
#[error("response destination does not match our ACS URL")]
|
||||
DestinationMismatch,
|
||||
#[error("assertion is expired or not yet valid")]
|
||||
TimeBounds,
|
||||
#[error("invalid SAML timestamp: {0}")]
|
||||
Timestamp(String),
|
||||
#[error("base64 decode failed: {0}")]
|
||||
Base64(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,294 @@
|
||||
//! SAMLResponse consumption: signature verification + SP-side validation.
|
||||
//!
|
||||
//! [`consume`] is intentionally **stateless** — it verifies the XML signature
|
||||
//! against the IdP's pinned certificate(s) and enforces every check that can
|
||||
//! be made from the response alone (Status, Destination, Issuer, Audience,
|
||||
//! time bounds, signature scope). It then returns the `assertion_id` and
|
||||
//! `in_response_to` so the HTTP layer can perform the *stateful* checks it
|
||||
//! owns: replay rejection, correlating the request we issued, and gating
|
||||
//! IdP-initiated login.
|
||||
|
||||
use roxmltree::{Document, Node};
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
use super::metadata::IdpMetadata;
|
||||
use super::{SamlError, SpParams};
|
||||
|
||||
const STATUS_SUCCESS: &str = "urn:oasis:names:tc:SAML:2.0:status:Success";
|
||||
|
||||
/// The verified subject of a SAML assertion. OpenPXE is single-tier, so this
|
||||
/// is all an operator session needs.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VerifiedPrincipal {
|
||||
/// The `<NameID>` value (an email, per our requested NameID format).
|
||||
pub name_id: String,
|
||||
/// Email used as the session identity. Equals `name_id` for the
|
||||
/// emailAddress NameID format.
|
||||
pub email: String,
|
||||
/// Human-readable display name, if the IdP sent one as an attribute.
|
||||
pub display_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Result of a successful [`consume`]. The IDs/expiry feed the HTTP layer's
|
||||
/// stateful checks.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VerifiedResponse {
|
||||
pub principal: VerifiedPrincipal,
|
||||
/// `InResponseTo` from the response, if present. `None` = unsolicited
|
||||
/// (IdP-initiated) — the HTTP layer only accepts that when the operator
|
||||
/// enabled it.
|
||||
pub in_response_to: Option<String>,
|
||||
/// The assertion's `ID` — used by the caller as the replay-guard key.
|
||||
pub assertion_id: String,
|
||||
/// The assertion's expiry (`Conditions/@NotOnOrAfter`) — the replay
|
||||
/// guard can drop the consumed ID after this instant.
|
||||
pub assertion_expiry: OffsetDateTime,
|
||||
/// `AuthnStatement/@SessionIndex`, if present (useful for future SLO).
|
||||
pub session_index: Option<String>,
|
||||
}
|
||||
|
||||
/// Verify and validate a decoded `SAMLResponse` XML document.
|
||||
pub fn consume(
|
||||
xml: &str,
|
||||
sp: &SpParams,
|
||||
idp: &IdpMetadata,
|
||||
now: OffsetDateTime,
|
||||
clock_skew: Duration,
|
||||
) -> Result<VerifiedResponse, SamlError> {
|
||||
// 1. Cryptographically verify the signature against the pinned IdP cert(s).
|
||||
// `trusted_keys_only` ignores any cert embedded in the document's
|
||||
// KeyInfo, so an attacker can't substitute their own key.
|
||||
let verified_uris = verify_signature(xml, &idp.signing_certs_der)?;
|
||||
|
||||
// 2. Parse for semantic validation.
|
||||
let doc = Document::parse(xml).map_err(|e| SamlError::Xml(e.to_string()))?;
|
||||
let root = doc.root_element();
|
||||
if root.tag_name().name() != "Response" {
|
||||
return Err(SamlError::MissingElement("Response".into()));
|
||||
}
|
||||
let response_id = root.attribute("ID").map(str::to_owned);
|
||||
let in_response_to = root.attribute("InResponseTo").map(str::to_owned);
|
||||
|
||||
// 3. Status must be Success.
|
||||
let status_value = root
|
||||
.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == "StatusCode")
|
||||
.and_then(|sc| sc.attribute("Value"))
|
||||
.unwrap_or("");
|
||||
if status_value != STATUS_SUCCESS && !status_value.ends_with(":Success") {
|
||||
return Err(SamlError::Status(status_value.to_owned()));
|
||||
}
|
||||
|
||||
// 4. Destination (if the IdP set one) must be our ACS.
|
||||
if let Some(dest) = root.attribute("Destination") {
|
||||
if !urls_equal(dest, &sp.acs_url) {
|
||||
return Err(SamlError::DestinationMismatch);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. Exactly one (unencrypted) Assertion.
|
||||
if root
|
||||
.descendants()
|
||||
.any(|n| n.is_element() && n.tag_name().name() == "EncryptedAssertion")
|
||||
{
|
||||
return Err(SamlError::EncryptedAssertionUnsupported);
|
||||
}
|
||||
let assertions: Vec<Node<'_, '_>> = root
|
||||
.children()
|
||||
.filter(|c| c.is_element() && c.tag_name().name() == "Assertion")
|
||||
.collect();
|
||||
if assertions.len() != 1 {
|
||||
return Err(SamlError::AssertionCount(assertions.len()));
|
||||
}
|
||||
let assertion = assertions[0];
|
||||
let assertion_id = assertion
|
||||
.attribute("ID")
|
||||
.map(str::to_owned)
|
||||
.ok_or_else(|| SamlError::MissingElement("Assertion/@ID".into()))?;
|
||||
|
||||
// 6. The signature must actually cover the assertion we're about to trust:
|
||||
// either the assertion itself, the enclosing response, or the whole
|
||||
// document. (bergshamra's strict_verification already constrains where
|
||||
// the signed element may sit; this ties it to *our* assertion.)
|
||||
let covers_assertion = verified_uris.iter().any(|u| {
|
||||
u.is_empty()
|
||||
|| u == &format!("#{assertion_id}")
|
||||
|| response_id
|
||||
.as_ref()
|
||||
.is_some_and(|rid| u == &format!("#{rid}"))
|
||||
});
|
||||
if !covers_assertion {
|
||||
return Err(SamlError::SignatureScope);
|
||||
}
|
||||
|
||||
// 7. Issuer must be the configured IdP.
|
||||
let issuer = first_child(assertion, "Issuer")
|
||||
.map(text_of)
|
||||
.unwrap_or_default();
|
||||
if !idp.entity_id.is_empty() && issuer != idp.entity_id {
|
||||
return Err(SamlError::IssuerMismatch);
|
||||
}
|
||||
|
||||
// 8. Subject → NameID + SubjectConfirmationData time/recipient checks.
|
||||
let subject = first_child(assertion, "Subject")
|
||||
.ok_or_else(|| SamlError::MissingElement("Subject".into()))?;
|
||||
let name_id = first_child(subject, "NameID")
|
||||
.map(text_of)
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| SamlError::MissingElement("NameID".into()))?;
|
||||
if let Some(scd) = subject
|
||||
.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == "SubjectConfirmationData")
|
||||
{
|
||||
if let Some(recipient) = scd.attribute("Recipient") {
|
||||
if !urls_equal(recipient, &sp.acs_url) {
|
||||
return Err(SamlError::DestinationMismatch);
|
||||
}
|
||||
}
|
||||
if let Some(noa) = scd.attribute("NotOnOrAfter") {
|
||||
let noa = parse_instant(noa)?;
|
||||
if now >= noa + clock_skew {
|
||||
return Err(SamlError::TimeBounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 9. Conditions: time window + audience.
|
||||
let conditions = first_child(assertion, "Conditions");
|
||||
if let Some(cond) = conditions {
|
||||
if let Some(nb) = cond.attribute("NotBefore") {
|
||||
let nb = parse_instant(nb)?;
|
||||
if now < nb - clock_skew {
|
||||
return Err(SamlError::TimeBounds);
|
||||
}
|
||||
}
|
||||
}
|
||||
let assertion_expiry = conditions
|
||||
.and_then(|c| c.attribute("NotOnOrAfter"))
|
||||
.map(parse_instant)
|
||||
.transpose()?
|
||||
.ok_or_else(|| SamlError::MissingElement("Conditions/@NotOnOrAfter".into()))?;
|
||||
if now >= assertion_expiry + clock_skew {
|
||||
return Err(SamlError::TimeBounds);
|
||||
}
|
||||
|
||||
let audience_ok = conditions.is_some_and(|c| {
|
||||
c.descendants()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "Audience")
|
||||
.any(|a| text_of(a) == sp.entity_id)
|
||||
});
|
||||
if !audience_ok {
|
||||
return Err(SamlError::AudienceMismatch);
|
||||
}
|
||||
|
||||
// 10. Optional: SessionIndex + display-name attribute.
|
||||
let session_index = assertion
|
||||
.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == "AuthnStatement")
|
||||
.and_then(|a| a.attribute("SessionIndex"))
|
||||
.map(str::to_owned);
|
||||
|
||||
let display_name = extract_display_name(assertion);
|
||||
|
||||
Ok(VerifiedResponse {
|
||||
principal: VerifiedPrincipal {
|
||||
email: name_id.clone(),
|
||||
name_id,
|
||||
display_name,
|
||||
},
|
||||
in_response_to,
|
||||
assertion_id,
|
||||
assertion_expiry,
|
||||
session_index,
|
||||
})
|
||||
}
|
||||
|
||||
/// Verify the document's XML-DSig against each pinned IdP cert in turn
|
||||
/// (handles key rotation), returning the verified `<Reference>` URIs.
|
||||
fn verify_signature(xml: &str, certs_der: &[Vec<u8>]) -> Result<Vec<String>, SamlError> {
|
||||
let mut last_err = String::from("no signing certificate matched");
|
||||
for der in certs_der {
|
||||
let key = match bergshamra::keys::loader::load_x509_cert_der(der) {
|
||||
Ok(k) => k,
|
||||
Err(e) => {
|
||||
last_err = e.to_string();
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let mut km = bergshamra::keys::KeysManager::new();
|
||||
km.add_key(key);
|
||||
// trusted_keys_only: only ever trust the pinned IdP key, never an
|
||||
// inline KeyInfo cert. strict_verification: XSW positional defense.
|
||||
let ctx = bergshamra::DsigContext::new(km)
|
||||
.with_trusted_keys_only(true)
|
||||
.with_strict_verification(true);
|
||||
match bergshamra::verify(&ctx, xml) {
|
||||
Ok(bergshamra::VerifyResult::Valid { references, .. }) => {
|
||||
return Ok(references.into_iter().map(|r| r.uri).collect());
|
||||
}
|
||||
Ok(bergshamra::VerifyResult::Invalid { reason }) => last_err = reason,
|
||||
Err(e) => last_err = e.to_string(),
|
||||
}
|
||||
}
|
||||
Err(SamlError::Signature(last_err))
|
||||
}
|
||||
|
||||
/// Pull a display name from the assertion's attribute statement, trying the
|
||||
/// common attribute names IdPs use (FleetDM checks the same set).
|
||||
fn extract_display_name(assertion: Node<'_, '_>) -> Option<String> {
|
||||
const WANTED: &[&str] = &[
|
||||
"name",
|
||||
"displayname",
|
||||
"cn",
|
||||
"urn:oid:2.5.4.3",
|
||||
"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name",
|
||||
];
|
||||
for attr in assertion
|
||||
.descendants()
|
||||
.filter(|n| n.is_element() && n.tag_name().name() == "Attribute")
|
||||
{
|
||||
let key = attr
|
||||
.attribute("Name")
|
||||
.or_else(|| attr.attribute("FriendlyName"))
|
||||
.unwrap_or("")
|
||||
.to_ascii_lowercase();
|
||||
if WANTED.contains(&key.as_str()) {
|
||||
if let Some(val) = attr
|
||||
.descendants()
|
||||
.find(|n| n.is_element() && n.tag_name().name() == "AttributeValue")
|
||||
{
|
||||
let v = text_of(val);
|
||||
if !v.is_empty() {
|
||||
return Some(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn first_child<'a, 'i>(n: Node<'a, 'i>, local: &str) -> Option<Node<'a, 'i>> {
|
||||
n.children()
|
||||
.find(|c| c.is_element() && c.tag_name().name() == local)
|
||||
}
|
||||
|
||||
fn text_of(n: Node<'_, '_>) -> String {
|
||||
n.children()
|
||||
.filter(Node::is_text)
|
||||
.filter_map(|c| c.text())
|
||||
.collect::<String>()
|
||||
.trim()
|
||||
.to_owned()
|
||||
}
|
||||
|
||||
/// Parse an `xs:dateTime` (e.g. `2026-05-31T12:00:00.000Z`).
|
||||
fn parse_instant(s: &str) -> Result<OffsetDateTime, SamlError> {
|
||||
OffsetDateTime::parse(s.trim(), &Rfc3339).map_err(|e| SamlError::Timestamp(format!("{s}: {e}")))
|
||||
}
|
||||
|
||||
/// Compare two URLs for SAML endpoint-matching purposes: exact, or differing
|
||||
/// only by a single trailing slash.
|
||||
fn urls_equal(a: &str, b: &str) -> bool {
|
||||
a == b || a.trim_end_matches('/') == b.trim_end_matches('/')
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! End-to-end SAML SP tests.
|
||||
//!
|
||||
//! We mint a throwaway self-signed cert/key with `rcgen`, sign a SAML Response
|
||||
//! template with `bergshamra::sign` (the same engine that verifies it), and
|
||||
//! drive [`response::consume`] through the accept path and every reject path.
|
||||
//! This proves both the signature wiring and the SP-semantic checks.
|
||||
|
||||
use time::format_description::well_known::Rfc3339;
|
||||
use time::{Duration, OffsetDateTime};
|
||||
|
||||
use super::metadata::IdpMetadata;
|
||||
use super::{response, SamlError, SpParams};
|
||||
|
||||
const SP_ENTITY: &str = "https://pxe.example.com";
|
||||
const ACS: &str = "https://pxe.example.com/api/sso/acs";
|
||||
const IDP_ENTITY: &str = "https://idp.example.com/realms/fleet";
|
||||
const EMAIL: &str = "[email protected]";
|
||||
|
||||
struct TestIdp {
|
||||
cert_der: Vec<u8>,
|
||||
key_pem: String,
|
||||
}
|
||||
|
||||
fn test_idp() -> TestIdp {
|
||||
let ck = rcgen::generate_simple_self_signed(vec!["idp.example.com".to_string()]).unwrap();
|
||||
TestIdp {
|
||||
cert_der: ck.cert.der().as_ref().to_vec(),
|
||||
key_pem: ck.key_pair.serialize_pem(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fmt(t: OffsetDateTime) -> String {
|
||||
t.replace_nanosecond(0).unwrap().format(&Rfc3339).unwrap()
|
||||
}
|
||||
|
||||
/// Knobs for building a response template — defaults are a valid response.
|
||||
struct Resp {
|
||||
issuer: String,
|
||||
audience: String,
|
||||
status: String,
|
||||
not_before: OffsetDateTime,
|
||||
not_on_or_after: OffsetDateTime,
|
||||
in_response_to: Option<String>,
|
||||
recipient: String,
|
||||
}
|
||||
|
||||
impl Default for Resp {
|
||||
fn default() -> Self {
|
||||
let now = OffsetDateTime::now_utc();
|
||||
Self {
|
||||
issuer: IDP_ENTITY.into(),
|
||||
audience: SP_ENTITY.into(),
|
||||
status: "urn:oasis:names:tc:SAML:2.0:status:Success".into(),
|
||||
not_before: now - Duration::minutes(5),
|
||||
not_on_or_after: now + Duration::hours(1),
|
||||
in_response_to: Some("_req-abc".into()),
|
||||
recipient: ACS.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Resp {
|
||||
/// The unsigned template (a `<ds:Signature>` with empty values).
|
||||
fn template(&self) -> String {
|
||||
let now = fmt(OffsetDateTime::now_utc());
|
||||
let irt = self
|
||||
.in_response_to
|
||||
.as_ref()
|
||||
.map(|v| format!(r#" InResponseTo="{v}""#))
|
||||
.unwrap_or_default();
|
||||
format!(
|
||||
r##"<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_resp1" Version="2.0" IssueInstant="{now}" Destination="{ACS}"{irt}>
|
||||
<saml:Issuer>{issuer}</saml:Issuer>
|
||||
<samlp:Status><samlp:StatusCode Value="{status}"/></samlp:Status>
|
||||
<saml:Assertion ID="_assertion1" Version="2.0" IssueInstant="{now}">
|
||||
<saml:Issuer>{issuer}</saml:Issuer>
|
||||
<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
|
||||
<ds:SignedInfo>
|
||||
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
|
||||
<ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"/>
|
||||
<ds:Reference URI="#_assertion1">
|
||||
<ds:Transforms>
|
||||
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
|
||||
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
|
||||
</ds:Transforms>
|
||||
<ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
|
||||
<ds:DigestValue></ds:DigestValue>
|
||||
</ds:Reference>
|
||||
</ds:SignedInfo>
|
||||
<ds:SignatureValue></ds:SignatureValue>
|
||||
</ds:Signature>
|
||||
<saml:Subject>
|
||||
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">{EMAIL}</saml:NameID>
|
||||
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
|
||||
<saml:SubjectConfirmationData Recipient="{recipient}" NotOnOrAfter="{noa}"{irt}/>
|
||||
</saml:SubjectConfirmation>
|
||||
</saml:Subject>
|
||||
<saml:Conditions NotBefore="{nb}" NotOnOrAfter="{noa}">
|
||||
<saml:AudienceRestriction><saml:Audience>{audience}</saml:Audience></saml:AudienceRestriction>
|
||||
</saml:Conditions>
|
||||
<saml:AuthnStatement AuthnInstant="{now}" SessionIndex="sess-123">
|
||||
<saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef></saml:AuthnContext>
|
||||
</saml:AuthnStatement>
|
||||
<saml:AttributeStatement>
|
||||
<saml:Attribute Name="displayName"><saml:AttributeValue>Miles Ward</saml:AttributeValue></saml:Attribute>
|
||||
</saml:AttributeStatement>
|
||||
</saml:Assertion>
|
||||
</samlp:Response>"##,
|
||||
issuer = self.issuer,
|
||||
status = self.status,
|
||||
audience = self.audience,
|
||||
recipient = self.recipient,
|
||||
nb = fmt(self.not_before),
|
||||
noa = fmt(self.not_on_or_after),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn sign(template: &str, key_pem: &str) -> String {
|
||||
let key = bergshamra::keys::loader::load_pem_auto(key_pem.as_bytes(), None)
|
||||
.expect("load test signing key");
|
||||
let mut km = bergshamra::keys::KeysManager::new();
|
||||
km.add_key(key);
|
||||
let ctx = bergshamra::DsigContext::new(km);
|
||||
bergshamra::sign(&ctx, template).expect("sign test response")
|
||||
}
|
||||
|
||||
fn sp() -> SpParams {
|
||||
SpParams {
|
||||
entity_id: SP_ENTITY.into(),
|
||||
acs_url: ACS.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn idp(cert_der: Vec<u8>) -> IdpMetadata {
|
||||
IdpMetadata {
|
||||
entity_id: IDP_ENTITY.into(),
|
||||
sso_redirect_url: None,
|
||||
sso_post_url: None,
|
||||
signing_certs_der: vec![cert_der],
|
||||
}
|
||||
}
|
||||
|
||||
fn consume(xml: &str, cert_der: Vec<u8>) -> Result<response::VerifiedResponse, SamlError> {
|
||||
response::consume(
|
||||
xml,
|
||||
&sp(),
|
||||
&idp(cert_der),
|
||||
OffsetDateTime::now_utc(),
|
||||
Duration::seconds(60),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn good_response_yields_principal() {
|
||||
let t = test_idp();
|
||||
let signed = sign(&Resp::default().template(), &t.key_pem);
|
||||
let out = consume(&signed, t.cert_der).expect("valid response should verify");
|
||||
assert_eq!(out.principal.email, EMAIL);
|
||||
assert_eq!(out.principal.name_id, EMAIL);
|
||||
assert_eq!(out.principal.display_name.as_deref(), Some("Miles Ward"));
|
||||
assert_eq!(out.in_response_to.as_deref(), Some("_req-abc"));
|
||||
assert_eq!(out.assertion_id, "_assertion1");
|
||||
assert_eq!(out.session_index.as_deref(), Some("sess-123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_assertion_is_rejected() {
|
||||
let t = test_idp();
|
||||
let signed = sign(&Resp::default().template(), &t.key_pem);
|
||||
// Flip the subject email after signing — breaks the digest.
|
||||
let tampered = signed.replace(EMAIL, "[email protected]");
|
||||
assert_ne!(signed, tampered);
|
||||
assert!(matches!(
|
||||
consume(&tampered, t.cert_der),
|
||||
Err(SamlError::Signature(_) | SamlError::SignatureScope)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsigned_response_is_rejected() {
|
||||
let t = test_idp();
|
||||
// Feed the *unsigned* template (empty SignatureValue) straight in.
|
||||
let unsigned = Resp::default().template();
|
||||
assert!(matches!(
|
||||
consume(&unsigned, t.cert_der),
|
||||
Err(SamlError::Signature(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_signing_key_is_rejected() {
|
||||
let signer = test_idp();
|
||||
let other = test_idp(); // different keypair pinned as the "IdP" cert
|
||||
let signed = sign(&Resp::default().template(), &signer.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, other.cert_der),
|
||||
Err(SamlError::Signature(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_audience_is_rejected() {
|
||||
let t = test_idp();
|
||||
let r = Resp {
|
||||
audience: "https://someone-else.example".into(),
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, t.cert_der),
|
||||
Err(SamlError::AudienceMismatch)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_assertion_is_rejected() {
|
||||
let t = test_idp();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let r = Resp {
|
||||
not_before: now - Duration::hours(2),
|
||||
not_on_or_after: now - Duration::hours(1),
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, t.cert_der),
|
||||
Err(SamlError::TimeBounds)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn future_assertion_is_rejected() {
|
||||
let t = test_idp();
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let r = Resp {
|
||||
not_before: now + Duration::hours(1),
|
||||
not_on_or_after: now + Duration::hours(2),
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, t.cert_der),
|
||||
Err(SamlError::TimeBounds)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_issuer_is_rejected() {
|
||||
let t = test_idp();
|
||||
let r = Resp {
|
||||
issuer: "https://evil-idp.example".into(),
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, t.cert_der),
|
||||
Err(SamlError::IssuerMismatch)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_success_status_is_rejected() {
|
||||
let t = test_idp();
|
||||
let r = Resp {
|
||||
status: "urn:oasis:names:tc:SAML:2.0:status:Requester".into(),
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
assert!(matches!(
|
||||
consume(&signed, t.cert_der),
|
||||
Err(SamlError::Status(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idp_initiated_has_no_in_response_to() {
|
||||
// No InResponseTo => the HTTP layer must gate it behind allow_idp_initiated.
|
||||
let t = test_idp();
|
||||
let r = Resp {
|
||||
in_response_to: None,
|
||||
..Resp::default()
|
||||
};
|
||||
let signed = sign(&r.template(), &t.key_pem);
|
||||
let out = consume(&signed, t.cert_der).expect("unsolicited but otherwise valid");
|
||||
assert!(out.in_response_to.is_none());
|
||||
}
|
||||
+84
-12
@@ -1,16 +1,17 @@
|
||||
//! SAML SSO configuration — FleetDM-shaped, storage-only for v0.4.5.
|
||||
//! SAML SSO configuration — FleetDM-shaped.
|
||||
//!
|
||||
//! The operator pastes their IdP's metadata XML (or its URL) and a
|
||||
//! human-readable label; v0.4.5 just persists it. The actual SAML
|
||||
//! response-validation / JIT-provisioning flow lands in a later release
|
||||
//! — for now we cover the "configurable" half so an operator can teach
|
||||
//! OpenPXE about their IdP today and flip the switch on next upgrade.
|
||||
//! human-readable label. As of v0.5.1 the SAML login flow is wired
|
||||
//! end-to-end (see [`crate::saml`]): SP-initiated AuthnRequest, the ACS
|
||||
//! endpoint, pure-Rust signature verification, and operator-session
|
||||
//! minting. This module owns only the persisted *configuration*.
|
||||
//!
|
||||
//! Shape borrowed from <https://github.com/fleetdm/fleet>'s app-config
|
||||
//! SSO block, minus the user-RBAC fields (OpenPXE is single-tier: you
|
||||
//! have access or you don't). Entity ID is omitted from the operator
|
||||
//! UI per the v0.4.5 brief — it defaults to the advertised public base
|
||||
//! URL when SAML wiring lands, which is what most IdPs expect anyway.
|
||||
//! SSO block, minus the user-RBAC fields (OpenPXE is single-tier: any
|
||||
//! IdP-authenticated user the SP cryptographically verifies gets an
|
||||
//! operator session; there is no per-user role table). Entity ID is
|
||||
//! exposed (FleetDM-style) but defaults to the advertised public base
|
||||
//! URL when blank, which is what most IdPs expect anyway.
|
||||
|
||||
use parking_lot::RwLock;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -47,6 +48,18 @@ pub struct SsoConfig {
|
||||
/// future SAML flow; not validated here beyond a basic length cap.
|
||||
#[serde(default)]
|
||||
pub metadata_url: String,
|
||||
/// SP Entity ID advertised to the IdP — mirrors FleetDM's "Entity ID".
|
||||
/// Must exactly match the SP/Relying-Party entry configured on the IdP.
|
||||
/// Empty falls back to the advertised public base URL at runtime, which
|
||||
/// is what most IdPs expect. Length-capped at [`MAX_URL_LEN`].
|
||||
#[serde(default)]
|
||||
pub entity_id: String,
|
||||
/// Allow IdP-initiated login — an unsolicited `<Response>` POSTed to the
|
||||
/// ACS with no `InResponseTo`. Mirrors FleetDM's "Allow SSO login
|
||||
/// initiated by identity provider". Default off; SP-initiated (the
|
||||
/// "Sign in with X" button) is always allowed regardless.
|
||||
#[serde(default)]
|
||||
pub allow_idp_initiated: bool,
|
||||
}
|
||||
|
||||
impl SsoConfig {
|
||||
@@ -56,8 +69,7 @@ impl SsoConfig {
|
||||
/// surface a yellow "configured but not live yet" hint.
|
||||
#[must_use]
|
||||
pub fn is_usable(&self) -> bool {
|
||||
self.enabled
|
||||
&& (!self.metadata.trim().is_empty() || !self.metadata_url.trim().is_empty())
|
||||
self.enabled && (!self.metadata.trim().is_empty() || !self.metadata_url.trim().is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,6 +120,12 @@ impl SsoStore {
|
||||
cfg.idp_logo_url = cfg.idp_logo_url.trim().to_string();
|
||||
cfg.metadata = cfg.metadata.trim().to_string();
|
||||
cfg.metadata_url = cfg.metadata_url.trim().to_string();
|
||||
cfg.entity_id = cfg.entity_id.trim().to_string();
|
||||
if cfg.entity_id.len() > MAX_URL_LEN {
|
||||
return Err(Error::Invalid(format!(
|
||||
"entity_id exceeds {MAX_URL_LEN}-char cap"
|
||||
)));
|
||||
}
|
||||
if cfg.metadata.len() > MAX_METADATA_BYTES {
|
||||
return Err(Error::Invalid(format!(
|
||||
"metadata XML exceeds {MAX_METADATA_BYTES}-byte cap"
|
||||
@@ -217,6 +235,8 @@ mod tests {
|
||||
metadata: String::new(),
|
||||
metadata_url: "https://idp.example.com/metadata".into(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
})
|
||||
.unwrap();
|
||||
drop(s);
|
||||
@@ -239,6 +259,8 @@ mod tests {
|
||||
metadata: xml.into(),
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
})
|
||||
.unwrap();
|
||||
assert!(s.snapshot().is_usable());
|
||||
@@ -254,6 +276,8 @@ mod tests {
|
||||
metadata: String::new(),
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
});
|
||||
assert!(matches!(r, Err(Error::Invalid(_))));
|
||||
// …and a disabled blank config is fine.
|
||||
@@ -270,6 +294,8 @@ mod tests {
|
||||
metadata: String::new(),
|
||||
metadata_url: "ftp://idp.example.com/metadata".into(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
});
|
||||
assert!(matches!(r, Err(Error::Invalid(_))));
|
||||
}
|
||||
@@ -287,6 +313,8 @@ mod tests {
|
||||
metadata: String::new(),
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: "data:image/png;base64,...".into(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
});
|
||||
assert!(matches!(r, Err(Error::Invalid(_))));
|
||||
// Real HTTPS URL is fine.
|
||||
@@ -296,9 +324,51 @@ mod tests {
|
||||
metadata: String::new(),
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: "https://idp.example.com/logo.png".into(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(s.snapshot().idp_logo_url, "https://idp.example.com/logo.png");
|
||||
assert_eq!(
|
||||
s.snapshot().idp_logo_url,
|
||||
"https://idp.example.com/logo.png"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_id_and_idp_initiated_round_trip() {
|
||||
// v0.5.1: SP Entity ID + IdP-initiated toggle persist across reload.
|
||||
let dir = tempdir().unwrap();
|
||||
let s = SsoStore::load_or_default(dir.path());
|
||||
s.replace(SsoConfig {
|
||||
enabled: true,
|
||||
idp_name: "Keycloak".into(),
|
||||
metadata: String::new(),
|
||||
metadata_url: "https://idp.example.com/metadata".into(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: "https://pxe.example.com".into(),
|
||||
allow_idp_initiated: true,
|
||||
})
|
||||
.unwrap();
|
||||
drop(s);
|
||||
let cfg = SsoStore::load_or_default(dir.path()).snapshot();
|
||||
assert_eq!(cfg.entity_id, "https://pxe.example.com");
|
||||
assert!(cfg.allow_idp_initiated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entity_id_cap_enforced() {
|
||||
let dir = tempdir().unwrap();
|
||||
let s = SsoStore::load_or_default(dir.path());
|
||||
let r = s.replace(SsoConfig {
|
||||
enabled: false,
|
||||
idp_name: String::new(),
|
||||
metadata: String::new(),
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: "x".repeat(MAX_URL_LEN + 1),
|
||||
allow_idp_initiated: false,
|
||||
});
|
||||
assert!(matches!(r, Err(Error::Invalid(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -312,6 +382,8 @@ mod tests {
|
||||
metadata: oversize,
|
||||
metadata_url: String::new(),
|
||||
idp_logo_url: String::new(),
|
||||
entity_id: String::new(),
|
||||
allow_idp_initiated: false,
|
||||
});
|
||||
assert!(matches!(r, Err(Error::Invalid(_))));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user