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