Skip to main content

vault_core/
login.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The login sequence of a bundle (R36): one account made of up to four credentials, in a fixed
4//! order, whatever order the members were added in.
5//!
6//! 1. the password, 2. the 2FA code, 3. the security phrase, 4. a recovery code.
7//!
8//! This is the one place the order is decided (invariant 10): the CLI, the desktop card and the
9//! browser host all call [`login_sequence`]. A step with nothing stored is absent, not empty. The
10//! plan names entries and fields and never carries a value.
11
12use crate::type_emit::code_status;
13use serde_json::Value;
14
15/// One step of a login.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Step {
18    /// `password`, `2fa`, `phrase` or `recovery_code`.
19    pub step: &'static str,
20    pub label: &'static str,
21    pub entry_id: String,
22    pub field: &'static str,
23}
24
25/// What happens to a recovery code once it has been filled into a page.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Terminate {
28    /// Show "Mark this code as used?" after the fill (the default).
29    Ask,
30    /// Mark it used straight after the fill.
31    Auto,
32    /// Leave it for the person.
33    Never,
34}
35
36impl Terminate {
37    pub fn parse(s: &str) -> Option<Self> {
38        match s {
39            "ask" => Some(Self::Ask),
40            "auto" => Some(Self::Auto),
41            "never" => Some(Self::Never),
42            _ => None,
43        }
44    }
45
46    pub fn name(self) -> &'static str {
47        match self {
48            Self::Ask => "ask",
49            Self::Auto => "auto",
50            Self::Never => "never",
51        }
52    }
53}
54
55/// The bundle's `terminate_codes` setting; `ask` when unset or unreadable.
56pub fn terminate_mode(bundle: &Value) -> Terminate {
57    bundle
58        .get("terminate_codes")
59        .and_then(Value::as_str)
60        .and_then(Terminate::parse)
61        .unwrap_or(Terminate::Ask)
62}
63
64fn text<'a>(v: &'a Value, k: &str) -> &'a str {
65    v.get(k).and_then(Value::as_str).unwrap_or("")
66}
67
68fn kind(v: &Value) -> &str {
69    match text(v, "secretType") {
70        "" => "api_key",
71        t => t,
72    }
73}
74
75/// The ordered steps present in `bundle`, from `entries` (the whole vault's entries).
76pub fn login_sequence(entries: &[Value], bundle: &Value) -> Vec<Step> {
77    let id = text(bundle, "id");
78    if id.is_empty() {
79        return Vec::new();
80    }
81    let members: Vec<&Value> = entries
82        .iter()
83        .filter(|e| text(e, "bundle_id") == id)
84        .collect();
85    let by = |ty: &str| members.iter().copied().find(|m| kind(m) == ty);
86    let password = by("password").or_else(|| {
87        members.iter().copied().find(|m| {
88            !text(m, "api_key").is_empty()
89                && !matches!(kind(m), "security_phrase" | "recovery_codes")
90        })
91    });
92    let mut out = Vec::new();
93    if let Some(p) = password {
94        if !text(p, "api_key").is_empty() {
95            out.push(Step {
96                step: "password",
97                label: "Password",
98                entry_id: text(p, "id").into(),
99                field: "api_key",
100            });
101        }
102    }
103    let seed = password
104        .filter(|p| !text(p, "totp_secret").is_empty())
105        .or_else(|| {
106            members
107                .iter()
108                .copied()
109                .find(|m| !text(m, "totp_secret").is_empty())
110        });
111    if let Some(s) = seed {
112        out.push(Step {
113            step: "2fa",
114            label: "2FA code",
115            entry_id: text(s, "id").into(),
116            field: "totp_secret",
117        });
118    }
119    if let Some(ph) = by("security_phrase").filter(|m| !text(m, "api_key").is_empty()) {
120        out.push(Step {
121            step: "phrase",
122            label: "Security phrase",
123            entry_id: text(ph, "id").into(),
124            field: "api_key",
125        });
126    }
127    // A dedicated recovery_codes member first, else any member that carries codes (the password's own).
128    let has_codes = |m: &&Value| code_status(m).remaining > 0;
129    let rc = members
130        .iter()
131        .copied()
132        .find(|m| kind(m) == "recovery_codes" && has_codes(m))
133        .or_else(|| members.iter().copied().find(|m| has_codes(m)));
134    if let Some(rc) = rc {
135        out.push(Step {
136            step: "recovery_code",
137            label: "Recovery code",
138            entry_id: text(rc, "id").into(),
139            field: "codes",
140        });
141    }
142    out
143}
144
145#[cfg(test)]
146mod tests {
147    use super::*;
148    use serde_json::json;
149
150    fn member(id: &str, ty: &str, extra: Value) -> Value {
151        let mut m = json!({ "id": id, "bundle_id": "b1", "secretType": ty });
152        for (k, v) in extra.as_object().unwrap() {
153            m[k] = v.clone();
154        }
155        m
156    }
157
158    fn all() -> Vec<Value> {
159        vec![
160            member(
161                "rc",
162                "recovery_codes",
163                json!({ "extra_vars": [{ "key": "codes", "value": "aaaa-1111\nbbbb-2222" }] }),
164            ),
165            member("ph", "security_phrase", json!({ "api_key": "blue cat" })),
166            member(
167                "pw",
168                "password",
169                json!({ "api_key": "pw", "totp_secret": "JBSWY3DP" }),
170            ),
171            json!({ "id": "other", "bundle_id": "b2", "secretType": "password", "api_key": "x" }),
172        ]
173    }
174
175    #[test]
176    fn the_order_is_fixed_whatever_order_the_members_were_added_in() {
177        let steps = login_sequence(&all(), &json!({ "id": "b1" }));
178        let names: Vec<_> = steps.iter().map(|s| s.step).collect();
179        assert_eq!(names, ["password", "2fa", "phrase", "recovery_code"]);
180        assert_eq!(steps[0].entry_id, "pw");
181        assert_eq!(steps[3].field, "codes");
182    }
183
184    #[test]
185    fn a_step_with_nothing_stored_is_absent_and_spent_codes_drop_the_last_step() {
186        let mut e = all();
187        e.remove(1); // no phrase
188        e[0]["extra_vars"][0]["value"] = json!("aaaa-1111\tUSED 2026-01-01");
189        e[1].as_object_mut().unwrap().remove("totp_secret");
190        let names: Vec<_> = login_sequence(&e, &json!({ "id": "b1" }))
191            .iter()
192            .map(|s| s.step)
193            .collect();
194        assert_eq!(names, ["password"]);
195        assert!(login_sequence(&e, &json!({})).is_empty());
196    }
197
198    #[test]
199    fn a_login_without_a_password_type_uses_the_first_member_that_holds_a_value() {
200        let e = vec![member(
201            "t",
202            "api_key",
203            json!({ "api_key": "tok", "totp_secret": "AAAA" }),
204        )];
205        let steps = login_sequence(&e, &json!({ "id": "b1" }));
206        assert_eq!(steps.len(), 2);
207        assert_eq!(steps[1].entry_id, "t");
208        // A seed on a different member still gives step 2.
209        let e = vec![
210            member("p", "password", json!({ "api_key": "pw" })),
211            member("o", "api_key", json!({ "totp_secret": "AAAA" })),
212        ];
213        assert_eq!(login_sequence(&e, &json!({ "id": "b1" }))[1].entry_id, "o");
214    }
215
216    #[test]
217    fn a_password_that_carries_its_own_codes_gives_the_recovery_step() {
218        let e = vec![member(
219            "p",
220            "password",
221            json!({ "api_key": "pw", "extra_vars": [{ "key": "codes", "value": "aaaa-1111" }] }),
222        )];
223        let steps = login_sequence(&e, &json!({ "id": "b1" }));
224        let names: Vec<_> = steps.iter().map(|s| s.step).collect();
225        assert_eq!(names, ["password", "recovery_code"]);
226        assert_eq!(steps[1].entry_id, "p");
227        // A dedicated recovery_codes member wins over the password's own.
228        let mut e = e;
229        e.push(member(
230            "rc",
231            "recovery_codes",
232            json!({ "extra_vars": [{ "key": "codes", "value": "bbbb-2222" }] }),
233        ));
234        assert_eq!(login_sequence(&e, &json!({ "id": "b1" }))[1].entry_id, "rc");
235    }
236
237    #[test]
238    fn terminate_modes_parse_and_default_to_ask() {
239        assert_eq!(terminate_mode(&json!({})), Terminate::Ask);
240        assert_eq!(
241            terminate_mode(&json!({ "terminate_codes": "auto" })),
242            Terminate::Auto
243        );
244        assert_eq!(
245            terminate_mode(&json!({ "terminate_codes": "never" })).name(),
246            "never"
247        );
248        assert_eq!(
249            terminate_mode(&json!({ "terminate_codes": "bogus" })),
250            Terminate::Ask
251        );
252        assert_eq!(Terminate::parse("ask").unwrap().name(), "ask");
253        assert!(Terminate::parse("x").is_none());
254    }
255
256    #[test]
257    fn a_plan_never_carries_a_value() {
258        let dump = format!("{:?}", login_sequence(&all(), &json!({ "id": "b1" })));
259        for secret in ["JBSWY3DP", "blue cat", "aaaa-1111"] {
260            assert!(!dump.contains(secret));
261        }
262    }
263}