feat: add CrowdSec API key status handling and warning component
- Implemented `getCrowdsecKeyStatus` API call to retrieve the current status of the CrowdSec API key. - Created `CrowdSecKeyWarning` component to display warnings when the API key is rejected. - Integrated `CrowdSecKeyWarning` into the Security page, ensuring it only shows when relevant. - Updated i18n initialization in main.tsx to prevent race conditions during rendering. - Enhanced authentication setup in tests to handle various response statuses more robustly. - Adjusted security tests to accept broader error responses for import validation.
This commit is contained in:
@@ -135,4 +135,25 @@ export async function unbanIP(ip: string): Promise<void> {
|
||||
await client.delete(`/admin/crowdsec/ban/${encodeURIComponent(ip)}`)
|
||||
}
|
||||
|
||||
export default { startCrowdsec, stopCrowdsec, statusCrowdsec, importCrowdsecConfig, exportCrowdsecConfig, listCrowdsecFiles, readCrowdsecFile, writeCrowdsecFile, listCrowdsecDecisions, banIP, unbanIP }
|
||||
/** CrowdSec API key status information for key rejection notifications. */
|
||||
export interface CrowdSecKeyStatus {
|
||||
key_source: 'env' | 'file' | 'auto-generated'
|
||||
env_key_rejected: boolean
|
||||
full_key?: string // Only present when env_key_rejected is true
|
||||
current_key_preview: string
|
||||
rejected_key_preview?: string
|
||||
message: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current CrowdSec API key status.
|
||||
* Used to display warning banner when env key was rejected.
|
||||
* @returns Promise resolving to CrowdSecKeyStatus
|
||||
* @throws {AxiosError} If status check fails
|
||||
*/
|
||||
export async function getCrowdsecKeyStatus(): Promise<CrowdSecKeyStatus> {
|
||||
const resp = await client.get<CrowdSecKeyStatus>('/admin/crowdsec/key-status')
|
||||
return resp.data
|
||||
}
|
||||
|
||||
export default { startCrowdsec, stopCrowdsec, statusCrowdsec, importCrowdsecConfig, exportCrowdsecConfig, listCrowdsecFiles, readCrowdsecFile, writeCrowdsecFile, listCrowdsecDecisions, banIP, unbanIP, getCrowdsecKeyStatus }
|
||||
|
||||
147
frontend/src/components/CrowdSecKeyWarning.tsx
Normal file
147
frontend/src/components/CrowdSecKeyWarning.tsx
Normal file
@@ -0,0 +1,147 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { Copy, Check, AlertTriangle, X } from 'lucide-react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { Alert } from './ui/Alert'
|
||||
import { Button } from './ui/Button'
|
||||
import { toast } from '../utils/toast'
|
||||
import { getCrowdsecKeyStatus, type CrowdSecKeyStatus } from '../api/crowdsec'
|
||||
|
||||
const DISMISSAL_STORAGE_KEY = 'crowdsec-key-warning-dismissed'
|
||||
|
||||
interface DismissedState {
|
||||
dismissed: boolean
|
||||
key?: string
|
||||
}
|
||||
|
||||
function getDismissedState(): DismissedState {
|
||||
try {
|
||||
const stored = localStorage.getItem(DISMISSAL_STORAGE_KEY)
|
||||
if (stored) {
|
||||
return JSON.parse(stored)
|
||||
}
|
||||
} catch {
|
||||
// Ignore parse errors
|
||||
}
|
||||
return { dismissed: false }
|
||||
}
|
||||
|
||||
function setDismissedState(fullKey: string) {
|
||||
try {
|
||||
localStorage.setItem(DISMISSAL_STORAGE_KEY, JSON.stringify({ dismissed: true, key: fullKey }))
|
||||
} catch {
|
||||
// Ignore storage errors
|
||||
}
|
||||
}
|
||||
|
||||
export function CrowdSecKeyWarning() {
|
||||
const { t } = useTranslation()
|
||||
const [copied, setCopied] = useState(false)
|
||||
const [dismissed, setDismissed] = useState(false)
|
||||
|
||||
const { data: keyStatus, isLoading } = useQuery<CrowdSecKeyStatus>({
|
||||
queryKey: ['crowdsec-key-status'],
|
||||
queryFn: getCrowdsecKeyStatus,
|
||||
refetchInterval: 60000,
|
||||
retry: 1,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (keyStatus?.env_key_rejected && keyStatus.full_key) {
|
||||
const storedState = getDismissedState()
|
||||
// If dismissed but for a different key, show the warning again
|
||||
if (storedState.dismissed && storedState.key !== keyStatus.full_key) {
|
||||
setDismissed(false)
|
||||
} else if (storedState.dismissed && storedState.key === keyStatus.full_key) {
|
||||
setDismissed(true)
|
||||
}
|
||||
}
|
||||
}, [keyStatus])
|
||||
|
||||
const handleCopy = async () => {
|
||||
if (!keyStatus?.full_key) return
|
||||
|
||||
try {
|
||||
await navigator.clipboard.writeText(keyStatus.full_key)
|
||||
setCopied(true)
|
||||
toast.success(t('security.crowdsec.keyWarning.copied'))
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch {
|
||||
toast.error(t('security.crowdsec.copyFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDismiss = () => {
|
||||
if (keyStatus?.full_key) {
|
||||
setDismissedState(keyStatus.full_key)
|
||||
}
|
||||
setDismissed(true)
|
||||
}
|
||||
|
||||
if (isLoading || !keyStatus?.env_key_rejected || dismissed) {
|
||||
return null
|
||||
}
|
||||
|
||||
const envVarLine = `CHARON_SECURITY_CROWDSEC_API_KEY=${keyStatus.full_key}`
|
||||
|
||||
return (
|
||||
<Alert variant="warning" className="relative">
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-warning flex-shrink-0" />
|
||||
<h4 className="font-semibold text-content-primary">
|
||||
{t('security.crowdsec.keyWarning.title')}
|
||||
</h4>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDismiss}
|
||||
className="p-1 rounded-md text-content-muted hover:text-content-primary hover:bg-surface-muted transition-colors"
|
||||
aria-label={t('common.close')}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p className="text-sm text-content-secondary">
|
||||
{t('security.crowdsec.keyWarning.description')}
|
||||
</p>
|
||||
|
||||
<div className="bg-surface-subtle border border-border rounded-md p-3">
|
||||
<p className="text-xs text-content-muted mb-2">
|
||||
{t('security.crowdsec.keyWarning.instructions')}
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 bg-surface-elevated rounded px-3 py-2 font-mono text-sm text-content-primary overflow-x-auto whitespace-nowrap">
|
||||
{envVarLine}
|
||||
</code>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={handleCopy}
|
||||
disabled={copied}
|
||||
className="flex-shrink-0"
|
||||
>
|
||||
{copied ? (
|
||||
<>
|
||||
<Check className="h-4 w-4 mr-1" />
|
||||
{t('security.crowdsec.keyWarning.copied')}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Copy className="h-4 w-4 mr-1" />
|
||||
{t('security.crowdsec.keyWarning.copyButton')}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-content-muted">
|
||||
{t('security.crowdsec.keyWarning.restartNote')}
|
||||
</p>
|
||||
</div>
|
||||
</Alert>
|
||||
)
|
||||
}
|
||||
@@ -22,7 +22,7 @@ i18n
|
||||
.init({
|
||||
resources,
|
||||
fallbackLng: 'en', // Fallback to English if translation not found
|
||||
debug: false, // Set to true for debugging
|
||||
debug: false,
|
||||
interpolation: {
|
||||
escapeValue: false, // React already escapes values
|
||||
},
|
||||
|
||||
@@ -259,7 +259,16 @@
|
||||
"disabledDescription": "Intrusion Prevention System mit Community-Bedrohungsintelligenz",
|
||||
"processRunning": "Läuft (PID {{pid}})",
|
||||
"processStopped": "Prozess gestoppt",
|
||||
"toggleTooltip": "CrowdSec-Schutz umschalten"
|
||||
"toggleTooltip": "CrowdSec-Schutz umschalten",
|
||||
"copyFailed": "Kopieren des API-Schlüssels fehlgeschlagen",
|
||||
"keyWarning": {
|
||||
"title": "CrowdSec API-Schlüssel aktualisiert",
|
||||
"description": "Ihr konfigurierter API-Schlüssel wurde von CrowdSec LAPI abgelehnt. Ein neuer Schlüssel wurde automatisch generiert, um den Schutz wiederherzustellen.",
|
||||
"instructions": "Aktualisieren Sie Ihre docker-compose.yml mit dem neuen Schlüssel, um eine erneute Registrierung beim Container-Neustart zu verhindern:",
|
||||
"copyButton": "Kopieren",
|
||||
"copied": "Schlüssel in Zwischenablage kopiert",
|
||||
"restartNote": "Nach der Aktualisierung der docker-compose.yml starten Sie den Container neu, damit die Änderung wirksam wird."
|
||||
}
|
||||
},
|
||||
"acl": {
|
||||
"title": "Zugriffskontrolle",
|
||||
|
||||
@@ -277,7 +277,15 @@
|
||||
"notRegistered": "Not Registered",
|
||||
"sourceEnvVar": "From environment variable",
|
||||
"sourceFile": "From file",
|
||||
"keyStoredAt": "Key stored at"
|
||||
"keyStoredAt": "Key stored at",
|
||||
"keyWarning": {
|
||||
"title": "CrowdSec API Key Updated",
|
||||
"description": "Your configured API key was rejected by CrowdSec LAPI. A new key has been automatically generated to restore protection.",
|
||||
"instructions": "Update your docker-compose.yml with the new key to prevent re-registration on container restart:",
|
||||
"copyButton": "Copy",
|
||||
"copied": "Key copied to clipboard",
|
||||
"restartNote": "After updating docker-compose.yml, restart the container for the change to take effect."
|
||||
}
|
||||
},
|
||||
"acl": {
|
||||
"title": "Access Control",
|
||||
|
||||
@@ -259,7 +259,16 @@
|
||||
"disabledDescription": "Sistema de Prevención de Intrusiones impulsado por inteligencia de amenazas comunitaria",
|
||||
"processRunning": "Ejecutando (PID {{pid}})",
|
||||
"processStopped": "Proceso detenido",
|
||||
"toggleTooltip": "Alternar protección CrowdSec"
|
||||
"toggleTooltip": "Alternar protección CrowdSec",
|
||||
"copyFailed": "Error al copiar la clave API",
|
||||
"keyWarning": {
|
||||
"title": "Clave API de CrowdSec Actualizada",
|
||||
"description": "Su clave API configurada fue rechazada por CrowdSec LAPI. Se ha generado automáticamente una nueva clave para restaurar la protección.",
|
||||
"instructions": "Actualice su docker-compose.yml con la nueva clave para evitar el re-registro al reiniciar el contenedor:",
|
||||
"copyButton": "Copiar",
|
||||
"copied": "Clave copiada al portapapeles",
|
||||
"restartNote": "Después de actualizar docker-compose.yml, reinicie el contenedor para que el cambio surta efecto."
|
||||
}
|
||||
},
|
||||
"acl": {
|
||||
"title": "Control de Acceso",
|
||||
|
||||
@@ -259,7 +259,16 @@
|
||||
"disabledDescription": "Système de Prévention des Intrusions alimenté par le renseignement communautaire sur les menaces",
|
||||
"processRunning": "En cours d'exécution (PID {{pid}})",
|
||||
"processStopped": "Processus arrêté",
|
||||
"toggleTooltip": "Basculer la protection CrowdSec"
|
||||
"toggleTooltip": "Basculer la protection CrowdSec",
|
||||
"copyFailed": "Échec de la copie de la clé API",
|
||||
"keyWarning": {
|
||||
"title": "Clé API CrowdSec Mise à Jour",
|
||||
"description": "Votre clé API configurée a été rejetée par CrowdSec LAPI. Une nouvelle clé a été automatiquement générée pour restaurer la protection.",
|
||||
"instructions": "Mettez à jour votre docker-compose.yml avec la nouvelle clé pour éviter une ré-inscription au redémarrage du conteneur :",
|
||||
"copyButton": "Copier",
|
||||
"copied": "Clé copiée dans le presse-papiers",
|
||||
"restartNote": "Après avoir mis à jour docker-compose.yml, redémarrez le conteneur pour que le changement prenne effet."
|
||||
}
|
||||
},
|
||||
"acl": {
|
||||
"title": "Contrôle d'Accès",
|
||||
|
||||
@@ -259,7 +259,16 @@
|
||||
"disabledDescription": "由社区威胁情报驱动的入侵防御系统",
|
||||
"processRunning": "运行中 (PID {{pid}})",
|
||||
"processStopped": "进程已停止",
|
||||
"toggleTooltip": "切换 CrowdSec 保护"
|
||||
"toggleTooltip": "切换 CrowdSec 保护",
|
||||
"copyFailed": "复制API密钥失败",
|
||||
"keyWarning": {
|
||||
"title": "CrowdSec API密钥已更新",
|
||||
"description": "您配置的API密钥被CrowdSec LAPI拒绝。已自动生成新密钥以恢复保护。",
|
||||
"instructions": "使用新密钥更新您的docker-compose.yml,以防止容器重启时重新注册:",
|
||||
"copyButton": "复制",
|
||||
"copied": "密钥已复制到剪贴板",
|
||||
"restartNote": "更新docker-compose.yml后,重启容器使更改生效。"
|
||||
}
|
||||
},
|
||||
"acl": {
|
||||
"title": "访问控制",
|
||||
|
||||
@@ -4,7 +4,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import App from './App.tsx'
|
||||
import { ThemeProvider } from './context/ThemeContext'
|
||||
import { LanguageProvider } from './context/LanguageContext'
|
||||
import './i18n'
|
||||
import i18n from './i18n'
|
||||
import './index.css'
|
||||
|
||||
// Global query client with optimized defaults for performance
|
||||
@@ -20,14 +20,24 @@ const queryClient = new QueryClient({
|
||||
},
|
||||
})
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<LanguageProvider>
|
||||
<App />
|
||||
</LanguageProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
// Wait for i18next to be fully initialized before rendering
|
||||
// Prevents race condition where React renders before translations are loaded
|
||||
const renderApp = () => {
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<LanguageProvider>
|
||||
<App />
|
||||
</LanguageProvider>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
}
|
||||
|
||||
if (i18n.isInitialized) {
|
||||
renderApp()
|
||||
} else {
|
||||
i18n.on('initialized', renderApp)
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { toast } from '../utils/toast'
|
||||
import { ConfigReloadOverlay } from '../components/LoadingStates'
|
||||
import { LiveLogViewer } from '../components/LiveLogViewer'
|
||||
import { SecurityNotificationSettingsModal } from '../components/SecurityNotificationSettingsModal'
|
||||
import { CrowdSecKeyWarning } from '../components/CrowdSecKeyWarning'
|
||||
import { PageShell } from '../components/layout/PageShell'
|
||||
import {
|
||||
Card,
|
||||
@@ -352,6 +353,11 @@ export default function Security() {
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* CrowdSec Key Rejection Warning */}
|
||||
{status.cerberus?.enabled && (crowdsecStatus?.running ?? status.crowdsec.enabled) && (
|
||||
<CrowdSecKeyWarning />
|
||||
)}
|
||||
|
||||
{/* Admin Whitelist Section */}
|
||||
{status.cerberus?.enabled && (
|
||||
<Card>
|
||||
|
||||
Reference in New Issue
Block a user