Skip to main content

vcon_server/
settings.rs

1//! A tenant's settings: the fixed list of names a tenant administrator may
2//! set, what each may hold, and what each is while unset.
3//!
4//! This is the one list of names. The registry keeps a row for each
5//! setting that was set (`tenant_setting`: tenant, name, value as
6//! [`Value::text`] writes it); a name with no row has its default. A row
7//! whose name or value this list does not read is damage, not a default.
8//!
9//! The names are `masking.<role>` for each tenant role (whether the
10//! console masks personal data for a user holding the role; on while
11//! unset), and `session.idle_seconds` and `session.absolute_seconds` (how
12//! long a session lasts without a request, and at most), each within the
13//! bounds this file states, with the idle limit never above the absolute
14//! one.
15
16use std::fmt;
17use std::ops::RangeInclusive;
18
19use crate::roles::{Role, Roles};
20
21/// The bounds of `session.idle_seconds`: one minute to 15 minutes, which
22/// is also what an unset limit is.
23pub const IDLE_SECONDS: RangeInclusive<u32> = 60..=900;
24
25/// The bounds of `session.absolute_seconds`: 5 minutes to 8 hours, which
26/// is also what an unset limit is.
27pub const ABSOLUTE_SECONDS: RangeInclusive<u32> = 300..=28_800;
28
29/// The name of a setting.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum Name {
32    /// Whether the console masks personal data for a user holding this
33    /// tenant role. The operator role has no setting: [`Name::ALL`] and
34    /// [`Name::parse`] never give it, and it reads as masked.
35    Masking(Role),
36    /// Seconds a session lasts without a request.
37    SessionIdle,
38    /// Seconds a session lasts at most.
39    SessionAbsolute,
40}
41
42/// What a setting holds.
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum Value {
45    /// A masking name's value: true while the console masks.
46    Flag(bool),
47    /// A limit's value.
48    Seconds(u32),
49}
50
51/// Why a change to the settings was refused.
52#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum SettingError {
54    /// A name outside [`Name::ALL`].
55    UnknownName,
56    /// A value that is not a flag for a masking name or a whole number
57    /// for a limit, or a change that is not an object of names.
58    BadValue,
59    /// A limit outside [`IDLE_SECONDS`] or [`ABSOLUTE_SECONDS`].
60    OutOfBounds,
61    /// The change would leave the idle limit above the absolute one.
62    IdleOverAbsolute,
63}
64
65impl fmt::Display for SettingError {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(match self {
68            SettingError::UnknownName => "a name is not a setting",
69            SettingError::BadValue => "a value is not of its setting's kind",
70            SettingError::OutOfBounds => "a limit is outside its bounds",
71            SettingError::IdleOverAbsolute => "the idle limit is above the absolute limit",
72        })
73    }
74}
75
76/// One name of a change with the value to store for it, or None to remove
77/// its row, which puts the name back to its default.
78pub type Change = (Name, Option<Value>);
79
80impl Name {
81    /// Every name, in the order a reader sees them.
82    pub const ALL: [Name; 8] = [
83        Name::Masking(Role::Reader),
84        Name::Masking(Role::Producer),
85        Name::Masking(Role::Records),
86        Name::Masking(Role::Legal),
87        Name::Masking(Role::Auditor),
88        Name::Masking(Role::TenantAdmin),
89        Name::SessionIdle,
90        Name::SessionAbsolute,
91    ];
92
93    /// The name as the registry, a body and an answer write it.
94    #[must_use]
95    pub fn as_str(self) -> &'static str {
96        match self {
97            Name::Masking(Role::Reader) => "masking.reader",
98            Name::Masking(Role::Producer) => "masking.producer",
99            Name::Masking(Role::Records) => "masking.records",
100            Name::Masking(Role::Legal) => "masking.legal",
101            Name::Masking(Role::Auditor) => "masking.auditor",
102            Name::Masking(Role::TenantAdmin) => "masking.tenant-admin",
103            Name::Masking(Role::Operator) => "masking.operator",
104            Name::SessionIdle => "session.idle_seconds",
105            Name::SessionAbsolute => "session.absolute_seconds",
106        }
107    }
108
109    /// The name written exactly as `text`, if the list has it.
110    #[must_use]
111    pub fn parse(text: &str) -> Option<Name> {
112        Name::ALL.into_iter().find(|name| name.as_str() == text)
113    }
114
115    /// The bounds of a limit; None for a masking flag.
116    fn bounds(self) -> Option<RangeInclusive<u32>> {
117        match self {
118            Name::Masking(_) => None,
119            Name::SessionIdle => Some(IDLE_SECONDS),
120            Name::SessionAbsolute => Some(ABSOLUTE_SECONDS),
121        }
122    }
123
124    /// The value a stored row's text holds for this name: only text that
125    /// [`Value::text`] writes, within the name's bounds.
126    #[must_use]
127    pub fn read(self, text: &str) -> Option<Value> {
128        let value = match self.bounds() {
129            None => Value::Flag(text.parse().ok()?),
130            Some(bounds) => {
131                let seconds = text.parse().ok()?;
132                bounds
133                    .contains(&seconds)
134                    .then_some(Value::Seconds(seconds))?
135            }
136        };
137        (value.text() == text).then_some(value)
138    }
139
140    /// The value a change's JSON holds for this name.
141    fn taken(self, value: &serde_json::Value) -> Result<Value, SettingError> {
142        let Some(bounds) = self.bounds() else {
143            return value
144                .as_bool()
145                .map(Value::Flag)
146                .ok_or(SettingError::BadValue);
147        };
148        let seconds = value.as_u64().ok_or(SettingError::BadValue)?;
149        u32::try_from(seconds)
150            .ok()
151            .filter(|seconds| bounds.contains(seconds))
152            .map(Value::Seconds)
153            .ok_or(SettingError::OutOfBounds)
154    }
155}
156
157impl Value {
158    /// The value as a stored row keeps it.
159    #[must_use]
160    pub fn text(self) -> String {
161        match self {
162            Value::Flag(flag) => flag.to_string(),
163            Value::Seconds(seconds) => seconds.to_string(),
164        }
165    }
166
167    fn to_json(self) -> serde_json::Value {
168        match self {
169            Value::Flag(flag) => flag.into(),
170            Value::Seconds(seconds) => seconds.into(),
171        }
172    }
173}
174
175/// The names of a change, comma-separated, in the list's order: what the
176/// audit record of the change keeps. It never holds a value.
177#[must_use]
178pub fn named(changes: &[Change]) -> String {
179    let names: Vec<&str> = changes.iter().map(|(name, _)| name.as_str()).collect();
180    names.join(",")
181}
182
183/// Every setting of one tenant.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub struct Settings {
186    /// The roles whose masking is off.
187    unmasked: Roles,
188    idle: u32,
189    absolute: u32,
190}
191
192impl Default for Settings {
193    /// What a tenant that set nothing has.
194    fn default() -> Settings {
195        Settings {
196            unmasked: Roles::default(),
197            idle: *IDLE_SECONDS.end(),
198            absolute: *ABSOLUTE_SECONDS.end(),
199        }
200    }
201}
202
203impl Settings {
204    /// The value of one name.
205    #[must_use]
206    pub fn get(&self, name: Name) -> Value {
207        match name {
208            Name::Masking(role) => Value::Flag(!self.unmasked.contains(role)),
209            Name::SessionIdle => Value::Seconds(self.idle),
210            Name::SessionAbsolute => Value::Seconds(self.absolute),
211        }
212    }
213
214    fn set(&mut self, name: Name, value: Value) {
215        match (name, value) {
216            (Name::Masking(role), Value::Flag(true)) => {
217                self.unmasked = self.unmasked.without(Roles::of(&[role]));
218            }
219            (Name::Masking(role), Value::Flag(false)) => {
220                self.unmasked = self.unmasked.with(Roles::of(&[role]));
221            }
222            (Name::SessionIdle, Value::Seconds(seconds)) => self.idle = seconds,
223            (Name::SessionAbsolute, Value::Seconds(seconds)) => self.absolute = seconds,
224            // `Name::read` and `Name::taken` give each name its own kind.
225            (Name::Masking(_), Value::Seconds(_))
226            | (Name::SessionIdle | Name::SessionAbsolute, Value::Flag(_)) => {}
227        }
228    }
229
230    /// The one rule that spans two names.
231    fn whole(self) -> Option<Settings> {
232        (self.idle <= self.absolute).then_some(self)
233    }
234
235    /// The settings a tenant's stored rows (name, value) make over the
236    /// defaults. None for damage: a name outside the list or stored twice,
237    /// a value its name does not read, or an idle limit above the absolute
238    /// one.
239    #[must_use]
240    pub fn stored(rows: &[(String, String)]) -> Option<Settings> {
241        let mut settings = Settings::default();
242        let mut seen = Vec::new();
243        for (name, value) in rows {
244            let name = Name::parse(name)?;
245            if seen.contains(&name) {
246                return None;
247            }
248            seen.push(name);
249            settings.set(name, name.read(value)?);
250        }
251        settings.whole()
252    }
253
254    /// These settings after a change: a JSON object of names, each with
255    /// its new value or null for its default. Also gives the rows to
256    /// write and remove, in the list's order. Nothing of a refused change
257    /// is taken.
258    ///
259    /// # Errors
260    ///
261    /// A [`SettingError`] for a change that is not an object, names a
262    /// setting outside the list, gives a value of the wrong kind or a limit
263    /// outside its bounds, or would leave the idle limit above the absolute
264    /// one.
265    pub fn changed(
266        &self,
267        change: &serde_json::Value,
268    ) -> Result<(Settings, Vec<Change>), SettingError> {
269        let change = change.as_object().ok_or(SettingError::BadValue)?;
270        if change.keys().any(|name| Name::parse(name).is_none()) {
271            return Err(SettingError::UnknownName);
272        }
273        let mut settings = *self;
274        let mut changes = Vec::new();
275        for name in Name::ALL {
276            let Some(value) = change.get(name.as_str()) else {
277                continue;
278            };
279            let stored = if value.is_null() {
280                settings.set(name, Settings::default().get(name));
281                None
282            } else {
283                let value = name.taken(value)?;
284                settings.set(name, value);
285                Some(value)
286            };
287            changes.push((name, stored));
288        }
289        let settings = settings.whole().ok_or(SettingError::IdleOverAbsolute)?;
290        Ok((settings, changes))
291    }
292
293    /// One object with every name and its value.
294    #[must_use]
295    pub fn to_json(&self) -> serde_json::Value {
296        Name::ALL
297            .into_iter()
298            .map(|name| (name.as_str().to_owned(), self.get(name).to_json()))
299            .collect::<serde_json::Map<_, _>>()
300            .into()
301    }
302}
303
304#[cfg(test)]
305mod tests {
306    use serde_json::json;
307
308    use super::*;
309    use crate::roles::Role;
310
311    fn rows(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
312        pairs
313            .iter()
314            .map(|(name, value)| ((*name).to_owned(), (*value).to_owned()))
315            .collect()
316    }
317
318    // Success.
319
320    #[test]
321    fn the_names_are_a_masking_flag_for_each_tenant_role_and_two_limits() {
322        let names: Vec<&str> = Name::ALL.iter().map(|name| name.as_str()).collect();
323        assert_eq!(
324            names,
325            [
326                "masking.reader",
327                "masking.producer",
328                "masking.records",
329                "masking.legal",
330                "masking.auditor",
331                "masking.tenant-admin",
332                "session.idle_seconds",
333                "session.absolute_seconds",
334            ],
335            "the fixed list of names, in the order a reader sees them"
336        );
337    }
338
339    #[test]
340    fn each_name_reads_back_from_its_text() {
341        for name in Name::ALL {
342            assert_eq!(
343                Name::parse(name.as_str()),
344                Some(name),
345                "{} reads back",
346                name.as_str()
347            );
348        }
349    }
350
351    #[test]
352    fn unset_settings_mask_every_role_and_keep_the_longest_limits() {
353        let unset = Settings::default();
354        for role in Role::ALL.into_iter().filter(|role| *role != Role::Operator) {
355            assert_eq!(
356                unset.get(Name::Masking(role)),
357                Value::Flag(true),
358                "masking is on for {} while unset",
359                role.name()
360            );
361        }
362        assert_eq!(
363            unset.get(Name::SessionIdle),
364            Value::Seconds(900),
365            "15 minutes idle while unset"
366        );
367        assert_eq!(
368            unset.get(Name::SessionAbsolute),
369            Value::Seconds(28_800),
370            "8 hours at most while unset"
371        );
372    }
373
374    #[test]
375    fn settings_are_shown_as_one_object_with_every_name() {
376        assert_eq!(
377            Settings::default().to_json(),
378            json!({
379                "masking.reader": true,
380                "masking.producer": true,
381                "masking.records": true,
382                "masking.legal": true,
383                "masking.auditor": true,
384                "masking.tenant-admin": true,
385                "session.idle_seconds": 900,
386                "session.absolute_seconds": 28_800,
387            }),
388            "every name with its value"
389        );
390    }
391
392    #[test]
393    fn a_change_sets_the_names_it_holds_and_leaves_the_others() {
394        let body = json!({ "masking.legal": false, "session.idle_seconds": 300 });
395        let (now, changes) = Settings::default().changed(&body).expect("a good change");
396        assert_eq!(
397            now.get(Name::Masking(Role::Legal)),
398            Value::Flag(false),
399            "set"
400        );
401        assert_eq!(now.get(Name::SessionIdle), Value::Seconds(300), "set");
402        assert_eq!(
403            now.get(Name::Masking(Role::Reader)),
404            Value::Flag(true),
405            "a name the change does not hold stays"
406        );
407        assert_eq!(
408            changes,
409            vec![
410                (Name::Masking(Role::Legal), Some(Value::Flag(false))),
411                (Name::SessionIdle, Some(Value::Seconds(300))),
412            ],
413            "the rows to write, in the list's order"
414        );
415    }
416
417    #[test]
418    fn a_null_puts_a_name_back_to_its_default() {
419        let was = Settings::stored(&rows(&[("session.idle_seconds", "120")])).expect("good rows");
420        let (now, changes) = was
421            .changed(&json!({ "session.idle_seconds": null }))
422            .expect("a good change");
423        assert_eq!(now, Settings::default(), "the default again");
424        assert_eq!(
425            changes,
426            vec![(Name::SessionIdle, None)],
427            "the row to remove"
428        );
429    }
430
431    #[test]
432    fn stored_rows_read_back_over_the_defaults() {
433        let read = Settings::stored(&rows(&[
434            ("masking.auditor", "false"),
435            ("session.absolute_seconds", "3600"),
436            ("session.idle_seconds", "600"),
437        ]))
438        .expect("good rows");
439        assert_eq!(
440            read.get(Name::Masking(Role::Auditor)),
441            Value::Flag(false),
442            "stored"
443        );
444        assert_eq!(
445            read.get(Name::SessionAbsolute),
446            Value::Seconds(3600),
447            "stored"
448        );
449        assert_eq!(read.get(Name::SessionIdle), Value::Seconds(600), "stored");
450        assert_eq!(
451            read.get(Name::Masking(Role::Reader)),
452            Value::Flag(true),
453            "no row: the default"
454        );
455    }
456
457    #[test]
458    fn a_value_is_written_as_the_text_it_reads_back_from() {
459        for (name, value, text) in [
460            (Name::Masking(Role::Reader), Value::Flag(false), "false"),
461            (Name::Masking(Role::Reader), Value::Flag(true), "true"),
462            (Name::SessionIdle, Value::Seconds(60), "60"),
463            (Name::SessionAbsolute, Value::Seconds(28_800), "28800"),
464        ] {
465            assert_eq!(value.text(), text, "{value:?} as text");
466            assert_eq!(
467                name.read(text),
468                Some(value),
469                "{text} read as {}",
470                name.as_str()
471            );
472        }
473    }
474
475    #[test]
476    fn both_limits_take_each_end_of_their_bounds() {
477        for (body, name, seconds) in [
478            (json!({ "session.idle_seconds": 60 }), Name::SessionIdle, 60),
479            (
480                json!({ "session.idle_seconds": 900 }),
481                Name::SessionIdle,
482                900,
483            ),
484            (
485                json!({ "session.absolute_seconds": 900 }),
486                Name::SessionAbsolute,
487                900,
488            ),
489            (
490                json!({ "session.absolute_seconds": 28_800 }),
491                Name::SessionAbsolute,
492                28_800,
493            ),
494        ] {
495            let (now, _) = Settings::default()
496                .changed(&body)
497                .unwrap_or_else(|error| panic!("{body} is within the bounds: {error:?}"));
498            assert_eq!(now.get(name), Value::Seconds(seconds), "{body}");
499        }
500    }
501
502    #[test]
503    fn a_change_that_states_the_value_a_name_has_still_writes_its_row() {
504        let (now, changes) = Settings::default()
505            .changed(&json!({ "masking.reader": true }))
506            .expect("a good change");
507        assert_eq!(now, Settings::default(), "nothing differs");
508        assert_eq!(
509            changes,
510            vec![(Name::Masking(Role::Reader), Some(Value::Flag(true)))],
511            "the name is set, not unset: its row is written"
512        );
513    }
514
515    #[test]
516    fn both_limits_may_change_together_to_a_pair_neither_could_reach_alone() {
517        let was = Settings::stored(&rows(&[
518            ("session.absolute_seconds", "300"),
519            ("session.idle_seconds", "120"),
520        ]))
521        .expect("good rows");
522        let body = json!({ "session.idle_seconds": 600, "session.absolute_seconds": 1200 });
523        let (now, _) = was.changed(&body).expect("the pair is good");
524        assert_eq!(now.get(Name::SessionIdle), Value::Seconds(600), "idle");
525        assert_eq!(
526            now.get(Name::SessionAbsolute),
527            Value::Seconds(1200),
528            "absolute"
529        );
530    }
531
532    #[test]
533    fn the_idle_limit_may_equal_the_absolute_one() {
534        let body = json!({ "session.idle_seconds": 600, "session.absolute_seconds": 600 });
535        let (now, _) = Settings::default().changed(&body).expect("equal is good");
536        assert_eq!(now.get(Name::SessionIdle), Value::Seconds(600), "idle");
537    }
538
539    // Failure.
540
541    #[test]
542    fn a_name_outside_the_list_is_refused() {
543        for name in [
544            "masking",
545            "masking.operator",
546            "masking.nobody",
547            "session.idle",
548            "bulk_export",
549            "",
550        ] {
551            assert_eq!(
552                Settings::default().changed(&json!({ name: true })),
553                Err(SettingError::UnknownName),
554                "{name:?} is not a setting"
555            );
556        }
557    }
558
559    #[test]
560    fn a_masking_flag_takes_only_true_or_false() {
561        for value in [json!("off"), json!(0), json!(1), json!([]), json!({})] {
562            assert_eq!(
563                Settings::default().changed(&json!({ "masking.reader": value })),
564                Err(SettingError::BadValue),
565                "{value} is not a flag"
566            );
567        }
568    }
569
570    #[test]
571    fn a_limit_takes_only_a_whole_number() {
572        for value in [
573            json!("300"),
574            json!(300.5),
575            json!(-300),
576            json!(true),
577            json!([300]),
578        ] {
579            assert_eq!(
580                Settings::default().changed(&json!({ "session.idle_seconds": value })),
581                Err(SettingError::BadValue),
582                "{value} is not a whole number of seconds"
583            );
584        }
585    }
586
587    #[test]
588    fn an_idle_limit_outside_its_bounds_is_refused() {
589        for seconds in [0, 59, 901, 28_800] {
590            assert_eq!(
591                Settings::default().changed(&json!({ "session.idle_seconds": seconds })),
592                Err(SettingError::OutOfBounds),
593                "{seconds} s idle"
594            );
595        }
596    }
597
598    #[test]
599    fn an_absolute_limit_outside_its_bounds_is_refused() {
600        for seconds in [0, 299, 28_801, 86_400] {
601            assert_eq!(
602                Settings::default().changed(&json!({ "session.absolute_seconds": seconds })),
603                Err(SettingError::OutOfBounds),
604                "{seconds} s at most"
605            );
606        }
607    }
608
609    #[test]
610    fn an_idle_limit_above_the_absolute_one_is_refused() {
611        let body = json!({ "session.idle_seconds": 900, "session.absolute_seconds": 600 });
612        assert_eq!(
613            Settings::default().changed(&body),
614            Err(SettingError::IdleOverAbsolute),
615            "both in one change"
616        );
617        let was = Settings::stored(&rows(&[("session.absolute_seconds", "300")]));
618        assert_eq!(was, None, "stored rows hold the rule too: idle is 900");
619        let was = Settings::stored(&rows(&[
620            ("session.absolute_seconds", "300"),
621            ("session.idle_seconds", "120"),
622        ]))
623        .expect("good rows");
624        assert_eq!(
625            was.changed(&json!({ "session.idle_seconds": 301 })),
626            Err(SettingError::IdleOverAbsolute),
627            "against the absolute limit already set"
628        );
629    }
630
631    #[test]
632    fn a_change_that_is_not_an_object_is_refused() {
633        for body in [json!([]), json!("masking.reader"), json!(null), json!(7)] {
634            assert_eq!(
635                Settings::default().changed(&body),
636                Err(SettingError::BadValue),
637                "{body} is not an object of names"
638            );
639        }
640    }
641
642    #[test]
643    fn one_bad_name_refuses_the_whole_change() {
644        let body = json!({ "masking.reader": false, "masking.nobody": false });
645        assert_eq!(
646            Settings::default().changed(&body),
647            Err(SettingError::UnknownName),
648            "nothing of the change is taken"
649        );
650    }
651
652    #[test]
653    fn a_stored_row_with_an_unknown_name_is_damage() {
654        assert_eq!(
655            Settings::stored(&rows(&[("masking.operator", "true")])),
656            None,
657            "not a default"
658        );
659    }
660
661    #[test]
662    fn a_stored_value_that_does_not_read_back_is_damage() {
663        for (name, value) in [
664            ("masking.reader", "on"),
665            ("masking.reader", "TRUE"),
666            ("masking.reader", ""),
667            ("session.idle_seconds", "0300"),
668            ("session.idle_seconds", "+300"),
669            ("session.idle_seconds", "300 "),
670            ("session.idle_seconds", "59"),
671            ("session.absolute_seconds", "28801"),
672            ("session.absolute_seconds", "4294967296"),
673        ] {
674            assert_eq!(
675                Settings::stored(&rows(&[(name, value)])),
676                None,
677                "{name} = {value:?}"
678            );
679        }
680    }
681
682    #[test]
683    fn a_name_stored_twice_is_damage() {
684        assert_eq!(
685            Settings::stored(&rows(&[
686                ("masking.reader", "false"),
687                ("masking.reader", "true"),
688            ])),
689            None,
690            "one row for a name"
691        );
692    }
693
694    #[test]
695    fn a_name_in_other_letters_is_not_the_name() {
696        for name in [
697            "Masking.reader",
698            "masking.Reader",
699            " masking.reader",
700            "masking.reader ",
701            "masking.tenant_admin",
702            "session.idle_seconds\n",
703        ] {
704            assert_eq!(Name::parse(name), None, "{name:?}");
705        }
706    }
707
708    // Edge.
709
710    #[test]
711    fn an_empty_change_changes_nothing() {
712        let (now, changes) = Settings::default()
713            .changed(&json!({}))
714            .expect("an empty object is a change of nothing");
715        assert_eq!(now, Settings::default(), "as it was");
716        assert!(changes.is_empty(), "no row to write: {changes:?}");
717    }
718
719    #[test]
720    fn no_rows_are_the_defaults() {
721        assert_eq!(
722            Settings::stored(&[]),
723            Some(Settings::default()),
724            "a tenant that set nothing"
725        );
726    }
727
728    #[test]
729    fn a_null_for_a_name_never_set_removes_nothing_and_is_not_an_error() {
730        let (now, changes) = Settings::default()
731            .changed(&json!({ "masking.legal": null }))
732            .expect("a good change");
733        assert_eq!(now, Settings::default(), "as it was");
734        assert_eq!(
735            changes,
736            vec![(Name::Masking(Role::Legal), None)],
737            "the removal is still asked of the table"
738        );
739    }
740
741    #[test]
742    fn putting_the_absolute_limit_back_under_a_shorter_idle_limit_is_good() {
743        let was = Settings::stored(&rows(&[
744            ("session.absolute_seconds", "300"),
745            ("session.idle_seconds", "120"),
746        ]))
747        .expect("good rows");
748        let (now, _) = was
749            .changed(&json!({ "session.absolute_seconds": null }))
750            .expect("8 hours is above 120 s");
751        assert_eq!(
752            now.get(Name::SessionAbsolute),
753            Value::Seconds(28_800),
754            "the default"
755        );
756        assert_eq!(now.get(Name::SessionIdle), Value::Seconds(120), "kept");
757    }
758
759    #[test]
760    fn putting_the_idle_limit_back_above_a_shorter_absolute_limit_is_refused() {
761        let was = Settings::stored(&rows(&[
762            ("session.absolute_seconds", "300"),
763            ("session.idle_seconds", "120"),
764        ]))
765        .expect("good rows");
766        assert_eq!(
767            was.changed(&json!({ "session.idle_seconds": null })),
768            Err(SettingError::IdleOverAbsolute),
769            "the default idle limit, 900 s, is above 300 s"
770        );
771    }
772
773    #[test]
774    fn the_changes_come_in_the_lists_order_whatever_the_bodys_order() {
775        let body = json!({
776            "session.absolute_seconds": 3600,
777            "masking.tenant-admin": false,
778            "masking.reader": false,
779        });
780        let (_, changes) = Settings::default().changed(&body).expect("a good change");
781        let names: Vec<&str> = changes.iter().map(|(name, _)| name.as_str()).collect();
782        assert_eq!(
783            names,
784            [
785                "masking.reader",
786                "masking.tenant-admin",
787                "session.absolute_seconds"
788            ],
789            "one order for the rows and the audit target"
790        );
791    }
792
793    #[test]
794    fn a_whole_number_written_with_a_fraction_of_zero_is_not_taken() {
795        assert_eq!(
796            Settings::default().changed(&json!({ "session.idle_seconds": 300.0 })),
797            Err(SettingError::BadValue),
798            "300.0 is a float in JSON"
799        );
800    }
801
802    #[test]
803    fn a_number_past_32_bits_is_out_of_bounds_not_a_crash() {
804        assert_eq!(
805            Settings::default().changed(&json!({ "session.absolute_seconds": 4_294_967_296_u64 })),
806            Err(SettingError::OutOfBounds),
807            "a whole number, too large"
808        );
809    }
810
811    #[test]
812    fn the_bounds_are_the_ones_the_pages_state() {
813        assert_eq!(IDLE_SECONDS, 60..=900, "one minute to 15 minutes");
814        assert_eq!(ABSOLUTE_SECONDS, 300..=28_800, "5 minutes to 8 hours");
815    }
816
817    #[test]
818    fn each_error_names_itself_for_a_problem_detail() {
819        assert_eq!(
820            SettingError::UnknownName.to_string(),
821            "a name is not a setting",
822            "unknown name"
823        );
824        assert_eq!(
825            SettingError::BadValue.to_string(),
826            "a value is not of its setting's kind",
827            "bad value"
828        );
829        assert_eq!(
830            SettingError::OutOfBounds.to_string(),
831            "a limit is outside its bounds",
832            "out of bounds"
833        );
834        assert_eq!(
835            SettingError::IdleOverAbsolute.to_string(),
836            "the idle limit is above the absolute limit",
837            "idle over absolute"
838        );
839    }
840
841    #[test]
842    fn the_names_written_together_are_the_audit_target() {
843        let body = json!({ "masking.reader": false, "session.idle_seconds": null });
844        let (_, changes) = Settings::default()
845            .changed(&json!({ "masking.reader": false }))
846            .expect("a good change");
847        assert_eq!(named(&changes), "masking.reader", "one name");
848        let was = Settings::default();
849        let (_, changes) = was.changed(&body).expect("a good change");
850        assert_eq!(
851            named(&changes),
852            "masking.reader,session.idle_seconds",
853            "names only, never a value"
854        );
855        assert_eq!(named(&[]), "", "no name");
856    }
857}