Skip to main content

orca/
generate.rs

1use crate::{
2    error::Error,
3    kani::KanidmOrcaClient,
4    model::ActorRole,
5    profile::Profile,
6    state::{Credential, Flag, Group, GroupName, Person, PreflightState, State},
7};
8use hashbrown::HashMap;
9use rand::{
10    distr::{Alphanumeric, SampleString, Uniform},
11    seq::{index, IndexedRandom},
12};
13
14use rand::{RngExt, SeedableRng};
15use rand_chacha::ChaCha8Rng;
16
17use std::collections::BTreeSet;
18
19const PEOPLE_PREFIX: &str = "person";
20
21// #[derive(Debug)]
22// pub struct PartialGroup {
23//     pub name: String,
24//     pub members: BTreeSet<String>,
25// }
26
27fn random_name(prefix: &str, rng: &mut ChaCha8Rng) -> String {
28    let suffix = Alphanumeric.sample_string(rng, 8).to_lowercase();
29    format!("{prefix}_{suffix}")
30}
31
32fn random_password(rng: &mut ChaCha8Rng) -> String {
33    Alphanumeric.sample_string(rng, 24)
34}
35
36pub async fn populate(_client: &KanidmOrcaClient, profile: Profile) -> Result<State, Error> {
37    // IMPORTANT: We have to perform these steps in order so that the RNG is deterministic between
38    // multiple invocations.
39    let mut seeded_rng = ChaCha8Rng::seed_from_u64(profile.seed());
40
41    let female_given_names = std::include_str!("../names-dataset/dataset/Female_given_names.txt");
42    let male_given_names = std::include_str!("../names-dataset/dataset/Male_given_names.txt");
43
44    let given_names = female_given_names
45        .split('\n')
46        .chain(male_given_names.split('\n'))
47        .collect::<Vec<_>>();
48
49    let surnames = std::include_str!("../names-dataset/dataset/Surnames.txt");
50
51    let surnames = surnames.split('\n').collect::<Vec<_>>();
52
53    debug!(
54        "name pool: given: {} - family: {}",
55        given_names.len(),
56        surnames.len()
57    );
58
59    let thread_count = profile.thread_count();
60
61    // PHASE 0 - For now, set require MFA off and extend the privilege expiry.
62    let preflight_flags = vec![
63        Flag::DisableAllPersonsMFAPolicy,
64        Flag::ExtendPrivilegedAuthExpiry,
65    ];
66
67    // PHASE 1 - generate a pool of persons that are not-yet created for future import.
68
69    // PHASE 2 - generate groups for integration access, assign roles to groups.
70    // These decide what each person is supposed to do with their life.
71    let mut groups = vec![
72        Group {
73            name: GroupName::RolePeopleSelfSetPassword,
74            role: ActorRole::PeopleSelfSetPassword,
75            ..Default::default()
76        },
77        Group {
78            name: GroupName::RolePeoplePiiReader,
79            role: ActorRole::PeoplePiiReader,
80            ..Default::default()
81        },
82        Group {
83            name: GroupName::RolePeopleSelfMailWrite,
84            role: ActorRole::PeopleSelfMailWrite,
85            ..Default::default()
86        },
87        Group {
88            name: GroupName::RolePeopleSelfReadProfile,
89            role: ActorRole::PeopleSelfReadProfile,
90            ..Default::default()
91        },
92        Group {
93            name: GroupName::RolePeopleSelfReadMemberOf,
94            role: ActorRole::PeopleSelfReadMemberOf,
95            ..Default::default()
96        },
97        Group {
98            name: GroupName::RolePeopleGroupAdmin,
99            role: ActorRole::PeopleGroupAdmin,
100            ..Default::default()
101        },
102    ];
103
104    // PHASE 3 - generate persons
105    //         - assign them credentials of various types.
106    let mut persons = Vec::with_capacity(profile.person_count() as usize);
107    let mut person_usernames = BTreeSet::new();
108
109    let model = *profile.model();
110
111    for _ in 0..profile.person_count() {
112        let given_name = given_names
113            .choose(&mut seeded_rng)
114            .expect("name set corrupted");
115        let surname = surnames
116            .choose(&mut seeded_rng)
117            .expect("name set corrupted");
118
119        let display_name = format!("{given_name} {surname}");
120
121        let username = display_name
122            .chars()
123            .filter(|c| c.is_ascii_alphanumeric())
124            .collect::<String>()
125            .to_lowercase();
126
127        let mut username = if username.is_empty() {
128            random_name(PEOPLE_PREFIX, &mut seeded_rng)
129        } else {
130            username
131        };
132
133        while person_usernames.contains(&username) {
134            username = random_name(PEOPLE_PREFIX, &mut seeded_rng);
135        }
136
137        let password = random_password(&mut seeded_rng);
138
139        let roles = BTreeSet::new();
140
141        // Data is ready, make changes to the server. These should be idempotent if possible.
142        let p = Person {
143            preflight_state: PreflightState::Present,
144            username: username.clone(),
145            display_name,
146            roles,
147            credential: Credential::Password { plain: password },
148            model,
149        };
150
151        debug!(?p);
152
153        person_usernames.insert(username.clone());
154        persons.push(p);
155    }
156
157    // Now, assign persons to roles.
158    //
159    // We do this by iterating through our roles, and then assigning
160    // them a baseline of required accounts with some variation. This
161    // way in each test it's guaranteed that *at least* one person
162    // to each role always will exist and be operational.
163    let member_count_by_group: HashMap<GroupName, u64> = profile
164        .get_properties_by_group()
165        .iter()
166        .filter_map(|(name, properties)| {
167            let group_name = GroupName::try_from(name).ok()?;
168            properties.member_count.map(|count| (group_name, count))
169        })
170        .collect();
171
172    for group in groups.iter_mut() {
173        let persons_to_choose = match member_count_by_group.get(&group.name) {
174            Some(person_count) => *person_count as usize,
175            None => {
176                let baseline = persons.len() / 3;
177                let inverse = persons.len() - baseline;
178                // Randomly add extra from the inverse
179                let extra =
180                    Uniform::new(0, inverse).map_err(|err| Error::RandomNumber(err.to_string()))?;
181                baseline + seeded_rng.sample(extra)
182            }
183        };
184
185        assert!(persons_to_choose <= persons.len());
186
187        debug!(?persons_to_choose);
188
189        let person_index = index::sample(&mut seeded_rng, persons.len(), persons_to_choose);
190
191        // Order doesn't matter, lets optimise for linear lookup.
192        let mut person_index = person_index.into_vec();
193        person_index.sort_unstable();
194
195        for p_idx in person_index {
196            let person = persons.get_mut(p_idx).unwrap();
197
198            // Add the person to the group.
199            group.members.insert(person.username.clone());
200
201            // Add the reverse links, this allows the person in the test
202            // to know their roles
203            person.roles.insert(group.role.clone());
204        }
205    }
206
207    // PHASE 4 - generate groups for user modification rights
208
209    // PHASE 5 - generate excess groups with nesting. Randomly assign persons.
210
211    // PHASE 6 - generate integrations -
212
213    // PHASE 7 - given the integrations and groupings,
214
215    drop(member_count_by_group); // it looks ugly but we have to do this to reassure the borrow checker we can return profile, as we were borrowing
216                                 //the group names from it
217
218    // Return the state.
219    let state = State {
220        profile,
221        // ---------------
222        groups,
223        preflight_flags,
224        persons,
225        thread_count,
226    };
227
228    Ok(state)
229}