1use std::collections::HashMap;
5
6use serde_json::{Map, Value};
7
8use crate::artifact::{new_id, resolve_artifact, ArtifactInput};
9use crate::bindings::{post_form_html, query_pairs, read_post, read_redirect, redirect_query};
10use crate::canon::sign_enveloped;
11use crate::clock::iso_now;
12use crate::config::{read_config_file, resolve_config, Config};
13use crate::error::{err, SamlError};
14use crate::http::{send, TlsOptions};
15use crate::keys::b64_standard;
16use crate::metadata::{metadata_document, read_idp_metadata_filtered, IdpMetadata};
17use crate::replay::MemoryReplayCache;
18use crate::response::{validate_response, Received, SamlLogin, ValidationContext};
19use crate::xml::{escape_xml, BINDING_ARTIFACT, BINDING_POST, BINDING_REDIRECT, NS_SAML, NS_SAMLP};
20
21#[derive(Default)]
23pub struct LoginOptions {
24 pub relay_state: Option<String>,
25 pub force_authn: bool,
26 pub is_passive: bool,
27 pub subject_hint: Option<String>,
28 pub subject_hint_format: Option<String>,
29 pub request_binding: String,
30 pub response_binding: String,
31 pub nonce: String,
32}
33
34#[derive(Debug)]
36pub struct LoginRequest {
37 pub id: String,
38 pub binding: String,
39 pub response_binding: String,
40 pub url: String,
41 pub xml: String,
42 pub fields: Vec<(String, String)>,
43 pub html: String,
44}
45
46pub enum AcsBody {
48 None,
49 Text(String),
50 Map(Vec<(String, String)>),
51}
52
53pub struct ServiceProvider {
55 pub config: Config,
56 pub idp: IdpMetadata,
57 replay: MemoryReplayCache,
58}
59
60impl ServiceProvider {
61 pub fn create(config: &Map<String, Value>, base_dir: &str, replay: Option<MemoryReplayCache>) -> Result<Self, SamlError> {
63 let resolved = resolve_config(config, base_dir)?;
64 let mut sp = Self { config: resolved, idp: empty_idp(), replay: replay.unwrap_or_else(|| MemoryReplayCache::new(0)) };
65 sp.refresh_metadata()?;
66 Ok(sp)
67 }
68
69 pub fn from_file(path: &str, overrides: Option<&Map<String, Value>>, replay: Option<MemoryReplayCache>) -> Result<Self, SamlError> {
71 let resolved = read_config_file(path, overrides)?;
72 let mut sp = Self { config: resolved, idp: empty_idp(), replay: replay.unwrap_or_else(|| MemoryReplayCache::new(0)) };
73 sp.refresh_metadata()?;
74 Ok(sp)
75 }
76
77 fn tls(&self) -> Option<TlsOptions> {
78 if self.config.idp_ca.is_empty() {
79 None
80 } else {
81 Some(TlsOptions { ca: self.config.idp_ca.clone(), cert: String::new(), key: String::new() })
82 }
83 }
84
85 pub fn refresh_metadata(&mut self) -> Result<(), SamlError> {
87 let source = self.config.idp_metadata.clone();
88 let xml = if source.starts_with('<') {
89 source
90 } else if source.starts_with("http://") || source.starts_with("https://") {
91 let answer = send(&source, "GET", &[("accept", "application/samlmetadata+xml, application/xml, text/xml")], "", self.tls().as_ref(), "metadata")?;
92 if answer.status != 200 {
93 return Err(err("metadata", format!("{source} answered HTTP {}", answer.status)));
94 }
95 answer.body
96 } else {
97 std::fs::read_to_string(&source).map_err(|_| err("metadata", format!("the identity provider metadata file {source} cannot be read")))?
98 };
99 self.idp = read_idp_metadata_filtered(&xml, &self.config.idp_entity_id)?;
100 Ok(())
101 }
102
103 pub fn metadata(&self) -> String {
105 metadata_document(&self.config)
106 }
107
108 pub fn login(&self, opt: &LoginOptions) -> Result<LoginRequest, SamlError> {
110 let binding = if opt.request_binding.is_empty() { self.config.request_binding.as_str() } else { opt.request_binding.as_str() };
111 let response = if opt.response_binding.is_empty() { self.config.response_binding.as_str() } else { opt.response_binding.as_str() };
112 if response == "artifact" && self.idp.artifact_resolution_services.is_empty() {
113 return Err(err("config", "the identity provider has no SOAP ArtifactResolutionService, so the Response cannot come by artifact"));
114 }
115 let destination = self.idp.sso.get(binding).cloned().unwrap_or_default();
116 if destination.is_empty() {
117 let which = if binding == "post" { "POST" } else { "Redirect" };
118 return Err(err("config", format!("the identity provider has no SingleSignOnService on HTTP-{which}")));
119 }
120 if let Some(relay) = &opt.relay_state {
121 if relay.len() > 80 {
122 return Err(err("config", "relayState is longer than the 80 bytes the bindings allow"));
123 }
124 }
125 let element_id = new_id();
126 let force = if opt.force_authn { " ForceAuthn=\"true\"" } else { "" };
127 let passive = if opt.is_passive { " Is passive=\"true\"" } else { "" };
128 let subject = if let Some(hint) = &opt.subject_hint {
129 let form = match &opt.subject_hint_format {
130 Some(format) if !format.is_empty() => format!(" Format=\"{}\"", escape_xml(format)),
131 _ => String::new(),
132 };
133 format!("<saml:Subject><saml:NameID{form}>{}</saml:NameID></saml:Subject>", escape_xml(hint))
134 } else {
135 String::new()
136 };
137 let policy = if self.config.name_id_format.is_empty() {
138 "<samlp:NameIDPolicy AllowCreate=\"true\"/>".to_string()
139 } else {
140 format!("<samlp:NameIDPolicy Format=\"{}\" AllowCreate=\"true\"/>", escape_xml(&self.config.name_id_format))
141 };
142 let protocol = match response {
143 "post" => BINDING_POST,
144 "redirect" => BINDING_REDIRECT,
145 "artifact" => BINDING_ARTIFACT,
146 _ => BINDING_POST,
147 };
148 let xml = format!(
149 "<samlp:AuthnRequest xmlns:samlp=\"{NS_SAMLP}\" xmlns:saml=\"{NS_SAML}\" ID=\"{element_id}\" Version=\"2.0\" IssueInstant=\"{}\" Destination=\"{}\" AssertionConsumerServiceURL=\"{}\" ProtocolBinding=\"{protocol}\"{force}{passive}><saml:Issuer>{}</saml:Issuer>{subject}{policy}</samlp:AuthnRequest>",
150 iso_now(),
151 escape_xml(&destination),
152 escape_xml(&self.config.acs_url),
153 escape_xml(&self.config.entity_id)
154 );
155 if binding == "redirect" {
156 let query = redirect_query("SAMLRequest", &xml, opt.relay_state.as_deref(), &self.config.private_key)?;
157 let join = if destination.contains('?') { "&" } else { "?" };
158 return Ok(LoginRequest {
159 id: element_id,
160 binding: binding.to_string(),
161 response_binding: response.to_string(),
162 url: format!("{destination}{join}{query}"),
163 xml,
164 fields: Vec::new(),
165 html: String::new(),
166 });
167 }
168 let signed = sign_enveloped(&xml, &element_id, &self.config.private_key, &self.config.certificate_der)?;
169 let mut fields = vec![("SAMLRequest".to_string(), b64_standard(signed.as_bytes()))];
170 if let Some(relay) = &opt.relay_state {
171 fields.push(("RelayState".to_string(), relay.clone()));
172 }
173 let pairs: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
174 let html = post_form_html(&destination, &pairs, &opt.nonce, "");
175 Ok(LoginRequest {
176 id: element_id,
177 binding: binding.to_string(),
178 response_binding: response.to_string(),
179 url: destination,
180 xml: signed,
181 fields,
182 html,
183 })
184 }
185
186 pub fn acs(&self, method: &str, raw_url: &str, body: &AcsBody, request_ids: &[String]) -> Result<SamlLogin, SamlError> {
188 let verb = method.to_ascii_uppercase();
189 let mut raw_query = String::new();
190 if let Some(index) = raw_url.find('?') {
191 raw_query = raw_url[index + 1..].to_string();
192 if let Some(hash) = raw_query.find('#') {
193 raw_query.truncate(hash);
194 }
195 }
196 let query = query_pairs(&raw_query);
197 let form = if verb == "POST" { form_of(body) } else { Vec::new() };
198 let q = |name: &str| query.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone());
199 let f = |name: &str| form.iter().find(|(k, _)| k == name).map(|(_, v)| v.clone());
200 let ctx = ValidationContext {
201 entity_id: &self.config.entity_id,
202 acs_url: &self.config.acs_url,
203 idp_entity_id: &self.idp.entity_id,
204 idp_certificates: &self.idp.certs,
205 decryption_key: &self.config.private_key,
206 clock_skew_ms: self.config.clock_skew_ms,
207 want_assertions_signed: self.config.want_assertions_signed,
208 want_assertions_encrypted: self.config.want_assertions_encrypted,
209 allow_unsolicited: self.config.allow_unsolicited,
210 replay: &self.replay,
211 expected_request_ids: request_ids,
212 };
213 let art = f("SAMLart").filter(|v| !v.is_empty()).or_else(|| q("SAMLart").filter(|v| !v.is_empty()));
214 if let Some(art) = art {
215 let tls = self.tls();
216 let (xml, response_id) = resolve_artifact(ArtifactInput {
217 artifact: &art,
218 entity_id: &self.config.entity_id,
219 idp_entity_id: &self.idp.entity_id,
220 services: &self.idp.artifact_resolution_services,
221 first_ars: &self.idp.first_ars,
222 idp_certificates: &self.idp.certs,
223 key: &self.config.private_key,
224 certificate_der: &self.config.certificate_der,
225 tls: tls.as_ref(),
226 })?;
227 let relay = if f("SAMLart").is_some() { f("RelayState") } else { q("RelayState") };
228 return validate_response(&Received { xml, binding: "artifact".to_string(), relay_state: relay, authenticated_by_binding: true, response_id }, &ctx);
229 }
230 if verb == "POST" {
231 if let Some(value) = f("SAMLResponse").filter(|v| !v.is_empty()) {
232 let xml = read_post(&value, "SAMLResponse")?;
233 let root = crate::canon::parse_tree(&xml, "the Response")?;
234 let response_id = root.attr_or("ID").to_string();
235 return validate_response(&Received {
236 xml,
237 binding: "post".to_string(),
238 relay_state: f("RelayState"),
239 authenticated_by_binding: false,
240 response_id,
241 }, &ctx);
242 }
243 }
244 if q("SAMLResponse").is_some_and(|v| !v.is_empty()) {
245 let message = read_redirect(&raw_query, "SAMLResponse", &self.idp.certs)?;
246 let root = crate::canon::parse_tree(&message.xml, "the Response")?;
247 let response_id = root.attr_or("ID").to_string();
248 return validate_response(&Received {
249 xml: message.xml,
250 binding: "redirect".to_string(),
251 relay_state: message.relay_state,
252 authenticated_by_binding: message.signed,
253 response_id,
254 }, &ctx);
255 }
256 Err(err("binding", "the request carries no SAMLResponse or SAMLart"))
257 }
258}
259
260fn form_of(body: &AcsBody) -> Vec<(String, String)> {
261 match body {
262 AcsBody::None => Vec::new(),
263 AcsBody::Text(text) => query_pairs(text),
264 AcsBody::Map(pairs) => pairs.clone(),
265 }
266}
267
268fn empty_idp() -> IdpMetadata {
269 IdpMetadata {
270 entity_id: String::new(),
271 sso: HashMap::new(),
272 artifact_resolution_services: HashMap::new(),
273 first_ars: String::new(),
274 certs: Vec::new(),
275 want_authn_requests_signed: false,
276 }
277}