File size: 13,966 Bytes
ea775bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/Resinat/Resin/internal/config"
"github.com/Resinat/Resin/internal/service"
)
func newTestServer() *Server {
runtimeCfg := &atomic.Pointer[config.RuntimeConfig]{}
runtimeCfg.Store(config.NewDefaultRuntimeConfig())
envCfg := &config.EnvConfig{
CacheDir: "/tmp/resin/cache",
StateDir: "/tmp/resin/state",
LogDir: "/tmp/resin/log",
ListenAddress: "127.0.0.1",
ResinPort: 2260,
APIMaxBodyBytes: 1 << 20,
MaxLatencyTableEntries: 12,
ProbeConcurrency: 1000,
GeoIPUpdateSchedule: "0 7 * * *",
DefaultPlatformStickyTTL: 7 * 24 * time.Hour,
DefaultPlatformRegexFilters: []string{"^Provider/.*"},
DefaultPlatformRegionFilters: []string{"us", "hk"},
DefaultPlatformReverseProxyMissAction: "TREAT_AS_EMPTY",
DefaultPlatformReverseProxyEmptyAccountBehavior: "ACCOUNT_HEADER_RULE",
DefaultPlatformReverseProxyFixedAccountHeader: "Authorization",
DefaultPlatformAllocationPolicy: "BALANCED",
ProbeTimeout: 15 * time.Second,
ResourceFetchTimeout: 30 * time.Second,
ProxyTransportMaxIdleConns: 1024,
ProxyTransportMaxIdleConnsPerHost: 64,
ProxyTransportIdleConnTimeout: 90 * time.Second,
ProxyBypassRules: []string{"localhost", "127.*"},
RequestLogQueueSize: 8192,
RequestLogQueueFlushBatchSize: 4096,
RequestLogQueueFlushInterval: 5 * time.Minute,
RequestLogDBMaxMB: 512,
RequestLogDBRetainCount: 5,
AdminToken: "test-admin-token",
ProxyToken: "test-proxy-token",
MetricThroughputIntervalSeconds: 1,
MetricThroughputRetentionSeconds: 3600,
MetricBucketSeconds: 3600,
MetricConnectionsIntervalSeconds: 5,
MetricConnectionsRetentionSeconds: 18000,
MetricLeasesIntervalSeconds: 5,
MetricLeasesRetentionSeconds: 18000,
MetricLatencyBinWidthMS: 100,
MetricLatencyBinOverflowMS: 3000,
}
systemInfo := service.SystemInfo{
Version: "1.0.0-test",
GitCommit: "abc123",
BuildTime: "2026-01-01T00:00:00Z",
StartedAt: time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC),
}
return NewServer(0, "test-admin-token", systemInfo, runtimeCfg, envCfg, nil, 1<<20, nil, nil)
}
// --- /healthz ---
func TestHealthz_OK(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]string
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if body["status"] != "ok" {
t.Errorf("status field: got %q, want %q", body["status"], "ok")
}
}
func TestHealthz_NoAuth(t *testing.T) {
// healthz should succeed WITHOUT any auth header
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Errorf("healthz should not require auth, got status %d", rec.Code)
}
}
// --- embedded WebUI ---
func TestWebUI_RootRedirectsToUI(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusFound {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusFound)
}
if location := rec.Header().Get("Location"); location != "/ui/" {
t.Fatalf("location: got %q, want %q", location, "/ui/")
}
}
func TestWebUI_IndexServed(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/ui/", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
if ctype := rec.Header().Get("Content-Type"); !strings.Contains(ctype, "text/html") {
t.Fatalf("content-type: got %q, want contains text/html", ctype)
}
if !strings.Contains(rec.Body.String(), "<div id=\"root\"></div>") {
t.Fatalf("unexpected index body: %q", rec.Body.String())
}
}
func TestWebUI_SPARouteFallback(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/ui/platforms/demo", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
if !strings.Contains(rec.Body.String(), "<div id=\"root\"></div>") {
t.Fatalf("unexpected fallback body: %q", rec.Body.String())
}
}
func TestWebUI_MissingAsset404(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/ui/assets/does-not-exist.js", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusNotFound)
}
}
func TestWebUI_LegacyRootPathNoLongerServed(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/dashboard", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusNotFound)
}
}
// --- /api/v1/system/info ---
func TestSystemInfo_OK(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/info", nil)
req.Header.Set("Authorization", "Bearer test-admin-token")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if body["version"] != "1.0.0-test" {
t.Errorf("version: got %q, want %q", body["version"], "1.0.0-test")
}
if body["git_commit"] != "abc123" {
t.Errorf("git_commit: got %q, want %q", body["git_commit"], "abc123")
}
if _, ok := body["started_at"]; !ok {
t.Error("missing started_at field")
}
}
func TestSystemInfo_RequiresAuth(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/info", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
// --- /api/v1/system/config ---
func TestSystemConfig_OK(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config", nil)
req.Header.Set("Authorization", "Bearer test-admin-token")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
// Check some default values
if body["request_log_enabled"] != true {
t.Errorf("request_log_enabled: got %v, want true", body["request_log_enabled"])
}
// JSON numbers are float64
if maxFail, ok := body["max_consecutive_failures"].(float64); !ok || maxFail != 3 {
t.Errorf("max_consecutive_failures: got %v, want 3", body["max_consecutive_failures"])
}
if _, ok := body["default_platform_config"]; ok {
t.Error("default_platform_config should not be exposed in /system/config")
}
if _, ok := body["probe_timeout"]; ok {
t.Error("probe_timeout should not be exposed in /system/config")
}
if _, ok := body["resource_fetch_timeout"]; ok {
t.Error("resource_fetch_timeout should not be exposed in /system/config")
}
if _, ok := body["request_log_db_max_mb"]; ok {
t.Error("request_log_db_max_mb should be env-only and not exposed in /system/config")
}
if _, ok := body["request_log_db_retain_count"]; ok {
t.Error("request_log_db_retain_count should be env-only and not exposed in /system/config")
}
if _, ok := body["request_log_batch_size"]; ok {
t.Error("request_log_batch_size should be env-only and not exposed in /system/config")
}
if _, ok := body["metric_latency_bin_ms"]; ok {
t.Error("metric_latency_bin_ms should be env-only and not exposed in /system/config")
}
if _, ok := body["metric_latency_overflow_ms"]; ok {
t.Error("metric_latency_overflow_ms should be env-only and not exposed in /system/config")
}
if _, ok := body["metric_bucket_seconds"]; ok {
t.Error("metric_bucket_seconds should be env-only and not exposed in /system/config")
}
if _, ok := body["metric_realtime_capacity"]; ok {
t.Error("metric_realtime_capacity should be env-only and not exposed in /system/config")
}
if _, ok := body["metric_sample_interval_sec"]; ok {
t.Error("metric_sample_interval_sec should be env-only and not exposed in /system/config")
}
}
func TestSystemConfig_RequiresAuth(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
// --- /api/v1/system/config/env ---
func TestSystemEnvConfig_OK(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config/env", nil)
req.Header.Set("Authorization", "Bearer test-admin-token")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if body["cache_dir"] != "/tmp/resin/cache" {
t.Errorf("cache_dir: got %q, want %q", body["cache_dir"], "/tmp/resin/cache")
}
if body["listen_address"] != "127.0.0.1" {
t.Errorf("listen_address: got %q, want %q", body["listen_address"], "127.0.0.1")
}
if body["default_platform_sticky_ttl"] != "168h0m0s" {
t.Errorf("default_platform_sticky_ttl: got %q, want %q", body["default_platform_sticky_ttl"], "168h0m0s")
}
if body["default_platform_reverse_proxy_empty_account_behavior"] != "ACCOUNT_HEADER_RULE" {
t.Errorf(
"default_platform_reverse_proxy_empty_account_behavior: got %v, want ACCOUNT_HEADER_RULE",
body["default_platform_reverse_proxy_empty_account_behavior"],
)
}
if body["default_platform_reverse_proxy_fixed_account_header"] != "Authorization" {
t.Errorf(
"default_platform_reverse_proxy_fixed_account_header: got %v, want Authorization",
body["default_platform_reverse_proxy_fixed_account_header"],
)
}
if body["probe_timeout"] != "15s" {
t.Errorf("probe_timeout: got %q, want %q", body["probe_timeout"], "15s")
}
if body["admin_token_set"] != true {
t.Errorf("admin_token_set: got %v, want true", body["admin_token_set"])
}
if body["proxy_token_set"] != true {
t.Errorf("proxy_token_set: got %v, want true", body["proxy_token_set"])
}
if body["admin_token_weak"] != false {
t.Errorf("admin_token_weak: got %v, want false", body["admin_token_weak"])
}
if body["proxy_token_weak"] != false {
t.Errorf("proxy_token_weak: got %v, want false", body["proxy_token_weak"])
}
if rules, ok := body["proxy_bypass_rules"].([]any); !ok || len(rules) != 2 || rules[0] != "localhost" || rules[1] != "127.*" {
t.Errorf("proxy_bypass_rules: got %#v, want [localhost 127.*]", body["proxy_bypass_rules"])
}
if _, ok := body["admin_token"]; ok {
t.Error("admin_token should not be exposed in /system/config/env")
}
if _, ok := body["proxy_token"]; ok {
t.Error("proxy_token should not be exposed in /system/config/env")
}
}
func TestSystemEnvConfig_RequiresAuth(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config/env", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
// --- /api/v1/system/config/default ---
func TestSystemDefaultConfig_OK(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config/default", nil)
req.Header.Set("Authorization", "Bearer test-admin-token")
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status: got %d, want %d", rec.Code, http.StatusOK)
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if body["request_log_enabled"] != true {
t.Errorf("request_log_enabled: got %v, want true", body["request_log_enabled"])
}
if maxFail, ok := body["max_consecutive_failures"].(float64); !ok || maxFail != 3 {
t.Errorf("max_consecutive_failures: got %v, want 3", body["max_consecutive_failures"])
}
}
func TestSystemDefaultConfig_RequiresAuth(t *testing.T) {
srv := newTestServer()
req := httptest.NewRequest(http.MethodGet, "/api/v1/system/config/default", nil)
rec := httptest.NewRecorder()
srv.Handler().ServeHTTP(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Errorf("status: got %d, want %d", rec.Code, http.StatusUnauthorized)
}
}
|