summaryrefslogtreecommitdiff
path: root/crates/common/src/auth/oauth/config.rs
blob: 79db96f76fed2d32c8c62b07b6f28304992d8060 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use std::time::Duration;

use biscuit::{
    jwa::{Algorithm, SignatureAlgorithm},
    jwk::{
        AlgorithmParameters, CommonParameters, EllipticCurve, EllipticCurveKeyParameters,
        EllipticCurveKeyType, JWKSet, OctetKeyParameters, OctetKeyType, PublicKeyUse,
        RSAKeyParameters, RSAKeyType, JWK,
    },
    jws::Secret,
};
use ring::signature::{self, KeyPair};
use rsa::{pkcs1::DecodeRsaPublicKey, traits::PublicKeyParts, RsaPublicKey};
use store::rand::{distributions::Alphanumeric, thread_rng, Rng};
use utils::config::Config;
use x509_parser::num_bigint::BigUint;

use crate::{
    config::{build_ecdsa_pem, build_rsa_keypair},
    manager::webadmin::Resource,
};

#[derive(Clone)]
pub struct OAuthConfig {
    pub oauth_key: String,
    pub oauth_expiry_user_code: u64,
    pub oauth_expiry_auth_code: u64,
    pub oauth_expiry_token: u64,
    pub oauth_expiry_refresh_token: u64,
    pub oauth_expiry_refresh_token_renew: u64,
    pub oauth_max_auth_attempts: u32,

    pub allow_anonymous_client_registration: bool,
    pub require_client_authentication: bool,

    pub oidc_expiry_id_token: u64,
    pub oidc_signing_secret: Secret,
    pub oidc_signature_algorithm: SignatureAlgorithm,
    pub oidc_jwks: Resource<Vec<u8>>,
}

impl OAuthConfig {
    pub fn parse(config: &mut Config) -> Self {
        let oidc_signature_algorithm = match config.value("oauth.oidc.signature-algorithm") {
            Some(alg) => match alg.to_uppercase().as_str() {
                "HS256" => SignatureAlgorithm::HS256,
                "HS384" => SignatureAlgorithm::HS384,
                "HS512" => SignatureAlgorithm::HS512,

                "RS256" => SignatureAlgorithm::RS256,
                "RS384" => SignatureAlgorithm::RS384,
                "RS512" => SignatureAlgorithm::RS512,

                "ES256" => SignatureAlgorithm::ES256,
                "ES384" => SignatureAlgorithm::ES384,

                "PS256" => SignatureAlgorithm::PS256,
                "PS384" => SignatureAlgorithm::PS384,
                "PS512" => SignatureAlgorithm::PS512,
                _ => {
                    config.new_parse_error(
                        "oauth.oidc.signature-algorithm",
                        format!("Invalid OIDC signature algorithm: {}", alg),
                    );
                    SignatureAlgorithm::HS256
                }
            },
            None => SignatureAlgorithm::HS256,
        };

        let rand_key = thread_rng()
            .sample_iter(Alphanumeric)
            .take(64)
            .map(char::from)
            .collect::<String>()
            .into_bytes();

        let (oidc_signing_secret, algorithm) = match oidc_signature_algorithm {
            SignatureAlgorithm::None
            | SignatureAlgorithm::HS256
            | SignatureAlgorithm::HS384
            | SignatureAlgorithm::HS512 => {
                let key = config
                    .value("oauth.oidc.signature-key")
                    .map(|s| s.to_string().into_bytes())
                    .unwrap_or(rand_key);

                (
                    Secret::Bytes(key.clone()),
                    AlgorithmParameters::OctetKey(OctetKeyParameters {
                        key_type: OctetKeyType::Octet,
                        value: key,
                    }),
                )
            }
            SignatureAlgorithm::RS256
            | SignatureAlgorithm::RS384
            | SignatureAlgorithm::RS512
            | SignatureAlgorithm::PS256
            | SignatureAlgorithm::PS384
            | SignatureAlgorithm::PS512 => parse_rsa_key(config).unwrap_or_else(|| {
                (
                    Secret::Bytes(rand_key.clone()),
                    AlgorithmParameters::OctetKey(OctetKeyParameters {
                        key_type: OctetKeyType::Octet,
                        value: rand_key,
                    }),
                )
            }),
            SignatureAlgorithm::ES256 | SignatureAlgorithm::ES384 | SignatureAlgorithm::ES512 => {
                parse_ecdsa_key(config, oidc_signature_algorithm).unwrap_or_else(|| {
                    (
                        Secret::Bytes(rand_key.clone()),
                        AlgorithmParameters::OctetKey(OctetKeyParameters {
                            key_type: OctetKeyType::Octet,
                            value: rand_key,
                        }),
                    )
                })
            }
        };

        let oidc_jwks = Resource {
            content_type: "application/json".into(),
            contents: serde_json::to_string(&JWKSet {
                keys: vec![JWK {
                    common: CommonParameters {
                        public_key_use: PublicKeyUse::Signature.into(),
                        algorithm: Algorithm::Signature(oidc_signature_algorithm).into(),
                        key_id: "default".to_string().into(),
                        ..Default::default()
                    },
                    algorithm,
                    additional: (),
                }],
            })
            .unwrap_or_default()
            .into_bytes(),
        };

        OAuthConfig {
            oauth_key: config
                .value("oauth.key")
                .map(|s| s.to_string())
                .unwrap_or_else(|| {
                    thread_rng()
                        .sample_iter(Alphanumeric)
                        .take(64)
                        .map(char::from)
                        .collect::<String>()
                }),
            oauth_expiry_user_code: config
                .property_or_default::<Duration>("oauth.expiry.user-code", "30m")
                .unwrap_or_else(|| Duration::from_secs(30 * 60))
                .as_secs(),
            oauth_expiry_auth_code: config
                .property_or_default::<Duration>("oauth.expiry.auth-code", "10m")
                .unwrap_or_else(|| Duration::from_secs(10 * 60))
                .as_secs(),
            oauth_expiry_token: config
                .property_or_default::<Duration>("oauth.expiry.token", "1h")
                .unwrap_or_else(|| Duration::from_secs(60 * 60))
                .as_secs(),
            oauth_expiry_refresh_token: config
                .property_or_default::<Duration>("oauth.expiry.refresh-token", "30d")
                .unwrap_or_else(|| Duration::from_secs(30 * 24 * 60 * 60))
                .as_secs(),
            oauth_expiry_refresh_token_renew: config
                .property_or_default::<Duration>("oauth.expiry.refresh-token-renew", "4d")
                .unwrap_or_else(|| Duration::from_secs(4 * 24 * 60 * 60))
                .as_secs(),
            oauth_max_auth_attempts: config
                .property_or_default("oauth.auth.max-attempts", "3")
                .unwrap_or(10),
            oidc_expiry_id_token: config
                .property_or_default::<Duration>("oauth.oidc.expiry.id-token", "15m")
                .unwrap_or_else(|| Duration::from_secs(15 * 60))
                .as_secs(),
            allow_anonymous_client_registration: config
                .property_or_default("oauth.client-registration.anonymous", "false")
                .unwrap_or(false),
            require_client_authentication: config
                .property_or_default("oauth.client-registration.required", "false")
                .unwrap_or(true),
            oidc_signing_secret,
            oidc_signature_algorithm,
            oidc_jwks,
        }
    }
}

impl Default for OAuthConfig {
    fn default() -> Self {
        Self {
            oauth_key: Default::default(),
            oauth_expiry_user_code: Default::default(),
            oauth_expiry_auth_code: Default::default(),
            oauth_expiry_token: Default::default(),
            oauth_expiry_refresh_token: Default::default(),
            oauth_expiry_refresh_token_renew: Default::default(),
            oauth_max_auth_attempts: Default::default(),
            oidc_expiry_id_token: Default::default(),
            allow_anonymous_client_registration: Default::default(),
            require_client_authentication: Default::default(),
            oidc_signing_secret: Secret::Bytes("secret".to_string().into_bytes()),
            oidc_signature_algorithm: SignatureAlgorithm::HS256,
            oidc_jwks: Resource {
                content_type: "application/json".into(),
                contents: serde_json::to_string(&JWKSet::<()> { keys: vec![] })
                    .unwrap_or_default()
                    .into_bytes(),
            },
        }
    }
}

fn parse_rsa_key(config: &mut Config) -> Option<(Secret, AlgorithmParameters)> {
    let rsa_key_pair = match build_rsa_keypair(config.value_require("oauth.oidc.signature-key")?) {
        Ok(key) => key,
        Err(err) => {
            config.new_build_error(
                "oauth.oidc.signature-key",
                format!("Failed to build RSA key: {}", err),
            );
            return None;
        }
    };

    let rsa_public_key = match RsaPublicKey::from_pkcs1_der(rsa_key_pair.public_key().as_ref()) {
        Ok(key) => key,
        Err(err) => {
            config.new_build_error(
                "oauth.oidc.signature-key",
                format!("Failed to obtain RSA public key: {}", err),
            );
            return None;
        }
    };

    let rsa_key_params = RSAKeyParameters {
        key_type: RSAKeyType::RSA,
        n: BigUint::from_bytes_be(&rsa_public_key.n().to_bytes_be()),
        e: BigUint::from_bytes_be(&rsa_public_key.e().to_bytes_be()),
        ..Default::default()
    };

    (
        Secret::RsaKeyPair(rsa_key_pair.into()),
        AlgorithmParameters::RSA(rsa_key_params),
    )
        .into()
}

fn parse_ecdsa_key(
    config: &mut Config,
    oidc_signature_algorithm: SignatureAlgorithm,
) -> Option<(Secret, AlgorithmParameters)> {
    let (alg, curve) = match oidc_signature_algorithm {
        SignatureAlgorithm::ES256 => (
            &signature::ECDSA_P256_SHA256_FIXED_SIGNING,
            EllipticCurve::P256,
        ),
        SignatureAlgorithm::ES384 => (
            &signature::ECDSA_P384_SHA384_FIXED_SIGNING,
            EllipticCurve::P384,
        ),
        _ => unreachable!(),
    };

    let ecdsa_key_pair =
        match build_ecdsa_pem(alg, config.value_require("oauth.oidc.signature-key")?) {
            Ok(key) => key,
            Err(err) => {
                config.new_build_error(
                    "oauth.oidc.signature-key",
                    format!("Failed to build ECDSA key: {}", err),
                );
                return None;
            }
        };

    let ecdsa_public_key = ecdsa_key_pair.public_key().as_ref();

    let (x, y) = match oidc_signature_algorithm {
        SignatureAlgorithm::ES256 => {
            let points = match p256::EncodedPoint::from_bytes(ecdsa_public_key) {
                Ok(points) => points,
                Err(err) => {
                    config.new_build_error(
                        "oauth.oidc.signature-key",
                        format!("Failed to parse ECDSA key: {}", err),
                    );
                    return None;
                }
            };

            (
                points.x().map(|x| x.to_vec()).unwrap_or_default(),
                points.y().map(|y| y.to_vec()).unwrap_or_default(),
            )
        }
        SignatureAlgorithm::ES384 => {
            let points = match p384::EncodedPoint::from_bytes(ecdsa_public_key) {
                Ok(points) => points,
                Err(err) => {
                    config.new_build_error(
                        "oauth.oidc.signature-key",
                        format!("Failed to parse ECDSA key: {}", err),
                    );
                    return None;
                }
            };

            (
                points.x().map(|x| x.to_vec()).unwrap_or_default(),
                points.y().map(|y| y.to_vec()).unwrap_or_default(),
            )
        }
        _ => unreachable!(),
    };

    let ecdsa_key_params = EllipticCurveKeyParameters {
        key_type: EllipticCurveKeyType::EC,
        curve,
        x,
        y,
        d: None,
    };

    (
        Secret::EcdsaKeyPair(ecdsa_key_pair.into()),
        AlgorithmParameters::EllipticCurve(ecdsa_key_params),
    )
        .into()
}