Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Add Auth code viewing and verify enrollment codes

Manav Rathi451620bc43f1
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 7a4bffa96c..bdc22e1522 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2492,6 +2492,7 @@ dependencies = [
"serde_json",
"thiserror 2.0.21",
"url",
+ "urlencoding",
"uuid",
"zeroize",
]
@@ -2611,6 +2612,7 @@ dependencies = [
"futures-core",
"getrandom 0.4.3",
"gloo-timers",
+ "hmac 0.13.0",
"hpke",
"log",
"md-5 0.11.0",
@@ -2620,6 +2622,8 @@ dependencies = [
"salsa20",
"serde",
"serde_json",
+ "sha1 0.11.0",
+ "sha2 0.11.0",
"subtle",
"thiserror 2.0.21",
"tokio",
@@ -3040,9 +3044,7 @@ dependencies = [
"dirs",
"ente-accounts",
"ente-core",
- "hmac 0.13.0",
"postgresql_embedded",
- "sha1 0.11.0",
"tokio",
"uuid",
]
diff --git a/rust/apps/cli-next/src/account.rs b/rust/apps/cli-next/src/account.rs
index ec2f10f99d..e1fa3e39de 100644
--- a/rust/apps/cli-next/src/account.rs
+++ b/rust/apps/cli-next/src/account.rs
@@ -316,17 +316,28 @@ pub async fn totp(
writeln!(std::io::stdout(), "{}", secret.as_str()).map_err(Into::into)
};
}
- let code = Zeroizing::new(match input {
- Some(mut input) => std::mem::take(&mut input.totp),
- None => {
- eprintln!("Add this secret to your authenticator: {}", secret.as_str());
- Password::new()
- .with_prompt("Authenticator code")
- .interact_on(&Term::stderr())?
- }
- });
let setup = TwoFactorSetup::from_secret(secret.to_string(), &account.identity.recovery_key);
- setup.enable(&client, &code).await?;
+ if let Some(input) = input {
+ setup.enable(&client, &input.totp).await?;
+ } else {
+ eprintln!("Add this secret to your authenticator: {}", secret.as_str());
+ loop {
+ let code = Zeroizing::new(
+ Password::new()
+ .with_prompt("Authenticator code")
+ .interact_on(&Term::stderr())?,
+ );
+ match setup.enable(&client, &code).await {
+ Err(ente_accounts::Error::IncorrectTotp) => {
+ eprintln!("Incorrect authenticator code. Try again.")
+ }
+ result => {
+ result?;
+ break;
+ }
+ }
+ }
+ }
output::action(
options.json,
&json!({"enabled": true}),
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rs
index 41b975ba80..63fe5ec133 100644
--- a/rust/apps/cli-next/src/args.rs
+++ b/rust/apps/cli-next/src/args.rs
@@ -14,8 +14,10 @@ use serde::{Deserialize, Serialize};
ente-cli-next photos album list
ente-cli-next photos file list --album <ID>
ente-cli-next photos export <DIR>
-Auth backups:
+Auth:
ente-cli-next account login --app auth
+ ente-cli-next auth code list
+ ente-cli-next auth code view <CODE>
ente-cli-next auth export <DIR>
Paste:
ente-cli-next paste create --input <PATH>
@@ -229,6 +231,11 @@ With --json: {\"text\": \"...\"}. --raw affects plain terminal output only. Requ
pub enum AuthCommand {
#[command(about = "Make an authenticated API request", after_help = API_HELP)]
Api(ApiArgs),
+ #[command(about = "Find saved Auth codes and show their current values")]
+ Code {
+ #[command(subcommand)]
+ command: CodeCommand,
+ },
#[command(about = "Export your Auth codes; encrypted by default")]
#[command(
after_long_help = "Refreshes Auth data first; --offline uses previously synced data.
@@ -255,6 +262,54 @@ Writes readable URI lines to stdout, or a new --output file. --json only formats
},
}
+#[derive(Subcommand)]
+pub enum CodeCommand {
+ #[command(about = "List saved codes without their secrets or current values")]
+ #[command(
+ after_long_help = "Refreshes Auth data first; --offline uses previously synced data.
+Search matches an ID, a displayed name, or words across issuer and account name, ignoring case.
+Codes in Trash are not listed.
+JSON fields: id, name, issuer, accountName, type (totp, hotp or steam)."
+ )]
+ List {
+ #[arg(
+ long,
+ value_name = "TEXT",
+ help = "Find codes by ID, displayed name or search words",
+ value_parser = nonempty_query
+ )]
+ search: Option<String>,
+ #[command(flatten)]
+ list: ListArgs,
+ },
+ #[command(about = "Show one current TOTP or Steam code and its expiry")]
+ #[command(
+ after_long_help = "Refreshes Auth data first; --offline uses previously synced data.
+An ID selects exactly. Otherwise match a name shown by list, or search words across issuer and account name.
+Matching ignores case, and every search word must occur in either field.
+Several matches fail and list candidates; narrow the search or use an ID.
+Quote queries containing spaces.
+A code in Trash must be restored in Ente Auth first.
+JSON fields: id, name, issuer, accountName, type, otp, validUntil (UTC).
+HOTP values are not supported yet."
+ )]
+ View {
+ #[arg(
+ help = "Code ID, displayed name or search words",
+ value_parser = nonempty_query
+ )]
+ code: String,
+ },
+}
+
+fn nonempty_query(query: &str) -> Result<String, String> {
+ if query.trim().is_empty() {
+ Err("supply a code ID or search text".into())
+ } else {
+ Ok(query.to_owned())
+ }
+}
+
#[derive(Args)]
pub struct AuthExportArgs {
#[arg(
diff --git a/rust/apps/cli-next/src/auth/code.rs b/rust/apps/cli-next/src/auth/code.rs
new file mode 100644
index 0000000000..be6376287d
--- /dev/null
+++ b/rust/apps/cli-next/src/auth/code.rs
@@ -0,0 +1,176 @@
+use std::io::Write;
+
+use anyhow::{Context, Result, ensure};
+use chrono::{DateTime, SecondsFormat, Utc};
+use ente_auth::code::Code;
+use serde::Serialize;
+use uuid::Uuid;
+
+use super::replica;
+use crate::{
+ api,
+ args::{App, CodeCommand, Options},
+ db, home, output,
+};
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Summary {
+ id: String,
+ name: String,
+ issuer: String,
+ account_name: String,
+ #[serde(rename = "type")]
+ kind: &'static str,
+}
+
+impl Summary {
+ fn new(id: String, code: &Code) -> Self {
+ Self {
+ id,
+ name: code.name(),
+ issuer: code.issuer.clone(),
+ account_name: code.account_name.clone(),
+ kind: code.kind.as_str(),
+ }
+ }
+}
+
+#[derive(Default)]
+struct Failures {
+ count: usize,
+ ids: Vec<String>,
+}
+
+impl Failures {
+ fn record(&mut self, id: String) {
+ self.count += 1;
+ if self.ids.len() < 10 {
+ self.ids.push(id);
+ }
+ }
+
+ fn check(&self) -> Result<()> {
+ ensure!(
+ self.count == 0,
+ "{} unreadable Auth code{} (IDs: {})",
+ self.count,
+ if self.count == 1 { "" } else { "s" },
+ self.ids.join(", ")
+ );
+ Ok(())
+ }
+}
+
+pub async fn run(command: CodeCommand, selected: Option<&str>, options: &Options) -> Result<()> {
+ let found = {
+ let (account, home) = home::open_account(selected, !options.offline)?;
+ let session = api::session(&account, App::Auth)?;
+ let mut db = db::open(&home.path, &account.db_key, !options.offline)?;
+ if !options.offline {
+ replica::refresh(&mut db, &session).await?;
+ }
+ let query = match &command {
+ CodeCommand::List { search, .. } => search.as_deref(),
+ CodeCommand::View { code } => Some(code.as_str()),
+ };
+ let id = query.and_then(|query| Uuid::parse_str(query).ok());
+ let mut failures = Failures::default();
+ replica::read(&db, &session, id, |records| {
+ let codes = records.filter_map(|record| {
+ let (code_id, record) = match record {
+ Ok(record) => record,
+ Err(error) => return Some(Err(error)),
+ };
+ let Ok(code) = record.and_then(|line| Code::from_uri(&line)) else {
+ failures.record(code_id);
+ return None;
+ };
+ if code.trashed {
+ return if id.is_some() && matches!(command, CodeCommand::View { .. }) {
+ Some(Err(anyhow::anyhow!(
+ "code {code_id} is in Trash; restore it in Ente Auth"
+ )))
+ } else {
+ None
+ };
+ }
+ (id.is_some() || query.is_none_or(|query| code.matches(query)))
+ .then_some(Ok((code_id, code)))
+ });
+ match &command {
+ CodeCommand::List { list, .. } => {
+ output::list(
+ codes.map(|row| row.map(|(id, code)| Summary::new(id, &code))),
+ list,
+ options.json,
+ ["ID", "NAME", "TYPE"],
+ "No codes.",
+ |code| {
+ [
+ code.id,
+ output::escape_controls(&code.name),
+ code.kind.into(),
+ ]
+ },
+ )?;
+ failures.check().context("Auth code list is incomplete")?;
+ Ok(None)
+ }
+ CodeCommand::View { code: selector } => {
+ let candidates = codes
+ .take(output::MAX_CANDIDATES + 1)
+ .collect::<Result<Vec<_>>>()?;
+ failures.check().with_context(|| {
+ if id.is_some() {
+ format!("cannot read code {selector:?}")
+ } else {
+ format!("cannot resolve code {selector:?}; select a known code ID")
+ }
+ })?;
+ output::select(
+ candidates,
+ selector,
+ "code",
+ "Narrow the search or use an ID.",
+ |(id, code)| (id.clone(), code.name()),
+ )
+ .map(Some)
+ }
+ }
+ })?
+ };
+ let Some((id, code)) = found else {
+ return Ok(());
+ };
+ let time =
+ u64::try_from(Utc::now().timestamp()).context("system clock is before the Unix epoch")?;
+ let (otp, valid_until) = code
+ .generate(time)
+ .with_context(|| format!("cannot generate code {id}"))?;
+ let valid_until = DateTime::from_timestamp(i64::try_from(valid_until)?, 0)
+ .context("code expiry is outside the supported range")?
+ .to_rfc3339_opts(SecondsFormat::Secs, true);
+ if options.json {
+ #[derive(Serialize)]
+ #[serde(rename_all = "camelCase")]
+ struct View {
+ #[serde(flatten)]
+ code: Summary,
+ otp: String,
+ valid_until: String,
+ }
+ output::json(&View {
+ code: Summary::new(id, &code),
+ otp,
+ valid_until,
+ })
+ } else {
+ writeln!(
+ std::io::stdout(),
+ "{}\n{otp}\nValid until {valid_until}",
+ output::escape_controls(&code.name())
+ )
+ .map_err(Into::into)
+ }
+}
diff --git a/rust/apps/cli-next/src/auth/mod.rs b/rust/apps/cli-next/src/auth/mod.rs
index ec086e8514..8bd57b9e38 100644
--- a/rust/apps/cli-next/src/auth/mod.rs
+++ b/rust/apps/cli-next/src/auth/mod.rs
@@ -1,3 +1,4 @@
+mod code;
mod output;
pub mod replica;
@@ -18,6 +19,7 @@ use output::Destination;
pub async fn run(command: AuthCommand, selected: Option<&str>, options: &Options) -> Result<()> {
match command {
AuthCommand::Api(args) => api::run(App::Auth, args, selected, options).await,
+ AuthCommand::Code { command } => code::run(command, selected, options).await,
AuthCommand::Export(args) => export(args, selected, options).await,
AuthCommand::Decrypt { input, output } => {
let destination = Destination::file(output.unwrap_or_else(|| PathBuf::from("-")));
diff --git a/rust/apps/cli-next/src/auth/replica.rs b/rust/apps/cli-next/src/auth/replica.rs
index f5f7568499..3f6009724c 100644
--- a/rust/apps/cli-next/src/auth/replica.rs
+++ b/rust/apps/cli-next/src/auth/replica.rs
@@ -1,9 +1,10 @@
use anyhow::{Context, Result, ensure};
use ente_auth::{WrappedKey, record};
use ente_core::Session;
+use uuid::Uuid;
use zeroize::Zeroizing;
-use crate::core_db::{Db, OptionalExtension, params};
+use crate::core_db::{Db, OptionalExtension, params, params_from_iter};
pub const SCHEMA: &str = "
CREATE TABLE auth_sync (
@@ -113,37 +114,23 @@ pub async fn refresh(db: &mut Db, session: &Session) -> Result<()> {
}
ensure!(
next > cursor,
- "Auth diff timestamp boundary did not advance; no new backup was written"
+ "Auth diff timestamp boundary did not advance"
);
cursor = next;
}
}
pub fn read_payload(db: &Db, session: &Session) -> Result<Payload> {
- let state = sync_state(db)?.context("no local Auth data; run export online first")?;
- ensure!(
- state.complete,
- "Auth refresh is incomplete; run export online first"
- );
let mut payload = Payload {
bytes: Zeroizing::new(Vec::new()),
records: 0,
failed: 0,
failed_ids: Vec::new(),
};
- let Some(wrapped) = state.key else {
- return Ok(payload);
- };
- let key = ente_auth::open_key(&wrapped, &session.master_key)?;
- db.read(|db| {
- let mut statement =
- db.prepare("SELECT id, encrypted_data, header FROM auth_entities ORDER BY id")?;
- let mut rows = statement.query([])?;
- while let Some(row) = rows.next()? {
- let id: String = row.get(0)?;
- let encrypted_data: Option<String> = row.get(1)?;
- let header: Option<String> = row.get(2)?;
- match record::uri_line(encrypted_data.as_deref(), header.as_deref(), &key) {
+ read(db, session, None, |rows| {
+ for row in rows {
+ let (id, record) = row?;
+ match record {
Ok(line) => {
payload.bytes.extend_from_slice(line.as_bytes());
payload.records += 1;
@@ -160,3 +147,40 @@ pub fn read_payload(db: &Db, session: &Session) -> Result<Payload> {
})?;
Ok(payload)
}
+
+type Record = (String, ente_auth::Result<Zeroizing<String>>);
+
+pub fn read<T>(
+ db: &Db,
+ session: &Session,
+ id: Option<Uuid>,
+ visit: impl FnOnce(&mut dyn Iterator<Item = Result<Record>>) -> Result<T>,
+) -> Result<T> {
+ let state = sync_state(db)?.context("no local Auth data; run the command online first")?;
+ ensure!(
+ state.complete,
+ "Auth refresh is incomplete; run the command online first"
+ );
+ let Some(wrapped) = state.key else {
+ return visit(&mut std::iter::empty());
+ };
+ let key = ente_auth::open_key(&wrapped, &session.master_key)?;
+ db.read(|db| {
+ let mut statement = db.prepare(if id.is_some() {
+ "SELECT id, encrypted_data, header FROM auth_entities WHERE id=?1"
+ } else {
+ "SELECT id, encrypted_data, header FROM auth_entities ORDER BY id"
+ })?;
+ let id = id.map(|id| id.to_string());
+ let rows = statement.query_map(params_from_iter(id.iter()), |row| {
+ let id = row.get(0)?;
+ let encrypted_data: Option<String> = row.get(1)?;
+ let header: Option<String> = row.get(2)?;
+ Ok((
+ id,
+ record::uri_line(encrypted_data.as_deref(), header.as_deref(), &key),
+ ))
+ })?;
+ Ok(visit(&mut rows.map(|row| row.map_err(Into::into))))
+ })?
+}
diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli-next/src/output.rs
index 80762cac6f..e0ebfc1a12 100644
--- a/rust/apps/cli-next/src/output.rs
+++ b/rust/apps/cli-next/src/output.rs
@@ -1,6 +1,6 @@
-use std::io::Write;
+use std::{fmt::Display, io::Write};
-use anyhow::{Context, Result};
+use anyhow::{Context, Result, bail};
use chrono::{DateTime, SecondsFormat};
use dialoguer::console::{Alignment, measure_text_width, pad_str};
use ente_accounts::admin::{Subscription, User, UserDetails};
@@ -17,6 +17,8 @@ use crate::{
vault::Account,
};
+pub const MAX_CANDIDATES: usize = 10;
+
#[derive(Serialize)]
pub struct AccountView<'a> {
id: String,
@@ -406,7 +408,36 @@ fn write_fields(fields: &[(&str, String)]) -> Result<()> {
Ok(())
}
-fn list<T: Serialize, const N: usize>(
+pub fn select<T, I: Display>(
+ mut matches: Vec<T>,
+ selector: &str,
+ kind: &str,
+ hint: &str,
+ identity: impl Fn(&T) -> (I, String),
+) -> Result<T> {
+ if matches.len() > 1 {
+ let candidates = matches
+ .iter()
+ .take(MAX_CANDIDATES)
+ .map(|item| {
+ let (id, name) = identity(item);
+ format!(" {id} {name:?}")
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+ let more = if matches.len() > MAX_CANDIDATES {
+ "\nMore matches omitted."
+ } else {
+ ""
+ };
+ bail!("{kind} {selector:?} is ambiguous:\n{candidates}{more}\n{hint}");
+ }
+ matches
+ .pop()
+ .with_context(|| format!("no {kind} matches {selector:?}"))
+}
+
+pub(crate) fn list<T: Serialize, const N: usize>(
mut items: impl Iterator<Item = Result<T>>,
args: &ListArgs,
as_json: bool,
diff --git a/rust/apps/cli-next/src/photos/mod.rs b/rust/apps/cli-next/src/photos/mod.rs
index a944b15909..0b361ba81d 100644
--- a/rust/apps/cli-next/src/photos/mod.rs
+++ b/rust/apps/cli-next/src/photos/mod.rs
@@ -3,7 +3,7 @@ pub mod replica;
use std::{io::Seek, path::Path};
-use anyhow::{Context, Result, bail, ensure};
+use anyhow::{Context, Result, ensure};
use ente_core::Session;
use ente_photos::files;
use serde_json::json;
@@ -11,13 +11,12 @@ use serde_json::json;
use crate::{
api,
args::{AlbumCommand, App, FileCommand, Options, PhotosCommand},
+ core_db::SqliteResult,
db, home,
- output::{self, AlbumView, FileView},
+ output::{self, AlbumView, FileView, MAX_CANDIDATES, select},
};
use replica::Replica;
-const MAX_CANDIDATES: usize = 10;
-
pub async fn run(command: PhotosCommand, selected: Option<&str>, options: &Options) -> Result<()> {
match command {
PhotosCommand::Api(args) => return api::run(App::Photos, args, selected, options).await,
@@ -82,9 +81,13 @@ fn album(command: AlbumCommand, replica: &Replica<'_>, options: &Options) -> Res
AlbumCommand::View { album } => {
let album =
replica.collections(Some(&album), Some((MAX_CANDIDATES + 1) as i64), |rows| {
- select(rows.map(|album| Ok(album?)), &album, "album", |a| {
- (a.id, a.name.as_deref().unwrap_or("unavailable"))
- })
+ select(
+ rows.collect::<SqliteResult<Vec<_>>>()?,
+ &album,
+ "album",
+ "Use an ID.",
+ |a| (a.id, a.name.as_deref().unwrap_or("unavailable").to_owned()),
+ )
})?;
let album = album
.value
@@ -110,9 +113,13 @@ async fn file(
let albums =
replica.collections(album, album.map(|_| (MAX_CANDIDATES + 1) as i64), |rows| {
if let Some(selector) = album {
- let entry = select(rows.map(|album| Ok(album?)), selector, "album", |a| {
- (a.id, a.name.as_deref().unwrap_or("unavailable"))
- })?;
+ let entry = select(
+ rows.collect::<SqliteResult<Vec<_>>>()?,
+ selector,
+ "album",
+ "Use an ID.",
+ |a| (a.id, a.name.as_deref().unwrap_or("unavailable").to_owned()),
+ )?;
Ok(vec![
entry.value.with_context(|| format!("album {}", entry.id))?,
])
@@ -149,9 +156,13 @@ async fn file(
Some(selector),
Some((MAX_CANDIDATES + 1) as i64),
|rows| {
- select(rows.map(|entry| Ok(entry?)), selector, "file", |e| {
- (e.id, e.name.as_deref().unwrap_or("unavailable"))
- })
+ select(
+ rows.collect::<SqliteResult<Vec<_>>>()?,
+ selector,
+ "file",
+ "Use an ID.",
+ |e| (e.id, e.name.as_deref().unwrap_or("unavailable").to_owned()),
+ )
},
)?;
let file = entry.file.with_context(|| format!("file {}", entry.id))?;
@@ -227,32 +238,3 @@ async fn file(
ensure!(!incomplete, "file results are incomplete");
Ok(())
}
-
-fn select<T>(
- items: impl Iterator<Item = Result<T>>,
- selector: &str,
- kind: &str,
- identity: impl Fn(&T) -> (i64, &str),
-) -> Result<T> {
- let mut matches = items.take(MAX_CANDIDATES + 1).collect::<Result<Vec<_>>>()?;
- if matches.len() > 1 {
- let candidates = matches
- .iter()
- .take(MAX_CANDIDATES)
- .map(|item| {
- let (id, name) = identity(item);
- format!(" {id} {name:?}")
- })
- .collect::<Vec<_>>()
- .join("\n");
- let more = if matches.len() > MAX_CANDIDATES {
- "\nMore matches omitted; use an ID."
- } else {
- ""
- };
- bail!("{kind} {selector:?} is ambiguous:\n{candidates}{more}");
- }
- matches
- .pop()
- .with_context(|| format!("no {kind} matches {selector:?}"))
-}
diff --git a/rust/apps/cli-next/tests/cli/account_prompt.py b/rust/apps/cli-next/tests/cli/account_prompt.py
index 32237b0b47..edaa7de2ce 100644
--- a/rust/apps/cli-next/tests/cli/account_prompt.py
+++ b/rust/apps/cli-next/tests/cli/account_prompt.py
@@ -75,6 +75,9 @@ def create(expect, send):
def enable(expect, send):
text = expect(b"Authenticator code:")
secret = re.search(rb"authenticator: ([A-Z2-7]+)", text)[1]
+ send(b"invalid", True)
+ expect(b"Incorrect authenticator code. Try again.")
+ expect(b"Authenticator code:")
key = base64.b32decode(secret + b"=" * (-len(secret) % 8))
digest = hmac.new(key, (int(time.time()) // 30).to_bytes(8, "big"), hashlib.sha1).digest()
offset = digest[-1] & 15
diff --git a/rust/apps/cli-next/tests/cli/auth.rs b/rust/apps/cli-next/tests/cli/auth.rs
index 0fa29670ad..8114946563 100644
--- a/rust/apps/cli-next/tests/cli/auth.rs
+++ b/rust/apps/cli-next/tests/cli/auth.rs
@@ -44,6 +44,232 @@ fn page(server: &mut Server, since: i64, rows: Vec<Value>) -> Mock {
.create()
}
+#[test]
+fn code_reads_refresh_select_and_render_without_a_backup() {
+ let mut server = Server::new();
+ let home = TestHome::new();
+ seed(&home, &server.url());
+ let key = Key::generate();
+ let key_request = key_response(&mut server, &key);
+ let uri = |name: &str| json!(format!("otpauth://totp/{name}?secret=MY"));
+ let initial = page(
+ &mut server,
+ 0,
+ vec![
+ entity(1, 10, &uri("GitHub:[email protected]"), &key),
+ entity(2, 10, &uri("GitHub:[email protected]"), &key),
+ entity(3, 10, &json!(URI), &key),
+ entity(4, 10, &json!("otpauth://totp/Steam:alice?secret=MY"), &key),
+ entity(
+ 5,
+ 10,
+ &json!({"rawData": "otpauth://hotp/Work:a%2B%252C#tag?secret=MY&counter=7"}),
+ &key,
+ ),
+ ],
+ );
+ let listed = success(home.run(&["auth", "code", "list", "--limit", "1", "--json"]));
+ let rows: Value = serde_json::from_slice(&listed.stdout).unwrap();
+ assert_eq!(
+ rows,
+ json!([{"id": Uuid::from_u128(1), "name": "GitHub ([email protected])",
+ "issuer": "GitHub", "accountName": "[email protected]", "type": "totp"}])
+ );
+ assert!(String::from_utf8_lossy(&listed.stderr).contains("Showing first 1"));
+ initial.assert();
+ initial.remove();
+ let view = |query: &str| {
+ home.json(&[
+ "auth",
+ "code",
+ "view",
+ query,
+ "--offline",
+ "--account",
+ "fixture",
+ ])
+ };
+ for query in [
+ "BOB gitHUB",
+ "GitHub ([email protected])",
+ &Uuid::from_u128(2).to_string(),
+ ] {
+ let result = view(query);
+ assert_eq!(result["id"], Uuid::from_u128(2).to_string());
+ assert_eq!(result["otp"].as_str().unwrap().len(), 6);
+ let expiry =
+ chrono::DateTime::parse_from_rfc3339(result["validUntil"].as_str().unwrap()).unwrap();
+ assert_eq!(expiry.timestamp() % 30, 0);
+ assert!(result["validUntil"].as_str().unwrap().ends_with('Z'));
+ }
+ let ambiguous = home.run(&["auth", "code", "view", "github", "--offline"]);
+ let error = failure(&ambiguous);
+ assert!(
+ error.contains("code \"github\" is ambiguous")
+ && error.contains("GitHub ([email protected])")
+ && error.contains(&Uuid::from_u128(2).to_string())
+ );
+ assert!(ambiguous.stdout.is_empty());
+ let missing = home.run(&["auth", "code", "view", "missing", "--offline"]);
+ assert!(failure(&missing).contains("no code matches \"missing\""));
+ assert!(missing.stdout.is_empty());
+ let all = home.json(&["auth", "code", "list", "--all", "--offline"]);
+ assert_eq!(all.as_array().unwrap().len(), 4);
+ assert_eq!(all[2]["type"], "steam");
+ assert_eq!(all[3]["name"], "Work (a+%2C#tag)");
+ assert_eq!(view("steam")["otp"].as_str().unwrap().len(), 5);
+ assert!(
+ failure(&home.run(&["auth", "code", "view", "Work", "--offline"]))
+ .contains("HOTP code generation is not supported")
+ );
+ assert!(
+ failure(&home.run(&[
+ "auth",
+ "code",
+ "view",
+ &Uuid::from_u128(3).to_string(),
+ "--offline"
+ ]))
+ .contains("in Trash")
+ );
+ let text = success(home.run(&["auth", "code", "view", "alice github", "--offline"]));
+ let text = String::from_utf8(text.stdout).unwrap();
+ assert!(text.starts_with("GitHub ([email protected])\n"));
+ assert!(text.contains("\nValid until "));
+
+ let changed = page(
+ &mut server,
+ 9,
+ vec![
+ entity(2, 20, &uri("Work:[email protected]"), &key),
+ entity(6, 20, &uri("GitHub:([email protected])"), &key),
+ ],
+ );
+ assert_eq!(
+ home.json(&["auth", "code", "view", "bob work"])["name"],
+ );
+ changed.assert();
+ changed.remove();
+ let copied = home.run(&[
+ "auth",
+ "code",
+ "view",
+ "GitHub ([email protected])",
+ "--offline",
+ ]);
+ assert!(failure(&copied).contains("code \"GitHub ([email protected])\" is ambiguous"));
+ assert_eq!(
+ home.json(&[
+ "auth",
+ "code",
+ "list",
+ "--search",
+ "GitHub ([email protected])",
+ "--offline"
+ ])
+ .as_array()
+ .unwrap()
+ .len(),
+ 2
+ );
+ assert_eq!(
+ home.json(&[
+ "auth",
+ "code",
+ "list",
+ "--search",
+ "BOB work",
+ "--limit",
+ "1",
+ "--offline"
+ ])[0]["id"],
+ Uuid::from_u128(2).to_string()
+ );
+ let unavailable = server
+ .mock("GET", "/authenticator/entity/diff")
+ .match_query(Matcher::Any)
+ .with_status(400)
+ .create();
+ let failed = home.run(&["auth", "code", "view", "bob"]);
+ failure(&failed);
+ assert!(failed.stdout.is_empty());
+ unavailable.assert();
+ key_request.assert();
+ drop(server);
+ assert_eq!(view("bob")["name"], "Work ([email protected])");
+}
+
+#[test]
+fn unreadable_codes_block_text_selection_but_not_ids_or_list_limits() {
+ let mut server = Server::new();
+ let home = TestHome::new();
+ seed(&home, &server.url());
+ let key = Key::generate();
+ let key_request = key_response(&mut server, &key);
+ let initial = page(
+ &mut server,
+ 0,
+ vec![
+ entity(1, 10, &json!("private-secret"), &key),
+ entity(2, 10, &json!("otpauth://totp/GitHub:alice?secret=MY"), &key),
+ entity(3, 10, &json!("otpauth://totp/Work:bob?secret=MY"), &key),
+ ],
+ );
+ let listed = home.run(&["auth", "code", "list", "--limit", "1", "--json"]);
+ let error = failure(&listed);
+ assert!(
+ error.contains("Auth code list is incomplete")
+ && error.contains("1 unreadable Auth code")
+ && error.contains(&Uuid::from_u128(1).to_string())
+ );
+ assert!(!error.contains("private-secret"));
+ assert_eq!(
+ serde_json::from_slice::<Value>(&listed.stdout).unwrap()[0]["id"],
+ Uuid::from_u128(2).to_string()
+ );
+ for query in ["GitHub (alice)", "github", "missing"] {
+ let output = home.run(&["auth", "code", "view", query, "--offline"]);
+ let error = failure(&output);
+ assert!(error.contains("unreadable Auth code"));
+ assert!(error.contains(&format!(
+ "cannot resolve code {query:?}; select a known code ID"
+ )));
+ assert!(output.stdout.is_empty());
+ }
+ let id = Uuid::from_u128(1).to_string();
+ let unreadable = home.run(&["auth", "code", "view", &id, "--offline"]);
+ assert!(
+ failure(&unreadable).contains(&format!("cannot read code {id:?}: 1 unreadable Auth code"))
+ );
+ assert!(unreadable.stdout.is_empty());
+ let result = home.json(&[
+ "auth",
+ "code",
+ "view",
+ &Uuid::from_u128(2).to_string(),
+ "--offline",
+ ]);
+ assert_eq!(result["name"], "GitHub (alice)");
+ assert_eq!(
+ home.json(&[
+ "auth",
+ "code",
+ "list",
+ "--search",
+ &Uuid::from_u128(2).to_string(),
+ "--offline"
+ ])[0]["name"],
+ "GitHub (alice)"
+ );
+ assert!(
+ failure(&home.run(&["auth", "code", "view", " ", "--offline"]))
+ .contains("supply a code ID or search text")
+ );
+ initial.assert();
+ key_request.assert();
+}
+
#[test]
fn refresh_keeps_progress_and_refuses_unreadable_codes_until_updated() {
let mut server = Server::new();
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 535e25b257..b9928e972b 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -384,11 +384,7 @@ impl AccountsClient {
.send()
.await?
.error_for_code()
- .await
- .map_err(|error| match error.status_code() {
- Some(400 | 401) => Error::IncorrectTotp,
- _ => error.into(),
- })?;
+ .await?;
Ok(())
}
diff --git a/rust/crates/accounts/src/error.rs b/rust/crates/accounts/src/error.rs
index 2515cd7931..693ceec744 100644
--- a/rust/crates/accounts/src/error.rs
+++ b/rust/crates/accounts/src/error.rs
@@ -1,4 +1,4 @@
-use ente_core::{b64, crypto, http};
+use ente_core::{b64, crypto, http, otp};
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
@@ -14,6 +14,9 @@ pub enum Error {
#[error(transparent)]
Crypto(#[from] crypto::Error),
+ #[error(transparent)]
+ Otp(#[from] otp::Error),
+
#[error("Decode error: {0}")]
Decode(String),
diff --git a/rust/crates/accounts/src/lifecycle.rs b/rust/crates/accounts/src/lifecycle.rs
index d20181e9b4..ac138002cc 100644
--- a/rust/crates/accounts/src/lifecycle.rs
+++ b/rust/crates/accounts/src/lifecycle.rs
@@ -1,6 +1,9 @@
-use ente_core::b64;
use ente_core::crypto::{self, SecretVec, secretbox};
-use std::fmt;
+use ente_core::{b64, otp};
+use std::{
+ fmt,
+ time::{SystemTime, UNIX_EPOCH},
+};
use uuid::Uuid;
use zeroize::{ZeroizeOnDrop, Zeroizing};
@@ -113,11 +116,27 @@ impl TwoFactorSetup {
}
pub async fn enable(&self, client: &AccountsClient, code: &str) -> Result<()> {
+ let time = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map_err(|_| Error::InvalidInput("system clock is before the Unix epoch".into()))?
+ .as_secs();
+ verify_totp(&self.secret_code, code, time)?;
let request = encrypt_two_factor_secret(&self.secret_code, &self.recovery_key, code)?;
client.enable_two_factor(&request).await
}
}
+fn verify_totp(secret: &str, code: &str, time: u64) -> Result<()> {
+ let secret = otp::decode_secret(secret)?;
+ for time in [time.saturating_sub(30), time, time + 30] {
+ let expected = Zeroizing::new(otp::totp(&secret, time, 30, 6, otp::Algorithm::Sha1)?);
+ if expected.as_str() == code {
+ return Ok(());
+ }
+ }
+ Err(Error::IncorrectTotp)
+}
+
pub async fn change_password(
client: &AccountsClient,
params: ChangePasswordParams,
diff --git a/rust/crates/accounts/src/lifecycle/tests.rs b/rust/crates/accounts/src/lifecycle/tests.rs
index f753668f68..9950928c62 100644
--- a/rust/crates/accounts/src/lifecycle/tests.rs
+++ b/rust/crates/accounts/src/lifecycle/tests.rs
@@ -64,7 +64,17 @@ async fn setup_two_factor_encrypts_secret_with_recovery_key() {
let result = TwoFactorSetup::start(&client, &master_key, &key_attributes)
.await
.unwrap();
- result.enable(&client, "123123").await.unwrap();
+ assert!(matches!(
+ result.enable(&client, "invalid").await,
+ Err(Error::IncorrectTotp)
+ ));
+ result
+ .enable(
+ &client,
+ &ente_test_support::account_fixture::current_totp(&result.secret_code).unwrap(),
+ )
+ .await
+ .unwrap();
assert_eq!(result.secret_code, "JBSWY3DPEHPK3PXP");
assert_eq!(result.recovery_key, recovery_key);
@@ -73,6 +83,24 @@ async fn setup_two_factor_encrypts_secret_with_recovery_key() {
enable.assert_async().await;
}
+#[test]
+fn enrollment_verifies_the_supplied_secret_and_window() {
+ let secret = "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ";
+ for code in ["755224", "287082", "359152"] {
+ verify_totp(secret, code, 59).unwrap();
+ }
+ for code in ["969429", "28708", "0287082", "invalid"] {
+ assert!(matches!(
+ verify_totp(secret, code, 59),
+ Err(Error::IncorrectTotp)
+ ));
+ }
+ assert!(matches!(
+ verify_totp("MY", "287082", 59),
+ Err(Error::IncorrectTotp)
+ ));
+}
+
#[tokio::test]
async fn configure_passkey_recovery_accepts_hex_recovery_key() {
let key_gen =
diff --git a/rust/crates/auth/Cargo.toml b/rust/crates/auth/Cargo.toml
index 93bb58dd43..636da38580 100644
--- a/rust/crates/auth/Cargo.toml
+++ b/rust/crates/auth/Cargo.toml
@@ -8,6 +8,7 @@ serde.workspace = true
serde_json = { workspace = true, features = ["raw_value"] }
thiserror.workspace = true
url.workspace = true
+urlencoding.workspace = true
uuid = { workspace = true, features = ["serde"] }
zeroize.workspace = true
diff --git a/rust/crates/auth/src/code.rs b/rust/crates/auth/src/code.rs
new file mode 100644
index 0000000000..2ae2ec9fc5
--- /dev/null
+++ b/rust/crates/auth/src/code.rs
@@ -0,0 +1,218 @@
+use ente_core::otp::{self, Algorithm};
+use serde::Deserialize;
+use url::Url;
+use zeroize::Zeroizing;
+
+use crate::{Error, Result};
+
+#[derive(Clone, Copy)]
+pub enum Kind {
+ Totp,
+ Hotp,
+ Steam,
+}
+
+impl Kind {
+ pub fn as_str(self) -> &'static str {
+ match self {
+ Self::Totp => "totp",
+ Self::Hotp => "hotp",
+ Self::Steam => "steam",
+ }
+ }
+}
+
+pub struct Code {
+ pub issuer: String,
+ pub account_name: String,
+ pub kind: Kind,
+ pub trashed: bool,
+ secret: Zeroizing<String>,
+ algorithm: String,
+ digits: String,
+ period: String,
+}
+
+impl Code {
+ pub fn from_uri(uri: &str) -> Result<Self> {
+ let uri = Zeroizing::new(uri.trim_end().replace('#', "%23"));
+ let parsed = Url::parse(&uri).map_err(|_| Error::InvalidRecord)?;
+ let query: std::collections::HashMap<_, _> = parsed.query_pairs().collect();
+ let label = urlencoding::decode(parsed.path().strip_prefix('/').unwrap_or(parsed.path()))
+ .map_err(|_| Error::InvalidRecord)?;
+ let mut issuer = query.get("issuer").map_or_else(
+ || {
+ label
+ .split_once(':')
+ .map_or(label.as_ref(), |(issuer, _)| issuer)
+ .to_owned()
+ },
+ ToString::to_string,
+ );
+ if query.contains_key("issuer")
+ && let Some((name, digits)) = issuer.rsplit_once("period=")
+ && !digits.is_empty()
+ && digits.bytes().all(|byte| byte.is_ascii_digit())
+ {
+ let name = name.strip_suffix('&').unwrap_or(name);
+ if !name.is_empty() && !name.ends_with(char::is_whitespace) {
+ issuer.truncate(name.len());
+ }
+ }
+ let account_name = label
+ .strip_prefix(&format!("{issuer}:"))
+ .or_else(|| label.split_once(':').map(|(_, account)| account))
+ .unwrap_or(&label)
+ .to_owned();
+ let kind = match parsed
+ .host_str()
+ .unwrap_or_default()
+ .to_ascii_lowercase()
+ .as_str()
+ {
+ "totp" if issuer.eq_ignore_ascii_case("steam") => Kind::Steam,
+ "totp" => Kind::Totp,
+ "steam" => Kind::Steam,
+ "hotp" => Kind::Hotp,
+ _ => return Err(Error::InvalidRecord),
+ };
+ #[derive(Default, Deserialize)]
+ struct Display {
+ trashed: Option<bool>,
+ }
+ let display = query
+ .get("codeDisplay")
+ .map(|value| serde_json::from_str::<Option<Display>>(value))
+ .transpose()
+ .map_err(|_| Error::InvalidRecord)?
+ .flatten()
+ .unwrap_or_default();
+ Ok(Self {
+ issuer,
+ account_name,
+ kind,
+ trashed: display.trashed.unwrap_or(false),
+ secret: Zeroizing::new(query.get("secret").ok_or(Error::InvalidRecord)?.to_string()),
+ algorithm: query
+ .get("algorithm")
+ .map_or("sha1", |s| s.as_ref())
+ .to_owned(),
+ digits: query.get("digits").map_or("6", |s| s.as_ref()).to_owned(),
+ period: query.get("period").map_or("30", |s| s.as_ref()).to_owned(),
+ })
+ }
+
+ pub fn name(&self) -> String {
+ match (self.issuer.is_empty(), self.account_name.is_empty()) {
+ (true, _) => self.account_name.clone(),
+ (_, true) => self.issuer.clone(),
+ _ => format!("{} ({})", self.issuer, self.account_name),
+ }
+ }
+
+ pub fn matches(&self, query: &str) -> bool {
+ let query = query.to_lowercase();
+ let issuer = self.issuer.to_lowercase();
+ let account = self.account_name.to_lowercase();
+ self.name().to_lowercase() == query
+ || query
+ .split_whitespace()
+ .all(|word| issuer.contains(word) || account.contains(word))
+ }
+
+ pub fn generate(&self, time: u64) -> Result<(String, u64)> {
+ if matches!(self.kind, Kind::Hotp) {
+ return Err(Error::UnsupportedHotp);
+ }
+ let secret = otp::decode_secret(&self.secret)?;
+ let (value, period) = if matches!(self.kind, Kind::Steam) {
+ (otp::steam(&secret, time)?, 30)
+ } else {
+ let algorithm = match self.algorithm.to_ascii_lowercase().as_str() {
+ "sha1" | "algorithm.sha1" => Algorithm::Sha1,
+ "sha256" | "algorithm.sha256" => Algorithm::Sha256,
+ "sha512" | "algorithm.sha512" => Algorithm::Sha512,
+ _ => return Err(Error::InvalidCodeParameters),
+ };
+ let digits = self
+ .digits
+ .parse()
+ .map_err(|_| Error::InvalidCodeParameters)?;
+ let period = self
+ .period
+ .parse()
+ .map_err(|_| Error::InvalidCodeParameters)?;
+ (otp::totp(&secret, time, period, digits, algorithm)?, period)
+ };
+ let valid_until = time
+ .checked_add(period - time % period)
+ .ok_or(Error::InvalidCodeParameters)?;
+ Ok((value, valid_until))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use ente_core::{
+ b64,
+ crypto::{Key, blob},
+ };
+ use serde_json::json;
+
+ #[test]
+ fn saved_forms_preserve_labels_and_generate_with_stored_parameters() {
+ let uri = "otpauth://totp/Work:alice%2B%252C#tag?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&digits=8&period=60&algorithm=Algorithm.SHA1";
+ let key = Key::generate();
+ for value in [
+ json!(uri),
+ json!({"rawData": uri, "display": {"note": "literal%2C"}}),
+ ] {
+ let encrypted = blob::encrypt(&serde_json::to_vec(&value).unwrap(), &key).unwrap();
+ let line = crate::record::uri_line(
+ Some(&b64::encode(&encrypted.encrypted_data)),
+ Some(&b64::encode(encrypted.decryption_header.as_bytes())),
+ &key,
+ )
+ .unwrap();
+ let code = Code::from_uri(&line).unwrap();
+ assert_eq!(code.name(), "Work (alice+%2C#tag)");
+ assert_eq!(
+ code.generate(2_222_222_219).unwrap(),
+ ("07081804".into(), 2_222_222_220)
+ );
+ assert_eq!(code.generate(2_222_222_220).unwrap().1, 2_222_222_280);
+ }
+ for uri in [
+ "otpauth://steam/alice?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
+ "otpauth://totp/alice?issuer=sTeAm&secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
+ ] {
+ let code = Code::from_uri(uri).unwrap();
+ assert!(matches!(code.kind, Kind::Steam));
+ assert_eq!(code.generate(59).unwrap(), ("PV9M4".into(), 60));
+ }
+ for (issuer, name, value) in [
+ ("Steamperiod=30", "Steam", "PV9M4"),
+ ("Steam%26period=30", "Steam", "PV9M4"),
+ ("Steam%20period=30", "Steam period=30", "287082"),
+ ] {
+ let code = Code::from_uri(&format!(
+ "otpauth://totp/alice?issuer={issuer}&secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
+ ))
+ .unwrap();
+ let name = format!("{name} (alice)");
+ assert_eq!(code.name(), name);
+ assert!(code.matches(&name));
+ assert_eq!(code.generate(59).unwrap(), (value.into(), 60));
+ }
+ let code =
+ Code::from_uri("otpauth://hotp/alice?issuer=Steam&secret=MY&counter=12").unwrap();
+ assert!(matches!(code.kind, Kind::Hotp));
+ assert!(matches!(code.generate(59), Err(Error::UnsupportedHotp)));
+ for parameter in ["algorithm=md5", "digits=11", "period=0", "period=oops"] {
+ let code =
+ Code::from_uri(&format!("otpauth://totp/alice?secret=MY&{parameter}")).unwrap();
+ assert!(code.generate(59).is_err());
+ }
+ }
+}
diff --git a/rust/crates/auth/src/lib.rs b/rust/crates/auth/src/lib.rs
index 329f801fcd..efa183e698 100644
--- a/rust/crates/auth/src/lib.rs
+++ b/rust/crates/auth/src/lib.rs
@@ -1,10 +1,11 @@
pub mod backup;
+pub mod code;
pub mod record;
use ente_core::{
Session, b64,
crypto::{self, Key, Nonce, secretbox},
- http,
+ http, otp,
};
use serde::Deserialize;
use uuid::Uuid;
@@ -18,10 +19,16 @@ pub enum Error {
Http(#[from] http::Error),
#[error(transparent)]
Crypto(#[from] crypto::Error),
+ #[error(transparent)]
+ Otp(#[from] otp::Error),
#[error("invalid Auth base64 encoding")]
Base64(#[from] b64::DecodeError),
#[error("unreadable Auth record")]
InvalidRecord,
+ #[error("invalid Auth code parameters")]
+ InvalidCodeParameters,
+ #[error("HOTP code generation is not supported yet")]
+ UnsupportedHotp,
#[error("invalid encrypted Auth export")]
InvalidBackup,
#[error("unsupported Auth export version")]
diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.toml
index 051a60a698..fdcfdab586 100644
--- a/rust/crates/core/Cargo.toml
+++ b/rust/crates/core/Cargo.toml
@@ -9,6 +9,7 @@ blake2b_simd = "1.0.5"
crypto_secretbox = { version = "0.1.0", default-features = false, features = ["alloc", "salsa20"] }
crypto_secretstream = "=0.2.0"
getrandom.workspace = true
+hmac.workspace = true
hpke = { version = "0.14.1", default-features = false, features = ["alloc", "chacha", "getrandom", "mlkem", "x25519"] }
log.workspace = true
md-5.workspace = true
@@ -17,6 +18,8 @@ reqwest = { workspace = true, features = ["http2", "charset", "system-proxy", "j
salsa20 = "0.10.0"
serde.workspace = true
serde_json.workspace = true
+sha1.workspace = true
+sha2.workspace = true
subtle.workspace = true
thiserror.workspace = true
x25519-dalek = { version = "3.0.0", features = ["static_secrets"] }
diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rs
index 4d4862e8a1..eb6886c2a4 100644
--- a/rust/crates/core/src/lib.rs
+++ b/rust/crates/core/src/lib.rs
@@ -4,6 +4,7 @@ pub mod error;
pub mod http;
pub mod id;
pub mod io;
+pub mod otp;
mod session;
pub mod urls;
diff --git a/rust/crates/core/src/otp.rs b/rust/crates/core/src/otp.rs
new file mode 100644
index 0000000000..283d405f35
--- /dev/null
+++ b/rust/crates/core/src/otp.rs
@@ -0,0 +1,146 @@
+use hmac::{Hmac, KeyInit, Mac};
+use sha1::Sha1;
+use sha2::{Sha256, Sha512};
+use zeroize::Zeroizing;
+
+use crate::crypto::SecretVec;
+
+#[derive(thiserror::Error, Debug)]
+pub enum Error {
+ #[error("Invalid Base32 OTP secret")]
+ InvalidSecret,
+ #[error("OTP requires one to ten digits and a positive period")]
+ InvalidParameters,
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(Clone, Copy)]
+pub enum Algorithm {
+ Sha1,
+ Sha256,
+ Sha512,
+}
+
+pub fn decode_secret(secret: &str) -> Result<SecretVec> {
+ let secret = Zeroizing::new(secret.trim().replace(' ', ""));
+ let mut bytes = Zeroizing::new(Vec::new());
+ let mut buffer = 0u32;
+ let mut bits = 0;
+ for byte in secret
+ .trim_end_matches('=')
+ .bytes()
+ .map(|b| b.to_ascii_uppercase())
+ {
+ let value = match byte {
+ b'A'..=b'Z' => byte - b'A',
+ b'2'..=b'7' => byte - b'2' + 26,
+ _ => return Err(Error::InvalidSecret),
+ };
+ buffer = (buffer << 5) | u32::from(value);
+ bits += 5;
+ if bits >= 8 {
+ bits -= 8;
+ bytes.push((buffer >> bits) as u8);
+ }
+ }
+ if bytes.is_empty() {
+ return Err(Error::InvalidSecret);
+ }
+ Ok(SecretVec::new(std::mem::take(&mut *bytes)))
+}
+
+pub fn totp(
+ secret: &[u8],
+ time: u64,
+ period: u64,
+ digits: u32,
+ algorithm: Algorithm,
+) -> Result<String> {
+ if period == 0 || !(1..=10).contains(&digits) {
+ return Err(Error::InvalidParameters);
+ }
+ let value = u64::from(truncate(secret, time / period, algorithm)?);
+ Ok(format!(
+ "{:0width$}",
+ value % 10u64.pow(digits),
+ width = digits as usize
+ ))
+}
+
+pub fn steam(secret: &[u8], time: u64) -> Result<String> {
+ let alphabet = b"23456789BCDFGHJKMNPQRTVWXY";
+ let mut value = truncate(secret, time / 30, Algorithm::Sha1)?;
+ Ok((0..5)
+ .map(|_| {
+ let letter = alphabet[value as usize % alphabet.len()] as char;
+ value /= alphabet.len() as u32;
+ letter
+ })
+ .collect())
+}
+
+fn digest<M: Mac + KeyInit>(secret: &[u8], counter: u64) -> Result<Zeroizing<Vec<u8>>> {
+ let mut mac = M::new_from_slice(secret).map_err(|_| Error::InvalidSecret)?;
+ mac.update(&counter.to_be_bytes());
+ Ok(Zeroizing::new(mac.finalize().into_bytes().to_vec()))
+}
+
+fn truncate(secret: &[u8], counter: u64, algorithm: Algorithm) -> Result<u32> {
+ let digest = match algorithm {
+ Algorithm::Sha1 => digest::<Hmac<Sha1>>(secret, counter),
+ Algorithm::Sha256 => digest::<Hmac<Sha256>>(secret, counter),
+ Algorithm::Sha512 => digest::<Hmac<Sha512>>(secret, counter),
+ }?;
+ let offset = (digest[digest.len() - 1] & 15) as usize;
+ let bytes = &digest[offset..offset + 4];
+ Ok(u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn rfc6238_vectors_and_extended_formats() {
+ let sha1 = b"12345678901234567890";
+ let sha256 = b"12345678901234567890123456789012";
+ let sha512 = b"1234567890123456789012345678901234567890123456789012345678901234";
+ for (time, expected) in [
+ (59, ["94287082", "46119246", "90693936"]),
+ (20_000_000_000, ["65353130", "77737706", "47863826"]),
+ ] {
+ for ((secret, algorithm), expected) in [
+ (sha1.as_slice(), Algorithm::Sha1),
+ (sha256.as_slice(), Algorithm::Sha256),
+ (sha512.as_slice(), Algorithm::Sha512),
+ ]
+ .into_iter()
+ .zip(expected)
+ {
+ assert_eq!(totp(secret, time, 30, 8, algorithm).unwrap(), expected);
+ }
+ }
+ assert_eq!(totp(sha1, 59, 30, 1, Algorithm::Sha1).unwrap(), "2");
+ assert_eq!(
+ totp(sha1, 59, 30, 10, Algorithm::Sha1).unwrap(),
+ "1094287082"
+ );
+ assert_eq!(steam(sha1, 59).unwrap(), "PV9M4");
+ assert_eq!(steam(sha1, 60).unwrap(), "B26KJ");
+ for (period, digits) in [(0, 6), (30, 0), (30, 11)] {
+ assert!(totp(sha1, 59, period, digits, Algorithm::Sha1).is_err());
+ }
+ }
+
+ #[test]
+ fn secrets_allow_app_normalization_and_short_keys() {
+ let secret = decode_secret(" my= = ==== ").unwrap();
+ assert_eq!(&*secret, b"f");
+ assert_eq!(totp(&secret, 59, 30, 6, Algorithm::Sha1).unwrap(), "300412");
+ assert_eq!(&*decode_secret("mzxw 6ytb").unwrap(), b"fooba");
+ for invalid in ["", "!secret!", "AAAA1", "A"] {
+ assert!(decode_secret(invalid).is_err());
+ }
+ }
+}
diff --git a/rust/crates/test-support/Cargo.toml b/rust/crates/test-support/Cargo.toml
index 86c3defcc3..cd571b2262 100644
--- a/rust/crates/test-support/Cargo.toml
+++ b/rust/crates/test-support/Cargo.toml
@@ -8,9 +8,7 @@ publish = false
dirs.workspace = true
ente-accounts.workspace = true
ente-core.workspace = true
-hmac.workspace = true
postgresql_embedded = { version = "0.20.4", default-features = false, features = ["blocking", "rustls", "theseus"] }
-sha1.workspace = true
tokio = { workspace = true, features = ["rt-multi-thread"] }
uuid = { workspace = true, features = ["v4"] }
diff --git a/rust/crates/test-support/src/account_fixture.rs b/rust/crates/test-support/src/account_fixture.rs
index 5615602359..429a319558 100644
--- a/rust/crates/test-support/src/account_fixture.rs
+++ b/rust/crates/test-support/src/account_fixture.rs
@@ -2,10 +2,8 @@ use std::time::{SystemTime, UNIX_EPOCH};
use ente_accounts::auth::{SrpSession, generate_srp_setup_with_login_key};
use ente_accounts::{AccountsClient, AccountsClientConfig, KeyAttributes, models::SetupSrpRequest};
-use ente_core::b64;
use ente_core::crypto::{Key, SecretKey, kdf, secretbox};
-use hmac::{Hmac, KeyInit, Mac};
-use sha1::Sha1;
+use ente_core::{b64, otp};
use uuid::Uuid;
use crate::{HARDCODED_OTT, HARDCODED_OTT_EMAIL_SUFFIX, TestResult};
@@ -116,37 +114,13 @@ pub async fn create_account(endpoint: &str, email_prefix: &str) -> TestResult<Te
}
pub fn current_totp(secret: &str) -> TestResult<String> {
- let key = decode_base32(secret)?;
- let counter = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() / 30;
- let mut mac = Hmac::<Sha1>::new_from_slice(&key)?;
- mac.update(&counter.to_be_bytes());
- let digest = mac.finalize().into_bytes();
- let offset = (digest[19] & 0x0f) as usize;
- let binary = ((digest[offset] as u32 & 0x7f) << 24)
- | ((digest[offset + 1] as u32) << 16)
- | ((digest[offset + 2] as u32) << 8)
- | digest[offset + 3] as u32;
- Ok(format!("{:06}", binary % 1_000_000))
-}
-
-fn decode_base32(secret: &str) -> TestResult<Vec<u8>> {
- let mut output = Vec::new();
- let mut buffer = 0u32;
- let mut bits = 0u8;
- for ch in secret.chars().filter(|ch| *ch != '=') {
- let value = match ch {
- 'A'..='Z' => ch as u8 - b'A',
- '2'..='7' => ch as u8 - b'2' + 26,
- _ => return Err(format!("invalid base32 character: {ch}").into()),
- } as u32;
- buffer = (buffer << 5) | value;
- bits += 5;
- while bits >= 8 {
- bits -= 8;
- output.push(((buffer >> bits) & 0xff) as u8);
- }
- }
- Ok(output)
+ Ok(otp::totp(
+ &otp::decode_secret(secret)?,
+ SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
+ 30,
+ 6,
+ otp::Algorithm::Sha1,
+ )?)
}
fn pad_left(data: &[u8], len: usize) -> Vec<u8> {