krill 0.16.0

Resource Public Key Infrastructure (RPKI) daemon
Documentation
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! Processing OpenID Connect claims.

use std::sync::Arc;
use log::warn;
use regex::{Regex, Replacer};
use serde::Deserialize;
use serde::de::{Deserializer, Error as _};
use serde_json::{Number as JsonNumber, Value as JsonValue};
use crate::commons::KrillResult;
use crate::commons::error::Error;
use super::util::{FlexibleIdTokenClaims, FlexibleUserInfoClaims};


//------------ Claims --------------------------------------------------------

#[derive(Debug)]
pub struct Claims<'a> {
    id_token_claims: &'a FlexibleIdTokenClaims,
    user_info_claims: Option<FlexibleUserInfoClaims>,

    id_standard: Option<JsonValue>,
    id_additional: Option<JsonValue>,
    user_standard: Option<JsonValue>,
    user_additional: Option<JsonValue>,
}

impl<'a> Claims<'a> {
    pub fn new(
        id_token_claims: &'a FlexibleIdTokenClaims,
        user_info_claims: Option<FlexibleUserInfoClaims>,
    ) -> Self {
        Self {
            id_token_claims, user_info_claims,
            id_standard: None, id_additional: None,
            user_standard: None, user_additional: None,
        }
    }

    pub fn extract_claims(
        &mut self, conf: &[TransformationRule],
    ) -> KrillResult<Option<Arc<str>>> {
        for rule in conf {
            match rule {
                TransformationRule::Fixed(subst) => {
                    return Ok(Some(subst.clone()))
                }
                TransformationRule::Match(rule) => {
                    if let Some(res) = self.process_match_rule(rule)? {
                        return Ok(Some(res))
                    }
                }
            }
        }

        Ok(None)
    }

    fn process_match_rule(
        &mut self, conf: &MatchRule,
    ) -> KrillResult<Option<Arc<str>>> {
        use self::ClaimSource::*;

        match conf.source {
            Some(IdTokenStandardClaim) => {
                Self::process_claim_json(conf, self.id_standard()?)
            }
            Some(IdTokenAdditionalClaim) => {
                Self::process_claim_json(conf, self.id_additional()?)
            }
            Some(UserInfoStandardClaim) => {
                self.user_standard()?.and_then(|json| {
                    Self::process_claim_json(conf, json).transpose()
                }).transpose()
            }
            Some(UserInfoAdditionalClaim) => {
                self.user_additional()?.and_then(|json| {
                    Self::process_claim_json(conf, json).transpose()
                }).transpose()
            }
            None => {
                if let Some(res) = Self::process_claim_json(
                    conf, self.id_standard()?
                )? {
                    return Ok(Some(res))
                }
                if let Some(res) = Self::process_claim_json(
                    conf, self.id_additional()?
                )? {
                    return Ok(Some(res))
                }
                if let Some(res) = self.user_standard()?.and_then(|json| {
                    Self::process_claim_json(conf, json).transpose()
                }).transpose()? {
                    return Ok(Some(res))
                }
                self.user_additional()?.and_then(|json| {
                    Self::process_claim_json(conf, json).transpose()
                }).transpose()
            }
        }
    }

    fn id_standard(&mut self) -> KrillResult<&JsonValue> {
        if self.id_standard.is_none() {
            self.id_standard = Some(
                serde_json::to_value(self.id_token_claims).map_err(|_| {
                    Self::internal_error(
                        "OpenID Connect: \
                         failed to generate standard ID token claims",
                         None
                    )
                })?
            )
        }
        Ok(self.id_standard.as_ref().unwrap())
    }

    fn id_additional(&mut self) -> KrillResult<&JsonValue> {
        if self.id_additional.is_none() {
            self.id_additional = Some(
                serde_json::to_value(
                    self.id_token_claims.additional_claims()
                ).map_err(|_| {
                    Self::internal_error(
                        "OpenID Connect: \
                         failed to generate additional ID token claims",
                         None
                    )
                })?
            )
        }
        Ok(self.id_additional.as_ref().unwrap())
    }

    fn user_standard(&mut self) -> KrillResult<Option<&JsonValue>> {
        let claims = match self.user_info_claims.as_ref() {
            Some(claims) => claims,
            None => return Ok(None)
        };
        if self.user_standard.is_none() {
            self.user_standard = Some(
                serde_json::to_value(claims).map_err(|_| {
                    Self::internal_error(
                        "OpenID Connect: \
                         failed to generate standard user info claims",
                         None
                    )
                })?
            )
        }
        Ok(self.user_standard.as_ref())
    }

    fn user_additional(&mut self) -> KrillResult<Option<&JsonValue>> {
        let claims = match self.user_info_claims.as_ref() {
            Some(claims) => claims,
            None => return Ok(None)
        };
        if self.user_additional.is_none() {
            self.user_additional = Some(
                serde_json::to_value(claims.additional_claims()).map_err(|_| {
                    Self::internal_error(
                        "OpenID Connect: \
                         failed to generate standard user info claims",
                         None
                    )
                })?
            )
        }
        Ok(self.user_additional.as_ref())
    }

    fn process_claim_json(
        conf: &MatchRule,
        json: &JsonValue,
    ) -> KrillResult<Option<Arc<str>>> {
        let object = match json {
            JsonValue::Object(object) => object,
            _ => return Ok(None)
        };
        let value = match object.get(&conf.claim) {
            Some(value) => value,
            None => return Ok(None)
        };
        match value {
            JsonValue::Array(array) => Self::process_claim_array(conf, array),
            JsonValue::Bool(true) => Self::process_claim_str(conf, "true"),
            JsonValue::Bool(false) => Self::process_claim_str(conf, "false"),
            JsonValue::String(s) => Self::process_claim_str(conf, s),
            JsonValue::Number(num) => Self::process_claim_number(conf, num),
            _ => Ok(None)
        }
    }

    fn process_claim_array(
        conf: &MatchRule,
        array: &[JsonValue],
    ) -> KrillResult<Option<Arc<str>>> {
        for item in array {
            let res = match item {
                JsonValue::Bool(true) => {
                    Self::process_claim_str(conf, "true")?
                }
                JsonValue::Bool(false) => {
                    Self::process_claim_str(conf, "false")?
                }
                JsonValue::String(s) => {
                    Self::process_claim_str(conf, s)?
                }
                JsonValue::Number(num) => {
                    Self::process_claim_number(conf, num)?
                }
                _ => None
            };
            if let Some(res) = res {
                return Ok(Some(res))
            }
        }
        Ok(None)
    }

    fn process_claim_number(
        conf: &MatchRule,
        num: &JsonNumber
    ) -> KrillResult<Option<Arc<str>>> {
        Self::process_claim_str(conf, &num.to_string())
    }

    fn process_claim_str(
        conf: &MatchRule,
        s: &str,
    ) -> KrillResult<Option<Arc<str>>> {
        if let Some(expr) = conf.match_expr.as_ref() {
            match conf.subst.as_ref() {
                Some(subst) => {
                    if subst.no_expansion {
                        match expr.0.find(s) {
                            Some(m) => {
                                let mut res = String::with_capacity(s.len());
                                res.push_str(&s[..m.start()]);
                                res.push_str(&subst.expr);
                                res.push_str(&s[m.end()..]);
                                Ok(Some(res.into()))
                            }
                            None => Ok(None)
                        }
                    }
                    else {
                        match expr.0.captures(s) {
                            Some(c) => {
                                let mut res = String::with_capacity(
                                    subst.expr.len()
                                );
                                c.expand(&subst.expr, &mut res);
                                Ok(Some(res.into()))
                            }
                            None => Ok(None)
                        }
                    }
                }
                None => {
                    if expr.0.is_match(s) {
                        Ok(Some(s.into()))
                    }
                    else {
                        Ok(None)
                    }
                }
            }
        }
        else {
            // If there is no match expression, the value always matches and
            // we return it (even if there is a subst expression -- we just
            // ignore it).
            Ok(Some(s.into()))
        }
    }


    /// Log and convert the given error such that the detailed, possibly
    /// sensitive details are logged and only the high level statement
    /// about the error is passed back to the caller.
    fn internal_error<S>(msg: S, additional_info: Option<S>) -> Error
    where
        S: Into<String>,
    {
        let msg: String = msg.into();
        match additional_info {
            Some(additional_info) => {
                warn!("{} [additional info: {}]", msg, additional_info.into())
            }
            None => warn!("{msg}"),
        };
        Error::ApiLoginError(msg)
    }
}


//------------ TransformationRule --------------------------------------------

/// Transformation rule for a claim.
#[derive(Clone, Debug, Deserialize)]
#[serde(try_from = "TransformationRuleConf")]
pub enum TransformationRule {
    /// Fixed rule.
    ///
    /// This rule matches always and returns the provided string.
    Fixed(Arc<str>),

    /// Matching rule.
    ///
    /// This rule tries to match the provided claim and optionally replaces
    /// the value with the given subst expression.
    ///
    /// The rule matches string values, number and boolean values with their
    /// JSON representation. It also matches arrays item by item with the
    /// first match being used.
    Match(MatchRule),
}


//------------ MatchRule -----------------------------------------------------

#[derive(Clone, Debug)]
pub struct MatchRule {
    pub source: Option<ClaimSource>,
    pub claim: String,
    pub match_expr: Option<MatchExpression>,
    pub subst: Option<SubstExpression>,
}


//------------ TransformationRuleConf ----------------------------------------

#[derive(Clone, Debug, Deserialize)]
pub struct TransformationRuleConf {
    pub source: Option<ClaimSource>,
    pub claim: Option<String>,
    #[serde(rename = "match")]
    pub match_expr: Option<MatchExpression>,
    pub subst: Option<String>,
}

impl TryFrom<TransformationRuleConf> for TransformationRule {
    type Error = String;

    fn try_from(src: TransformationRuleConf) -> Result<Self, Self::Error> {
        if let Some(claim) = src.claim {
            Ok(TransformationRule::Match(MatchRule {
                source: src.source,
                claim,
                match_expr: src.match_expr,
                subst: src.subst.map(Into::into)
            }))
        }
        else {
            let subst = match src.subst {
                Some(subst) => subst,
                None => {
                    return Err(
                        "'subst' is mandatory if 'claim' is missing".into()
                    )
                }
            };

            // Complain if we have 'match' to avoid possible errors. All
            // the other things are probably fine.
            if src.match_expr.is_some() {
                return Err(
                    "'claim' is mandatory if 'match' is present".into()
                )
            }

            Ok(TransformationRule::Fixed(subst.into()))
        }
    }
}


//------------ MatchExpression -----------------------------------------------

#[derive(Clone, Debug)]
pub struct MatchExpression(Regex);

impl<'de> Deserialize<'de> for MatchExpression {
    fn deserialize<D: Deserializer<'de>>(
        deserializer: D
    ) -> Result<Self, D::Error> {
        String::deserialize(deserializer).and_then(|s| {
            Regex::try_from(s).map_err(D::Error::custom)
        }).map(Self)
    }
}


//------------ SubstExpression -----------------------------------------------

#[derive(Clone, Debug)]
pub struct SubstExpression {
    expr: String,
    no_expansion: bool,
}

impl From<String> for SubstExpression {
    fn from(mut expr: String) -> Self {
        let no_expansion = expr.no_expansion().is_some();
        Self { expr, no_expansion }
    }
}


//------------ ClaimSource ---------------------------------------------------

#[derive(Clone, Copy, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum ClaimSource {
    IdTokenStandardClaim,
    IdTokenAdditionalClaim,
    UserInfoStandardClaim,
    UserInfoAdditionalClaim,
}

impl std::fmt::Display for ClaimSource {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use self::ClaimSource::*;

        f.write_str(
            match self {
                IdTokenStandardClaim => "id-token-standard-claim",
                IdTokenAdditionalClaim => "id-token-additional-claim",
                UserInfoStandardClaim => "user-info-standard-claim",
                UserInfoAdditionalClaim => "user-info-additional-claim",
            }
        )
    }
}

impl<'de> Deserialize<'de> for ClaimSource {
    fn deserialize<D>(
        d: D,
    ) -> Result<ClaimSource, D::Error>
    where
        D: Deserializer<'de>,
    {
        use self::ClaimSource::*;

        match <&'de str>::deserialize(d)? {
            "id-token-standard-claim" => Ok(IdTokenStandardClaim),
            "id-token-additional-claim" => Ok(IdTokenAdditionalClaim),
            "user-info-standard-claim" => Ok(UserInfoStandardClaim),
            "user-info-additional-claim" => Ok(UserInfoAdditionalClaim),
            s => {
                Err(serde::de::Error::custom(
                    format!(
                        "expected \"id-token-additional-claim\", \
                        \"id-token-standard-claim\", \
                        \"user-info-standard-claim\", or \
                        \"user-info-additional-claim\", found : \"{s}\""
                )))
            }
        }
    }
}