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
// Generate and manage spn's for all entries in the domain. Also deals with
// the infrequent - but possible - case where a domain is renamed.
use std::iter::once;
use std::sync::Arc;

// use crate::value::{PartialValue, Value};
use kanidm_proto::v1::{ConsistencyError, OperationError};

use crate::entry::{Entry, EntryCommitted, EntryInvalid, EntryNew, EntrySealed};
use crate::event::{CreateEvent, ModifyEvent};
use crate::plugins::Plugin;
use crate::prelude::*;

pub struct Spn {}

impl Plugin for Spn {
    fn id() -> &'static str {
        "plugin_spn"
    }

    // hook on pre-create and modify to generate / validate.
    #[instrument(level = "debug", name = "spn_pre_create_transform", skip_all)]
    fn pre_create_transform(
        qs: &mut QueryServerWriteTransaction,
        cand: &mut Vec<Entry<EntryInvalid, EntryNew>>,
        _ce: &CreateEvent,
    ) -> Result<(), OperationError> {
        // Always generate the spn and set it. Why? Because the effort
        // needed to validate is the same as generation, so we may as well
        // just generate and set blindly when required.
        Self::modify_inner(qs, cand)
    }

    #[instrument(level = "debug", name = "spn_pre_modify", skip_all)]
    fn pre_modify(
        qs: &mut QueryServerWriteTransaction,
        cand: &mut Vec<Entry<EntryInvalid, EntryCommitted>>,
        _me: &ModifyEvent,
    ) -> Result<(), OperationError> {
        Self::modify_inner(qs, cand)
    }

    #[instrument(level = "debug", name = "spn_pre_batch_modify", skip_all)]
    fn pre_batch_modify(
        qs: &mut QueryServerWriteTransaction,
        cand: &mut Vec<Entry<EntryInvalid, EntryCommitted>>,
        _me: &BatchModifyEvent,
    ) -> Result<(), OperationError> {
        Self::modify_inner(qs, cand)
    }

    #[instrument(level = "debug", name = "spn_post_modify", skip_all)]
    fn post_modify(
        qs: &mut QueryServerWriteTransaction,
        // List of what we modified that was valid?
        pre_cand: &[Arc<Entry<EntrySealed, EntryCommitted>>],
        cand: &[Entry<EntrySealed, EntryCommitted>],
        _ce: &ModifyEvent,
    ) -> Result<(), OperationError> {
        Self::post_modify_inner(qs, pre_cand, cand)
    }

    #[instrument(level = "debug", name = "spn_post_batch_modify", skip_all)]
    fn post_batch_modify(
        qs: &mut QueryServerWriteTransaction,
        // List of what we modified that was valid?
        pre_cand: &[Arc<Entry<EntrySealed, EntryCommitted>>],
        cand: &[Entry<EntrySealed, EntryCommitted>],
        _ce: &BatchModifyEvent,
    ) -> Result<(), OperationError> {
        Self::post_modify_inner(qs, pre_cand, cand)
    }

    #[instrument(level = "debug", name = "spn_verify", skip(qs))]
    fn verify(qs: &mut QueryServerReadTransaction) -> Vec<Result<(), ConsistencyError>> {
        // Verify that all items with spn's have valid spns.
        //   We need to consider the case that an item has a different origin domain too,
        // so we should be able to verify that *those* spns validate to the trusted domain info
        // we have been sent also. It's not up to use to generate those though ...

        let domain_name = qs.get_domain_name().to_string();

        let filt_in = filter!(f_or!([
            f_eq("class", PVCLASS_GROUP.clone()),
            f_eq("class", PVCLASS_ACCOUNT.clone())
        ]));

        let all_cand = match qs
            .internal_search(filt_in)
            .map_err(|_| Err(ConsistencyError::QueryServerSearchFailure))
        {
            Ok(all_cand) => all_cand,
            Err(e) => return vec![e],
        };

        let mut r = Vec::new();

        for e in all_cand {
            let g_spn = match e.generate_spn(&domain_name) {
                Some(s) => s,
                None => {
                    admin_error!(
                        uuid = ?e.get_uuid(),
                        "Entry SPN could not be generated (missing name!?)",
                    );
                    debug_assert!(false);
                    r.push(Err(ConsistencyError::InvalidSpn(e.get_id())));
                    continue;
                }
            };
            match e.get_ava_single("spn") {
                Some(r_spn) => {
                    trace!("verify spn: s {:?} == ex {:?} ?", r_spn, g_spn);
                    if r_spn != g_spn {
                        admin_error!(
                            uuid = ?e.get_uuid(),
                            "Entry SPN does not match expected s {:?} != ex {:?}",
                            r_spn,
                            g_spn,
                        );
                        debug_assert!(false);
                        r.push(Err(ConsistencyError::InvalidSpn(e.get_id())))
                    }
                }
                None => {
                    admin_error!(uuid = ?e.get_uuid(), "Entry does not contain an SPN");
                    r.push(Err(ConsistencyError::InvalidSpn(e.get_id())))
                }
            }
        }
        r
    }
}

impl Spn {
    fn modify_inner<T: Clone + std::fmt::Debug>(
        qs: &mut QueryServerWriteTransaction,
        cand: &mut [Entry<EntryInvalid, T>],
    ) -> Result<(), OperationError> {
        let domain_name = qs.get_domain_name();

        for ent in cand.iter_mut() {
            if ent.attribute_equality("class", &PVCLASS_GROUP)
                || ent.attribute_equality("class", &PVCLASS_ACCOUNT)
            {
                let spn = ent
                    .generate_spn(domain_name)
                    .ok_or(OperationError::InvalidEntryState)
                    .map_err(|e| {
                        admin_error!(
                            "Account or group missing name, unable to generate spn!? {:?} entry_id = {:?}",
                            e, ent.get_uuid()
                        );
                        e
                    })?;
                trace!("plugin_spn: set spn to {:?}", spn);
                ent.set_ava("spn", once(spn));
            }
        }
        Ok(())
    }

    fn post_modify_inner(
        qs: &mut QueryServerWriteTransaction,
        pre_cand: &[Arc<Entry<EntrySealed, EntryCommitted>>],
        cand: &[Entry<EntrySealed, EntryCommitted>],
    ) -> Result<(), OperationError> {
        // On modify, if changing domain_name on UUID_DOMAIN_INFO
        //    trigger the spn regen ... which is expensive. Future
        // TODO #157: will be improvements to modify on large txns.

        let domain_name_changed = cand.iter().zip(pre_cand.iter()).find_map(|(post, pre)| {
            let domain_name = post.get_ava_single("domain_name");
            if post.attribute_equality("uuid", &PVUUID_DOMAIN_INFO)
                && domain_name != pre.get_ava_single("domain_name")
            {
                domain_name
            } else {
                None
            }
        });

        let domain_name = match domain_name_changed {
            Some(s) => s,
            None => return Ok(()),
        };

        admin_info!(
            "IMPORTANT!!! Changing domain name to \"{:?}\". THIS MAY TAKE A LONG TIME ...",
            domain_name
        );

        // All we do is purge spn, and allow the plugin to recreate. Neat! It's also all still
        // within the transaction, just in case!
        qs.internal_modify(
            &filter!(f_or!([
                f_eq("class", PVCLASS_GROUP.clone()),
                f_eq("class", PVCLASS_ACCOUNT.clone())
            ])),
            &modlist!([m_purge("spn")]),
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;

    #[test]
    fn test_spn_generate_create() {
        // on create don't provide
        let e: Entry<EntryInit, EntryNew> = Entry::unsafe_from_entry_str(
            r#"{
            "attrs": {
                "class": ["account", "service_account"],
                "name": ["testperson"],
                "description": ["testperson"],
                "displayname": ["testperson"]
            }
        }"#,
        );

        let create = vec![e];
        let preload = Vec::new();

        run_create_test!(
            Ok(()),
            preload,
            create,
            None,
            |_qs_write: &QueryServerWriteTransaction| {}
        );
        // We don't need a validator due to the fn verify above.
    }

    #[test]
    fn test_spn_generate_modify() {
        // on a purge of the spen, generate it.
        let e: Entry<EntryInit, EntryNew> = Entry::unsafe_from_entry_str(
            r#"{
            "attrs": {
                "class": ["account", "service_account"],
                "name": ["testperson"],
                "description": ["testperson"],
                "displayname": ["testperson"]
            }
        }"#,
        );

        let preload = vec![e];

        run_modify_test!(
            Ok(()),
            preload,
            filter!(f_eq("name", PartialValue::new_iname("testperson"))),
            modlist!([m_purge("spn")]),
            None,
            |_| {},
            |_| {}
        );
    }

    #[test]
    fn test_spn_validate_create() {
        // on create providing invalid spn, we over-write it.
        let e: Entry<EntryInit, EntryNew> = Entry::unsafe_from_entry_str(
            r#"{
            "attrs": {
                "class": ["account", "service_account"],
                "spn": ["testperson@invalid_domain.com"],
                "name": ["testperson"],
                "description": ["testperson"],
                "displayname": ["testperson"]
            }
        }"#,
        );

        let create = vec![e];
        let preload = Vec::new();

        run_create_test!(
            Ok(()),
            preload,
            create,
            None,
            |_qs_write: &QueryServerWriteTransaction| {}
        );
    }

    #[test]
    fn test_spn_validate_modify() {
        // On modify (removed/present) of the spn, just regenerate it.
        let e: Entry<EntryInit, EntryNew> = Entry::unsafe_from_entry_str(
            r#"{
            "attrs": {
                "class": ["account", "service_account"],
                "name": ["testperson"],
                "description": ["testperson"],
                "displayname": ["testperson"]
            }
        }"#,
        );

        let preload = vec![e];

        run_modify_test!(
            Ok(()),
            preload,
            filter!(f_eq("name", PartialValue::new_iname("testperson"))),
            modlist!([
                m_purge("spn"),
                m_pres("spn", &Value::new_spn_str("invalid", "spn"))
            ]),
            None,
            |_| {},
            |_| {}
        );
    }

    #[qs_test]
    async fn test_spn_regen_domain_rename(server: &QueryServer) {
        let mut server_txn = server.write(duration_from_epoch_now()).await;

        let ex1 = Value::new_spn_str("admin", "example.com");
        let ex2 = Value::new_spn_str("admin", "new.example.com");
        // get the current domain name
        // check the spn on admin is admin@<initial domain>
        let e_pre = server_txn
            .internal_search_uuid(UUID_ADMIN)
            .expect("must not fail");

        let e_pre_spn = e_pre.get_ava_single("spn").expect("must not fail");
        assert!(e_pre_spn == ex1);

        // trigger the domain_name change (this will be a cli option to the server
        // in the final version), but it will still call the same qs function to perform the
        // change.
        unsafe {
            server_txn
                .domain_rename_inner("new.example.com")
                .expect("should not fail!");
        }

        // check the spn on admin is admin@<new domain>
        let e_post = server_txn
            .internal_search_uuid(UUID_ADMIN)
            .expect("must not fail");

        let e_post_spn = e_post.get_ava_single("spn").expect("must not fail");
        debug!("{:?}", e_post_spn);
        debug!("{:?}", ex2);
        assert!(e_post_spn == ex2);

        server_txn.commit().expect("Must not fail");
    }
}