Skip to content

armgit / ente

Public Imported from GitHub
0

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

Refine replacement Rust CLI

Manav Rathiab65aafe8e44
diff --git a/.github/workflows/rust-cli-test.yml b/.github/workflows/rust-cli-test.yml
index 372a716239..38020bd81f 100644
--- a/.github/workflows/rust-cli-test.yml
+++ b/.github/workflows/rust-cli-test.yml
@@ -50,7 +50,7 @@ jobs:
security set-key-partition-list -S apple-tool:,apple: -s -k "$password" "$keychain"
security list-keychains -d user -s "$keychain"
security default-keychain -d user -s "$keychain"
- python3 apps/cli-next/scripts/macos-keyring.py test 'Ente CLI CI'
+ python3 apps/cli-next/scripts/native-keyring.py test --sign 'Ente CLI CI'
- name: Remove the disposable keychain
if: always()
@@ -59,3 +59,17 @@ jobs:
if [[ -e "$keychain" ]]; then
security delete-keychain "$keychain"
fi
+
+ native-keyring-windows:
+ runs-on: windows-latest
+ timeout-minutes: 30
+ defaults:
+ run:
+ working-directory: rust
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+
+ - name: Run with Windows Credential Manager
+ run: python apps/cli-next/scripts/native-keyring.py test
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index b06dfdd050..58d5d2f9db 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2428,14 +2428,6 @@ dependencies = [
"wasm-bindgen",
]
-[[package]]
-name = "ente-collections"
-version = "0.0.0"
-dependencies = [
- "ente-core",
- "thiserror 2.0.18",
-]
-
[[package]]
name = "ente-cli-next"
version = "0.1.0"
@@ -2458,10 +2450,17 @@ dependencies = [
"tokio",
"url",
"uuid",
- "windows-sys 0.61.2",
"zeroize",
]
+[[package]]
+name = "ente-collections"
+version = "0.0.0"
+dependencies = [
+ "ente-core",
+ "thiserror 2.0.18",
+]
+
[[package]]
name = "ente-contacts"
version = "0.0.0"
@@ -2758,6 +2757,7 @@ name = "ente-photos"
version = "0.0.0"
dependencies = [
"ente-assets",
+ "ente-collections",
"ente-core",
"ente-exif",
"ente-location",
@@ -2766,7 +2766,6 @@ dependencies = [
"serde",
"tempfile",
"thiserror 2.0.18",
- "zeroize",
]
[[package]]
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 6ae03eca85..3a8c67e29e 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -113,7 +113,6 @@ urlencoding = "2.1.3"
uuid = "1.23.1"
wasm-bindgen = "0.2.125"
wasm-bindgen-futures = "0.4.75"
-windows-sys = "0.61.2"
zeroize = { version = "1.9.0", features = ["derive"] }
zip = { version = "8.6.0", default-features = false, features = ["deflate-flate2-zlib-rs"] }
diff --git a/rust/apps/cli-next/Cargo.toml b/rust/apps/cli-next/Cargo.toml
index 16810f02d4..abfd781438 100644
--- a/rust/apps/cli-next/Cargo.toml
+++ b/rust/apps/cli-next/Cargo.toml
@@ -26,9 +26,6 @@ url.workspace = true
uuid = { workspace = true, features = ["serde", "v4"] }
zeroize.workspace = true
-[target.'cfg(windows)'.dependencies]
-windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security_Authorization"] }
-
[dev-dependencies]
ente-test-support.workspace = true
mockito.workspace = true
diff --git a/rust/apps/cli-next/scripts/macos-keyring.py b/rust/apps/cli-next/scripts/native-keyring.py
similarity index 53%
rename from rust/apps/cli-next/scripts/macos-keyring.py
rename to rust/apps/cli-next/scripts/native-keyring.py
index 15fdf9dde7..e58c303cc4 100644
--- a/rust/apps/cli-next/scripts/macos-keyring.py
+++ b/rust/apps/cli-next/scripts/native-keyring.py
@@ -5,13 +5,20 @@ import subprocess
from pathlib import Path
parser = argparse.ArgumentParser(
- description="Build or test the CLI with stable macOS Keychain access."
+ description="Build or test the CLI with native secret storage."
)
parser.add_argument(
- "mode", choices=["build", "test"], help="build prints the CLI path; test runs the keyring test"
+ "mode",
+ choices=["build", "test"],
+ help="build prints the CLI path; test runs the keyring tests",
+)
+parser.add_argument(
+ "--sign", metavar="IDENTITY", help="code-sign executables with this macOS identity"
)
-parser.add_argument("identity", help="identity from security find-identity -v -p codesigning")
args = parser.parse_args()
+if args.mode == "build" and not args.sign:
+ parser.error("build requires --sign")
+
app = Path(__file__).resolve().parent.parent
cargo = {
"build": ["cargo", "build", "--bin", "ente-cli-next"],
@@ -22,7 +29,10 @@ messages = subprocess.check_output(cargo, cwd=app, text=True)
executables = {}
for line in messages.splitlines():
message = json.loads(line)
- if message.get("executable") and message["manifest_path"] == str(app / "Cargo.toml"):
+ if (
+ message.get("executable")
+ and Path(message["manifest_path"]).resolve() == app / "Cargo.toml"
+ ):
executables[message["target"]["kind"][0]] = message["executable"]
test_name = "native_keyring_survives_separate_processes"
@@ -31,23 +41,26 @@ if args.mode == "test":
[executables["test"], "--ignored", "--exact", test_name, "--list"], text=True
)
if f"{test_name}: test" not in listing.splitlines():
- raise SystemExit("Native keyring test not found; nothing was signed or run.")
+ raise SystemExit("Native keyring test not found; nothing was run.")
+
+if args.sign:
+ # The test reads keys created by the CLI; both need the same development identity.
+ subprocess.run(
+ [
+ "codesign",
+ "--force",
+ "--sign",
+ args.sign,
+ "--identifier",
+ "io.ente.cli.dev",
+ *executables.values(),
+ ],
+ check=True,
+ )
+ subprocess.run(["codesign", "--verify", "--strict", *executables.values()], check=True)
-# The test reads keys created by the CLI; both need the same development identity.
-subprocess.run(
- [
- "codesign",
- "--force",
- "--sign",
- args.identity,
- "--identifier",
- "io.ente.cli.dev",
- *executables.values(),
- ],
- check=True,
-)
-subprocess.run(["codesign", "--verify", "--strict", *executables.values()], check=True)
if args.mode == "test":
+ subprocess.run([executables["test"]], check=True)
subprocess.run(
[executables["test"], "--ignored", "--exact", test_name], check=True
)
diff --git a/rust/apps/cli-next/src/api.rs b/rust/apps/cli-next/src/api.rs
index 4bf332b738..d6dc3f7923 100644
--- a/rust/apps/cli-next/src/api.rs
+++ b/rust/apps/cli-next/src/api.rs
@@ -4,13 +4,12 @@ use anyhow::{Context, Result, ensure};
use ente_accounts::{AccountsClient, AccountsClientConfig};
use ente_core::{
Session, b64,
- crypto::SecretVec,
- http::{Api, ApiConfig, Auth},
+ crypto::{Key, SecretKey},
+ http::{ApiConfig, Auth},
};
use reqwest::{
Client, Method,
header::{HeaderMap, HeaderName, HeaderValue},
- redirect::Policy,
};
use url::Url;
use zeroize::Zeroizing;
@@ -21,42 +20,36 @@ use crate::{
vault::Account,
};
+pub(crate) const USER_AGENT: &str = concat!("ente-cli-next/", env!("CARGO_PKG_VERSION"));
+
pub fn http() -> Result<Client> {
Ok(Client::builder()
- .user_agent(concat!("ente-cli-next/", env!("CARGO_PKG_VERSION")))
+ .user_agent(USER_AGENT)
.connect_timeout(Duration::from_secs(15))
.read_timeout(Duration::from_secs(30))
- .redirect(Policy::custom(|attempt| {
- if attempt.previous().len() >= 10 {
- attempt.error("too many redirects")
- } else if attempt
- .previous()
- .first()
- .is_some_and(|first| first.origin() != attempt.url().origin())
- {
- attempt.error("redirect leaves the selected account's origin")
- } else {
- attempt.follow()
- }
- }))
.build()?)
}
pub fn accounts_client(origin: &str, product: Product) -> Result<AccountsClient> {
- Ok(AccountsClient::with_http(
- AccountsClientConfig::new(product.client_package()).with_origin(origin),
- http()?.into(),
- ))
+ Ok(AccountsClient::new(
+ AccountsClientConfig::new(product.client_package())
+ .with_origin(origin)
+ .with_user_agent(USER_AGENT),
+ )?)
}
pub fn session(account: &Account, product: Product) -> Result<Session> {
let mut config = ApiConfig::new(account.origin.clone());
config.client_package = Some(product.client_package().into());
+ config.user_agent = Some(USER_AGENT.into());
config.auth = Some(Auth::User(b64::encode_url_safe(account.token(product)?)));
- Ok(Session {
- api: Api::new(http()?.into(), config),
- master_key: SecretVec::new(account.identity.master_key.clone()),
- })
+ Session::new(
+ config,
+ account.user_id,
+ Key::try_from_slice(&account.identity.master_key)?,
+ SecretKey::try_from_slice(&account.identity.secret_key)?,
+ )
+ .map_err(Into::into)
}
pub async fn raw(account: &Account, product: Product, args: ApiArgs) -> Result<()> {
@@ -111,13 +104,13 @@ pub async fn raw(account: &Account, product: Product, args: ApiArgs) -> Result<(
if let Some(path) = args.body {
request = request.body(read_input(&path)?.to_vec());
}
- let mut response = request.send().await.map_err(reqwest::Error::without_url)?;
+ let mut response = request.send().await.map_err(ente_core::http::Error::from)?;
let status = response.status();
let mut stdout = std::io::stdout().lock();
while let Some(chunk) = response
.chunk()
.await
- .map_err(reqwest::Error::without_url)?
+ .map_err(ente_core::http::Error::from)?
{
stdout.write_all(&chunk)?;
}
diff --git a/rust/apps/cli-next/src/args.rs b/rust/apps/cli-next/src/args.rs
index 39063d2590..35afa63865 100644
--- a/rust/apps/cli-next/src/args.rs
+++ b/rust/apps/cli-next/src/args.rs
@@ -16,7 +16,7 @@ pub struct Cli {
long,
global = true,
value_name = "NAME",
- help = "Use this saved account instead of the selected one"
+ help = "Use this account instead of the selected one"
)]
pub account: Option<String>,
#[command(subcommand)]
@@ -25,22 +25,22 @@ pub struct Cli {
#[derive(Subcommand)]
pub enum Command {
- #[command(about = "Log in to Ente Photos, list albums, or call the Photos API")]
+ #[command(about = "Manage Ente Photos")]
Photos {
#[command(subcommand)]
command: PhotosCommand,
},
- #[command(about = "Log in to Ente Locker or call the Locker API")]
+ #[command(about = "Manage Ente Locker")]
Locker {
#[command(subcommand)]
command: SessionCommand,
},
- #[command(about = "Log in to Ente Auth or call the Auth API")]
+ #[command(about = "Manage Ente Auth")]
Auth {
#[command(subcommand)]
command: SessionCommand,
},
- #[command(about = "View and manage saved accounts")]
+ #[command(about = "Manage accounts on this device")]
Account {
#[command(subcommand)]
command: AccountCommand,
@@ -63,7 +63,7 @@ Keep the same home and key across unattended invocations."
pub enum PhotosCommand {
#[command(flatten)]
Session(SessionCommand),
- #[command(about = "Work with albums")]
+ #[command(about = "Manage albums")]
Album {
#[command(subcommand)]
command: AlbumCommand,
@@ -83,7 +83,7 @@ otp is the email code. totp is the authenticator code. Include them only when re
#[command(about = "Log out")]
Logout,
#[command(
- about = "Send a raw API request",
+ about = "Make an authenticated API request",
after_help = "The response body is written unchanged, including when --json is set."
)]
Api(ApiArgs),
@@ -100,7 +100,7 @@ pub struct LoginArgs {
#[arg(
long,
conflicts_with = "account",
- help = "Name for a new saved account; defaults to the account's email"
+ help = "Name for a new account on this device; defaults to the account's email"
)]
pub name: Option<String>,
#[arg(
@@ -142,28 +142,28 @@ pub enum AlbumCommand {
#[derive(Subcommand)]
pub enum AccountCommand {
- #[command(about = "List saved accounts")]
+ #[command(about = "List accounts on this device")]
List,
- #[command(about = "Show a saved account")]
+ #[command(about = "Show an account")]
View {
- #[arg(help = "Saved account name")]
+ #[arg(help = "Account name")]
name: String,
},
#[command(about = "Make an account the selected one")]
Switch {
- #[arg(help = "Saved account name")]
+ #[arg(help = "Account name")]
name: String,
},
#[command(about = "Change an account's local name")]
Rename {
- #[arg(help = "Saved account name")]
+ #[arg(help = "Account name")]
name: String,
#[arg(help = "New local name")]
new_name: String,
},
- #[command(about = "Forget an account on this machine; remote sessions stay valid")]
+ #[command(about = "Forget an account on this device; remote sessions stay valid")]
Remove {
- #[arg(help = "Saved account name")]
+ #[arg(help = "Account name")]
name: String,
},
}
@@ -200,6 +200,14 @@ impl Product {
}
}
+ pub fn display_name(self) -> &'static str {
+ match self {
+ Self::Photos => "Ente Photos",
+ Self::Locker => "Ente Locker",
+ Self::Auth => "Ente Auth",
+ }
+ }
+
pub fn client_package(self) -> &'static str {
match self {
Self::Photos => "io.ente.photos",
diff --git a/rust/apps/cli-next/src/login.rs b/rust/apps/cli-next/src/login.rs
index 2f0971600c..6e4cc17136 100644
--- a/rust/apps/cli-next/src/login.rs
+++ b/rust/apps/cli-next/src/login.rs
@@ -10,7 +10,7 @@ use ente_accounts::{
AuthFlow, AuthFlowUi, DEFAULT_API_ORIGIN, LoginParams, OtpPurpose, SecondFactorMethod,
TotpPurpose,
};
-use ente_core::http::{Api, ApiConfig};
+use ente_core::http::{Api, ApiConfig, Http};
use serde::Deserialize;
use url::Url;
use uuid::Uuid;
@@ -24,27 +24,36 @@ use crate::{
};
pub async fn login(
- vault: Vault,
product: Product,
args: LoginArgs,
selected: Option<&str>,
) -> Result<(State, usize)> {
+ let requested_origin = match selected {
+ Some(_) => None,
+ None => Some(normalize_host(
+ args.host.as_deref().unwrap_or(DEFAULT_API_ORIGIN),
+ )?),
+ };
+ let credentials = args.input.as_deref().map(Credentials::read).transpose()?;
+ let vault = Vault::open()?;
let (expected, origin) = match selected {
Some(name) => {
let account = &vault.state.accounts[vault.state.named(name)?];
(Some(account.storage_id), account.origin.clone())
}
- None => (
- None,
- normalize_host(args.host.as_deref().unwrap_or(DEFAULT_API_ORIGIN))?,
- ),
+ None => (None, requested_origin.unwrap()),
};
let (snapshot, access) = vault.release();
- Api::new(api::http()?.into(), ApiConfig::new(origin.clone()))
+ let mut config = ApiConfig::new(origin.clone());
+ config.user_agent = Some(api::USER_AGENT.into());
+ Api::new(Http::new()?, config)
.ping()
.await
.context("cannot reach the selected Ente server")?;
- let (params, mut ui) = LoginUi::read(args.input.as_deref())?;
+ let (params, mut ui) = match credentials {
+ Some(credentials) => credentials.into_login(),
+ None => LoginUi::prompt()?,
+ };
let client = api::accounts_client(&origin, product)?;
let mut authenticated = AuthFlow::new(&client, &mut ui).login(params).await?;
client.set_auth_token(Some(ente_core::b64::encode_url_safe(
@@ -63,16 +72,11 @@ pub async fn login(
ensure!(
snapshot_existing
.is_some_and(|index| snapshot.accounts[index].storage_id == expected),
- "authenticated identity does not match --account; local state has not changed"
+ "authenticated identity does not match --account"
);
}
let mut new_name = requested_name.unwrap_or_else(|| email.clone());
- if snapshot_existing.is_some() {
- ensure!(
- !supplied_name,
- "account already exists; use account rename to change its local name"
- );
- } else {
+ if snapshot_existing.is_none() {
while let Err(error) = snapshot.check_name(&new_name) {
if !ui.interactive {
return Err(error);
@@ -97,18 +101,15 @@ pub async fn login(
.accounts
.iter()
.position(|account| account.storage_id == expected)
- .context(
- "selected account was removed during login; local state has not changed",
- )?;
+ .context("selected account was removed during login")?;
ensure!(
existing == Some(current),
- "authenticated identity does not match --account; local state has not changed"
+ "authenticated identity does not match --account"
);
}
let identity = AccountKeys {
master_key: std::mem::take(&mut authenticated.secrets.master_key),
secret_key: std::mem::take(&mut authenticated.secrets.secret_key),
- public_key: std::mem::take(&mut authenticated.secrets.public_key),
};
let session = StoredSession {
token: std::mem::take(&mut authenticated.secrets.token),
@@ -200,29 +201,34 @@ struct Credentials {
totp: Option<String>,
}
+impl Credentials {
+ fn read(path: &Path) -> Result<Self> {
+ parse_json(&read_input(path)?)
+ .context("login input must contain email and password, with optional otp and totp")
+ }
+
+ fn into_login(mut self) -> (LoginParams, LoginUi) {
+ let params = LoginParams {
+ email: std::mem::take(&mut self.email),
+ password: Zeroizing::new(std::mem::take(&mut self.password)),
+ };
+ (
+ params,
+ LoginUi {
+ interactive: false,
+ credentials: Some(self),
+ },
+ )
+ }
+}
+
struct LoginUi {
interactive: bool,
credentials: Option<Credentials>,
}
impl LoginUi {
- fn read(path: Option<&Path>) -> Result<(LoginParams, Self)> {
- if let Some(path) = path {
- let mut credentials: Credentials = parse_json(&read_input(path)?).context(
- "login input must contain email and password, with optional otp and totp",
- )?;
- let params = LoginParams {
- email: std::mem::take(&mut credentials.email),
- password: Zeroizing::new(std::mem::take(&mut credentials.password)),
- };
- return Ok((
- params,
- Self {
- interactive: false,
- credentials: Some(credentials),
- },
- ));
- }
+ fn prompt() -> Result<(LoginParams, Self)> {
ensure!(
io::stdin().is_terminal() && io::stderr().is_terminal(),
"noninteractive login requires --input <file> or --input -"
diff --git a/rust/apps/cli-next/src/main.rs b/rust/apps/cli-next/src/main.rs
index e99ebb45cd..15c898b76e 100644
--- a/rust/apps/cli-next/src/main.rs
+++ b/rust/apps/cli-next/src/main.rs
@@ -2,7 +2,6 @@ mod api;
mod args;
mod login;
mod output;
-mod permissions;
mod vault;
use std::{
@@ -12,10 +11,7 @@ use std::{
use anyhow::{Context, Result};
use clap::Parser;
-use ente_core::{
- b64,
- crypto::{Key, PublicKey, SecretKey},
-};
+use ente_core::{b64, crypto::Key};
use ente_photos::collections;
use serde::de::DeserializeOwned;
use serde_json::json;
@@ -81,16 +77,11 @@ async fn album_list(selected: Option<&str>, json_output: bool) -> Result<()> {
let state = State::load()?;
let account = &state.accounts[state.resolve(selected)?];
let session = api::session(account, Product::Photos)?;
- let albums = collections::list(
- &session,
- account.user_id,
- &PublicKey::try_from_slice(&account.identity.public_key)?,
- &SecretKey::try_from_slice(&account.identity.secret_key)?,
- )
- .await?
- .into_iter()
- .map(AlbumView::try_from)
- .collect::<Result<Vec<_>>>()?;
+ let albums = collections::list(&session)
+ .await?
+ .into_iter()
+ .map(AlbumView::try_from)
+ .collect::<Result<Vec<_>>>()?;
if json_output {
output::json(&albums)
} else {
@@ -111,12 +102,12 @@ async fn session(
api::raw(&state.accounts[index], product, args).await
}
SessionCommand::Login(args) => {
- let (state, index) = login::login(Vault::open()?, product, args, selected).await?;
+ let (state, index) = login::login(product, args, selected).await?;
let account = AccountView::new(&state.accounts[index], state.selected);
if json_output {
output::json(&json!({ "account": account, "product": product }))
} else {
- output::accounts(&[account])
+ output::account(&account)
}
}
SessionCommand::Logout => {
@@ -138,7 +129,7 @@ async fn session(
output::action(
json_output,
&json!({ "account": name, "product": product, "loggedOut": true }),
- &format!("Logged out of {} for {:?}.", product.name(), name),
+ &format!("Logged out of {} for {:?}.", product.display_name(), name),
)
}
}
@@ -165,7 +156,7 @@ fn account_command(command: AccountCommand, json_output: bool) -> Result<()> {
if json_output {
output::json(&account)
} else {
- output::accounts(&[account])
+ output::account(&account)
}
}
AccountCommand::Switch { name } => {
@@ -211,7 +202,7 @@ fn output_account(state: State, index: usize, json_output: bool) -> Result<()> {
if json_output {
output::json(&account)
} else {
- output::accounts(&[account])
+ output::account(&account)
}
}
diff --git a/rust/apps/cli-next/src/output.rs b/rust/apps/cli-next/src/output.rs
index 32de676980..99a6ed0e81 100644
--- a/rust/apps/cli-next/src/output.rs
+++ b/rust/apps/cli-next/src/output.rs
@@ -2,6 +2,7 @@ use std::io::Write;
use anyhow::{Context, Result};
use chrono::{DateTime, SecondsFormat};
+use dialoguer::console::{Alignment, measure_text_width, pad_str};
use ente_photos::collections::{Collection, Visibility};
use serde::Serialize;
use uuid::Uuid;
@@ -37,7 +38,7 @@ pub struct AlbumView {
id: String,
name: String,
#[serde(rename = "type")]
- kind: String,
+ kind: &'static str,
visibility: &'static str,
owner_id: String,
updated_at: String,
@@ -53,7 +54,7 @@ impl TryFrom<Collection> for AlbumView {
Ok(Self {
id: album.id.to_string(),
name: album.name,
- kind: album.kind,
+ kind: album.kind.name(),
visibility: match album.visibility {
Visibility::Visible => "visible",
Visibility::Archived => "archived",
@@ -82,23 +83,52 @@ pub fn action(as_json: bool, value: &impl Serialize, message: &str) -> Result<()
pub fn accounts(accounts: &[AccountView<'_>]) -> Result<()> {
let mut stdout = std::io::stdout().lock();
- writeln!(stdout, "SELECTED\tNAME\tEMAIL\tHOST\tPRODUCTS\tID")?;
- for account in accounts {
- let products = account
- .products
- .iter()
- .map(|p| p.name())
- .collect::<Vec<_>>()
- .join(",");
+ if accounts.is_empty() {
+ return writeln!(stdout, "No accounts on this device.").map_err(Into::into);
+ }
+ let rows = accounts
+ .iter()
+ .map(|account| {
+ [
+ if account.selected { "*" } else { "" }.to_owned(),
+ escape_controls(account.name),
+ escape_controls(account.email),
+ escape_controls(account.host),
+ products(account),
+ account.id.clone(),
+ ]
+ })
+ .collect::<Vec<_>>();
+ write_table(
+ &mut stdout,
+ ["SELECTED", "NAME", "EMAIL", "HOST", "LOGGED IN", "ID"],
+ &rows,
+ )
+}
+
+pub fn account(account: &AccountView<'_>) -> Result<()> {
+ let fields = [
+ ("Name", escape_controls(account.name)),
+ ("Email", escape_controls(account.email)),
+ ("Host", escape_controls(account.host)),
+ ("Logged in", products(account)),
+ (
+ "Selected",
+ if account.selected { "yes" } else { "no" }.to_owned(),
+ ),
+ ("ID", account.id.clone()),
+ ];
+ let width = fields
+ .iter()
+ .map(|(name, _)| measure_text_width(name))
+ .max()
+ .unwrap();
+ let mut stdout = std::io::stdout().lock();
+ for (name, value) in fields {
writeln!(
stdout,
- "{}\t{}\t{}\t{}\t{}\t{}",
- if account.selected { "*" } else { "" },
- escape_controls(account.name),
- escape_controls(account.email),
- escape_controls(account.host),
- products,
- account.id
+ "{} {value}",
+ pad_str(name, width, Alignment::Left, None)
)?;
}
Ok(())
@@ -106,18 +136,72 @@ pub fn accounts(accounts: &[AccountView<'_>]) -> Result<()> {
pub fn albums(albums: &[AlbumView]) -> Result<()> {
let mut stdout = std::io::stdout().lock();
- writeln!(stdout, "ID\tNAME\tTYPE\tVISIBILITY\tOWNER\tUPDATED")?;
- for album in albums {
- writeln!(
- stdout,
- "{}\t{}\t{}\t{}\t{}\t{}",
- album.id,
- escape_controls(&album.name),
- escape_controls(&album.kind),
- album.visibility,
- album.owner_id,
- album.updated_at
- )?;
+ if albums.is_empty() {
+ return writeln!(stdout, "No albums.").map_err(Into::into);
+ }
+ let rows = albums
+ .iter()
+ .map(|album| {
+ [
+ album.id.clone(),
+ escape_controls(&album.name),
+ album.kind.to_owned(),
+ album.visibility.to_owned(),
+ album.owner_id.clone(),
+ album.updated_at.clone(),
+ ]
+ })
+ .collect::<Vec<_>>();
+ write_table(
+ &mut stdout,
+ ["ID", "NAME", "TYPE", "VISIBILITY", "OWNER", "UPDATED"],
+ &rows,
+ )
+}
+
+fn products(account: &AccountView<'_>) -> String {
+ let products = account
+ .products
+ .iter()
+ .map(|product| product.name())
+ .collect::<Vec<_>>()
+ .join(",");
+ if products.is_empty() {
+ "none".to_owned()
+ } else {
+ products
+ }
+}
+
+fn write_table<const N: usize>(
+ out: &mut impl Write,
+ header: [&str; N],
+ rows: &[[String; N]],
+) -> Result<()> {
+ let header = header.map(str::to_owned);
+ let widths: [usize; N] = std::array::from_fn(|column| {
+ std::iter::once(&header)
+ .chain(rows)
+ .map(|row| measure_text_width(&row[column]))
+ .max()
+ .unwrap()
+ });
+ for row in std::iter::once(&header).chain(rows) {
+ for (column, cell) in row.iter().enumerate() {
+ if column > 0 {
+ write!(out, " ")?;
+ }
+ if column + 1 == N {
+ write!(out, "{cell}")?;
+ } else {
+ write!(
+ out,
+ "{}",
+ pad_str(cell, widths[column], Alignment::Left, None)
+ )?;
+ }
+ }
+ writeln!(out)?;
}
Ok(())
}
@@ -136,7 +220,7 @@ fn escape_controls(value: &str) -> String {
#[cfg(test)]
mod tests {
- use super::escape_controls;
+ use super::{escape_controls, write_table};
#[test]
fn human_output_preserves_printable_names() {
@@ -145,4 +229,22 @@ mod tests {
"Bob's \"album\"\\t\\n"
);
}
+
+ #[test]
+ fn human_tables_align_unicode_cells() {
+ let mut output = Vec::new();
+ write_table(
+ &mut output,
+ ["NAME", "LOGGED IN"],
+ &[
+ ["猫".to_owned(), "photos".to_owned()],
+ ["longer".to_owned(), "auth".to_owned()],
+ ],
+ )
+ .unwrap();
+ assert_eq!(
+ String::from_utf8(output).unwrap(),
+ "NAME LOGGED IN\n猫 photos\nlonger auth\n"
+ );
+ }
}
diff --git a/rust/apps/cli-next/src/permissions.rs b/rust/apps/cli-next/src/permissions.rs
deleted file mode 100644
index 4834b71ebd..0000000000
--- a/rust/apps/cli-next/src/permissions.rs
+++ /dev/null
@@ -1,75 +0,0 @@
-use std::{fs, io, path::Path};
-
-#[cfg(unix)]
-pub fn create_home(path: &Path) -> io::Result<()> {
- use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
- fs::DirBuilder::new()
- .recursive(true)
- .mode(0o700)
- .create(path)?;
- fs::set_permissions(path, fs::Permissions::from_mode(0o700))
-}
-
-#[cfg(windows)]
-pub fn create_home(path: &Path) -> io::Result<()> {
- use std::{os::windows::ffi::OsStrExt, ptr};
- use windows_sys::Win32::{
- Foundation::LocalFree,
- Security::{
- Authorization::{
- ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
- SE_FILE_OBJECT, SetNamedSecurityInfoW,
- },
- DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl,
- PROTECTED_DACL_SECURITY_INFORMATION,
- },
- };
-
- fs::create_dir_all(path)?;
- let path: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
- // Protected DACL: only the owner, inherited by new files and directories.
- let sddl: Vec<u16> = "D:P(A;OICI;FA;;;OW)\0".encode_utf16().collect();
- let mut descriptor = ptr::null_mut();
- // SAFETY: all pointers refer to live buffers. Windows allocates descriptor;
- // the DACL borrows it until SetNamedSecurityInfoW finishes, then we free it.
- unsafe {
- if ConvertStringSecurityDescriptorToSecurityDescriptorW(
- sddl.as_ptr(),
- SDDL_REVISION_1,
- &mut descriptor,
- ptr::null_mut(),
- ) == 0
- {
- return Err(io::Error::last_os_error());
- }
- let mut present = 0;
- let mut defaulted = 0;
- let mut dacl = ptr::null_mut();
- let result = if GetSecurityDescriptorDacl(
- descriptor,
- &mut present,
- &mut dacl,
- &mut defaulted,
- ) == 0
- {
- Err(io::Error::last_os_error())
- } else {
- let status = SetNamedSecurityInfoW(
- path.as_ptr(),
- SE_FILE_OBJECT,
- DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
- ptr::null_mut(),
- ptr::null_mut(),
- dacl,
- ptr::null_mut(),
- );
- if status == 0 {
- Ok(())
- } else {
- Err(io::Error::from_raw_os_error(status as i32))
- }
- };
- LocalFree(descriptor);
- result
- }
-}
diff --git a/rust/apps/cli-next/src/vault.rs b/rust/apps/cli-next/src/vault.rs
index 9092b0ecc0..68ac908c1b 100644
--- a/rust/apps/cli-next/src/vault.rs
+++ b/rust/apps/cli-next/src/vault.rs
@@ -2,7 +2,7 @@ use std::{
collections::BTreeMap,
env,
fs::{self, File, OpenOptions},
- io::ErrorKind,
+ io::{self, ErrorKind},
path::{Path, PathBuf},
};
@@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize};
use uuid::Uuid;
use zeroize::{ZeroizeOnDrop, Zeroizing};
-use crate::{args::Product, parse_json, permissions};
+use crate::{args::Product, parse_json};
const SCHEMA_VERSION: u8 = 1;
const VAULT_FILE: &str = "vault.json";
@@ -65,7 +65,6 @@ pub struct Account {
pub struct AccountKeys {
pub master_key: Vec<u8>,
pub secret_key: Vec<u8>,
- pub public_key: Vec<u8>,
}
#[derive(Serialize, Deserialize, ZeroizeOnDrop)]
@@ -77,7 +76,7 @@ impl Vault {
pub fn open() -> Result<Self> {
let override_key = environment_key()?;
let home = application_home()?;
- permissions::create_home(&home).context("cannot create private CLI home")?;
+ create_home(&home).context("cannot create private CLI home")?;
let home = fs::canonicalize(home)?;
let lock = lock(&home)?;
let encrypted = read_vault(&home)?;
@@ -227,6 +226,20 @@ fn read_vault(home: &Path) -> Result<Option<Vec<u8>>> {
}
}
+fn create_home(path: &Path) -> io::Result<()> {
+ #[cfg(unix)]
+ use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
+
+ let mut builder = fs::DirBuilder::new();
+ builder.recursive(true);
+ #[cfg(unix)]
+ builder.mode(0o700);
+ builder.create(path)?;
+ #[cfg(unix)]
+ fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
+ Ok(())
+}
+
fn lock(home: &Path) -> Result<File> {
let mut options = OpenOptions::new();
options.read(true).write(true).create(true);
@@ -312,26 +325,22 @@ fn keyring_error(error: keyring::Error, exists: bool) -> anyhow::Error {
}
fn decrypt(bytes: &[u8], key: &Key) -> Result<State> {
- let unlock_error = || {
- anyhow::anyhow!(
- "cannot unlock CLI vault: wrong key or damaged ciphertext; it has not been modified"
- )
- };
- let encrypted: EncryptedVault = parse_json(bytes)
- .context("unsupported or invalid CLI vault format; it has not been modified")?;
- let ciphertext = b64::decode(&encrypted.data).map_err(|_| {
- anyhow::anyhow!("unsupported or invalid CLI vault format; it has not been modified")
- })?;
+ let unlock_error =
+ || anyhow::anyhow!("cannot unlock CLI vault: wrong key or damaged ciphertext");
+ let encrypted: EncryptedVault =
+ parse_json(bytes).context("unsupported or invalid CLI vault format")?;
+ let ciphertext = b64::decode(&encrypted.data)
+ .map_err(|_| anyhow::anyhow!("unsupported or invalid CLI vault format"))?;
let plaintext =
Zeroizing::new(blob::decrypt_combined(&ciphertext, key).map_err(|_| unlock_error())?);
let version: VersionedState<serde::de::IgnoredAny> =
- parse_json(&plaintext).context("invalid CLI vault contents; it has not been modified")?;
+ parse_json(&plaintext).context("invalid CLI vault contents")?;
ensure!(
version.schema_version == SCHEMA_VERSION,
- "unsupported CLI vault schema; it has not been modified"
+ "unsupported CLI vault schema"
);
let stored: VersionedState<State> =
- parse_json(&plaintext).context("invalid CLI vault contents; it has not been modified")?;
+ parse_json(&plaintext).context("invalid CLI vault contents")?;
Ok(stored.state)
}
diff --git a/rust/apps/cli-next/tests/cli.rs b/rust/apps/cli-next/tests/cli.rs
index 48d8e56a7e..2075cb4fae 100644
--- a/rust/apps/cli-next/tests/cli.rs
+++ b/rust/apps/cli-next/tests/cli.rs
@@ -19,6 +19,12 @@ fn reads_do_not_initialize_storage() {
if existing_home {
fs::create_dir(&path).unwrap();
}
+ let output = home
+ .command(&["account", "list"])
+ .env("ENTE_CLI_HOME", &path)
+ .output()
+ .unwrap();
+ assert_eq!(success(output).stdout, b"No accounts on this device.\n");
for args in [
vec!["account", "list", "--json"],
vec!["account", "view", "missing"],
@@ -65,6 +71,19 @@ fn reads_do_not_initialize_storage() {
}
}
+#[test]
+fn invalid_login_host_does_not_initialize_storage() {
+ let home = TestHome::new();
+ let path = home.dir.path().join("unused");
+ let output = home
+ .command(&["photos", "login", "--host", "https://["])
+ .env("ENTE_CLI_HOME", &path)
+ .output()
+ .unwrap();
+ assert!(failure(&output).contains("invalid API host"));
+ assert!(!path.exists());
+}
+
#[test]
fn deleted_collections_are_filtered_before_decryption() {
let mut server = mockito::Server::new();
@@ -81,10 +100,15 @@ fn deleted_collections_are_filtered_before_decryption() {
}]})
.to_string(),
)
+ .expect(2)
.create();
let home = TestHome::new();
home.seed(&server.url());
assert_eq!(home.json(&["photos", "album", "list"]), json!([]));
+ assert_eq!(
+ success(home.run(&["photos", "album", "list"])).stdout,
+ b"No albums.\n"
+ );
request.assert();
}
@@ -213,26 +237,9 @@ fn vault_schema_version_is_checked_after_decryption() {
#[tokio::test]
async fn raw_api_preserves_requests_and_responses_without_leaking_credentials() {
let mut origin = mockito::Server::new_async().await;
- let mut other = mockito::Server::new_async().await;
let home = TestHome::new();
home.seed(&origin.url());
let secret = "--8=";
- let escaped = other
- .mock("GET", mockito::Matcher::Any)
- .expect(0)
- .create_async()
- .await;
- let redirect = origin
- .mock("GET", "/redirect")
- .with_status(302)
- .with_header("location", &format!("{}/stolen", other.url()))
- .create_async()
- .await;
- failure(&home.run(&["photos", "api", "/redirect"]));
- failure(&home.run(&["photos", "api", &format!("{}/stolen", other.url())]));
- redirect.assert_async().await;
- escaped.assert_async().await;
-
let headers = home.dir.path().join("headers.json");
fs::write(&headers, br#"{"Host":"different.example.org"}"#).unwrap();
let mismatched_host = origin.mock("GET", "/host").expect(0).create_async().await;
@@ -312,7 +319,7 @@ fn private_json_errors_do_not_echo_values() {
let ping = server
.mock("GET", "/ping")
.with_body(r#"{"message":"pong","id":"fixture"}"#)
- .expect(5)
+ .expect(0)
.create();
let authentication = server
.mock("GET", "/users/srp/attributes")
@@ -321,8 +328,6 @@ fn private_json_errors_do_not_echo_values() {
.create();
let request = server.mock("GET", "/request").expect(0).create();
let home = TestHome::new();
- home.seed(&server.url());
- let original = fs::read(home.dir.path().join("vault.json")).unwrap();
let mut errors = Vec::new();
for input in [
json!({"email": "[email protected]", "password": 987654321}),
@@ -340,6 +345,9 @@ fn private_json_errors_do_not_echo_values() {
assert!(error.contains("login input must contain"), "{error}");
errors.push(error);
}
+ assert_eq!(fs::read_dir(home.dir.path()).unwrap().count(), 0);
+ home.seed(&server.url());
+ let original = fs::read(home.dir.path().join("vault.json")).unwrap();
for input in [
json!({"x-auth-token": 987654321}),
json!("private-987654321"),
@@ -394,11 +402,24 @@ fn logout_reconciles_remote_and_local_session_state() {
.create();
let home = TestHome::new();
home.seed(&server.url());
- success(home.run(&["photos", "logout"]));
+ assert_eq!(
+ success(home.run(&["photos", "logout"])).stdout,
+ b"Logged out of Ente Photos for \"fixture\".\n"
+ );
assert_eq!(
home.json(&["account", "view", "fixture"])["products"],
json!([])
);
+ let origin = server.url();
+ assert_eq!(
+ success(home.run(&["account", "list"])).stdout,
+ format!(
+ "SELECTED NAME EMAIL {host:<width$} LOGGED IN ID\n* fixture [email protected] {origin} none 9007199254740993\n",
+ host = "HOST",
+ width = origin.len()
+ )
+ .as_bytes()
+ );
revoked.assert();
let unavailable = server
@@ -421,6 +442,10 @@ fn logout_reconciles_remote_and_local_session_state() {
fn account_updates_preserve_identity_and_selection() {
let home = TestHome::new();
home.seed("http://localhost:8080");
+ assert_eq!(
+ success(home.run(&["account", "view", "fixture"])).stdout,
+ b"Name fixture\nEmail [email protected]\nHost http://localhost:8080\nLogged in photos\nSelected yes\nID 9007199254740993\n"
+ );
assert_eq!(
home.json(&["account", "list"]),
json!([{
@@ -567,7 +592,7 @@ impl TestHome {
"accounts": [{
"storage_id": id, "name": "fixture", "email": "[email protected]",
"origin": origin, "user_id": 9007199254740993i64,
- "identity": {"master_key": vec![0u8; 32], "secret_key": vec![0u8; 32], "public_key": vec![0u8; 32]},
+ "identity": {"master_key": vec![0u8; 32], "secret_key": vec![0u8; 32]},
"sessions": {"photos": {"token": [0xfb, 0xef]}}
}]
}));
diff --git a/rust/apps/cli-next/tests/support/museum.rs b/rust/apps/cli-next/tests/support/museum.rs
index e920667594..19deb2df0d 100644
--- a/rust/apps/cli-next/tests/support/museum.rs
+++ b/rust/apps/cli-next/tests/support/museum.rs
@@ -32,35 +32,46 @@ fn login_save_failures_follow_the_vault_replacement() -> TestResult {
login(&home, "photos", &email, &["--host", &origin]);
}
let before = session_count(&origin, &owner).await;
- let previous_vault = fs::read(home.dir.path().join("vault.json")).ok();
- let fifo = home.dir.path().join("login-input");
+ let vault_path = home.dir.path().join("vault.json");
+ let previous_vault = fs::read(&vault_path).ok();
+ let snapshot_vault = previous_vault.clone().unwrap_or_else(|| {
+ home.write_vault(&json!({"accounts": [], "selected": null}));
+ fs::read(&vault_path).unwrap()
+ });
+ fs::remove_file(&vault_path).unwrap();
+ // Pause login at its first vault read.
assert!(
Command::new("mkfifo")
- .arg(&fifo)
+ .arg(&vault_path)
.status()
.unwrap()
.success()
);
- let child = home
+ let mut child = home
.command(&[
- "photos",
- "login",
- "--host",
- &origin,
- "--input",
- fifo.to_str().unwrap(),
- "--json",
+ "photos", "login", "--host", &origin, "--input", "-", "--json",
])
+ .stdin(Stdio::piped())
.spawn()
.unwrap();
- // Opening the FIFO waits until login has reached credential input.
- let mut input = fs::OpenOptions::new().write(true).open(&fifo).unwrap();
- let lock_free = fs::File::open(home.dir.path().join("vault.lock"))
+ child
+ .stdin
+ .take()
.unwrap()
- .try_lock()
- .is_ok();
- let concurrent_name = if lock_free && relogin && !before_replacement {
- success(home.run(&["account", "rename", &email, "renamed"]));
+ .write_all(&credentials(&email))
+ .unwrap();
+ let mut snapshot_writer = fs::OpenOptions::new()
+ .write(true)
+ .open(&vault_path)
+ .unwrap();
+ fs::remove_file(&vault_path).unwrap();
+ if let Some(previous) = &previous_vault {
+ fs::write(&vault_path, previous).unwrap();
+ }
+ let concurrent_name = if relogin && !before_replacement {
+ let mut state = home.read_vault();
+ state["accounts"][0]["name"] = json!("renamed");
+ home.write_vault(&state);
Some("renamed")
} else {
None
@@ -71,14 +82,10 @@ fn login_save_failures_follow_the_vault_replacement() -> TestResult {
// Allow replacement, but deny opening the directory for its final sync.
fs::set_permissions(home.dir.path(), fs::Permissions::from_mode(0o300)).unwrap();
}
- input.write_all(&credentials(&email)).unwrap();
- drop(input);
+ snapshot_writer.write_all(&snapshot_vault).unwrap();
+ drop(snapshot_writer);
let output = child.wait_with_output().unwrap();
fs::set_permissions(home.dir.path(), fs::Permissions::from_mode(0o700)).unwrap();
- assert!(
- lock_free,
- "login held the vault lock while waiting for credentials"
- );
if before_replacement {
failure(&output);
assert_eq!(
@@ -132,11 +139,11 @@ async fn exercise(origin: String) -> TestResult {
let alice = create_account(&origin, &alice_email).await;
let alice_id = alice.user_id.to_string();
let bob = create_account(&origin, &bob_email).await;
- let (album, key) = create_album(&origin, &alice, "Monsoon 🌧", false).await;
- let (archive, archive_key) = create_album(&origin, &alice, "Archive", true).await;
- let (hidden, hidden_key) = create_album(&origin, &alice, "Private album", false).await;
+ let (album, key) = create_album(&origin, &alice, "Monsoon 🌧", "folder", false).await;
+ let (archive, archive_key) = create_album(&origin, &alice, "Archive", "album", true).await;
+ let (hidden, hidden_key) = create_album(&origin, &alice, "Private album", "album", false).await;
let (default_hidden, default_hidden_key) =
- create_album(&origin, &alice, "Default hidden", false).await;
+ create_album(&origin, &alice, "Default hidden", "album", false).await;
set_album_metadata(
&origin,
&alice,
@@ -164,7 +171,7 @@ async fn exercise(origin: String) -> TestResult {
json!({"subType": 1}),
)
.await;
- let (bob_album, _) = create_album(&origin, &bob, "Bob's album", false).await;
+ let (bob_album, _) = create_album(&origin, &bob, "Bob's album", "album", false).await;
let shared_key = sealed::seal(
key.as_bytes(),
&PublicKey::try_from_slice(&bob.secrets.public_key).unwrap(),
@@ -226,17 +233,7 @@ async fn exercise(origin: String) -> TestResult {
0
);
let human = String::from_utf8(success(home.run(&["photos", "album", "list"])).stdout).unwrap();
- assert!(human.starts_with("ID\tNAME\tTYPE\tVISIBILITY\tOWNER\tUPDATED\n"));
- let mut listed: Vec<_> = human
- .lines()
- .skip(1)
- .map(|line| {
- let columns: Vec<_> = line.split('\t').collect();
- (columns[1], columns[3])
- })
- .collect();
- listed.sort();
- assert_eq!(listed, expected);
+ assert!(human.starts_with("ID "));
let raw: Value =
serde_json::from_slice(&success(home.run(&["photos", "api", "/collections/v2"])).stdout)
.unwrap();
@@ -418,6 +415,7 @@ async fn create_album(
origin: &str,
owner: &AuthenticatedAccount,
name: &str,
+ kind: &str,
legacy: bool,
) -> (i64, Key) {
let key = Key::generate();
@@ -431,7 +429,7 @@ async fn create_album(
.json(&json!({
"encryptedKey": b64::encode(&wrapped.encrypted_data), "keyDecryptionNonce": b64::encode(wrapped.nonce.as_bytes()),
"name": if legacy { name } else { "" }, "encryptedName": b64::encode(&encrypted_name.encrypted_data),
- "nameDecryptionNonce": b64::encode(encrypted_name.nonce.as_bytes()), "type": "album", "attributes": {"version": 1}
+ "nameDecryptionNonce": b64::encode(encrypted_name.nonce.as_bytes()), "type": kind, "attributes": {"version": 1}
})).send().await.unwrap().error_for_status().unwrap().json().await.unwrap();
(response["collection"]["id"].as_i64().unwrap(), key)
}
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.toml
index 68d0da505b..77da99191f 100644
--- a/rust/apps/ensu/src-tauri/Cargo.toml
+++ b/rust/apps/ensu/src-tauri/Cargo.toml
@@ -29,7 +29,7 @@ libc = "0.2.0"
rustix = { version = "1.1.4", features = ["fs"] }
[target.'cfg(windows)'.dependencies]
-windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_SystemInformation"] }
+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_System_SystemInformation"] }
[features]
custom-protocol = ["tauri/custom-protocol"]
diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rs
index 12d8fecc5c..d209618bac 100644
--- a/rust/crates/accounts/src/client.rs
+++ b/rust/crates/accounts/src/client.rs
@@ -47,12 +47,8 @@ pub struct AccountsClient {
impl AccountsClient {
pub fn new(config: AccountsClientConfig) -> Result<Self> {
- Ok(Self::with_http(config, Http::new()?))
- }
-
- pub fn with_http(config: AccountsClientConfig, http: Http) -> Self {
let api = Api::new(
- http,
+ Http::new()?,
ApiConfig {
origin: config.origin,
client_package: Some(config.client_package.clone()),
@@ -61,10 +57,10 @@ impl AccountsClient {
auth: config.auth_token.map(Auth::User),
},
);
- Self {
+ Ok(Self {
api,
client_package: config.client_package,
- }
+ })
}
pub fn set_auth_token(&self, auth_token: Option<String>) {
diff --git a/rust/crates/core/src/http.rs b/rust/crates/core/src/http.rs
index ba075da764..37a6f6c81c 100644
--- a/rust/crates/core/src/http.rs
+++ b/rust/crates/core/src/http.rs
@@ -100,12 +100,6 @@ pub struct Http {
client: reqwest::Client,
}
-impl From<reqwest::Client> for Http {
- fn from(client: reqwest::Client) -> Self {
- Self { client }
- }
-}
-
impl Http {
pub fn new() -> Result<Self, Error> {
let builder = reqwest::Client::builder();
diff --git a/rust/crates/photos/Cargo.toml b/rust/crates/photos/Cargo.toml
index f5f658ddbb..cf2a52c846 100644
--- a/rust/crates/photos/Cargo.toml
+++ b/rust/crates/photos/Cargo.toml
@@ -4,6 +4,7 @@ edition.workspace = true
[dependencies]
ente-assets.workspace = true
+ente-collections.workspace = true
ente-core.workspace = true
ente-exif.workspace = true
ente-location.workspace = true
@@ -11,7 +12,6 @@ quick-xml.workspace = true
rusqlite = { workspace = true, default-features = true }
serde.workspace = true
thiserror.workspace = true
-zeroize.workspace = true
[dev-dependencies]
tempfile.workspace = true
diff --git a/rust/crates/photos/src/collections.rs b/rust/crates/photos/src/collections.rs
index c043f2990c..e44b709495 100644
--- a/rust/crates/photos/src/collections.rs
+++ b/rust/crates/photos/src/collections.rs
@@ -1,10 +1,10 @@
+use ente_collections::open_collection_key;
use ente_core::{
Session, b64,
- crypto::{self, Header, Key, Nonce, PublicKey, SecretKey, blob, sealed, secretbox},
+ crypto::{self, Header, Nonce, blob, secretbox},
http,
};
use serde::Deserialize;
-use zeroize::Zeroizing;
const DEFAULT_HIDDEN_SUBTYPE: u8 = 1;
const ARCHIVED_VISIBILITY: u8 = 1;
@@ -14,12 +14,29 @@ const HIDDEN_VISIBILITY: u8 = 2;
pub struct Collection {
pub id: i64,
pub name: String,
- pub kind: String,
+ pub kind: Kind,
pub visibility: Visibility,
pub owner_id: i64,
pub updated_at_micros: i64,
}
+#[derive(Debug, Clone, Copy)]
+pub enum Kind {
+ Album,
+ Favorites,
+ Uncategorized,
+}
+
+impl Kind {
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Album => "album",
+ Self::Favorites => "favorites",
+ Self::Uncategorized => "uncategorized",
+ }
+ }
+}
+
#[derive(Debug)]
pub enum Visibility {
Visible,
@@ -35,16 +52,13 @@ pub enum Error {
Crypto(#[from] crypto::Error),
#[error(transparent)]
Base64(#[from] b64::DecodeError),
+ #[error(transparent)]
+ Collections(#[from] ente_collections::Error),
#[error("invalid collection {id}: {reason}")]
InvalidCollection { id: i64, reason: &'static str },
}
-pub async fn list(
- session: &Session,
- user_id: i64,
- public_key: &PublicKey,
- secret_key: &SecretKey,
-) -> Result<Vec<Collection>, Error> {
+pub async fn list(session: &Session) -> Result<Vec<Collection>, Error> {
let response: CollectionsResponse = session
.api
.get("/collections/v2")
@@ -55,26 +69,18 @@ pub async fn list(
.await?
.json()
.await?;
- let master_key = Key::try_from_slice(&session.master_key)?;
-
response
.collections
.into_iter()
.filter(|c| c.is_deleted != Some(true))
.map(|c| {
- let owned = c.owner.id == user_id;
- let encrypted_key = b64::decode(&c.encrypted_key)?;
- let key_bytes = Zeroizing::new(if owned {
- let nonce = c.required(&c.key_decryption_nonce, "missing key nonce")?;
- secretbox::decrypt(
- &encrypted_key,
- &Nonce::try_from_slice(&b64::decode(nonce)?)?,
- &master_key,
- )?
- } else {
- sealed::open(&encrypted_key, public_key, secret_key)?
- });
- let key = Key::try_from_slice(&key_bytes)?;
+ let owned = c.owner.id == session.user_id;
+ let key = open_collection_key(
+ session,
+ c.owner.id,
+ &c.encrypted_key,
+ c.key_decryption_nonce.as_deref(),
+ )?;
let name = match c.name.as_deref().filter(|name| !name.is_empty()) {
Some(name) => name.to_owned(),
None => {
@@ -118,7 +124,11 @@ pub async fn list(
Ok(Collection {
id: c.id,
name,
- kind: c.kind,
+ kind: match c.kind.as_str() {
+ "favorites" => Kind::Favorites,
+ "uncategorized" => Kind::Uncategorized,
+ _ => Kind::Album,
+ },
visibility: match visibility {
ARCHIVED_VISIBILITY => Visibility::Archived,
HIDDEN_VISIBILITY => Visibility::Hidden,