Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,8 @@ docker-compose*.yml

client_secret*.json
client_secrets*.json

# Server-only persistent data and recovery files.
/backups/
/storage/
/operations/
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/
5 changes: 4 additions & 1 deletion main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())


Expand Down Expand Up @@ -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:
Expand Down
47 changes: 37 additions & 10 deletions static/youtube-upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down Expand Up @@ -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(() => {});
});
2 changes: 1 addition & 1 deletion templates/video.html
Original file line number Diff line number Diff line change
Expand Up @@ -4293,7 +4293,7 @@ <h3 class="text-xs font-semibold text-slate-200 flex items-center gap-2">
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,
Expand Down
21 changes: 21 additions & 0 deletions tests/browser/test_video_studio.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
24 changes: 24 additions & 0 deletions tests/test_youtube_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
3 changes: 3 additions & 0 deletions web_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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',
)
Expand Down
4 changes: 2 additions & 2 deletions youtube_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down Expand Up @@ -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():
Expand Down
Loading