fix: sanitize LRCLIB lyrics and align admin settings
Build and Publish / Build and Publish Docker Image (push) Successful in 2m11s
Build and Publish / Build and Publish Docker Image (push) Successful in 2m11s
This commit is contained in:
1 parent
964d182e77
commit
8ec3ba3687
7 files changed
+95
-6
No files matched your search
@@ -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<LyricsVersion> {
|
||||
fn version(mut record: Record) -> Option<LyricsVersion> {
|
||||
// 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<LyricsVersion> {
|
||||
};
|
||||
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(),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
|
||||
@@ -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); }
|
||||
|
||||
|
||||
@@ -1031,11 +1031,11 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="panel settings-section" id="settings-lyrics">
|
||||
<section class="panel settings-section settings-lyrics" id="settings-lyrics">
|
||||
<div class="panel-head"><div class="panel-title"><strong>Lyrics · LRCLIB</strong><span>Automatic library enrichment</span></div></div>
|
||||
<div class="setting-toggle">
|
||||
<label class="setting-toggle-row"><span>Fetch lyrics automatically</span><input type="checkbox" x-model="settingsDraft.lyrics_enrichment_enabled" /></label>
|
||||
<div class="setting-help">Requests to the external LRCLIB API reveal track metadata from this library. Disabling stops automatic requests; saved lyrics remain available.</div>
|
||||
<div class="setting-help">External LRCLIB requests reveal track metadata from this library. Saved lyrics remain available when disabled.</div>
|
||||
<span class="source-pill" :class="sourceClass('lyrics_enrichment_enabled')" x-text="settingSource('lyrics_enrichment_enabled')"></span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -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.');
|
||||
|
||||
Reference in new issue
Block a user