Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(truenas): test edited saved connections canonically
rcourtman21de6abdcf86
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 0a52d35a53..aec2258279 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -466,7 +466,10 @@ instead of falling back to panel-local inference or agent-first setup guidance.Saved connection retests from that workspace must use the server-owned`POST /api/truenas/connections/{id}/test` path so operators can verify storedcredentials without leaking masked-secret placeholders back into the draft-connection form contract.+connection form contract. When the operator is editing a saved connection, that+same path must also accept the in-flight form payload and merge unchanged+masked secrets on the server, so edit-dialog tests do not force credential+re-entry just to validate changed host or TLS fields.When that same platform workspace reports TrueNAS as unavailable, the disabledstate must mean the server has explicitly opted out of the default-on TrueNASintegration, not that operators still need to enable a hidden feature gate fordiff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 378383f9aa..23393acc53 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -631,7 +631,10 @@ Draft validation must stay on `POST /api/truenas/connections/test`, whilere-testing one saved connection must route through`POST /api/truenas/connections/{id}/test` so the server reuses stored secretmaterial instead of forcing the frontend to round-trip redaction placeholders-back through the draft-test API.+back through the draft-test API. That saved-connection test route must also+accept the edit-form payload for an existing connection and merge unchanged+masked secrets server-side, so editing operators can test changed host / port /+TLS fields before saving without re-entering retained credentials.That same `/api/truenas/connections` list boundary now also owns theoperator-facing runtime summary for those configured connections. The listresponse must carry the canonical redacted config together with poll healthdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 95ac3c7bea..cf26f4f421 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -84,7 +84,7 @@ querying, and the operator-facing storage health presentation layer.18. Preserve the dedicated backend-owned `relay:mobile:access` capability and its governed backward-compatible route inventory plus the shared helper call sites around it, so storage- and recovery-adjacent transport surfaces do not treat the mobile relay credential as a general AI scope bundle.19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.-21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, saved-connection retest routes, or similar provider setup flows, storage and recovery may consume the resulting recovery points but must not absorb that connection-management ownership into storage/recovery-local handlers or page flows.+21. Keep provider-backed recovery onboarding on the adjacent platform-connections contract. When `internal/api/` grows or changes TrueNAS connection CRUD, masked-secret preservation, saved-connection retest routes, edit-form saved-test payload overlays, or similar provider setup flows, storage and recovery may consume the resulting recovery points but must not absorb that connection-management ownership into storage/recovery-local handlers or page flows.22. Keep backend-native platform actions on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app control for Assistant, storage and recovery may consume the refreshed recovery points afterward, but they must not grow a parallel recovery-local action transport or action-specific payload shape.23. Keep backend-native platform diagnostics on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app log reads for Assistant, storage and recovery may use those diagnostics during investigation, but they must not grow a parallel recovery-local log transport or diagnostic payload shape.24. Keep backend-native platform configuration reads on the adjacent AI/runtime and platform contracts. When `internal/api/` wires native TrueNAS app config for Assistant, storage and recovery may use that runtime shape during investigation, but they must not grow a parallel recovery-local config transport or provider-shaped configuration payload.@@ -1570,7 +1570,10 @@ adjacent platform-connections contract instead of being rebuilt asstorage/recovery-local connection flows. In particular, re-testing one savedTrueNAS recovery source must stay on the server-owned stored-config path ratherthan forcing storage or recovery surfaces to round-trip redacted secrets back-through the draft connection payload contract.+through the draft-test API; when edit-form payload overlays are present, that+same saved-connection path must merge unchanged secrets server-side instead of+making recovery-owned surfaces collect credentials again just to test updated+host or TLS fields before saving.That same provider-backed boundary also owns connection poll cadence, last-synchealth, failure summaries, and discovered platform-contribution counts exposedin the TrueNAS settings workspace. Storage and recovery may consume thediff --git a/frontend-modern/src/api/__tests__/truenas.test.ts b/frontend-modern/src/api/__tests__/truenas.test.tsindex 1a135eecf8..fa0b21f303 100644--- a/frontend-modern/src/api/__tests__/truenas.test.ts+++ b/frontend-modern/src/api/__tests__/truenas.test.ts@@ -121,7 +121,13 @@ describe('TrueNASAPI', () => {apiKey: 'secret',}),).resolves.toEqual({ success: true });- await expect(TrueNASAPI.testSavedConnection('conn/1')).resolves.toEqual({ success: true });+ await expect(+ TrueNASAPI.testSavedConnection('conn/1', {+ host: 'truenas.local',+ apiKey: '********',+ useHttps: true,+ }),+ ).resolves.toEqual({ success: true });expect(apiFetchJSON).toHaveBeenNthCalledWith(1,@@ -170,6 +176,11 @@ describe('TrueNASAPI', () => {'/api/truenas/connections/conn%2F1/test',expect.objectContaining({method: 'POST',+ body: JSON.stringify({+ host: 'truenas.local',+ apiKey: '********',+ useHttps: true,+ }),}),);});diff --git a/frontend-modern/src/api/truenas.ts b/frontend-modern/src/api/truenas.tsindex 34ec915b3a..be8d5e2304 100644--- a/frontend-modern/src/api/truenas.ts+++ b/frontend-modern/src/api/truenas.ts@@ -205,11 +205,15 @@ export class TrueNASAPI {};}- static async testSavedConnection(id: string): Promise<TrueNASConnectionTestResult> {+ static async testSavedConnection(+ id: string,+ input?: TrueNASConnectionInput,+ ): Promise<TrueNASConnectionTestResult> {const response = await apiFetchJSON<Partial<TrueNASConnectionTestResult>>(`${TRUE_NAS_CONNECTIONS_PATH}/${encodeURIComponent(id)}/test`,{method: 'POST',+ ...(input !== undefined ? { body: JSON.stringify(serializeTrueNASConnectionInput(input)) } : {}),},);return {diff --git a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsxindex 383de33814..980e9624ae 100644--- a/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx+++ b/frontend-modern/src/components/Settings/__tests__/useTrueNASSettingsPanelState.test.tsx@@ -135,4 +135,39 @@ describe('useTrueNASSettingsPanelState', () => {'TrueNAS connection successful for tower',);});++ it('tests edited saved connections through the canonical saved-connection API path', async () => {+ vi.mocked(TrueNASAPI.listConnections).mockResolvedValueOnce([+ {+ id: 'conn-1',+ name: 'tower',+ host: 'truenas.local',+ apiKey: '********',+ pollIntervalSeconds: 60,+ useHttps: true,+ insecureSkipVerify: false,+ enabled: true,+ },+ ] as never);+ vi.mocked(TrueNASAPI.testSavedConnection).mockResolvedValueOnce({ success: true } as never);++ const { result } = renderHook(() => useTrueNASSettingsPanelState());++ await waitFor(() => expect(result.connections()).toHaveLength(1));++ result.openEditDialog(result.connections()[0]);+ result.updateForm({ host: 'tower-edited.local', pollIntervalSeconds: '120' });+ await result.testCurrentForm();++ expect(TrueNASAPI.testSavedConnection).toHaveBeenCalledWith(+ 'conn-1',+ expect.objectContaining({+ host: 'tower-edited.local',+ apiKey: '********',+ pollIntervalSeconds: 120,+ }),+ );+ expect(TrueNASAPI.testConnection).not.toHaveBeenCalled();+ expect(notificationStore.success).toHaveBeenCalledWith('TrueNAS connection successful');+ });});diff --git a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.tsindex 18b29f6627..1569f8abe7 100644--- a/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts+++ b/frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts@@ -234,7 +234,12 @@ export function useTrueNASSettingsPanelState() {const testCurrentForm = async () => {setTesting(true);try {- await TrueNASAPI.testConnection(buildConnectionInput(form()));+ const payload = buildConnectionInput(form());+ if (editingConnectionId()) {+ await TrueNASAPI.testSavedConnection(editingConnectionId()!, payload);+ } else {+ await TrueNASAPI.testConnection(payload);+ }notificationStore.success('TrueNAS connection successful');return true;} catch (error) {diff --git a/internal/api/truenas_handlers.go b/internal/api/truenas_handlers.goindex 50033dfeec..df61c151cc 100644--- a/internal/api/truenas_handlers.go+++ b/internal/api/truenas_handlers.go@@ -1,8 +1,10 @@package apiimport (+ "bytes""context""encoding/json"+ "io""net/http""net/url""strings"@@ -57,12 +59,10 @@ func (h *TrueNASHandlers) HandleAdd(w http.ResponseWriter, r *http.Request) {}instance.ID = strings.TrimSpace(instance.ID)- instance.Name = strings.TrimSpace(instance.Name)- instance.Host = strings.TrimSpace(instance.Host)if instance.ID == "" {instance.ID = config.NewTrueNASInstance().ID}- instance.ApplyDefaults()+ normalizeTrueNASInstance(&instance)if err := instance.Validate(); err != nil {writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)@@ -214,13 +214,7 @@ func (h *TrueNASHandlers) HandleUpdate(w http.ResponseWriter, r *http.Request) {}instance.ID = connectionID- instance.Name = strings.TrimSpace(instance.Name)- instance.Host = strings.TrimSpace(instance.Host)- instance.APIKey = strings.TrimSpace(instance.APIKey)- instance.Username = strings.TrimSpace(instance.Username)- instance.Password = strings.TrimSpace(instance.Password)- instance.Fingerprint = strings.TrimSpace(instance.Fingerprint)- instance.ApplyDefaults()+ normalizeTrueNASInstance(&instance)persistence := h.persistenceForRequest(w, r.Context())if persistence == nil {@@ -275,12 +269,7 @@ func (h *TrueNASHandlers) HandleTestConnection(w http.ResponseWriter, r *http.Rereturn}- instance.Host = strings.TrimSpace(instance.Host)- instance.APIKey = strings.TrimSpace(instance.APIKey)- instance.Username = strings.TrimSpace(instance.Username)- instance.Password = strings.TrimSpace(instance.Password)- instance.Fingerprint = strings.TrimSpace(instance.Fingerprint)- instance.ApplyDefaults()+ normalizeTrueNASInstance(&instance)if err := instance.Validate(); err != nil {writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)return@@ -319,7 +308,19 @@ func (h *TrueNASHandlers) HandleTestSavedConnection(w http.ResponseWriter, r *htif strings.TrimSpace(instance.ID) != connectionID {continue}- instance.ApplyDefaults()+ normalizeTrueNASInstance(&instance)+ if payload, hasPayload, ok := decodeOptionalTrueNASInstanceRequest(w, r); !ok {+ return+ } else if hasPayload {+ payload.ID = connectionID+ normalizeTrueNASInstance(&payload)+ payload.PreserveMaskedSecrets(instance)+ if err := payload.Validate(); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "validation_error", err.Error(), nil)+ return+ }+ instance = payload+ }h.testConnectionInstance(w, r, instance)return}@@ -365,6 +366,44 @@ func (h *TrueNASHandlers) testConnectionInstance(writeJSON(w, http.StatusOK, map[string]any{"success": true})}+func normalizeTrueNASInstance(instance *config.TrueNASInstance) {+ if instance == nil {+ return+ }+ instance.Name = strings.TrimSpace(instance.Name)+ instance.Host = strings.TrimSpace(instance.Host)+ instance.APIKey = strings.TrimSpace(instance.APIKey)+ instance.Username = strings.TrimSpace(instance.Username)+ instance.Password = strings.TrimSpace(instance.Password)+ instance.Fingerprint = strings.TrimSpace(instance.Fingerprint)+ instance.ApplyDefaults()+}++func decodeOptionalTrueNASInstanceRequest(+ w http.ResponseWriter,+ r *http.Request,+) (config.TrueNASInstance, bool, bool) {+ r.Body = http.MaxBytesReader(w, r.Body, 32*1024)+ defer r.Body.Close()++ body, err := io.ReadAll(r.Body)+ if err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})+ return config.TrueNASInstance{}, false, false+ }+ if len(bytes.TrimSpace(body)) == 0 {+ return config.TrueNASInstance{}, false, true+ }++ var instance config.TrueNASInstance+ if err := json.Unmarshal(body, &instance); err != nil {+ writeErrorResponse(w, http.StatusBadRequest, "invalid_request", "Invalid request body", map[string]string{"error": err.Error()})+ return config.TrueNASInstance{}, false, false+ }++ return instance, true, true+}+func (h *TrueNASHandlers) featureEnabled(w http.ResponseWriter) bool {if truenas.IsFeatureEnabled() {return truediff --git a/internal/api/truenas_handlers_test.go b/internal/api/truenas_handlers_test.goindex 8bcc8957d2..e26564d921 100644--- a/internal/api/truenas_handlers_test.go+++ b/internal/api/truenas_handlers_test.go@@ -534,6 +534,69 @@ func TestTrueNASHandlers_HandleTestSavedConnection_UsesStoredSecrets(t *testing.}}+func TestTrueNASHandlers_HandleTestSavedConnection_MergesEditedPayloadWithStoredSecrets(t *testing.T) {+ setTrueNASFeatureForTest(t, true)++ handler, persistence, _ := newTrueNASHandlersForTest(t, nil)+ if err := persistence.SaveTrueNASConfig([]config.TrueNASInstance{+ {+ ID: "conn-1",+ Name: "tower",+ Host: "truenas.local",+ Port: 443,+ APIKey: "super-secret",+ UseHTTPS: true,+ InsecureSkipVerify: false,+ Fingerprint: "sha256:old",+ Enabled: true,+ PollIntervalSecs: 60,+ },+ }); err != nil {+ t.Fatalf("seed truenas config: %v", err)+ }++ var gotConfig truenas.ClientConfig+ handler.newClient = func(cfg truenas.ClientConfig) (trueNASClient, error) {+ gotConfig = cfg+ return &fakeTrueNASClient{}, nil+ }++ body := marshalTrueNASRequest(t, map[string]any{+ "name": "Tower Edited",+ "host": "tower-edited.local",+ "port": 8443,+ "apiKey": "********",+ "useHttps": true,+ "insecureSkipVerify": true,+ "fingerprint": "sha256:new",+ "enabled": true,+ "pollIntervalSeconds": 120,+ })+ req := httptest.NewRequest(+ http.MethodPost,+ "/api/truenas/connections/conn-1/test",+ bytes.NewReader(body),+ )+ rec := httptest.NewRecorder()+ handler.HandleTestSavedConnection(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }+ if gotConfig.Host != "tower-edited.local" {+ t.Fatalf("expected edited host, got %+v", gotConfig)+ }+ if gotConfig.Port != 8443 {+ t.Fatalf("expected edited port, got %+v", gotConfig)+ }+ if gotConfig.APIKey != "super-secret" {+ t.Fatalf("expected stored API key to be reused, got %+v", gotConfig)+ }+ if !gotConfig.InsecureSkipVerify || gotConfig.Fingerprint != "sha256:new" {+ t.Fatalf("expected edited TLS settings, got %+v", gotConfig)+ }+}+func newTrueNASHandlersForTest(t *testing.T, cfg *config.Config) (*TrueNASHandlers, *config.ConfigPersistence, *monitoring.Monitor) {t.Helper()diff --git a/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts b/tests/integration/tests/21-truenas-settings-platform-connections.spec.tsindex 84875897cb..998a09e1c8 100644--- a/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts+++ b/tests/integration/tests/21-truenas-settings-platform-connections.spec.ts@@ -195,15 +195,16 @@ test.describe('TrueNAS platform connections settings', () => {await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });});- test('adds, retests, and deletes TrueNAS connections through the canonical settings workflow', async ({+ test('adds, edits, retests, and deletes TrueNAS connections through the canonical settings workflow', async ({page,}) => {const syncedAt = new Date(Date.now() - 60_000).toISOString();let connections: Record<string, unknown>[] = [];let draftTestPayload: Record<string, unknown> | null = null;let createPayload: Record<string, unknown> | null = null;+ let updatePayload: Record<string, unknown> | null = null;let draftTestCalls = 0;- const savedTestPaths: string[] = [];+ const savedTestRequests: Array<{ path: string; payload: Record<string, unknown> | null }> = [];const deletePaths: string[] = [];await page.route('**/api/truenas/connections**', async (route) => {@@ -271,7 +272,10 @@ test.describe('TrueNAS platform connections settings', () => {}if (pathname === '/api/truenas/connections/conn-1/test' && method === 'POST') {- savedTestPaths.push(pathname);+ savedTestRequests.push({+ path: pathname,+ payload: request.postData() ? JSON.parse(request.postData() || '{}') : null,+ });await route.fulfill({status: 200,contentType: 'application/json',@@ -280,6 +284,45 @@ test.describe('TrueNAS platform connections settings', () => {return;}+ if (pathname === '/api/truenas/connections/conn-1' && method === 'PUT') {+ updatePayload = JSON.parse(request.postData() || '{}');+ connections = [+ {+ id: 'conn-1',+ name: updatePayload.name,+ host: updatePayload.host,+ port: updatePayload.port,+ apiKey: '********',+ useHttps: updatePayload.useHttps,+ insecureSkipVerify: updatePayload.insecureSkipVerify,+ fingerprint: updatePayload.fingerprint,+ enabled: updatePayload.enabled,+ pollIntervalSeconds: updatePayload.pollIntervalSeconds,+ poll: {+ intervalSeconds: updatePayload.pollIntervalSeconds,+ lastSuccessAt: syncedAt,+ },+ observed: {+ host: 'tower',+ resourceId: 'tower',+ collectedAt: syncedAt,+ systems: 1,+ storagePools: 2,+ datasets: 12,+ apps: 4,+ disks: 8,+ recoveryArtifacts: 18,+ },+ },+ ];+ await route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify(connections[0]),+ });+ return;+ }+if (pathname === '/api/truenas/connections/conn-1' && method === 'DELETE') {deletePaths.push(pathname);connections = [];@@ -344,8 +387,60 @@ test.describe('TrueNAS platform connections settings', () => {pollIntervalSeconds: 90,});+ await connectionCard.getByRole('button', { name: 'Edit' }).click();+ const editDialog = page.getByRole('dialog', { name: 'Edit TrueNAS connection' });+ await expect(editDialog).toBeVisible();+ await expect(+ editDialog.getByPlaceholder('Saved API key retained unless replaced'),+ ).toBeVisible();++ await editDialog.getByPlaceholder('tower').fill('Tower NAS Edited');+ await editDialog.getByPlaceholder('truenas.local').fill('tower-edited.local');+ await editDialog.getByPlaceholder('60').fill('120');++ await editDialog.getByRole('button', { name: 'Test connection' }).click();+ await expect+ .poll(() => savedTestRequests[0])+ .toMatchObject({+ path: '/api/truenas/connections/conn-1/test',+ payload: {+ name: 'Tower NAS Edited',+ host: 'tower-edited.local',+ port: 443,+ apiKey: '********',+ useHttps: true,+ enabled: true,+ pollIntervalSeconds: 120,+ },+ });+ await expect.poll(() => draftTestCalls).toBe(1);++ await editDialog.getByRole('button', { name: 'Save connection' }).click();+ await expect+ .poll(() => updatePayload)+ .toMatchObject({+ name: 'Tower NAS Edited',+ host: 'tower-edited.local',+ port: 443,+ apiKey: '********',+ useHttps: true,+ enabled: true,+ pollIntervalSeconds: 120,+ });+ await expect(connectionCard).toContainText('Tower NAS Edited');+await connectionCard.getByRole('button', { name: 'Test' }).click();- await expect.poll(() => savedTestPaths).toEqual(['/api/truenas/connections/conn-1/test']);+ await expect.poll(() => savedTestRequests).toEqual([+ expect.objectContaining({+ path: '/api/truenas/connections/conn-1/test',+ payload: expect.objectContaining({+ host: 'tower-edited.local',+ apiKey: '********',+ pollIntervalSeconds: 120,+ }),+ }),+ { path: '/api/truenas/connections/conn-1/test', payload: null },+ ]);await expect.poll(() => draftTestCalls).toBe(1);await connectionCard.getByRole('button', { name: 'Delete' }).click();