From 69fd70bf4d450e6b33e40dc1858d37270471fc67 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 21:52:23 +0200 Subject: [PATCH 1/2] fix: yotube upload --- .dockerignore | 5 +++++ .gitignore | 5 +++++ main.py | 5 ++++- static/youtube-upload.js | 47 +++++++++++++++++++++++++++++++--------- templates/video.html | 2 +- web_auth.py | 3 +++ youtube_upload.py | 4 ++-- 7 files changed, 57 insertions(+), 14 deletions(-) diff --git a/.dockerignore b/.dockerignore index 273e032..63456cd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -60,3 +60,8 @@ docker-compose*.yml client_secret*.json client_secrets*.json + +# Server-only persistent data and recovery files. +/backups/ +/storage/ +/operations/ diff --git a/.gitignore b/.gitignore index 79d59f1..0614abd 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,8 @@ instance/ # Google OAuth client downloads must never be committed. client_secret*.json client_secrets*.json + +# Server-only persistent data and recovery files. +/backups/ +/storage/ +/operations/ diff --git a/main.py b/main.py index bd1cdf8..41afead 100644 --- a/main.py +++ b/main.py @@ -159,6 +159,9 @@ def main(): @app.route('/studio') def studio(): """Serve the dedicated Video Studio page (music downloader).""" + # Establish identity before the page starts parallel API requests. + youtube_uploads.owner() + youtube_uploads.csrf() return render_template("video.html", title_fonts=_available_fonts()) @@ -1675,7 +1678,7 @@ def make_video() -> tuple[object, int]: youtube_body = None if data.get('youtube') is not None: if not youtube_uploads.valid_csrf(): - return jsonify(error='Invalid YouTube request token. Reload the page.'), 403 + return jsonify(code='youtube_csrf_invalid', error='Invalid YouTube request token. Reload the page.'), 403 try: youtube_body = youtube_uploads.check_ready(data['youtube']) except ValueError as error: diff --git a/static/youtube-upload.js b/static/youtube-upload.js index 6534c69..939448b 100644 --- a/static/youtube-upload.js +++ b/static/youtube-upload.js @@ -18,23 +18,50 @@ function youtubeSettings() { return settings; } -async function youtubeRequest(url, options = {}) { - const response = await fetch(url, {...options, headers: {...options.headers, 'X-YouTube-CSRF': youtubeCsrf}, cache: 'no-store'}); - const result = await response.json(); - if (!response.ok) throw new Error(result.error || 'YouTube request failed.'); - return result; -} +let youtubeConnectionRequest = null; async function loadYouTubeConnection() { - try { - const result = await youtubeRequest('/api/youtube/status'); + // Share one request so simultaneous actions cannot race session setup. + if (youtubeConnectionRequest) return youtubeConnectionRequest; + youtubeConnectionRequest = (async () => { + const response = await fetch('/api/youtube/status', {cache: 'no-store'}); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || 'Could not check YouTube connection.'); youtubeCsrf = result.csrf_token; youtubeConnected = result.connected; ytElement('youtubeConnection').textContent = result.connected ? 'YouTube account connected.' : 'YouTube account not connected.'; ytElement('youtubeRedirect').textContent = result.redirect_uri; - } catch (error) { + return result; + })(); + try { return await youtubeConnectionRequest; } + catch (error) { ytElement('youtubeConnection').textContent = error.message; + throw error; + } finally { youtubeConnectionRequest = null; } +} + +async function youtubeFetch(url, options = {}) { + const mutating = (options.method || 'GET').toUpperCase() === 'POST'; + // Refresh before every mutation, including actions from older open tabs. + if (mutating) await loadYouTubeConnection(); + const send = () => fetch(url, {...options, headers: {...options.headers, 'X-YouTube-CSRF': youtubeCsrf}, cache: 'no-store'}); + let response = await send(); + if (mutating && response.status === 403) { + const rejection = await response.clone().json().catch(() => ({})); + // This response is issued before any upload/render/OAuth side effect. + if (rejection.code === 'youtube_csrf_invalid') { + await loadYouTubeConnection(); + response = await send(); + } } + return response; +} + +async function youtubeRequest(url, options = {}) { + const response = await youtubeFetch(url, options); + const result = await response.json(); + if (!response.ok) throw new Error(result.error || 'YouTube request failed.'); + return result; } async function connectYouTube() { @@ -125,5 +152,5 @@ document.addEventListener('DOMContentLoaded', () => { if (outcome !== 'connected') showToast(outcome === 'denied' ? 'Google authorization cancelled.' : 'Google authorization failed. Check the redirect URI and try connecting again.', 'error'); history.replaceState(null, '', location.pathname); } - loadYouTubeConnection(); + loadYouTubeConnection().catch(() => {}); }); diff --git a/templates/video.html b/templates/video.html index a478cd8..76ff783 100644 --- a/templates/video.html +++ b/templates/video.html @@ -4293,7 +4293,7 @@

formData.append('payload', JSON.stringify(payload)); stopProgress = startRenderProgress(renderId); - const response = await fetch('/api/render_video', { + const response = await (youtube ? youtubeFetch : fetch)('/api/render_video', { method: 'POST', headers: youtube ? {'X-YouTube-CSRF': youtubeCsrf} : {}, body: formData, diff --git a/web_auth.py b/web_auth.py index c5d6b97..b9a926e 100644 --- a/web_auth.py +++ b/web_auth.py @@ -69,6 +69,9 @@ def init_web_auth(app, env_values=None): app.secret_key = _session_secret(app, settings) app.config.update( PERMANENT_SESSION_LIFETIME=timedelta(days=365), + # Read-only requests must not overwrite a newer session cookie from + # a parallel OAuth/status request. + SESSION_REFRESH_EACH_REQUEST=False, SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Lax', ) diff --git a/youtube_upload.py b/youtube_upload.py index cd21f0f..6293c69 100644 --- a/youtube_upload.py +++ b/youtube_upload.py @@ -121,7 +121,7 @@ def csrf(self): def valid_csrf(self): token = request.headers.get('X-YouTube-CSRF', '') - return bool(token) and hmac.compare_digest(token, session.get('youtube_csrf', '')) + return bool(token) and hmac.compare_digest(token.encode(), session.get('youtube_csrf', '').encode()) def render_token(self, path): return self.signer.dumps({'owner': self.owner(), 'path': path}) @@ -221,7 +221,7 @@ def _routes(self): def youtube_csrf(): if request.path.startswith('/api/youtube/') and request.method == 'POST': if not self.valid_csrf(): - return jsonify(error='Invalid YouTube request token. Reload the page.'), 403 + return jsonify(code='youtube_csrf_invalid', error='Invalid YouTube request token. Reload the page.'), 403 @app.get('/api/youtube/status') def youtube_status(): From 77b32d49bf098834df0a6668c3144a2a8e280dc2 Mon Sep 17 00:00:00 2001 From: deltaaa00 Date: Tue, 17 Nov 2026 21:52:33 +0200 Subject: [PATCH 2/2] fix: tests --- tests/browser/test_video_studio.py | 21 +++++++++++++++++++++ tests/test_youtube_upload.py | 24 ++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/tests/browser/test_video_studio.py b/tests/browser/test_video_studio.py index 3800951..a42eb41 100644 --- a/tests/browser/test_video_studio.py +++ b/tests/browser/test_video_studio.py @@ -786,3 +786,24 @@ def render(route): assert page.locator('#youtubeDescription').input_value() == 'Опис відео\n🌍' assert not page.locator('#youtubeAuto').is_checked() assert page.locator('#youtubeSecret').input_value() == '' + + +def test_youtube_refreshes_stale_request_token_and_retries_once(studio): + page, _ = studio + status_count = [] + requests = [] + def status(route): + status_count.append(1) + route.fulfill(json={'connected': True, 'csrf_token': f'token-{len(status_count)}', + 'redirect_uri': 'https://automap.test/api/youtube/callback'}) + def disconnect(route): + requests.append(route.request.headers['x-youtube-csrf']) + if len(requests) == 1: + route.fulfill(status=403, json={'code': 'youtube_csrf_invalid', 'error': 'Stale token'}) + else: + route.fulfill(json={'connected': False}) + page.route('**/api/youtube/status', status) + page.route('**/api/youtube/disconnect', disconnect) + page.evaluate("youtubeCsrf = 'old-tab-token'; youtubeRequest('/api/youtube/disconnect', {method:'POST'})") + assert requests == ['token-1', 'token-2'] + assert len(status_count) == 2 diff --git a/tests/test_youtube_upload.py b/tests/test_youtube_upload.py index 95fa7ed..b2382ec 100644 --- a/tests/test_youtube_upload.py +++ b/tests/test_youtube_upload.py @@ -230,3 +230,27 @@ def test_failed_upload_never_exposes_secrets_and_releases_slot(web, tmp_path, mo assert web.youtube_uploads.slots.acquire(blocking=False) web.youtube_uploads.slots.release() web.youtube_uploads.slots.release() + + +def test_studio_initializes_youtube_session_before_parallel_requests(web, tmp_path): + web.app.config['YOUTUBE_DATA_DIR'] = tmp_path / 'youtube' + client = web.app.test_client() + assert client.get('/studio').status_code == 200 + with client.session_transaction() as cookie: + owner = cookie['youtube_owner'] + token = cookie['youtube_csrf'] + # A late response from a read-only API must not replace a newer cookie. + response = client.get('/api/youtube/status') + assert response.json['csrf_token'] == token + assert 'Set-Cookie' not in response.headers + with client.session_transaction() as cookie: + assert cookie['youtube_owner'] == owner + response = client.post('/api/youtube/disconnect', headers={'X-YouTube-CSRF': token}) + assert response.status_code == 200 + + +def test_csrf_rejection_identifies_safe_to_retry_requests(web, tmp_path): + client, headers = setup_client(web, tmp_path) + response = client.post('/api/youtube/disconnect', headers={'X-YouTube-CSRF': 'stale'}) + assert response.status_code == 403 and response.json['code'] == 'youtube_csrf_invalid' + assert client.post('/api/youtube/disconnect', headers=headers).status_code == 200