Skip to main content

saml2_sp/
config.rs

1// SPDX-FileCopyrightText: 2026 Iya CyberSecurity Solutions, LLC
2// SPDX-License-Identifier: MIT
3
4use std::path::{Path, PathBuf};
5
6use rsa::RsaPrivateKey;
7use serde_json::{Map, Value};
8
9use crate::error::{err, SamlError};
10use crate::keys::{certificate_pem, load_certificate_der, load_private_key, private_pem, same_public};
11
12/// Configuration with its files read and its defaults filled in.
13/// `signals` is present only when CAEP and RISC are off. `None` means on.
14pub struct Config {
15    pub entity_id: String,
16    pub acs_url: String,
17    pub private_key_pem: String,
18    pub certificate_pem: String,
19    pub idp_metadata: String,
20    pub request_binding: String,
21    pub response_binding: String,
22    pub clock_skew_ms: i64,
23    pub want_assertions_signed: bool,
24    pub want_assertions_encrypted: bool,
25    pub allow_unsolicited: bool,
26    pub signals: Option<bool>,
27    pub idp_ca: String,
28    pub idp_entity_id: String,
29    pub name_id_format: String,
30    pub(crate) private_key: RsaPrivateKey,
31    pub(crate) certificate_der: Vec<u8>,
32}
33
34impl std::fmt::Debug for Config {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("Config")
37            .field("entity_id", &self.entity_id)
38            .field("acs_url", &self.acs_url)
39            .field("request_binding", &self.request_binding)
40            .field("response_binding", &self.response_binding)
41            .field("clock_skew_ms", &self.clock_skew_ms)
42            .field("want_assertions_signed", &self.want_assertions_signed)
43            .field("want_assertions_encrypted", &self.want_assertions_encrypted)
44            .field("allow_unsolicited", &self.allow_unsolicited)
45            .field("signals", &self.signals)
46            .finish()
47    }
48}
49
50impl Config {
51    pub fn has(&self, key: &str) -> bool {
52        key == "signals" && self.signals.is_some()
53    }
54}
55
56fn expand(value: &str) -> Result<String, SamlError> {
57    let mut value = value.to_string();
58    let mut seen = 0;
59    loop {
60        if value.starts_with("env:") || value.starts_with("file:") {
61            seen += 1;
62            if seen > 4 {
63                return Err(err("config", format!("the placeholder {value} is nested too deeply")));
64            }
65            if let Some(name) = value.strip_prefix("env:") {
66                let got = std::env::var(name).ok();
67                if name.is_empty() || got.is_none() {
68                    let shown = if name.is_empty() { value.clone() } else { name.to_string() };
69                    return Err(err("config", format!("environment variable {shown} is not set")));
70                }
71                value = got.unwrap();
72                continue;
73            }
74            value = value[5..].to_string();
75            continue;
76        }
77        return Ok(value);
78    }
79}
80
81fn looks_like_pem(value: &str) -> bool {
82    value.contains("-----BEGIN ")
83}
84
85fn material(value: &str, base_dir: &Path, what: &str) -> Result<String, SamlError> {
86    let value = expand(value)?;
87    if looks_like_pem(&value) {
88        return Ok(value);
89    }
90    let path = if Path::new(&value).is_absolute() {
91        PathBuf::from(&value)
92    } else {
93        base_dir.join(&value)
94    };
95    let path = path.canonicalize().unwrap_or(path);
96    std::fs::read_to_string(&path).map_err(|e| err("config", format!("{what} is neither a PEM nor a readable file ({}): {e}", path.display())))
97}
98
99fn absolute(value: Option<&Value>, what: &str) -> Result<String, SamlError> {
100    let text = value.and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
101    if text.is_empty() {
102        return Err(err("config", format!("{what} is required")));
103    }
104    if !(text.starts_with("https://") || text.starts_with("http://")) {
105        return Err(err("config", format!("{what} must be an absolute http(s) URL, not {text}")));
106    }
107    Ok(text)
108}
109
110fn stringify(value: &Value) -> String {
111    match value {
112        Value::String(text) => text.clone(),
113        other => other.to_string(),
114    }
115}
116
117fn one_of(value: Option<&Value>, allowed: &[&str], fallback: &str, what: &str) -> Result<String, SamlError> {
118    let Some(value) = value else { return Ok(fallback.to_string()) };
119    if value.is_null() || value.as_str() == Some("") {
120        return Ok(fallback.to_string());
121    }
122    let Some(text) = value.as_str() else {
123        return Err(err("config", format!("{what} must be one of {}, not {}", allowed.join(", "), stringify(value))));
124    };
125    if allowed.contains(&text) {
126        Ok(text.to_string())
127    } else {
128        Err(err("config", format!("{what} must be one of {}, not {text}", allowed.join(", "))))
129    }
130}
131
132fn as_number(value: &Value) -> Option<f64> {
133    value.as_f64().filter(|n| n.is_finite())
134}
135
136fn bool_or(value: &Value, fallback: bool) -> bool {
137    value.as_bool().unwrap_or(fallback)
138}
139
140/// Reads files named by the configuration and fills in defaults.
141pub fn resolve_config(config: &Map<String, Value>, base_dir: &str) -> Result<Config, SamlError> {
142    let base = if base_dir.is_empty() {
143        std::env::current_dir().map_err(|e| err("config", e.to_string()))?
144    } else {
145        PathBuf::from(base_dir)
146    };
147    let entity_id = config.get("entityId").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
148    if entity_id.is_empty() {
149        return Err(err("config", "entityId is required"));
150    }
151    let acs_url = absolute(config.get("acsUrl"), "acsUrl")?;
152    let key_text = config.get("privateKey").and_then(|v| v.as_str());
153    let cert_text = config.get("certificate").and_then(|v| v.as_str());
154    let (Some(key_text), Some(cert_text)) = (key_text, cert_text) else {
155        return Err(err("config", "privateKey and certificate are required: every AuthnRequest is signed"));
156    };
157    let key_pem = material(key_text, &base, "privateKey")?;
158    let cert_pem = material(cert_text, &base, "certificate")?;
159    let private_key = load_private_key(&key_pem).map_err(|e| {
160        if e.message.starts_with("the private key is ") {
161            e
162        } else if e.message.contains("cannot be read") {
163            e
164        } else {
165            err("config", format!("the private key or certificate cannot be read: {}", e.message))
166        }
167    })?;
168    let certificate_der = load_certificate_der(&cert_pem)?;
169    if !same_public(&private_key, &certificate_der) {
170        return Err(err("config", "the certificate is not for the private key"));
171    }
172    let mut idp_meta = config.get("idpMetadata").and_then(|v| v.as_str()).unwrap_or("").trim().to_string();
173    if idp_meta.is_empty() {
174        return Err(err("config", "idpMetadata is required"));
175    }
176    idp_meta = expand(&idp_meta)?;
177    if !(idp_meta.starts_with("http://") || idp_meta.starts_with("https://") || idp_meta.starts_with('<')) {
178        let path = if Path::new(&idp_meta).is_absolute() { PathBuf::from(&idp_meta) } else { base.join(&idp_meta) };
179        idp_meta = path.to_string_lossy().to_string();
180    }
181    let mut skew = 60.0;
182    if let Some(raw) = config.get("clockSkewSeconds") {
183        if !raw.is_null() {
184            let Some(n) = as_number(raw) else {
185                return Err(err("config", "clockSkewSeconds must be a number from 0 to 600"));
186            };
187            if !(0.0..=600.0).contains(&n) {
188                return Err(err("config", "clockSkewSeconds must be a number from 0 to 600"));
189            }
190            skew = n;
191        }
192    }
193    if let Some(raw) = config.get("signals") {
194        if !raw.is_boolean() {
195            return Err(err("config", "signals must be true or false"));
196        }
197    }
198    let request = one_of(config.get("requestBinding"), &["redirect", "post"], "redirect", "requestBinding")?;
199    let response = one_of(config.get("responseBinding"), &["post", "redirect", "artifact"], "post", "responseBinding")?;
200    let signals = if config.get("signals").and_then(|v| v.as_bool()) == Some(false) { Some(false) } else { None };
201    let mut idp_ca = String::new();
202    if let Some(text) = config.get("idpCa").and_then(|v| v.as_str()) {
203        if !text.is_empty() {
204            idp_ca = material(text, &base, "idpCa")?;
205        }
206    }
207    let idp_entity_id = config.get("idpEntityId").and_then(|v| v.as_str()).unwrap_or("").to_string();
208    let name_id_format = config.get("nameIdFormat").and_then(|v| v.as_str()).unwrap_or("").to_string();
209    let want_assertions_signed = config.get("wantAssertionsSigned").map(|v| if v.is_null() { true } else { bool_or(v, true) }).unwrap_or(true);
210    let want_assertions_encrypted = config.get("wantAssertionsEncrypted").map(|v| if v.is_null() { false } else { bool_or(v, false) }).unwrap_or(false);
211    let allow_unsolicited = config.get("allowUnsolicited").map(|v| if v.is_null() { false } else { bool_or(v, false) }).unwrap_or(false);
212    let private_key_pem = private_pem(&private_key);
213    Ok(Config {
214        entity_id,
215        acs_url,
216        private_key_pem,
217        certificate_pem: certificate_pem(&certificate_der),
218        idp_metadata: idp_meta,
219        request_binding: request,
220        response_binding: response,
221        clock_skew_ms: (skew as i64) * 1000,
222        want_assertions_signed,
223        want_assertions_encrypted,
224        allow_unsolicited,
225        signals,
226        idp_ca,
227        idp_entity_id,
228        name_id_format,
229        private_key,
230        certificate_der,
231    })
232}
233
234pub(crate) fn read_config_file(path: &str, overrides: Option<&Map<String, Value>>) -> Result<Config, SamlError> {
235    let raw = std::fs::read(path).map_err(|e| err("config", format!("{path} cannot be read as JSON: {e}")))?;
236    let parsed: Value = serde_json::from_slice(&raw).map_err(|e| err("config", format!("{path} cannot be read as JSON: {e}")))?;
237    let mut obj = parsed.as_object().cloned().ok_or_else(|| err("config", "the configuration must be an object"))?;
238    if let Some(overrides) = overrides {
239        for (k, v) in overrides {
240            if !v.is_null() {
241                obj.insert(k.clone(), v.clone());
242            }
243        }
244    }
245    let dir = Path::new(path).parent().map(|p| {
246        std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()).to_string_lossy().to_string()
247    }).unwrap_or_default();
248    let abs_dir = if Path::new(path).is_absolute() {
249        dir
250    } else {
251        std::env::current_dir().ok().and_then(|cwd| {
252            let full = cwd.join(path);
253            full.parent().map(|p| p.to_string_lossy().to_string())
254        }).unwrap_or(dir)
255    };
256    resolve_config(&obj, &abs_dir)
257}