Skip to main content

kaniop_radius/reconcile/
kanidm_token.rs

1//! Kanidm token executors: list, mint, verify and revoke.
2//!
3//! These perform the effects the pure planner ([`super::token`]) decides on.
4//! They never choose *what* to do: minting happens only for a
5//! `CurrentToken::Mint` plan, revoking only for ids in a plan computed from a
6//! fresh observation (see the planner's module docs).
7//!
8//! Bearer tokens are write-only and shown once by Kanidm. [`Bearer`] holds
9//! one without `Display`, `Serialize` or a revealing `Debug`, so it cannot
10//! reach a log line or event by accident; call [`Bearer::expose`] only to
11//! write the config Secret or authenticate a verification session.
12
13use std::fmt;
14use std::time::Duration;
15
16use kanidm_client::KanidmClient;
17use kanidm_proto::internal::ApiToken;
18use kaniop_operator::metrics::{
19    ControllerMetrics, KANIDM_OP_DESTROY_API_TOKEN, KANIDM_OP_GENERATE_API_TOKEN,
20    KANIDM_OP_LIST_API_TOKENS, KANIDM_OP_WHOAMI, KANIDM_OUTCOME_CHANGED, KANIDM_OUTCOME_UNCHANGED,
21};
22use time::OffsetDateTime;
23use tracing::debug;
24use uuid::Uuid;
25
26use crate::reconcile::error::{ExecError, ExecResult, kanidm_error};
27use crate::reconcile::identity::is_not_found;
28use crate::reconcile::sdk;
29
30const TOKEN_LABEL_PREFIX: &str = "kaniop-radius-";
31
32/// A Kanidm bearer token. Deliberately opaque: see the module docs.
33#[derive(Clone, PartialEq, Eq)]
34pub struct Bearer(String);
35
36impl Bearer {
37    pub fn new(value: String) -> Self {
38        Self(value)
39    }
40
41    /// The token text. Never log or put it in status, events or errors.
42    pub fn expose(&self) -> &str {
43        &self.0
44    }
45}
46
47impl fmt::Debug for Bearer {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.write_str("Bearer(<redacted>)")
50    }
51}
52
53/// A freshly minted, not yet verified or stored token.
54#[derive(Debug)]
55pub struct MintedToken {
56    pub token_id: Uuid,
57    pub bearer: Bearer,
58}
59
60/// A unique label for one mint. The account is dedicated to one CR UID, so
61/// the label is informational (it names the issuer in Kanidm's UI) and the
62/// uniqueness only serves to find the new token's id after the call.
63pub fn new_token_label() -> String {
64    format!("{TOKEN_LABEL_PREFIX}{}", Uuid::new_v4().simple())
65}
66
67/// Find the one token carrying `label` that was not in `before`.
68///
69/// `generate_api_token` returns only the bearer, so the token id comes from a
70/// second listing. Anything other than exactly one new match is ambiguous and
71/// the token is left alone (the planner revokes unused orphans after the
72/// grace period).
73pub fn find_minted_token(before: &[ApiToken], after: &[ApiToken], label: &str) -> Option<Uuid> {
74    let mut matching = after
75        .iter()
76        .filter(|token| token.label == label)
77        .filter(|token| before.iter().all(|old| old.token_id != token.token_id));
78    let found = matching.next()?;
79    matching.next().is_none().then_some(found.token_id)
80}
81
82/// Tokens currently on the account.
83pub async fn list_tokens(
84    client: &KanidmClient,
85    metrics: &ControllerMetrics,
86    account: &str,
87) -> ExecResult<Vec<ApiToken>> {
88    sdk::call(
89        metrics,
90        KANIDM_OP_LIST_API_TOKENS,
91        KANIDM_OUTCOME_UNCHANGED,
92        client.idm_service_account_list_api_token(account),
93    )
94    .await
95    .map_err(|e| kanidm_error("list API tokens of", "RADIUS service account", e))
96}
97
98/// Mint a read-only token on the (already ownership-verified) account.
99///
100/// `expiry` is `TokenPolicy::new_token_expiry(now)`: set when rotation is
101/// enabled, absent otherwise. The bearer is not stored anywhere yet: the
102/// caller must verify it and persist it in the config Secret in the same
103/// reconcile. If this call fails after Kanidm accepted the request, the
104/// token is an orphan the planner revokes once past the grace period.
105pub async fn mint_token(
106    client: &KanidmClient,
107    metrics: &ControllerMetrics,
108    account: &str,
109    expiry: Option<OffsetDateTime>,
110) -> ExecResult<MintedToken> {
111    let label = new_token_label();
112    let before = list_tokens(client, metrics, account).await?;
113    let bearer = sdk::call(
114        metrics,
115        KANIDM_OP_GENERATE_API_TOKEN,
116        KANIDM_OUTCOME_CHANGED,
117        client.idm_service_account_generate_api_token(
118            account, &label, expiry, false, // read-only is mandatory for RADIUS
119            false, // not compact
120        ),
121    )
122    .await
123    .map_err(|e| kanidm_error("generate API token for", "RADIUS service account", e))?;
124    let after = list_tokens(client, metrics, account).await?;
125    let token_id = find_minted_token(&before, &after, &label).ok_or_else(|| {
126        ExecError::MintedTokenNotFound {
127            account: account.to_string(),
128        }
129    })?;
130    Ok(MintedToken {
131        token_id,
132        bearer: Bearer::new(bearer),
133    })
134}
135
136/// How [`verify_token`] retries. Right after a mint, a Kanidm replica other
137/// than the one that issued the token may not know it yet.
138#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct VerifyRetry {
140    pub attempts: u32,
141    pub delay: Duration,
142}
143
144impl Default for VerifyRetry {
145    fn default() -> Self {
146        Self {
147            attempts: 5,
148            delay: Duration::from_secs(1),
149        }
150    }
151}
152
153/// Promotion gate: authenticate to Kanidm with the candidate token
154/// alone. `KanidmClient::new_session` copies the cached client's address and
155/// TLS settings but not its bearer, so a success proves the candidate itself.
156///
157/// A 401 (`whoami` returns `None`) is retried like a transient error, then
158/// reported as [`ExecError::CandidateRejected`]. Transport and server errors
159/// that persist through the retries are returned with their source.
160pub async fn verify_token(
161    client: &KanidmClient,
162    metrics: &ControllerMetrics,
163    account: &str,
164    bearer: &Bearer,
165    retry: VerifyRetry,
166) -> ExecResult<()> {
167    let session = client
168        .new_session()
169        .map_err(|e| kanidm_error("open session for", "token verification", e))?;
170    session.set_token(bearer.expose().to_string()).await;
171    let attempts = retry.attempts.max(1);
172    let mut last: Option<ExecError> = None;
173    for attempt in 1..=attempts {
174        if attempt > 1 {
175            tokio::time::sleep(retry.delay).await;
176        }
177        match sdk::call(
178            metrics,
179            KANIDM_OP_WHOAMI,
180            KANIDM_OUTCOME_UNCHANGED,
181            session.whoami(),
182        )
183        .await
184        {
185            Ok(Some(_)) => return Ok(()),
186            Ok(None) => {
187                last = Some(ExecError::CandidateRejected {
188                    account: account.to_string(),
189                });
190            }
191            Err(error) => {
192                last = Some(kanidm_error(
193                    "verify token of",
194                    "RADIUS service account",
195                    error,
196                ))
197            }
198        }
199        debug!(attempt, attempts, "candidate token not accepted yet");
200    }
201    Err(last.unwrap_or_else(|| ExecError::CandidateRejected {
202        account: account.to_string(),
203    }))
204}
205
206/// What [`revoke_token`] did.
207#[derive(Clone, Copy, Debug, PartialEq, Eq)]
208pub enum RevokeOutcome {
209    Revoked,
210    /// Kanidm no longer has the token (or account): the goal is met.
211    AlreadyAbsent,
212}
213
214/// Revoke one token by id. A token that is already gone is success, so the
215/// call is idempotent across retries and concurrent reconciles.
216pub async fn revoke_token(
217    client: &KanidmClient,
218    metrics: &ControllerMetrics,
219    account: &str,
220    token_id: Uuid,
221) -> ExecResult<RevokeOutcome> {
222    match sdk::call(
223        metrics,
224        KANIDM_OP_DESTROY_API_TOKEN,
225        KANIDM_OUTCOME_CHANGED,
226        client.idm_service_account_destroy_api_token(account, token_id),
227    )
228    .await
229    {
230        Ok(()) => Ok(RevokeOutcome::Revoked),
231        Err(error) if is_not_found(&error) => Ok(RevokeOutcome::AlreadyAbsent),
232        Err(error) => Err(kanidm_error(
233            "revoke API token of",
234            "RADIUS service account",
235            error,
236        )),
237    }
238}
239
240#[cfg(test)]
241mod tests {
242    use std::sync::{Arc, Mutex};
243
244    use http::StatusCode;
245    use kanidm_client::ClientError;
246    use serde_json::{Value, json};
247
248    use super::*;
249    use crate::reconcile::kanidm_mock::{self, Request};
250
251    const ACCOUNT: &str = "kaniop_radius_d10066c345994487972d26bb42587a32";
252    const TOKEN_A: &str = "9ad74e68-147f-49e8-96db-dc21c920ff3b";
253    const TOKEN_B: &str = "31b30b65-037a-418f-b7ca-0c376da2db28";
254
255    fn token(id: &str, label: &str) -> ApiToken {
256        serde_json::from_value(json!({
257            "account_id": "00000000-0000-0000-0000-000000000001",
258            "token_id": id,
259            "label": label,
260            "expiry": null,
261            "issued_at": 1_700_000_000,
262            "purpose": "readonly"
263        }))
264        .unwrap()
265    }
266
267    fn token_json(t: &ApiToken) -> Value {
268        serde_json::to_value(t).unwrap()
269    }
270
271    #[test]
272    fn label_is_unique_and_well_formed() {
273        let a = new_token_label();
274        let b = new_token_label();
275        assert_ne!(a, b);
276        assert!(a.starts_with("kaniop-radius-") && a.len() == 14 + 32);
277    }
278
279    #[test]
280    fn finds_exactly_one_new_token_by_label() {
281        let old = token(TOKEN_A, "kaniop-radius-old");
282        let new = token(TOKEN_B, "kaniop-radius-new");
283        let before = [old.clone()];
284        let after = [old.clone(), new];
285        assert_eq!(
286            find_minted_token(&before, &after, "kaniop-radius-new"),
287            Some(uuid(TOKEN_B))
288        );
289        // No such label.
290        assert_eq!(find_minted_token(&before, &after, "other"), None);
291        // The label existed before: that is not our new token.
292        assert_eq!(find_minted_token(&after, &after, "kaniop-radius-new"), None);
293        // Two new tokens share the label: ambiguous, so none.
294        let dup = [
295            old.clone(),
296            token(TOKEN_B, "x"),
297            token(TOKEN_A.replace('9', "8").as_str(), "x"),
298        ];
299        assert_eq!(find_minted_token(&before, &dup, "x"), None);
300    }
301
302    fn uuid(s: &str) -> Uuid {
303        Uuid::parse_str(s).unwrap()
304    }
305
306    #[test]
307    fn bearer_never_shows_in_debug() {
308        let minted = MintedToken {
309            token_id: uuid(TOKEN_A),
310            bearer: Bearer::new("eyJ-secret-bearer".into()),
311        };
312        let text = format!("{minted:?} {:?}", minted.bearer);
313        assert!(!text.contains("eyJ-secret-bearer"), "{text}");
314        assert_eq!(minted.bearer.expose(), "eyJ-secret-bearer");
315    }
316
317    #[test]
318    fn not_found_detection() {
319        let http =
320            |code: u16| ClientError::Http(StatusCode::from_u16(code).unwrap(), None, String::new());
321        assert!(is_not_found(&http(404)));
322        assert!(!is_not_found(&http(500)));
323        assert!(!is_not_found(&http(403)));
324        assert!(!is_not_found(&ClientError::Unauthorized));
325        let no_match = ClientError::Http(
326            StatusCode::BAD_REQUEST,
327            Some(kanidm_proto::internal::OperationError::NoMatchingEntries),
328            String::new(),
329        );
330        assert!(is_not_found(&no_match));
331    }
332
333    #[tokio::test]
334    async fn mint_requests_a_read_only_token_with_expiry_and_finds_its_id() {
335        let listed = Arc::new(Mutex::new(Vec::<Value>::new()));
336        let label = Arc::new(Mutex::new(None::<String>));
337        let (l, lb) = (listed.clone(), label.clone());
338        let mock = kanidm_mock::start(move |req: &Request| {
339            let list_path = format!("/v1/service_account/{ACCOUNT}/_api_token");
340            match (req.method.as_str(), req.path == list_path) {
341                ("GET", true) => (200, serde_json::to_string(&*l.lock().unwrap()).unwrap()),
342                ("POST", true) => {
343                    let body: Value = serde_json::from_str(&req.body).unwrap();
344                    let new_label = body["label"].as_str().unwrap().to_string();
345                    l.lock()
346                        .unwrap()
347                        .push(token_json(&token(TOKEN_B, &new_label)));
348                    *lb.lock().unwrap() = Some(new_label);
349                    (200, "\"bearer-jws-value\"".into())
350                }
351                _ => (500, "{}".into()),
352            }
353        })
354        .await;
355        let expiry = OffsetDateTime::from_unix_timestamp(1_800_000_000).unwrap();
356        let minted = mint_token(&mock.client, &mock.metrics, ACCOUNT, Some(expiry))
357            .await
358            .unwrap();
359        assert_eq!(minted.token_id, uuid(TOKEN_B));
360        assert_eq!(minted.bearer.expose(), "bearer-jws-value");
361
362        let post = mock.writes().pop().unwrap();
363        let body: Value = serde_json::from_str(&post.body).unwrap();
364        assert_eq!(body["read_write"], false, "RADIUS tokens are read-only");
365        assert_eq!(body["compact"], false);
366        assert!(!body["expiry"].is_null(), "expiry requested: {body}");
367        assert_eq!(body["label"], label.lock().unwrap().clone().unwrap());
368    }
369
370    #[tokio::test]
371    async fn mint_without_rotation_requests_no_expiry() {
372        let mock = kanidm_mock::start(|req: &Request| match req.method.as_str() {
373            "POST" => (200, "\"b\"".into()),
374            _ => (200, "[]".into()),
375        })
376        .await;
377        // The after-listing is empty, so the id cannot be found; the request
378        // shape is what this checks.
379        let error = mint_token(&mock.client, &mock.metrics, ACCOUNT, None)
380            .await
381            .unwrap_err();
382        assert!(matches!(error, ExecError::MintedTokenNotFound { .. }));
383        let body: Value = serde_json::from_str(&mock.writes()[0].body).unwrap();
384        assert!(body["expiry"].is_null());
385        assert!(!error.to_string().contains("\"b\""));
386    }
387
388    #[tokio::test]
389    async fn mint_failure_keeps_source_and_creates_nothing_else() {
390        let mock = kanidm_mock::start(|req: &Request| match req.method.as_str() {
391            "POST" => (500, "{}".into()),
392            _ => (200, "[]".into()),
393        })
394        .await;
395        let error = mint_token(&mock.client, &mock.metrics, ACCOUNT, None)
396            .await
397            .unwrap_err();
398        assert!(matches!(error, ExecError::Api(_)));
399        assert_eq!(mock.writes().len(), 1);
400    }
401
402    fn whoami_ok() -> (u16, String) {
403        (
404            200,
405            json!({"youare": {"attrs": {"name": [ACCOUNT]}}}).to_string(),
406        )
407    }
408
409    const FAST: VerifyRetry = VerifyRetry {
410        attempts: 3,
411        delay: Duration::from_millis(0),
412    };
413
414    #[tokio::test]
415    async fn verify_uses_only_the_candidate_token() {
416        let mock = kanidm_mock::start(|_| whoami_ok()).await;
417        // The shared client carries the operator's own credential.
418        mock.client.set_token("operator-admin-token".into()).await;
419        verify_token(
420            &mock.client,
421            &mock.metrics,
422            ACCOUNT,
423            &Bearer::new("candidate-token".into()),
424            FAST,
425        )
426        .await
427        .unwrap();
428        let requests = mock.requests();
429        assert_eq!(requests.len(), 1);
430        assert_eq!(requests[0].path, "/v1/self");
431        assert_eq!(
432            requests[0].authorization.as_deref(),
433            Some("Bearer candidate-token")
434        );
435        // The shared client's credential is untouched.
436        assert_eq!(
437            mock.client.get_token().await.as_deref(),
438            Some("operator-admin-token")
439        );
440    }
441
442    #[tokio::test]
443    async fn verify_rejects_a_token_kanidm_does_not_accept() {
444        let mock = kanidm_mock::start(|_| (401, "null".into())).await;
445        let error = verify_token(
446            &mock.client,
447            &mock.metrics,
448            ACCOUNT,
449            &Bearer::new("candidate-token".into()),
450            FAST,
451        )
452        .await
453        .unwrap_err();
454        assert!(matches!(error, ExecError::CandidateRejected { .. }));
455        assert!(!error.to_string().contains("candidate-token"));
456        assert_eq!(mock.requests().len(), 3, "retried for replication lag");
457    }
458
459    #[tokio::test]
460    async fn verify_succeeds_once_a_lagging_replica_catches_up() {
461        let calls = Arc::new(Mutex::new(0));
462        let c = calls.clone();
463        let mock = kanidm_mock::start(move |_| {
464            let mut n = c.lock().unwrap();
465            *n += 1;
466            if *n < 3 {
467                (401, "null".into())
468            } else {
469                whoami_ok()
470            }
471        })
472        .await;
473        verify_token(
474            &mock.client,
475            &mock.metrics,
476            ACCOUNT,
477            &Bearer::new("t".into()),
478            FAST,
479        )
480        .await
481        .unwrap();
482        assert_eq!(*calls.lock().unwrap(), 3);
483    }
484
485    #[tokio::test]
486    async fn verify_reports_persistent_server_errors_with_their_source() {
487        let mock = kanidm_mock::start(|_| (503, "{}".into())).await;
488        let error = verify_token(
489            &mock.client,
490            &mock.metrics,
491            ACCOUNT,
492            &Bearer::new("t".into()),
493            FAST,
494        )
495        .await
496        .unwrap_err();
497        assert!(matches!(error, ExecError::Api(_)));
498    }
499
500    #[tokio::test]
501    async fn revoke_by_id_and_already_absent_is_success() {
502        let mock = kanidm_mock::start(|req: &Request| {
503            if req.path.ends_with(TOKEN_A) {
504                (200, "null".into())
505            } else if req.path.ends_with(TOKEN_B) {
506                (404, json!("NoMatchingEntries").to_string())
507            } else {
508                (500, "{}".into())
509            }
510        })
511        .await;
512        assert_eq!(
513            revoke_token(&mock.client, &mock.metrics, ACCOUNT, uuid(TOKEN_A))
514                .await
515                .unwrap(),
516            RevokeOutcome::Revoked
517        );
518        assert_eq!(
519            revoke_token(&mock.client, &mock.metrics, ACCOUNT, uuid(TOKEN_B))
520                .await
521                .unwrap(),
522            RevokeOutcome::AlreadyAbsent
523        );
524        let writes = mock.writes();
525        assert_eq!(writes[0].method, "DELETE");
526        assert_eq!(
527            writes[0].path,
528            format!("/v1/service_account/{ACCOUNT}/_api_token/{TOKEN_A}")
529        );
530    }
531
532    #[tokio::test]
533    async fn revoke_failure_is_an_error() {
534        let mock = kanidm_mock::start(|_| (500, "{}".into())).await;
535        let error = revoke_token(&mock.client, &mock.metrics, ACCOUNT, uuid(TOKEN_A))
536            .await
537            .unwrap_err();
538        assert!(matches!(error, ExecError::Api(_)));
539    }
540}