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