This repository has no description
1package spindle
2
3import (
4 "log/slog"
5 "net/http"
6 "net/http/httptest"
7 "testing"
8
9 "tangled.org/core/idresolver"
10 "tangled.org/core/spindle/config"
11)
12
13func TestAdminRouterMountedOnlyWhenConfigured(t *testing.T) {
14 tests := []struct {
15 name string
16 password string
17 want int
18 }{
19 // mounted: rejects the unauthenticated request instead of 404ing
20 {"configured", "s3cret", http.StatusUnauthorized},
21 {"unset password", "", http.StatusNotFound},
22 }
23
24 for _, tt := range tests {
25 t.Run(tt.name, func(t *testing.T) {
26 s := &Spindle{
27 l: slog.Default(),
28 res: idresolver.DefaultResolver("https://plc.test"),
29 cfg: &config.Config{Server: config.Server{
30 AdminPassword: tt.password,
31 Hostname: "spindle.test",
32 }},
33 }
34
35 req := httptest.NewRequest(http.MethodPost, "/admin/member/allow", nil)
36 w := httptest.NewRecorder()
37 s.Router().ServeHTTP(w, req)
38
39 if w.Code != tt.want {
40 t.Errorf("status = %d, want %d", w.Code, tt.want)
41 }
42 })
43 }
44}
45
46func TestAdminMiddleware(t *testing.T) {
47 tests := []struct {
48 name string
49 configured string
50 user, pass string
51 basicAuth bool
52 want int
53 }{
54 {"correct password", "s3cret", "admin", "s3cret", true, http.StatusOK},
55 {"wrong password", "s3cret", "admin", "nope", true, http.StatusUnauthorized},
56 {"wrong user", "s3cret", "root", "s3cret", true, http.StatusUnauthorized},
57 {"no credentials", "s3cret", "", "", false, http.StatusUnauthorized},
58 // Router() skips the mount when the password is unset, but keep the middleware
59 // fail-closed too - an empty password must not authenticate anyone.
60 {"unset password", "", "admin", "", true, http.StatusUnauthorized},
61 {"unset password, no credentials", "", "", "", false, http.StatusUnauthorized},
62 }
63
64 for _, tt := range tests {
65 t.Run(tt.name, func(t *testing.T) {
66 s := &Spindle{cfg: &config.Config{
67 Server: config.Server{AdminPassword: tt.configured},
68 }}
69
70 req := httptest.NewRequest(http.MethodPost, "/admin/member/allow", nil)
71 if tt.basicAuth {
72 req.SetBasicAuth(tt.user, tt.pass)
73 }
74 w := httptest.NewRecorder()
75
76 s.adminMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
77 w.WriteHeader(http.StatusOK)
78 })).ServeHTTP(w, req)
79
80 if w.Code != tt.want {
81 t.Errorf("status = %d, want %d", w.Code, tt.want)
82 }
83 })
84 }
85}