From 8ec3ba368761c3721c072f109aa2d7444ed9dcb1 Mon Sep 17 00:00:00 2001 From: AB Date: Mon, 23 Nov 2026 02:04:44 +0200 Subject: [PATCH] fix: sanitize LRCLIB lyrics and align admin settings --- src/jobs/lyrics_backfill.rs | 28 +++++++++++++++++++++++-- src/jobs/lyrics_backfill_tests.rs | 22 +++++++++++++++++++ src/lyrics/mod.rs | 35 +++++++++++++++++++++++++++++++ templates/admin/responsive.html | 2 +- templates/admin/styles.html | 3 +++ templates/admin/v2.html | 4 ++-- tests/browser-admin-lyrics.cjs | 7 ++++++- 7 files changed, 95 insertions(+), 6 deletions(-) diff --git a/src/jobs/lyrics_backfill.rs b/src/jobs/lyrics_backfill.rs index 3139235..e7913c8 100644 --- a/src/jobs/lyrics_backfill.rs +++ b/src/jobs/lyrics_backfill.rs @@ -59,6 +59,7 @@ impl Job for LyricsBackfillJob { log.info("Automatic LRCLIB enrichment is disabled; stored lyrics remain available."); return Ok(()); } + log.info("Starting LRCLIB lyrics enrichment; completed lookups will be skipped."); // Prevent overlapping manual/scheduled runs, including across server processes. let mut lock_connection = ctx.pool.begin().await?; let locked: bool = sqlx::query_scalar("SELECT pg_try_advisory_xact_lock(7834219601)") @@ -69,6 +70,9 @@ impl Job for LyricsBackfillJob { return Ok(()); } let result = enrich(ctx, log).await; + if let Err(error) = &result { + log.error(&format!("{error:#}")); + } // Transaction locks are also released if the task is cancelled. lock_connection.rollback().await?; result @@ -147,7 +151,7 @@ async fn enrich(ctx: &JobContext, log: &mut JobLog) -> Result<()> { if !versions.is_empty() { found += 1 } - if processed % 100 == 0 { + if processed == 1 || processed % 25 == 0 { log.info(&format!( "Lyrics: {processed} content items, {found} found, {requests} API lookups." )); @@ -277,7 +281,13 @@ fn matching(record: &Record, track: &Candidate) -> bool { && record.duration.is_finite() && (record.duration - track.duration).abs() <= 2.0 } -fn version(record: Record) -> Option { +fn version(mut record: Record) -> Option { + // JSON permits NUL, but PostgreSQL text/JSONB cannot represent it. Provider + // texts occasionally contain these invisible bytes; remove them before + // parsing LRC or writing either the lookup cache or the content binding. + record.album_name.retain(|c| c != '\0'); + record.plain_lyrics = record.plain_lyrics.map(without_nul); + record.synced_lyrics = record.synced_lyrics.map(without_nul); let synced = record .synced_lyrics .filter(|v| !crate::lyrics::parse_lrc(v).is_empty()); @@ -297,6 +307,11 @@ fn version(record: Record) -> Option { }; value.validate().ok().map(|()| value) } + +fn without_nul(mut text: String) -> String { + text.retain(|c| c != '\0'); + text +} async fn lookup( client: &Client, track: &Candidate, @@ -336,6 +351,15 @@ async fn lookup( mod tests { use super::*; #[test] + fn provider_nul_is_removed_before_cache_and_lrc_parsing() { + let record:Record=serde_json::from_str(r#"{"id":7,"trackName":"Song","artistName":"Artist","albumName":"Al\u0000bum","duration":100,"plainLyrics":"\u0000Words ๐ŸŽต","syncedLyrics":"\u0000[00:01]Wo\u0000rds ๐ŸŽต"}"#).unwrap(); + let lyrics = version(record).unwrap(); + assert_eq!(lyrics.label, "LRCLIB ยท Album"); + assert_eq!(lyrics.plain_text.as_deref(), Some("Words ๐ŸŽต")); + assert_eq!(lyrics.synced_lrc.as_deref(), Some("[00:01]Words ๐ŸŽต")); + assert!(!serde_json::to_string(&lyrics).unwrap().contains("\\u0000")); + } + #[test] fn strict_matching_and_timed_validation() { let track = Candidate { hash: "hash".into(), diff --git a/src/jobs/lyrics_backfill_tests.rs b/src/jobs/lyrics_backfill_tests.rs index d7f32c3..277bfe2 100644 --- a/src/jobs/lyrics_backfill_tests.rs +++ b/src/jobs/lyrics_backfill_tests.rs @@ -91,6 +91,28 @@ async fn postgres_cache_retry_content_binding_and_manual_versions() { "same metadata shares durable API cache" ); let signature = rows[0].signature.clone(); + // Reproduce production's JSONB rejection of provider U+0000, through the + // actual normalization, cache write and text attachment paths. + let rejected = sqlx::query("SELECT $1::jsonb") + .bind(serde_json::json!({"text":"Words\0here"})) + .execute(&pool) + .await + .unwrap_err(); + assert_eq!( + rejected.as_database_error().unwrap().code().as_deref(), + Some("22P05") + ); + let record:Record=serde_json::from_str(r#"{"id":9,"trackName":"Song","artistName":"Artist","albumName":"Al\u0000bum","duration":100,"plainLyrics":"Wo\u0000rds ๐ŸŽต","syncedLyrics":"\u0000[00:01]Words ๐ŸŽต"}"#).unwrap(); + let cleaned = version(record).unwrap(); + sqlx::query("INSERT INTO furumusic__lyrics_lookup(signature,status,versions) VALUES('_nul_fixture','found',$1)") + .bind(serde_json::to_value(vec![&cleaned]).unwrap()).execute(&pool).await.unwrap(); + attach(&pool, &rows[0], std::slice::from_ref(&cleaned)) + .await + .unwrap(); + assert_eq!( + crate::lyrics::versions(&pool, &rows[0].hash).await.unwrap(), + vec![cleaned] + ); sqlx::query("INSERT INTO furumusic__lyrics_lookup(signature,status) VALUES($1,'not_found')") .bind(&signature) .execute(&pool) diff --git a/src/lyrics/mod.rs b/src/lyrics/mod.rs index 56c4817..c52ba24 100644 --- a/src/lyrics/mod.rs +++ b/src/lyrics/mod.rs @@ -94,6 +94,22 @@ pub fn validate_edit(body: &LyricsEdit) -> Result<()> { let mut ids = std::collections::HashSet::new(); for version in &body.versions { version.validate()?; + let fields = [ + Some(version.id.as_str()), + Some(version.label.as_str()), + Some(version.source.as_str()), + version.source_id.as_deref(), + version.language.as_deref(), + version.plain_text.as_deref(), + version.synced_lrc.as_deref(), + ]; + anyhow::ensure!( + fields + .into_iter() + .flatten() + .all(|text| !text.contains('\0')), + "lyrics cannot contain the NUL character (U+0000)" + ); anyhow::ensure!(ids.insert(&version.id), "duplicate version id"); } anyhow::ensure!( @@ -195,6 +211,25 @@ pub fn parse_lrc(value: &str) -> Vec<(i64, String)> { mod tests { use super::*; #[test] + fn manual_lyrics_reject_nul_before_database_writes() { + let version = LyricsVersion { + id: "manual:1".into(), + label: "Original".into(), + source: "manual".into(), + source_id: None, + language: None, + plain_text: Some("Words\0here".into()), + synced_lrc: None, + instrumental: false, + }; + let error = validate_edit(&LyricsEdit { + versions: vec![version], + retry_lookup: false, + }) + .unwrap_err(); + assert!(error.to_string().contains("U+0000")); + } + #[test] fn lrc_timestamps_offsets_and_malformed_metadata() { assert_eq!( parse_lrc( diff --git a/templates/admin/responsive.html b/templates/admin/responsive.html index fe31253..d50b971 100644 --- a/templates/admin/responsive.html +++ b/templates/admin/responsive.html @@ -70,7 +70,7 @@ html { overscroll-behavior:none; } .task-form-body { overflow:visible; } .run-log-body { min-height:300px; overflow:visible; } .run-log-output { min-height:50dvh; max-height:70dvh; } - .settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "actions"; } + .settings-layout { grid-template-columns:minmax(0,1fr); grid-template-areas:"access" "oidc" "agent" "agentstatus" "similarity" "similaritystatus" "downloads" "federation" "lastfm" "developer" "lyrics" "actions"; } .settings-federation-body { grid-template-columns:minmax(0,1fr); } .repair-shell { grid-template-columns:250px minmax(0,1fr); } } diff --git a/templates/admin/styles.html b/templates/admin/styles.html index 03d0a4a..b3c0f70 100644 --- a/templates/admin/styles.html +++ b/templates/admin/styles.html @@ -867,6 +867,7 @@ tbody tr:hover { "downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads downloads" "federation federation federation federation federation federation federation federation federation federation federation federation" "lastfm lastfm lastfm lastfm lastfm lastfm lastfm lastfm developer developer developer developer" + "lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics lyrics" "actions actions actions actions actions actions actions actions actions actions actions actions"; gap: 16px; align-items: stretch; @@ -889,6 +890,8 @@ tbody tr:hover { .settings-downloads { grid-area: downloads; } .settings-federation { grid-area: federation; } .settings-lastfm { grid-area: lastfm; } +.settings-lyrics { grid-area: lyrics; } +.settings-lyrics > .setting-toggle {margin:0 16px 16px} .settings-developer { grid-area: developer; } .settings-section-narrow { border-left: 2px solid rgba(29, 185, 84, 0.55); } diff --git a/templates/admin/v2.html b/templates/admin/v2.html index c1fc245..0b158d4 100644 --- a/templates/admin/v2.html +++ b/templates/admin/v2.html @@ -1031,11 +1031,11 @@ -
+
Lyrics ยท LRCLIBAutomatic library enrichment
-
Requests to the external LRCLIB API reveal track metadata from this library. Disabling stops automatic requests; saved lyrics remain available.
+
External LRCLIB requests reveal track metadata from this library. Saved lyrics remain available when disabled.
diff --git a/tests/browser-admin-lyrics.cjs b/tests/browser-admin-lyrics.cjs index 4691d61..fb647a9 100644 --- a/tests/browser-admin-lyrics.cjs +++ b/tests/browser-admin-lyrics.cjs @@ -4,7 +4,7 @@ const html=fs.readFileSync('target/lyrics-admin-fixture.html','utf8'),alpine=fs. (async()=>{ const browser=await chromium.launch({headless:true,...(process.env.CHROME_PATH?{executablePath:process.env.CHROME_PATH}:{})}); try { - for(const viewport of [{width:1440,height:1000},{width:390,height:844}]){ + for(const viewport of [{width:1920,height:1080},{width:1440,height:1000},{width:390,height:844}]){ const page=await browser.newPage({viewport}),errors=[];page.on('pageerror',e=>errors.push(e.message)); await page.route('**/*',route=>{ const url=new URL(route.request().url()); @@ -37,6 +37,11 @@ const html=fs.readFileSync('target/lyrics-admin-fixture.html','utf8'),alpine=fs. const toggle=page.locator('#settings-lyrics input[type=checkbox]');await toggle.waitFor({state:'visible'}); const toggleBox=await toggle.boundingBox();assert.ok(toggleBox.width<=20&&toggleBox.height<=20); assert.equal(await toggle.isChecked(),true); + const layout=await page.locator('.settings-layout').boundingBox(),lyrics=await page.locator('#settings-lyrics').boundingBox(); + assert.ok(lyrics.width>=layout.width*0.9,'lyrics must occupy the full settings row'); + assert.equal(await page.locator('#settings-lyrics').evaluate(el=>getComputedStyle(el).gridArea),'lyrics'); + await page.locator('#settings-lyrics').scrollIntoViewIfNeeded(); + await page.screenshot({path:`target/lyrics-settings-${viewport.width}.png`,fullPage:true}); assert.deepEqual(errors,[]);await page.close(); } console.log('Lyrics admin desktop/mobile checks passed.');