diff --git a/files/k0s/kiosk/kiosk-gate.js b/files/k0s/kiosk/kiosk-gate.js index a75781ef..d6122fb7 100644 --- a/files/k0s/kiosk/kiosk-gate.js +++ b/files/k0s/kiosk/kiosk-gate.js @@ -3,6 +3,124 @@ const healthURL = 'http://127.0.0.1:8585/health' const gateID = 'kubestellar-kiosk-gate' + const INITIAL_BACKOFF_MS = 500 + const BACKOFF_FACTOR = 2 + const MAX_RETRIES = 4 + const STAGGER_INTERVAL_MS = 75 + const MAX_RETRY_DELAY_MS = 30_000 + + // Page-lifetime cursor: any concurrent /api burst is spaced, not only the + // first-boot hydration one, because the console rate limiter is also + // page-lifetime and periodic refreshes fan out the same way. + let lastDispatchTime = -STAGGER_INTERVAL_MS + + const sleep = (ms, signal) => new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(new DOMException('Aborted', 'AbortError')) + return + } + const timer = setTimeout(resolve, ms) + signal?.addEventListener('abort', () => { + clearTimeout(timer) + reject(new DOMException('Aborted', 'AbortError')) + }, { once: true }) + }) + + const isApiRequest = (input) => { + try { + let urlStr + if (typeof input === 'string') { + urlStr = input + } else if (input instanceof URL) { + urlStr = input.href + } else if (input && typeof input === 'object' && 'url' in input) { + urlStr = input.url + } else { + urlStr = String(input) + } + + const origin = typeof window !== 'undefined' && window.location ? window.location.origin : 'http://localhost' + const parsed = new URL(urlStr, origin) + return parsed.origin === origin && (parsed.pathname === '/api' || parsed.pathname.startsWith('/api/')) + } catch { + return false + } + } + + const staggerRequest = async (signal) => { + const now = Date.now() + const scheduledTime = Math.max(now, lastDispatchTime + STAGGER_INTERVAL_MS) + lastDispatchTime = scheduledTime + const waitMs = scheduledTime - now + if (waitMs > 0) { + await sleep(waitMs, signal) + } + } + + const clampDelay = (ms) => Math.min(Math.max(ms, 0), MAX_RETRY_DELAY_MS) + + const parseRetryAfter = (response) => { + try { + const header = response.headers?.get?.('Retry-After') + if (!header) return null + const seconds = Number(header) + if (!Number.isNaN(seconds) && seconds >= 0) { + return clampDelay(seconds * 1000) + } + const dateMs = Date.parse(header) + if (!Number.isNaN(dateMs)) { + return clampDelay(dateMs - Date.now()) + } + } catch { + // fallback + } + return null + } + + const executeFetch = (originalFetch, input, init) => { + if (typeof Request !== 'undefined' && input instanceof Request) { + try { + return originalFetch(input.clone(), init) + } catch { + return originalFetch(input, init) + } + } + return originalFetch(input, init) + } + + if (typeof window !== 'undefined' && typeof window.fetch === 'function') { + const originalFetch = window.fetch.bind(window) + + window.fetch = async function (input, init) { + if (!isApiRequest(input)) { + return originalFetch(input, init) + } + + const signal = init?.signal || (typeof Request !== 'undefined' && input instanceof Request ? input.signal : undefined) + if (signal?.aborted) { + throw new DOMException('The user aborted a request.', 'AbortError') + } + + await staggerRequest(signal) + + let attempt = 0 + while (true) { + const response = await executeFetch(originalFetch, input, init) + if (response.status !== 429 || attempt >= MAX_RETRIES) { + return response + } + + attempt++ + const retryAfterMs = parseRetryAfter(response) + const backoffMs = retryAfterMs !== null + ? retryAfterMs + : clampDelay(INITIAL_BACKOFF_MS * Math.pow(BACKOFF_FACTOR, attempt - 1)) + + await sleep(backoffMs, signal) + } + } + } + const hasSession = () => { try { return window.localStorage.getItem(sessionKey) === 'true' @@ -44,10 +162,40 @@ } } - document.addEventListener('keydown', (event) => { - const gate = document.getElementById(gateID) - if (gate && !gate.contains(event.target)) event.preventDefault() - }, true) - window.setInterval(() => void updateGate(), 2_000) - void updateGate() + if (typeof document !== 'undefined') { + document.addEventListener('keydown', (event) => { + const gate = document.getElementById(gateID) + if (gate && !gate.contains(event.target)) event.preventDefault() + }, true) + } + + const startGateLoop = () => { + window.setInterval(() => void updateGate(), 2_000) + void updateGate() + } + + if (typeof window !== 'undefined') { + // The interceptor above is installed at parse time, but the gate markup + // needs document.body, which does not exist yet when this script runs + // synchronously from . + if (typeof document !== 'undefined' && document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', startGateLoop, { once: true }) + } else { + startGateLoop() + } + } + + if (typeof module !== 'undefined' && module.exports) { + module.exports = { + isApiRequest, + parseRetryAfter, + staggerRequest, + clampDelay, + INITIAL_BACKOFF_MS, + BACKOFF_FACTOR, + MAX_RETRIES, + STAGGER_INTERVAL_MS, + MAX_RETRY_DELAY_MS, + } + } })() diff --git a/files/k0s/kiosk/nginx.conf b/files/k0s/kiosk/nginx.conf index e34bf24b..afe0f50a 100644 --- a/files/k0s/kiosk/nginx.conf +++ b/files/k0s/kiosk/nginx.conf @@ -41,8 +41,11 @@ http { proxy_set_header Accept-Encoding ""; proxy_set_header Connection ""; sub_filter_once on; - sub_filter '' ''; - sub_filter '' ''; + # Injected synchronously at the end of so window.fetch is patched + # before the console bundle executes. Classic non-deferred scripts run + # before any deferred/module script and before end-of-body scripts, so + # the first-boot hydration burst is intercepted. + sub_filter '' ''; } } } diff --git a/tests/unit/test_kubestellar_kiosk.py b/tests/unit/test_kubestellar_kiosk.py index ec608c72..c0f239b6 100644 --- a/tests/unit/test_kubestellar_kiosk.py +++ b/tests/unit/test_kubestellar_kiosk.py @@ -1,6 +1,11 @@ """Contracts for the KubeStellar kiosk proxy and authenticated agent gate.""" +import json from pathlib import Path +import shutil +import subprocess + +import pytest ROOT = Path(__file__).resolve().parents[2] KIOSK = ROOT / "files" / "k0s" / "kiosk" @@ -54,12 +59,11 @@ def test_proxy_injects_only_csp_safe_same_origin_assets() -> None: assert "sub_filter_types" not in nginx assert ( 'sub_filter \'\' ' - '\'\';' - ) in nginx - assert ( - 'sub_filter \'\' ' - '\'\';' + '\'' + '\';' ) in nginx + assert "