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
// use tide::log;
use tide::Request;

use http_types::Mime;
use std::collections::HashMap;
use std::str::FromStr;

use saml_rs::sp::ServiceProvider;
use std::fs::read_to_string;
use std::path::Path;

/// Placeholder function for development purposes, just returns a "Doing nothing" 200 response.
pub async fn do_nothing(mut _req: Request<AppState>) -> tide::Result {
    Ok(tide::Response::builder(418)
        .body("Doing nothing")
        .content_type(Mime::from_str("text/html;charset=utf-8").unwrap())
        // .header("custom-header", "value")
        .build())
}

use openssl::x509::X509;

// #[derive(serde_deserialize, Debug)]
#[derive(Debug, Clone)]
pub struct ServerConfig {
    pub bind_address: String,
    pub public_hostname: String,
    pub tls_cert_path: String,
    pub tls_key_path: String,
    pub entity_id: String,
    pub sp_metadata_files: Option<Vec<&'static str>>,
    pub sp_metadata: HashMap<String, ServiceProvider>,
    // Default session lifetime across SPs
    pub session_lifetime: u128,

    pub saml_cert_path: String,
    pub saml_key_path: String,

    pub saml_signing_key: Option<openssl::pkey::PKey<openssl::pkey::Private>>,
    pub saml_signing_cert: Option<X509>,
}

fn load_sp_metadata(filenames: Vec<String>) -> HashMap<String, ServiceProvider> {
    // load the SP metadata files

    let mut sp_metadata = HashMap::new();
    eprintln!("Configuration has SP metadata filenames: {:?}", filenames);
    for filename in filenames {
        let expanded_filename: String = shellexpand::tilde(&filename).into_owned();
        if Path::new(&expanded_filename).exists() {
            log::debug!("Found SP metadata file: {:?}", expanded_filename);
            let filecontents = match read_to_string(&expanded_filename) {
                Err(error) => {
                    eprintln!(
                        "Couldn't load SP Metadata file {} for some reason: {:?}",
                        &expanded_filename, error
                    );
                    continue;
                }
                Ok(value) => value,
            };
            // parse the XML
            let parsed_sp = saml_rs::sp::ServiceProvider::from_str(&filecontents).unwrap();
            eprintln!("SP Metadata loaded: {:?}", parsed_sp);
            sp_metadata.insert(parsed_sp.entity_id.to_string(), parsed_sp);
        } else {
            eprintln!(
                "Couldn't find file {:?}, not loading metadata.",
                expanded_filename
            );
        }
    }
    sp_metadata
}

impl ServerConfig {
    pub fn default() -> Self {
        ServerConfig {
            bind_address: "127.0.0.1".to_string(),
            public_hostname: "example.com".to_string(),
            tls_cert_path: "Need to set this".to_string(),
            tls_key_path: "Need to set this".to_string(),

            entity_id: "https://example.com/idp/".to_string(),
            sp_metadata_files: None,
            sp_metadata: HashMap::new(),
            session_lifetime: 43200, // 12 hours

            // TODO: possibly remove saml_cert_path from [ServerConfig.default]
            saml_cert_path: "Need to set this".to_string(),
            // TODO: possibly remove saml_key_path from [ServerConfig.default]
            saml_key_path: "Need to set this".to_string(),

            saml_signing_key: None,
            saml_signing_cert: None,
        }
    }

    /// Pass this a filename (with or without extension) and it'll choose from JSON/YAML/TOML etc and also check
    /// environment variables starting with SAML_
    pub fn from_filename_and_env(path: String) -> Self {
        let settings = config::Config::builder()
            .add_source(config::File::with_name(&path))
            .add_source(config::Environment::with_prefix("SAML"))
            .build()
            .unwrap();

        let filenames: Vec<String> = match settings.get("sp_metadata_files") {
            Ok(filenames) => filenames,
            _ => Vec::<String>::new(),
        };

        log::debug!("Loading SP Metadata from config.");

        let sp_metadata = load_sp_metadata(filenames);
        eprintln!("Done loading SP Metadata from config.");

        let tilde_cert_path: String = settings.get("tls_cert_path").unwrap_or_else(|error| {
            eprintln!(
                "You need to specify 'tls_cert_path' in configuration, quitting. ({:?})",
                error
            );
            std::process::exit(1)
        });
        let tilde_key_path: String = settings.get("tls_key_path").unwrap_or_else(|error| {
            eprintln!(
                "You need to specify 'tls_key_path' in configuration, quitting. ({:?})",
                error
            );
            std::process::exit(1)
        });

        let tilde_saml_cert_path: String = settings.get("saml_cert_path").unwrap_or_else(|error| {
            eprintln!(
                "You need to specify 'saml_cert_path' in configuration, quitting. ({:?})",
                error
            );
            std::process::exit(1)
        });
        let tilde_saml_key_path: String = settings.get("saml_key_path").unwrap_or_else(|error| {
            eprintln!(
                "You need to specify 'saml_key_path' in configuration, quitting. ({:?})",
                error
            );
            std::process::exit(1)
        });
        let bind_address: String = settings.get("bind_address").unwrap_or_else(|error| {
            eprintln!(
                "You need to specify 'bind_address' in configuration, quitting. ({:?})",
                error
            );
            std::process::exit(1)
        });
        let tls_cert_path = shellexpand::tilde(&tilde_cert_path).into_owned();
        let tls_key_path = shellexpand::tilde(&tilde_key_path).into_owned();
        let saml_cert_path = shellexpand::tilde(&tilde_saml_cert_path).into_owned();
        let saml_key_path = shellexpand::tilde(&tilde_saml_key_path).into_owned();

        use saml_rs::sign::load_key_from_filename;
        let saml_signing_key = match load_key_from_filename(&saml_key_path) {
            Ok(value) => value,
            Err(error) => {
                eprintln!(
                    "Failed to load SAML signing key from {}: {:?}",
                    &saml_key_path, error
                );
                std::process::exit(1);
            }
        };
        let saml_signing_cert = match saml_rs::sign::load_public_cert_from_filename(&saml_cert_path)
        {
            Ok(value) => value,
            Err(error) => {
                eprintln!(
                    "Failed to load SAML signing cert from {}: {:?}",
                    &saml_key_path, error
                );
                std::process::exit(1);
            }
        };

        eprintln!("SETTINGS\n{:?}", settings);
        ServerConfig {
            public_hostname: settings
                .get("public_hostname")
                .unwrap_or(ServerConfig::default().public_hostname),
            bind_address,
            tls_cert_path,
            tls_key_path,
            entity_id: settings
                .get("entity_id")
                .unwrap_or(ServerConfig::default().entity_id),
            sp_metadata_files: settings
                .get("sp_metadata_files")
                .unwrap_or(ServerConfig::default().sp_metadata_files),
            sp_metadata,
            session_lifetime: settings
                .get("default_session_lifetime")
                .unwrap_or(ServerConfig::default().session_lifetime),
            saml_cert_path,
            saml_key_path,

            saml_signing_key: Some(saml_signing_key),
            saml_signing_cert: Some(saml_signing_cert),
        }
    }
}

use openssl::pkey;

#[derive(Clone, Debug)]
pub struct AppState {
    pub hostname: String,
    pub issuer: String,
    pub service_providers: HashMap<String, ServiceProvider>,
    pub tls_cert_path: String,
    pub tls_key_path: String,

    pub saml_cert_path: String,
    pub saml_key_path: String,

    pub saml_signing_key: pkey::PKey<pkey::Private>,
    pub saml_signing_cert: X509,
}

use std::convert::From;

impl From<ServerConfig> for AppState {
    fn from(server_config: ServerConfig) -> AppState {
        AppState {
            hostname: server_config.public_hostname.to_string(),
            issuer: server_config.entity_id.to_string(),
            service_providers: server_config.sp_metadata,
            tls_cert_path: server_config.tls_cert_path.to_string(),
            tls_key_path: server_config.tls_key_path.to_string(),

            saml_cert_path: server_config.saml_cert_path,
            saml_key_path: server_config.saml_key_path,
            saml_signing_key: server_config.saml_signing_key.unwrap(),
            saml_signing_cert: server_config.saml_signing_cert.unwrap(),
        }
    }
}