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
392    /// Helper for validation and fixups of an "origin" provided as a string.
393    pub 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 {
439                    reason: e.to_string(),
440                }
441                .into())
442            }
443        }
444    }
445}
446
447/// A login handed over from the store API, which has been persisted and contains persistence
448/// information such as id and time stamps
449#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
450pub struct Login {
451    // meta fields
452    pub id: String,
453    pub time_created: i64,
454    pub time_password_changed: i64,
455    pub time_last_used: i64,
456    pub times_used: i64,
457
458    // login fields
459    pub origin: String,
460    pub form_action_origin: Option<String>,
461    pub http_realm: Option<String>,
462    pub username_field: String,
463    pub password_field: String,
464
465    // secure fields
466    pub username: String,
467    pub password: String,
468}
469
470impl Login {
471    pub fn new(meta: LoginMeta, fields: LoginFields, sec_fields: SecureLoginFields) -> Self {
472        Self {
473            id: meta.id,
474            time_created: meta.time_created,
475            time_password_changed: meta.time_password_changed,
476            time_last_used: meta.time_last_used,
477            times_used: meta.times_used,
478
479            origin: fields.origin,
480            form_action_origin: fields.form_action_origin,
481            http_realm: fields.http_realm,
482            username_field: fields.username_field,
483            password_field: fields.password_field,
484
485            username: sec_fields.username,
486            password: sec_fields.password,
487        }
488    }
489
490    #[inline]
491    pub fn guid(&self) -> Guid {
492        Guid::from_string(self.id.clone())
493    }
494
495    pub fn entry(&self) -> LoginEntry {
496        LoginEntry {
497            origin: self.origin.clone(),
498            form_action_origin: self.form_action_origin.clone(),
499            http_realm: self.http_realm.clone(),
500            username_field: self.username_field.clone(),
501            password_field: self.password_field.clone(),
502
503            username: self.username.clone(),
504            password: self.password.clone(),
505        }
506    }
507
508    pub fn encrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<EncryptedLogin> {
509        let sec_fields = SecureLoginFields {
510            username: self.username,
511            password: self.password,
512        }
513        .encrypt(encdec, &self.id)?;
514        Ok(EncryptedLogin {
515            meta: LoginMeta {
516                id: self.id,
517                time_created: self.time_created,
518                time_password_changed: self.time_password_changed,
519                time_last_used: self.time_last_used,
520                times_used: self.times_used,
521            },
522            fields: LoginFields {
523                origin: self.origin,
524                form_action_origin: self.form_action_origin,
525                http_realm: self.http_realm,
526                username_field: self.username_field,
527                password_field: self.password_field,
528            },
529            sec_fields,
530        })
531    }
532}
533
534/// A login stored in the database
535#[derive(Debug, Clone, Hash, PartialEq, Eq, Default)]
536pub struct EncryptedLogin {
537    pub meta: LoginMeta,
538    pub fields: LoginFields,
539    pub sec_fields: String,
540}
541
542impl EncryptedLogin {
543    #[inline]
544    pub fn guid(&self) -> Guid {
545        Guid::from_string(self.meta.id.clone())
546    }
547
548    // TODO: Remove this: https://github.com/mozilla/application-services/issues/4185
549    #[inline]
550    pub fn guid_str(&self) -> &str {
551        &self.meta.id
552    }
553
554    pub fn decrypt(self, encdec: &dyn EncryptorDecryptor) -> Result<Login> {
555        let sec_fields = self.decrypt_fields(encdec)?;
556        Ok(Login::new(self.meta, self.fields, sec_fields))
557    }
558
559    pub fn decrypt_fields(&self, encdec: &dyn EncryptorDecryptor) -> Result<SecureLoginFields> {
560        SecureLoginFields::decrypt(&self.sec_fields, encdec, &self.meta.id)
561    }
562
563    pub(crate) fn from_row(row: &Row<'_>) -> Result<EncryptedLogin> {
564        let login = EncryptedLogin {
565            meta: LoginMeta {
566                id: row.get("guid")?,
567                time_created: row.get("timeCreated")?,
568                // Might be null
569                time_last_used: row
570                    .get::<_, Option<i64>>("timeLastUsed")?
571                    .unwrap_or_default(),
572
573                time_password_changed: row.get("timePasswordChanged")?,
574                times_used: row.get("timesUsed")?,
575            },
576            fields: LoginFields {
577                origin: row.get("origin")?,
578                http_realm: row.get("httpRealm")?,
579
580                form_action_origin: row.get("formActionOrigin")?,
581
582                username_field: string_or_default(row, "usernameField")?,
583                password_field: string_or_default(row, "passwordField")?,
584            },
585            sec_fields: row.get("secFields")?,
586        };
587        // XXX - we used to perform a fixup here, but that seems heavy-handed
588        // and difficult - we now only do that on add/insert when we have the
589        // encryption key.
590        Ok(login)
591    }
592}
593
594fn string_or_default(row: &Row<'_>, col: &str) -> Result<String> {
595    Ok(row.get::<_, Option<String>>(col)?.unwrap_or_default())
596}
597
598pub trait ValidateAndFixup {
599    // Our validate and fixup functions.
600    fn check_valid(&self) -> Result<()>
601    where
602        Self: Sized,
603    {
604        self.validate_and_fixup(false)?;
605        Ok(())
606    }
607
608    fn fixup(self) -> Result<Self>
609    where
610        Self: Sized,
611    {
612        match self.maybe_fixup()? {
613            None => Ok(self),
614            Some(login) => Ok(login),
615        }
616    }
617
618    fn maybe_fixup(&self) -> Result<Option<Self>>
619    where
620        Self: Sized,
621    {
622        self.validate_and_fixup(true)
623    }
624
625    // validates, and optionally fixes, a struct. If fixup is false and there is a validation
626    // issue, an `Err` is returned. If fixup is true and a problem was fixed, and `Ok(Some<Self>)`
627    // is returned with the fixed version. If there was no validation problem, `Ok(None)` is
628    // returned.
629    fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>>
630    where
631        Self: Sized;
632}
633
634impl ValidateAndFixup for LoginEntry {
635    fn validate_and_fixup(&self, fixup: bool) -> Result<Option<Self>> {
636        // XXX TODO: we've definitely got more validation and fixups to add here!
637
638        let mut maybe_fixed = None;
639
640        /// A little helper to magic a Some(self.clone()) into existence when needed.
641        macro_rules! get_fixed_or_throw {
642            ($err:expr) => {
643                // This is a block expression returning a local variable,
644                // entirely so we can give it an explicit type declaration.
645                {
646                    if !fixup {
647                        return Err($err.into());
648                    }
649                    warn!("Fixing login record {:?}", $err);
650                    let fixed: Result<&mut Self> =
651                        Ok(maybe_fixed.get_or_insert_with(|| self.clone()));
652                    fixed
653                }
654            };
655        }
656
657        if self.origin.is_empty() {
658            return Err(InvalidLogin::EmptyOrigin.into());
659        }
660
661        if self.form_action_origin.is_some() && self.http_realm.is_some() {
662            get_fixed_or_throw!(InvalidLogin::BothTargets)?.http_realm = None;
663        }
664
665        if self.form_action_origin.is_none() && self.http_realm.is_none() {
666            return Err(InvalidLogin::NoTarget.into());
667        }
668
669        let form_action_origin = self.form_action_origin.clone().unwrap_or_default();
670        let http_realm = maybe_fixed
671            .as_ref()
672            .unwrap_or(self)
673            .http_realm
674            .clone()
675            .unwrap_or_default();
676
677        let field_data = [
678            ("form_action_origin", &form_action_origin),
679            ("http_realm", &http_realm),
680            ("origin", &self.origin),
681            ("username_field", &self.username_field),
682            ("password_field", &self.password_field),
683        ];
684
685        for (field_name, field_value) in &field_data {
686            // Nuls are invalid.
687            if field_value.contains('\0') {
688                return Err(InvalidLogin::IllegalFieldValue {
689                    field_info: format!("`{}` contains Nul", field_name),
690                }
691                .into());
692            }
693
694            // Newlines are invalid in Desktop for all the fields here.
695            if field_value.contains('\n') || field_value.contains('\r') {
696                return Err(InvalidLogin::IllegalFieldValue {
697                    field_info: format!("`{}` contains newline", field_name),
698                }
699                .into());
700            }
701        }
702
703        // Desktop doesn't like fields with the below patterns
704        if self.username_field == "." {
705            return Err(InvalidLogin::IllegalFieldValue {
706                field_info: "`username_field` is a period".into(),
707            }
708            .into());
709        }
710
711        // Check we can parse the origin, then use the normalized version of it.
712        if let Some(fixed) = Self::validate_and_fixup_origin(&self.origin)? {
713            get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
714                field_info: "Origin is not normalized".into()
715            })?
716            .origin = fixed;
717        }
718
719        match &maybe_fixed.as_ref().unwrap_or(self).form_action_origin {
720            None => {
721                if !self.username_field.is_empty() {
722                    get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
723                        field_info: "username_field must be empty when form_action_origin is null"
724                            .into()
725                    })?
726                    .username_field
727                    .clear();
728                }
729                if !self.password_field.is_empty() {
730                    get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
731                        field_info: "password_field must be empty when form_action_origin is null"
732                            .into()
733                    })?
734                    .password_field
735                    .clear();
736                }
737            }
738            Some(href) => {
739                // "", ".", and "javascript:" are special cases documented at the top of this file.
740                if href == "." {
741                    // A bit of a special case - if we are being asked to fixup, we replace
742                    // "." with an empty string - but if not fixing up we don't complain.
743                    if fixup {
744                        maybe_fixed
745                            .get_or_insert_with(|| self.clone())
746                            .form_action_origin = Some("".into());
747                    }
748                } else if !href.is_empty() && href != "javascript:" {
749                    if let Some(fixed) = Self::validate_and_fixup_origin(href)? {
750                        get_fixed_or_throw!(InvalidLogin::IllegalFieldValue {
751                            field_info: "form_action_origin is not normalized".into()
752                        })?
753                        .form_action_origin = Some(fixed);
754                    }
755                }
756            }
757        }
758
759        // secure fields
760        //
761        // \r\n chars are valid in desktop for some reason, so we allow them here too.
762        if self.username.contains('\0') {
763            return Err(InvalidLogin::IllegalFieldValue {
764                field_info: "`username` contains Nul".into(),
765            }
766            .into());
767        }
768        if self.password.is_empty() {
769            return Err(InvalidLogin::EmptyPassword.into());
770        }
771        if self.password.contains('\0') {
772            return Err(InvalidLogin::IllegalFieldValue {
773                field_info: "`password` contains Nul".into(),
774            }
775            .into());
776        }
777
778        Ok(maybe_fixed)
779    }
780}
781
782#[cfg(test)]
783pub mod test_utils {
784    use super::*;
785    use crate::encryption::test_utils::encrypt_struct;
786
787    // Factory function to make a new login
788    //
789    // It uses the guid to create a unique origin/form_action_origin
790    pub fn enc_login(id: &str, password: &str) -> EncryptedLogin {
791        let sec_fields = SecureLoginFields {
792            username: "user".to_string(),
793            password: password.to_string(),
794        };
795        EncryptedLogin {
796            meta: LoginMeta {
797                id: id.to_string(),
798                ..Default::default()
799            },
800            fields: LoginFields {
801                form_action_origin: Some(format!("https://{}.example.com", id)),
802                origin: format!("https://{}.example.com", id),
803                ..Default::default()
804            },
805            // TODO: fixme
806            sec_fields: encrypt_struct(&sec_fields),
807        }
808    }
809}
810
811#[cfg(test)]
812mod tests {
813    use super::*;
814
815    #[test]
816    fn test_url_fixups() -> Result<()> {
817        // Start with URLs which are all valid and already normalized.
818        for input in &[
819            // The list of valid origins documented at the top of this file.
820            "https://site.com",
821            "http://site.com:1234",
822            "ftp://ftp.site.com",
823            "moz-proxy://127.0.0.1:8888",
824            "chrome://MyLegacyExtension",
825            "file://",
826            "https://[::1]",
827        ] {
828            assert_eq!(LoginEntry::validate_and_fixup_origin(input)?, None);
829        }
830
831        // And URLs which get normalized.
832        for (input, output) in &[
833            ("https://site.com/", "https://site.com"),
834            ("http://site.com:1234/", "http://site.com:1234"),
835            ("http://example.com/foo?query=wtf#bar", "http://example.com"),
836            ("http://example.com/foo#bar", "http://example.com"),
837            (
838                "http://username:password@example.com/",
839                "http://example.com",
840            ),
841            ("http://😍.com/", "http://xn--r28h.com"),
842            ("https://[0:0:0:0:0:0:0:1]", "https://[::1]"),
843            // All `file://` URLs normalize to exactly `file://`. See #2384 for
844            // why we might consider changing that later.
845            ("file:///", "file://"),
846            ("file://foo/bar", "file://"),
847            ("file://foo/bar/", "file://"),
848            ("moz-proxy://127.0.0.1:8888/", "moz-proxy://127.0.0.1:8888"),
849            (
850                "moz-proxy://127.0.0.1:8888/foo",
851                "moz-proxy://127.0.0.1:8888",
852            ),
853            ("chrome://MyLegacyExtension/", "chrome://MyLegacyExtension"),
854            (
855                "chrome://MyLegacyExtension/foo",
856                "chrome://MyLegacyExtension",
857            ),
858        ] {
859            assert_eq!(
860                LoginEntry::validate_and_fixup_origin(input)?,
861                Some((*output).into())
862            );
863        }
864
865        // Finally, look at some invalid logins
866        for input in &[".", "example", "example.com"] {
867            assert!(LoginEntry::validate_and_fixup_origin(input).is_err());
868        }
869
870        Ok(())
871    }
872
873    #[test]
874    fn test_check_valid() {
875        #[derive(Debug, Clone)]
876        struct TestCase {
877            login: LoginEntry,
878            should_err: bool,
879            expected_err: &'static str,
880        }
881
882        let valid_login = LoginEntry {
883            origin: "https://www.example.com".into(),
884            http_realm: Some("https://www.example.com".into()),
885            username: "test".into(),
886            password: "test".into(),
887            ..Default::default()
888        };
889
890        let login_with_empty_origin = LoginEntry {
891            origin: "".into(),
892            http_realm: Some("https://www.example.com".into()),
893            username: "test".into(),
894            password: "test".into(),
895            ..Default::default()
896        };
897
898        let login_with_empty_password = LoginEntry {
899            origin: "https://www.example.com".into(),
900            http_realm: Some("https://www.example.com".into()),
901            username: "test".into(),
902            password: "".into(),
903            ..Default::default()
904        };
905
906        let login_with_form_submit_and_http_realm = LoginEntry {
907            origin: "https://www.example.com".into(),
908            http_realm: Some("https://www.example.com".into()),
909            form_action_origin: Some("https://www.example.com".into()),
910            username: "".into(),
911            password: "test".into(),
912            ..Default::default()
913        };
914
915        let login_without_form_submit_or_http_realm = LoginEntry {
916            origin: "https://www.example.com".into(),
917            username: "".into(),
918            password: "test".into(),
919            ..Default::default()
920        };
921
922        let login_with_legacy_form_submit_and_http_realm = LoginEntry {
923            origin: "https://www.example.com".into(),
924            form_action_origin: Some("".into()),
925            username: "".into(),
926            password: "test".into(),
927            ..Default::default()
928        };
929
930        let login_with_null_http_realm = LoginEntry {
931            origin: "https://www.example.com".into(),
932            http_realm: Some("https://www.example.\0com".into()),
933            username: "test".into(),
934            password: "test".into(),
935            ..Default::default()
936        };
937
938        let login_with_null_username = LoginEntry {
939            origin: "https://www.example.com".into(),
940            http_realm: Some("https://www.example.com".into()),
941            username: "\0".into(),
942            password: "test".into(),
943            ..Default::default()
944        };
945
946        let login_with_null_password = LoginEntry {
947            origin: "https://www.example.com".into(),
948            http_realm: Some("https://www.example.com".into()),
949            username: "username".into(),
950            password: "test\0".into(),
951            ..Default::default()
952        };
953
954        let login_with_newline_origin = LoginEntry {
955            origin: "\rhttps://www.example.com".into(),
956            http_realm: Some("https://www.example.com".into()),
957            username: "test".into(),
958            password: "test".into(),
959            ..Default::default()
960        };
961
962        let login_with_newline_username_field = LoginEntry {
963            origin: "https://www.example.com".into(),
964            http_realm: Some("https://www.example.com".into()),
965            username_field: "\n".into(),
966            username: "test".into(),
967            password: "test".into(),
968            ..Default::default()
969        };
970
971        let login_with_newline_realm = LoginEntry {
972            origin: "https://www.example.com".into(),
973            http_realm: Some("foo\nbar".into()),
974            username: "test".into(),
975            password: "test".into(),
976            ..Default::default()
977        };
978
979        let login_with_newline_password = LoginEntry {
980            origin: "https://www.example.com".into(),
981            http_realm: Some("https://www.example.com".into()),
982            username: "test".into(),
983            password: "test\n".into(),
984            ..Default::default()
985        };
986
987        let login_with_period_username_field = LoginEntry {
988            origin: "https://www.example.com".into(),
989            http_realm: Some("https://www.example.com".into()),
990            username_field: ".".into(),
991            username: "test".into(),
992            password: "test".into(),
993            ..Default::default()
994        };
995
996        let login_with_period_form_action_origin = LoginEntry {
997            form_action_origin: Some(".".into()),
998            origin: "https://www.example.com".into(),
999            username: "test".into(),
1000            password: "test".into(),
1001            ..Default::default()
1002        };
1003
1004        let login_with_javascript_form_action_origin = LoginEntry {
1005            form_action_origin: Some("javascript:".into()),
1006            origin: "https://www.example.com".into(),
1007            username: "test".into(),
1008            password: "test".into(),
1009            ..Default::default()
1010        };
1011
1012        let login_with_malformed_origin_parens = LoginEntry {
1013            origin: " (".into(),
1014            http_realm: Some("https://www.example.com".into()),
1015            username: "test".into(),
1016            password: "test".into(),
1017            ..Default::default()
1018        };
1019
1020        let login_with_host_unicode = LoginEntry {
1021            origin: "http://💖.com".into(),
1022            http_realm: Some("https://www.example.com".into()),
1023            username: "test".into(),
1024            password: "test".into(),
1025            ..Default::default()
1026        };
1027
1028        let login_with_origin_trailing_slash = LoginEntry {
1029            origin: "https://www.example.com/".into(),
1030            http_realm: Some("https://www.example.com".into()),
1031            username: "test".into(),
1032            password: "test".into(),
1033            ..Default::default()
1034        };
1035
1036        let login_with_origin_expanded_ipv6 = LoginEntry {
1037            origin: "https://[0:0:0:0:0:0:1:1]".into(),
1038            http_realm: Some("https://www.example.com".into()),
1039            username: "test".into(),
1040            password: "test".into(),
1041            ..Default::default()
1042        };
1043
1044        let login_with_unknown_protocol = LoginEntry {
1045            origin: "moz-proxy://127.0.0.1:8888".into(),
1046            http_realm: Some("https://www.example.com".into()),
1047            username: "test".into(),
1048            password: "test".into(),
1049            ..Default::default()
1050        };
1051
1052        let test_cases = [
1053            TestCase {
1054                login: valid_login,
1055                should_err: false,
1056                expected_err: "",
1057            },
1058            TestCase {
1059                login: login_with_empty_origin,
1060                should_err: true,
1061                expected_err: "Invalid login: Origin is empty",
1062            },
1063            TestCase {
1064                login: login_with_empty_password,
1065                should_err: true,
1066                expected_err: "Invalid login: Password is empty",
1067            },
1068            TestCase {
1069                login: login_with_form_submit_and_http_realm,
1070                should_err: true,
1071                expected_err: "Invalid login: Both `formActionOrigin` and `httpRealm` are present",
1072            },
1073            TestCase {
1074                login: login_without_form_submit_or_http_realm,
1075                should_err: true,
1076                expected_err:
1077                    "Invalid login: Neither `formActionOrigin` or `httpRealm` are present",
1078            },
1079            TestCase {
1080                login: login_with_null_http_realm,
1081                should_err: true,
1082                expected_err: "Invalid login: Login has illegal field: `http_realm` contains Nul",
1083            },
1084            TestCase {
1085                login: login_with_null_username,
1086                should_err: true,
1087                expected_err: "Invalid login: Login has illegal field: `username` contains Nul",
1088            },
1089            TestCase {
1090                login: login_with_null_password,
1091                should_err: true,
1092                expected_err: "Invalid login: Login has illegal field: `password` contains Nul",
1093            },
1094            TestCase {
1095                login: login_with_newline_origin,
1096                should_err: true,
1097                expected_err: "Invalid login: Login has illegal field: `origin` contains newline",
1098            },
1099            TestCase {
1100                login: login_with_newline_realm,
1101                should_err: true,
1102                expected_err:
1103                    "Invalid login: Login has illegal field: `http_realm` contains newline",
1104            },
1105            TestCase {
1106                login: login_with_newline_username_field,
1107                should_err: true,
1108                expected_err:
1109                    "Invalid login: Login has illegal field: `username_field` contains newline",
1110            },
1111            TestCase {
1112                login: login_with_newline_password,
1113                should_err: false,
1114                expected_err: "",
1115            },
1116            TestCase {
1117                login: login_with_period_username_field,
1118                should_err: true,
1119                expected_err:
1120                    "Invalid login: Login has illegal field: `username_field` is a period",
1121            },
1122            TestCase {
1123                login: login_with_period_form_action_origin,
1124                should_err: false,
1125                expected_err: "",
1126            },
1127            TestCase {
1128                login: login_with_javascript_form_action_origin,
1129                should_err: false,
1130                expected_err: "",
1131            },
1132            TestCase {
1133                login: login_with_malformed_origin_parens,
1134                should_err: true,
1135                expected_err:
1136                    "Invalid login: Login has illegal origin: relative URL without a base",
1137            },
1138            TestCase {
1139                login: login_with_host_unicode,
1140                should_err: true,
1141                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1142            },
1143            TestCase {
1144                login: login_with_origin_trailing_slash,
1145                should_err: true,
1146                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1147            },
1148            TestCase {
1149                login: login_with_origin_expanded_ipv6,
1150                should_err: true,
1151                expected_err: "Invalid login: Login has illegal field: Origin is not normalized",
1152            },
1153            TestCase {
1154                login: login_with_unknown_protocol,
1155                should_err: false,
1156                expected_err: "",
1157            },
1158            TestCase {
1159                login: login_with_legacy_form_submit_and_http_realm,
1160                should_err: false,
1161                expected_err: "",
1162            },
1163        ];
1164
1165        for tc in &test_cases {
1166            let actual = tc.login.check_valid();
1167
1168            if tc.should_err {
1169                assert!(actual.is_err(), "{:#?}", tc);
1170                assert_eq!(
1171                    tc.expected_err,
1172                    actual.unwrap_err().to_string(),
1173                    "{:#?}",
1174                    tc,
1175                );
1176            } else {
1177                assert!(actual.is_ok(), "{:#?}", tc);
1178                assert!(
1179                    tc.login.clone().fixup().is_ok(),
1180                    "Fixup failed after check_valid passed: {:#?}",
1181                    &tc,
1182                );
1183            }
1184        }
1185    }
1186
1187    #[test]
1188    fn test_fixup() {
1189        #[derive(Debug, Default)]
1190        struct TestCase {
1191            login: LoginEntry,
1192            fixedup_host: Option<&'static str>,
1193            fixedup_form_action_origin: Option<String>,
1194        }
1195
1196        // Note that most URL fixups are tested above, but we have one or 2 here.
1197        let login_with_full_url = LoginEntry {
1198            origin: "http://example.com/foo?query=wtf#bar".into(),
1199            form_action_origin: Some("http://example.com/foo?query=wtf#bar".into()),
1200            username: "test".into(),
1201            password: "test".into(),
1202            ..Default::default()
1203        };
1204
1205        let login_with_host_unicode = LoginEntry {
1206            origin: "http://😍.com".into(),
1207            form_action_origin: Some("http://😍.com".into()),
1208            username: "test".into(),
1209            password: "test".into(),
1210            ..Default::default()
1211        };
1212
1213        let login_with_period_fsu = LoginEntry {
1214            origin: "https://example.com".into(),
1215            form_action_origin: Some(".".into()),
1216            username: "test".into(),
1217            password: "test".into(),
1218            ..Default::default()
1219        };
1220        let login_with_empty_fsu = LoginEntry {
1221            origin: "https://example.com".into(),
1222            form_action_origin: Some("".into()),
1223            username: "test".into(),
1224            password: "test".into(),
1225            ..Default::default()
1226        };
1227
1228        let login_with_form_submit_and_http_realm = LoginEntry {
1229            origin: "https://www.example.com".into(),
1230            form_action_origin: Some("https://www.example.com".into()),
1231            // If both http_realm and form_action_origin are specified, we drop
1232            // the former when fixing up. So for this test we must have an
1233            // invalid value in http_realm to ensure we don't validate a value
1234            // we end up dropping.
1235            http_realm: Some("\n".into()),
1236            username: "".into(),
1237            password: "test".into(),
1238            ..Default::default()
1239        };
1240
1241        let test_cases = [
1242            TestCase {
1243                login: login_with_full_url,
1244                fixedup_host: "http://example.com".into(),
1245                fixedup_form_action_origin: Some("http://example.com".into()),
1246            },
1247            TestCase {
1248                login: login_with_host_unicode,
1249                fixedup_host: "http://xn--r28h.com".into(),
1250                fixedup_form_action_origin: Some("http://xn--r28h.com".into()),
1251            },
1252            TestCase {
1253                login: login_with_period_fsu,
1254                fixedup_form_action_origin: Some("".into()),
1255                ..TestCase::default()
1256            },
1257            TestCase {
1258                login: login_with_form_submit_and_http_realm,
1259                fixedup_form_action_origin: Some("https://www.example.com".into()),
1260                ..TestCase::default()
1261            },
1262            TestCase {
1263                login: login_with_empty_fsu,
1264                // Should still be empty.
1265                fixedup_form_action_origin: Some("".into()),
1266                ..TestCase::default()
1267            },
1268        ];
1269
1270        for tc in &test_cases {
1271            let login = tc.login.clone().fixup().expect("should work");
1272            if let Some(expected) = tc.fixedup_host {
1273                assert_eq!(login.origin, expected, "origin not fixed in {:#?}", tc);
1274            }
1275            assert_eq!(
1276                login.form_action_origin, tc.fixedup_form_action_origin,
1277                "form_action_origin not fixed in {:#?}",
1278                tc,
1279            );
1280            login.check_valid().unwrap_or_else(|e| {
1281                panic!("Fixup produces invalid record: {:#?}", (e, &tc, &login));
1282            });
1283            assert_eq!(
1284                login.clone().fixup().unwrap(),
1285                login,
1286                "fixup did not reach fixed point for testcase: {:#?}",
1287                tc,
1288            );
1289        }
1290    }
1291
1292    #[test]
1293    fn test_secure_fields_serde() {
1294        let sf = SecureLoginFields {
1295            username: "foo".into(),
1296            password: "pwd".into(),
1297        };
1298        assert_eq!(
1299            serde_json::to_string(&sf).unwrap(),
1300            r#"{"u":"foo","p":"pwd"}"#
1301        );
1302        let got: SecureLoginFields = serde_json::from_str(r#"{"u": "user", "p": "p"}"#).unwrap();
1303        let expected = SecureLoginFields {
1304            username: "user".into(),
1305            password: "p".into(),
1306        };
1307        assert_eq!(got, expected);
1308    }
1309}