Skip to main content

orca/models/
basic.rs

1use crate::model::{self, ActorModel, ActorRole, Transition, TransitionAction, TransitionResult};
2
3use crate::{error::Error, run::EventRecord, state::*};
4use kanidm_client::KanidmClient;
5
6use async_trait::async_trait;
7use rand::RngExt;
8use rand_chacha::ChaCha8Rng;
9
10use std::{collections::BTreeSet, time::Duration};
11
12enum State {
13    Unauthenticated,
14    Authenticated,
15    AuthenticatedWithReauth,
16}
17
18pub struct ActorBasic {
19    state: State,
20    randomised_backoff_time: Duration,
21}
22
23impl ActorBasic {
24    pub fn new(mut cha_rng: ChaCha8Rng, warmup_time_ms: u64) -> Self {
25        let max_backoff_time_in_ms = 2 * warmup_time_ms / 3;
26        let randomised_backoff_time =
27            Duration::from_millis(cha_rng.random_range(0..max_backoff_time_in_ms));
28        ActorBasic {
29            state: State::Unauthenticated,
30            randomised_backoff_time,
31        }
32    }
33}
34
35#[async_trait]
36impl ActorModel for ActorBasic {
37    async fn transition(
38        &mut self,
39        client: &KanidmClient,
40        person: &Person,
41    ) -> Result<Vec<EventRecord>, Error> {
42        let transition = self.next_transition(&person.roles);
43
44        if let Some(delay) = transition.delay {
45            tokio::time::sleep(delay).await;
46        }
47
48        // Once we get to here, we want the transition to go ahead.
49        let (result, event) = match transition.action {
50            TransitionAction::Login => model::login(client, person).await,
51            TransitionAction::Logout => model::logout(client, person).await,
52            TransitionAction::PrivilegeReauth => model::privilege_reauth(client, person).await,
53            TransitionAction::WriteAttributePersonMail => {
54                let mail = format!("{}@example.com", person.username);
55                let values = &[mail.as_str()];
56                model::person_set_self_mail(client, person, values).await
57            }
58            TransitionAction::ReadSelfAccount => {
59                model::person_get_self_account(client, person).await
60            }
61            TransitionAction::ReadSelfMemberOf => {
62                model::person_get_self_memberof(client, person).await
63            }
64            TransitionAction::WriteSelfPassword => {
65                // I know it's dumb but here we just re-set the same password because it's the simplest thing to do
66                let Credential::Password { plain } = &person.credential;
67                model::person_set_self_password(client, person, plain).await
68            }
69        }?;
70
71        self.next_state(transition.action, result);
72
73        Ok(event)
74    }
75}
76
77impl ActorBasic {
78    fn next_transition(&mut self, roles: &BTreeSet<ActorRole>) -> Transition {
79        let logout_transition = Transition {
80            delay: Some(Duration::from_secs(5)),
81            action: TransitionAction::Logout,
82        };
83        match self.state {
84            State::Unauthenticated => Transition {
85                delay: Some(self.randomised_backoff_time),
86                action: TransitionAction::Login,
87            },
88            State::Authenticated => Transition {
89                delay: Some(Duration::from_secs(2)),
90                action: TransitionAction::PrivilegeReauth,
91            },
92            // Since this is the basic model we don't want to get too fancy and do too many things, but since the struct Person
93            // already comes with a BTreeSet of roles we don't want to change that, so we arbitrarily choose to use just the first role
94            // (which is always deterministic thanks to the rng seed used to choose the roles)
95            State::AuthenticatedWithReauth => match roles.first() {
96                Some(role) => match role {
97                    ActorRole::PeopleSelfMailWrite => Transition {
98                        delay: Some(Duration::from_secs(5)),
99                        action: TransitionAction::WriteAttributePersonMail,
100                    },
101                    ActorRole::PeopleSelfReadProfile => Transition {
102                        delay: Some(Duration::from_secs(2)),
103                        action: TransitionAction::ReadSelfAccount,
104                    },
105                    ActorRole::PeopleSelfReadMemberOf => Transition {
106                        delay: Some(Duration::from_secs(1)),
107                        action: TransitionAction::ReadSelfMemberOf,
108                    },
109                    ActorRole::PeopleSelfSetPassword => Transition {
110                        delay: Some(Duration::from_secs(3)),
111                        action: TransitionAction::WriteSelfPassword,
112                    },
113                    ActorRole::PeoplePiiReader | ActorRole::PeopleGroupAdmin | ActorRole::None => {
114                        logout_transition
115                    }
116                },
117                None => logout_transition,
118            },
119        }
120    }
121
122    fn next_state(&mut self, action: TransitionAction, result: TransitionResult) {
123        // Is this a design flaw? We probably need to know what the state was that we
124        // requested to move to?
125        match (&self.state, action, result) {
126            (State::Unauthenticated, TransitionAction::Login, TransitionResult::Ok) => {
127                self.state = State::Authenticated;
128            }
129            (State::Authenticated, TransitionAction::PrivilegeReauth, TransitionResult::Ok) => {
130                self.state = State::AuthenticatedWithReauth;
131            }
132            (
133                State::AuthenticatedWithReauth,
134                TransitionAction::WriteAttributePersonMail
135                | TransitionAction::ReadSelfAccount
136                | TransitionAction::ReadSelfMemberOf
137                | TransitionAction::WriteSelfPassword,
138                TransitionResult::Ok,
139            ) => {
140                self.state = State::AuthenticatedWithReauth;
141            }
142            (_, TransitionAction::Logout, TransitionResult::Ok) => {
143                self.state = State::Unauthenticated;
144            }
145            #[allow(clippy::unreachable)]
146            (_, _, TransitionResult::Ok) => {
147                unreachable!();
148            }
149            (_, _, TransitionResult::Error) => {
150                self.state = State::Unauthenticated;
151            }
152        }
153    }
154}