use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
use crate::error::{LinkError, Result};
use crate::noise::MAX_PLAINTEXT;
pub const MAX_ID_LEN: usize = 64;
pub const MAX_ORIGIN_LEN: usize = 2_048;
pub const MAX_TEXT_LEN: usize = 1_024;
pub const MAX_PASSWORD_LEN: usize = 4_096;
pub const MAX_CANDIDATES: usize = 200;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MatchTier {
Exact,
Registrable,
Suffix,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Candidate {
pub id: String,
pub title: String,
pub username: String,
pub staged: bool,
pub tier: MatchTier,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SaveKind {
New,
PasswordChanged,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SaveOutcome {
Staged,
JournalFull,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum DenyReason {
UserDenied,
TimedOut,
AutofillOff,
OpenApp,
RateLimited,
Busy,
Retry,
NoGrant,
Invalid,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum IndexState {
Ready,
Missing,
Expired,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ByeReason {
Unpaired,
AutofillOff,
ShuttingDown,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(
tag = "type",
rename_all = "camelCase",
rename_all_fields = "camelCase"
)]
pub enum Message {
Query {
id: String,
frame_origin: String,
top_origin: String,
browser: String,
},
Pending { id: String },
Candidates {
id: String,
grant_ttl_secs: u32,
candidates: Vec<Candidate>,
},
Reveal { id: String, item: String },
Secret {
id: String,
username: String,
password: Zeroizing<String>,
},
Save {
id: String,
frame_origin: String,
username: String,
password: Zeroizing<String>,
kind: SaveKind,
},
Saved { id: String, outcome: SaveOutcome },
Denied { id: String, reason: DenyReason },
Cancel { id: String },
Status {
autofill_on: bool,
notifications_on: bool,
index: IndexState,
},
Ping,
Pong,
Bye { reason: ByeReason },
}
impl Message {
pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>> {
self.validate()?;
let bytes = Zeroizing::new(
serde_json::to_vec(self).map_err(|e| LinkError::BadMessage(e.to_string()))?,
);
if bytes.len() > MAX_PLAINTEXT {
return Err(LinkError::TooLarge);
}
Ok(bytes)
}
pub fn decode(bytes: &[u8]) -> Result<Message> {
if bytes.len() > MAX_PLAINTEXT {
return Err(LinkError::TooLarge);
}
let message: Message = serde_json::from_slice(bytes).map_err(|e| {
LinkError::BadMessage(format!("{:?} at column {}", e.classify(), e.column()))
})?;
message.validate()?;
Ok(message)
}
pub fn request_id(&self) -> Option<&str> {
match self {
Message::Query { id, .. }
| Message::Pending { id }
| Message::Candidates { id, .. }
| Message::Reveal { id, .. }
| Message::Secret { id, .. }
| Message::Save { id, .. }
| Message::Saved { id, .. }
| Message::Denied { id, .. }
| Message::Cancel { id } => Some(id),
Message::Status { .. } | Message::Ping | Message::Pong | Message::Bye { .. } => None,
}
}
pub fn validate(&self) -> Result<()> {
if let Some(id) = self.request_id() {
check_id(id)?;
}
match self {
Message::Query {
frame_origin,
top_origin,
browser,
..
} => {
check_origin(frame_origin)?;
check_origin(top_origin)?;
check_text(browser, "browser")?;
}
Message::Candidates { candidates, .. } => {
if candidates.len() > MAX_CANDIDATES {
return Err(LinkError::BadMessage("too many candidates".into()));
}
for c in candidates {
check_nonempty(&c.id, MAX_ID_LEN, "candidate id")?;
check_text(&c.title, "title")?;
check_text(&c.username, "username")?;
}
}
Message::Reveal { item, .. } => check_nonempty(item, MAX_ID_LEN, "item")?,
Message::Secret {
username, password, ..
} => {
check_text(username, "username")?;
check_password(password)?;
}
Message::Save {
frame_origin,
username,
password,
..
} => {
check_origin(frame_origin)?;
check_text(username, "username")?;
check_password(password)?;
if password.is_empty() {
return Err(LinkError::BadMessage("empty password".into()));
}
}
_ => {}
}
Ok(())
}
}
fn check_id(id: &str) -> Result<()> {
check_nonempty(id, MAX_ID_LEN, "id")
}
fn check_nonempty(value: &str, max: usize, what: &str) -> Result<()> {
if value.is_empty() || value.len() > max {
return Err(LinkError::BadMessage(format!("{what} length")));
}
Ok(())
}
fn check_text(value: &str, what: &str) -> Result<()> {
if value.len() > MAX_TEXT_LEN {
return Err(LinkError::BadMessage(format!("{what} too long")));
}
Ok(())
}
fn check_password(value: &str) -> Result<()> {
if value.len() > MAX_PASSWORD_LEN {
return Err(LinkError::BadMessage("password too long".into()));
}
Ok(())
}
fn check_origin(value: &str) -> Result<()> {
check_nonempty(value, MAX_ORIGIN_LEN, "origin")?;
let Some((scheme, rest)) = value.split_once("://") else {
return Err(LinkError::BadMessage("origin without scheme".into()));
};
let scheme_ok = !scheme.is_empty()
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'));
if !scheme_ok || rest.is_empty() || rest.contains(['/', '?', '#', '@']) {
return Err(LinkError::BadMessage("not an origin".into()));
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn secret() -> Message {
Message::Secret {
id: "r1".into(),
username: "anna".into(),
password: Zeroizing::new("hunter2".into()),
}
}
fn all_messages() -> Vec<Message> {
vec![
Message::Query {
id: "r1".into(),
frame_origin: "https://login.example.com".into(),
top_origin: "https://example.com".into(),
browser: "Chrome".into(),
},
Message::Pending { id: "r1".into() },
Message::Candidates {
id: "r1".into(),
grant_ttl_secs: 60,
candidates: vec![Candidate {
id: "item-1".into(),
title: "Example".into(),
username: "anna".into(),
staged: false,
tier: MatchTier::Registrable,
}],
},
Message::Reveal {
id: "r1".into(),
item: "item-1".into(),
},
secret(),
Message::Save {
id: "r2".into(),
frame_origin: "https://example.com:8443".into(),
username: "anna".into(),
password: Zeroizing::new("new pass".into()),
kind: SaveKind::PasswordChanged,
},
Message::Saved {
id: "r2".into(),
outcome: SaveOutcome::JournalFull,
},
Message::Denied {
id: "r3".into(),
reason: DenyReason::NoGrant,
},
Message::Cancel { id: "r3".into() },
Message::Status {
autofill_on: true,
notifications_on: false,
index: IndexState::Expired,
},
Message::Ping,
Message::Pong,
Message::Bye {
reason: ByeReason::AutofillOff,
},
]
}
#[test]
fn every_message_round_trips() {
for m in all_messages() {
let bytes = m.encode().unwrap();
assert_eq!(Message::decode(&bytes).unwrap(), m);
}
}
#[test]
fn wire_format_is_camel_case_with_a_type_tag() {
let bytes = Message::Query {
id: "r1".into(),
frame_origin: "https://a.example".into(),
top_origin: "https://a.example".into(),
browser: "Firefox".into(),
}
.encode()
.unwrap();
let text = std::str::from_utf8(&bytes).unwrap();
assert!(text.contains(r#""type":"query""#), "{text}");
assert!(
text.contains(r#""frameOrigin":"https://a.example""#),
"{text}"
);
let ping = Message::Ping.encode().unwrap();
assert_eq!(ping.as_slice(), br#"{"type":"ping"}"#);
}
#[test]
fn unknown_type_is_an_error_and_unknown_fields_are_ignored() {
assert!(Message::decode(br#"{"type":"teleport","id":"x"}"#).is_err());
let m = Message::decode(br#"{"type":"pending","id":"x","future":1}"#).unwrap();
assert_eq!(m, Message::Pending { id: "x".into() });
}
#[test]
fn origins_are_checked() {
let query = |origin: &str| Message::Query {
id: "r".into(),
frame_origin: origin.into(),
top_origin: "https://ok.example".into(),
browser: String::new(),
};
for good in [
"https://example.com",
"http://localhost:3000",
"https://[::1]:8080",
] {
assert!(query(good).validate().is_ok(), "{good}");
}
for bad in [
"",
"example.com",
"https://",
"https://example.com/login",
"https://example.com?token=1",
"https://example.com#x",
"https://user@example.com",
] {
assert!(query(bad).validate().is_err(), "{bad}");
}
}
#[test]
fn limits_are_enforced_on_decode() {
let long_id = format!(
r#"{{"type":"pending","id":"{}"}}"#,
"x".repeat(MAX_ID_LEN + 1)
);
assert!(Message::decode(long_id.as_bytes()).is_err());
assert!(Message::decode(br#"{"type":"pending","id":""}"#).is_err());
let many = Message::Candidates {
id: "r".into(),
grant_ttl_secs: 60,
candidates: vec![
Candidate {
id: "i".into(),
title: String::new(),
username: String::new(),
staged: false,
tier: MatchTier::Exact,
};
MAX_CANDIDATES + 1
],
};
assert!(many.encode().is_err());
let long_password = Message::Secret {
id: "r".into(),
username: String::new(),
password: Zeroizing::new("p".repeat(MAX_PASSWORD_LEN + 1)),
};
assert!(long_password.encode().is_err());
}
#[test]
fn empty_save_password_is_refused() {
let m = Message::Save {
id: "r".into(),
frame_origin: "https://example.com".into(),
username: "a".into(),
password: Zeroizing::new(String::new()),
kind: SaveKind::New,
};
assert!(m.validate().is_err());
}
#[test]
fn decode_errors_do_not_quote_input() {
let bad = br#"{"type":"secret","id":"r","username":"a","password":"hunter2""#;
let error = Message::decode(bad).unwrap_err().to_string();
assert!(!error.contains("hunter2"), "{error}");
}
#[test]
fn request_ids() {
assert_eq!(secret().request_id(), Some("r1"));
assert_eq!(Message::Ping.request_id(), None);
}
}