[GH-ISSUE #2318] [Issue]: Concurrent Spotify token refresh clobbers the rotated refresh token, permanently breaking the connection #1143

Closed
opened 2026-10-21 05:27:45 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @Romuromylus on GitHub (Jun 5, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2318

Originally assigned to: @Romuromylus on GitHub.

Summary

Severity: Medium — Concurrency / credential corruption. Spotify's Authorization Code + PKCE flow rotates the refresh token on every refresh and invalidates the previous one. Token refresh in resolve_credentials has no serializing lock, so when two Spotify commands run concurrently in the ~60s pre-expiry window they each refresh with the same stale refresh token; Spotify hands each a different new token and invalidates the prior. The racing save_spotify_tokens writes are last-writer-wins, so the persisted token can be one Spotify already invalidated — permanently breaking the connection until the user manually reconnects.

Expected behavior

Concurrent Spotify commands should serialize token refresh: the second caller waits and re-reads the freshly-saved token rather than issuing a second refresh with the now-stale refresh token.

Actual behavior

src-tauri/src/commands/storage/integrations/spotify.rs, resolve_credentials (2547-2633), proactive refresh at 2594-2596:

if access_token.is_empty()
    || (expires_at > 0 && now_millis() > expires_at.saturating_sub(60_000))
{
    let token = refresh_agent_token(state, &agent_id).await?;   // no lock: concurrent callers all refresh with the same old refresh_token

refresh_agent_token (2646-2669) posts grant_type=refresh_token with no client secret (public-client PKCE), and save_spotify_tokens (2671-2733) unconditionally overwrites spotifyRefreshTokenEncrypted (2713-2717). The only static lock in the file is SPOTIFY_TRACK_INDEX_CACHE (line 60) — there is no lock around token refresh. Each Spotify op is a separate #[tauri::command] async fn (commands/integrations.rs: spotify_player, spotify_devices, spotify_access_token, spotify_player_play/pause/next/volume), and Tauri runs them concurrently. SpotifyMiniPlayer.tsx polls playerQuery and devicesQuery every 5s (independent useQuery, no dedup), so two resolve_credentials routinely overlap.

The storage write-lock makes each individual patch atomic but does NOT serialize the two network refreshes or prevent stale-token reuse.

Steps to reproduce

  1. Connect the Spotify DJ agent.
  2. Let the access token approach its ~1h expiry.
  3. Within the ~60s pre-expiry window, have the UI issue 2+ Spotify commands (normal player+devices polling, or rapid play/pause/next).
  4. Two refreshes fire with the same refresh token; the persisted token may be the invalidated one → all later refreshes 400 → connection broken until manual reconnect.

Impact area

  • Tauri/Rust storage, assets, LLM, integrations, security, imports, or HTTP runtime

Environment

  • Branch or commit: refactor @ b0e5561d
  • Run mode: Tauri desktop (also server mode)
  • OS + version: not relevant (static source audit)
  • Node + pnpm versions: not relevant
  • Rust version, if relevant: not relevant
  • Remote Runtime URL configured? not relevant (applies to both)
  • Provider, model, or integration, if relevant: Spotify DJ integration

Logs, screenshots, or video

Static source audit; cited to file:line above.

Regression notes

Found via static audit of the refactor branch; not verified against main.

Additional context

Probabilistic trigger (needs the token near expiry while two commands overlap) and recovery is a one-click reconnect, hence medium not high — but it silently corrupts a stored credential. Suggested fix: serialize refresh per agent via a per-agent tokio::sync::Mutex (e.g. static OnceLock<Mutex<HashMap<agent_id, Arc<Mutex<()>>>>>); after acquiring, re-read settings and skip the network refresh if another task already refreshed (expires_at now in the future).

Template check

Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @Romuromylus on GitHub (Jun 5, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/2318 Originally assigned to: @Romuromylus on GitHub. ## Summary **Severity: Medium — Concurrency / credential corruption.** Spotify's Authorization Code + PKCE flow rotates the refresh token on every refresh and invalidates the previous one. Token refresh in `resolve_credentials` has no serializing lock, so when two Spotify commands run concurrently in the ~60s pre-expiry window they each refresh with the same stale refresh token; Spotify hands each a different new token and invalidates the prior. The racing `save_spotify_tokens` writes are last-writer-wins, so the persisted token can be one Spotify already invalidated — permanently breaking the connection until the user manually reconnects. ## Expected behavior Concurrent Spotify commands should serialize token refresh: the second caller waits and re-reads the freshly-saved token rather than issuing a second refresh with the now-stale refresh token. ## Actual behavior `src-tauri/src/commands/storage/integrations/spotify.rs`, `resolve_credentials` (2547-2633), proactive refresh at 2594-2596: ```rust if access_token.is_empty() || (expires_at > 0 && now_millis() > expires_at.saturating_sub(60_000)) { let token = refresh_agent_token(state, &agent_id).await?; // no lock: concurrent callers all refresh with the same old refresh_token ``` `refresh_agent_token` (2646-2669) posts `grant_type=refresh_token` with no client secret (public-client PKCE), and `save_spotify_tokens` (2671-2733) unconditionally overwrites `spotifyRefreshTokenEncrypted` (2713-2717). The only static lock in the file is `SPOTIFY_TRACK_INDEX_CACHE` (line 60) — there is no lock around token refresh. Each Spotify op is a separate `#[tauri::command] async fn` (`commands/integrations.rs`: `spotify_player`, `spotify_devices`, `spotify_access_token`, `spotify_player_play/pause/next/volume`), and Tauri runs them concurrently. `SpotifyMiniPlayer.tsx` polls `playerQuery` and `devicesQuery` every 5s (independent `useQuery`, no dedup), so two `resolve_credentials` routinely overlap. The storage write-lock makes each individual `patch` atomic but does NOT serialize the two network refreshes or prevent stale-token reuse. ## Steps to reproduce 1. Connect the Spotify DJ agent. 2. Let the access token approach its ~1h expiry. 3. Within the ~60s pre-expiry window, have the UI issue 2+ Spotify commands (normal player+devices polling, or rapid play/pause/next). 4. Two refreshes fire with the same refresh token; the persisted token may be the invalidated one → all later refreshes 400 → connection broken until manual reconnect. ## Impact area - [x] Tauri/Rust storage, assets, LLM, integrations, security, imports, or HTTP runtime ## Environment - Branch or commit: refactor @ b0e5561d - Run mode: Tauri desktop (also server mode) - OS + version: not relevant (static source audit) - Node + pnpm versions: not relevant - Rust version, if relevant: not relevant - Remote Runtime URL configured? not relevant (applies to both) - Provider, model, or integration, if relevant: Spotify DJ integration ## Logs, screenshots, or video Static source audit; cited to file:line above. ## Regression notes Found via static audit of the refactor branch; not verified against main. ## Additional context Probabilistic trigger (needs the token near expiry while two commands overlap) and recovery is a one-click reconnect, hence medium not high — but it silently corrupts a stored credential. Suggested fix: serialize refresh per agent via a per-agent `tokio::sync::Mutex` (e.g. `static OnceLock<Mutex<HashMap<agent_id, Arc<Mutex<()>>>>>`); after acquiring, re-read settings and skip the network refresh if another task already refreshed (`expires_at` now in the future). ## Template check Please uncheck the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
bsakaguchi 2026-10-21 05:27:45 +07:00
Author
Owner

@Romuromylus commented on GitHub (Jun 6, 2026):

Fixed by #2400, merged into refactor.

<!-- gh-comment-id:4637947988 --> @Romuromylus commented on GitHub (Jun 6, 2026): Fixed by #2400, merged into `refactor`.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#1143
No description provided.