fix(jellyfin): authenticate with the header Jellyfin 12 requires

Jellyfin 12.0 disables legacy authorization by default and its migration
turns it off on upgraded servers (server PR #15559). Sign-in still worked,
but every later request carried the token in X-Emby-Token, so the first
library read answered 401 and the panel reported "Signed in, but library
access failed" (#502).

Send every authenticated request with Authorization: MediaBrowser ... Token
and the install's persisted DeviceId, percent-encode the values the server
URL-decodes, stream with ApiKey instead of api_key, and read libraries from
/UserViews with a 404-only fallback to the obsolete /Users/{id}/Views route
for 10.8. Both modern forms are read by every server since 10.8.

A socket fixture now pins the header shape, the absence of legacy headers
and query keys, the views route and its fallback. Live suites pass against
12.1.0 and 10.11.11, and a token issued by 10.11.11 keeps working after the
same server is migrated to 12.1, so stored sessions need no re-login.

cc
This commit is contained in:
vicrodh committed 2026-09-15 11:14:45 -06:00
1 parent 0e7e1802f5
commit 5a1b29d7e5
6 files changed
+278 -32

No files matched your search

+98 -20
View File
@@ -7,6 +7,21 @@
//! Everything below was MEASURED against Jellyfin 10.11.11 on 2026-08-20; the
//! numbers and the field shapes live in
//! `qbz-nix-docs/qt-frontend/2026-08-20-jellyfin-subsonic/01-research.md`.
//! The request shapes were re-verified against 12.1.0 on 2026-09-15 (#502).
//!
//! # Authorization: one header, every version
//!
//! Jellyfin 12.0 disabled "legacy authorization" by default, and its migration
//! turns it off on upgraded servers too (server PR #15559). With it off the
//! server no longer reads `X-Emby-Token`, `X-MediaBrowser-Token`,
//! `X-Emby-Authorization` or the `api_key` query parameter. Sign-in still
//! succeeds (it carries no token), and then EVERY following request answers
//! 401 — exactly the "Signed in, but library access failed" users reported.
//!
//! The only forms read with legacy authorization off are the `Authorization:
//! MediaBrowser …, Token="…"` header and the `ApiKey` query parameter. Both
//! are also read by every server back to at least 10.8 (checked in the
//! server's `AuthorizationContext`), so this crate uses nothing else.
//!
//! # The three facts that shape this file
//!
@@ -447,6 +462,10 @@ pub struct JellyfinClient {
base: String,
token: String,
user_id: String,
/// The install's persisted DeviceId (see [`auth_header`]). Sent with the
/// token so the server keeps attributing requests to the session that
/// owns it instead of rewriting that device's record.
device_id: String,
}
/// Normalise a user-typed address: strip a trailing slash, default the scheme
@@ -487,19 +506,36 @@ pub fn normalize_base_url(input: &str) -> String {
/// whichever finishes first holding a dead one. This is not hypothetical:
/// it is what five parallel live tests did to each other before they were
/// made to share a session.
///
/// Values are percent-encoded: the server URL-decodes every value it parses
/// (`AuthorizationContext.GetParts`), so a raw `+`, `%`, `"` or `,` would
/// otherwise arrive altered or split the header.
fn auth_header(device_id: &str, token: Option<&str>) -> String {
let mut h = format!(
r#"MediaBrowser Client="QBZ", Device="{}", DeviceId="{}", Version="{}""#,
std::env::consts::OS,
device_id,
env!("CARGO_PKG_VERSION"),
header_value(std::env::consts::OS),
header_value(device_id),
header_value(env!("CARGO_PKG_VERSION")),
);
if let Some(t) = token {
h.push_str(&format!(r#", Token="{t}""#));
h.push_str(&format!(r#", Token="{}""#, header_value(t)));
}
h
}
/// Percent-encode everything outside RFC 3986's unreserved set.
fn header_value(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
for byte in raw.bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
out.push(byte as char);
} else {
out.push_str(&format!("%{byte:02X}"));
}
}
out
}
fn client() -> Result<reqwest::Client> {
reqwest::Client::builder()
.connect_timeout(Duration::from_secs(5))
@@ -717,12 +753,16 @@ fn quick_connect_check(status: reqwest::StatusCode) -> Result<()> {
impl JellyfinClient {
/// Build a client over an EXISTING token (the stored-credentials path).
pub fn new(base_url: &str, token: &str, user_id: &str) -> Result<Self> {
///
/// `device_id` must be the one the token was issued under — the install's
/// persisted id, never a fresh one (see [`auth_header`]).
pub fn new(base_url: &str, token: &str, user_id: &str, device_id: &str) -> Result<Self> {
Ok(Self {
http: client()?,
base: normalize_base_url(base_url),
token: token.to_string(),
user_id: user_id.to_string(),
device_id: device_id.to_string(),
})
}
@@ -730,18 +770,23 @@ impl JellyfinClient {
&self.base
}
async fn get_json<T: for<'de> Deserialize<'de>>(&self, path_and_query: &str) -> Result<T> {
let resp = self
.http
async fn get(&self, path_and_query: &str) -> Result<reqwest::Response> {
self.http
.get(format!("{}{}", self.base, path_and_query))
.header("X-Emby-Token", &self.token)
// THE header, never `X-Emby-Token`: see the module docs.
.header(
"Authorization",
auth_header(&self.device_id, Some(&self.token)),
)
.send()
.await
.map_err(|e| transport_error(&e))?;
.map_err(|e| transport_error(&e))
}
async fn get_json<T: for<'de> Deserialize<'de>>(&self, path_and_query: &str) -> Result<T> {
let resp = self.get(path_and_query).await?;
check(resp.status())?;
resp.json::<T>()
.await
.map_err(|e| JellyfinError::Decode(e.to_string()))
decode(resp).await
}
/// The user's MUSIC libraries (`CollectionType == "music"`).
@@ -749,10 +794,21 @@ impl JellyfinClient {
/// A server also exposes a `playlists` view; it is filtered out here rather
/// than by the caller, because "which of these is music" is a question
/// about Jellyfin, and this crate is where Jellyfin's vocabulary lives.
///
/// `GET /UserViews?userId=` is the current route (10.9+). The older
/// `/Users/{id}/Views` is marked obsolete in 12 and liable for removal, so
/// it is only asked when the current route does not exist (10.8).
pub async fn music_libraries(&self) -> Result<Vec<MusicLibrary>> {
let env: ItemsEnvelope<ViewDto> = self
.get_json(&format!("/Users/{}/Views", self.user_id))
let resp = self
.get(&format!("/UserViews?userId={}", self.user_id))
.await?;
let resp = if resp.status() == reqwest::StatusCode::NOT_FOUND {
self.get(&format!("/Users/{}/Views", self.user_id)).await?
} else {
resp
};
check(resp.status())?;
let env: ItemsEnvelope<ViewDto> = decode(resp).await?;
Ok(env
.items
.into_iter()
@@ -878,6 +934,12 @@ impl JellyfinClient {
}
}
async fn decode<T: for<'de> Deserialize<'de>>(resp: reqwest::Response) -> Result<T> {
resp.json::<T>()
.await
.map_err(|e| JellyfinError::Decode(e.to_string()))
}
fn tracks_page_path(
user_id: &str,
library_id: Option<&str>,
@@ -928,14 +990,17 @@ fn tracks_page_path(
/// `audioBitRate` on this endpoint are exactly how a bit-perfect path becomes a
/// resampled one.
///
/// The token rides in the query string because the feeder takes a URL, not a
/// request builder. That makes this a SECRET-BEARING string: never log it whole.
/// The token rides in the query string because the url is handed to consumers
/// that cannot add headers (a DLNA / Chromecast renderer fetches it itself).
/// `ApiKey`, never `api_key`: the lowercase form is legacy authorization, which
/// Jellyfin 12 no longer reads (module docs). That makes this a SECRET-BEARING
/// string: never log it whole.
pub fn stream_url(base_url: &str, token: &str, item_id: &str) -> String {
format!(
"{}/Audio/{}/stream?static=true&api_key={}",
"{}/Audio/{}/stream?static=true&ApiKey={}",
normalize_base_url(base_url),
item_id,
token
header_value(token)
)
}
@@ -998,6 +1063,18 @@ mod tests {
assert!(auth_header("qbz-abc", Some("sekrit")).contains(r#"Token="sekrit""#));
}
/// The server URL-decodes each value, so anything outside the unreserved
/// set must be encoded or it arrives changed (`+` becomes a space) or ends
/// the value early (`"`, `,`).
#[test]
fn auth_header_values_survive_the_servers_url_decoding() {
let h = auth_header("id+with,odd\"chars", Some("a+b%c"));
assert!(h.starts_with("MediaBrowser "));
assert!(h.contains(r#"DeviceId="id%2Bwith%2Codd%22chars""#), "{h}");
assert!(h.contains(r#"Token="a%2Bb%25c""#), "{h}");
assert_eq!(header_value("qbz-0f3A_9.~"), "qbz-0f3A_9.~");
}
/// A chunked response with no `Content-Length` is the server transcoding.
/// This is the assertion that keeps a bit-perfect path bit-perfect.
#[test]
@@ -1231,8 +1308,9 @@ mod tests {
let u = stream_url("http://h:8096/", "tok", "item42");
assert_eq!(
u,
"http://h:8096/Audio/item42/stream?static=true&api_key=tok"
"http://h:8096/Audio/item42/stream?static=true&ApiKey=tok"
);
assert!(!u.contains("api_key"), "api_key is legacy authorization");
assert!(
!u.contains("audioCodec"),
"a codec parameter IS a transcode"
+143
View File
@@ -0,0 +1,143 @@
//! Wire-level authorization contract (#502). Jellyfin 12 no longer reads the
//! legacy token forms, so every authenticated request must carry the token in
//! `Authorization: MediaBrowser …, Token="…"` — and nothing else. A local socket
//! records exactly what the client sends; CI runs this, unlike `tests/live.rs`.
use qbz_jellyfin::{JellyfinClient, JellyfinError};
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
const VIEWS: &str =
r#"{"Items":[{"Id":"lib","Name":"Music","CollectionType":"music"}],"TotalRecordCount":1}"#;
/// Serve `responses` in order; hand back every raw request received.
async fn server(
responses: Vec<(u16, &'static str)>,
) -> (String, tokio::task::JoinHandle<Vec<String>>) {
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}/jellyfin", listener.local_addr().unwrap());
let task = tokio::spawn(async move {
let mut requests = Vec::new();
for (status, body) in responses {
let (mut socket, _) = tokio::time::timeout(Duration::from_secs(10), listener.accept())
.await
.unwrap()
.unwrap();
let mut bytes = Vec::new();
while !String::from_utf8_lossy(&bytes).contains("\r\n\r\n") {
let mut buf = [0; 4096];
let n = socket.read(&mut buf).await.unwrap();
assert!(n > 0);
bytes.extend_from_slice(&buf[..n]);
}
requests.push(String::from_utf8(bytes).unwrap());
socket
.write_all(
format!(
"HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
)
.as_bytes(),
)
.await
.unwrap();
}
requests
});
(url, task)
}
fn header<'a>(request: &'a str, name: &str) -> Option<&'a str> {
request.lines().find_map(|line| {
let (key, value) = line.split_once(':')?;
key.eq_ignore_ascii_case(name).then(|| value.trim())
})
}
fn assert_modern_authorization(request: &str) {
let auth = header(request, "authorization").expect("no Authorization header");
assert!(auth.starts_with("MediaBrowser "), "{auth}");
assert!(auth.contains(r#"Token="stored-token""#), "{auth}");
assert!(auth.contains(r#"DeviceId="stable-install""#), "{auth}");
for legacy in [
"x-emby-token",
"x-mediabrowser-token",
"x-emby-authorization",
] {
assert!(
header(request, legacy).is_none(),
"legacy header {legacy} sent"
);
}
assert!(!request.contains("api_key"), "legacy api_key query sent");
}
fn client(url: &str) -> JellyfinClient {
JellyfinClient::new(url, "stored-token", "user-1", "stable-install").unwrap()
}
#[tokio::test]
async fn library_reads_use_the_authorization_header_and_the_current_views_route() {
let (url, task) = server(vec![
(200, VIEWS),
(200, r#"{"Items":[],"TotalRecordCount":7}"#),
(200, r#"{"Items":[],"TotalRecordCount":7}"#),
(
200,
r#"{"Items":[{"Id":"t1","Container":"flac"}],"TotalRecordCount":1}"#,
),
])
.await;
let c = client(&url);
assert_eq!(c.music_libraries().await.unwrap()[0].id, "lib");
assert_eq!(c.track_count(Some("lib")).await.unwrap(), 7);
assert_eq!(
c.essential_tracks_page(Some("lib"), 0, None)
.await
.unwrap()
.1,
7
);
assert_eq!(
c.track_quality(&["t1".to_string()]).await.unwrap()[0].id,
"t1"
);
let requests = task.await.unwrap();
assert!(
requests[0].starts_with("GET /jellyfin/UserViews?userId=user-1 HTTP/1.1"),
"{}",
requests[0].lines().next().unwrap()
);
for request in &requests {
assert_modern_authorization(request);
}
}
/// 10.8 has no `/UserViews`; only then is the obsolete route asked.
#[tokio::test]
async fn a_server_without_user_views_falls_back_to_the_obsolete_route() {
let (url, task) = server(vec![(404, ""), (200, VIEWS)]).await;
assert_eq!(client(&url).music_libraries().await.unwrap().len(), 1);
let requests = task.await.unwrap();
assert!(requests[1].starts_with("GET /jellyfin/Users/user-1/Views HTTP/1.1"));
assert_modern_authorization(&requests[1]);
}
#[tokio::test]
async fn a_rejected_token_is_unauthorized_and_does_not_fall_back() {
let (url, task) = server(vec![(401, "")]).await;
assert_eq!(
client(&url).music_libraries().await.unwrap_err(),
JellyfinError::Unauthorized
);
assert_eq!(task.await.unwrap().len(), 1);
}
#[test]
fn the_stream_url_uses_the_modern_query_key() {
let url = qbz_jellyfin::stream_url("http://h:8096", "stored-token", "item");
assert_eq!(
url,
"http://h:8096/Audio/item/stream?static=true&ApiKey=stored-token"
);
}
+1 -1
View File
@@ -67,7 +67,7 @@ async fn session(url: &str, user: &str, pass: &str) -> &'static qbz_jellyfin::Se
/// The authenticated client every live test shares.
async fn client(url: &str, user: &str, pass: &str) -> qbz_jellyfin::JellyfinClient {
let s = session(url, user, pass).await;
qbz_jellyfin::JellyfinClient::new(url, &s.access_token, &s.user_id).unwrap()
qbz_jellyfin::JellyfinClient::new(url, &s.access_token, &s.user_id, "qbz-live-test").unwrap()
}
macro_rules! skip_without_server {
+33 -8
View File
@@ -284,7 +284,7 @@ async fn verified_jellyfin_session(
session: qbz_jellyfin::Session,
mut cfg: MediaServerSettings,
) -> Result<MediaServerSettings, String> {
qbz_jellyfin::JellyfinClient::new(url, &session.access_token, &session.user_id)
qbz_jellyfin::JellyfinClient::new(url, &session.access_token, &session.user_id, &cfg.device_id)
.map_err(|e| e.to_string())?
.music_libraries()
.await
@@ -740,10 +740,13 @@ mod tests {
}
let request = String::from_utf8_lossy(&bytes);
assert!(request.lines().next().unwrap().contains(path));
if path.contains("/Views") {
assert!(request
.to_ascii_lowercase()
.contains("x-emby-token: test-token"));
if path.contains("Views") {
// Jellyfin 12 reads only the modern form (#502).
let lower = request.to_ascii_lowercase();
assert!(lower.contains("authorization: mediabrowser "));
assert!(request.contains(r#"Token="test-token""#));
assert!(request.contains(r#"DeviceId="test-device""#));
assert!(!lower.contains("x-emby-token"));
}
let response = format!("HTTP/1.1 {status} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",body.len());
socket.write_all(response.as_bytes()).await.unwrap();
@@ -761,19 +764,41 @@ mod tests {
const SUB_NO: &str =
r#"{"subsonic-response":{"status":"failed","error":{"code":40,"message":"denied"}}}"#;
for kind in MediaServerKind::ALL {
for mode in ["login-rejected", "library-rejected", "success"] {
// "success-10.8": a server that predates `/UserViews` (10.9) must
// still connect through the obsolete route. Self-hosted servers
// often sit on stable distributions and lag behind releases.
for mode in [
"login-rejected",
"library-rejected",
"success",
"success-10.8",
] {
let responses = match (kind, mode) {
(MediaServerKind::Jellyfin, "login-rejected") => {
vec![("/Users/AuthenticateByName", 401, "{}")]
}
(MediaServerKind::Jellyfin, "library-rejected") => vec![
("/Users/AuthenticateByName", 200, JF_AUTH),
("/Users/uid/Views", 401, "{}"),
("/UserViews?userId=uid", 401, "{}"),
],
(MediaServerKind::Jellyfin, "success-10.8") => vec![
("/Users/AuthenticateByName", 200, JF_AUTH),
("/UserViews?userId=uid", 404, ""),
(
"/Users/uid/Views",
200,
r#"{"Items":[],"TotalRecordCount":0}"#,
),
(
"/System/Info/Public",
200,
r#"{"ServerName":"test","Version":"10.8.13","Id":"server"}"#,
),
],
(MediaServerKind::Jellyfin, _) => vec![
("/Users/AuthenticateByName", 200, JF_AUTH),
(
"/Users/uid/Views",
"/UserViews?userId=uid",
200,
r#"{"Items":[],"TotalRecordCount":0}"#,
),
+2 -2
View File
@@ -292,7 +292,7 @@ pub async fn sync_jellyfin(full: bool) -> Result<SyncReport, String> {
async fn sync_jellyfin_inner(cfg: MediaServerSettings, full: bool) -> Result<SyncReport, String> {
let kind = MediaServerKind::Jellyfin;
let client = qbz_jellyfin::JellyfinClient::new(&cfg.base_url, &cfg.token, &cfg.username)
let client = qbz_jellyfin::JellyfinClient::new(&cfg.base_url, &cfg.token, &cfg.username, &cfg.device_id)
.map_err(|e| e.to_string())?;
// `username` holds the Jellyfin USER ID for the API's purposes — see
// `connect_jellyfin`, which stores the id the auth response returned rather
@@ -548,7 +548,7 @@ async fn jellyfin_quality_worker(epoch: u64) -> Result<(), String> {
if !cfg.is_configured(MediaServerKind::Jellyfin) {
return Ok(());
}
let client = qbz_jellyfin::JellyfinClient::new(&cfg.base_url, &cfg.token, &cfg.username)
let client = qbz_jellyfin::JellyfinClient::new(&cfg.base_url, &cfg.token, &cfg.username, &cfg.device_id)
.map_err(|error| error.to_string())?;
let mut hydrated = 0usize;
let mut batches = 0usize;
+1 -1
View File
@@ -136,7 +136,7 @@ async fn jellyfin_walks_from_a_sweep_to_real_audio() {
.await
.expect("authenticate");
let client =
qbz_jellyfin::JellyfinClient::new(&url, &session.access_token, &session.user_id).unwrap();
qbz_jellyfin::JellyfinClient::new(&url, &session.access_token, &session.user_id, "qbz-e2e").unwrap();
let libs = client.music_libraries().await.expect("libraries");
let (page, total) = client
.tracks_page(Some(&libs[0].id), 0, None)