Google's "Transfer accounts -> Export accounts" produces an otpauth-migration:// link wrapping a base64 protobuf that holds many accounts at once, and splits large exports across several QR codes. v0.1 rejected these outright; now they import. The protobuf is decoded by hand rather than pulling prost: the schema is four messages that have not changed since 2020, and the wire format needed is two types (varint, length-delimited). Unknown fields are skipped properly, so a future Google addition degrades rather than corrupting the parse. Two details in this format silently produce plausible-but-wrong codes if taken backwards, so both are pinned by tests: the `secret` field is RAW BYTES, not base32, and the payload carries NO period field -- every Google export is 30-second TOTP. - core/migration.rs: protobuf decode, lenient base64 (all four alphabet and padding spellings), issuer reconciliation between the `name` prefix and the dedicated `issuer` field, and batch metadata surfaced as "Part 1 of 2" - vault: add_many() with duplicate detection, persisting once per batch rather than once per account; duplicates match on secret AND naming, so keeping one secret under two labels stays possible - http-api: preview returns a list flagged with what is already stored; import takes the link plus selected indices and re-parses server-side, so secrets never travel out to the browser and back. /api/qr/decode now returns every payload in an image, not just the first - webui: multi-account import checklist with select all/none, per-entry algorithm and digit chips, already-present entries pre-unticked, and skipped entries named with their reason (HOTP, MD5) instead of silently dropped Verified end to end against real QR images: upload -> decode -> preview -> import, with the resulting codes cross-checked against an independent RFC 6238 implementation, including an 8-digit account. 124 tests (was 101). Co-Authored-By: Claude Opus 4.8 <[email protected]>
734 lines
25 KiB
Rust
734 lines
25 KiB
Rust
//! Google Authenticator export parsing (`otpauth-migration://offline?data=…`).
|
|
//!
|
|
//! The payload is a base64 protobuf holding many accounts at once. Google
|
|
//! splits large exports across several QR codes, each carrying `batch_index`
|
|
//! and `batch_size` so the user knows how many screens to scan.
|
|
//!
|
|
//! ## Why the protobuf is hand-decoded
|
|
//!
|
|
//! Pulling `prost` would mean either a `protoc` build dependency or a
|
|
//! generated file checked in, for a schema that is four messages long and has
|
|
//! not changed since 2020. The wire format we need is two wire types (varint
|
|
//! and length-delimited), so the reader below is short enough to audit.
|
|
//! Unknown fields are skipped properly, so a future Google addition won't
|
|
//! break parsing.
|
|
//!
|
|
//! Schema (Google Authenticator 5.10, reverse-engineered but stable):
|
|
//!
|
|
//! ```text
|
|
//! MigrationPayload { otp_parameters=1 (repeated), version=2,
|
|
//! batch_size=3, batch_index=4, batch_id=5 }
|
|
//! OtpParameters { secret=1 (bytes), name=2, issuer=3,
|
|
//! algorithm=4, digits=5, type=6, counter=7 }
|
|
//! Algorithm { UNSPECIFIED=0, SHA1=1, SHA256=2, SHA512=3, MD5=4 }
|
|
//! DigitCount { UNSPECIFIED=0, SIX=1, EIGHT=2 }
|
|
//! OtpType { UNSPECIFIED=0, HOTP=1, TOTP=2 }
|
|
//! ```
|
|
//!
|
|
//! Two traps worth naming, because both silently produce wrong codes:
|
|
//!
|
|
//! * **`secret` is raw bytes, not base32.** It has to be base32-encoded to
|
|
//! become the secret an `otpauth://` URI would carry.
|
|
//! * **There is no period field.** Google only ever exports 30-second TOTP,
|
|
//! so 30 is assumed rather than guessed at.
|
|
|
|
use crate::totp::{Algorithm, OtpAuth, Totp};
|
|
use crate::{Error, Result};
|
|
|
|
/// Google never exports a period; every entry is the 30-second default.
|
|
const ASSUMED_PERIOD: u64 = 30;
|
|
|
|
/// An account present in the export that we deliberately did not import.
|
|
#[derive(Debug, Clone)]
|
|
pub struct Skipped {
|
|
pub name: String,
|
|
pub reason: String,
|
|
}
|
|
|
|
/// One decoded export QR code.
|
|
#[derive(Debug, Clone, Default)]
|
|
pub struct ImportBatch {
|
|
pub accounts: Vec<OtpAuth>,
|
|
pub skipped: Vec<Skipped>,
|
|
/// 0-based index of this QR within the export, when present.
|
|
pub batch_index: Option<i32>,
|
|
/// Total number of QR codes in the export, when present.
|
|
pub batch_size: Option<i32>,
|
|
/// Identifies which export a QR belongs to, so codes from two different
|
|
/// export sessions aren't mistaken for parts of one.
|
|
pub batch_id: Option<i32>,
|
|
}
|
|
|
|
impl ImportBatch {
|
|
/// Human-readable "Part 2 of 3", when the export was split.
|
|
pub fn part_label(&self) -> Option<String> {
|
|
match (self.batch_index, self.batch_size) {
|
|
(Some(i), Some(n)) if n > 1 => Some(format!("Part {} of {n}", i + 1)),
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Is this a Google Authenticator export link?
|
|
pub fn is_migration_uri(uri: &str) -> bool {
|
|
uri.trim()
|
|
.to_ascii_lowercase()
|
|
.starts_with("otpauth-migration://")
|
|
}
|
|
|
|
/// Parse an `otpauth-migration://offline?data=…` link into its accounts.
|
|
pub fn parse_migration(uri: &str) -> Result<ImportBatch> {
|
|
let uri = uri.trim();
|
|
let parsed = url::Url::parse(uri)
|
|
.map_err(|e| Error::invalid(format!("not a valid export link: {e}")))?;
|
|
|
|
if !parsed.scheme().eq_ignore_ascii_case("otpauth-migration") {
|
|
return Err(Error::invalid(
|
|
"that is not a Google Authenticator export link",
|
|
));
|
|
}
|
|
|
|
// `url` percent-decodes query values for us. Google's base64 contains
|
|
// `+` and `/`, which arrive percent-encoded in a well-formed URI.
|
|
let data = parsed
|
|
.query_pairs()
|
|
.find(|(k, _)| k.eq_ignore_ascii_case("data"))
|
|
.map(|(_, v)| v.into_owned())
|
|
.ok_or_else(|| Error::invalid("the export link has no ?data= parameter"))?;
|
|
|
|
if data.trim().is_empty() {
|
|
return Err(Error::invalid("the export link's data parameter is empty"));
|
|
}
|
|
|
|
let raw = decode_base64_lenient(&data)?;
|
|
decode_payload(&raw)
|
|
}
|
|
|
|
/// Decode base64 across the variants that turn up in the wild.
|
|
///
|
|
/// Google emits standard-alphabet padded base64, but the link is often
|
|
/// copied through tools that swap in the URL-safe alphabet or strip padding.
|
|
/// Trying all four costs nothing and avoids an unhelpful failure on a link
|
|
/// that is perfectly recoverable.
|
|
fn decode_base64_lenient(s: &str) -> Result<Vec<u8>> {
|
|
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
|
|
use base64::Engine;
|
|
|
|
// Whitespace can be introduced by line-wrapping when a link is pasted.
|
|
let cleaned: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
|
|
|
// A macro rather than a slice of trait objects: base64's `Engine` is not
|
|
// dyn-compatible, and the alternatives are all zero-sized consts anyway.
|
|
macro_rules! try_decode {
|
|
($engine:expr) => {
|
|
if let Ok(bytes) = $engine.decode(&cleaned) {
|
|
if !bytes.is_empty() {
|
|
return Ok(bytes);
|
|
}
|
|
}
|
|
};
|
|
}
|
|
try_decode!(STANDARD);
|
|
try_decode!(STANDARD_NO_PAD);
|
|
try_decode!(URL_SAFE);
|
|
try_decode!(URL_SAFE_NO_PAD);
|
|
Err(Error::invalid(
|
|
"the export link's data is not valid base64 — copy the whole link, \
|
|
including everything after data=",
|
|
))
|
|
}
|
|
|
|
// ── Minimal protobuf reader ───────────────────────────────────────────────
|
|
|
|
struct Reader<'a> {
|
|
buf: &'a [u8],
|
|
pos: usize,
|
|
}
|
|
|
|
impl<'a> Reader<'a> {
|
|
fn new(buf: &'a [u8]) -> Self {
|
|
Self { buf, pos: 0 }
|
|
}
|
|
|
|
fn done(&self) -> bool {
|
|
self.pos >= self.buf.len()
|
|
}
|
|
|
|
fn varint(&mut self) -> Option<u64> {
|
|
let mut value: u64 = 0;
|
|
let mut shift = 0u32;
|
|
loop {
|
|
let byte = *self.buf.get(self.pos)?;
|
|
self.pos += 1;
|
|
// 10 groups of 7 bits is the most a u64 can hold; more than that
|
|
// is a malformed (or hostile) message rather than a big number.
|
|
if shift > 63 {
|
|
return None;
|
|
}
|
|
value |= u64::from(byte & 0x7f) << shift;
|
|
if byte & 0x80 == 0 {
|
|
return Some(value);
|
|
}
|
|
shift += 7;
|
|
}
|
|
}
|
|
|
|
/// Returns `(field_number, wire_type)`.
|
|
fn tag(&mut self) -> Option<(u32, u8)> {
|
|
let key = self.varint()?;
|
|
let field = u32::try_from(key >> 3).ok()?;
|
|
let wire = (key & 0x07) as u8;
|
|
if field == 0 {
|
|
return None; // field 0 is illegal; treat as corruption
|
|
}
|
|
Some((field, wire))
|
|
}
|
|
|
|
fn length_delimited(&mut self) -> Option<&'a [u8]> {
|
|
let len = usize::try_from(self.varint()?).ok()?;
|
|
let end = self.pos.checked_add(len)?;
|
|
let slice = self.buf.get(self.pos..end)?;
|
|
self.pos = end;
|
|
Some(slice)
|
|
}
|
|
|
|
/// Advance past a field we don't care about, so unknown additions to the
|
|
/// schema don't desynchronise the parse.
|
|
fn skip(&mut self, wire: u8) -> Option<()> {
|
|
match wire {
|
|
0 => {
|
|
self.varint()?;
|
|
}
|
|
1 => self.pos = self.pos.checked_add(8)?,
|
|
2 => {
|
|
self.length_delimited()?;
|
|
}
|
|
5 => self.pos = self.pos.checked_add(4)?,
|
|
// 3/4 are the deprecated start/end-group types, which this schema
|
|
// never uses. Anything else is corruption.
|
|
_ => return None,
|
|
}
|
|
if self.pos > self.buf.len() {
|
|
return None;
|
|
}
|
|
Some(())
|
|
}
|
|
}
|
|
|
|
fn corrupt() -> Error {
|
|
Error::invalid(
|
|
"the export data could not be decoded — re-export from Google \
|
|
Authenticator and scan the fresh QR code",
|
|
)
|
|
}
|
|
|
|
fn decode_payload(raw: &[u8]) -> Result<ImportBatch> {
|
|
let mut out = ImportBatch::default();
|
|
let mut r = Reader::new(raw);
|
|
|
|
while !r.done() {
|
|
let (field, wire) = r.tag().ok_or_else(corrupt)?;
|
|
match (field, wire) {
|
|
(1, 2) => {
|
|
let entry = r.length_delimited().ok_or_else(corrupt)?;
|
|
match decode_entry(entry) {
|
|
Ok(Some(account)) => out.accounts.push(account),
|
|
Ok(None) => {}
|
|
Err(skipped) => out.skipped.push(skipped),
|
|
}
|
|
}
|
|
(3, 0) => out.batch_size = r.varint().ok_or_else(corrupt)?.try_into().ok(),
|
|
(4, 0) => out.batch_index = r.varint().ok_or_else(corrupt)?.try_into().ok(),
|
|
(5, 0) => out.batch_id = r.varint().ok_or_else(corrupt)?.try_into().ok(),
|
|
// version (2) and anything Google adds later.
|
|
_ => r.skip(wire).ok_or_else(corrupt)?,
|
|
}
|
|
}
|
|
|
|
if out.accounts.is_empty() && out.skipped.is_empty() {
|
|
return Err(Error::invalid("that export link contains no accounts"));
|
|
}
|
|
Ok(out)
|
|
}
|
|
|
|
/// Decode one `OtpParameters`. `Err(Skipped)` means "present but not
|
|
/// importable", which the UI reports rather than silently dropping.
|
|
fn decode_entry(buf: &[u8]) -> std::result::Result<Option<OtpAuth>, Skipped> {
|
|
let mut secret: Vec<u8> = Vec::new();
|
|
let mut name = String::new();
|
|
let mut issuer = String::new();
|
|
let mut algorithm = Algorithm::Sha1;
|
|
let mut digits: u8 = 6;
|
|
let mut otp_type: u64 = 2; // default to TOTP when unspecified
|
|
let mut bad_algorithm: Option<u64> = None;
|
|
|
|
let mut r = Reader::new(buf);
|
|
while !r.done() {
|
|
let Some((field, wire)) = r.tag() else { break };
|
|
match (field, wire) {
|
|
(1, 2) => secret = r.length_delimited().unwrap_or_default().to_vec(),
|
|
(2, 2) => {
|
|
name =
|
|
String::from_utf8_lossy(r.length_delimited().unwrap_or_default()).into_owned();
|
|
}
|
|
(3, 2) => {
|
|
issuer =
|
|
String::from_utf8_lossy(r.length_delimited().unwrap_or_default()).into_owned();
|
|
}
|
|
(4, 0) => match r.varint().unwrap_or(1) {
|
|
0 | 1 => algorithm = Algorithm::Sha1, // unspecified means SHA1
|
|
2 => algorithm = Algorithm::Sha256,
|
|
3 => algorithm = Algorithm::Sha512,
|
|
other => bad_algorithm = Some(other), // MD5 and anything new
|
|
},
|
|
(5, 0) => {
|
|
digits = match r.varint().unwrap_or(1) {
|
|
2 => 8,
|
|
_ => 6, // unspecified and SIX both mean 6
|
|
};
|
|
}
|
|
(6, 0) => otp_type = r.varint().unwrap_or(2),
|
|
_ => {
|
|
if r.skip(wire).is_none() {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Split "Issuer:account", the same shape an otpauth:// label uses. The
|
|
// dedicated issuer field wins when both are present.
|
|
let (label_issuer, account) = match name.split_once(':') {
|
|
Some((i, a)) => (Some(i.trim().to_string()), a.trim().to_string()),
|
|
None => (None, name.trim().to_string()),
|
|
};
|
|
let issuer_final = if issuer.trim().is_empty() {
|
|
label_issuer.unwrap_or_default()
|
|
} else {
|
|
issuer.trim().to_string()
|
|
};
|
|
let display = if account.is_empty() && issuer_final.is_empty() {
|
|
"(unnamed)".to_string()
|
|
} else if account.is_empty() {
|
|
issuer_final.clone()
|
|
} else {
|
|
account.clone()
|
|
};
|
|
|
|
if otp_type == 1 {
|
|
return Err(Skipped {
|
|
name: display,
|
|
reason: "counter-based (HOTP) codes aren't supported".into(),
|
|
});
|
|
}
|
|
if let Some(alg) = bad_algorithm {
|
|
let which = if alg == 4 {
|
|
"MD5"
|
|
} else {
|
|
"an unknown algorithm"
|
|
};
|
|
return Err(Skipped {
|
|
name: display,
|
|
reason: format!("uses {which}, which isn't supported"),
|
|
});
|
|
}
|
|
if secret.is_empty() {
|
|
return Err(Skipped {
|
|
name: display,
|
|
reason: "has no secret".into(),
|
|
});
|
|
}
|
|
|
|
// The protobuf carries raw secret bytes; Totp expects the same, so no
|
|
// base32 round-trip is needed here (only for display/export).
|
|
match Totp::new(secret, algorithm, digits, ASSUMED_PERIOD) {
|
|
Ok(totp) => Ok(Some(OtpAuth {
|
|
totp,
|
|
issuer: if issuer_final.is_empty() {
|
|
account.clone()
|
|
} else {
|
|
issuer_final
|
|
},
|
|
label: account,
|
|
})),
|
|
Err(e) => Err(Skipped {
|
|
name: display,
|
|
reason: e.to_string(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
// ── Tests ─────────────────────────────────────────────────────────────────
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::totp::encode_secret;
|
|
|
|
// Minimal protobuf *encoder*, so these tests drive the parser with real
|
|
// wire bytes rather than a mock.
|
|
|
|
fn put_varint(v: u64, out: &mut Vec<u8>) {
|
|
let mut v = v;
|
|
loop {
|
|
let mut byte = (v & 0x7f) as u8;
|
|
v >>= 7;
|
|
if v != 0 {
|
|
byte |= 0x80;
|
|
}
|
|
out.push(byte);
|
|
if v == 0 {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn put_tag(field: u32, wire: u8, out: &mut Vec<u8>) {
|
|
put_varint((u64::from(field) << 3) | u64::from(wire), out);
|
|
}
|
|
|
|
fn put_bytes(field: u32, bytes: &[u8], out: &mut Vec<u8>) {
|
|
put_tag(field, 2, out);
|
|
put_varint(bytes.len() as u64, out);
|
|
out.extend_from_slice(bytes);
|
|
}
|
|
|
|
fn put_uint(field: u32, v: u64, out: &mut Vec<u8>) {
|
|
put_tag(field, 0, out);
|
|
put_varint(v, out);
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
struct Entry {
|
|
secret: Vec<u8>,
|
|
name: &'static str,
|
|
issuer: &'static str,
|
|
algorithm: u64,
|
|
digits: u64,
|
|
otp_type: u64,
|
|
}
|
|
|
|
impl Default for Entry {
|
|
fn default() -> Self {
|
|
Self {
|
|
secret: b"12345678901234567890".to_vec(),
|
|
name: "[email protected]",
|
|
issuer: "Cloudflare",
|
|
algorithm: 1, // SHA1
|
|
digits: 1, // SIX
|
|
otp_type: 2, // TOTP
|
|
}
|
|
}
|
|
}
|
|
|
|
fn encode_entry(e: &Entry) -> Vec<u8> {
|
|
let mut b = Vec::new();
|
|
put_bytes(1, &e.secret, &mut b);
|
|
put_bytes(2, e.name.as_bytes(), &mut b);
|
|
put_bytes(3, e.issuer.as_bytes(), &mut b);
|
|
put_uint(4, e.algorithm, &mut b);
|
|
put_uint(5, e.digits, &mut b);
|
|
put_uint(6, e.otp_type, &mut b);
|
|
b
|
|
}
|
|
|
|
fn encode_payload(entries: &[Entry], batch: Option<(i32, i32, i32)>) -> Vec<u8> {
|
|
let mut b = Vec::new();
|
|
for e in entries {
|
|
put_bytes(1, &encode_entry(e), &mut b);
|
|
}
|
|
put_uint(2, 1, &mut b); // version
|
|
if let Some((size, index, id)) = batch {
|
|
put_uint(3, size as u64, &mut b);
|
|
put_uint(4, index as u64, &mut b);
|
|
put_uint(5, id as u64, &mut b);
|
|
}
|
|
b
|
|
}
|
|
|
|
/// Build a link the way Google does: standard base64, percent-encoded
|
|
/// into the query string.
|
|
fn make_uri(payload: &[u8]) -> String {
|
|
use base64::Engine;
|
|
let b64 = base64::engine::general_purpose::STANDARD.encode(payload);
|
|
let escaped = b64
|
|
.replace('+', "%2B")
|
|
.replace('/', "%2F")
|
|
.replace('=', "%3D");
|
|
format!("otpauth-migration://offline?data={escaped}")
|
|
}
|
|
|
|
fn uri_for(entries: &[Entry]) -> String {
|
|
make_uri(&encode_payload(entries, None))
|
|
}
|
|
|
|
#[test]
|
|
fn detects_migration_links() {
|
|
assert!(is_migration_uri("otpauth-migration://offline?data=abc"));
|
|
assert!(is_migration_uri("OTPAUTH-MIGRATION://offline?data=abc"));
|
|
assert!(!is_migration_uri("otpauth://totp/X?secret=A"));
|
|
}
|
|
|
|
#[test]
|
|
fn imports_a_single_account() {
|
|
let b = parse_migration(&uri_for(&[Entry::default()])).unwrap();
|
|
assert_eq!(b.accounts.len(), 1);
|
|
assert!(b.skipped.is_empty());
|
|
let a = &b.accounts[0];
|
|
assert_eq!(a.issuer, "Cloudflare");
|
|
assert_eq!(a.label, "[email protected]");
|
|
assert_eq!(a.totp.digits, 6);
|
|
assert_eq!(a.totp.period, 30, "Google exports are always 30s");
|
|
assert_eq!(a.totp.algorithm, Algorithm::Sha1);
|
|
}
|
|
|
|
#[test]
|
|
fn secret_is_raw_bytes_not_base32() {
|
|
// The single most dangerous trap: treating the protobuf secret as if
|
|
// it were already base32 yields plausible-looking but wrong codes.
|
|
// The RFC 6238 vector secret is ASCII "12345678901234567890".
|
|
let b = parse_migration(&uri_for(&[Entry::default()])).unwrap();
|
|
let totp = &b.accounts[0].totp;
|
|
assert_eq!(totp.secret, b"12345678901234567890");
|
|
// And it base32-encodes to the well-known test value.
|
|
assert_eq!(
|
|
encode_secret(&totp.secret),
|
|
"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
|
|
);
|
|
// Which means it produces the official RFC 6238 code at t=59.
|
|
assert_eq!(totp.code_at(59), "287082");
|
|
}
|
|
|
|
#[test]
|
|
fn imports_several_accounts_from_one_qr() {
|
|
let entries = vec![
|
|
Entry {
|
|
name: "[email protected]",
|
|
issuer: "Cloudflare",
|
|
..Entry::default()
|
|
},
|
|
Entry {
|
|
name: "[email protected]",
|
|
issuer: "Plex",
|
|
..Entry::default()
|
|
},
|
|
Entry {
|
|
name: "[email protected]",
|
|
issuer: "Ubisoft",
|
|
..Entry::default()
|
|
},
|
|
];
|
|
let b = parse_migration(&uri_for(&entries)).unwrap();
|
|
assert_eq!(b.accounts.len(), 3);
|
|
let issuers: Vec<_> = b.accounts.iter().map(|a| a.issuer.as_str()).collect();
|
|
assert_eq!(issuers, ["Cloudflare", "Plex", "Ubisoft"]);
|
|
}
|
|
|
|
#[test]
|
|
fn reports_batch_position() {
|
|
let uri = make_uri(&encode_payload(&[Entry::default()], Some((3, 1, 42))));
|
|
let b = parse_migration(&uri).unwrap();
|
|
assert_eq!(b.batch_size, Some(3));
|
|
assert_eq!(b.batch_index, Some(1));
|
|
assert_eq!(b.batch_id, Some(42));
|
|
// batch_index is 0-based; humans count from one.
|
|
assert_eq!(b.part_label().as_deref(), Some("Part 2 of 3"));
|
|
|
|
// A single-QR export shouldn't claim to be part of a series.
|
|
let solo = parse_migration(&uri_for(&[Entry::default()])).unwrap();
|
|
assert!(solo.part_label().is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn honours_algorithm_and_digit_variants() {
|
|
for (code, want) in [(2, Algorithm::Sha256), (3, Algorithm::Sha512)] {
|
|
let e = Entry {
|
|
algorithm: code,
|
|
..Entry::default()
|
|
};
|
|
let b = parse_migration(&uri_for(&[e])).unwrap();
|
|
assert_eq!(b.accounts[0].totp.algorithm, want);
|
|
}
|
|
let e = Entry {
|
|
digits: 2,
|
|
..Entry::default()
|
|
}; // EIGHT
|
|
let b = parse_migration(&uri_for(&[e])).unwrap();
|
|
assert_eq!(b.accounts[0].totp.digits, 8);
|
|
}
|
|
|
|
#[test]
|
|
fn unspecified_enums_fall_back_to_the_common_defaults() {
|
|
let e = Entry {
|
|
algorithm: 0,
|
|
digits: 0,
|
|
otp_type: 0,
|
|
..Entry::default()
|
|
};
|
|
let b = parse_migration(&uri_for(&[e])).unwrap();
|
|
assert_eq!(b.accounts[0].totp.algorithm, Algorithm::Sha1);
|
|
assert_eq!(b.accounts[0].totp.digits, 6);
|
|
}
|
|
|
|
#[test]
|
|
fn skips_unsupported_entries_but_keeps_the_rest() {
|
|
let entries = vec![
|
|
Entry {
|
|
name: "[email protected]",
|
|
..Entry::default()
|
|
},
|
|
Entry {
|
|
name: "[email protected]",
|
|
otp_type: 1,
|
|
..Entry::default()
|
|
}, // HOTP
|
|
Entry {
|
|
name: "[email protected]",
|
|
algorithm: 4,
|
|
..Entry::default()
|
|
}, // MD5
|
|
Entry {
|
|
name: "[email protected]",
|
|
secret: vec![],
|
|
..Entry::default()
|
|
},
|
|
];
|
|
let b = parse_migration(&uri_for(&entries)).unwrap();
|
|
|
|
// One good account survives; the other three are reported, not dropped.
|
|
assert_eq!(b.accounts.len(), 1);
|
|
assert_eq!(b.accounts[0].label, "[email protected]");
|
|
assert_eq!(b.skipped.len(), 3);
|
|
|
|
let reason = |n: &str| {
|
|
b.skipped
|
|
.iter()
|
|
.find(|s| s.name == n)
|
|
.map(|s| s.reason.clone())
|
|
.unwrap()
|
|
};
|
|
assert!(reason("[email protected]").contains("HOTP"));
|
|
assert!(reason("[email protected]").contains("MD5"));
|
|
assert!(reason("[email protected]").contains("no secret"));
|
|
}
|
|
|
|
#[test]
|
|
fn name_may_carry_the_issuer_prefix() {
|
|
let e = Entry {
|
|
name: "Cloudflare:[email protected]",
|
|
issuer: "",
|
|
..Entry::default()
|
|
};
|
|
let b = parse_migration(&uri_for(&[e])).unwrap();
|
|
assert_eq!(b.accounts[0].issuer, "Cloudflare");
|
|
assert_eq!(b.accounts[0].label, "[email protected]");
|
|
}
|
|
|
|
#[test]
|
|
fn issuer_field_wins_over_the_name_prefix() {
|
|
let e = Entry {
|
|
name: "Stale:[email protected]",
|
|
issuer: "Microsoft",
|
|
..Entry::default()
|
|
};
|
|
let b = parse_migration(&uri_for(&[e])).unwrap();
|
|
assert_eq!(b.accounts[0].issuer, "Microsoft");
|
|
assert_eq!(b.accounts[0].label, "[email protected]");
|
|
}
|
|
|
|
#[test]
|
|
fn accepts_every_base64_variant() {
|
|
use base64::engine::general_purpose::{
|
|
STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD,
|
|
};
|
|
use base64::Engine;
|
|
// A payload whose base64 is guaranteed to contain +/ (or -_).
|
|
let entries: Vec<Entry> = (0..4)
|
|
.map(|i| Entry {
|
|
secret: vec![0xfb, 0xff, 0xbf, i],
|
|
..Entry::default()
|
|
})
|
|
.collect();
|
|
let raw = encode_payload(&entries, None);
|
|
|
|
for (name, encoded) in [
|
|
("standard", STANDARD.encode(&raw)),
|
|
("standard-nopad", STANDARD_NO_PAD.encode(&raw)),
|
|
("urlsafe", URL_SAFE.encode(&raw)),
|
|
("urlsafe-nopad", URL_SAFE_NO_PAD.encode(&raw)),
|
|
] {
|
|
let escaped = encoded
|
|
.replace('+', "%2B")
|
|
.replace('/', "%2F")
|
|
.replace('=', "%3D");
|
|
let uri = format!("otpauth-migration://offline?data={escaped}");
|
|
let b = parse_migration(&uri).unwrap_or_else(|e| panic!("{name} should decode: {e}"));
|
|
assert_eq!(b.accounts.len(), 4, "{name}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_fields_do_not_break_parsing() {
|
|
// Forward compatibility: if Google adds a field, we must skip it
|
|
// rather than desynchronise and mangle everything after it.
|
|
let mut entry = encode_entry(&Entry::default());
|
|
put_bytes(99, b"some future string", &mut entry);
|
|
put_uint(98, 1234, &mut entry);
|
|
|
|
let mut payload = Vec::new();
|
|
put_bytes(1, &entry, &mut payload);
|
|
put_bytes(77, b"future payload field", &mut payload);
|
|
put_uint(76, 5, &mut payload);
|
|
|
|
let b = parse_migration(&make_uri(&payload)).unwrap();
|
|
assert_eq!(b.accounts.len(), 1);
|
|
assert_eq!(b.accounts[0].issuer, "Cloudflare");
|
|
}
|
|
|
|
#[test]
|
|
fn rejects_malformed_input_clearly() {
|
|
assert!(parse_migration("otpauth-migration://offline").is_err());
|
|
assert!(parse_migration("otpauth-migration://offline?data=").is_err());
|
|
assert!(parse_migration("otpauth-migration://offline?data=!!!not base64!!!").is_err());
|
|
assert!(parse_migration("otpauth://totp/X?secret=JBSWY3DPEHPK3PXP").is_err());
|
|
assert!(parse_migration("nonsense").is_err());
|
|
|
|
// Truncated protobuf: a length prefix that runs past the buffer.
|
|
let uri = make_uri(&[0x0a, 0x7f, 0x01, 0x02]);
|
|
assert!(parse_migration(&uri).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn an_export_with_no_accounts_is_an_error() {
|
|
// Version field only, no entries.
|
|
let mut payload = Vec::new();
|
|
put_uint(2, 1, &mut payload);
|
|
let e = parse_migration(&make_uri(&payload))
|
|
.unwrap_err()
|
|
.to_string();
|
|
assert!(e.contains("no accounts"), "got: {e}");
|
|
}
|
|
|
|
#[test]
|
|
fn a_large_export_round_trips() {
|
|
// Google splits at roughly ten per QR; make sure nothing chokes on a
|
|
// full batch, and that every secret survives intact.
|
|
let entries: Vec<Entry> = (0..10)
|
|
.map(|i| Entry {
|
|
secret: vec![i; 20],
|
|
name: "[email protected]",
|
|
..Entry::default()
|
|
})
|
|
.collect();
|
|
let b = parse_migration(&uri_for(&entries)).unwrap();
|
|
assert_eq!(b.accounts.len(), 10);
|
|
for (i, a) in b.accounts.iter().enumerate() {
|
|
assert_eq!(
|
|
a.totp.secret,
|
|
vec![i as u8; 20],
|
|
"entry {i} secret corrupted"
|
|
);
|
|
}
|
|
}
|
|
}
|