| 1 |
// Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package caddy |
| 16 |
|
| 17 |
import ( |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"crypto" |
| 21 |
"crypto/tls" |
| 22 |
"crypto/x509" |
| 23 |
"encoding/json" |
| 24 |
"errors" |
| 25 |
"fmt" |
| 26 |
"maps" |
| 27 |
"net/http" |
| 28 |
"net/http/httptest" |
| 29 |
"os" |
| 30 |
"reflect" |
| 31 |
"sync" |
| 32 |
"testing" |
| 33 |
"time" |
| 34 |
|
| 35 |
"github.com/caddyserver/certmagic" |
| 36 |
"github.com/prometheus/client_golang/prometheus" |
| 37 |
dto "github.com/prometheus/client_model/go" |
| 38 |
"go.uber.org/zap" |
| 39 |
"go.uber.org/zap/zaptest/observer" |
| 40 |
) |
| 41 |
|
| 42 |
var testCfg = []byte(`{ |
| 43 |
"apps": { |
| 44 |
"http": { |
| 45 |
"servers": { |
| 46 |
"myserver": { |
| 47 |
"listen": ["tcp/localhost:8080-8084"], |
| 48 |
"read_timeout": "30s" |
| 49 |
}, |
| 50 |
"yourserver": { |
| 51 |
"listen": ["127.0.0.1:5000"], |
| 52 |
"read_header_timeout": "15s" |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
} |
| 58 |
`) |
| 59 |
|
| 60 |
type testAdminPublicKey string |
| 61 |
|
| 62 |
func (k testAdminPublicKey) Equal(x crypto.PublicKey) bool { |
| 63 |
other, ok := x.(testAdminPublicKey) |
| 64 |
return ok && k == other |
| 65 |
} |
| 66 |
|
| 67 |
func TestUnsyncedConfigAccess(t *testing.T) { |
| 68 |
// each test is performed in sequence, so |
| 69 |
// each change builds on the previous ones; |
| 70 |
// the config is not reset between tests |
| 71 |
for i, tc := range []struct { |
| 72 |
method string |
| 73 |
path string // rawConfigKey will be prepended |
| 74 |
payload string |
| 75 |
expect string // JSON representation of what the whole config is expected to be after the request |
| 76 |
shouldErr bool |
| 77 |
}{ |
| 78 |
{ |
| 79 |
method: "POST", |
| 80 |
path: "", |
| 81 |
payload: `{"foo": "bar", "list": ["a", "b", "c"]}`, // starting value |
| 82 |
expect: `{"foo": "bar", "list": ["a", "b", "c"]}`, |
| 83 |
}, |
| 84 |
{ |
| 85 |
method: "POST", |
| 86 |
path: "/foo", |
| 87 |
payload: `"jet"`, |
| 88 |
expect: `{"foo": "jet", "list": ["a", "b", "c"]}`, |
| 89 |
}, |
| 90 |
{ |
| 91 |
method: "POST", |
| 92 |
path: "/bar", |
| 93 |
payload: `{"aa": "bb", "qq": "zz"}`, |
| 94 |
expect: `{"foo": "jet", "bar": {"aa": "bb", "qq": "zz"}, "list": ["a", "b", "c"]}`, |
| 95 |
}, |
| 96 |
{ |
| 97 |
method: "DELETE", |
| 98 |
path: "/bar/qq", |
| 99 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c"]}`, |
| 100 |
}, |
| 101 |
{ |
| 102 |
method: "DELETE", |
| 103 |
path: "/bar/qq", |
| 104 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c"]}`, |
| 105 |
shouldErr: true, |
| 106 |
}, |
| 107 |
{ |
| 108 |
method: "POST", |
| 109 |
path: "/list", |
| 110 |
payload: `"e"`, |
| 111 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c", "e"]}`, |
| 112 |
}, |
| 113 |
{ |
| 114 |
method: "PUT", |
| 115 |
path: "/list/3", |
| 116 |
payload: `"d"`, |
| 117 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c", "d", "e"]}`, |
| 118 |
}, |
| 119 |
{ |
| 120 |
method: "DELETE", |
| 121 |
path: "/list/3", |
| 122 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c", "e"]}`, |
| 123 |
}, |
| 124 |
{ |
| 125 |
method: "PATCH", |
| 126 |
path: "/list/3", |
| 127 |
payload: `"d"`, |
| 128 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c", "d"]}`, |
| 129 |
}, |
| 130 |
{ |
| 131 |
method: "POST", |
| 132 |
path: "/list/...", |
| 133 |
payload: `["e", "f", "g"]`, |
| 134 |
expect: `{"foo": "jet", "bar": {"aa": "bb"}, "list": ["a", "b", "c", "d", "e", "f", "g"]}`, |
| 135 |
}, |
| 136 |
} { |
| 137 |
err := unsyncedConfigAccess(tc.method, rawConfigKey+tc.path, []byte(tc.payload), nil) |
| 138 |
|
| 139 |
if tc.shouldErr && err == nil { |
| 140 |
t.Fatalf("Test %d: Expected error return value, but got: %v", i, err) |
| 141 |
} |
| 142 |
if !tc.shouldErr && err != nil { |
| 143 |
t.Fatalf("Test %d: Should not have had error return value, but got: %v", i, err) |
| 144 |
} |
| 145 |
|
| 146 |
// decode the expected config so we can do a convenient DeepEqual |
| 147 |
var expectedDecoded any |
| 148 |
err = json.Unmarshal([]byte(tc.expect), &expectedDecoded) |
| 149 |
if err != nil { |
| 150 |
t.Fatalf("Test %d: Unmarshaling expected config: %v", i, err) |
| 151 |
} |
| 152 |
|
| 153 |
// make sure the resulting config is as we expect it |
| 154 |
if !reflect.DeepEqual(rawCfg[rawConfigKey], expectedDecoded) { |
| 155 |
t.Fatalf("Test %d:\nExpected:\n\t%#v\nActual:\n\t%#v", |
| 156 |
i, expectedDecoded, rawCfg[rawConfigKey]) |
| 157 |
} |
| 158 |
} |
| 159 |
} |
| 160 |
|
| 161 |
// TestLoadConcurrent exercises Load under concurrent conditions |
| 162 |
// and is most useful under test with `-race` enabled. |
| 163 |
func TestLoadConcurrent(t *testing.T) { |
| 164 |
var wg sync.WaitGroup |
| 165 |
|
| 166 |
for i := 0; i < 100; i++ { |
| 167 |
wg.Go(func() { |
| 168 |
_ = Load(testCfg, true) |
| 169 |
}) |
| 170 |
} |
| 171 |
wg.Wait() |
| 172 |
} |
| 173 |
|
| 174 |
type fooModule struct { |
| 175 |
IntField int |
| 176 |
StrField string |
| 177 |
} |
| 178 |
|
| 179 |
func (fooModule) CaddyModule() ModuleInfo { |
| 180 |
return ModuleInfo{ |
| 181 |
ID: "foo", |
| 182 |
New: func() Module { return new(fooModule) }, |
| 183 |
} |
| 184 |
} |
| 185 |
func (fooModule) Start() error { return nil } |
| 186 |
func (fooModule) Stop() error { return nil } |
| 187 |
|
| 188 |
func TestETags(t *testing.T) { |
| 189 |
RegisterModule(fooModule{}) |
| 190 |
|
| 191 |
if err := Load([]byte(`{"admin": {"listen": "localhost:2999"}, "apps": {"foo": {"strField": "abc", "intField": 0}}}`), true); err != nil { |
| 192 |
t.Fatalf("loading: %s", err) |
| 193 |
} |
| 194 |
|
| 195 |
const key = "/" + rawConfigKey + "/apps/foo" |
| 196 |
|
| 197 |
// try update the config with the wrong etag |
| 198 |
err := changeConfig(http.MethodPost, key, []byte(`{"strField": "abc", "intField": 1}}`), fmt.Sprintf(`"/%s not_an_etag"`, rawConfigKey), false) |
| 199 |
if apiErr, ok := err.(APIError); !ok || apiErr.HTTPStatus != http.StatusPreconditionFailed { |
| 200 |
t.Fatalf("expected precondition failed; got %v", err) |
| 201 |
} |
| 202 |
|
| 203 |
// get the etag |
| 204 |
hash := etagHasher() |
| 205 |
if err := readConfig(key, hash); err != nil { |
| 206 |
t.Fatalf("reading: %s", err) |
| 207 |
} |
| 208 |
|
| 209 |
// do the same update with the correct key |
| 210 |
err = changeConfig(http.MethodPost, key, []byte(`{"strField": "abc", "intField": 1}`), makeEtag(key, hash), false) |
| 211 |
if err != nil { |
| 212 |
t.Fatalf("expected update to work; got %v", err) |
| 213 |
} |
| 214 |
|
| 215 |
// now try another update. The hash should no longer match and we should get precondition failed |
| 216 |
err = changeConfig(http.MethodPost, key, []byte(`{"strField": "abc", "intField": 2}`), makeEtag(key, hash), false) |
| 217 |
if apiErr, ok := err.(APIError); !ok || apiErr.HTTPStatus != http.StatusPreconditionFailed { |
| 218 |
t.Fatalf("expected precondition failed; got %v", err) |
| 219 |
} |
| 220 |
} |
| 221 |
|
| 222 |
func BenchmarkLoad(b *testing.B) { |
| 223 |
for b.Loop() { |
| 224 |
Load(testCfg, true) |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
func TestAdminHandlerErrorHandling(t *testing.T) { |
| 229 |
initAdminMetrics() |
| 230 |
|
| 231 |
handler := adminHandler{ |
| 232 |
mux: http.NewServeMux(), |
| 233 |
} |
| 234 |
|
| 235 |
handler.mux.Handle("/error", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 236 |
err := fmt.Errorf("test error") |
| 237 |
handler.handleError(w, r, err) |
| 238 |
})) |
| 239 |
|
| 240 |
req := httptest.NewRequest(http.MethodGet, "/error", nil) |
| 241 |
rr := httptest.NewRecorder() |
| 242 |
|
| 243 |
handler.ServeHTTP(rr, req) |
| 244 |
|
| 245 |
if rr.Code == http.StatusOK { |
| 246 |
t.Error("expected error response, got success") |
| 247 |
} |
| 248 |
|
| 249 |
var apiErr APIError |
| 250 |
if err := json.NewDecoder(rr.Body).Decode(&apiErr); err != nil { |
| 251 |
t.Fatalf("decoding response: %v", err) |
| 252 |
} |
| 253 |
if apiErr.Message != "test error" { |
| 254 |
t.Errorf("expected error message 'test error', got '%s'", apiErr.Message) |
| 255 |
} |
| 256 |
} |
| 257 |
|
| 258 |
func TestAdminHandlerServeHTTPRedactsSensitiveHeadersInLogs(t *testing.T) { |
| 259 |
core, logs := observer.New(zap.InfoLevel) |
| 260 |
|
| 261 |
defaultLoggerMu.Lock() |
| 262 |
origLogger := defaultLogger.logger |
| 263 |
defaultLogger.logger = zap.New(core) |
| 264 |
defaultLoggerMu.Unlock() |
| 265 |
t.Cleanup(func() { |
| 266 |
defaultLoggerMu.Lock() |
| 267 |
defaultLogger.logger = origLogger |
| 268 |
defaultLoggerMu.Unlock() |
| 269 |
}) |
| 270 |
|
| 271 |
handler := adminHandler{ |
| 272 |
mux: http.NewServeMux(), |
| 273 |
} |
| 274 |
req := httptest.NewRequest(http.MethodGet, "/", nil) |
| 275 |
req.Header.Set("Authorization", "Bearer secret") |
| 276 |
req.Header.Set("Cookie", "session=secret") |
| 277 |
req.Header.Set("X-Test", "ok") |
| 278 |
rr := httptest.NewRecorder() |
| 279 |
|
| 280 |
handler.ServeHTTP(rr, req) |
| 281 |
|
| 282 |
if logs.Len() == 0 { |
| 283 |
t.Fatal("expected request log entry") |
| 284 |
} |
| 285 |
|
| 286 |
ctx := logs.All()[0].ContextMap() |
| 287 |
headers, ok := ctx["headers"].(map[string]any) |
| 288 |
if !ok { |
| 289 |
t.Fatalf("expected headers field in log context, got %T", ctx["headers"]) |
| 290 |
} |
| 291 |
|
| 292 |
if got := headers["Authorization"]; !reflect.DeepEqual(got, []any{"REDACTED"}) { |
| 293 |
t.Fatalf("expected redacted Authorization header, got %#v", got) |
| 294 |
} |
| 295 |
if got := headers["Cookie"]; !reflect.DeepEqual(got, []any{"REDACTED"}) { |
| 296 |
t.Fatalf("expected redacted Cookie header, got %#v", got) |
| 297 |
} |
| 298 |
if got := headers["X-Test"]; !reflect.DeepEqual(got, []any{"ok"}) { |
| 299 |
t.Fatalf("expected X-Test header to remain visible, got %#v", got) |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
func initAdminMetrics() { |
| 304 |
if adminMetrics.requestErrors != nil { |
| 305 |
prometheus.Unregister(adminMetrics.requestErrors) |
| 306 |
} |
| 307 |
if adminMetrics.requestCount != nil { |
| 308 |
prometheus.Unregister(adminMetrics.requestCount) |
| 309 |
} |
| 310 |
|
| 311 |
adminMetrics.requestErrors = prometheus.NewCounterVec(prometheus.CounterOpts{ |
| 312 |
Namespace: "caddy", |
| 313 |
Subsystem: "admin_http", |
| 314 |
Name: "request_errors_total", |
| 315 |
Help: "Number of errors that occurred handling admin endpoint requests", |
| 316 |
}, []string{"handler", "path", "method"}) |
| 317 |
|
| 318 |
adminMetrics.requestCount = prometheus.NewCounterVec(prometheus.CounterOpts{ |
| 319 |
Namespace: "caddy", |
| 320 |
Subsystem: "admin_http", |
| 321 |
Name: "requests_total", |
| 322 |
Help: "Count of requests to the admin endpoint", |
| 323 |
}, []string{"handler", "path", "code", "method"}) // Added code and method labels |
| 324 |
|
| 325 |
prometheus.MustRegister(adminMetrics.requestErrors) |
| 326 |
prometheus.MustRegister(adminMetrics.requestCount) |
| 327 |
} |
| 328 |
|
| 329 |
func TestAdminHandlerBuiltinRouteErrors(t *testing.T) { |
| 330 |
initAdminMetrics() |
| 331 |
|
| 332 |
cfg := &Config{ |
| 333 |
Admin: &AdminConfig{ |
| 334 |
Listen: "localhost:2019", |
| 335 |
}, |
| 336 |
} |
| 337 |
|
| 338 |
// Build the admin handler directly (no listener active) |
| 339 |
addr, err := ParseNetworkAddress("localhost:2019") |
| 340 |
if err != nil { |
| 341 |
t.Fatalf("Failed to parse address: %v", err) |
| 342 |
} |
| 343 |
handler, err := cfg.Admin.newAdminHandler(addr, false, Context{}) |
| 344 |
if err != nil { |
| 345 |
t.Fatalf("Failed to create admin handler: %v", err) |
| 346 |
} |
| 347 |
|
| 348 |
tests := []struct { |
| 349 |
name string |
| 350 |
path string |
| 351 |
method string |
| 352 |
expectedStatus int |
| 353 |
}{ |
| 354 |
{ |
| 355 |
name: "stop endpoint wrong method", |
| 356 |
path: "/stop", |
| 357 |
method: http.MethodGet, |
| 358 |
expectedStatus: http.StatusMethodNotAllowed, |
| 359 |
}, |
| 360 |
{ |
| 361 |
name: "config endpoint wrong content-type", |
| 362 |
path: "/config/", |
| 363 |
method: http.MethodPost, |
| 364 |
expectedStatus: http.StatusBadRequest, |
| 365 |
}, |
| 366 |
{ |
| 367 |
name: "config ID missing ID", |
| 368 |
path: "/id/", |
| 369 |
method: http.MethodGet, |
| 370 |
expectedStatus: http.StatusBadRequest, |
| 371 |
}, |
| 372 |
} |
| 373 |
|
| 374 |
for _, test := range tests { |
| 375 |
t.Run(test.name, func(t *testing.T) { |
| 376 |
req := httptest.NewRequest(test.method, fmt.Sprintf("http://localhost:2019%s", test.path), nil) |
| 377 |
rr := httptest.NewRecorder() |
| 378 |
|
| 379 |
handler.ServeHTTP(rr, req) |
| 380 |
|
| 381 |
if rr.Code != test.expectedStatus { |
| 382 |
t.Errorf("expected status %d but got %d", test.expectedStatus, rr.Code) |
| 383 |
} |
| 384 |
|
| 385 |
metricValue := testGetMetricValue(map[string]string{ |
| 386 |
"path": test.path, |
| 387 |
"handler": "admin", |
| 388 |
"method": test.method, |
| 389 |
}) |
| 390 |
if metricValue != 1 { |
| 391 |
t.Errorf("expected error metric to be incremented once, got %v", metricValue) |
| 392 |
} |
| 393 |
}) |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
func testGetMetricValue(labels map[string]string) float64 { |
| 398 |
promLabels := prometheus.Labels{} |
| 399 |
maps.Copy(promLabels, labels) |
| 400 |
|
| 401 |
metric, err := adminMetrics.requestErrors.GetMetricWith(promLabels) |
| 402 |
if err != nil { |
| 403 |
return 0 |
| 404 |
} |
| 405 |
|
| 406 |
pb := &dto.Metric{} |
| 407 |
metric.Write(pb) |
| 408 |
return pb.GetCounter().GetValue() |
| 409 |
} |
| 410 |
|
| 411 |
type mockRouter struct { |
| 412 |
routes []AdminRoute |
| 413 |
} |
| 414 |
|
| 415 |
func (m mockRouter) Routes() []AdminRoute { |
| 416 |
return m.routes |
| 417 |
} |
| 418 |
|
| 419 |
type mockModule struct { |
| 420 |
mockRouter |
| 421 |
} |
| 422 |
|
| 423 |
func (m *mockModule) CaddyModule() ModuleInfo { |
| 424 |
return ModuleInfo{ |
| 425 |
ID: "admin.api.mock", |
| 426 |
New: func() Module { |
| 427 |
mm := &mockModule{ |
| 428 |
mockRouter: mockRouter{ |
| 429 |
routes: m.routes, |
| 430 |
}, |
| 431 |
} |
| 432 |
return mm |
| 433 |
}, |
| 434 |
} |
| 435 |
} |
| 436 |
|
| 437 |
func TestNewAdminHandlerRouterRegistration(t *testing.T) { |
| 438 |
originalModules := make(map[string]ModuleInfo) |
| 439 |
maps.Copy(originalModules, modules) |
| 440 |
defer func() { |
| 441 |
modules = originalModules |
| 442 |
}() |
| 443 |
|
| 444 |
mockRoute := AdminRoute{ |
| 445 |
Pattern: "/mock", |
| 446 |
Handler: AdminHandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 447 |
w.WriteHeader(http.StatusOK) |
| 448 |
return nil |
| 449 |
}), |
| 450 |
} |
| 451 |
|
| 452 |
mock := &mockModule{ |
| 453 |
mockRouter: mockRouter{ |
| 454 |
routes: []AdminRoute{mockRoute}, |
| 455 |
}, |
| 456 |
} |
| 457 |
RegisterModule(mock) |
| 458 |
|
| 459 |
addr, err := ParseNetworkAddress("localhost:2019") |
| 460 |
if err != nil { |
| 461 |
t.Fatalf("Failed to parse address: %v", err) |
| 462 |
} |
| 463 |
|
| 464 |
admin := &AdminConfig{ |
| 465 |
EnforceOrigin: false, |
| 466 |
} |
| 467 |
handler, err := admin.newAdminHandler(addr, false, Context{}) |
| 468 |
if err != nil { |
| 469 |
t.Fatalf("Failed to create admin handler: %v", err) |
| 470 |
} |
| 471 |
|
| 472 |
req := httptest.NewRequest("GET", "/mock", nil) |
| 473 |
req.Host = "localhost:2019" |
| 474 |
rr := httptest.NewRecorder() |
| 475 |
|
| 476 |
handler.ServeHTTP(rr, req) |
| 477 |
|
| 478 |
if rr.Code != http.StatusOK { |
| 479 |
t.Errorf("Expected status code %d but got %d", http.StatusOK, rr.Code) |
| 480 |
t.Logf("Response body: %s", rr.Body.String()) |
| 481 |
} |
| 482 |
} |
| 483 |
|
| 484 |
type mockProvisionableRouter struct { |
| 485 |
mockRouter |
| 486 |
provisionErr error |
| 487 |
provisioned bool |
| 488 |
} |
| 489 |
|
| 490 |
func (m *mockProvisionableRouter) Provision(Context) error { |
| 491 |
m.provisioned = true |
| 492 |
return m.provisionErr |
| 493 |
} |
| 494 |
|
| 495 |
type mockProvisionableModule struct { |
| 496 |
*mockProvisionableRouter |
| 497 |
} |
| 498 |
|
| 499 |
func (m *mockProvisionableModule) CaddyModule() ModuleInfo { |
| 500 |
return ModuleInfo{ |
| 501 |
ID: "admin.api.mock_provision", |
| 502 |
New: func() Module { |
| 503 |
mm := &mockProvisionableModule{ |
| 504 |
mockProvisionableRouter: &mockProvisionableRouter{ |
| 505 |
mockRouter: m.mockRouter, |
| 506 |
provisionErr: m.provisionErr, |
| 507 |
}, |
| 508 |
} |
| 509 |
return mm |
| 510 |
}, |
| 511 |
} |
| 512 |
} |
| 513 |
|
| 514 |
func TestAdminRouterProvisioning(t *testing.T) { |
| 515 |
tests := []struct { |
| 516 |
name string |
| 517 |
provisionErr error |
| 518 |
wantErr bool |
| 519 |
}{ |
| 520 |
{ |
| 521 |
name: "successful provisioning", |
| 522 |
provisionErr: nil, |
| 523 |
wantErr: false, |
| 524 |
}, |
| 525 |
{ |
| 526 |
name: "provisioning error", |
| 527 |
provisionErr: fmt.Errorf("provision failed"), |
| 528 |
wantErr: true, |
| 529 |
}, |
| 530 |
} |
| 531 |
|
| 532 |
for _, test := range tests { |
| 533 |
t.Run(test.name, func(t *testing.T) { |
| 534 |
originalModules := make(map[string]ModuleInfo) |
| 535 |
maps.Copy(originalModules, modules) |
| 536 |
defer func() { |
| 537 |
modules = originalModules |
| 538 |
}() |
| 539 |
|
| 540 |
mockRoute := AdminRoute{ |
| 541 |
Pattern: "/mock", |
| 542 |
Handler: AdminHandlerFunc(func(w http.ResponseWriter, r *http.Request) error { |
| 543 |
return nil |
| 544 |
}), |
| 545 |
} |
| 546 |
|
| 547 |
// Create provisionable module |
| 548 |
mock := &mockProvisionableModule{ |
| 549 |
mockProvisionableRouter: &mockProvisionableRouter{ |
| 550 |
mockRouter: mockRouter{ |
| 551 |
routes: []AdminRoute{mockRoute}, |
| 552 |
}, |
| 553 |
provisionErr: test.provisionErr, |
| 554 |
}, |
| 555 |
} |
| 556 |
RegisterModule(mock) |
| 557 |
|
| 558 |
admin := &AdminConfig{} |
| 559 |
addr, err := ParseNetworkAddress("localhost:2019") |
| 560 |
if err != nil { |
| 561 |
t.Fatalf("Failed to parse address: %v", err) |
| 562 |
} |
| 563 |
|
| 564 |
_, err = admin.newAdminHandler(addr, false, Context{}) |
| 565 |
|
| 566 |
if test.wantErr { |
| 567 |
if err == nil { |
| 568 |
t.Error("Expected error but got nil") |
| 569 |
} |
| 570 |
} else { |
| 571 |
if err != nil { |
| 572 |
t.Errorf("Expected no error but got: %v", err) |
| 573 |
} |
| 574 |
} |
| 575 |
}) |
| 576 |
} |
| 577 |
} |
| 578 |
|
| 579 |
func TestAllowedOriginsUnixSocket(t *testing.T) { |
| 580 |
// see comment in allowedOrigins() as to why we do not fill out allowed origins for UDS |
| 581 |
tests := []struct { |
| 582 |
name string |
| 583 |
addr NetworkAddress |
| 584 |
origins []string |
| 585 |
expectOrigins []string |
| 586 |
}{ |
| 587 |
{ |
| 588 |
name: "unix socket with default origins", |
| 589 |
addr: NetworkAddress{ |
| 590 |
Network: "unix", |
| 591 |
Host: "/tmp/caddy.sock", |
| 592 |
}, |
| 593 |
origins: nil, // default origins |
| 594 |
expectOrigins: []string{}, |
| 595 |
}, |
| 596 |
{ |
| 597 |
name: "unix socket with custom origins", |
| 598 |
addr: NetworkAddress{ |
| 599 |
Network: "unix", |
| 600 |
Host: "/tmp/caddy.sock", |
| 601 |
}, |
| 602 |
origins: []string{"example.com"}, |
| 603 |
expectOrigins: []string{ |
| 604 |
"example.com", |
| 605 |
}, |
| 606 |
}, |
| 607 |
{ |
| 608 |
name: "tcp socket on localhost gets all loopback addresses", |
| 609 |
addr: NetworkAddress{ |
| 610 |
Network: "tcp", |
| 611 |
Host: "localhost", |
| 612 |
StartPort: 2019, |
| 613 |
EndPort: 2019, |
| 614 |
}, |
| 615 |
origins: nil, |
| 616 |
expectOrigins: []string{ |
| 617 |
"localhost:2019", |
| 618 |
"[::1]:2019", |
| 619 |
"127.0.0.1:2019", |
| 620 |
}, |
| 621 |
}, |
| 622 |
} |
| 623 |
|
| 624 |
for i, test := range tests { |
| 625 |
t.Run(test.name, func(t *testing.T) { |
| 626 |
admin := AdminConfig{ |
| 627 |
Origins: test.origins, |
| 628 |
} |
| 629 |
|
| 630 |
got := admin.allowedOrigins(test.addr) |
| 631 |
|
| 632 |
var gotOrigins []string |
| 633 |
for _, u := range got { |
| 634 |
gotOrigins = append(gotOrigins, u.Host) |
| 635 |
} |
| 636 |
|
| 637 |
if len(gotOrigins) != len(test.expectOrigins) { |
| 638 |
t.Errorf("%d: Expected %d origins but got %d", i, len(test.expectOrigins), len(gotOrigins)) |
| 639 |
return |
| 640 |
} |
| 641 |
|
| 642 |
expectMap := make(map[string]struct{}) |
| 643 |
for _, origin := range test.expectOrigins { |
| 644 |
expectMap[origin] = struct{}{} |
| 645 |
} |
| 646 |
|
| 647 |
gotMap := make(map[string]struct{}) |
| 648 |
for _, origin := range gotOrigins { |
| 649 |
gotMap[origin] = struct{}{} |
| 650 |
} |
| 651 |
|
| 652 |
if !reflect.DeepEqual(expectMap, gotMap) { |
| 653 |
t.Errorf("%d: Origins mismatch.\nExpected: %v\nGot: %v", i, test.expectOrigins, gotOrigins) |
| 654 |
} |
| 655 |
}) |
| 656 |
} |
| 657 |
} |
| 658 |
|
| 659 |
func TestRemoteAdminAccessControlPathSegmentMatching(t *testing.T) { |
| 660 |
const authorizedKey testAdminPublicKey = "authorized" |
| 661 |
peerCert := &x509.Certificate{PublicKey: authorizedKey} |
| 662 |
|
| 663 |
tests := []struct { |
| 664 |
name string |
| 665 |
allowedPath string |
| 666 |
requestPath string |
| 667 |
wantErr bool |
| 668 |
}{ |
| 669 |
{ |
| 670 |
name: "exact path", |
| 671 |
allowedPath: "/pki/ca/prod", |
| 672 |
requestPath: "/pki/ca/prod", |
| 673 |
wantErr: false, |
| 674 |
}, |
| 675 |
{ |
| 676 |
name: "subpath", |
| 677 |
allowedPath: "/pki/ca/prod", |
| 678 |
requestPath: "/pki/ca/prod/certificates", |
| 679 |
wantErr: false, |
| 680 |
}, |
| 681 |
{ |
| 682 |
name: "trailing slash subpath", |
| 683 |
allowedPath: "/pki/ca/prod/", |
| 684 |
requestPath: "/pki/ca/prod/certificates", |
| 685 |
wantErr: false, |
| 686 |
}, |
| 687 |
{ |
| 688 |
name: "sibling with shared prefix", |
| 689 |
allowedPath: "/pki/ca/prod", |
| 690 |
requestPath: "/pki/ca/prod-backup", |
| 691 |
wantErr: true, |
| 692 |
}, |
| 693 |
{ |
| 694 |
name: "same segment plus digit", |
| 695 |
allowedPath: "/pki/ca/prod", |
| 696 |
requestPath: "/pki/ca/prod1", |
| 697 |
wantErr: true, |
| 698 |
}, |
| 699 |
{ |
| 700 |
name: "root path", |
| 701 |
allowedPath: "/", |
| 702 |
requestPath: "/pki/ca/prod", |
| 703 |
wantErr: false, |
| 704 |
}, |
| 705 |
} |
| 706 |
|
| 707 |
for i, test := range tests { |
| 708 |
t.Run(test.name, func(t *testing.T) { |
| 709 |
remote := RemoteAdmin{ |
| 710 |
AccessControl: []*AdminAccess{ |
| 711 |
{ |
| 712 |
Permissions: []AdminPermissions{ |
| 713 |
{ |
| 714 |
Methods: []string{http.MethodGet}, |
| 715 |
Paths: []string{test.allowedPath}, |
| 716 |
}, |
| 717 |
}, |
| 718 |
publicKeys: []crypto.PublicKey{authorizedKey}, |
| 719 |
}, |
| 720 |
}, |
| 721 |
} |
| 722 |
|
| 723 |
req := httptest.NewRequest(http.MethodGet, "https://localhost:2021"+test.requestPath, nil) |
| 724 |
req.TLS = &tls.ConnectionState{ |
| 725 |
VerifiedChains: [][]*x509.Certificate{{peerCert}}, |
| 726 |
} |
| 727 |
|
| 728 |
err := remote.enforceAccessControls(req) |
| 729 |
if test.wantErr { |
| 730 |
if err == nil { |
| 731 |
t.Errorf("test %d (%s): allowed path %q, request path %q: expected forbidden error, got nil", i, test.name, test.allowedPath, test.requestPath) |
| 732 |
return |
| 733 |
} |
| 734 |
var apiErr APIError |
| 735 |
if !errors.As(err, &apiErr) { |
| 736 |
t.Errorf("test %d (%s): allowed path %q, request path %q: expected APIError with HTTP status %d, got %T: %v", i, test.name, test.allowedPath, test.requestPath, http.StatusForbidden, err, err) |
| 737 |
return |
| 738 |
} |
| 739 |
if apiErr.HTTPStatus != http.StatusForbidden { |
| 740 |
t.Errorf("test %d (%s): allowed path %q, request path %q: expected HTTP status %d, got %d", i, test.name, test.allowedPath, test.requestPath, http.StatusForbidden, apiErr.HTTPStatus) |
| 741 |
} |
| 742 |
return |
| 743 |
} |
| 744 |
|
| 745 |
if err != nil { |
| 746 |
t.Errorf("test %d (%s): allowed path %q, request path %q: expected no error, got %v", i, test.name, test.allowedPath, test.requestPath, err) |
| 747 |
} |
| 748 |
}) |
| 749 |
} |
| 750 |
} |
| 751 |
|
| 752 |
func TestReplaceRemoteAdminServer(t *testing.T) { |
| 753 |
const testCert = `MIIDCTCCAfGgAwIBAgIUXsqJ1mY8pKlHQtI3HJ23x2eZPqwwDQYJKoZIhvcNAQEL |
| 754 |
BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIzMDEwMTAwMDAwMFoXDTI0MDEw |
| 755 |
MTAwMDAwMFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF |
| 756 |
AAOCAQ8AMIIBCgKCAQEA4O4S6BSoYcoxvRqI+h7yPOjF6KjntjzVVm9M+uHK4lzX |
| 757 |
F1L3pSxJ2nDD4wZEV3FJ5yFOHVFqkG2vXG3BIczOlYG7UeNmKbQnKc5kZj3HGUrS |
| 758 |
VGEktA4OJbeZhhWP15gcXN5eDM2eH3g9BFXVX6AURxLiUXzhNBUEZuj/OEyH9yEF |
| 759 |
/qPCE+EjzVvWxvBXwgz/io4r4yok/Vq/bxJ6FlV6R7DX5oJSXyO0VEHZPi9DIyNU |
| 760 |
kK3F/r4U1sWiJGWOs8i3YQWZ2ejh1C0aLFZpPcCGGgMNpoF31gyYP6ZuPDUyCXsE |
| 761 |
g36UUw1JHNtIXYcLhnXuqj4A8TybTDpgXLqvwA9DBQIDAQABo1MwUTAdBgNVHQ4E |
| 762 |
FgQUc13z30pFC63rr/HGKOE7E82vjXwwHwYDVR0jBBgwFoAUc13z30pFC63rr/HG |
| 763 |
KOE7E82vjXwwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAHO3j |
| 764 |
oeiUXXJ7xD4P8Wj5t9d+E8lE1Xv1Dk3Z+EdG5+dan+RcToE42JJp9zB7FIh5Qz8g |
| 765 |
W77LAjqh5oyqz3A2VJcyVgfE3uJP1R1mJM7JfGHf84QH4TZF2Q1RZY4SZs0VQ6+q |
| 766 |
5wSlIZ4NXDy4Q4XkIJBGS61wT8IzYFXYBpx4PCP1Qj0PIE4sevEGwjsBIgxK307o |
| 767 |
BxF8AWe6N6e4YZmQLGjQ+SeH0iwZb6vpkHyAY8Kj2hvK+cq2P7vU3VGi0t3r1F8L |
| 768 |
IvrXHCvO2BMNJ/1UK1M4YNX8LYJqQhg9hEsIROe1OE/m3VhxIYMJI+qZXk9yHfgJ |
| 769 |
vq+SH04xKhtFudVBAQ==` |
| 770 |
|
| 771 |
tests := []struct { |
| 772 |
name string |
| 773 |
cfg *Config |
| 774 |
wantErr bool |
| 775 |
}{ |
| 776 |
{ |
| 777 |
name: "nil config", |
| 778 |
cfg: nil, |
| 779 |
wantErr: false, |
| 780 |
}, |
| 781 |
{ |
| 782 |
name: "nil admin config", |
| 783 |
cfg: &Config{ |
| 784 |
Admin: nil, |
| 785 |
}, |
| 786 |
wantErr: false, |
| 787 |
}, |
| 788 |
{ |
| 789 |
name: "nil remote config", |
| 790 |
cfg: &Config{ |
| 791 |
Admin: &AdminConfig{}, |
| 792 |
}, |
| 793 |
wantErr: false, |
| 794 |
}, |
| 795 |
{ |
| 796 |
name: "invalid listen address", |
| 797 |
cfg: &Config{ |
| 798 |
Admin: &AdminConfig{ |
| 799 |
Remote: &RemoteAdmin{ |
| 800 |
Listen: "invalid:address", |
| 801 |
}, |
| 802 |
}, |
| 803 |
}, |
| 804 |
wantErr: true, |
| 805 |
}, |
| 806 |
{ |
| 807 |
name: "valid config", |
| 808 |
cfg: &Config{ |
| 809 |
Admin: &AdminConfig{ |
| 810 |
Identity: &IdentityConfig{}, |
| 811 |
Remote: &RemoteAdmin{ |
| 812 |
Listen: "localhost:2021", |
| 813 |
AccessControl: []*AdminAccess{ |
| 814 |
{ |
| 815 |
PublicKeys: []string{testCert}, |
| 816 |
Permissions: []AdminPermissions{{Methods: []string{"GET"}, Paths: []string{"/test"}}}, |
| 817 |
}, |
| 818 |
}, |
| 819 |
}, |
| 820 |
}, |
| 821 |
}, |
| 822 |
wantErr: false, |
| 823 |
}, |
| 824 |
{ |
| 825 |
name: "invalid certificate", |
| 826 |
cfg: &Config{ |
| 827 |
Admin: &AdminConfig{ |
| 828 |
Identity: &IdentityConfig{}, |
| 829 |
Remote: &RemoteAdmin{ |
| 830 |
Listen: "localhost:2021", |
| 831 |
AccessControl: []*AdminAccess{ |
| 832 |
{ |
| 833 |
PublicKeys: []string{"invalid-cert-data"}, |
| 834 |
Permissions: []AdminPermissions{{Methods: []string{"GET"}, Paths: []string{"/test"}}}, |
| 835 |
}, |
| 836 |
}, |
| 837 |
}, |
| 838 |
}, |
| 839 |
}, |
| 840 |
wantErr: true, |
| 841 |
}, |
| 842 |
} |
| 843 |
|
| 844 |
for _, test := range tests { |
| 845 |
t.Run(test.name, func(t *testing.T) { |
| 846 |
ctx := Context{ |
| 847 |
Context: context.Background(), |
| 848 |
cfg: test.cfg, |
| 849 |
} |
| 850 |
|
| 851 |
if test.cfg != nil { |
| 852 |
test.cfg.storage = &certmagic.FileStorage{Path: t.TempDir()} |
| 853 |
} |
| 854 |
|
| 855 |
if test.cfg != nil && test.cfg.Admin != nil && test.cfg.Admin.Identity != nil { |
| 856 |
identityCertCache = certmagic.NewCache(certmagic.CacheOptions{ |
| 857 |
GetConfigForCert: func(certmagic.Certificate) (*certmagic.Config, error) { |
| 858 |
return &certmagic.Config{}, nil |
| 859 |
}, |
| 860 |
}) |
| 861 |
} |
| 862 |
|
| 863 |
err := replaceRemoteAdminServer(ctx, test.cfg) |
| 864 |
|
| 865 |
if test.wantErr { |
| 866 |
if err == nil { |
| 867 |
t.Error("Expected error but got nil") |
| 868 |
} |
| 869 |
} else { |
| 870 |
if err != nil { |
| 871 |
t.Errorf("Expected no error but got: %v", err) |
| 872 |
} |
| 873 |
} |
| 874 |
|
| 875 |
// Clean up |
| 876 |
if remoteAdminServer != nil { |
| 877 |
_ = stopAdminServer(remoteAdminServer) |
| 878 |
} |
| 879 |
}) |
| 880 |
} |
| 881 |
} |
| 882 |
|
| 883 |
type mockIssuer struct { |
| 884 |
configSet *certmagic.Config |
| 885 |
} |
| 886 |
|
| 887 |
func (m *mockIssuer) Issue(ctx context.Context, csr *x509.CertificateRequest) (*certmagic.IssuedCertificate, error) { |
| 888 |
return &certmagic.IssuedCertificate{ |
| 889 |
Certificate: []byte(csr.Raw), |
| 890 |
}, nil |
| 891 |
} |
| 892 |
|
| 893 |
func (m *mockIssuer) SetConfig(cfg *certmagic.Config) { |
| 894 |
m.configSet = cfg |
| 895 |
} |
| 896 |
|
| 897 |
func (m *mockIssuer) IssuerKey() string { |
| 898 |
return "mock" |
| 899 |
} |
| 900 |
|
| 901 |
type mockIssuerModule struct { |
| 902 |
*mockIssuer |
| 903 |
} |
| 904 |
|
| 905 |
func (m *mockIssuerModule) CaddyModule() ModuleInfo { |
| 906 |
return ModuleInfo{ |
| 907 |
ID: "tls.issuance.acme", |
| 908 |
New: func() Module { |
| 909 |
return &mockIssuerModule{mockIssuer: new(mockIssuer)} |
| 910 |
}, |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
func TestManageIdentity(t *testing.T) { |
| •915 |
t.Skip() |
| 916 |
originalModules := make(map[string]ModuleInfo) |
| 917 |
maps.Copy(originalModules, modules) |
| 918 |
defer func() { |
| 919 |
modules = originalModules |
| 920 |
}() |
| 921 |
|
| 922 |
RegisterModule(&mockIssuerModule{}) |
| 923 |
|
| 924 |
certPEM := []byte(`-----BEGIN CERTIFICATE----- |
| 925 |
MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE |
| 926 |
BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl |
| 927 |
cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw |
| 928 |
WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN |
| 929 |
TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp |
| 930 |
bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE3lcub2pUwkjC |
| 931 |
5GJQA2ZZfJJi6d1QHhEmkX9VxKYGp6gagZuRqJWy9TXP6++1ZzQQxqZLD0TkuxZ9 |
| 932 |
8i9Nz00000CCBjCCAQQwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMGgG |
| 933 |
CCsGAQUFBwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29t |
| 934 |
L0dJQUcyLmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5j |
| 935 |
b20vb2NzcDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/ |
| 936 |
BAIwADAfBgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHREEEDAO |
| 937 |
ggxtYWlsLmdvb2dsZTANBgkqhkiG9w0BAQUFAAOCAQEAMP6IWgNGZE8wP9TjFjSZ |
| 938 |
3mmW3A1eIr0CuPwNZ2LJ5ZD1i70ojzcj4I9IdP5yPg9CAEV4hNASbM1LzfC7GmJE |
| 939 |
tPzW5tRmpKVWZGRgTgZI8Hp/xZXMwLh9ZmXV4kESFAGj5G5FNvJyUV7R5Eh+7OZX |
| 940 |
7G4jJ4ZGJh+5jzN9HdJJHQHGYNIYOzC7+HH9UMwCjX9vhQ4RjwFZJThS2Yb+y7pb |
| 941 |
9yxTJZoXC6J0H5JpnZb7kZEJ+Xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx |
| 942 |
-----END CERTIFICATE-----`) |
| 943 |
|
| 944 |
keyPEM := []byte(`-----BEGIN PRIVATE KEY----- |
| 945 |
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDRS0LmTwUT0iwP |
| 946 |
... |
| 947 |
-----END PRIVATE KEY-----`) |
| 948 |
|
| 949 |
tmpDir, err := os.MkdirTemp("", "TestManageIdentity-") |
| 950 |
if err != nil { |
| 951 |
t.Fatal(err) |
| 952 |
} |
| 953 |
testStorage := certmagic.FileStorage{Path: tmpDir} |
| 954 |
// Clean up the temp dir after the test finishes. Ensure any background |
| 955 |
// certificate maintenance is stopped first to avoid RemoveAll races. |
| 956 |
t.Cleanup(func() { |
| 957 |
if identityCertCache != nil { |
| 958 |
identityCertCache.Stop() |
| 959 |
identityCertCache = nil |
| 960 |
} |
| 961 |
// Give goroutines a moment to exit and release file handles. |
| 962 |
time.Sleep(50 * time.Millisecond) |
| 963 |
_ = os.RemoveAll(tmpDir) |
| 964 |
}) |
| 965 |
|
| 966 |
err = testStorage.Store(context.Background(), "localhost/localhost.crt", certPEM) |
| 967 |
if err != nil { |
| 968 |
t.Fatal(err) |
| 969 |
} |
| 970 |
err = testStorage.Store(context.Background(), "localhost/localhost.key", keyPEM) |
| 971 |
if err != nil { |
| 972 |
t.Fatal(err) |
| 973 |
} |
| 974 |
|
| 975 |
tests := []struct { |
| 976 |
name string |
| 977 |
cfg *Config |
| 978 |
wantErr bool |
| 979 |
checkState func(*testing.T, *Config) |
| 980 |
}{ |
| 981 |
{ |
| 982 |
name: "nil config", |
| 983 |
cfg: nil, |
| 984 |
}, |
| 985 |
{ |
| 986 |
name: "nil admin config", |
| 987 |
cfg: &Config{ |
| 988 |
Admin: nil, |
| 989 |
}, |
| 990 |
}, |
| 991 |
{ |
| 992 |
name: "nil identity config", |
| 993 |
cfg: &Config{ |
| 994 |
Admin: &AdminConfig{}, |
| 995 |
}, |
| 996 |
}, |
| 997 |
{ |
| 998 |
name: "default issuer when none specified", |
| 999 |
cfg: &Config{ |
| 1000 |
Admin: &AdminConfig{ |
| 1001 |
Identity: &IdentityConfig{ |
| 1002 |
Identifiers: []string{"localhost"}, |
| 1003 |
}, |
| 1004 |
}, |
| 1005 |
storage: &testStorage, |
| 1006 |
}, |
| 1007 |
checkState: func(t *testing.T, cfg *Config) { |
| 1008 |
if len(cfg.Admin.Identity.issuers) == 0 { |
| 1009 |
t.Error("Expected at least 1 issuer to be configured") |
| 1010 |
return |
| 1011 |
} |
| 1012 |
if _, ok := cfg.Admin.Identity.issuers[0].(*mockIssuerModule); !ok { |
| 1013 |
t.Error("Expected mock issuer to be configured") |
| 1014 |
} |
| 1015 |
}, |
| 1016 |
}, |
| 1017 |
{ |
| 1018 |
name: "custom issuer", |
| 1019 |
cfg: &Config{ |
| 1020 |
Admin: &AdminConfig{ |
| 1021 |
Identity: &IdentityConfig{ |
| 1022 |
Identifiers: []string{"localhost"}, |
| 1023 |
IssuersRaw: []json.RawMessage{ |
| 1024 |
json.RawMessage(`{"module": "acme"}`), |
| 1025 |
}, |
| 1026 |
}, |
| 1027 |
}, |
| 1028 |
storage: &testStorage, |
| 1029 |
}, |
| 1030 |
checkState: func(t *testing.T, cfg *Config) { |
| 1031 |
if len(cfg.Admin.Identity.issuers) != 1 { |
| 1032 |
t.Fatalf("Expected 1 issuer, got %d", len(cfg.Admin.Identity.issuers)) |
| 1033 |
} |
| 1034 |
mockIss, ok := cfg.Admin.Identity.issuers[0].(*mockIssuerModule) |
| 1035 |
if !ok { |
| 1036 |
t.Fatal("Expected mock issuer") |
| 1037 |
} |
| 1038 |
if mockIss.configSet == nil { |
| 1039 |
t.Error("Issuer config was not set") |
| 1040 |
} |
| 1041 |
}, |
| 1042 |
}, |
| 1043 |
{ |
| 1044 |
name: "invalid issuer module", |
| 1045 |
cfg: &Config{ |
| 1046 |
Admin: &AdminConfig{ |
| 1047 |
Identity: &IdentityConfig{ |
| 1048 |
Identifiers: []string{"localhost"}, |
| 1049 |
IssuersRaw: []json.RawMessage{ |
| 1050 |
json.RawMessage(`{"module": "doesnt_exist"}`), |
| 1051 |
}, |
| 1052 |
}, |
| 1053 |
}, |
| 1054 |
}, |
| 1055 |
wantErr: true, |
| 1056 |
}, |
| 1057 |
} |
| 1058 |
|
| 1059 |
for _, test := range tests { |
| 1060 |
t.Run(test.name, func(t *testing.T) { |
| 1061 |
if identityCertCache != nil { |
| 1062 |
// Reset the cert cache before each test |
| 1063 |
identityCertCache.Stop() |
| 1064 |
identityCertCache = nil |
| 1065 |
} |
| 1066 |
// Ensure any cache started by manageIdentity is stopped at the end |
| 1067 |
defer func() { |
| 1068 |
if identityCertCache != nil { |
| 1069 |
identityCertCache.Stop() |
| 1070 |
identityCertCache = nil |
| 1071 |
} |
| 1072 |
}() |
| 1073 |
|
| 1074 |
ctx := Context{ |
| 1075 |
Context: context.Background(), |
| 1076 |
cfg: test.cfg, |
| 1077 |
moduleInstances: make(map[string][]Module), |
| 1078 |
} |
| 1079 |
|
| 1080 |
// If this test provided a FileStorage, set the package-level |
| 1081 |
// testCertMagicStorageOverride so certmagicConfig will use it. |
| 1082 |
if test.cfg != nil && test.cfg.storage != nil { |
| 1083 |
testCertMagicStorageOverride = test.cfg.storage |
| 1084 |
defer func() { testCertMagicStorageOverride = nil }() |
| 1085 |
} |
| 1086 |
|
| 1087 |
err := manageIdentity(ctx, test.cfg) |
| 1088 |
|
| 1089 |
if test.wantErr { |
| 1090 |
if err == nil { |
| 1091 |
t.Error("Expected error but got nil") |
| 1092 |
} |
| 1093 |
return |
| 1094 |
} |
| 1095 |
if err != nil { |
| 1096 |
t.Fatalf("Expected no error but got: %v", err) |
| 1097 |
} |
| 1098 |
|
| 1099 |
if test.checkState != nil { |
| 1100 |
test.checkState(t, test.cfg) |
| 1101 |
} |
| 1102 |
}) |
| 1103 |
} |
| 1104 |
} |
| 1105 |
|
| 1106 |
func TestUnsyncedConfigAccessCanonicalArrayIndices(t *testing.T) { |
| 1107 |
rawCfg = map[string]any{ |
| 1108 |
rawConfigKey: map[string]any{ |
| 1109 |
"list": []any{"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"}, |
| 1110 |
}, |
| 1111 |
} |
| 1112 |
|
| 1113 |
tests := []struct { |
| 1114 |
name string |
| 1115 |
path string |
| 1116 |
wantOutput string |
| 1117 |
wantErr bool |
| 1118 |
}{ |
| 1119 |
{name: "allow zero", path: "/" + rawConfigKey + "/list/0", wantOutput: "\"zero\"\n"}, |
| 1120 |
{name: "allow one", path: "/" + rawConfigKey + "/list/1", wantOutput: "\"one\"\n"}, |
| 1121 |
{name: "allow ten", path: "/" + rawConfigKey + "/list/10", wantOutput: "\"ten\"\n"}, |
| 1122 |
{name: "reject leading zero", path: "/" + rawConfigKey + "/list/01", wantErr: true}, |
| 1123 |
{name: "reject multiple leading zeros", path: "/" + rawConfigKey + "/list/002", wantErr: true}, |
| 1124 |
{name: "reject plus sign", path: "/" + rawConfigKey + "/list/+1", wantErr: true}, |
| 1125 |
{name: "reject negative zero", path: "/" + rawConfigKey + "/list/-0", wantErr: true}, |
| 1126 |
} |
| 1127 |
|
| 1128 |
for i, tc := range tests { |
| 1129 |
t.Run(tc.name, func(t *testing.T) { |
| 1130 |
var gotOutput bytes.Buffer |
| 1131 |
err := unsyncedConfigAccess(http.MethodGet, tc.path, nil, &gotOutput) |
| 1132 |
|
| 1133 |
if tc.wantErr { |
| 1134 |
if err == nil { |
| 1135 |
t.Errorf("test %d (%s): input path %q: expected error, got nil with output %q", i, tc.name, tc.path, gotOutput.String()) |
| 1136 |
} |
| 1137 |
return |
| 1138 |
} |
| 1139 |
|
| 1140 |
if err != nil { |
| 1141 |
t.Errorf("test %d (%s): input path %q: expected no error with output %q, got error %v with output %q", i, tc.name, tc.path, tc.wantOutput, err, gotOutput.String()) |
| 1142 |
} |
| 1143 |
if gotOutput.String() != tc.wantOutput { |
| 1144 |
t.Errorf("test %d (%s): input path %q: expected output %q, got %q", i, tc.name, tc.path, tc.wantOutput, gotOutput.String()) |
| 1145 |
} |
| 1146 |
}) |
| 1147 |
} |
| 1148 |
} |