1package app
2
3import (
4 "context"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8
9 adminhttp "github.com/bnema/gordon/internal/adapters/in/http/admin"
10 "github.com/bnema/zerowrap"
11)
12
13func TestCreateAuthService_Disabled_ReturnsNilServices(t *testing.T) {
14 t.Parallel()
15
16 cfg := Config{}
17 cfg.Auth.Enabled = false
18
19 store, authSvc, err := createAuthService(context.Background(), cfg, zerowrap.Default())
20 if err != nil {
21 t.Fatalf("expected no error when auth is disabled, got %v", err)
22 }
23 if store != nil {
24 t.Fatalf("expected nil token store when auth is disabled")
25 }
26 if authSvc != nil {
27 t.Fatalf("expected nil auth service when auth is disabled")
28 }
29}
30
31func TestCreateHTTPHandlers_LocalMode_DisablesAdminRoutes(t *testing.T) {
32 t.Parallel()
33
34 cfg := Config{}
35 cfg.Auth.Enabled = false
36
37 svc := &services{adminHandler: &adminhttp.Handler{}}
38 registryHandler, _ := createHTTPHandlers(svc, cfg, zerowrap.Default())
39
40 req := httptest.NewRequest(http.MethodGet, "/admin/status", nil)
41 req.RemoteAddr = "192.0.2.10:12345"
42
43 rec := httptest.NewRecorder()
44 registryHandler.ServeHTTP(rec, req)
45
46 if rec.Code != http.StatusNotFound {
47 t.Fatalf("expected status %d, got %d", http.StatusNotFound, rec.Code)
48 }
49}
50
51func TestCreateHTTPHandlers_LocalMode_RestrictsRegistryToLoopback(t *testing.T) {
52 t.Parallel()
53
54 cfg := Config{}
55 cfg.Auth.Enabled = false
56
57 registryHandler, _ := createHTTPHandlers(&services{}, cfg, zerowrap.Default())
58
59 req := httptest.NewRequest(http.MethodGet, "/v2/test/manifests/latest", nil)
60 req.RemoteAddr = "192.0.2.20:12345"
61
62 rec := httptest.NewRecorder()
63 registryHandler.ServeHTTP(rec, req)
64
65 if rec.Code != http.StatusForbidden {
66 t.Fatalf("expected status %d, got %d", http.StatusForbidden, rec.Code)
67 }
68}
69
70func TestBuildRegistryCIDRAllowlistMiddleware_InvalidEntries_DenyAll(t *testing.T) {
71 t.Parallel()
72
73 cfg := Config{}
74 cfg.Server.RegistryAllowedIPs = []string{"not-a-cidr"}
75
76 mw := buildRegistryCIDRAllowlistMiddleware(cfg, nil, zerowrap.Default())
77 if mw == nil {
78 t.Fatal("expected non-nil allowlist middleware")
79 }
80
81 handler := mw(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
82 w.WriteHeader(http.StatusOK)
83 }))
84
85 req := httptest.NewRequest(http.MethodGet, "/v2/test/manifests/latest", nil)
86 req.RemoteAddr = "127.0.0.1:12345"
87
88 rec := httptest.NewRecorder()
89 handler.ServeHTTP(rec, req)
90
91 if rec.Code != http.StatusForbidden {
92 t.Fatalf("expected status %d, got %d", http.StatusForbidden, rec.Code)
93 }
94}