fix: log in with the password on servers that refuse tokens

Nextcloud Music answers a token login with Subsonic error 41, so remus
could not log in to it at all. Login now retries with the password,
hex-encoded as the spec allows, when the server returns 41, and saves
which method worked. Servers that accept tokens are unaffected, and
existing login files still load.

Server errors now keep their code. A wrong password on Nextcloud adds a
line about the API password from the Music app's settings, which is not
the Nextcloud login password.
This commit is contained in:
Ansho Rei
2026-11-04 03:44:34 +01:00
parent a74fd1bd5c
commit c12ed3e12d
5 changed files with 358 additions and 59 deletions
+49 -21
View File
@@ -18,7 +18,7 @@ use tokio::sync::Semaphore;
use crate::config::{self, Config};
use crate::player::{Player, PlayerEvent};
use crate::subsonic::{Album, Artist, Client, Playlist, SearchResult, Song};
use crate::subsonic::{self, Album, Artist, Client, Playlist, SearchResult, Song};
use crate::{Action, AppWindow, Area, Header, Hint, Item, Screen, Theme};
thread_local! {
@@ -257,7 +257,7 @@ impl App {
log::info!("using saved login for {} on {}", cfg.username, cfg.url);
self.ui.set_login_server(cfg.url.clone().into());
self.ui.set_login_username(cfg.username.clone().into());
self.enter_browse(Client::new(&cfg.url, &cfg.username, &cfg.salt, &cfg.token));
self.enter_browse(cfg.client());
}
Ok(None) => {
log::info!("no saved login, showing the login screen");
@@ -330,27 +330,22 @@ impl App {
}
self.ui.set_login_error("".into());
self.ui.set_login_busy(true);
let client = Client::from_password(&url, &user, &password);
let probe = client.clone();
self.spawn(async move { probe.ping().await }, move |app, r| {
app.ui.set_login_busy(false);
match r {
Ok(()) => {
app.ui.set_login_password("".into());
let cfg = Config {
url: client.base().to_string(),
username: client.user().to_string(),
salt: client.salt().to_string(),
token: client.token().to_string(),
};
if let Err(e) = config::save(&cfg) {
app.toast(format!("Could not save settings: {e:#}"));
self.spawn(
async move { Client::login(&url, &user, &password).await },
move |app, r| {
app.ui.set_login_busy(false);
match r {
Ok(client) => {
app.ui.set_login_password("".into());
if let Err(e) = config::save(&Config::from_client(&client)) {
app.toast(format!("Could not save settings: {e:#}"));
}
app.enter_browse(client);
}
app.enter_browse(client);
Err(e) => app.ui.set_login_error(login_error(&e).into()),
}
Err(e) => app.ui.set_login_error(format!("{e:#}").into()),
}
});
},
);
}
fn enter_browse(&mut self, client: Client) {
@@ -1734,6 +1729,26 @@ fn tint(seed: &str) -> Color {
Color::from_rgb_u8(to(r), to(g), to(b))
}
/// The message for a failed login, with a pointer to the fix where the
/// server's own message does not give one.
fn login_error(e: &anyhow::Error) -> String {
let msg = format!("{e:#}");
match subsonic::api_error(e) {
Some(a)
if a.code == subsonic::WRONG_CREDENTIALS
&& a.server
.as_deref()
.is_some_and(|s| s.to_lowercase().contains("nextcloud")) =>
{
format!(
"{msg}. Nextcloud Music needs the API password generated in its own \
settings, not your Nextcloud login password."
)
}
_ => msg,
}
}
fn fmt_time(secs: f64) -> String {
let t = secs.max(0.0) as u64;
let (h, m, s) = (t / 3600, (t / 60) % 60, t % 60);
@@ -1794,6 +1809,19 @@ mod tests {
assert_eq!(bucket(5000.0), 1536);
}
#[test]
fn nextcloud_wrong_password_points_at_the_api_password() {
let err = |server: &str| {
anyhow::Error::from(subsonic::ApiError {
code: subsonic::WRONG_CREDENTIALS,
message: "Wrong username or password".into(),
server: Some(server.into()),
})
};
assert!(login_error(&err("nextcloud music")).contains("API password"));
assert_eq!(login_error(&err("navidrome")), "Wrong username or password");
}
#[test]
fn formatting() {
assert_eq!(fmt_time(61.9), "1:01");
+76 -3
View File
@@ -7,14 +7,48 @@ use anyhow::{Context, Result};
use directories::ProjectDirs;
use serde::{Deserialize, Serialize};
/// Server credentials. `token` is md5(password + salt): not the password,
/// but enough to log in to this server, so the file is written 0600.
#[derive(Debug, Clone, Serialize, Deserialize)]
use crate::subsonic::{Auth, Client};
/// Server credentials, written 0600. Either a token, md5(password + salt),
/// which is not the password but is enough to log in to this server; or, for
/// a server that refuses tokens, the password itself.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Config {
pub url: String,
pub username: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub salt: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub token: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub password: Option<String>,
}
impl Config {
pub fn from_client(client: &Client) -> Config {
let (salt, token, password) = match client.auth() {
Auth::Token { salt, token } => (salt.clone(), token.clone(), None),
Auth::Password(p) => (String::new(), String::new(), Some(p.clone())),
};
Config {
url: client.base().to_string(),
username: client.user().to_string(),
salt,
token,
password,
}
}
pub fn client(&self) -> Client {
let auth = match &self.password {
Some(p) => Auth::Password(p.clone()),
None => Auth::Token {
salt: self.salt.clone(),
token: self.token.clone(),
},
};
Client::new(&self.url, &self.username, auth)
}
}
fn dirs() -> Option<ProjectDirs> {
@@ -67,3 +101,42 @@ pub fn save(cfg: &Config) -> Result<()> {
log::info!("saved login to {}", path.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn token_login_from_before_password_auth_still_loads() {
let old = "url = \"https://h\"\nusername = \"u\"\nsalt = \"s\"\ntoken = \"t\"\n";
let cfg: Config = toml::from_str(old).unwrap();
assert_eq!(cfg.password, None);
let auth = Auth::Token {
salt: "s".into(),
token: "t".into(),
};
assert_eq!(*cfg.client().auth(), auth);
}
#[test]
fn each_auth_method_round_trips() {
let token = Auth::Token {
salt: "s".into(),
token: "t".into(),
};
for auth in [token, Auth::Password("sesame".into())] {
let cfg = Config::from_client(&Client::new("https://h", "u", auth.clone()));
let text = toml::to_string(&cfg).unwrap();
let back: Config = toml::from_str(&text).unwrap();
assert_eq!(back, cfg);
assert_eq!(*back.client().auth(), auth);
}
}
#[test]
fn password_login_stores_no_token_fields() {
let cfg = Config::from_client(&Client::new("https://h", "u", Auth::Password("p".into())));
let text = toml::to_string(&cfg).unwrap();
assert!(!text.contains("salt") && !text.contains("token"), "{text}");
}
}
+2
View File
@@ -301,6 +301,8 @@ mod tests {
assert_eq!(s, "Not Found (404), URL: https://h/rest/stream?…, Redirect to: (NULL)");
assert!(!strip_queries("\"http://x/y?t=secret\" next").contains("secret"));
assert_eq!(strip_queries("what? no url here"), "what? no url here");
let s = strip_queries("URL: https://h/rest/stream?u=a&p=enc%3A736573616d65&v=1 failed");
assert!(!s.contains("736573616d65"), "{s}");
}
/// Writes `secs` of silence as a 16-bit mono WAV and returns its file:// URI.
+229 -35
View File
@@ -10,17 +10,53 @@ use serde::de::{DeserializeOwned, Deserializer};
const API_VERSION: &str = "1.16.1";
const CLIENT_NAME: &str = "remus";
/// Subsonic error 41: the server does not accept token authentication.
const TOKEN_AUTH_NOT_SUPPORTED: i64 = 41;
/// Subsonic error 40: wrong username or password.
pub const WRONG_CREDENTIALS: i64 = 40;
/// How requests prove who is asking.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Auth {
/// `t` = md5(password + `s`). The password itself is not kept.
Token { salt: String, token: String },
/// The password, sent hex-encoded on every request. For servers that
/// refuse tokens, such as Nextcloud Music.
Password(String),
}
/// An error reported by the server inside a Subsonic response.
#[derive(Debug)]
pub struct ApiError {
pub code: i64,
pub message: String,
/// The `type` the server reports about itself, such as "nextcloud music".
pub server: Option<String>,
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ApiError {}
/// The server's error code, if `e` is an error reported by the server.
pub fn api_error(e: &anyhow::Error) -> Option<&ApiError> {
e.downcast_ref::<ApiError>()
}
#[derive(Clone)]
pub struct Client {
http: reqwest::Client,
base: String,
user: String,
salt: String,
token: String,
auth: Auth,
}
impl Client {
pub fn new(base: &str, user: &str, salt: &str, token: &str) -> Self {
pub fn new(base: &str, user: &str, auth: Auth) -> Self {
let http = reqwest::Client::builder()
.user_agent(concat!("remus/", env!("CARGO_PKG_VERSION")))
.timeout(std::time::Duration::from_secs(30))
@@ -30,8 +66,7 @@ impl Client {
http,
base: normalize_base(base),
user: user.to_string(),
salt: salt.to_string(),
token: token.to_string(),
auth,
}
}
@@ -40,7 +75,23 @@ impl Client {
pub fn from_password(base: &str, user: &str, password: &str) -> Self {
let salt = random_salt();
let token = format!("{:x}", md5::compute(format!("{password}{salt}")));
Client::new(base, user, &salt, &token)
Client::new(base, user, Auth::Token { salt, token })
}
/// Logs in with a token, or with the password itself when the server
/// refuses tokens. Returns the client that worked.
pub async fn login(base: &str, user: &str, password: &str) -> Result<Client> {
let client = Client::from_password(base, user, password);
match client.ping().await {
Ok(()) => Ok(client),
Err(e) if api_error(&e).is_some_and(|a| a.code == TOKEN_AUTH_NOT_SUPPORTED) => {
log::info!("server does not accept token auth, logging in with the password");
let client = Client::new(base, user, Auth::Password(password.to_string()));
client.ping().await?;
Ok(client)
}
Err(e) => Err(e),
}
}
pub fn base(&self) -> &str {
@@ -49,22 +100,32 @@ impl Client {
pub fn user(&self) -> &str {
&self.user
}
pub fn salt(&self) -> &str {
&self.salt
pub fn auth(&self) -> &Auth {
&self.auth
}
pub fn token(&self) -> &str {
&self.token
/// The query parameters every request starts with.
fn auth_params(&self) -> Vec<(&'static str, String)> {
let mut params = vec![("u", self.user.clone())];
match &self.auth {
Auth::Token { salt, token } => {
params.push(("t", token.clone()));
params.push(("s", salt.clone()));
}
Auth::Password(password) => {
// Hex keeps the password out of plain sight in URLs; it is not encryption.
let hex: String = password.bytes().map(|b| format!("{b:02x}")).collect();
params.push(("p", format!("enc:{hex}")));
}
}
params.push(("v", API_VERSION.to_string()));
params.push(("c", CLIENT_NAME.to_string()));
params.push(("f", "json".to_string()));
params
}
fn endpoint_url(&self, endpoint: &str, params: &[(&str, String)]) -> Result<reqwest::Url> {
let mut all: Vec<(&str, String)> = vec![
("u", self.user.clone()),
("t", self.token.clone()),
("s", self.salt.clone()),
("v", API_VERSION.to_string()),
("c", CLIENT_NAME.to_string()),
("f", "json".to_string()),
];
let mut all = self.auth_params();
all.extend(params.iter().cloned());
reqwest::Url::parse_with_params(&format!("{}/rest/{endpoint}", self.base), &all)
.with_context(|| format!("invalid server url {}", self.base))
@@ -83,22 +144,12 @@ impl Client {
if !status.is_success() {
bail!("{endpoint}: server returned {status}");
}
let mut body: serde_json::Value = resp
let body: serde_json::Value = resp
.json()
.await
.map_err(redact)
.with_context(|| format!("{endpoint}: invalid json"))?;
let inner = body
.get_mut("subsonic-response")
.map(serde_json::Value::take)
.ok_or_else(|| anyhow!("{endpoint}: not a subsonic response"))?;
if inner.get("status").and_then(|s| s.as_str()) != Some("ok") {
let msg = inner
.pointer("/error/message")
.and_then(|m| m.as_str())
.unwrap_or("unknown error");
bail!("{msg}");
}
let inner = unwrap_response(endpoint, body)?;
serde_json::from_value(inner).with_context(|| format!("{endpoint}: unexpected response shape"))
}
@@ -246,6 +297,27 @@ impl Client {
}
}
/// The payload of a Subsonic response, or the server's error as an `ApiError`.
fn unwrap_response(endpoint: &str, mut body: serde_json::Value) -> Result<serde_json::Value> {
let inner = body
.get_mut("subsonic-response")
.map(serde_json::Value::take)
.ok_or_else(|| anyhow!("{endpoint}: not a subsonic response"))?;
if inner.get("status").and_then(|s| s.as_str()) == Some("ok") {
return Ok(inner);
}
Err(ApiError {
code: inner.pointer("/error/code").and_then(|c| c.as_i64()).unwrap_or(0),
message: inner
.pointer("/error/message")
.and_then(|m| m.as_str())
.unwrap_or("unknown error")
.to_string(),
server: inner.get("type").and_then(|s| s.as_str()).map(str::to_string),
}
.into())
}
/// Request URLs carry the auth token, so they must never reach an error
/// message: those end up on screen and in the logs.
fn redact(e: reqwest::Error) -> reqwest::Error {
@@ -425,8 +497,18 @@ mod tests {
#[ignore]
async fn live_server() {
let var = |k| std::env::var(k).unwrap_or_else(|_| panic!("{k} not set"));
let c = Client::from_password(&var("REMUS_TEST_URL"), &var("REMUS_TEST_USER"), &var("REMUS_TEST_PASS"));
c.ping().await.unwrap();
let (url, user, pass) = (var("REMUS_TEST_URL"), var("REMUS_TEST_USER"), var("REMUS_TEST_PASS"));
let Ok(c) = Client::login(&url, &user, &pass).await else {
panic!("login to {url} failed");
};
println!(
"auth: {}",
if matches!(c.auth(), Auth::Token { .. }) {
"token"
} else {
"password"
}
);
let albums = c.album_list("newest", 10, 0).await.unwrap();
assert!(!albums.is_empty(), "no albums");
@@ -467,7 +549,11 @@ mod tests {
#[tokio::test]
async fn errors_never_contain_the_token() {
// Port 1 on loopback refuses the connection, so the request fails.
let c = Client::new("http://127.0.0.1:1", "u", "somesalt", "secrettoken");
let auth = Auth::Token {
salt: "somesalt".into(),
token: "secrettoken".into(),
};
let c = Client::new("http://127.0.0.1:1", "u", auth);
let err = format!("{:#}", c.ping().await.unwrap_err());
assert!(!err.contains("secrettoken"), "token leaked: {err}");
assert!(!err.contains("somesalt"), "salt leaked: {err}");
@@ -475,10 +561,118 @@ mod tests {
assert!(!err.contains("secrettoken"), "token leaked: {err}");
}
#[tokio::test]
async fn errors_never_contain_the_password() {
let c = Client::new("http://127.0.0.1:1", "u", Auth::Password("sesame".into()));
let hex = "736573616d65";
for err in [
format!("{:#}", c.ping().await.unwrap_err()),
format!("{:#}", c.cover_art("al-1", 256).await.unwrap_err()),
] {
assert!(!err.contains("sesame") && !err.contains(hex), "password leaked: {err}");
}
}
#[test]
fn token_is_md5_of_password_and_salt() {
let c = Client::from_password("http://x", "u", "sesame");
let expected = format!("{:x}", md5::compute(format!("sesame{}", c.salt())));
assert_eq!(c.token(), expected);
let Auth::Token { salt, token } = c.auth() else {
panic!("from_password should use a token");
};
assert_eq!(*token, format!("{:x}", md5::compute(format!("sesame{salt}"))));
}
fn query(c: &Client) -> Vec<(String, String)> {
c.endpoint_url("ping", &[])
.unwrap()
.query_pairs()
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect()
}
#[test]
fn token_auth_sends_token_and_salt_only() {
let c = Client::new(
"http://x",
"u",
Auth::Token {
salt: "s1".into(),
token: "t1".into(),
},
);
let q = query(&c);
assert!(q.contains(&("t".into(), "t1".into())));
assert!(q.contains(&("s".into(), "s1".into())));
assert!(!q.iter().any(|(k, _)| k == "p"));
}
#[test]
fn password_auth_sends_the_password_hex_encoded() {
let c = Client::new("http://x", "u", Auth::Password("sesame".into()));
let q = query(&c);
assert!(q.contains(&("u".into(), "u".into())));
assert!(q.contains(&("p".into(), "enc:736573616d65".into())));
assert!(!q.iter().any(|(k, _)| k == "t" || k == "s"));
}
#[test]
fn server_errors_keep_their_code() {
// As Nextcloud Music answers a token login.
let body = serde_json::json!({"subsonic-response": {
"error": {"code": 41, "message": "Token-based authentication not supported"},
"status": "failed", "version": "1.16.1", "type": "nextcloud music", "openSubsonic": true
}});
let e = unwrap_response("ping", body).unwrap_err();
let api = api_error(&e).expect("an ApiError");
assert_eq!(api.code, 41);
assert_eq!(api.server.as_deref(), Some("nextcloud music"));
assert_eq!(e.to_string(), "Token-based authentication not supported");
let ok = serde_json::json!({"subsonic-response": {"status": "ok", "version": "1.16.1"}});
assert!(unwrap_response("ping", ok).is_ok());
}
/// A one-request-per-connection HTTP server on loopback that answers like
/// Nextcloud Music: tokens refused, the password "sesame" accepted.
fn fake_tokenless_server() -> String {
use std::io::{BufRead, BufReader, Write};
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let mut line = String::new();
let mut reader = BufReader::new(stream.try_clone().unwrap());
let _ = reader.read_line(&mut line);
let error = |code: i64, msg: &str| {
format!(
r#"{{"subsonic-response":{{"status":"failed","error":{{"code":{code},"message":"{msg}"}}}}}}"#
)
};
let body = if line.contains("t=") {
error(41, "Token-based authentication not supported")
} else if line.contains("p=enc%3A736573616d65") || line.contains("p=enc:736573616d65") {
r#"{"subsonic-response":{"status":"ok"}}"#.to_string()
} else {
error(40, "Wrong username or password")
};
let _ = write!(
stream,
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
});
format!("http://{addr}")
}
#[tokio::test]
async fn login_falls_back_to_the_password_when_tokens_are_refused() {
let base = fake_tokenless_server();
let c = Client::login(&base, "u", "sesame").await.unwrap();
assert_eq!(*c.auth(), Auth::Password("sesame".into()));
let Err(e) = Client::login(&base, "u", "wrong").await else {
panic!("a wrong password logged in");
};
assert_eq!(api_error(&e).map(|a| a.code), Some(WRONG_CREDENTIALS));
}
}