Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

78.6 KB
Raw Blame
package truenas

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
	"time"

	"github.com/gorilla/websocket"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
)

// Subscription terminal-message regressions for #2396. The envelope is from
// the reporter's source-derived 25.04.2.6 example, not a retained wire capture.
func TestJSONRPCSubscriptionTerminationRejectsWithoutWaitingOrRetry(t *testing.T) {
	for _, stream := range []string{"app.stats", "reporting.realtime", "app.container_log_follow"} {
		for _, beforeReply := range []bool{false, true} {
			t.Run(fmt.Sprintf("%s/before_reply=%t", stream, beforeReply), func(t *testing.T) {
				var subscribes, unsubscribes atomic.Int32
				fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
					switch request.Method {
					case "auth.login_ex":
						return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
					case "reporting.get_data":
						return protocolFixtureReply{result: []any{}}
					case "core.subscribe":
						subscribes.Add(1)
						collection := request.Params.([]any)[0].(string)
						return protocolFixtureReply{result: "private-sub-id", beforeReply: beforeReply, notifications: []protocolFixtureNotification{{
							method: "notify_unsubscribed", params: map[string]any{"collection": collection, "error": map[string]any{
								"error": 14, "errname": "EFAULT", "reason": "private-app-name fixture-key fixture-user https://private.invalid",
								"trace": "private-trace", "extra": "private-extra",
							}},
						}}}
					case "core.unsubscribe":
						unsubscribes.Add(1)
						return protocolFixtureReply{result: nil}
					case "pool.query":
						return protocolFixtureReply{result: []any{}}
					default:
						t.Errorf("unexpected method %s", request.Method)
						return protocolFixtureReply{close: true}
					}
				}, nil)
				client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 2 * time.Second})
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()
				started := time.Now()
				var err error
				switch stream {
				case "app.stats":
					var stats map[string]AppStats
					stats, err = client.GetAppStats(ctx)
					if stats != nil {
						t.Error("rejected stats fabricated a sample")
					}
				case "reporting.realtime":
					var telemetry *SystemInfo
					telemetry, err = client.GetSystemTelemetry(ctx)
					if telemetry != nil {
						t.Error("rejected telemetry fabricated a sample")
					}
				default:
					var lines []AppLogLine
					lines, err = client.GetAppLogs(ctx, "private-app-name", "private-container", 100)
					if lines != nil {
						t.Error("rejected logs appeared successful")
					}
				}
				var rpcErr *RPCError
				if !errors.As(err, &rpcErr) || rpcErr.Code != 14 || rpcErr.Message != "subscription rejected" {
					t.Fatalf("termination = %v, want structured errno=14 rejection", err)
				}
				if elapsed := time.Since(started); elapsed >= time.Second {
					t.Fatalf("terminal event waited for the operation budget: %s", elapsed)
				}
				for _, private := range []string{"private-app-name", "fixture-key", "fixture-user", "private.invalid", "private-trace", "private-extra", "private-sub-id", "private-container"} {
					if strings.Contains(err.Error(), private) || strings.Contains(client.TransportStatus().LastError, private) {
						t.Fatalf("termination exposed %s", private)
					}
				}
				if client.rpc != nil || client.TransportStatus().Connected || subscribes.Load() != 1 || unsubscribes.Load() != 0 || fixture.sessions.Load() != 1 {
					t.Fatal("terminal rejection retried, reused the stream or tried to cancel its ended subscription")
				}
				if _, err := client.GetPools(ctx); err != nil || fixture.sessions.Load() != 2 || fixture.restRequests.Load() != 0 {
					t.Fatalf("next read did not recover on a fresh RPC session: %v", err)
				}
			})
		}
	}
}

func TestJSONRPCSubscriptionTerminationIgnoresOtherCollections(t *testing.T) {
	var unsubscribes atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		case "core.subscribe":
			collection := request.Params.([]any)[0].(string)
			return protocolFixtureReply{result: "stats-sub", notifications: []protocolFixtureNotification{
				{method: "notify_unsubscribed", params: map[string]any{"collection": "app.stats:{\"interval\":99}", "error": map[string]any{"error": 14}}},
				{method: "notify_unsubscribed", params: map[string]any{"collection": "app.stats.extra:{\"interval\":2}", "error": "malformed-unrelated-error"}},
				{method: "notify_unsubscribed", params: map[string]any{"collection": "reporting.realtime:{\"interval\":2}", "error": nil}},
				{method: "collection_update", params: map[string]any{"collection": collection, "fields": []any{map[string]any{"app_name": "fixture-app", "cpu_usage": 7}}}},
			}}
		case "core.unsubscribe":
			unsubscribes.Add(1)
			return protocolFixtureReply{result: nil}
		default:
			return protocolFixtureReply{result: []any{}}
		}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
	for poll := 0; poll < 2; poll++ {
		stats, err := client.GetAppStats(context.Background())
		if err != nil || stats["fixture-app"].CPUPercent != 7 {
			t.Fatalf("unrelated terminal event interrupted stats: %v, %+v", err, stats)
		}
	}
	if fixture.sessions.Load() != 1 || unsubscribes.Load() != 2 || !client.TransportStatus().Connected {
		t.Fatal("unrelated event prevented ordinary cleanup and session reuse")
	}
}

func TestJSONRPCSubscriptionCleanTerminationDoesNotInventStats(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if request.Method == "core.subscribe" {
			return protocolFixtureReply{result: "stats-sub", notifications: []protocolFixtureNotification{{method: "notify_unsubscribed", params: map[string]any{"collection": request.Params.([]any)[0], "error": nil}}}}
		}
		return protocolFixtureReply{result: []any{}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 2 * time.Second})
	stats, err := client.GetAppStats(context.Background())
	var rpcErr *RPCError
	if stats != nil || !errors.As(err, &rpcErr) || rpcErr.Message != "subscription ended before a sample" || client.TransportStatus().Connected {
		t.Fatalf("clean termination appeared sampled or left an unresolved stream: %v, %+v", err, stats)
	}
}

func TestJSONRPCSubscriptionCleanLogEndKeepsSession(t *testing.T) {
	var unsubscribes atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if request.Method == "core.subscribe" {
			collection := request.Params.([]any)[0]
			return protocolFixtureReply{result: "log-sub", notifications: []protocolFixtureNotification{
				{method: "collection_update", params: map[string]any{"collection": collection, "fields": []any{map[string]any{"data": "fixture-line"}}}},
				{method: "notify_unsubscribed", params: map[string]any{"collection": "app.container_log_follow:{}", "error": map[string]any{"error": 14}}},
				{method: "notify_unsubscribed", params: map[string]any{"collection": collection, "error": nil}},
			}}
		}
		if request.Method == "core.unsubscribe" {
			unsubscribes.Add(1)
		}
		return protocolFixtureReply{result: []any{}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
	lines, err := client.GetAppLogs(context.Background(), "fixture-app", "fixture-container", 100)
	if err != nil || len(lines) != 1 || lines[0].Data != "fixture-line" {
		t.Fatalf("clean log end lost the bounded tail: %v, %+v", err, lines)
	}
	if _, err := client.GetPools(context.Background()); err != nil || fixture.sessions.Load() != 1 || unsubscribes.Load() != 0 || !client.TransportStatus().Connected {
		t.Fatalf("clean log end discarded or unsubscribed an already-ended stream: %v", err)
	}
}

func TestJSONRPCSubscriptionMalformedTerminalDiscardsWithoutWireText(t *testing.T) {
	for _, terminal := range []any{map[string]any{"error": "private-invalid-errno", "reason": "private-error"}, "private-error", true} {
		t.Run(fmt.Sprintf("%T", terminal), func(t *testing.T) {
			fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
				if request.Method == "auth.login_ex" {
					return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
				}
				if request.Method == "core.subscribe" {
					return protocolFixtureReply{result: "stats-sub", notifications: []protocolFixtureNotification{{method: "notify_unsubscribed", params: map[string]any{"collection": request.Params.([]any)[0], "error": terminal}}}}
				}
				return protocolFixtureReply{result: []any{}}
			}, nil)
			client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 2 * time.Second})
			_, err := client.GetAppStats(context.Background())
			if err == nil || strings.Contains(err.Error(), "private-") || !strings.Contains(err.Error(), "invalid truenas app.stats termination error") || client.rpc != nil || fixture.sessions.Load() != 1 {
				t.Fatalf("malformed termination was lost, leaked or reused: %v", err)
			}
		})
	}
}

type protocolFixtureReply struct {
	result        any
	err           *trueNASRPCError
	notifications []protocolFixtureNotification
	beforeReply   bool
	close         bool
}

type protocolFixtureNotification struct {
	method string
	params any
}

type protocolFixture struct {
	server       *httptest.Server
	sessions     atomic.Int32
	restRequests atomic.Int32
}

func newProtocolFixture(
	t *testing.T,
	handle func(session int, request trueNASRPCRequest) protocolFixtureReply,
	handleREST http.HandlerFunc,
) *protocolFixture {
	t.Helper()

	fixture := &protocolFixture{}
	upgrader := websocket.Upgrader{}
	fixture.server = httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		if request.URL.Path != "/api/current" || !websocket.IsWebSocketUpgrade(request) {
			fixture.restRequests.Add(1)
			if handleREST == nil {
				http.NotFound(writer, request)
				return
			}
			handleREST(writer, request)
			return
		}

		conn, err := upgrader.Upgrade(writer, request, nil)
		if err != nil {
			t.Errorf("upgrade protocol fixture websocket: %v", err)
			return
		}
		defer func() { _ = conn.Close() }()
		session := int(fixture.sessions.Add(1))

		for {
			var rpcRequest trueNASRPCRequest
			if err := conn.ReadJSON(&rpcRequest); err != nil {
				return
			}
			reply := handle(session, rpcRequest)
			if reply.close {
				return
			}
			response := trueNASRPCResponse{
				JSONRPC: "2.0",
				ID:      rpcRequest.ID,
				Error:   reply.err,
			}
			if reply.err == nil {
				raw, err := json.Marshal(reply.result)
				if err != nil {
					t.Errorf("marshal protocol fixture result: %v", err)
					return
				}
				response.Result = raw
			}
			if !reply.beforeReply {
				if err := conn.WriteJSON(response); err != nil {
					return
				}
			}
			for _, notification := range reply.notifications {
				params, err := json.Marshal(notification.params)
				if err != nil {
					t.Errorf("marshal protocol fixture notification: %v", err)
					return
				}
				if err := conn.WriteJSON(trueNASRPCResponse{
					JSONRPC: "2.0",
					Method:  notification.method,
					Params:  params,
				}); err != nil {
					return
				}
			}
			if reply.beforeReply {
				if err := conn.WriteJSON(response); err != nil {
					return
				}
			}
		}
	}))
	t.Cleanup(fixture.server.Close)
	return fixture
}

func protocolFixtureClient(t *testing.T, serverURL string, config ClientConfig) *Client {
	t.Helper()
	config.InsecureSkipVerify = true
	client := mustClientForServer(t, serverURL, config)
	t.Cleanup(client.Close)
	return client
}

func TestJSONRPCTransportUsesLoginExForReadonlyAPIKey(t *testing.T) {
	var sawLogin atomic.Bool
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			params, ok := request.Params.([]any)
			if !ok || len(params) != 1 {
				t.Errorf("auth.login_ex params = %#v", request.Params)
				return protocolFixtureReply{close: true}
			}
			login, ok := params[0].(map[string]any)
			if !ok {
				t.Errorf("auth.login_ex login payload = %#v", params[0])
				return protocolFixtureReply{close: true}
			}
			if login["mechanism"] != "API_KEY_PLAIN" || login["username"] != "pulse-readonly" || login["api_key"] != "readonly-key" {
				t.Errorf("auth.login_ex login payload = %#v", login)
			}
			sawLogin.Store(true)
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		case "system.info":
			return protocolFixtureReply{result: map[string]any{
				"hostname":       "nas-readonly",
				"version":        "TrueNAS-SCALE-25.10.4",
				"system_serial":  "READONLY-1",
				"uptime_seconds": 42,
				"physical_cores": 8,
				"physmem":        16 * 1024 * 1024 * 1024,
			}}
		default:
			t.Errorf("unexpected rpc method %q", request.Method)
			return protocolFixtureReply{close: true}
		}
	}, nil)

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{
		APIKey:   "readonly-key",
		Username: "pulse-readonly",
	})
	system, err := client.GetSystemInfo(context.Background())
	if err != nil {
		t.Fatalf("GetSystemInfo() error = %v", err)
	}
	if !sawLogin.Load() || system.Hostname != "nas-readonly" || system.Version != "TrueNAS-SCALE-25.10.4" {
		t.Fatalf("unexpected readonly system result: %+v", system)
	}
	if fixture.restRequests.Load() != 0 {
		t.Fatalf("modern JSON-RPC session made %d REST requests", fixture.restRequests.Load())
	}
	status := client.TransportStatus()
	if status.Mode != TransportJSONRPC || !status.Connected || status.AuthMechanism != "api-key-plain" || !status.TLS {
		t.Fatalf("unexpected transport status: %+v", status)
	}
}

func TestJSONRPCLegacyAPIKeyLoginRemovalRequestsOwnerUsername(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method != "auth.login_with_api_key" {
			t.Errorf("unexpected rpc method %q", request.Method)
			return protocolFixtureReply{close: true}
		}
		return protocolFixtureReply{err: &trueNASRPCError{
			Code:    -32601,
			Message: "Method not found",
		}}
	}, nil)

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "upgrade-key"})
	_, err := client.GetSystemInfo(context.Background())
	if err == nil || !strings.Contains(err.Error(), "requires the API key owner username") {
		t.Fatalf("GetSystemInfo() error = %v, want upgrade guidance", err)
	}
	if fixture.restRequests.Load() != 0 {
		t.Fatalf("removed login method made %d REST downgrade requests", fixture.restRequests.Load())
	}
}

func TestJSONRPCPermissionFailureDoesNotDowngradeToREST(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		case "system.info":
			data, _ := json.Marshal(map[string]any{
				"reason":  "Not authorized",
				"errname": "EACCES",
			})
			return protocolFixtureReply{err: &trueNASRPCError{
				Code:    -32001,
				Message: "Method call error",
				Data:    data,
			}}
		default:
			return protocolFixtureReply{close: true}
		}
	}, func(writer http.ResponseWriter, _ *http.Request) {
		t.Error("REST must not be called after an authoritative JSON-RPC permission error")
		http.Error(writer, "unexpected", http.StatusInternalServerError)
	})

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{
		APIKey:   "readonly-key",
		Username: "pulse-readonly",
	})
	_, err := client.GetSystemInfo(context.Background())
	if err == nil || !strings.Contains(err.Error(), "EACCES") {
		t.Fatalf("GetSystemInfo() error = %v, want structured permission failure", err)
	}
	if fixture.restRequests.Load() != 0 {
		t.Fatalf("permission failure made %d REST requests", fixture.restRequests.Load())
	}
	status := client.TransportStatus()
	if status.Mode != TransportJSONRPC || !status.Connected {
		t.Fatalf("permission failure changed transport authority: %+v", status)
	}
}

func TestJSONRPCReadonlyActionDenialIsAuthoritativeAndNotRetried(t *testing.T) {
	var actionCalls atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		case "app.start":
			actionCalls.Add(1)
			data, _ := json.Marshal(map[string]any{
				"reason":  "Not authorized",
				"errname": "EACCES",
			})
			return protocolFixtureReply{err: &trueNASRPCError{
				Code:    -32001,
				Message: "Method call error",
				Data:    data,
			}}
		default:
			return protocolFixtureReply{close: true}
		}
	}, func(writer http.ResponseWriter, _ *http.Request) {
		t.Error("REST must not be called after an authoritative action denial")
		http.Error(writer, "unexpected", http.StatusInternalServerError)
	})

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{
		APIKey:   "readonly-key",
		Username: "pulse-readonly",
	})
	err := client.StartApp(context.Background(), "nextcloud")
	var rpcErr *RPCError
	if !errors.As(err, &rpcErr) || rpcErr.Errname != "EACCES" || rpcErr.Method != "app.start" {
		t.Fatalf("StartApp() error = %v, want structured app.start permission denial", err)
	}
	if actionCalls.Load() != 1 || fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 {
		t.Fatalf("actionCalls=%d sessions=%d restRequests=%d, denial was retried or downgraded",
			actionCalls.Load(), fixture.sessions.Load(), fixture.restRequests.Load())
	}
}

func TestTransportNegotiationAllowsOnlyRecognizedLegacyREST(t *testing.T) {
	t.Run("legacy scale", func(t *testing.T) {
		server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			switch request.URL.Path {
			case "/api/current":
				http.NotFound(writer, request)
			case "/api/v2.0/system/info":
				_, _ = writer.Write([]byte(`{"hostname":"legacy","version":"TrueNAS-SCALE-24.10.2","uptime_seconds":1}`))
			case "/api/v2.0/pool":
				_, _ = writer.Write([]byte(`[{"id":1,"name":"tank","status":"ONLINE"}]`))
			default:
				http.NotFound(writer, request)
			}
		}))
		t.Cleanup(server.Close)

		client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "legacy-key"})
		pools, err := client.GetPools(context.Background())
		if err != nil {
			t.Fatalf("GetPools() legacy error = %v", err)
		}
		if len(pools) != 1 || pools[0].Name != "tank" {
			t.Fatalf("unexpected legacy pools: %+v", pools)
		}
		if status := client.TransportStatus(); status.Mode != TransportLegacyREST || status.ApplianceVersion != "TrueNAS-SCALE-24.10.2" {
			t.Fatalf("unexpected legacy status: %+v", status)
		}
	})

	t.Run("legacy core", func(t *testing.T) {
		server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			switch request.URL.Path {
			case "/api/current":
				http.NotFound(writer, request)
			case "/api/v2.0/system/info":
				_, _ = writer.Write([]byte(`{"hostname":"core","version":"TrueNAS-13.0-U6.4","uptime_seconds":1}`))
			case "/api/v2.0/pool":
				_, _ = writer.Write([]byte(`[{"id":1,"name":"core-tank","status":"ONLINE"}]`))
			default:
				http.NotFound(writer, request)
			}
		}))
		t.Cleanup(server.Close)

		client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "legacy-core-key"})
		pools, err := client.GetPools(context.Background())
		if err != nil {
			t.Fatalf("GetPools() CORE error = %v", err)
		}
		if len(pools) != 1 || pools[0].Name != "core-tank" {
			t.Fatalf("unexpected CORE pools: %+v", pools)
		}
		if status := client.TransportStatus(); status.Mode != TransportLegacyREST ||
			status.ApplianceVersion != "TrueNAS-13.0-U6.4" {
			t.Fatalf("unexpected CORE status: %+v", status)
		}
	})

	for _, test := range []struct {
		name    string
		version string
	}{
		{name: "legacy core 12 https redirect", version: "TrueNAS-12.0-U5"},
		{name: "legacy core 13 https redirect", version: "TrueNAS-13.0-U6.4"},
	} {
		t.Run(test.name, func(t *testing.T) {
			var poolRESTCalls atomic.Int32
			server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
				switch request.URL.Path {
				case "/api/current":
					http.Redirect(writer, request, "/ui/", http.StatusFound)
				case "/api/v2.0/system/info":
					_, _ = fmt.Fprintf(writer, `{"hostname":"core","version":%q,"uptime_seconds":1}`, test.version)
				case "/api/v2.0/pool":
					poolRESTCalls.Add(1)
					_, _ = writer.Write([]byte(`[{"id":1,"name":"core-tank","status":"ONLINE"}]`))
				default:
					http.NotFound(writer, request)
				}
			}))
			t.Cleanup(server.Close)

			client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "legacy-core-key"})
			pools, err := client.GetPools(context.Background())
			if err != nil {
				t.Fatalf("GetPools() redirected CORE error = %v", err)
			}
			if len(pools) != 1 || pools[0].Name != "core-tank" {
				t.Fatalf("unexpected redirected CORE pools: %+v", pools)
			}
			if poolRESTCalls.Load() != 1 {
				t.Fatalf("redirected CORE pool REST calls = %d, want 1", poolRESTCalls.Load())
			}
			if status := client.TransportStatus(); status.Mode != TransportLegacyREST ||
				status.ApplianceVersion != test.version {
				t.Fatalf("unexpected redirected CORE status: %+v", status)
			}
		})
	}

	t.Run("current scale fail closed", func(t *testing.T) {
		var poolRESTCalls atomic.Int32
		server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			switch request.URL.Path {
			case "/api/current":
				http.NotFound(writer, request)
			case "/api/v2.0/system/info":
				_, _ = writer.Write([]byte(`{"hostname":"current","version":"TrueNAS-SCALE-25.10.4","uptime_seconds":1}`))
			case "/api/v2.0/pool":
				poolRESTCalls.Add(1)
				_, _ = writer.Write([]byte(`[]`))
			default:
				http.NotFound(writer, request)
			}
		}))
		t.Cleanup(server.Close)

		client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "current-key"})
		_, err := client.GetPools(context.Background())
		if err == nil || !strings.Contains(err.Error(), "refusing REST downgrade") {
			t.Fatalf("GetPools() error = %v, want fail-closed downgrade error", err)
		}
		if poolRESTCalls.Load() != 0 {
			t.Fatalf("current SCALE used pool REST %d times", poolRESTCalls.Load())
		}
	})

	t.Run("current scale https redirect fails closed", func(t *testing.T) {
		var poolRESTCalls atomic.Int32
		server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
			switch request.URL.Path {
			case "/api/current":
				http.Redirect(writer, request, "/ui/", http.StatusFound)
			case "/api/v2.0/system/info":
				_, _ = writer.Write([]byte(`{"hostname":"current","version":"TrueNAS-SCALE-25.10.4","uptime_seconds":1}`))
			case "/api/v2.0/pool":
				poolRESTCalls.Add(1)
				_, _ = writer.Write([]byte(`[]`))
			default:
				http.NotFound(writer, request)
			}
		}))
		t.Cleanup(server.Close)

		client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "current-key"})
		_, err := client.GetPools(context.Background())
		if err == nil || !strings.Contains(err.Error(), "refusing REST downgrade") {
			t.Fatalf("GetPools() error = %v, want fail-closed downgrade error", err)
		}
		if poolRESTCalls.Load() != 0 {
			t.Fatalf("current SCALE used pool REST %d times", poolRESTCalls.Load())
		}
	})
}

func TestJSONRPCCredentialsRequireTLSWithoutSendingAuthentication(t *testing.T) {
	var rpcRequests atomic.Int32
	var restRequests atomic.Int32
	upgrader := websocket.Upgrader{}
	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		if request.URL.Path != "/api/current" || !websocket.IsWebSocketUpgrade(request) {
			restRequests.Add(1)
			http.NotFound(writer, request)
			return
		}
		conn, err := upgrader.Upgrade(writer, request, nil)
		if err != nil {
			t.Errorf("upgrade plaintext websocket: %v", err)
			return
		}
		defer func() { _ = conn.Close() }()
		var rpcRequest trueNASRPCRequest
		if conn.ReadJSON(&rpcRequest) == nil {
			rpcRequests.Add(1)
		}
	}))
	t.Cleanup(server.Close)

	client := mustClientForServer(t, server.URL, ClientConfig{
		APIKey:   "must-not-cross-plaintext",
		Username: "pulse-readonly",
	})
	client.allowInsecureRPC = false
	t.Cleanup(client.Close)
	_, err := client.GetPools(context.Background())
	if err == nil || !strings.Contains(err.Error(), "credentials require TLS") {
		t.Fatalf("GetPools() error = %v, want TLS requirement", err)
	}
	if rpcRequests.Load() != 0 || restRequests.Load() != 0 {
		t.Fatalf("plaintext negotiation sent rpc=%d REST=%d requests after websocket upgrade",
			rpcRequests.Load(), restRequests.Load())
	}
}

func TestTransportNegotiationIsIsolatedAcrossAppliances(t *testing.T) {
	modern := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		case "pool.query":
			return protocolFixtureReply{result: []map[string]any{{"id": 1, "name": "modern", "status": "ONLINE"}}}
		default:
			return protocolFixtureReply{close: true}
		}
	}, nil)
	legacyServer := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		switch request.URL.Path {
		case "/api/current":
			http.NotFound(writer, request)
		case "/api/v2.0/system/info":
			_, _ = writer.Write([]byte(`{"hostname":"legacy","version":"TrueNAS-SCALE-24.10.2"}`))
		case "/api/v2.0/pool":
			_, _ = writer.Write([]byte(`[{"id":2,"name":"legacy","status":"ONLINE"}]`))
		default:
			http.NotFound(writer, request)
		}
	}))
	t.Cleanup(legacyServer.Close)

	modernClient := protocolFixtureClient(t, modern.server.URL, ClientConfig{
		APIKey:   "modern-key",
		Username: "pulse-readonly",
	})
	legacyClient := protocolFixtureClient(t, legacyServer.URL, ClientConfig{APIKey: "legacy-key"})

	modernPools, modernErr := modernClient.GetPools(context.Background())
	legacyPools, legacyErr := legacyClient.GetPools(context.Background())
	if modernErr != nil || legacyErr != nil {
		t.Fatalf("multi-appliance polls failed: modern=%v legacy=%v", modernErr, legacyErr)
	}
	if len(modernPools) != 1 || modernPools[0].Name != "modern" ||
		len(legacyPools) != 1 || legacyPools[0].Name != "legacy" {
		t.Fatalf("unexpected isolated inventories: modern=%+v legacy=%+v", modernPools, legacyPools)
	}
	modernStatus := modernClient.TransportStatus()
	legacyStatus := legacyClient.TransportStatus()
	if modernStatus.Mode != TransportJSONRPC || modernStatus.Endpoint == legacyStatus.Endpoint ||
		legacyStatus.Mode != TransportLegacyREST {
		t.Fatalf("transport decisions leaked across clients: modern=%+v legacy=%+v", modernStatus, legacyStatus)
	}
}

func TestNegotiatedJSONRPCTransportNeverRenegotiatesToREST(t *testing.T) {
	var websocketAttempts atomic.Int32
	var restRequests atomic.Int32
	upgrader := websocket.Upgrader{}
	server := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		switch request.URL.Path {
		case "/api/current":
			if websocketAttempts.Add(1) > 1 {
				http.NotFound(writer, request)
				return
			}
			conn, err := upgrader.Upgrade(writer, request, nil)
			if err != nil {
				t.Errorf("upgrade initial websocket: %v", err)
				return
			}
			defer func() { _ = conn.Close() }()
			for {
				var rpcRequest trueNASRPCRequest
				if err := conn.ReadJSON(&rpcRequest); err != nil {
					return
				}
				var result any
				switch rpcRequest.Method {
				case "auth.login_with_api_key":
					result = true
				case "pool.query":
					result = []map[string]any{{"id": 1, "name": "modern", "status": "ONLINE"}}
				default:
					t.Errorf("unexpected rpc method %q", rpcRequest.Method)
					return
				}
				raw, err := json.Marshal(result)
				if err != nil {
					t.Errorf("marshal rpc result: %v", err)
					return
				}
				if err := conn.WriteJSON(trueNASRPCResponse{
					JSONRPC: "2.0",
					ID:      rpcRequest.ID,
					Result:  raw,
				}); err != nil {
					return
				}
			}
		case "/api/v2.0/system/info", "/api/v2.0/pool":
			restRequests.Add(1)
			_, _ = writer.Write([]byte(`{"version":"TrueNAS-SCALE-24.10.2"}`))
		default:
			http.NotFound(writer, request)
		}
	}))
	t.Cleanup(server.Close)

	client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "modern-key"})
	if _, err := client.GetPools(context.Background()); err != nil {
		t.Fatalf("initial GetPools() error = %v", err)
	}

	client.rpcMu.Lock()
	client.closeRPCLocked()
	client.rpcMu.Unlock()

	_, err := client.GetPools(context.Background())
	if err == nil || !strings.Contains(err.Error(), "transport is immutable") {
		t.Fatalf("GetPools() reconnect error = %v, want immutable transport failure", err)
	}
	if restRequests.Load() != 0 {
		t.Fatalf("negotiated JSON-RPC transport made %d REST downgrade requests", restRequests.Load())
	}
	status := client.TransportStatus()
	if status.Mode != TransportJSONRPC || status.Connected {
		t.Fatalf("immutable reconnect changed transport authority: %+v", status)
	}
}

func TestJSONRPCReadReconnectsButActionIsNeverReplayed(t *testing.T) {
	t.Run("read reconnect", func(t *testing.T) {
		var poolCalls atomic.Int32
		fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
			if request.Method == "auth.login_with_api_key" {
				return protocolFixtureReply{result: true}
			}
			if request.Method != "pool.query" {
				return protocolFixtureReply{close: true}
			}
			call := poolCalls.Add(1)
			if session == 1 && call == 2 {
				return protocolFixtureReply{close: true}
			}
			return protocolFixtureReply{result: []map[string]any{{"id": 1, "name": "tank", "status": "ONLINE"}}}
		}, nil)

		client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "legacy-auth-key"})
		if _, err := client.GetPools(context.Background()); err != nil {
			t.Fatalf("first GetPools() error = %v", err)
		}
		if _, err := client.GetPools(context.Background()); err != nil {
			t.Fatalf("reconnected GetPools() error = %v", err)
		}
		if fixture.sessions.Load() != 2 || poolCalls.Load() != 3 {
			t.Fatalf("sessions=%d poolCalls=%d, want one replay on a new session", fixture.sessions.Load(), poolCalls.Load())
		}
		if status := client.TransportStatus(); status.Reconnects != 1 || status.Mode != TransportJSONRPC {
			t.Fatalf("unexpected reconnect status: %+v", status)
		}
	})

	t.Run("action outcome unknown", func(t *testing.T) {
		var actionCalls atomic.Int32
		fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
			if request.Method == "auth.login_with_api_key" {
				return protocolFixtureReply{result: true}
			}
			if request.Method == "app.start" {
				actionCalls.Add(1)
				return protocolFixtureReply{close: true}
			}
			return protocolFixtureReply{close: true}
		}, nil)

		client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "app-write-key"})
		err := client.StartApp(context.Background(), "nextcloud")
		if err == nil || !strings.Contains(err.Error(), "outcome is unknown") {
			t.Fatalf("StartApp() error = %v, want non-replay outcome", err)
		}
		if actionCalls.Load() != 1 || fixture.sessions.Load() != 1 {
			t.Fatalf("actionCalls=%d sessions=%d, action was replayed", actionCalls.Load(), fixture.sessions.Load())
		}
	})
}

func TestJSONRPCQueryReturnsCompleteUnpaginatedInventory(t *testing.T) {
	poolFixture := make([]map[string]any, 0, 225)
	for i := 0; i < 225; i++ {
		poolFixture = append(poolFixture, map[string]any{"id": i + 1, "name": "pool-" + strings.Repeat("x", i%4), "status": "ONLINE"})
	}
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_with_api_key" {
			return protocolFixtureReply{result: true}
		}
		if request.Method != "pool.query" {
			return protocolFixtureReply{close: true}
		}
		params, ok := request.Params.([]any)
		if !ok || len(params) != 2 {
			t.Errorf("pool.query params = %#v", request.Params)
		} else if options, ok := params[1].(map[string]any); !ok || len(options) != 0 {
			t.Errorf("pool.query options must request the authoritative complete set, got %#v", params[1])
		}
		return protocolFixtureReply{result: poolFixture}
	}, nil)

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "readonly-key"})
	pools, err := client.GetPools(context.Background())
	if err != nil {
		t.Fatalf("GetPools() error = %v", err)
	}
	if len(pools) != len(poolFixture) {
		t.Fatalf("GetPools() returned %d pools, want %d", len(pools), len(poolFixture))
	}
}

func TestJSONRPCFetchSnapshotUsesPublishedTrueNAS26MethodsWithoutREST(t *testing.T) {
	methodCalls := make(map[string]int)
	var methodCallsMu sync.Mutex
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		methodCallsMu.Lock()
		methodCalls[request.Method]++
		methodCallsMu.Unlock()

		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		case "system.info":
			return protocolFixtureReply{result: map[string]any{
				"hostname":       "inventory-nas",
				"version":        "TrueNAS-SCALE-26.0.0-BETA.3",
				"system_serial":  "INVENTORY-1",
				"uptime_seconds": 60,
				"physical_cores": 4,
				"physmem":        8 * 1024 * 1024 * 1024,
			}}
		case "reporting.get_data":
			return protocolFixtureReply{result: []any{}}
		case "core.subscribe":
			params, _ := request.Params.([]any)
			event, _ := params[0].(string)
			if strings.HasPrefix(event, "reporting.realtime:") {
				return protocolFixtureReply{
					result: "sub-realtime",
					notifications: []protocolFixtureNotification{{
						method: "collection_update",
						params: map[string]any{
							"collection": event,
							"fields":     map[string]any{"cpu": map[string]any{"usage": 12}},
						},
					}},
				}
			}
			if strings.HasPrefix(event, "app.stats:") {
				return protocolFixtureReply{
					result: "sub-app-stats",
					notifications: []protocolFixtureNotification{{
						method: "collection_update",
						params: map[string]any{
							"collection": event,
							"fields":     []any{},
						},
					}},
				}
			}
			t.Errorf("unexpected subscription event %q", event)
			return protocolFixtureReply{close: true}
		case "core.unsubscribe":
			return protocolFixtureReply{result: nil}
		case "pool.query", "pool.dataset.query", "disk.query", "alert.list",
			"service.query", "app.query", "vm.query", "sharing.smb.query",
			"sharing.nfs.query", "zfs.resource.snapshot.query", "replication.query":
			return protocolFixtureReply{result: []any{}}
		case "boot.get_state":
			return protocolFixtureReply{result: map[string]any{
				"id": "boot-pool", "name": "boot-pool", "status": "ONLINE",
			}}
		default:
			t.Errorf("unexpected rpc method %q", request.Method)
			return protocolFixtureReply{close: true}
		}
	}, nil)

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{
		APIKey:   "readonly-key",
		Username: "pulse-readonly",
	})
	snapshot, err := client.FetchSnapshot(context.Background())
	if err != nil {
		t.Fatalf("FetchSnapshot() error = %v", err)
	}
	if snapshot.System.Hostname != "inventory-nas" ||
		snapshot.System.Version != "TrueNAS-SCALE-26.0.0-BETA.3" ||
		snapshot.System.CPUPercent != 12 {
		t.Fatalf("unexpected snapshot system: %+v", snapshot.System)
	}

	for _, method := range []string{
		"system.info",
		"pool.query",
		"boot.get_state",
		"pool.dataset.query",
		"disk.query",
		"alert.list",
		"service.query",
		"app.query",
		"vm.query",
		"sharing.smb.query",
		"sharing.nfs.query",
		"zfs.resource.snapshot.query",
		"replication.query",
	} {
		methodCallsMu.Lock()
		count := methodCalls[method]
		methodCallsMu.Unlock()
		if count != 1 {
			t.Errorf("%s calls = %d, want exactly one", method, count)
		}
	}
	methodCallsMu.Lock()
	subscribeCalls := methodCalls["core.subscribe"]
	unsubscribeCalls := methodCalls["core.unsubscribe"]
	methodCallsMu.Unlock()
	if subscribeCalls != 1 || unsubscribeCalls != 1 {
		t.Fatalf("subscription lifecycle calls: subscribe=%d unsubscribe=%d, want 1/1 (realtime only for empty apps)", subscribeCalls, unsubscribeCalls)
	}
	if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 {
		t.Fatalf("snapshot sessions=%d REST=%d, want one modern session and no REST",
			fixture.sessions.Load(), fixture.restRequests.Load())
	}
}

func TestJSONRPCAppStatsNumbersReuseSession(t *testing.T) {
	for _, cpu := range []string{"0.0286", "0.0", "17"} {
		t.Run(cpu, func(t *testing.T) {
			var logins, subscribes, unsubscribes atomic.Int32
			fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
				switch request.Method {
				case "auth.login_ex":
					logins.Add(1)
					return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
				case "app.query":
					return protocolFixtureReply{result: []any{map[string]any{"id": "fixture-app", "name": "Fixture app", "state": "RUNNING"}}}
				case "core.subscribe":
					subscribes.Add(1)
					collection := request.Params.([]any)[0].(string)
					return protocolFixtureReply{result: "stats-sub", notifications: []protocolFixtureNotification{{
						method: "collection_update", params: map[string]any{
							"collection": collection, "fields": []any{map[string]any{
								"app_name": "fixture-app", "cpu_usage": json.Number(cpu), "memory": 1072459776,
								"networks": []any{map[string]any{"interface_name": "eth0", "rx_bytes": 3671, "tx_bytes": 284}},
								"blkio":    map[string]any{"read": 29720576, "write": 0},
							}},
						},
					}}}
				case "core.unsubscribe":
					unsubscribes.Add(1)
					return protocolFixtureReply{result: nil}
				case "pool.query":
					return protocolFixtureReply{result: []any{}}
				default:
					t.Errorf("unexpected method %s", request.Method)
					return protocolFixtureReply{close: true}
				}
			}, nil)
			client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
			wantCPU, _ := strconv.ParseFloat(cpu, 64)
			var lastStats time.Time
			for poll := 0; poll < 3; poll++ {
				apps, err := client.GetApps(context.Background())
				if err != nil || len(apps) != 1 || apps[0].ID != "fixture-app" {
					t.Fatalf("poll %d lost app inventory: %+v, %v", poll, apps, err)
				}
				if stats := apps[0].Stats; stats == nil {
					t.Errorf("poll %d lost app.stats for JSON CPU number %s", poll, cpu)
				} else {
					if stats.CPUPercent != wantCPU || stats.MemoryBytes != 1072459776 || stats.NetInRate != 3671 || stats.NetOutRate != 284 ||
						stats.BlockReadBytes != 29720576 || stats.BlockWriteBytes != 0 || stats.IntervalSeconds != 2 || !stats.CollectedAt.After(lastStats) {
						t.Errorf("poll %d lost precise CPU/sibling fields/freshness: %+v", poll, stats)
					}
					lastStats = stats.CollectedAt
				}
			}
			if _, err := client.GetPools(context.Background()); err != nil {
				t.Fatal(err)
			}
			if fixture.sessions.Load() != 1 || logins.Load() != 1 || subscribes.Load() != 3 || unsubscribes.Load() != 3 ||
				fixture.restRequests.Load() != 0 || !client.TransportStatus().Connected {
				t.Errorf("JSON CPU number caused session churn: sessions=%d logins=%d subscribe=%d unsubscribe=%d", fixture.sessions.Load(), logins.Load(), subscribes.Load(), unsubscribes.Load())
			}
		})
	}
}

// Invalid CPU data must still fail the complete event, not fabricate an idle
// sample or retry a non-transport decode failure after accepting JSON numbers.
func TestJSONRPCAppStatsRejectsMalformedCPUNumbers(t *testing.T) {
	for _, cpu := range []string{`"0.0286"`, `true`, `{}`, `[]`, `1e309`} {
		t.Run(cpu, func(t *testing.T) {
			var subscribes, unsubscribes, logins atomic.Int32
			fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
				switch request.Method {
				case "auth.login_ex":
					logins.Add(1)
					return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
				case "core.subscribe":
					subscribes.Add(1)
					collection := request.Params.([]any)[0].(string)
					return protocolFixtureReply{result: "stats-sub", notifications: []protocolFixtureNotification{{
						method: "collection_update", params: map[string]any{
							"collection": collection,
							"fields": []any{
								map[string]any{"app_name": "valid-app", "cpu_usage": json.Number("0.0286")},
								map[string]any{"app_name": "invalid-app", "cpu_usage": json.RawMessage(cpu)},
							},
						},
					}}}
				case "core.unsubscribe":
					unsubscribes.Add(1)
					return protocolFixtureReply{result: nil}
				case "pool.query":
					return protocolFixtureReply{result: []any{}}
				default:
					t.Errorf("unexpected method %s", request.Method)
					return protocolFixtureReply{close: true}
				}
			}, nil)
			client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
			stats, err := client.GetAppStats(context.Background())
			if err == nil || !strings.Contains(err.Error(), "decode truenas app.stats notification") || stats != nil {
				t.Fatalf("malformed CPU produced partial/successful stats: %+v, %v", stats, err)
			}
			if client.rpc != nil || client.TransportStatus().Connected || fixture.sessions.Load() != 1 ||
				logins.Load() != 1 || subscribes.Load() != 1 || unsubscribes.Load() != 0 {
				t.Fatal("malformed stats were retried, retained the failed session or attempted unsubscribe")
			}
			if _, err := client.GetPools(context.Background()); err != nil || fixture.sessions.Load() != 2 ||
				logins.Load() != 2 || fixture.restRequests.Load() != 0 {
				t.Fatalf("next independent read did not recover over authenticated JSON-RPC: %v", err)
			}
		})
	}
}

func TestJSONRPCMalformedSubscriptionEventDiscardsSession(t *testing.T) {
	fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_with_api_key":
			return protocolFixtureReply{result: true}
		case "core.subscribe":
			return protocolFixtureReply{
				result: "sub-malformed",
				notifications: []protocolFixtureNotification{{
					method: "collection_update",
					params: map[string]any{
						"collection": "app.stats:{\"interval\":2}",
						"fields":     "not-an-array",
					},
				}},
			}
		case "pool.query":
			if session != 2 {
				t.Errorf("pool.query reused malformed subscription session %d", session)
			}
			return protocolFixtureReply{result: []map[string]any{{"id": 1, "name": "tank", "status": "ONLINE"}}}
		default:
			t.Errorf("unexpected rpc method %q", request.Method)
			return protocolFixtureReply{close: true}
		}
	}, nil)

	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "readonly-key"})
	if _, err := client.GetAppStats(context.Background()); err == nil ||
		!strings.Contains(err.Error(), "decode truenas app.stats notification") {
		t.Fatalf("GetAppStats() error = %v, want malformed event error", err)
	}
	pools, err := client.GetPools(context.Background())
	if err != nil {
		t.Fatalf("GetPools() after discarded stream error = %v", err)
	}
	if len(pools) != 1 || pools[0].Name != "tank" || fixture.sessions.Load() != 2 {
		t.Fatalf("unexpected post-discard state: pools=%+v sessions=%d", pools, fixture.sessions.Load())
	}
	if status := client.TransportStatus(); status.Reconnects != 1 {
		t.Fatalf("discarded stream reconnect was not observable: %+v", status)
	}
}

func TestTransportDiagnosticsAreConnectionLocalAndSecretFree(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_with_api_key" {
			data, _ := json.Marshal(map[string]any{
				"reason":  "invalid credential never-expose-this-key",
				"errname": "EINVAL",
			})
			return protocolFixtureReply{err: &trueNASRPCError{
				Code:    -32001,
				Message: "Method call error",
				Data:    data,
			}}
		}
		return protocolFixtureReply{close: true}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "never-expose-this-key"})

	if _, err := client.GetPools(context.Background()); err == nil {
		t.Fatal("expected authentication failure")
	}
	status := client.TransportStatus()
	encoded, err := json.Marshal(status)
	if err != nil {
		t.Fatalf("Marshal(status) error = %v", err)
	}
	if strings.Contains(string(encoded), "never-expose-this-key") {
		t.Fatalf("transport status exposed API key: %s", encoded)
	}
	if status.Mode != TransportUnknown {
		t.Fatalf("failed authentication selected a transport: %+v", status)
	}
}

// Issue #1631 handshake-redirect coverage: the v6.1.2 JSON-RPC migration
// broke http-configured appliances behind TrueNAS's HTTP -> HTTPS redirect.
// The websocket dial must upgrade a same-host https redirect to wss itself
// and refuse anything that would move the connection to another host.

func newHTTPRedirectServer(t *testing.T, location func() string, status int) *httptest.Server {
	t.Helper()
	server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		http.Redirect(writer, request, location(), status)
	}))
	t.Cleanup(server.Close)
	return server
}

func redirectFixtureClient(t *testing.T, redirectURL string) *Client {
	t.Helper()
	parsed, err := url.Parse(redirectURL)
	if err != nil {
		t.Fatalf("parse redirect server URL %q: %v", redirectURL, err)
	}
	port, err := strconv.Atoi(parsed.Port())
	if err != nil {
		t.Fatalf("parse redirect server port from %q: %v", redirectURL, err)
	}
	client, err := NewClient(ClientConfig{
		Host:               "http://" + parsed.Hostname(),
		Port:               port,
		Username:           "pulse-readonly",
		APIKey:             "readonly-key",
		InsecureSkipVerify: true,
		Timeout:            5 * time.Second,
	})
	if err != nil {
		t.Fatalf("NewClient() error = %v", err)
	}
	t.Cleanup(client.Close)
	return client
}

func TestIssue1631HTTPRedirectUpgradesHandshakeToTLS(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS", "user_info": nil}}
		}
		t.Errorf("unexpected rpc method %q", request.Method)
		return protocolFixtureReply{close: true}
	}, nil)

	redirect := newHTTPRedirectServer(t, func() string {
		return fixture.server.URL + "/api/current"
	}, http.StatusFound)
	client := redirectFixtureClient(t, redirect.URL)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	mode, err := client.ensureTransport(ctx)
	if err != nil {
		t.Fatalf("ensureTransport() error = %v", err)
	}
	if mode != TransportJSONRPC {
		t.Fatalf("ensureTransport() mode = %s, want %s", mode, TransportJSONRPC)
	}

	status := client.TransportStatus()
	if !status.TLS {
		t.Errorf("TransportStatus().TLS = false, want true after https upgrade")
	}
	if !strings.HasPrefix(status.Endpoint, "wss://") {
		t.Errorf("TransportStatus().Endpoint = %q, want wss:// endpoint", status.Endpoint)
	}
	if !client.config.UseHTTPS {
		t.Errorf("config.UseHTTPS = false, want true after https upgrade")
	}
	if fixture.sessions.Load() == 0 {
		t.Errorf("TLS fixture saw no websocket sessions; upgrade retry never landed")
	}
}

func TestIssue1631CrossHostRedirectIsRefused(t *testing.T) {
	redirect := newHTTPRedirectServer(t, func() string {
		return "https://other-appliance.example/api/current"
	}, http.StatusFound)
	client := redirectFixtureClient(t, redirect.URL)

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_, err := client.ensureTransport(ctx)
	if err == nil {
		t.Fatal("ensureTransport() error = nil, want cross-host redirect refusal")
	}
	if !strings.Contains(err.Error(), "redirected to") || !strings.Contains(err.Error(), "other-appliance.example") {
		t.Errorf("ensureTransport() error = %q, want actionable message naming the redirect target", err)
	}
	if status := client.TransportStatus(); status.TLS {
		t.Errorf("TransportStatus().TLS = true, want false when redirect is refused")
	}
}

func TestIssue1631HTTPSUpgradeTargetRules(t *testing.T) {
	cases := []struct {
		name     string
		current  string
		location string
		want     string
		ok       bool
	}{
		{"same host default port", "ws://nas.local:80/api/current", "https://nas.local/ui/", "wss://nas.local:443/api/current", true},
		{"same host explicit port", "ws://nas.local:80/api/current", "https://nas.local:8443/", "wss://nas.local:8443/api/current", true},
		{"cross host", "ws://nas.local:80/api/current", "https://evil.example/", "", false},
		{"relative location", "ws://nas.local:80/api/current", "/ui/", "", false},
		{"downgrade from wss", "wss://nas.local:443/api/current", "https://nas.local/", "", false},
		{"http location", "ws://nas.local:80/api/current", "http://nas.local:8080/", "", false},
		{"empty location", "ws://nas.local:80/api/current", "", "", false},
	}
	for _, tc := range cases {
		got, ok := httpsUpgradeTarget(tc.current, tc.location)
		if ok != tc.ok || got != tc.want {
			t.Errorf("%s: httpsUpgradeTarget(%q, %q) = (%q, %v), want (%q, %v)", tc.name, tc.current, tc.location, got, ok, tc.want, tc.ok)
		}
	}
}

// Model an authenticated appliance with a transport idle limit. This is not
// evidence of a particular appliance firmware's authenticated timeout policy.
func TestAuthenticatedRPCSurvivesIdleTransportTimeout(t *testing.T) {
	var sessions, pings atomic.Int32
	upgrader := websocket.Upgrader{}
	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		conn, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			return
		}
		defer conn.Close()
		sessions.Add(1)
		resetIdle := func() { _ = conn.SetReadDeadline(time.Now().Add(35 * time.Second)) }
		conn.SetPingHandler(func(data string) error {
			pings.Add(1)
			resetIdle()
			return conn.WriteControl(websocket.PongMessage, []byte(data), time.Now().Add(time.Second))
		})
		resetIdle()
		for {
			var request trueNASRPCRequest
			if err := conn.ReadJSON(&request); err != nil {
				return
			}
			resetIdle()
			var result any = map[string]any{"version": "TrueNAS-SCALE-25.04.2"}
			if request.Method == "auth.login_ex" {
				result = map[string]any{"response_type": "SUCCESS"}
			}
			if err := conn.WriteJSON(map[string]any{"jsonrpc": "2.0", "id": request.ID, "result": result}); err != nil {
				return
			}
		}
	}))
	defer server.Close()
	client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
	defer client.Close()
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Second)
	defer cancel()
	if _, err := client.GetSystemInfo(ctx); err != nil {
		t.Fatal(err)
	}
	client.rpcMu.Lock()
	session := client.rpc
	client.rpcMu.Unlock()
	// Cancelling the opening call must not cancel the persistent session.
	cancel()
	ctx, cancel = context.WithTimeout(context.Background(), 50*time.Second)
	defer cancel()
	// Longer than the fixture's idle timeout, shorter than two production pings.
	time.Sleep(40 * time.Second)
	if _, err := client.GetSystemInfo(ctx); err != nil {
		t.Fatal(err)
	}
	if got := sessions.Load(); got != 1 {
		t.Errorf("authenticated sessions = %d, want 1 (idle connection was lost)", got)
	}
	if pings.Load() == 0 {
		t.Error("no websocket keepalive received")
	}
	client.Close()
	select {
	case <-session.keepaliveDone:
	default:
		t.Error("Close returned before keepalive exited")
	}
}

func TestRPCSessionKeepaliveConcurrentCallsAndShutdown(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, _ trueNASRPCRequest) protocolFixtureReply {
		time.Sleep(3 * time.Millisecond)
		return protocolFixtureReply{result: "ok"}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{})
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	conn, err := client.dialRPC(ctx)
	if err != nil {
		t.Fatal(err)
	}
	rpc := &trueNASRPCClient{conn: conn, nextID: 1}
	rpc.startKeepalive(time.Millisecond)
	defer rpc.close()
	for i := 0; i < 20; i++ {
		var result string
		if err := rpc.call(ctx, "fixture.read", nil, &result); err != nil {
			t.Fatal(err)
		}
		if result != "ok" {
			t.Fatalf("result = %q", result)
		}
	}
	// A failed control write must terminate its sender and close the socket,
	// rather than retaining a goroutine until a future poll/client shutdown.
	_ = conn.Close()
	select {
	case <-rpc.keepaliveDone:
	case <-time.After(time.Second):
		t.Fatal("keepalive did not exit after socket failure")
	}
}

// The production poll loop has a cancellation context, not a per-request
// deadline. A silent peer must still be bounded by ClientConfig.Timeout. These
// fixtures never infer an appliance's reason for failing to reply.
func awaitConfiguredRPCBudget(t *testing.T, operation func(context.Context) error) error {
	t.Helper()
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	done := make(chan error, 1)
	go func() { done <- operation(ctx) }()
	select {
	case err := <-done:
		return err
	case <-time.After(time.Second):
		t.Error("RPC operation ignored the configured timeout")
		cancel() // Also lets the pre-repair adverse control terminate safely.
		select {
		case err := <-done:
			return err
		case <-time.After(5 * time.Second):
			t.Fatal("cancelled RPC operation did not stop")
			return nil
		}
	}
}

func assertRPCTimeout(t *testing.T, err error) {
	t.Helper()
	if err == nil || (!errors.Is(err, context.DeadlineExceeded) && !isTimeoutError(err)) {
		t.Errorf("expected a timeout, got %v", err)
	}
}

func TestJSONRPCConfiguredTimeoutBoundsHandshake(t *testing.T) {
	release := make(chan struct{})
	var restRequests atomic.Int32
	server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/current" {
			restRequests.Add(1)
		}
		<-release // TCP/TLS succeeds, but no WebSocket handshake response follows.
	}))
	t.Cleanup(server.Close)
	client := protocolFixtureClient(t, server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
	t.Cleanup(func() { close(release) })
	err := awaitConfiguredRPCBudget(t, client.TestConnection)
	assertRPCTimeout(t, err)
	var handshake *RPCHandshakeError
	if !errors.As(err, &handshake) || client.TransportStatus().Connected || restRequests.Load() != 0 {
		t.Fatalf("handshake timeout lost its type/status or downgraded to REST: %v", err)
	}
}

func TestJSONRPCConfiguredTimeoutBoundsAuthentication(t *testing.T) {
	release := make(chan struct{})
	var logins atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			logins.Add(1)
			<-release
		}
		return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
	t.Cleanup(func() { close(release) })
	err := awaitConfiguredRPCBudget(t, client.TestConnection)
	assertRPCTimeout(t, err)
	if fixture.sessions.Load() != 1 || logins.Load() != 1 || fixture.restRequests.Load() != 0 || client.TransportStatus().Connected {
		t.Fatalf("silent authentication retried, downgraded or appeared connected: %+v", client.TransportStatus())
	}
}

func TestJSONRPCConfiguredTimeoutBoundsReadAndRecovers(t *testing.T) {
	release := make(chan struct{})
	var reads atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if request.Method == "system.info" && reads.Add(1) == 1 {
			<-release
		}
		return protocolFixtureReply{result: map[string]any{"hostname": "timeout-fixture", "version": "TrueNAS-SCALE-25.10.7"}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
	t.Cleanup(func() { close(release) })
	err := awaitConfiguredRPCBudget(t, client.TestConnection)
	assertRPCTimeout(t, err)
	if fixture.sessions.Load() != 1 || reads.Load() != 1 || client.TransportStatus().Connected {
		t.Fatal("expired operation gained a retry budget or retained its timed-out session")
	}
	if err := client.TestConnection(context.Background()); err != nil {
		t.Fatalf("subsequent operation did not recover: %v", err)
	}
	if fixture.sessions.Load() != 2 || reads.Load() != 2 || fixture.restRequests.Load() != 0 || !client.TransportStatus().Connected {
		t.Fatalf("subsequent operation did not negotiate one fresh RPC session: %+v", client.TransportStatus())
	}
}

func TestJSONRPCConfiguredTimeoutIncludesReadRetryBackoff(t *testing.T) {
	release := make(chan struct{})
	var reads atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if reads.Add(1) == 1 {
			// The 100 ms reconnect backoff cannot fit in the remaining part of
			// a 200 ms operation. It must not create a new deadline on retry.
			time.Sleep(150 * time.Millisecond)
			return protocolFixtureReply{close: true}
		}
		<-release
		return protocolFixtureReply{result: nil}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 2 * time.Second})
	t.Cleanup(func() { close(release) })
	// This case must reach the read/retry boundary, rather than also racing a
	// cold TLS/login against 200 ms. Separate fixtures above bound those stages.
	if err := client.withRPC(context.Background(), func(context.Context, *trueNASRPCClient) error { return nil }); err != nil {
		t.Fatalf("prepare authenticated read-retry session: %v", err)
	}
	if fixture.sessions.Load() != 1 || reads.Load() != 0 || fixture.restRequests.Load() != 0 {
		t.Fatalf("read-retry setup dispatched work: sessions=%d reads=%d REST=%d", fixture.sessions.Load(), reads.Load(), fixture.restRequests.Load())
	}
	client.config.Timeout = 200 * time.Millisecond // unchanged budget under test
	err := awaitConfiguredRPCBudget(t, client.TestConnection)
	assertRPCTimeout(t, err)
	if fixture.sessions.Load() != 1 || reads.Load() != 1 || fixture.restRequests.Load() != 0 {
		t.Fatalf("read retry restarted an exhausted operation budget: sessions=%d reads=%d REST=%d", fixture.sessions.Load(), reads.Load(), fixture.restRequests.Load())
	}
}

func TestJSONRPCConfiguredTimeoutDoesNotExtendCallerDeadline(t *testing.T) {
	release := make(chan struct{})
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		<-release
		return protocolFixtureReply{result: nil}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 5 * time.Second})
	t.Cleanup(func() { close(release) })
	err := awaitConfiguredRPCBudget(t, func(parent context.Context) error {
		ctx, cancel := context.WithTimeout(parent, 100*time.Millisecond)
		defer cancel()
		return client.TestConnection(ctx)
	})
	assertRPCTimeout(t, err)
	if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 {
		t.Fatal("caller deadline gained a retry or REST downgrade")
	}
}

func TestJSONRPCConfiguredTimeoutDoesNotReplayAction(t *testing.T) {
	release := make(chan struct{})
	var actions atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if request.Method == "app.start" {
			actions.Add(1)
			<-release
		}
		return protocolFixtureReply{result: nil}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
	t.Cleanup(func() { close(release) })
	err := awaitConfiguredRPCBudget(t, func(ctx context.Context) error { return client.StartApp(ctx, "fixture-app") })
	assertRPCTimeout(t, err)
	if !strings.Contains(err.Error(), "outcome is unknown") || actions.Load() != 1 || fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 {
		t.Fatalf("timed-out action was replayed or lost its unknown outcome: %v", err)
	}
}

func TestJSONRPCConfiguredTimeoutBoundsSubscriptions(t *testing.T) {
	for _, stream := range []string{"telemetry", "app-stats", "app-logs"} {
		t.Run(stream, func(t *testing.T) {
			fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
				switch request.Method {
				case "auth.login_ex":
					return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
				case "core.subscribe":
					return protocolFixtureReply{result: "fixture-subscription"} // No stream event ever arrives.
				default:
					return protocolFixtureReply{result: []any{}}
				}
			}, nil)
			client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
			err := awaitConfiguredRPCBudget(t, func(ctx context.Context) error {
				switch stream {
				case "telemetry":
					_, err := client.GetSystemTelemetry(ctx)
					return err
				case "app-stats":
					_, err := client.GetAppStats(ctx)
					return err
				default:
					_, err := client.GetAppLogs(ctx, "fixture-app", "fixture-container", 100)
					return err
				}
			})
			assertRPCTimeout(t, err)
			if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 || client.TransportStatus().Connected {
				t.Fatal("expired stream was retried, downgraded or left reusable")
			}
		})
	}
}

func TestJSONRPCWaitingDeadlineDoesNotInterruptSessionOwner(t *testing.T) {
	release := make(chan struct{})
	started := make(chan struct{})
	var reads atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if reads.Add(1) == 1 {
			close(started)
			<-release
		}
		return protocolFixtureReply{result: map[string]any{"hostname": "session-owner"}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 5 * time.Second})
	var released atomic.Bool
	unblock := func() {
		if released.CompareAndSwap(false, true) {
			close(release)
		}
	}
	t.Cleanup(unblock)
	owner := make(chan error, 1)
	go func() { owner <- client.TestConnection(context.Background()) }()
	select {
	case <-started:
	case <-time.After(2 * time.Second):
		t.Fatal("session owner did not dispatch")
	}
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
	defer cancel()
	waiter := make(chan error, 1)
	go func() { waiter <- client.TestConnection(ctx) }()
	select {
	case err := <-waiter:
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Errorf("waiter error = %v, want caller deadline", err)
		}
	case <-time.After(time.Second):
		t.Error("caller deadline could not abandon the session lock wait")
		unblock() // Do not strand the predecessor's uncancellable mutex waiter.
		<-waiter
	}
	if reads.Load() != 1 {
		t.Error("cancelled waiter dispatched a request")
	}
	unblock()
	if err := <-owner; err != nil {
		t.Fatalf("waiter interrupted the session owner: %v", err)
	}
	if err := client.TestConnection(context.Background()); err != nil || fixture.sessions.Load() != 1 {
		t.Fatalf("cancelled waiter poisoned the shared session: %v, sessions=%d", err, fixture.sessions.Load())
	}
}

func TestJSONRPCPreCancelledCallDoesNotDispatch(t *testing.T) {
	var actions atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		if request.Method == "auth.login_ex" {
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		}
		if request.Method == "app.start" {
			actions.Add(1)
		}
		return protocolFixtureReply{result: map[string]any{"hostname": "cancel-fixture"}}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
	if err := client.TestConnection(context.Background()); err != nil {
		t.Fatal(err)
	}
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	if err := client.StartApp(ctx, "fixture-app"); !errors.Is(err, context.Canceled) {
		t.Fatalf("pre-cancelled action error = %v", err)
	}
	if err := client.TestConnection(context.Background()); err != nil || fixture.sessions.Load() != 1 || actions.Load() != 0 {
		t.Fatalf("pre-cancelled action dispatched or poisoned the session: %v", err)
	}
}

func TestJSONRPCSnapshotContinuesAfterTelemetryTimeout(t *testing.T) {
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		case "system.info":
			return protocolFixtureReply{result: map[string]any{"hostname": "inventory-timeout", "version": "TrueNAS-SCALE-25.10.7", "system_serial": "FIXTURE-1", "physmem": 1024}}
		case "core.subscribe":
			params, _ := request.Params.([]any)
			event, _ := params[0].(string)
			if strings.HasPrefix(event, "app.stats:") {
				// Only live system telemetry is silent in this fixture. App
				// inventory's separate best-effort subscription still replies.
				return protocolFixtureReply{result: "empty-app-stats", notifications: []protocolFixtureNotification{{
					method: "collection_update", params: map[string]any{"collection": event, "fields": []any{}},
				}}}
			}
			return protocolFixtureReply{result: "silent-realtime"}
		case "pool.query":
			return protocolFixtureReply{result: []map[string]any{{"id": 1, "name": "tank", "status": "ONLINE"}}}
		default:
			return protocolFixtureReply{result: []any{}}
		}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 200 * time.Millisecond})
	var snapshot *FixtureSnapshot
	err := awaitConfiguredRPCBudget(t, func(ctx context.Context) error {
		var err error
		snapshot, err = client.FetchSnapshot(ctx)
		return err
	})
	if err != nil || snapshot == nil || snapshot.System.Hostname != "inventory-timeout" || len(snapshot.Pools) != 1 {
		t.Fatalf("optional telemetry timeout prevented usable inventory: %v, %+v", err, snapshot)
	}
	if snapshot.System.Telemetry == nil || snapshot.System.Telemetry.ErrorCategory != "timeout" || snapshot.System.Telemetry.CPU || snapshot.System.Telemetry.Memory {
		t.Fatalf("silent telemetry appeared fresh or lost its timeout: %+v", snapshot.System.Telemetry)
	}
	if fixture.sessions.Load() != 2 || fixture.restRequests.Load() != 0 {
		t.Fatalf("inventory did not recover on RPC after discarding the stream: sessions=%d rest=%d", fixture.sessions.Load(), fixture.restRequests.Load())
	}
}

func TestJSONRPCEmptyAppsDoNotSubscribeToStats(t *testing.T) {
	var appQueries, statsSubscriptions atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		case "app.query":
			if appQueries.Add(1) == 1 {
				return protocolFixtureReply{result: nil}
			}
			return protocolFixtureReply{result: []any{}}
		case "core.subscribe":
			statsSubscriptions.Add(1)
			// Deliberately silent stats on an appliance with no apps. The final
			// client must never issue this request, even with a cancellation-only
			// caller context like the production poller.
			return protocolFixtureReply{result: "unavailable-apps"}
		case "system.info":
			return protocolFixtureReply{result: map[string]any{"hostname": "empty-app-nas", "version": "TrueNAS-SCALE-25.04.2.6"}}
		default:
			t.Errorf("unexpected method %s", request.Method)
			return protocolFixtureReply{close: true}
		}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user", Timeout: 100 * time.Millisecond})
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	for i := 0; i < 2; i++ {
		apps, err := client.GetApps(ctx)
		if err != nil || apps == nil || len(apps) != 0 {
			t.Fatalf("empty app query %d did not preserve an empty successful inventory", i)
		}
	}
	if statsSubscriptions.Load() != 0 {
		t.Fatal("empty inventory still issued a stats subscription")
	}
	if _, err := client.GetSystemInfo(ctx); err != nil {
		t.Fatal(err)
	}
	if fixture.sessions.Load() != 1 || fixture.restRequests.Load() != 0 || !client.TransportStatus().Connected {
		t.Fatal("empty apps discarded the healthy authenticated session or changed transport")
	}
}

func TestLegacyRESTEmptyAppsDoNotNegotiateStats(t *testing.T) {
	var appQueries atomic.Int32
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		t.Errorf("empty legacy app inventory issued RPC method %s", request.Method)
		return protocolFixtureReply{close: true}
	}, func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/api/v2.0/app" {
			t.Errorf("unexpected legacy path %s", r.URL.Path)
			return
		}
		appQueries.Add(1)
		_ = json.NewEncoder(w).Encode([]any{})
	})
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key"})
	// Negotiation is covered separately; isolate the already-selected legacy
	// inventory path here, so no attempted JSON-RPC stats lookup is hidden.
	client.mode = TransportLegacyREST
	apps, err := client.GetApps(context.Background())
	if err != nil || apps == nil || len(apps) != 0 || appQueries.Load() != 1 || fixture.sessions.Load() != 0 {
		t.Fatal("empty legacy app inventory did not stay a single REST read")
	}
}

func TestJSONRPCStreamRetryDiscardsUnusableSecondSession(t *testing.T) {
	for _, failure := range []string{"malformed_event", "empty_subscription", "unsubscribe_error"} {
		t.Run(failure, func(t *testing.T) {
			var subscribes atomic.Int32
			fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
				switch request.Method {
				case "auth.login_ex":
					return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
				case "core.subscribe":
					subscribes.Add(1)
					if session == 1 {
						return protocolFixtureReply{close: true}
					}
					if failure == "empty_subscription" {
						return protocolFixtureReply{result: ""}
					}
					var fields any = []any{map[string]any{"app_name": "fixture-app", "cpu_usage": 3}}
					if failure == "malformed_event" {
						fields = "invalid-fields"
					}
					return protocolFixtureReply{result: "private-subscription-id", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.stats:{\"interval\":2}", "fields": fields}}}}
				case "core.unsubscribe":
					return protocolFixtureReply{err: &trueNASRPCError{Code: -32001, Message: "fixture-method-error"}}
				case "pool.query":
					if session != 3 {
						t.Error("next read reused an unusable second stream session")
					}
					return protocolFixtureReply{result: []any{}}
				default:
					t.Errorf("unexpected method %s", request.Method)
					return protocolFixtureReply{close: true}
				}
			}, nil)
			client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
			if _, err := client.GetAppStats(context.Background()); err == nil {
				t.Fatal("bad second stream session appeared successful")
			}
			if client.TransportStatus().Connected {
				t.Fatal("unusable second stream session remained connected")
			}
			if client.rpc != nil {
				t.Fatal("unusable second stream session was retained")
			}
			if _, err := client.GetPools(context.Background()); err != nil {
				t.Fatal(err)
			}
			if subscribes.Load() != 2 || fixture.sessions.Load() != 3 || fixture.restRequests.Load() != 0 {
				t.Fatal("stream retry/disposal changed its retry limit or downgraded transport")
			}
		})
	}
}

func TestJSONRPCStreamRetryReturnsCompletedLogTail(t *testing.T) {
	fixture := newProtocolFixture(t, func(session int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		case "core.subscribe":
			if session == 1 {
				return protocolFixtureReply{close: true}
			}
			return protocolFixtureReply{result: "fixture-log-sub", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.container_log_follow:{}", "fields": []any{map[string]any{"data": "fixture-line"}}}}}}
		case "pool.query":
			if session != 3 {
				t.Error("timed-out log socket was reused")
			}
			return protocolFixtureReply{result: []any{}}
		default:
			t.Errorf("unexpected method %s", request.Method)
			return protocolFixtureReply{close: true}
		}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "fixture-key", Username: "fixture-user"})
	lines, err := client.GetAppLogs(context.Background(), "fixture-app", "fixture-container", 100)
	if err != nil || len(lines) != 1 || lines[0].Data != "fixture-line" {
		t.Fatal("completed retry lost its log tail or returned a consumed-session sentinel")
	}
	if client.TransportStatus().Connected || client.rpc != nil {
		t.Fatal("completed retry kept a timed-out log socket")
	}
	if _, err := client.GetPools(context.Background()); err != nil {
		t.Fatal(err)
	}
	if fixture.sessions.Load() != 3 || fixture.restRequests.Load() != 0 {
		t.Fatal("next read did not open exactly one fresh modern session")
	}
}

func TestRPCSessionCloseDetails(t *testing.T) {
	for _, tc := range []struct {
		name             string
		err              error
		method, category string
	}{
		{"explicit", nil, "", ""},
		{"idle tail", errRPCStreamSessionConsumed, "app.container_log_follow", "idle_timeout"},
		{"timeout", &RPCTransportError{Method: "pool.query", Phase: "read", Err: context.DeadlineExceeded}, "pool.query", "timeout"},
		{"cancel", &RPCTransportError{Method: "app.start", Phase: "read", Err: context.Canceled}, "app.start", "cancelled"},
		{"transport", &RPCTransportError{Method: "system.info", Phase: "read", Err: errors.New("private-error-text")}, "system.info", "transport_error"},
		{"stream decode", &discardRPCSessionError{method: "app.stats", err: errors.New("private-event-text")}, "app.stats", "protocol_error"},
		{"unsubscribe refusal", &discardRPCSessionError{method: "core.unsubscribe", err: &RPCError{Method: "core.unsubscribe", Message: "private-wire-message"}}, "core.unsubscribe", "method_error"},
	} {
		t.Run(tc.name, func(t *testing.T) {
			method, category := rpcSessionCloseDetails(tc.err)
			if method != tc.method || category != tc.category {
				t.Fatalf("close classification = %s/%s, want %s/%s", method, category, tc.method, tc.category)
			}
		})
	}
}

func captureRPCCloseLogs(t *testing.T) *bytes.Buffer {
	t.Helper()
	var output bytes.Buffer
	previous := log.Logger
	log.Logger = zerolog.New(&output)
	t.Cleanup(func() { log.Logger = previous })
	return &output
}

func rpcCloseLogRecords(t *testing.T, output *bytes.Buffer) []map[string]any {
	t.Helper()
	var records []map[string]any
	decoder := json.NewDecoder(bytes.NewReader(output.Bytes()))
	for decoder.More() {
		var record map[string]any
		if err := decoder.Decode(&record); err != nil {
			t.Fatal("close log is not structured JSON")
		}
		records = append(records, record)
	}
	return records
}

func TestRPCSessionCloseLogIsBoundedAndSecretFree(t *testing.T) {
	output := captureRPCCloseLogs(t)
	fixture := newProtocolFixture(t, func(_ int, request trueNASRPCRequest) protocolFixtureReply {
		switch request.Method {
		case "auth.login_ex":
			return protocolFixtureReply{result: map[string]any{"response_type": "SUCCESS"}}
		case "core.subscribe":
			return protocolFixtureReply{result: "private-subscription-id", notifications: []protocolFixtureNotification{{method: "collection_update", params: map[string]any{"collection": "app.stats:{\"interval\":2}", "fields": []any{}}}}}
		case "core.unsubscribe":
			return protocolFixtureReply{err: &trueNASRPCError{Code: -32001, Message: "private-wire-message private-api-key private-password private-subscription-id"}}
		default:
			return protocolFixtureReply{close: true}
		}
	}, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{APIKey: "private-api-key", Password: "private-password", Username: "private-owner"})
	if _, err := client.GetAppStats(context.Background()); err == nil {
		t.Fatal("fixture did not fail its unsubscribe")
	}
	client.Close()
	records := rpcCloseLogRecords(t, output)
	if len(records) != 1 {
		t.Fatalf("close records = %d, want exactly one for disposal and subsequent Close", len(records))
	}
	record := records[0]
	if record["reason"] != "stream_error" || record["method"] != "core.unsubscribe" || record["category"] != "method_error" || record["component"] != "truenas_rpc" || record["action"] != "close_session" {
		t.Fatal("close log lost its fixed local cause")
	}
	if _, ok := record["session_age"].(float64); !ok {
		t.Fatal("close log lost the authenticated session age")
	}
	for _, private := range []string{"private-api-key", "private-password", "private-owner", "private-wire-message", "private-subscription-id", fixture.server.URL} {
		if bytes.Contains(output.Bytes(), []byte(private)) {
			t.Fatal("close log contains private wire/configuration data")
		}
	}
	for key := range record {
		switch key {
		case "component", "action", "reason", "method", "category", "session_age", "level", "message":
		default:
			t.Fatalf("unexpected close log field %s", key)
		}
	}
}

func TestRPCSessionCloseLogKeepsFirstKeepaliveCause(t *testing.T) {
	output := captureRPCCloseLogs(t)
	fixture := newProtocolFixture(t, func(_ int, _ trueNASRPCRequest) protocolFixtureReply { return protocolFixtureReply{result: true} }, nil)
	client := protocolFixtureClient(t, fixture.server.URL, ClientConfig{})
	conn, err := client.dialRPC(context.Background())
	if err != nil {
		t.Fatal(err)
	}
	rpc := &trueNASRPCClient{conn: conn, nextID: 1, openedAt: time.Now()}
	rpc.startKeepalive(time.Millisecond)
	_ = conn.Close() // Inject a control-write failure, without an RPC payload.
	select {
	case <-rpc.keepaliveDone:
	case <-time.After(time.Second):
		t.Fatal("failed keepalive did not stop")
	}
	rpc.close()
	records := rpcCloseLogRecords(t, output)
	if len(records) != 1 || records[0]["reason"] != "keepalive_write_error" || records[0]["category"] != "transport_error" {
		t.Fatal("later client disposal overwrote or duplicated the first keepalive close cause")
	}
}