feat(backup): Off-Site-Upload nach S3 + SFTP

Schutz gegen Box-Total-Loss — lokale Backups in /var/backups/edgeguard
helfen nicht, wenn die Disk stirbt oder die Box brennt. Nach jedem
erfolgreichen lokalen Backup wird die tar.gz an alle aktiven
Off-Site-Ziele hochgeladen.

Migration 0022: backup_remotes (kind=s3|sftp, target_url, settings
JSONB, active, last_upload_at, last_error) + backups.remote_uploads
JSONB (per-Target-Result).

internal/services/backup/remote/:
  - UploadAll() — pro aktivem Target ein Upload, Failures non-fatal
  - S3 via minio-go/v7 — funktioniert mit AWS, MinIO, Backblaze B2,
    Cloudflare R2, Hetzner Object Storage (alle S3-API-kompatibel)
  - SFTP via golang.org/x/crypto/ssh + pkg/sftp. Password + Private-
    Key (OpenSSH, base64-encoded) als Auth. Optional host_key_
    fingerprint-Pinning (SHA256:...); leer = TOFU (unsicher vs MitM,
    OK für initial setup).
  - Test() lädt eine 1KB-Probe + löscht sie wieder — Operator-UI hat
    einen „Verbindung testen"-Button.

backup.Service.RemoteUploader-Interface: nach erfolgreichem
recordSuccess() läuft UploadAll, Results landen in backups.remote_
uploads JSONB. last_upload_at/last_error in backup_remotes pro Target
gepflegt. API + Scheduler injizieren beide den Adapter.

internal/handlers/backup_remotes.go: CRUD + POST /:id/test. Sensitive
Felder (secret_key, password, private_key) werden in GET-Responses
durch ***SET*** maskiert; UpdateChannel merged das zurück damit der
Operator bei Edit ohne Re-Eingabe speichern kann.

UI: Backups-Page jetzt mit Tabs "Sicherungen" + "Off-Site-Ziele".
Tab 2 hat CRUD-Tabelle mit kind-konditionalem Form (S3-Felder oder
SFTP-Felder), Test-Button pro Row, last_upload-Status mit FAIL-Tag
bei Errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Debian
2026-05-13 18:49:02 +02:00
parent 81a8217493
commit 27ac7b53fc
16 changed files with 1520 additions and 329 deletions

View File

@@ -0,0 +1,332 @@
import { useEffect, useRef, useState } from 'react'
import {
Alert, Button, Card, Popconfirm, Space, Table, Tag, Tooltip, Typography, message,
} from 'antd'
import type { ColumnsType } from 'antd/es/table'
import {
CloudDownloadOutlined,
CloudUploadOutlined,
DeleteOutlined,
ReloadOutlined,
RocketOutlined,
UndoOutlined,
} from '@ant-design/icons'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import dayjs from 'dayjs'
import apiClient, { isEnvelope } from '../../api/client'
const { Text } = Typography
interface Backup {
id: number
file: string
size_bytes: number
sha256: string
db_dump_bytes: number
files_bytes: number
kind: 'manual' | 'scheduled'
status: 'success' | 'failed'
error?: string
host?: string
started_at: string
finished_at: string
}
function fmtSize(n: number): string {
if (n < 1024) return n + ' B'
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'
if (n < 1024 * 1024 * 1024) return (n / 1024 / 1024).toFixed(1) + ' MB'
return (n / 1024 / 1024 / 1024).toFixed(2) + ' GB'
}
function fmtDuration(start: string, end: string): string {
const ms = new Date(end).getTime() - new Date(start).getTime()
if (ms < 1000) return ms + ' ms'
if (ms < 60_000) return (ms / 1000).toFixed(1) + ' s'
return (ms / 60_000).toFixed(1) + ' min'
}
export default function HistoryTab() {
const { t } = useTranslation()
const qc = useQueryClient()
const [msg, msgCtx] = message.useMessage()
const list = useQuery({
queryKey: ['backups'],
queryFn: async () => {
const r = await apiClient.get('/backups')
return isEnvelope(r.data) ? (r.data.data as { backups: Backup[] }).backups : []
},
refetchInterval: 30_000,
})
const trigger = useMutation({
mutationFn: async () => {
const r = await apiClient.post('/backups')
return isEnvelope(r.data) ? r.data.data : r.data
},
onSuccess: (res: { file?: string }) => {
msg.success(t('backups.created', { file: res?.file ?? '?' }))
qc.invalidateQueries({ queryKey: ['backups'] })
},
onError: (e: Error) => msg.error(t('backups.failed') + ': ' + e.message),
})
const [busyDelete, setBusyDelete] = useState<number | null>(null)
const del = useMutation({
mutationFn: async (id: number) => {
setBusyDelete(id)
try { await apiClient.delete(`/backups/${id}`) } finally { setBusyDelete(null) }
},
onSuccess: () => {
msg.success(t('backups.deleted'))
qc.invalidateQueries({ queryKey: ['backups'] })
},
onError: (e: Error) => msg.error(e.message),
})
// Restore-Modal-State: nach Klick aufs Restore zeigen wir ein
// Vollbild-Overlay mit Step-Indicator + Health-Poll (analog Update).
const [restoring, setRestoring] = useState<{ file: string } | null>(null)
const [restoreElapsed, setRestoreElapsed] = useState(0)
const tickRef = useRef<ReturnType<typeof setInterval> | null>(null)
const pollRef = useRef<ReturnType<typeof setInterval> | null>(null)
useEffect(() => () => {
if (tickRef.current) clearInterval(tickRef.current)
if (pollRef.current) clearInterval(pollRef.current)
}, [])
const restore = useMutation({
mutationFn: async (id: number) => {
const r = await apiClient.post(`/backups/${id}/restore`)
return isEnvelope(r.data) ? r.data.data : r.data
},
onError: (e: Error) => {
setRestoring(null)
if (tickRef.current) clearInterval(tickRef.current)
msg.error(t('backups.restoreFailed') + ': ' + e.message)
},
})
const startRestore = (b: Backup) => {
setRestoring({ file: b.file })
setRestoreElapsed(0)
tickRef.current = setInterval(() => setRestoreElapsed((e) => e + 1), 1000)
restore.mutate(b.id, {
onSuccess: () => {
// Poll /system/health bis API neu hochkommt → reload.
let sawDown = false
pollRef.current = setInterval(async () => {
try {
const res = await apiClient.get('/system/health')
const v = isEnvelope(res.data) ? (res.data.data as { version: string }).version : ''
if (sawDown && v) {
if (pollRef.current) clearInterval(pollRef.current)
if (tickRef.current) clearInterval(tickRef.current)
setRestoring(null)
msg.success(t('backups.restoreDone'))
setTimeout(() => window.location.reload(), 1500)
}
} catch {
sawDown = true
}
}, 3000)
// Safety-Timeout 3 min — Restore kann bei großer DB länger
// dauern als Upgrade. Danach reload trotzdem.
setTimeout(() => {
if (pollRef.current) clearInterval(pollRef.current)
if (tickRef.current) clearInterval(tickRef.current)
setRestoring(null)
window.location.reload()
}, 180_000)
},
})
}
const download = (b: Backup) => {
// gin.FileAttachment liefert via Browser direkt; einfach
// Cookie-authentifiziert in eine versteckte Form öffnen.
const url = `/api/v1/backups/${b.id}/download`
const a = document.createElement('a')
a.href = url
a.download = b.file
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}
const columns: ColumnsType<Backup> = [
{
title: t('backups.col.time'), dataIndex: 'started_at', width: 170,
render: (v: string) => <Text style={{ fontFamily: 'monospace', fontSize: 12 }}>
{dayjs(v).format('YYYY-MM-DD HH:mm:ss')}
</Text>,
},
{
title: t('backups.col.file'), dataIndex: 'file',
render: (v: string, row) => (
<div>
<Text style={{ fontFamily: 'monospace' }}>{v}</Text>
<div>
<Text type="secondary" style={{ fontSize: 11 }}>
sha256: {row.sha256.slice(0, 16)}
</Text>
</div>
</div>
),
},
{
title: t('backups.col.kind'), dataIndex: 'kind', width: 110,
render: (k: Backup['kind']) =>
<Tag color={k === 'scheduled' ? 'cyan' : 'blue'}>{k}</Tag>,
},
{
title: t('backups.col.status'), dataIndex: 'status', width: 110,
render: (s: Backup['status'], row) =>
s === 'success'
? <Tag color="green">OK</Tag>
: (
<Tooltip title={row.error}>
<Tag color="red">{t('backups.failedTag')}</Tag>
</Tooltip>
),
},
{
title: t('backups.col.size'), dataIndex: 'size_bytes', width: 110,
render: (n: number, row) => (
<div>
<Text>{fmtSize(n)}</Text>
<div>
<Text type="secondary" style={{ fontSize: 11 }}>
DB {fmtSize(row.db_dump_bytes)} · Files {fmtSize(row.files_bytes)}
</Text>
</div>
</div>
),
},
{
title: t('backups.col.duration'), key: 'duration', width: 90,
render: (_, row) => <Text type="secondary">{fmtDuration(row.started_at, row.finished_at)}</Text>,
},
{
title: t('common.actions'), key: 'a', width: 280,
render: (_, row) => (
<Space size={4}>
<Tooltip title={t('backups.downloadTooltip')}>
<Button
size="small"
icon={<CloudDownloadOutlined />}
onClick={() => download(row)}
disabled={row.status !== 'success'}
>{t('backups.download')}</Button>
</Tooltip>
<Popconfirm
title={t('backups.confirmRestoreTitle')}
description={t('backups.confirmRestoreDesc', { file: row.file })}
okText={t('backups.restoreOk')}
okButtonProps={{ danger: true }}
cancelText={t('common.cancel')}
onConfirm={() => startRestore(row)}
disabled={row.status !== 'success'}
>
<Button
size="small"
icon={<UndoOutlined />}
disabled={row.status !== 'success'}
>{t('backups.restore')}</Button>
</Popconfirm>
<Popconfirm
title={t('backups.confirmDelete', { file: row.file })}
onConfirm={() => del.mutate(row.id)}
okButtonProps={{ danger: true }}
>
<Button size="small" danger icon={<DeleteOutlined />} loading={busyDelete === row.id}>
{t('common.delete')}
</Button>
</Popconfirm>
</Space>
),
},
]
return (
<div>
{msgCtx}
<Space style={{ marginBottom: 12 }}>
<Tooltip title={t('backups.refreshTooltip')}>
<Button icon={<ReloadOutlined />} onClick={() => list.refetch()}>
{t('common.refresh')}
</Button>
</Tooltip>
<Button
type="primary"
icon={<CloudUploadOutlined />}
loading={trigger.isPending}
onClick={() => trigger.mutate()}
>
{t('backups.runNow')}
</Button>
</Space>
<Card className="mb-16">
<Alert
type="info"
showIcon
message={t('backups.scopeTitle')}
description={t('backups.scopeDesc')}
/>
</Card>
<Table
rowKey="id"
size="small"
loading={list.isFetching}
dataSource={list.data ?? []}
columns={columns}
pagination={{ pageSize: 25, showSizeChanger: true, pageSizeOptions: [25, 50, 100] }}
locale={{ emptyText: t('backups.empty') }}
/>
{restoring && (
<div className="update-modal-overlay">
<div className="update-modal">
<div className="update-modal__orbit">
<div className="update-modal__ring" />
<div className="update-modal__ring update-modal__ring--2" />
<div className="update-modal__dot" />
<div className="update-modal__dot update-modal__dot--2" />
<div className="update-modal__center">
<RocketOutlined className="update-modal__icon" />
</div>
</div>
<div className="update-modal__title">{t('backups.restoreRunning')}</div>
<div className="update-modal__version">{restoring.file}</div>
<div className="update-modal__steps">
<div className={`update-modal__step ${restoreElapsed < 5 ? 'update-modal__step--active' : 'update-modal__step--done'}`}>
<span className="update-modal__step-dot" />
<span>{t('backups.step.extract')}</span>
</div>
<div className={`update-modal__step ${restoreElapsed >= 5 && restoreElapsed < 15 ? 'update-modal__step--active' : restoreElapsed >= 15 ? 'update-modal__step--done' : ''}`}>
<span className="update-modal__step-dot" />
<span>{t('backups.step.psql')}</span>
</div>
<div className={`update-modal__step ${restoreElapsed >= 15 && restoreElapsed < 25 ? 'update-modal__step--active' : restoreElapsed >= 25 ? 'update-modal__step--done' : ''}`}>
<span className="update-modal__step-dot" />
<span>{t('backups.step.render')}</span>
</div>
<div className={`update-modal__step ${restoreElapsed >= 25 ? 'update-modal__step--active' : ''}`}>
<span className="update-modal__step-dot" />
<span>{t('backups.step.restart')}</span>
</div>
</div>
<div className="update-modal__timer">{restoreElapsed}s</div>
<div className="update-modal__hint">{t('backups.restoreHint')}</div>
</div>
</div>
)}
</div>
)
}