logins/
login.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5//  N.B. if you're making a documentation change here, you might also want to make it in:
6//
7//    * The API docs in ../ios/Logins/LoginRecord.swift
8//    * The API docs in ../android/src/main/java/mozilla/appservices/logins/ServerPassword.kt
9//    * The android-components docs at
10//      https://github.com/mozilla-mobile/android-components/tree/master/components/service/sync-logins
11//
12//  We'll figure out a more scalable approach to maintaining all those docs at some point...
13
14//! # Login Structs
15//!
16//! This module defines a number of core structs for Logins. They are:
17//! * [`LoginEntry`] A login entry by the user.  This includes the username/password, the site it
18//!   was submitted to, etc.  [`LoginEntry`] does not store data specific to a DB record.
19//! * [`Login`] - A [`LoginEntry`] plus DB record information.  This includes the GUID and metadata
20//!   like time_last_used.
21//! * [`EncryptedLogin`] -- A Login above with the username/password data encrypted.
22//! * [`LoginFields`], [`SecureLoginFields`], [`LoginMeta`] -- These group the common fields in the
23//!   structs above.
24//!
25//! Why so many structs for similar data?  Consider some common use cases in a hypothetical browser
26//! (currently no browsers act exactly like this, although Fenix/android-components comes close):
27//!
28//! - User visits a page with a login form.
29//!   - We inform the user if there are saved logins that can be autofilled.  We use the
30//!     `LoginDb.get_by_base_domain()` which returns a `Vec<EncryptedLogin>`.  We don't decrypt the
31//!     logins because we want to avoid requiring the encryption key at this point, which would
32//!     force the user to authenticate.  Note: this is aspirational at this point, no actual
33//!     implementations follow this flow.  Still, we want application-services to support it.
34//!   - If the user chooses to autofill, we decrypt the logins into a `Vec<Login>`.  We need to
35//!     decrypt at this point to display the username and autofill the password if they select one.
36//!   - When the user selects a login, we can use the already decrypted data from `Login` to fill
37//!     in the form.
38//! - User chooses to save a login for autofilling later.
39//!    - We present the user with a dialog that:
40//!       - Displays a header that differentiates between different types of save: adding a new
41//!         login, updating an existing login, filling in a blank username, etc.
42//!       - Allows the user to tweak the username, in case we failed to detect the form field
43//!         correctly.  This may affect which header should be shown.
44//!    - Here we use `find_login_to_update()` which returns an `Option<Login>`.  Returning a login
45//!      that has decrypted data avoids forcing the consumer code to decrypt the username again.
46//!
47//! # Login
48//! This has the complete set of data about a login. Very closely related is the
49//! "sync payload", defined in sync/payload.rs, which handles all aspects of the JSON serialization.
50//! It contains the following fields:
51//! - `meta`: A [`LoginMeta`] struct.
52//! - fields: A [`LoginFields`] struct.
53//! - sec_fields: A [`SecureLoginFields`] struct.
54//!
55//! # LoginEntry
56//! The struct used to add or update logins. This has the plain-text version of the fields that are
57//! stored encrypted, so almost all uses of an LoginEntry struct will also require the
58//! encryption key to be known and passed in.    [LoginDB] methods that save data typically input
59//! [LoginEntry] instances.  This allows the DB code to handle dupe-checking issues like
60//! determining which login record should be updated for a newly submitted [LoginEntry].
61//! It contains the following fields:
62//! - fields: A [`LoginFields`] struct.
63//! - sec_fields: A [`SecureLoginFields`] struct.
64//!
65//! # EncryptedLogin
66//! Encrypted version of [`Login`].  [LoginDB] methods that return data typically return [EncryptedLogin]
67//! this allows deferring decryption, and therefore user authentication, until the secure data is needed.
68//! It contains the following fields
69//! - `meta`: A [`LoginMeta`] struct.
70//! - `fields`: A [`LoginFields`] struct.
71//! - `sec_fields`: The secure fields as an encrypted string
72//!
73//! # SecureLoginFields
74//! The struct used to hold the fields which are stored encrypted. It contains:
75//! - username: A string.
76//! - password: A string.
77//!
78//! # LoginFields
79//!
80//! The core set of fields, use by both [`Login`] and [`LoginEntry`]
81//! It contains the following fields:
82//!
83//! - `origin`:  The origin at which this login can be used, as a string.
84//!
85//!   The login should only be used on sites that match this origin (for whatever definition
86//!   of "matches" makes sense at the application level, e.g. eTLD+1 matching).
87//!   This field is required, must be a valid origin in punycode format, and must not be
88//!   set to the empty string.
89//!
90//!   Examples of valid `origin` values include:
91//!   - "https://site.com"
92//!   - "http://site.com:1234"
93//!   - "ftp://ftp.site.com"
94//!   - "moz-proxy://127.0.0.1:8888"
95//!   - "chrome://MyLegacyExtension"
96//!   - "file://"
97//!   - "https://\[::1\]"
98//!
99//!   If invalid data is received in this field (either from the application, or via sync)
100//!   then the logins store will attempt to coerce it into valid data by:
101//!   - truncating full URLs to just their origin component, if it is not an opaque origin
102//!   - converting values with non-ascii characters into punycode
103//!
104//!   **XXX TODO:**
105//!   - Add a field with the original unicode versions of the URLs instead of punycode?
106//!
107//! - `sec_fields`: The `username` and `password` for the site, stored as a encrypted JSON
108//!   representation of an `SecureLoginFields`.
109//!
110//!   This field is required and usually encrypted.  There are two different value types:
111//!   - Plaintext empty string: Used for deleted records
112//!   - Encrypted value: The credentials associated with the login.
113//!
114//! - `http_realm`:  The challenge string for HTTP Basic authentication, if any.
115//!
116//!   If present, the login should only be used in response to a HTTP Basic Auth
117//!   challenge that specifies a matching realm. For legacy reasons this string may not
118//!   contain null bytes, carriage returns or newlines.
119//!
120//!   If this field is set to the empty string, this indicates a wildcard match on realm.
121//!
122//!   This field must not be present if `form_action_origin` is set, since they indicate different types
123//!   of login (HTTP-Auth based versus form-based). Exactly one of `http_realm` and `form_action_origin`
124//!   must be present.
125//!
126//! - `form_action_origin`:  The target origin of forms in which this login can be used, if any, as a string.
127//!
128//!   If present, the login should only be used in forms whose target submission URL matches this origin.
129//!   This field must be a valid origin or one of the following special cases:
130//!   - An empty string, which is a wildcard match for any origin.
131//!   - The single character ".", which is equivalent to the empty string
132//!   - The string "javascript:", which matches any form with javascript target URL.
133//!
134//!   This field must not be present if `http_realm` is set, since they indicate different types of login
135//!   (HTTP-Auth based versus form-based). Exactly one of `http_realm` and `form_action_origin` must be present.
136//!
137//!   If invalid data is received in this field (either from the application, or via sync) then the
138//!   logins store will attempt to coerce it into valid data by:
139//!   - truncating full URLs to just their origin component
140//!   - converting origins with non-ascii characters into punycode
141//!   - replacing invalid values with null if a valid 'http_realm' field is present
142//!
143//! - `username_field`:  The name of the form field into which the 'username' should be filled, if any.
144//!
145//!   This value is stored if provided by the application, but does not imply any restrictions on
146//!   how the login may be used in practice. For legacy reasons this string may not contain null
147//!   bytes, carriage returns or newlines. This field must be empty unless `form_action_origin` is set.
148//!
149//!   If invalid data is received in this field (either from the application, or via sync)
150//!   then the logins store will attempt to coerce it into valid data by:
151//!   - setting to the empty string if 'form_action_origin' is not present
152//!
153//! - `password_field`:  The name of the form field into which the 'password' should be filled, if any.
154//!
155//!   This value is stored if provided by the application, but does not imply any restrictions on
156//!   how the login may be used in practice. For legacy reasons this string may not contain null
157//!   bytes, carriage returns or newlines. This field must be empty unless `form_action_origin` is set.
158//!
159//!   If invalid data is received in this field (either from the application, or via sync)
160//!   then the logins store will attempt to coerce it into valid data by:
161//!   - setting to the empty string if 'form_action_origin' is not present
162//!
163//! # LoginMeta
164//!
165//! This contains data relating to the login database record -- both on the local instance and
166//! synced to other browsers.
167//! It contains the following fields:
168//! - `id`:  A unique string identifier for this record.
169//!
170//!   Consumers may assume that `id` contains only "safe" ASCII characters but should otherwise
171//!   treat this it as an opaque identifier. These are generated as needed.
172//!
173//! - `timesUsed`:  A lower bound on the number of times the password from this record has been used, as an integer.
174//!
175//!   Applications should use the `touch()` method of the logins store to indicate when a password
176//!   has been used, and should ensure that they only count uses of the actual `password` field
177//!   (so for example, copying the `password` field to the clipboard should count as a "use", but
178//!   copying just the `username` field should not).
179//!
180//!   This number may not record uses that occurred on other devices, since some legacy
181//!   sync clients do not record this information. It may be zero for records obtained
182//!   via sync that have never been used locally.
183//!
184//!   When merging duplicate records, the two usage counts are summed.
185//!
186//!   This field is managed internally by the logins store by default and does not need to
187//!   be set explicitly, although any application-provided value will be preserved when creating
188//!   a new record.
189//!
190//!   If invalid data is received in this field (either from the application, or via sync)
191//!   then the logins store will attempt to coerce it into valid data by:
192//!   - replacing missing or negative values with 0
193//!
194//!   **XXX TODO:**
195//!   - test that we prevent this counter from moving backwards.
196//!   - test fixups of missing or negative values
197//!   - test that we correctly merge dupes
198//!
199//! - `time_created`: An upper bound on the time of creation of this login, in integer milliseconds from the unix epoch.
200//!
201//!   This is an upper bound because some legacy sync clients do not record this information.
202//!
203//!   Note that this field is typically a timestamp taken from the local machine clock, so it
204//!   may be wildly inaccurate if the client does not have an accurate clock.
205//!
206//!   This field is managed internally by the logins store by default and does not need to
207//!   be set explicitly, although any application-provided value will be preserved when creating
208//!   a new record.
209//!
210//!   When merging duplicate records, the smallest non-zero value is taken.
211//!
212//!   If invalid data is received in this field (either from the application, or via sync)
213//!   then the logins store will attempt to coerce it into valid data by:
214//!   - replacing missing or negative values with the current time
215//!
216//!   **XXX TODO:**
217//!   - test that we prevent this timestamp from moving backwards.
218//!   - test fixups of missing or negative values
219//!   - test that we correctly merge dupes
220//!
221//! - `time_last_used`: A lower bound on the time of last use of this login, in integer milliseconds from the unix epoch.
222//!
223//!   This is a lower bound because some legacy sync clients do not record this information;
224//!   in that case newer clients set `timeLastUsed` when they use the record for the first time.
225//!
226//!   Note that this field is typically a timestamp taken from the local machine clock, so it
227//!   may be wildly inaccurate if the client does not have an accurate clock.
228//!
229//!   This field is managed internally by the logins store by default and does not need to
230//!   be set explicitly, although any application-provided value will be preserved when creating
231//!   a new record.
232//!
233//!   When merging duplicate records, the largest non-zero value is taken.
234//!
235//!   If invalid data is received in this field (either from the application, or via sync)
236//!   then the logins store will attempt to coerce it into valid data by:
237//!   - removing negative values
238//!
239//!   **XXX TODO:**
240//!   - test that we prevent this timestamp from moving backwards.
241//!   - test fixups of missing or negative values
242//!   - test that we correctly merge dupes
243//!
244//! - `time_password_changed`: A lower bound on the time that the `password` field was last changed, in integer
245//!   milliseconds from the unix epoch.
246//!
247//!   Changes to other fields (such as `username`) are not reflected in this timestamp.
248//!   This is a lower bound because some legacy sync clients do not record this information;
249//!   in that case newer clients set `time_password_changed` when they change the `password` field.
250//!
251//!   Note that this field is typically a timestamp taken from the local machine clock, so it
252//!   may be wildly inaccurate if the client does not have an accurate clock.
253//!
254//!   This field is managed internally by the logins store by default and does not need to
255//!   be set explicitly, although any application-provided value will be preserved when creating
256//!   a new record.
257//!
258//!   When merging duplicate records, the largest non-zero value is taken.
259//!
260//!   If invalid data is received in this field (either from the application, or via sync)
261//!   then the logins store will attempt to coerce it into valid data by:
262//!   - removing negative values
263//!
264//!   **XXX TODO:**
265//!   - test that we prevent this timestamp from moving backwards.
266//!   - test that we don't set this for changes to other fields.
267//!   - test that we correctly merge dupes
268//!
269//!
270//! In order to deal with data from legacy clients in a robust way, it is necessary to be able to build
271//! and manipulate all these `Login` structs that contain invalid data.  The non-encrypted structs
272//! implement the `ValidateAndFixup` trait, providing the following methods which can be used by
273//! callers to ensure that they're only working with valid records:
274//!
275//! - `Login::check_valid()`:    Checks validity of a login record, returning `()` if it is valid
276//!   or an error if it is not.
277//!
278//! - `Login::fixup()`:   Returns either the existing login if it is valid, a clone with invalid fields
279//!   fixed up if it was safe to do so, or an error if the login is irreparably invalid.
280
281use crate::{encryption::EncryptorDecryptor, error::*};
282use rusqlite::Row;
283use serde_derive::*;
284use sync_guid::Guid;
285use url::Url;
286
287// LoginEntry fields that are stored in cleartext
288#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
289pub struct LoginFields {
290    pub origin: String,
291    pub form_action_origin: Option<String>,
292    pub http_realm: Option<String>,
293    pub username_field: String,
294    pub password_field: String,
295}
296
297/// LoginEntry fields that are stored encrypted
298#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize, Default)]
299pub struct SecureLoginFields {
300    // - Username cannot be null, use the empty string instead
301    // - Password can't be empty or null (enforced in the ValidateAndFixup code)
302    //
303    // This matches the desktop behavior:
304    // https://searchfox.org/mozilla-central/rev/d3683dbb252506400c71256ef3994cdbdfb71ada/toolkit/components/passwordmgr/LoginManager.jsm#260-267
305
306    // Because we store the json version of this in the DB, and that's the only place the json
307    // is used, we rename the fields to short names, just to reduce the overhead in the DB.
308    #[serde(rename = "u")]
309    pub username: String,
310    #[serde(rename = "p")]
311    pub password: String,
312}
313
314impl SecureLoginFields {
315    pub fn encrypt(&self, encdec: &dyn EncryptorDecryptor, login_id: &str) -> Result<String> {
316        let string = serde_json::to_string(&self)?;
317        let cipherbytes = encdec
318            .encrypt(string.as_bytes().into())
319            .map_err(|e| Error::EncryptionFailed(format!("{e} (encrypting {login_id})")))?;
320        let ciphertext = std::str::from_utf8(&cipherbytes).map_err(|e| {
321            Error::EncryptionFailed(format!("{e} (encrypting {login_id}: data not utf8)"))
322        })?;
323        Ok(ciphertext.to_owned())
324    }
325
326    pub fn decrypt(
327        ciphertext: &str,
328        encdec: &dyn EncryptorDecryptor,
329        login_id: &str,
330    ) -> Result<Self> {
331        let jsonbytes = encdec
332            .decrypt(ciphertext.as_bytes().into())
333            .map_err(|e| Error::DecryptionFailed(format!("{e} (decrypting {login_id})")))?;
334        let json =
335            std::str::from_utf8(&jsonbytes).map_err(|e| Error::DecryptionFailed(e.to_string()))?;
336        Ok(serde_json::from_str(json)?)
337    }
338}
339
340/// Login data specific to database records
341#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
342pub struct LoginMeta {
343    pub id: String,
344    pub time_created: i64,
345    pub time_password_changed: i64,
346    pub time_last_used: i64,
347    pub times_used: i64,
348}
349
350/// A login together with meta fields, handed over to the store API; ie a login persisted
351/// elsewhere, useful for migrations
352pub struct LoginEntryWithMeta {
353    pub entry: LoginEntry,
354    pub meta: LoginMeta,
355}
356
357/// A bulk insert result entry, returned by `add_many` and `add_many_with_records`
358pub enum BulkResultEntry {
359    Success { login: Login },
360    Error { message: String },
361}
362
363/// A login handed over to the store API; ie a login not yet persisted
364#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
365pub struct LoginEntry {
366    // login fields
367    pub origin: String,
368    pub form_action_origin: Option<String>,
369    pub http_realm: Option<String>,
370    pub username_field: String,
371    pub password_field: String,
372
373    // secure fields
374    pub username: String,
375    pub password: String,
376}
377
378impl LoginEntry {
379    pub fn new(fields: LoginFields, sec_fields: SecureLoginFields) -> Self {
380        Self {
381            origin: fields.origin,
382            form_action_origin: fields.form_action_origin,
383            http_realm: fields.http_realm,
384            username_field: fields.username_field,
385            password_field: fields.password_field,
386
387            username: sec_fields.username,
388            password: sec_fields.password,
389        }
390    }
391    /// Internal helper for validation and fixups of an "origin" stored as
392    /// a string.
393    fn validate_and_fixup_origin(origin: &str) -> Result<Option<String>> {
394        // Check we can parse the origin, then use the normalized version of it.
395        match Url::parse(origin) {
396            Ok(mut u) => {
397                // Presumably this is a faster path than always setting?
398                if u.path() != "/"
399                    || u.fragment().is_some()
400                    || u.query().is_some()
401                    || u.username() != "/"
402                    || u.password().is_some()
403                {
404                    // Not identical - we only want the origin part, so kill
405                    // any other parts which may exist.
406                    // But first special case `file://` URLs which always
407                    // resolve to `file://`
408                    if u.scheme() == "file" {
409                        return Ok(if origin == "file://" {
410                            None
411                        } else {
412                            Some("file://".into())
413                        });
414                    }
415                    u.set_path("");
416                    u.set_fragment(None);
417                    u.set_query(None);
418                    let _ = u.set_username("");
419                    let _ = u.set_password(None);
420                    let mut href = String::from(u);
421                    // We always store without the trailing "/" which Urls have.
422                    if href.ends_with('/') {
423                        href.pop().expect("url must have a length");
424                    }
425                    if origin != href {
426                        // Needs to be fixed up.
427                        return Ok(Some(href));
428                    }
429                }
430                Ok(None)
431            }
432            Err(e) => {
433                breadcrumb!(
434                    "Error parsing login origin: {e:?} ({})",
435                    error_support::redact_url(origin)
436                );
437                // We can't fixup completely invalid records, so always throw.
438                Err(InvalidLogin::IllegalOrigin.into())
439            }
440        }
441    }
442}
443
444/// A login handed over from the store API, which has been persisted and contains persistence
445/// information such as id and time stamps
446#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
447pub struct Login {
448    // meta fields
449    pub id: String,
450    pub time_created: i64,
451    pub time_password_changed: i64,
452    pub time_last_used: i64,
453    pub times_used: i64,
454
455    // login fields
456    pub origin: String,
457    pub form_action_origin: Option<String>,
458    pub http_realm: Option<String>,
459    pub username_field: String,
460    pub password_field: String,
461
462    // secure fields
463    pub username: String,
464    pub password: String,
465}
466
467impl Login {
468    pub fn new(meta: LoginMeta, fields: LoginFields, sec_fields: SecureLoginFields) -> Self {
469        Self {
470            id: meta.id,
471            time_created: meta.time_created,
472            time_password_changed: meta.time_password_changed,
473            time_last_used: meta.time_last_used,
474            times_used: meta.times_used,
475
476            origin: fields.origin,
477            form_action_origin: fields.form_action_origin,
478            http_realm: fields.http_realm,
479            username_field: fields.username_field,
480            password_field: fields.password_field,
481
482            username: sec_fields.username,
483            password: sec_fields.password,
484        }
485    }
486
487    #[inline]
488    pub fn guid(&self) -> Guid {
489        Guid::from_string(self.id.clone())
490    }
491
492    pub fn entry(&self) -> LoginEntry {
493        LoginEntry {
494            origin: self.origin.clone(),
495            form_action_origin: self.form_action_origin.clone(),
496            http_realm: self.http_realm.clone(),
497            username_field: self.username_field.clone(),
498            password_field: self.password_field.clone(),
499
500            username: self.username.clone(),
501            password: self.password.clone(),
502        }
503    }
504
505    pub fn encrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<EncryptedLogin> {
506        let sec_fields = SecureLoginFields {
507            username: self.username,
508            password: self.password,
509        }
510        .encrypt(encdec, &self.id)?;
511        Ok(EncryptedLogin {
512            meta: LoginMeta {
513                id: self.id,
514                time_created: self.time_created,
515                time_password_changed: self.time_password_changed,
516                time_last_used: self.time_last_used,
517                times_used: self.times_used,
518            },
519            fields: LoginFields {
520                origin: self.origin,
521                form_action_origin: self.form_action_origin,
522                http_realm: self.http_realm,
523                username_field: self.username_field,
524                password_field: self.password_field,
525            },
526            sec_fields,
527        })
528    }
529}
530
531/// A login stored in the database
532#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
533pub struct EncryptedLogin {
534    pub meta: LoginMeta,
535    pub fields: LoginFields,
536    pub sec_fields: String,
537}
538
539impl EncryptedLogin {
540    #[inline]
541    pub fn guid(&self) -> Guid {
542        Guid::from_string(self.meta.id.clone())
543    }
544
545    // TODO: Remove this: https://github.com/mozilla/application-services/issues/4185
546    #[inline]
547    pub fn guid_str(&self) -> &str {
548        &self.meta.id
549    }
550
551    pub fn decrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<Login> {
552        let sec_fields = self.decrypt_fields(encdec)?;
553        Ok(Login::new(self.meta, self.fields, sec_fields))
554    }
555
556    pub fn decrypt_fields(&self, encdec: &dyn EncryptorDecryptor) -> Result<SecureLoginFields> {
557        SecureLoginFields::decrypt(&self.sec_fields, encdec, &self.meta.id)
558    }
559
560    pub(crate) fn from_row(row: &Row<'_>) -> Result<EncryptedLogin> {
561        let login = EncryptedLogin {
562            meta: LoginMeta {
563                id: row.get("guid")?,
564                time_created: row.get("timeCreated")?,
565                // Might be null
566                time_last_used: row
567                    .get::<_, Option<i64>>("timeLastUsed")?
568                    .unwrap_or_default(),
569
570                time_password_changed: row.get("timePasswordChanged")?,
571                times_used: row.get("timesUsed")?,
572            },
573            fields: LoginFields {
574                origin: row.get("origin")?,
575                http_realm: row.get("httpRealm")?,
576
577                form_action_origin: row.get("formActionOrigin")?,
578
579                username_field: string_or_default(row, "usernameField")?,
580                password_field: string_or_default(row, "passwordField")?,
581            },
582            sec_fields: row.get("secFields")?,
583        };
584        // XXX - we used to perform a fixup here, but that seems heavy-handed
585        // and difficult - we now only do that on add/insert when we have the
586        // encryption key.
587        Ok(login)
588    }
589}
590
591fn string_or_default(row: &Row<'_>, col: &str) -> Result<String> {
592    Ok(row.get::<_, Option<String>>(col)?.unwrap_or_default())
593}
594
595pub trait ValidateAndFixup {
596    // Our validate and fixup functions.
597    fn check_valid(&self) -> Result<()>
598    where
599        Self: Sized,
600    {
601        self.validate_and_fixup(false)?;
602        Ok(())
603    }
604
605    fn fixup(self) -> Result<Self>
606    where
607        Self: Sized,
608    {
609        match self.maybe_fixup()? {
610            None => Ok(self),
611            Some(login) => Ok(login),
612        }
613    }
614
615    fn maybe_fixup(&self) -> Result<Option<Self>>
616    where
617        Self: Sized,
618    {
619        self.validate_and_fixup(true)
620    }
621
622    // validates, and optionally fixes, a struct. If fixup is false and there is a validation
623    // issue, an `Err` is returned. If fixup is true and a problem was fixed, and `Ok(Some<Self>)`
624    // is returned with the fixed version. If there was no validation problem, `Ok(None)` is
625    // returned.
626    fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>>
627    where
628        Self: Sized;
629}
630
631impl ValidateAndFixup for LoginEntry {
632    fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>> {
633        // XXX TODO: we've definitely got more validation and fixups to add here!
634
635        let mut maybe_fixed = None;
636
637        /// A little helper to magic a Some(self.clone()) into existence when needed.
638        macro_rules! get_fixed_or_throw {
639            ($err:expr) => {
640                // This is a block expression returning a local variable,
641                // entirely so we can give it an explicit type declaration.
642                {
643                    if !fixup {
644                        return Err($err.into());
645                    }
646                    warn!("Fixing login record {:?}", $err);
647                    let fixed: Result<&mut Self> =
648                        Ok(maybe_fixed.get_or_insert_with(|| self.clone()));
649                    fixed
650                }
651            };
652        }
653
654        if self.origin.is_empty() {
655            return Err(InvalidLogin::EmptyOrigin.into());
656        }
657
658        if self.form_action_origin.is_some() && self.http_realm.is_some() {
659            get_fixed_or_throw!(InvalidLogin::BothTargets)?.http_realm = None;
660        }
661
662        if self.form_action_origin.is_none() && self.http_realm.is_none() {
663            return Err(InvalidLogin::NoTarget.into());
664        }
665
666        let form_action_origin = self.form_action_origin.clone().unwrap_or_default();
667        let http_realm = maybe_fixed
668            .as_ref()
669            .unwrap_or(self)
670            .http_realm
671            .clone()
672            .unwrap_or_default();
673
674        let field_data = [
675            ("form_action_origin", &form_action_origin),
676            ("http_realm", &http_realm),
677            ("origin", &self.origin),
678            ("username_field", &self.username_field),
679            ("password_field", &self.password_field),
680        ];
681
682        for (field_name, field_value) in &field_data {
683            // Nuls are invalid.
684            if field_value.contains('\0') {
685                return Err(InvalidLogin::IllegalFieldValue {
686                    field_info: format!("`{}` contains Nul", field_name),
687                }
688                .into());
689            }
690
691            // Newlines are invalid in Desktop for all the fields here.
692            if field_value.contains('\n') || field_value.contains('\r') {
693                return Err(InvalidLogin::IllegalFieldValue {
694                    field_info: format!("`{}` contains newline", field_name),
695                }
696                .into());
697            }
698        }
699
700        // Desktop doesn't like fields with the below patterns
701        if self.username_field == "." {
702            return Err(InvalidLogin::IllegalFieldValue {
703                field_info: "`username_field` is a period".into(),
704            }
705            .into());
706        }
707
708        // Check we can parse the origin, then use the normalized version of it.
709        if let Some(fixed) = Self::validate_and_fixup_origin(&self.origin)? {
710            get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
711                field_info: "Origin is not normalized".into()
712            })?
713            .origin = fixed;
714        }
715
716        match &maybe_fixed.as_ref().unwrap_or(self).form_action_origin {
717            None => {
718                if !self.username_field.is_empty() {
719                    get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
720                        field_info: "username_field must be empty when form_action_origin is null"
721                            .into()
722                    })?
723                    .username_field
724                    .clear();
725                }
726                if !self.password_field.is_empty() {
727                    get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
728                        field_info: "password_field must be empty when form_action_origin is null"
729                            .into()
730                    })?
731                    .password_field
732                    .clear();
733                }
734            }
735            Some(href) => {
736                // "", ".", and "javascript:" are special cases documented at the top of this file.
737                if href == "." {
738                    // A bit of a special case - if we are being asked to fixup, we replace
739                    // "." with an empty string - but if not fixing up we don't complain.
740                    if fixup {
741                        maybe_fixed
742                            .get_or_insert_with(|| self.clone())
743                            .form_action_origin = Some("".into());
744                    }
745                } else if !href.is_empty() && href != "javascript:" {
746                    if let Some(fixed) = Self::validate_and_fixup_origin(href)? {
747                        get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
748                            field_info: "form_action_origin is not normalized".into()
749                        })?
750                        .form_action_origin = Some(fixed);
751                    }
752                }
753            }
754        }
755
756        // secure fields
757        //
758        // \r\n chars are valid in desktop for some reason, so we allow them here too.
759        if self.username.contains('\0') {
760            return Err(InvalidLogin::IllegalFieldValue {
761                field_info: "`username` contains Nul".into(),
762            }
763            .into());
764        }
765        if self.password.is_empty() {
766            return Err(InvalidLogin::EmptyPassword.into());
767        }
768        if self.password.contains('\0') {
769            return Err(InvalidLogin::IllegalFieldValue {
770                field_info: "`password` contains Nul".into(),
771            }
772            .into());
773        }
774
775        Ok(maybe_fixed)
776    }
777}
778
779#[cfg(test)]
780pub mod test_utils {
781    use super::*;
782    use crate::encryption::test_utils::encrypt_struct;
783
784    // Factory function to make a new login
785    //
786    // It uses the guid to create a unique origin/form_action_origin
787    pub fn enc_login(id: &str, password: &str) -> EncryptedLogin {
788        let sec_fields = SecureLoginFields {
789            username: "user".to_string(),
790            password: password.to_string(),
791        };
792        EncryptedLogin {
793            meta: LoginMeta {
794                id: id.to_string(),
795                ..Default::default()
796            },
797            fields: LoginFields {
798                form_action_origin: Some(format!("https://{}.example.com", id)),
799                origin: format!("https://{}.example.com", id),
800                ..Default::default()
801            },
802            // TODO: fixme
803            sec_fields: encrypt_struct(&sec_fields),
804        }
805    }
806}
807
808#[cfg(test)]
809mod tests {
810    use super::*;
811
812    #[test]
813    fn test_url_fixups() -> Result<()> {
814        // Start with URLs which are all valid and already normalized.
815        for input in &[
816            // The list of valid origins documented at the top of this file.
817            "https://site.com",
818            "http://site.com:1234",
819            "ftp://ftp.site.com",
820            "moz-proxy://127.0.0.1:8888",
821            "chrome://MyLegacyExtension",
822            "file://",
823            "https://[::1]",
824        ] {
825            assert_eq!(LoginEntry::validate_and_fixup_origin(input)?, None);
826        }
827
828        // And URLs which get normalized.
829        for (input, output) in &[
830            ("https://site.com/", "https://site.com"),
831            ("http://site.com:1234/", "http://site.com:1234"),
832            ("http://example.com/foo?query=wtf#bar", "http://example.com"),
833            ("http://example.com/foo#bar", "http://example.com"),
834            (
835                "http://username:password@example.com/",
836                "http://example.com",
837            ),
838            ("http://😍.com/", "http://xn--r28h.com"),
839            ("https://[0:0:0:0:0:0:0:1]", "https://[::1]"),
840            // All `file://` URLs normalize to exactly `file://`. See #2384 for
841            // why we might consider changing that later.
842            ("file:///", "file://"),
843            ("file://foo/bar", "file://"),
844            ("file://foo/bar/", "file://"),
845            ("moz-proxy://127.0.0.1:8888/", "moz-proxy://127.0.0.1:8888"),
846            (
847                "moz-proxy://127.0.0.1:8888/foo",
848                "moz-proxy://127.0.0.1:8888",
849            ),
850            ("chrome://MyLegacyExtension/", "chrome://MyLegacyExtension"),
851            (
852                "chrome://MyLegacyExtension/foo",
853                "chrome://MyLegacyExtension",
854            ),
855        ] {
856            assert_eq!(
857                LoginEntry::validate_and_fixup_origin(input)?,
858                Some((*output).into())
859            );
860        }
861        Ok(())
862    }
863
864    #[test]
865    fn test_check_valid() {
866        #[derive(Debug, Clone)]
867        struct TestCase {
868            login: LoginEntry,
869            should_err: bool,
870            expected_err: &'static str,
871        }
872
873        let valid_login = LoginEntry {
874            origin: "https://www.example.com".into(),
875            http_realm: Some("https://www.example.com".into()),
876            username: "test".into(),
877            password: "test".into(),
878            ..Default::default()
879        };
880
881        let login_with_empty_origin = LoginEntry {
882            origin: "".into(),
883            http_realm: Some("https://www.example.com".into()),
884            username: "test".into(),
885            password: "test".into(),
886            ..Default::default()
887        };
888
889        let login_with_empty_password = LoginEntry {
890            origin: "https://www.example.com".into(),
891            http_realm: Some("https://www.example.com".into()),
892            username: "test".into(),
893            password: "".into(),
894            ..Default::default()
895        };
896
897        let login_with_form_submit_and_http_realm = LoginEntry {
898            origin: "https://www.example.com".into(),
899            http_realm: Some("https://www.example.com".into()),
900            form_action_origin: Some("https://www.example.com".into()),
901            username: "".into(),
902            password: "test".into(),
903            ..Default::default()
904        };
905
906        let login_without_form_submit_or_http_realm = LoginEntry {
907            origin: "https://www.example.com".into(),
908            username: "".into(),
909            password: "test".into(),
910            ..Default::default()
911        };
912
913        let login_with_legacy_form_submit_and_http_realm = LoginEntry {
914            origin: "https://www.example.com".into(),
915            form_action_origin: Some("".into()),
916            username: "".into(),
917            password: "test".into(),
918            ..Default::default()
919        };
920
921        let login_with_null_http_realm = LoginEntry {
922            origin: "https://www.example.com".into(),
923            http_realm: Some("https://www.example.\0com".into()),
924            username: "test".into(),
925            password: "test".into(),
926            ..Default::default()
927        };
928
929        let login_with_null_username = LoginEntry {
930            origin: "https://www.example.com".into(),
931            http_realm: Some("https://www.example.com".into()),
932            username: "\0".into(),
933            password: "test".into(),
934            ..Default::default()
935        };
936
937        let login_with_null_password = LoginEntry {
938            origin: "https://www.example.com".into(),
939            http_realm: Some("https://www.example.com".into()),
940            username: "username".into(),
941            password: "test\0".into(),
942            ..Default::default()
943        };
944
945        let login_with_newline_origin = LoginEntry {
946            origin: "\rhttps://www.example.com".into(),
947            http_realm: Some("https://www.example.com".into()),
948            username: "test".into(),
949            password: "test".into(),
950            ..Default::default()
951        };
952
953        let login_with_newline_username_field = LoginEntry {
954            origin: "https://www.example.com".into(),
955            http_realm: Some("https://www.example.com".into()),
956            username_field: "\n".into(),
957            username: "test".into(),
958            password: "test".into(),
959            ..Default::default()
960        };
961
962        let login_with_newline_realm = LoginEntry {
963            origin: "https://www.example.com".into(),
964            http_realm: Some("foo\nbar".into()),
965            username: "test".into(),
966            password: "test".into(),
967            ..Default::default()
968        };
969
970        let login_with_newline_password = LoginEntry {
971            origin: "https://www.example.com".into(),
972            http_realm: Some("https://www.example.com".into()),
973            username: "test".into(),
974            password: "test\n".into(),
975            ..Default::default()
976        };
977
978        let login_with_period_username_field = LoginEntry {
979            origin: "https://www.example.com".into(),
980            http_realm: Some("https://www.example.com".into()),
981            username_field: ".".into(),
982            username: "test".into(),
983            password: "test".into(),
984            ..Default::default()
985        };
986
987        let login_with_period_form_action_origin = LoginEntry {
988            form_action_origin: Some(".".into()),
989            origin: "https://www.example.com".into(),
990            username: "test".into(),
991            password: "test".into(),
992            ..Default::default()
993        };
994
995        let login_with_javascript_form_action_origin = LoginEntry {
996            form_action_origin: Some("javascript:".into()),
997            origin: "https://www.example.com".into(),
998            username: "test".into(),
999            password: "test".into(),
1000            ..Default::default()
1001        };
1002
1003        let login_with_malformed_origin_parens = LoginEntry {
1004            origin: " (".into(),
1005            http_realm: Some("https://www.example.com".into()),
1006            username: "test".into(),
1007            password: "test".into(),
1008            ..Default::default()
1009        };
1010
1011        let login_with_host_unicode = LoginEntry {
1012            origin: "http://💖.com".into(),
1013            http_realm: Some("https://www.example.com".into()),
1014            username: "test".into(),
1015            password: "test".into(),
1016            ..Default::default()
1017        };
1018
1019        let login_with_origin_trailing_slash = LoginEntry {
1020            origin: "https://www.example.com/".into(),
1021            http_realm: Some("https://www.example.com".into()),
1022            username: "test".into(),
1023            password: "test".into(),
1024            ..Default::default()
1025        };
1026
1027        let login_with_origin_expanded_ipv6 = LoginEntry {
1028            origin: "https://[0:0:0:0:0:0:1:1]".into(),
1029            http_realm: Some("https://www.example.com".into()),
1030            username: "test".into(),
1031            password: "test".into(),
1032            ..Default::default()
1033        };
1034
1035        let login_with_unknown_protocol = LoginEntry {
1036            origin: "moz-proxy://127.0.0.1:8888".into(),
1037            http_realm: Some("https://www.example.com".into()),
1038            username: "test".into(),
1039            password: "test".into(),
1040            ..Default::default()
1041        };
1042
1043        let test_cases = [
1044            TestCase {
1045                login: valid_login,
1046                should_err: false,
1047                expected_err: "",
1048            },
1049            TestCase {
1050                login: login_with_empty_origin,
1051                should_err: true,
1052                expected_err: "Invalid login: Origin is empty",
1053            },
1054            TestCase {
1055                login: login_with_empty_password,
1056                should_err: true,
1057                expected_err: "Invalid login: Password is empty",
1058            },
1059            TestCase {
1060                login: login_with_form_submit_and_http_realm,
1061                should_err: true,
1062                expected_err: "Invalid login: Both `formActionOrigin` and `httpRealm` are present",
1063            },
1064            TestCase {
1065                login: login_without_form_submit_or_http_realm,
1066                should_err: true,
1067                expected_err:
1068                    "Invalid login: Neither `formActionOrigin` or `httpRealm` are present",
1069            },
1070            TestCase {
1071                login: login_with_null_http_realm,
1072                should_err: true,
1073                expected_err: "Invalid login: Login has illegal field: `http_realm` contains Nul",
1074            },
1075            TestCase {
1076                login: login_with_null_username,
1077                should_err: true,
1078                expected_err: "Invalid login: Login has illegal field: `username` contains Nul",
1079            },
1080            TestCase {
1081                login: login_with_null_password,
1082                should_err: true,
1083                expected_err: "Invalid login: Login has illegal field: `password` contains Nul",
1084            },
1085            TestCase {
1086                login: login_with_newline_origin,
1087                should_err: true,
1088                expected_err: "Invalid login: Login has illegal field: `origin` contains newline",
1089            },
1090            TestCase {
1091                login: login_with_newline_realm,
1092                should_err: true,
1093                expected_err:
1094                    "Invalid login: Login has illegal field: `http_realm` contains newline",
1095            },
1096            TestCase {
1097                login: login_with_newline_username_field,
1098                should_err: true,
1099                expected_err:
1100                    "Invalid login: Login has illegal field: `username_field` contains newline",
1101            },
1102            TestCase {
1103                login: login_with_newline_password,
1104                should_err: false,
1105                expected_err: "",
1106            },
1107            TestCase {
1108                login: login_with_period_username_field,
1109                should_err: true,
1110                expected_err:
1111                    "Invalid login: Login has illegal field: `username_field` is a period",
1112            },
1113            TestCase {
1114                login: login_with_period_form_action_origin,
1115                should_err: false,
1116                expected_err: "",
1117            },
1118            TestCase {
1119                login: login_with_javascript_form_action_origin,
1120                should_err: false,
1121                expected_err: "",
1122            },
1123            TestCase {
1124                login: login_with_malformed_origin_parens,
1125                should_err: true,
1126                expected_err: "Invalid login: Login has illegal origin",
1127            },
1128            TestCase {
1129                login: login_with_host_unicode,
1130                should_err: true,
1131                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1132            },
1133            TestCase {
1134                login: login_with_origin_trailing_slash,
1135                should_err: true,
1136                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1137            },
1138            TestCase {
1139                login: login_with_origin_expanded_ipv6,
1140                should_err: true,
1141                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1142            },
1143            TestCase {
1144                login: login_with_unknown_protocol,
1145                should_err: false,
1146                expected_err: "",
1147            },
1148            TestCase {
1149                login: login_with_legacy_form_submit_and_http_realm,
1150                should_err: false,
1151                expected_err: "",
1152            },
1153        ];
1154
1155        for tc in &test_cases {
1156            let actual = tc.login.check_valid();
1157
1158            if tc.should_err {
1159                assert!(actual.is_err(), "{:#?}", tc);
1160                assert_eq!(
1161                    tc.expected_err,
1162                    actual.unwrap_err().to_string(),
1163                    "{:#?}",
1164                    tc,
1165                );
1166            } else {
1167                assert!(actual.is_ok(), "{:#?}", tc);
1168                assert!(
1169                    tc.login.clone().fixup().is_ok(),
1170                    "Fixup failed after check_valid passed: {:#?}",
1171                    &tc,
1172                );
1173            }
1174        }
1175    }
1176
1177    #[test]
1178    fn test_fixup() {
1179        #[derive(Debug, Default)]
1180        struct TestCase {
1181            login: LoginEntry,
1182            fixedup_host: Option<&'static str>,
1183            fixedup_form_action_origin: Option<String>,
1184        }
1185
1186        // Note that most URL fixups are tested above, but we have one or 2 here.
1187        let login_with_full_url = LoginEntry {
1188            origin: "http://example.com/foo?query=wtf#bar".into(),
1189            form_action_origin: Some("http://example.com/foo?query=wtf#bar".into()),
1190            username: "test".into(),
1191            password: "test".into(),
1192            ..Default::default()
1193        };
1194
1195        let login_with_host_unicode = LoginEntry {
1196            origin: "http://😍.com".into(),
1197            form_action_origin: Some("http://😍.com".into()),
1198            username: "test".into(),
1199            password: "test".into(),
1200            ..Default::default()
1201        };
1202
1203        let login_with_period_fsu = LoginEntry {
1204            origin: "https://example.com".into(),
1205            form_action_origin: Some(".".into()),
1206            username: "test".into(),
1207            password: "test".into(),
1208            ..Default::default()
1209        };
1210        let login_with_empty_fsu = LoginEntry {
1211            origin: "https://example.com".into(),
1212            form_action_origin: Some("".into()),
1213            username: "test".into(),
1214            password: "test".into(),
1215            ..Default::default()
1216        };
1217
1218        let login_with_form_submit_and_http_realm = LoginEntry {
1219            origin: "https://www.example.com".into(),
1220            form_action_origin: Some("https://www.example.com".into()),
1221            // If both http_realm and form_action_origin are specified, we drop
1222            // the former when fixing up. So for this test we must have an
1223            // invalid value in http_realm to ensure we don't validate a value
1224            // we end up dropping.
1225            http_realm: Some("\n".into()),
1226            username: "".into(),
1227            password: "test".into(),
1228            ..Default::default()
1229        };
1230
1231        let test_cases = [
1232            TestCase {
1233                login: login_with_full_url,
1234                fixedup_host: "http://example.com".into(),
1235                fixedup_form_action_origin: Some("http://example.com".into()),
1236            },
1237            TestCase {
1238                login: login_with_host_unicode,
1239                fixedup_host: "http://xn--r28h.com".into(),
1240                fixedup_form_action_origin: Some("http://xn--r28h.com".into()),
1241            },
1242            TestCase {
1243                login: login_with_period_fsu,
1244                fixedup_form_action_origin: Some("".into()),
1245                ..TestCase::default()
1246            },
1247            TestCase {
1248                login: login_with_form_submit_and_http_realm,
1249                fixedup_form_action_origin: Some("https://www.example.com".into()),
1250                ..TestCase::default()
1251            },
1252            TestCase {
1253                login: login_with_empty_fsu,
1254                // Should still be empty.
1255                fixedup_form_action_origin: Some("".into()),
1256                ..TestCase::default()
1257            },
1258        ];
1259
1260        for tc in &test_cases {
1261            let login = tc.login.clone().fixup().expect("should work");
1262            if let Some(expected) = tc.fixedup_host {
1263                assert_eq!(login.origin, expected, "origin not fixed in {:#?}", tc);
1264            }
1265            assert_eq!(
1266                login.form_action_origin, tc.fixedup_form_action_origin,
1267                "form_action_origin not fixed in {:#?}",
1268                tc,
1269            );
1270            login.check_valid().unwrap_or_else(|e| {
1271                panic!("Fixup produces invalid record: {:#?}", (e, &tc, &login));
1272            });
1273            assert_eq!(
1274                login.clone().fixup().unwrap(),
1275                login,
1276                "fixup did not reach fixed point for testcase: {:#?}",
1277                tc,
1278            );
1279        }
1280    }
1281
1282    #[test]
1283    fn test_secure_fields_serde() {
1284        let sf = SecureLoginFields {
1285            username: "foo".into(),
1286            password: "pwd".into(),
1287        };
1288        assert_eq!(
1289            serde_json::to_string(&sf).unwrap(),
1290            r#"{"u":"foo","p":"pwd"}"#
1291        );
1292        let got: SecureLoginFields = serde_json::from_str(r#"{"u": "user", "p": "p"}"#).unwrap();
1293        let expected = SecureLoginFields {
1294            username: "user".into(),
1295            password: "p".into(),
1296        };
1297        assert_eq!(got, expected);
1298    }
1299}