diff --git a/client/src/components/Admin/storage/AdminStoragePanel.test.tsx b/client/src/components/Admin/storage/AdminStoragePanel.test.tsx new file mode 100644 index 000000000..a12e024d9 --- /dev/null +++ b/client/src/components/Admin/storage/AdminStoragePanel.test.tsx @@ -0,0 +1,210 @@ +import { http, HttpResponse } from 'msw'; +import { beforeEach, describe, expect, it } from 'vitest'; +import { MASKED_SETTING_VALUE, type StorageAdminState, type StorageConfig } from '@trek/shared'; +import { server } from '../../../../tests/helpers/msw/server'; +import { fireEvent, render, screen, waitFor, within } from '../../../../tests/helpers/render'; +import { ToastContainer } from '../../shared/Toast'; +import AdminStoragePanel from './AdminStoragePanel'; + +const S3_MASKED = { + endpoint: 'http://127.0.0.1:9000', bucket: 'trek', accessKeyId: 'ak', + secretAccessKey: MASKED_SETTING_VALUE, region: 'us-east-1', keyPrefix: '', retries: 1, timeoutMs: 30000, +}; + +function baseState(overrides: Partial = {}): StorageAdminState { + return { + backends: [ + { name: 'uploads-local', type: 'local', source: 'built-in', options: { root: '/data/uploads' }, categories: ['files', 'journey', 'covers', 'avatars', 'photos', 'photos-google', 'photos-trek'] }, + { name: 'backups-local', type: 'local', source: 'built-in', options: { root: '/data/backups' }, categories: ['backups'] }, + { name: 'place-photos-local', type: 'local', source: 'env', options: { root: '/photos' }, categories: ['places'] }, + { name: 'off-box', type: 's3', source: 'settings', options: S3_MASKED, categories: ['covers'] }, + ], + categories: { + files: { backend: 'uploads-local', source: 'default' }, + journey: { backend: 'uploads-local', source: 'default' }, + covers: { backend: 'off-box', source: 'settings' }, + avatars: { backend: 'uploads-local', source: 'default' }, + places: { backend: 'place-photos-local', source: 'default' }, + photos: { backend: 'uploads-local', source: 'default' }, + 'photos-google': { backend: 'uploads-local', source: 'default' }, + 'photos-trek': { backend: 'uploads-local', source: 'default' }, + backups: { backend: 'backups-local', source: 'default' }, + }, + health: { replicaFailures: [] }, + encryptionReady: true, + seedFilePresent: false, + ...overrides, + }; +} + +function stubGet(state: StorageAdminState) { + server.use(http.get('/api/admin/storage', () => HttpResponse.json(state))); +} + +async function renderPanel(state: StorageAdminState = baseState()) { + stubGet(state); + render( + <> + + + , + ); + await waitFor(() => expect(screen.getByText('Backends')).toBeInTheDocument()); +} + +const backendRow = (name: string) => screen.getByTestId(`storage-backend-${name}`); +const categoryRow = (category: string) => screen.getByTestId(`storage-category-${category}`); + +describe('AdminStoragePanel', () => { + beforeEach(() => { + // Each test re-stubs GET; PUT/POST are stubbed where used. + }); + + it('FE-ADMIN-STOR-001: renders every backend with type badge, source tag and its categories', async () => { + await renderPanel(); + const uploads = backendRow('uploads-local'); + expect(within(uploads).getByText('Local')).toBeInTheDocument(); + expect(within(uploads).getByText('Built-in')).toBeInTheDocument(); + expect(within(uploads).getByText(/Used by: files/)).toBeInTheDocument(); + const env = backendRow('place-photos-local'); + expect(within(env).getByText('Environment')).toBeInTheDocument(); + expect(within(env).getByText(/read-only/)).toBeInTheDocument(); + expect(within(env).queryByRole('button', { name: 'Edit' })).not.toBeInTheDocument(); + expect(within(env).queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument(); + const offBox = backendRow('off-box'); + expect(within(offBox).getByText('S3')).toBeInTheDocument(); + expect(within(offBox).getByText('Settings')).toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-002: the mask echoes through edit → save untouched (no-op by contract)', async () => { + let putBody: unknown; + await renderPanel(); + server.use( + http.put('/api/admin/storage', async ({ request }) => { + putBody = await request.json(); + return HttpResponse.json(baseState()); + }), + ); + fireEvent.click(within(backendRow('off-box')).getByRole('button', { name: 'Edit' })); + expect(screen.getByLabelText(/Secret access key/)).toHaveValue(MASKED_SETTING_VALUE); + fireEvent.click(screen.getByRole('button', { name: 'Apply' })); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + await screen.findByText('Storage configuration saved'); + const body = putBody as StorageConfig; + const offBox = body.backends.find((b) => b.name === 'off-box')!; + expect((offBox.options as Record).secretAccessKey).toBe(MASKED_SETTING_VALUE); + }); + + it('FE-ADMIN-STOR-003: the PUT carries only the settings-owned document', async () => { + let putBody: unknown; + await renderPanel(); + server.use( + http.put('/api/admin/storage', async ({ request }) => { + putBody = await request.json(); + return HttpResponse.json(baseState()); + }), + ); + // Touch something to enable Save: reassign the files category. + fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)')); + const choices = screen.getAllByText('off-box'); + fireEvent.click(choices[choices.length - 1]!); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + await screen.findByText('Storage configuration saved'); + const body = putBody as StorageConfig; + expect(body.backends.map((b) => b.name)).toEqual(['off-box']); // built-ins/env never in the body + expect(body.categories).toEqual({ covers: 'off-box', files: 'off-box' }); + }); + + it('FE-ADMIN-STOR-004: reassigning a category shows the objects-do-not-move warning inline', async () => { + await renderPanel(); + expect(screen.queryByText(/Existing objects do not move/)).not.toBeInTheDocument(); + fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)')); + const choices = screen.getAllByText('off-box'); + fireEvent.click(choices[choices.length - 1]!); + expect(within(categoryRow('files')).getByText(/Existing objects do not move/)).toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-005: a 400 renders the server message verbatim next to Save', async () => { + await renderPanel(); + const registryError = + "backend 'off-box' has a plaintext secret 'secretAccessKey' but ENCRYPTION_KEY is not set — set ENCRYPTION_KEY explicitly to save credentialed storage backends (the implicit key persisted in the data directory is not accepted: it rides inside backups)"; + server.use(http.put('/api/admin/storage', () => HttpResponse.json({ error: registryError }, { status: 400 }))); + fireEvent.click(within(categoryRow('files')).getByText('uploads-local (default)')); + const choices = screen.getAllByText('off-box'); + fireEvent.click(choices[choices.length - 1]!); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + expect(await screen.findByText(registryError)).toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-006: Remove pre-checks assignments in the confirm dialog, then omits the backend from the PUT', async () => { + let putBody: unknown; + await renderPanel(); + server.use( + http.put('/api/admin/storage', async ({ request }) => { + putBody = await request.json(); + return HttpResponse.json(baseState()); + }), + ); + fireEvent.click(within(backendRow('off-box')).getByRole('button', { name: 'Remove' })); + expect(screen.getByText(/Still assigned to: covers/)).toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: 'Remove backend' })); + fireEvent.click(screen.getByRole('button', { name: 'Save changes' })); + await screen.findByText('Storage configuration saved'); + expect((putBody as StorageConfig).backends).toEqual([]); + }); + + it('FE-ADMIN-STOR-007: Test shows per-target results for a mirror', async () => { + const state = baseState(); + state.backends.push({ + name: 'backup-mirror', type: 'mirror', source: 'settings', + options: { primary: 'backups-local', replicas: ['off-box'] }, categories: [], + }); + await renderPanel(state); + server.use( + http.post('/api/admin/storage/test', () => + HttpResponse.json({ + ok: false, + targets: [ + { name: 'backups-local', ok: true }, + { name: 'off-box', ok: false, error: 'connect ECONNREFUSED' }, + ], + }), + ), + ); + fireEvent.click(within(backendRow('backup-mirror')).getByRole('button', { name: 'Test' })); + await within(backendRow('backup-mirror')).findByText('Test failed'); + expect(within(backendRow('backup-mirror')).getByText(/backups-local/)).toBeInTheDocument(); + expect(within(backendRow('backup-mirror')).getByText(/connect ECONNREFUSED/)).toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-008: the health strip lists replica failures with a relative age; all-clear otherwise', async () => { + const now = Date.now(); + await renderPanel( + baseState({ + health: { replicaFailures: [{ backend: 'off-box', key: 'backups/db.sqlite3', op: 'put', error: 'timeout', at: now - 120_000 }] }, + }), + ); + expect(screen.getByText(/put of backups\/db\.sqlite3 on off-box failed: timeout/)).toBeInTheDocument(); + expect(screen.getByText(/2 minutes ago/)).toBeInTheDocument(); + expect(screen.queryByText('No replica failures recorded.')).not.toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-009: all-clear health and the seed-file note', async () => { + await renderPanel(baseState({ seedFilePresent: true })); + expect(screen.getByText('No replica failures recorded.')).toBeInTheDocument(); + expect(screen.getByText(/seed file is present but ignored/)).toBeInTheDocument(); + }); + + it('FE-ADMIN-STOR-010: a managed-mode 403 on GET renders its body message gracefully', async () => { + server.use( + http.get('/api/admin/storage', () => + HttpResponse.json( + { error: 'This is configured by the operator of this instance.', code: 'MANAGED_FORBIDDEN' }, + { status: 403 }, + ), + ), + ); + render(); + expect(await screen.findByText('This is configured by the operator of this instance.')).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Admin/storage/AdminStoragePanel.tsx b/client/src/components/Admin/storage/AdminStoragePanel.tsx new file mode 100644 index 000000000..563058e3b --- /dev/null +++ b/client/src/components/Admin/storage/AdminStoragePanel.tsx @@ -0,0 +1,296 @@ +import React, { useState } from 'react' +import { Activity, FolderTree, HardDrive } from 'lucide-react' +import { STORAGE_CATEGORIES, type StorageBackend, type StorageCategory, type StorageTestResponse } from '@trek/shared' +import { useTranslation } from '../../../i18n' +import { relativeTime } from '../../../utils/relativeTime' +import ConfirmDialog from '../../shared/ConfirmDialog' +import CustomSelect from '../../shared/CustomSelect' +import { useToast } from '../../shared/Toast' +import Section from '../../Settings/Section' +import BackendForm from './BackendForm' +import { + asWireBackend, + categoriesPointingAt, + mirrorsReferencing, + removeBackend, + upsertBackend, + type StateBackend, +} from './storageModel' +import { useStorageAdmin } from './useStorageAdmin' + +interface Row { + name: string + type: StorageBackend['type'] + source: 'built-in' | 'env' | 'settings' + backend: StorageBackend + categories: readonly string[] +} + +function TestResult({ result, failedLabel, okLabel }: { + result: StorageTestResponse | undefined + failedLabel: string + okLabel: string +}): React.ReactElement | null { + if (result === undefined) return null + return ( +
+

{result.ok ? okLabel : failedLabel}

+ {result.targets.map((target) => ( +

+ {target.ok ? '✓' : '✗'} {target.name} + {target.error ? ` — ${target.error}` : ''} +

+ ))} +
+ ) +} + +export default function AdminStoragePanel(): React.ReactElement { + const { t, locale } = useTranslation() + const toast = useToast() + const admin = useStorageAdmin(t('common.error')) + const [editing, setEditing] = useState<{ initial: StorageBackend | null; originalName: string | null } | null>(null) + const [confirmRemove, setConfirmRemove] = useState(null) + + if (admin.loading) { + return

{t('storage.loading')}

+ } + if (!admin.state || !admin.draft) { + return ( +
+ {admin.loadError || t('common.error')} +
+ ) + } + const { state, draft } = admin + + const draftNames = draft.backends.map((b) => b.name) + const backendNames = [...new Set([...state.backends.map((b) => b.name), ...draftNames])] + + // The list shows the DRAFT world: built-ins/env from the state (unless a + // draft row overrides the name), settings rows from the draft (unsaved + // edits, additions and removals included). + const stateByName = new Map(state.backends.map((b) => [b.name, b])) + const rows: Row[] = [] + for (const b of state.backends) { + if (draftNames.includes(b.name)) continue // the draft copy renders below + if (b.source === 'settings') continue // removed from the draft, pending save + rows.push({ name: b.name, type: b.type, source: b.source, backend: asWireBackend(b), categories: b.categories }) + } + for (const b of draft.backends) { + const inState = stateByName.get(b.name) as StateBackend | undefined + rows.push({ + name: b.name, + type: b.type, + source: 'settings', + backend: b, + categories: inState?.categories ?? categoriesPointingAt(draft, b.name), + }) + } + + const startEdit = (row: Row) => { + // Editing a built-in creates a settings override row bearing its name — + // the first-class relocation path (merge-by-name). + setEditing({ initial: row.backend, originalName: row.name }) + } + + const commitBackend = (backend: StorageBackend) => { + const renamedFrom = + editing?.originalName && editing.originalName !== backend.name ? editing.originalName : null + const base = renamedFrom ? removeBackend(draft, renamedFrom) : draft + admin.setDraft(upsertBackend(base, backend)) + setEditing(null) + } + + const removeMessage = (name: string): string => { + const assigned = categoriesPointingAt(draft, name) + const mirrors = mirrorsReferencing(draft, name) + return [ + t('storage.remove.body', { name }), + assigned.length > 0 ? t('storage.remove.stillAssigned', { categories: assigned.join(', ') }) : '', + mirrors.length > 0 ? t('storage.remove.referencedBy', { backends: mirrors.join(', ') }) : '', + ] + .filter(Boolean) + .join(' ') + } + + const setCategory = (category: StorageCategory, backendName: string) => { + const effective = state.categories[category]! + // Exhaustive record: storageAdminStateSchema's `categories` maps all nine + // STORAGE_CATEGORIES entries (server-enforced), so this index is total. + const categories = { ...draft.categories } + if (effective.source === 'default' && backendName === effective.backend) { + delete categories[category] // back to the default → no longer settings-owned + } else { + categories[category] = backendName + } + admin.setDraft({ ...draft, categories }) + } + + const save = async () => { + if (await admin.save()) toast.success(t('storage.saved')) + } + + return ( +
+
+ {state.health.replicaFailures.length === 0 ? ( +

{t('storage.health.allClear')}

+ ) : ( +
    + {state.health.replicaFailures.map((failure) => ( +
  • + {t('storage.health.failureLine', { + op: failure.op, + key: failure.key, + backend: failure.backend, + error: failure.error, + })} + · {relativeTime(failure.at, locale)} +
  • + ))} +
+ )} + {state.seedFilePresent &&

{t('storage.health.seedFile')}

} +
+ +
+

{t('storage.description')}

+
+ {rows.map((row) => ( +
+
+ {row.name} + + {t(`storage.type.${row.type}`)} + + + {t(`storage.source.${row.source}`)} + + + + {row.source !== 'env' && ( + + )} + {row.source === 'settings' && ( + + )} +
+

+ {row.categories.length > 0 + ? t('storage.backends.usedBy', { categories: row.categories.join(', ') }) + : t('storage.backends.unused')} +

+ {row.source === 'env' &&

{t('storage.backends.envReadOnly')}

} + {admin.testResults[row.name] === 'running' ? ( +

{t('storage.test.running')}

+ ) : ( + + )} +
+ ))} +
+ + {editing ? ( + setEditing(null)} + /> + ) : ( + + )} +
+ +
+
+ {STORAGE_CATEGORIES.map((category) => { + const effective = state.categories[category]! + // Exhaustive record — see the setCategory comment above. + const selected = draft.categories[category] ?? effective.backend + const changed = selected !== effective.backend + return ( +
+ + setCategory(category, String(value))} + options={backendNames.map((name) => ({ + value: name, + label: + effective.source === 'default' && name === effective.backend + ? `${name} (${t('storage.categories.default')})` + : name, + }))} + size="sm" + style={{ maxWidth: 320 }} + /> + {changed && ( +

+ {t('storage.categories.reassignWarning')} +

+ )} +
+ ) + })} +
+
+ +
+ + {admin.dirty && {t('storage.unsaved')}} +
+ {admin.saveError && ( +

+ {admin.saveError} +

+ )} + + setConfirmRemove(null)} + onConfirm={() => { + if (confirmRemove) admin.setDraft(removeBackend(draft, confirmRemove)) + setConfirmRemove(null) + }} + title={t('storage.remove.title')} + message={confirmRemove ? removeMessage(confirmRemove) : ''} + confirmLabel={t('storage.remove.title')} + /> +
+ ) +} diff --git a/client/src/components/Admin/storage/useStorageAdmin.ts b/client/src/components/Admin/storage/useStorageAdmin.ts new file mode 100644 index 000000000..0fd5203c6 --- /dev/null +++ b/client/src/components/Admin/storage/useStorageAdmin.ts @@ -0,0 +1,104 @@ +import { useCallback, useEffect, useState } from 'react' +import type { StorageAdminState, StorageBackend, StorageConfig, StorageTestResponse } from '@trek/shared' +import { adminApi } from '../../../api/client' +import { getApiErrorMessage } from '../../../types' +import { settingsDocumentOf } from './storageModel' + +export type StorageTestResults = Record + +export interface StorageAdmin { + state: StorageAdminState | null + /** The settings-owned document (the PUT body), with local edits layered in. */ + draft: StorageConfig | null + dirty: boolean + loading: boolean + loadError: string | null + /** Server 400s land here VERBATIM — long registry messages outlive a toast. */ + saveError: string | null + saving: boolean + testResults: StorageTestResults + setDraft: (next: StorageConfig) => void + save: () => Promise + test: (backend: StorageBackend) => Promise +} + +/** + * Shared by the desktop and phone storage panels (DefaultUserSettingsTab + * model: self-contained, adminApi directly, deliberately no offline core — + * hoster-level config is online-only). + */ +export function useStorageAdmin(genericError: string): StorageAdmin { + const [state, setState] = useState(null) + const [draft, setDraftState] = useState(null) + const [dirty, setDirty] = useState(false) + const [loading, setLoading] = useState(true) + const [loadError, setLoadError] = useState(null) + const [saveError, setSaveError] = useState(null) + const [saving, setSaving] = useState(false) + const [testResults, setTestResults] = useState({}) + + const applyState = useCallback((next: StorageAdminState) => { + setState(next) + setDraftState(settingsDocumentOf(next)) + setDirty(false) + setSaveError(null) + }, []) + + useEffect(() => { + let cancelled = false + adminApi + .getStorage() + .then((data) => { + if (!cancelled) applyState(data) + }) + .catch((err: unknown) => { + if (!cancelled) setLoadError(getApiErrorMessage(err, genericError)) + }) + .finally(() => { + if (!cancelled) setLoading(false) + }) + return () => { + cancelled = true + } + }, [applyState, genericError]) + + const setDraft = useCallback((next: StorageConfig) => { + setDraftState(next) + setDirty(true) + }, []) + + const save = useCallback(async (): Promise => { + if (!draft) return false + setSaving(true) + setSaveError(null) + try { + // The response is the fresh effective world, never the request echo. + applyState(await adminApi.updateStorage(draft)) + return true + } catch (err: unknown) { + setSaveError(getApiErrorMessage(err, genericError)) + return false + } finally { + setSaving(false) + } + }, [draft, applyState, genericError]) + + const test = useCallback( + async (backend: StorageBackend): Promise => { + setTestResults((prev) => ({ ...prev, [backend.name]: 'running' })) + try { + const result = await adminApi.testStorageBackend(backend) + setTestResults((prev) => ({ ...prev, [backend.name]: result })) + } catch (err: unknown) { + const error = getApiErrorMessage(err, genericError) + setTestResults((prev) => ({ + ...prev, + [backend.name]: { ok: false, targets: [{ name: backend.name, ok: false, error }] }, + })) + } + }, + [genericError], + ) + + return { state, draft, dirty, loading, loadError, saveError, saving, testResults, setDraft, save, test } +}