diff --git a/CMakeLists.txt b/CMakeLists.txt index f19a519..e21039f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,18 +16,17 @@ target_include_directories(EchoionWeb PUBLIC # EchoionCore is configured before this module and creates the header-only # Boost:: targets from the single system Boost. Fall back to discovering them -# only if this module is ever built without Core. -if(NOT TARGET Boost::beast) - find_package(Boost 1.87 CONFIG QUIET) - foreach(_hdr asio beast system) - if(NOT TARGET Boost::${_hdr}) - add_library(_web_boost_${_hdr}_hdr INTERFACE) - add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr) - target_include_directories(_web_boost_${_hdr}_hdr INTERFACE - "${Boost_INCLUDE_DIRS}") - endif() - endforeach() -endif() +# only if this module is ever built without Core. Check each target because +# aliases created by a sibling directory are not necessarily visible here. +find_package(Boost 1.87 CONFIG QUIET COMPONENTS system url) +foreach(_hdr asio beast system) + if(NOT TARGET Boost::${_hdr}) + add_library(_web_boost_${_hdr}_hdr INTERFACE) + add_library(Boost::${_hdr} ALIAS _web_boost_${_hdr}_hdr) + target_include_directories(_web_boost_${_hdr}_hdr INTERFACE + "${Boost_INCLUDE_DIRS}") + endif() +endforeach() find_package(Threads REQUIRED) @@ -42,6 +41,7 @@ target_link_libraries(EchoionWeb Boost::beast Boost::asio Boost::system + Boost::url ) if(MSVC) @@ -55,6 +55,16 @@ endif() # That build output is what ships next to the runtime binary (default webRoot # "./web", relative to the working directory) and is installed. Opt out with # -DECHOION_BUILD_WEB=OFF to skip the npm build (e.g. for a C++-only CI job). +if(BUILD_TESTS) + add_executable(echoion_web_security_tests + tests/HttpSecurityTests.cpp) + target_link_libraries(echoion_web_security_tests PRIVATE + EchoionWeb + Threads::Threads) + add_test(NAME echoion_web_security_tests + COMMAND echoion_web_security_tests) +endif() + option(ECHOION_BUILD_WEB "Build the React dashboard frontend with npm/vite" ON) set(_web_frontend "${CMAKE_CURRENT_SOURCE_DIR}/frontend") diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 21c8beb..b234a9a 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -894,9 +894,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -911,9 +908,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -928,9 +922,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -945,9 +936,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -962,9 +950,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -979,9 +964,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -996,9 +978,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1013,9 +992,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1030,9 +1006,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1047,9 +1020,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1064,9 +1034,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1081,9 +1048,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1098,9 +1062,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/frontend/scripts/i18n-check.mjs b/frontend/scripts/i18n-check.mjs index d77942c..c870d08 100644 --- a/frontend/scripts/i18n-check.mjs +++ b/frontend/scripts/i18n-check.mjs @@ -46,6 +46,8 @@ const KNOWN_DYNAMIC = new Set([ 'Playback history and server insights', 'Server & Admin', 'Manage subscribers and broadcast', + 'Updates', + 'Runtime, Core, and plugin release control', 'RPC / API', 'Connect to Echoion programmatically', // Sidebar NAV labels rendered via t(item.label) — same strings as HEADS diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0d67666..3872007 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -16,6 +16,7 @@ import { SearchView } from './views/SearchView'; import { LibraryView } from './views/LibraryView'; import { StatsView } from './views/StatsView'; import { ServerView } from './views/ServerView'; +import { UpdatesView } from './views/UpdatesView'; import { RpcView } from './views/RpcView'; const HEADS: Record = { @@ -25,6 +26,7 @@ const HEADS: Record = { library: ['Library', 'Your favorites and saved playlists'], stats: ['History & Stats', 'Playback history and server insights'], server: ['Server & Admin', 'Manage subscribers and broadcast'], + updates: ['Updates', 'Runtime, Core, and plugin release control'], rpc: ['RPC / API', 'Connect to Echoion programmatically'], }; @@ -92,6 +94,7 @@ export function App() { {s.view === 'library' && } {s.view === 'stats' && } {s.view === 'server' && } + {s.view === 'updates' && } {s.view === 'rpc' && } diff --git a/frontend/src/components/Modal.test.tsx b/frontend/src/components/Modal.test.tsx new file mode 100644 index 0000000..7c54542 --- /dev/null +++ b/frontend/src/components/Modal.test.tsx @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; +import { Modal } from './Modal'; + +describe('Modal accessibility', () => { + it('labels the dialog and exposes a named close control', () => { + const html = renderToStaticMarkup( + {}}> +

Review the candidate.

+
+ ); + expect(html).toContain('role="dialog"'); + expect(html).toContain('aria-modal="true"'); + expect(html).toContain('aria-labelledby='); + expect(html).toContain('aria-label="Close"'); + }); +}); diff --git a/frontend/src/components/Modal.tsx b/frontend/src/components/Modal.tsx index 61f4cda..60df469 100644 --- a/frontend/src/components/Modal.tsx +++ b/frontend/src/components/Modal.tsx @@ -1,5 +1,6 @@ -import type { ReactNode } from 'react'; +import { useEffect, useId, useRef, type KeyboardEvent, type ReactNode } from 'react'; import { CloseIcon } from './icons'; +import { t } from '../i18n'; export function Modal(props: { title: string; @@ -8,15 +9,60 @@ export function Modal(props: { footer?: ReactNode; wide?: boolean; }) { + const titleId = useId(); + const modalRef = useRef(null); + + useEffect(() => { + const previous = document.activeElement as HTMLElement | null; + const focusable = modalRef.current?.querySelector( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ); + focusable?.focus(); + return () => previous?.focus(); + }, []); + + function onKeyDown(event: KeyboardEvent) { + if (event.key === 'Escape') { + event.preventDefault(); + props.onClose(); + return; + } + if (event.key !== 'Tab' || !modalRef.current) return; + const focusable = Array.from( + modalRef.current.querySelectorAll( + 'button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])' + ) + ); + if (!focusable.length) return; + const first = focusable[0]; + const last = focusable[focusable.length - 1]; + if (event.shiftKey && document.activeElement === first) { + event.preventDefault(); + last.focus(); + } else if (!event.shiftKey && document.activeElement === last) { + event.preventDefault(); + first.focus(); + } + } + return (
e.stopPropagation()} >
-

{props.title}

-
diff --git a/frontend/src/components/Sidebar.tsx b/frontend/src/components/Sidebar.tsx index cb45f5a..1a109d6 100644 --- a/frontend/src/components/Sidebar.tsx +++ b/frontend/src/components/Sidebar.tsx @@ -20,6 +20,7 @@ import { QueueIcon, SearchIcon, StatsIcon, + UpdateIcon, WatchIcon, } from './icons'; import { t, useLanguage } from '../i18n'; @@ -31,6 +32,7 @@ const NAV: Array<{ view: ViewName; icon: ReactNode; label: string }> = [ { view: 'library', icon: , label: 'Library' }, { view: 'stats', icon: , label: 'History & Stats' }, { view: 'server', icon: , label: 'Server & Admin' }, + { view: 'updates', icon: , label: 'Updates' }, { view: 'rpc', icon: , label: 'RPC / API' }, ]; @@ -66,7 +68,9 @@ export function Sidebar() {
+ + ); +} + +function PolicyEditor(props: { + component: UpdateComponent; + policy: ComponentUpdatePolicy; + sourceIds: string[]; + onChange: (policy: ComponentUpdatePolicy) => void; +}) { + const label = componentLabel(props.component); + return ( +
+
+ {label} + +
+ + + +
+ ); +} + +function SourceEditor(props: { + id: string; + source: UpdateSourceConfig; + canDelete: boolean; + onChange: (source: UpdateSourceConfig) => void; + onDelete: () => void; +}) { + function updateKey(index: number, field: 'id' | 'ed25519', value: string) { + const keys = props.source.publicKeys.map((key, keyIndex) => + keyIndex === index ? { ...key, [field]: value } : key + ); + props.onChange({ ...props.source, publicKeys: keys }); + } + + return ( +
+ + {props.id} + {props.id === 'official' && ( + {t('Build default')} + )} + +
+ + + +
+ +
+
+ {t('Ed25519 trust keys')} +

+ {t('Only public verification keys belong here.')} +

+
+ +
+
+ {props.source.publicKeys.length ? ( + props.source.publicKeys.map((key, index) => ( +
+ + + +
+ )) + ) : ( +

+ {t('No custom keys; the build-injected keyring is used when available.')} +

+ )} +
+ {props.canDelete && ( +
+ +
+ )} +
+ ); +} + +function PluginRow(props: { + plugin: PluginUpdateStatus; + busy: boolean; + onApply: () => void; + onRollback: () => void; +}) { + const candidate = props.plugin.candidate; + return ( +
+
+ {props.plugin.name || props.plugin.id} + {props.plugin.id} +
+ + {props.plugin.managed ? t('Managed') : t('Unmanaged')} + +
+ {props.plugin.currentVersion || '—'} + {candidate && <> → {candidate.version}} +
+
+ {props.plugin.managed && candidate && ( + + )} + {props.plugin.managed && props.plugin.rollbackVersion && ( + + )} +
+
+ ); +} + +export function UpdatesView() { + const app = useStore(appStore); + const isAdmin = !!app.identity?.isAdmin; + const [status, setStatus] = useState(null); + const [config, setConfig] = useState(null); + const [draft, setDraft] = useState(null); + const [dirty, setDirty] = useState(false); + const [loading, setLoading] = useState(false); + const [busy, setBusy] = useState(''); + + const loadStatus = useCallback(async () => { + const payload = await safeCall('GetUpdateStatus'); + if (payload !== null) setStatus(normalizeUpdateStatus(payload)); + }, []); + + const loadConfig = useCallback(async () => { + const payload = await safeCall('GetUpdateConfig'); + if (payload === null) return; + const next = normalizeUpdateConfig(payload); + setConfig(next); + setDraft(cloneUpdateConfig(next)); + setDirty(false); + }, []); + + const loadAll = useCallback(async () => { + setLoading(true); + await Promise.all([loadStatus(), loadConfig()]); + setLoading(false); + }, [loadConfig, loadStatus]); + + useEffect(() => { + if (!isAdmin) return; + void loadAll(); + return rpc.on('updates.changed', (payload) => { + if (looksLikeStatusPayload(payload)) { + setStatus(normalizeUpdateStatus(payload)); + } else { + void loadStatus(); + } + }); + }, [isAdmin, loadAll, loadStatus]); + + const sourceIds = useMemo( + () => Object.keys(draft?.sources || {}), + [draft?.sources] + ); + + function changeDraft(next: UpdateConfig) { + setDraft(next); + setDirty(true); + } + + function changePolicy( + component: UpdateComponent, + policy: ComponentUpdatePolicy + ) { + if (!draft) return; + if (component === 'plugins') { + changeDraft({ + ...draft, + plugins: { ...draft.plugins, ...policy }, + }); + return; + } + changeDraft({ ...draft, [component]: policy }); + } + + async function checkForUpdates() { + setBusy('check'); + const payload = await safeCall('CheckForUpdates'); + if (payload !== null) { + await loadStatus(); + toast(t('Update check completed')); + } + setBusy(''); + } + + async function confirmCandidate( + component: UpdateComponent, + candidate: UpdateCandidate, + pluginId?: string + ): Promise { + let confirmationToken: string | undefined; + + if (candidate.signed === false) { + const phrase = `UNSIGNED ${candidate.version}`; + const entered = await promptDialog({ + title: t('Confirm unsigned update'), + message: tf( + 'This artifact has no trusted signature. Type {0} to authorize this exact candidate.', + phrase + ), + placeholder: phrase, + confirmLabel: t('Authorize unsigned candidate'), + }); + if (entered !== phrase) return null; + const approval = await safeCall<{ confirmationToken?: string }>( + 'ConfirmUnsignedUpdate', + { + component, + pluginId, + candidateId: candidate.id || candidate.version, + version: candidate.version, + confirmation: phrase, + } + ); + if (approval === null) return null; + confirmationToken = approval.confirmationToken; + } + + if (candidate.downgrade) { + const entered = await promptDialog({ + title: t('Confirm downgrade'), + message: t('A downgrade may make saved state incompatible. Type DOWNGRADE to continue.'), + placeholder: 'DOWNGRADE', + confirmLabel: t('Continue with downgrade'), + }); + if (entered !== 'DOWNGRADE') return null; + } + + if (component === 'runtime' || candidate.requiresRestart) { + const confirmed = await confirmDialog({ + title: t('Restart Echoion'), + message: t('Applying this update restarts Echoion after it becomes idle. Continue?'), + confirmLabel: t('Apply and restart'), + }); + if (!confirmed) return null; + } + + return confirmationToken; + } + + async function applyUpdate( + component: UpdateComponent, + candidate?: UpdateCandidate, + pluginId?: string + ) { + if (!candidate || candidate.compatible === false) return; + const confirmationToken = await confirmCandidate( + component, + candidate, + pluginId + ); + if (confirmationToken === null) return; + const key = `apply:${component}:${pluginId || ''}`; + setBusy(key); + const payload = await safeCall('ApplyUpdate', { + component, + pluginId, + candidateId: candidate.id || candidate.version, + version: candidate.version, + confirmationToken, + }); + if (payload !== null) { + await loadStatus(); + toast(tf('{0} update queued', pluginId || componentLabel(component))); + } + setBusy(''); + } + + async function rollbackUpdate( + component: UpdateComponent, + version?: string, + pluginId?: string + ) { + if (!version) return; + const confirmed = await confirmDialog({ + title: t('Confirm rollback'), + message: tf('Roll back {0} to {1}?', pluginId || componentLabel(component), version), + confirmLabel: t('Rollback'), + danger: true, + }); + if (!confirmed) return; + const key = `rollback:${component}:${pluginId || ''}`; + setBusy(key); + const payload = await safeCall('RollbackUpdate', { + component, + pluginId, + version, + }); + if (payload !== null) { + await loadStatus(); + toast(t('Rollback queued')); + } + setBusy(''); + } + + async function saveConfig() { + if (!draft || !config) return; + const newlyUnsigned = Object.entries(draft.sources) + .filter( + ([id, source]) => + source.allowUnsigned && !config.sources[id]?.allowUnsigned + ) + .map(([id]) => id); + if (newlyUnsigned.length) { + const entered = await promptDialog({ + title: t('Enable unsigned update policy'), + message: tf( + 'Unsigned staging will be permitted for: {0}. Type ENABLE UNSIGNED to save this policy.', + newlyUnsigned.join(', ') + ), + placeholder: 'ENABLE UNSIGNED', + confirmLabel: t('Save unsafe policy'), + }); + if (entered !== 'ENABLE UNSIGNED') return; + } + setBusy('save'); + const payload = await safeCall('SetUpdateConfig', { + config: configForSave(draft), + }); + if (payload !== null) { + await loadConfig(); + toast(t('Update policy saved')); + await loadStatus(); + } + setBusy(''); + } + + async function addSource() { + if (!draft) return; + const id = await promptDialog({ + title: t('Add update source'), + message: t('Use a short ID made from letters, numbers, dots, dashes, or underscores.'), + placeholder: 'private-stable', + confirmLabel: t('Add source'), + }); + if (!id) return; + if (!isValidSourceId(id)) { + toast(t('Invalid source ID')); + return; + } + if (draft.sources[id]) { + toast(t('That source already exists')); + return; + } + changeDraft({ + ...draft, + sources: { + ...draft.sources, + [id]: { + url: '', + publicKeys: [], + allowUnsigned: false, + bearerTokenEnv: '', + }, + }, + }); + } + + async function removeSource(id: string) { + if (!draft) return; + const used = COMPONENTS.some( + (component) => draft[component].source === id + ) || Object.values(draft.plugins.overrides).some( + (override) => override.source === id + ); + if (used) { + toast(t('Move every component off this source before removing it')); + return; + } + if ( + !(await confirmDialog({ + title: t('Remove update source'), + message: tf('Remove source {0} and its public keys?', id), + confirmLabel: t('Remove source'), + danger: true, + })) + ) return; + const sources = { ...draft.sources }; + delete sources[id]; + changeDraft({ ...draft, sources }); + } + + async function addPluginOverride() { + if (!draft) return; + const id = await promptDialog({ + title: t('Add plugin channel override'), + message: t('Enter the exact managed plugin ID.'), + placeholder: 'plugin.id', + confirmLabel: t('Add override'), + }); + if (!id) return; + if (draft.plugins.overrides[id]) { + toast(t('That plugin override already exists')); + return; + } + changeDraft({ + ...draft, + plugins: { + ...draft.plugins, + overrides: { + ...draft.plugins.overrides, + [id]: { + source: draft.plugins.source, + channel: draft.plugins.channel, + autoApply: draft.plugins.autoApply, + }, + }, + }, + }); + } + + if (!isAdmin) { + return ( +
+
+

{t('Administrator authentication required')}

+

+ {t('Update policy, trust keys, and activation controls are restricted to administrators.')} +

+
+
+ ); + } + + return ( +
+
+
+
+
+ + +
+
+ +
+ {loading ? t('Loading update state…') : status?.message || ''} +
+ +
+ {status && COMPONENTS.map((component) => ( + + void applyUpdate( + component, + status.components[component].candidate + ) + } + onRollback={() => + void rollbackUpdate( + component, + status.components[component].rollbackVersion + ) + } + /> + ))} +
+ +
+
+
+
+

{t('Installed plugins')}

+

+ {t('Only managed plugins participate in update activation.')} +

+
+ + {status?.plugins.filter((plugin) => plugin.managed).length || 0} {t('managed')} + +
+
+ {status?.plugins.length ? status.plugins.map((plugin) => ( + + void applyUpdate('plugins', plugin.candidate, plugin.id) + } + onRollback={() => + void rollbackUpdate( + 'plugins', + plugin.rollbackVersion, + plugin.id + ) + } + /> + )) : ( +

{t('No installed plugins reported')}

+ )} +
+
+ +
+
+
+

{t('Update history')}

+

{t('Checks, staging, activation, and rollback outcomes')}

+
+
+
+ + + + + + + + + + + {status?.history.length ? status.history.slice(0, 100).map((entry, index) => ( + + + + + + + )) : ( + + + + )} + +
{t('When')}{t('Target')}{t('Action')}{t('Result')}
{formatTimestamp(entry.timestamp)} + {entry.pluginId || entry.component || '—'} + {entry.version && {entry.version}} + {entry.action || '—'} + + {entry.result || t('Recorded')} + +
{t('No update history yet')}
+
+
+
+ + {draft && config && ( +
{ + event.preventDefault(); + void saveConfig(); + }} + > +
+
+ {t('POLICY DECK')} +

{t('Automation and trust')}

+

+ {t('Configure timing, independent channels, feeds, and public trust roots.')} +

+
+
+ + +
+
+ +
+
+ + + + + + + +
+
+ +
+
+
+

{t('Component channels')}

+

+ {t('Selections remain independent; incompatible cohorts stay staged.')} +

+
+
+
+ {COMPONENTS.map((component) => ( + changePolicy(component, policy)} + /> + ))} +
+ +
+ +
+
+
+

{t('Plugin channel overrides')}

+

{t('Pin individual managed plugins to another source or channel.')}

+
+ +
+
+ {Object.entries(draft.plugins.overrides).length ? Object.entries(draft.plugins.overrides).map(([id, policy]) => ( +
+ {id} + + + changeDraft({ + ...draft, + plugins: { + ...draft.plugins, + overrides: { + ...draft.plugins.overrides, + [id]: { ...policy, channel: event.target.value }, + }, + }, + }) + } + /> + + +
+ )) : ( +

{t('No plugin overrides')}

+ )} +
+
+ +
+
+

{t('Sources and trust roots')}

+

+ {t('Secret values stay in the service environment and are never returned here.')} +

+
+ +
+
+ {Object.entries(draft.sources).map(([id, source]) => ( + 1} + onChange={(next) => + changeDraft({ + ...draft, + sources: { ...draft.sources, [id]: next }, + }) + } + onDelete={() => void removeSource(id)} + /> + ))} +
+
+ )} +
+ ); +} diff --git a/include/echoion/web/HttpSecurity.hpp b/include/echoion/web/HttpSecurity.hpp new file mode 100644 index 0000000..cd520c8 --- /dev/null +++ b/include/echoion/web/HttpSecurity.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Echoion::Web::Security +{ + namespace asio = boost::asio; + + class CidrBlock + { + public: + + CidrBlock(asio::ip::address network, unsigned int prefixLength); + + [[nodiscard]] bool contains( + const asio::ip::address& address) const noexcept; + + private: + + asio::ip::address network_; + unsigned int prefixLength_ = 0; + }; + + using ParsedCidrs = std::expected, std::string>; + + [[nodiscard]] ParsedCidrs parseTrustedProxyCidrs( + std::span cidrs); + + [[nodiscard]] std::string effectiveClientAddress( + const asio::ip::address& immediatePeer, + std::optional forwardedFor, + std::span trustedProxies); + + [[nodiscard]] bool validShortSlug(std::string_view slug) noexcept; + [[nodiscard]] bool validRedirectLocation(std::string_view location) noexcept; + + class ShortLinkRateLimiter + { + public: + + using Clock = std::chrono::steady_clock; + using TimePoint = Clock::time_point; + + struct Config { + double globalRate = 200.0; + double globalBurst = 400.0; + double peerRate = 10.0; + double peerBurst = 20.0; + std::size_t maxPeers = 4096; + Clock::duration idleTimeout = std::chrono::minutes(10); + Clock::duration sweepInterval = std::chrono::minutes(1); + }; + + ShortLinkRateLimiter(); + explicit ShortLinkRateLimiter(Config config); + + [[nodiscard]] bool allow(std::string_view peer); + [[nodiscard]] bool allow(std::string_view peer, TimePoint now); + void reset(); + [[nodiscard]] std::size_t trackedPeerCount() const; + + private: + + struct TokenBucket { + double tokens = 0.0; + TimePoint updated{}; + bool initialized = false; + }; + + struct PeerBucket { + TokenBucket bucket; + TimePoint lastSeen{}; + }; + + static void refill(TokenBucket& bucket, double rate, double burst, + TimePoint now) noexcept; + void evictIdle(TimePoint now, bool force); + + Config config_; + mutable std::mutex mutex_; + TokenBucket global_; + std::unordered_map peers_; + TimePoint nextSweep_{}; + bool sweepInitialized_ = false; + }; + +} // namespace Echoion::Web::Security diff --git a/include/echoion/web/HttpServer.hpp b/include/echoion/web/HttpServer.hpp index 549be92..4bcfab3 100644 --- a/include/echoion/web/HttpServer.hpp +++ b/include/echoion/web/HttpServer.hpp @@ -1,5 +1,7 @@ #pragma once +#include "echoion/web/HttpSecurity.hpp" + #include #include #include @@ -7,13 +9,16 @@ #include #include +#include #include #include #include #include +#include #include #include #include +#include namespace Echoion::Web { @@ -43,6 +48,7 @@ namespace Echoion::Web // Server-wide switch for the Now Playing video preview, // surfaced to the browser via /config.json. bool nowPlayingVideo = true; + std::vector trustedProxyCidrs; }; HttpServer(); @@ -52,6 +58,12 @@ namespace Echoion::Web void stop(); [[nodiscard]] bool isRunning() const { return running_; } + using TrustedProxyUpdate = std::expected; + [[nodiscard]] static TrustedProxyUpdate validateTrustedProxyCidrs( + const std::vector& cidrs); + [[nodiscard]] TrustedProxyUpdate setTrustedProxyCidrs( + const std::vector& cidrs); + // A user's avatar image, served at GET /avatar/. Installed // by Core (which owns the TeamSpeak plugin handle); best-effort — // nullopt yields a 404 and the UI falls back to initials. It may be @@ -79,6 +91,25 @@ namespace Echoion::Web dashboardProvider_ = std::move(provider); } + enum class ShortLinkStatus { + found, + notFound, + gone, + rateLimited, + unavailable, + }; + struct ShortLinkResolution { + ShortLinkStatus status = ShortLinkStatus::notFound; + std::string location; + }; + using ShortLinkResolver = + std::function; + void setShortLinkResolver(ShortLinkResolver resolver) + { + std::lock_guard lock(shortLinkResolverMutex_); + shortLinkResolver_ = std::move(resolver); + } + private: void acceptLoop(); @@ -96,7 +127,12 @@ namespace Echoion::Web // Serves one request; returns true when the connection should be // kept open for the next request (HTTP keep-alive). bool serveHttp(asio::ip::tcp::socket& socket, - const http::request& req); + const http::request& req, + std::string_view clientAddress); + [[nodiscard]] std::string clientAddress( + const asio::ip::tcp::socket& socket, + const http::request& req) const; + [[nodiscard]] bool allowShortLinkRequest(std::string_view peer); Config config_; asio::io_context ioContext_; @@ -126,6 +162,11 @@ namespace Echoion::Web std::mutex avatarProviderMutex_; DashboardProvider dashboardProvider_; std::mutex dashboardProviderMutex_; + ShortLinkResolver shortLinkResolver_; + std::mutex shortLinkResolverMutex_; + mutable std::shared_mutex trustedProxyMutex_; + std::vector trustedProxyNetworks_; + Security::ShortLinkRateLimiter shortLinkRateLimiter_; }; } // namespace Echoion::Web diff --git a/src/HttpSecurity.cpp b/src/HttpSecurity.cpp new file mode 100644 index 0000000..6d89efe --- /dev/null +++ b/src/HttpSecurity.cpp @@ -0,0 +1,351 @@ +#include "echoion/web/HttpSecurity.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Echoion::Web::Security +{ + namespace + { + constexpr std::size_t MAX_FORWARDED_HOPS = 64; + constexpr std::size_t MAX_REDIRECT_LENGTH = 8192; + + asio::ip::address + normalizeMappedAddress(const asio::ip::address& address) + { + if (address.is_v6() && address.to_v6().is_v4_mapped()) { + return asio::ip::make_address_v4(asio::ip::v4_mapped, + address.to_v6()); + } + return address; + } + + bool isTrusted(const asio::ip::address& address, + std::span + trustedProxies) noexcept + { + return std::ranges::any_of(trustedProxies, + [&address](const CidrBlock& network) { + return network.contains(address); + }); + } + + std::string_view trimForwardedToken(std::string_view token) noexcept + { + while (!token.empty() && + (token.front() == ' ' || token.front() == '\t')) { + token.remove_prefix(1); + } + while (!token.empty() && + (token.back() == ' ' || token.back() == '\t')) { + token.remove_suffix(1); + } + return token; + } + } // namespace + + CidrBlock::CidrBlock(asio::ip::address network, unsigned int prefixLength) + : network_(std::move(network)), prefixLength_(prefixLength) + { + } + + bool CidrBlock::contains(const asio::ip::address& address) const noexcept + { + asio::ip::address candidate = address; + if (network_.is_v4() && candidate.is_v6()) { + if (!candidate.to_v6().is_v4_mapped()) { + return false; + } + candidate = asio::ip::make_address_v4(asio::ip::v4_mapped, + candidate.to_v6()); + } else if (network_.is_v6() && candidate.is_v4()) { + candidate = asio::ip::make_address_v6(asio::ip::v4_mapped, + candidate.to_v4()); + } + if (network_.is_v4() != candidate.is_v4()) { + return false; + } + + const auto matches = [this](const auto& lhs, const auto& rhs) { + for (std::size_t index = 0; index < lhs.size(); ++index) { + const auto consumed = static_cast(index * 8); + const auto remaining = + prefixLength_ > consumed ? prefixLength_ - consumed : 0U; + const auto mask = static_cast( + remaining >= 8 ? 0xffU + : remaining == 0 ? 0U + : 0xffU << (8 - remaining)); + if ((lhs[index] & mask) != (rhs[index] & mask)) { + return false; + } + } + return true; + }; + + return network_.is_v4() ? matches(network_.to_v4().to_bytes(), + candidate.to_v4().to_bytes()) + : matches(network_.to_v6().to_bytes(), + candidate.to_v6().to_bytes()); + } + + ParsedCidrs parseTrustedProxyCidrs(std::span cidrs) + { + std::vector parsed; + parsed.reserve(cidrs.size()); + for (std::size_t index = 0; index < cidrs.size(); ++index) { + const std::string_view cidr = cidrs[index]; + const auto slash = cidr.find('/'); + if (cidr.empty() || slash == 0 || + (slash != std::string_view::npos && + (slash + 1 == cidr.size() || + cidr.find('/', slash + 1) != std::string_view::npos))) { + return std::unexpected( + std::format("trusted proxy CIDR #{} ('{}') is malformed", + index + 1, cidr)); + } + + const std::string_view addressText = cidr.substr(0, slash); + if (addressText.contains('%')) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') must not contain an IPv6 " + "scope identifier", + index + 1, cidr)); + } + boost::system::error_code error; + const auto network = asio::ip::make_address(addressText, error); + if (error) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') has an invalid address", + index + 1, cidr)); + } + + const unsigned int maxBits = network.is_v4() ? 32U : 128U; + unsigned int prefixLength = maxBits; + if (slash != std::string_view::npos) { + const std::string_view prefix = cidr.substr(slash + 1); + const auto [end, code] = std::from_chars( + prefix.data(), prefix.data() + prefix.size(), prefixLength); + if (code != std::errc{} || + end != prefix.data() + prefix.size() || + prefixLength > maxBits) { + return std::unexpected(std::format( + "trusted proxy CIDR #{} ('{}') has an invalid prefix", + index + 1, cidr)); + } + } + parsed.emplace_back(network, prefixLength); + } + return parsed; + } + + std::string effectiveClientAddress(const asio::ip::address& immediatePeer, + std::optional + forwardedFor, + std::span + trustedProxies) + { + const auto directAddress = normalizeMappedAddress(immediatePeer); + if (!forwardedFor || !isTrusted(immediatePeer, trustedProxies)) { + return directAddress.to_string(); + } + + std::vector hops; + hops.reserve(8); + std::string_view remaining = *forwardedFor; + for (;;) { + if (hops.size() == MAX_FORWARDED_HOPS) { + return directAddress.to_string(); + } + const auto comma = remaining.find(','); + const auto token = trimForwardedToken(remaining.substr(0, comma)); + if (token.empty() || token.contains('%')) { + return directAddress.to_string(); + } + boost::system::error_code error; + auto hop = asio::ip::make_address(token, error); + if (error || (hop.is_v6() && hop.to_v6().scope_id() != 0)) { + return directAddress.to_string(); + } + hops.push_back(std::move(hop)); + if (comma == std::string_view::npos) { + break; + } + remaining.remove_prefix(comma + 1); + } + + asio::ip::address effective = immediatePeer; + for (auto hop = hops.rbegin(); hop != hops.rend(); ++hop) { + if (!isTrusted(effective, trustedProxies)) { + break; + } + effective = *hop; + } + return normalizeMappedAddress(effective).to_string(); + } + + bool validShortSlug(std::string_view slug) noexcept + { + return slug.size() == 10 && + std::ranges::all_of(slug, [](unsigned char character) { + return (character >= '0' && character <= '9') || + (character >= 'A' && character <= 'Z') || + (character >= 'a' && character <= 'z'); + }); + } + + bool validRedirectLocation(std::string_view location) noexcept + { + if (location.empty() || location.size() > MAX_REDIRECT_LENGTH || + std::ranges::any_of(location, [](unsigned char character) { + return character <= 0x20U || character >= 0x7fU; + })) { + return false; + } + + const auto parsed = boost::urls::parse_uri(location); + if (!parsed) { + return false; + } + const auto& url = *parsed; + if ((url.scheme_id() != boost::urls::scheme::http && + url.scheme_id() != boost::urls::scheme::https) || + !url.has_authority() || url.has_userinfo() || + url.encoded_host().empty()) { + return false; + } + + if (url.has_port()) { + const auto port = url.port(); + unsigned int number = 0; + const auto [end, code] = + std::from_chars(port.data(), port.data() + port.size(), number); + if (port.empty() || code != std::errc{} || + end != port.data() + port.size() || number == 0 || + number > 65535) { + return false; + } + } + return true; + } + + ShortLinkRateLimiter::ShortLinkRateLimiter() + : ShortLinkRateLimiter(Config{}) + { + } + + ShortLinkRateLimiter::ShortLinkRateLimiter(Config config) : config_(config) + { + if (!std::isfinite(config_.globalRate) || config_.globalRate < 0.0 || + !std::isfinite(config_.globalBurst) || config_.globalBurst < 1.0 || + !std::isfinite(config_.peerRate) || config_.peerRate < 0.0 || + !std::isfinite(config_.peerBurst) || config_.peerBurst < 1.0 || + config_.maxPeers == 0 || + config_.idleTimeout < Clock::duration::zero() || + config_.sweepInterval < Clock::duration::zero()) { + throw std::invalid_argument( + "invalid short-link rate limiter settings"); + } + peers_.reserve(config_.maxPeers); + } + + bool ShortLinkRateLimiter::allow(std::string_view peer) + { + return allow(peer, Clock::now()); + } + + bool ShortLinkRateLimiter::allow(std::string_view peer, TimePoint now) + { + std::lock_guard lock(mutex_); + evictIdle(now, false); + refill(global_, config_.globalRate, config_.globalBurst, now); + if (global_.tokens < 1.0) { + return false; + } + + const std::string peerKey{peer}; + auto found = peers_.find(peerKey); + if (found == peers_.end()) { + if (peers_.size() >= config_.maxPeers) { + evictIdle(now, true); + } + if (peers_.size() >= config_.maxPeers) { + return false; + } + found = + peers_ + .emplace(peerKey, PeerBucket{.bucket = {}, .lastSeen = now}) + .first; + } + + found->second.lastSeen = now; + refill(found->second.bucket, config_.peerRate, config_.peerBurst, now); + if (found->second.bucket.tokens < 1.0) { + return false; + } + + // Commit both token deductions together. A peer-local rejection never + // consumes global capacity and cannot starve unrelated clients. + global_.tokens -= 1.0; + found->second.bucket.tokens -= 1.0; + return true; + } + + void ShortLinkRateLimiter::reset() + { + std::lock_guard lock(mutex_); + global_ = {}; + peers_.clear(); + nextSweep_ = {}; + sweepInitialized_ = false; + } + + std::size_t ShortLinkRateLimiter::trackedPeerCount() const + { + std::lock_guard lock(mutex_); + return peers_.size(); + } + + void ShortLinkRateLimiter::refill(TokenBucket& bucket, double rate, + double burst, TimePoint now) noexcept + { + if (!bucket.initialized) { + bucket.tokens = burst; + bucket.updated = now; + bucket.initialized = true; + return; + } + const auto elapsed = + now > bucket.updated + ? std::chrono::duration(now - bucket.updated).count() + : 0.0; + bucket.tokens = std::min(burst, bucket.tokens + elapsed * rate); + bucket.updated = now; + } + + void ShortLinkRateLimiter::evictIdle(TimePoint now, bool force) + { + if (!force && sweepInitialized_ && now < nextSweep_) { + return; + } + for (auto peer = peers_.begin(); peer != peers_.end();) { + const bool expired = + now >= peer->second.lastSeen && + now - peer->second.lastSeen >= config_.idleTimeout; + if (expired) { + peer = peers_.erase(peer); + } else { + ++peer; + } + } + nextSweep_ = now + config_.sweepInterval; + sweepInitialized_ = true; + } + +} // namespace Echoion::Web::Security diff --git a/src/HttpServer.cpp b/src/HttpServer.cpp index 2b5e979..3ec2414 100644 --- a/src/HttpServer.cpp +++ b/src/HttpServer.cpp @@ -12,6 +12,10 @@ #include #include +#if defined(__unix__) || defined(__APPLE__) +#include +#endif + namespace Echoion::Web { namespace websocket = beast::websocket; @@ -114,19 +118,77 @@ namespace Echoion::Web from.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore); to.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignore); } + } // namespace HttpServer::HttpServer() = default; HttpServer::~HttpServer() { stop(); } + HttpServer::TrustedProxyUpdate HttpServer::validateTrustedProxyCidrs( + const std::vector& cidrs) + { + try { + auto parsed = Security::parseTrustedProxyCidrs(cidrs); + if (!parsed) { + return std::unexpected(std::move(parsed.error())); + } + return {}; + } catch (const std::exception& exception) { + return std::unexpected( + std::format("failed to validate trusted proxy CIDRs: {}", + exception.what())); + } + } + + HttpServer::TrustedProxyUpdate + HttpServer::setTrustedProxyCidrs(const std::vector& cidrs) + { + try { + auto parsed = Security::parseTrustedProxyCidrs(cidrs); + if (!parsed) { + return std::unexpected(std::move(parsed.error())); + } + { + std::unique_lock lock(trustedProxyMutex_); + // A trust-policy change changes the peer identity used by the + // limiter. Reset while new address calculations are blocked, + // then publish the already-parsed policy with a no-throw swap. + shortLinkRateLimiter_.reset(); + trustedProxyNetworks_.swap(*parsed); + } + return {}; + } catch (const std::exception& exception) { + return std::unexpected(std::format( + "failed to update trusted proxy CIDRs: {}", exception.what())); + } + } + bool HttpServer::start(const Config& config) { - if (running_.exchange(true)) { + if (running_.load()) { return false; } - config_ = config; try { + auto trustedProxies = + Security::parseTrustedProxyCidrs(config.trustedProxyCidrs); + if (!trustedProxies) { + Void::Log::error( + "HttpServer", "{}", + std::format("Failed to start web interface: {}", + trustedProxies.error())); + return false; + } + bool expected = false; + if (!running_.compare_exchange_strong(expected, true)) { + return false; + } + config_ = config; + { + std::unique_lock lock(trustedProxyMutex_); + trustedProxyNetworks_ = std::move(*trustedProxies); + } + shortLinkRateLimiter_.reset(); ioContext_.restart(); asio::ip::tcp::endpoint endpoint( @@ -272,26 +334,79 @@ namespace Echoion::Web { beast::error_code ec; beast::flat_buffer buffer; - // Serve requests on this connection until the peer closes, an error - // occurs, or the request asks not to keep the connection alive. - while (running_.load()) { - http::request req; - http::read(*socket, buffer, req, ec); - if (ec) { - return; - } - - if (websocket::is_upgrade(req)) { - if (req.target() == "/rpc") { - bridgeRpc(socket, req, buffer); - } - return; - } - - if (!serveHttp(*socket, req)) { + // Bound slow clients and parser memory. Every accepted connection + // serves exactly one request; browsers simply open another connection. +#if defined(__unix__) || defined(__APPLE__) + timeval timeout{.tv_sec = 5, .tv_usec = 0}; + (void)::setsockopt(socket->native_handle(), SOL_SOCKET, SO_RCVTIMEO, + &timeout, sizeof(timeout)); +#endif + http::request_parser parser; + parser.header_limit(32 * 1024); + parser.body_limit(0); + http::read(*socket, buffer, parser, ec); + if (ec) { + return; + } + auto req = parser.release(); + for (const auto& field : req) { + if (field.name_string().size() + field.value().size() > 8 * 1024) { + http::response response{ + http::status::request_header_fields_too_large, + req.version()}; + response.set(http::field::server, "Echoion"); + response.body() = "Request Header Fields Too Large"; + response.prepare_payload(); + response.keep_alive(false); + http::write(*socket, response, ec); return; } } + + if (websocket::is_upgrade(req)) { + if (req.target() == "/rpc") { + bridgeRpc(socket, req, buffer); + } + return; + } + + (void)serveHttp(*socket, req, clientAddress(*socket, req)); + } + + std::string HttpServer::clientAddress( + const asio::ip::tcp::socket& socket, + const http::request& req) const + { + boost::system::error_code error; + const auto endpoint = socket.remote_endpoint(error); + if (error) { + return {}; + } + + std::optional forwardedFor; + for (const auto& field : req) { + if (!beast::iequals(field.name_string(), "X-Forwarded-For")) { + continue; + } + // Multiple field-lines have ambiguous intermediary semantics. + // Ignore all of them instead of choosing an attacker-controlled + // value. + if (forwardedFor) { + forwardedFor.reset(); + break; + } + forwardedFor = + std::string_view{field.value().data(), field.value().size()}; + } + + std::shared_lock lock(trustedProxyMutex_); + return Security::effectiveClientAddress( + endpoint.address(), forwardedFor, trustedProxyNetworks_); + } + + bool HttpServer::allowShortLinkRequest(std::string_view peer) + { + return shortLinkRateLimiter_.allow(peer); } void HttpServer::bridgeRpc(std::shared_ptr browser, @@ -315,25 +430,10 @@ namespace Echoion::Web // Forward the browser's effective IP so the RPC server can offer // address-based autologin. Never trust a client-supplied value; a - // reverse proxy's X-Forwarded-For (first hop) wins over the socket - // address because the proxy connects from its own host. + // X-Forwarded-For is accepted only from configured proxies and walked + // from right to left, stopping at the nearest untrusted hop. req.erase("X-Echoion-Client-Ip"); - std::string clientIp; - if (auto xff = req.find("X-Forwarded-For"); xff != req.end()) { - clientIp = std::string(xff->value()); - if (auto comma = clientIp.find(','); comma != std::string::npos) { - clientIp = clientIp.substr(0, comma); - } - while (!clientIp.empty() && clientIp.front() == ' ') { - clientIp.erase(clientIp.begin()); - } - } - if (clientIp.empty()) { - boost::system::error_code epEc; - if (auto ep = browser->remote_endpoint(epEc); !epEc) { - clientIp = ep.address().to_string(); - } - } + const std::string clientIp = clientAddress(*browser, req); if (!clientIp.empty()) { req.set("X-Echoion-Client-Ip", clientIp); } @@ -373,7 +473,8 @@ namespace Echoion::Web } bool HttpServer::serveHttp(asio::ip::tcp::socket& socket, - const http::request& req) + const http::request& req, + std::string_view requestAddress) { beast::error_code ec; const bool isHead = req.method() == http::verb::head; @@ -398,7 +499,7 @@ namespace Echoion::Web if (!location.empty()) { res.set(http::field::location, location); } - res.keep_alive(req.keep_alive()); + res.keep_alive(false); // HEAD advertises the real Content-Length but carries no body. res.content_length( status == http::status::not_modified ? 0 : body.size()); @@ -468,6 +569,65 @@ namespace Echoion::Web return !ec && req.keep_alive(); } + constexpr std::string_view kShortPrefix = "/s/"; + if (target.starts_with(kShortPrefix)) { + const std::string key = target.substr(kShortPrefix.size()); + if (!Security::validShortSlug(key)) { + respond(http::status::not_found, "text/plain", "Not Found", + "no-store"); + return false; + } + if (!allowShortLinkRequest(requestAddress)) { + respond(http::status::too_many_requests, "text/plain", + "Too Many Requests", "no-store"); + return false; + } + ShortLinkResolver resolver; + { + std::lock_guard lock(shortLinkResolverMutex_); + resolver = shortLinkResolver_; + } + const auto resolution = + resolver ? resolver(key) + : ShortLinkResolution{.status = + ShortLinkStatus::unavailable, + .location = {}}; + http::status status = http::status::not_found; + switch (resolution.status) { + case ShortLinkStatus::found: + status = http::status::found; + break; + case ShortLinkStatus::gone: + status = http::status::gone; + break; + case ShortLinkStatus::rateLimited: + status = http::status::too_many_requests; + break; + case ShortLinkStatus::unavailable: + status = http::status::service_unavailable; + break; + case ShortLinkStatus::notFound: + break; + } + http::response response{status, req.version()}; + response.set(http::field::server, "Echoion"); + response.set(http::field::cache_control, "no-store"); + response.set("Referrer-Policy", "no-referrer"); + response.set("X-Robots-Tag", "noindex, nofollow"); + response.set("X-Content-Type-Options", "nosniff"); + response.set("Content-Security-Policy", "default-src 'none'"); + if (status == http::status::found && + Security::validRedirectLocation(resolution.location)) { + response.set(http::field::location, resolution.location); + } else if (status == http::status::found) { + response.result(http::status::service_unavailable); + } + response.content_length(0); + response.keep_alive(false); + http::write(socket, response, ec); + return false; + } + // User avatar images, resolved through Core's provider (TeamSpeak // avatar cache). Best-effort: 404 lets the UI fall back to its // initial-letter avatars; short private caching keeps reloads cheap diff --git a/tests/HttpSecurityTests.cpp b/tests/HttpSecurityTests.cpp new file mode 100644 index 0000000..c7fa42b --- /dev/null +++ b/tests/HttpSecurityTests.cpp @@ -0,0 +1,300 @@ +#include "echoion/web/HttpSecurity.hpp" +#include "echoion/web/HttpServer.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Echoion::Web::Security::ShortLinkRateLimiter; + namespace asio = boost::asio; + + bool expect(bool condition, std::string_view message) + { + if (!condition) { + std::cerr << message << '\n'; + } + return condition; + } + + bool testShortSlugs() + { + using Echoion::Web::Security::validShortSlug; + std::string nonAscii(9, 'a'); + nonAscii.push_back(static_cast(0xe9)); + return expect(validShortSlug("aZ019BcDeF"), + "ASCII short slug was rejected") && + expect(!validShortSlug("aZ019BcDe_"), + "punctuation was accepted in a short slug") && + expect(!validShortSlug("short"), + "short slug length was not enforced") && + expect(!validShortSlug(nonAscii), + "locale-dependent non-ASCII alphanumeric was accepted"); + } + + bool testCidrsAndForwarding() + { + using Echoion::Web::Security::effectiveClientAddress; + using Echoion::Web::Security::parseTrustedProxyCidrs; + + const std::vector trustedTexts{"10.0.0.0/8", + "192.0.2.0/24"}; + auto trusted = parseTrustedProxyCidrs(trustedTexts); + if (!expect(trusted.has_value(), "valid trusted proxy CIDRs failed")) { + return false; + } + + const std::vector invalidCidrs{"", + "10.0.0.0/", + "10.0.0.0/33", + "10.0.0.0/-1", + "10.0.0.0/+8", + "10.0.0.0/8 ", + " 10.0.0.0/8", + "2001:db8::/129", + "fe80::1%1/128", + "10.0.0.0/8/9", + "not-an-address"}; + for (const auto& invalid : invalidCidrs) { + const std::vector one{invalid}; + if (!expect(!parseTrustedProxyCidrs(one), + "invalid trusted proxy CIDR was accepted: " + + invalid)) { + return false; + } + } + + const std::vector mappedV4Text{"192.0.2.0/24"}; + auto mappedV4 = parseTrustedProxyCidrs(mappedV4Text); + const std::vector mappedV6Text{"::ffff:192.0.2.0/120"}; + auto mappedV6 = parseTrustedProxyCidrs(mappedV6Text); + if (!expect(mappedV4 && mappedV6, + "IPv4-mapped test networks did not parse") || + !expect((*mappedV4)[0].contains( + asio::ip::make_address("::ffff:192.0.2.42")), + "IPv4 CIDR did not match an IPv4-mapped peer") || + !expect( + (*mappedV6)[0].contains(asio::ip::make_address("192.0.2.42")), + "IPv4-mapped IPv6 CIDR did not match an IPv4 peer")) { + return false; + } + + const auto immediate = asio::ip::make_address("10.0.0.10"); + if (!expect(effectiveClientAddress( + immediate, "203.0.113.9, 198.51.100.7, 192.0.2.20", + *trusted) == "198.51.100.7", + "X-Forwarded-For was not walked from right to left") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, 198.51.100.7", + *trusted) == "198.51.100.7", + "spoofed leftmost forwarded hop was trusted") || + !expect(effectiveClientAddress(asio::ip::make_address("172.16.0.2"), + "203.0.113.9", + *trusted) == "172.16.0.2", + "untrusted direct peer supplied a forwarded address") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, invalid, 192.0.2.20", + *trusted) == "10.0.0.10", + "malformed forwarded chain was partially accepted") || + !expect(effectiveClientAddress( + asio::ip::make_address("::ffff:10.0.0.10"), + "198.51.100.7", *trusted) == "198.51.100.7", + "IPv4-mapped trusted peer was not recognized") || + !expect(effectiveClientAddress(immediate, + "203.0.113.9, ::ffff:192.0.2.20", + *trusted) == "203.0.113.9", + "IPv4-mapped trusted intermediary was not recognized") || + !expect(effectiveClientAddress( + asio::ip::make_address("::ffff:172.16.0.2"), + std::nullopt, *trusted) == "172.16.0.2", + "IPv4-mapped direct address was not normalized")) { + return false; + } + return true; + } + + bool testRedirectLocations() + { + using Echoion::Web::Security::validRedirectLocation; + const std::vector valid{ + "https://example.test/watch?v=abc%201#fragment", + "HTTP://example.test/", "http://[2001:db8::1]:8080/path"}; + for (const auto location : valid) { + if (!expect(validRedirectLocation(location), + "valid HTTP redirect was rejected")) { + return false; + } + } + + const std::vector invalid{ + "", + "ftp://example.test/file", + "/relative/path", + "http:///missing-host", + "https://user@example.test/", + "https://example.test:", + "https://example.test:0/", + "https://example.test:65536/", + "https://example.test/a b"}; + for (const auto location : invalid) { + if (!expect(!validRedirectLocation(location), + "unsafe redirect location was accepted")) { + return false; + } + } + + for (unsigned int control = 0; control <= 0x20; ++control) { + std::string location = "https://example.test/path"; + location.push_back(static_cast(control)); + if (!expect(!validRedirectLocation(location), + "ASCII control was accepted in redirect location")) { + return false; + } + } + for (const unsigned int control : {0x7fU, 0x80U, 0x9fU}) { + std::string location = "https://example.test/path"; + location.push_back(static_cast(control)); + if (!expect(!validRedirectLocation(location), + "DEL/C1 control was accepted in redirect location")) { + return false; + } + } + return true; + } + + bool testTrustedProxyRuntimeUpdates() + { + Echoion::Web::HttpServer server; + const std::vector initial{"127.0.0.0/8"}; + const std::vector replacement{"::1/128"}; + const std::vector invalid{"127.0.0.1/129"}; + const std::vector none; + return expect(server.setTrustedProxyCidrs(initial).has_value(), + "initial live trusted-proxy update failed") && + expect(server.setTrustedProxyCidrs(replacement).has_value(), + "replacement live trusted-proxy update failed") && + expect(!server.setTrustedProxyCidrs(invalid), + "invalid live trusted-proxy update was accepted") && + expect(server.setTrustedProxyCidrs(none).has_value(), + "clearing live trusted proxies failed"); + } + + bool testRateLimiterFairnessAndBounds() + { + using namespace std::chrono_literals; + const auto now = ShortLinkRateLimiter::TimePoint{} + 1s; + ShortLinkRateLimiter fair({ + .globalRate = 0.0, + .globalBurst = 2.0, + .peerRate = 0.0, + .peerBurst = 1.0, + .maxPeers = 4, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + if (!expect(fair.allow("peer-a", now), + "first peer request was rejected") || + !expect(!fair.allow("peer-a", now), + "peer burst limit was not enforced") || + !expect(fair.allow("peer-b", now), + "peer rejection consumed unrelated global capacity")) { + return false; + } + + ShortLinkRateLimiter bounded({ + .globalRate = 100.0, + .globalBurst = 100.0, + .peerRate = 100.0, + .peerBurst = 2.0, + .maxPeers = 2, + .idleTimeout = 100ms, + .sweepInterval = 1h, + }); + if (!expect(bounded.allow("peer-a", now) && + bounded.allow("peer-b", now), + "bounded limiter rejected initial peers") || + !expect(!bounded.allow("peer-c", now), + "bounded limiter exceeded its peer cap") || + !expect(bounded.trackedPeerCount() == 2, + "bounded limiter retained too many peers") || + !expect(bounded.allow("peer-c", now + 200ms), + "idle peer entries were not evicted") || + !expect(bounded.trackedPeerCount() <= 2, + "idle eviction broke the peer cap")) { + return false; + } + return true; + } + + bool testRateLimiterConcurrency() + { + using namespace std::chrono_literals; + ShortLinkRateLimiter limiter({ + .globalRate = 0.0, + .globalBurst = 100.0, + .peerRate = 0.0, + .peerBurst = 5.0, + .maxPeers = 16, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + const auto now = ShortLinkRateLimiter::TimePoint{} + 1s; + std::atomic allowed{0}; + std::vector workers; + workers.reserve(32); + for (int index = 0; index < 32; ++index) { + workers.emplace_back([&] { + if (limiter.allow("one-peer", now)) { + ++allowed; + } + }); + } + for (auto& worker : workers) { + worker.join(); + } + if (!expect(allowed.load() == 5, + "concurrent limiter admitted beyond the peer burst")) { + return false; + } + + ShortLinkRateLimiter global({ + .globalRate = 0.0, + .globalBurst = 7.0, + .peerRate = 0.0, + .peerBurst = 1.0, + .maxPeers = 64, + .idleTimeout = 1min, + .sweepInterval = 1min, + }); + allowed = 0; + workers.clear(); + for (int index = 0; index < 32; ++index) { + workers.emplace_back([&, index] { + if (global.allow("peer-" + std::to_string(index), now)) { + ++allowed; + } + }); + } + for (auto& worker : workers) { + worker.join(); + } + return expect(allowed.load() == 7, + "concurrent limiter admitted beyond the global burst"); + } +} // namespace + +int main() +{ + return testShortSlugs() && testCidrsAndForwarding() && + testRedirectLocations() && + testTrustedProxyRuntimeUpdates() && + testRateLimiterFairnessAndBounds() && + testRateLimiterConcurrency() + ? 0 + : 1; +}