File size: 7,590 Bytes
c37473d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package auth

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"os"
	"strings"
	"testing"

	"ds2api/internal/config"
)

// stubStore implements AdminConfigReader for testing without pulling in the
// full config store. We intentionally use a struct (not a mock) so the test
// exercises the real auth code paths.
type stubStore struct {
	passwordHash string
	expireHours  int
	validAfter   int64
}

func (s stubStore) AdminPasswordHash() string     { return s.passwordHash }
func (s stubStore) AdminJWTExpireHours() int      { return s.expireHours }
func (s stubStore) AdminJWTValidAfterUnix() int64 { return s.validAfter }

func TestEffectiveAdminKeyNeverReturnsHardcodedDefault(t *testing.T) {
	// Security: ensure the historical "admin" default is gone. If this test
	// ever fails, it means a regression reintroduced a publicly-known default
	// credential that would let anyone log in to deployments without
	// DS2API_ADMIN_KEY set.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_CONFIG_JSON", "")

	stub := stubStore{}
	if got := effectiveAdminKey(stub); got != "" {
		t.Fatalf("effectiveAdminKey with no env and no password hash must be empty, got %q", got)
	}
	if got := AdminKey(); got != "" {
		t.Fatalf("AdminKey() with no env must be empty, got %q", got)
	}
}

func TestVerifyAdminCredentialRejectsEmptyAndDefaultAdmin(t *testing.T) {
	// Security: with no admin key configured and no password hash, login
	// MUST be impossible — even if an attacker tries "admin" or empty string.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_CONFIG_JSON", "")

	stub := stubStore{}
	for _, candidate := range []string{"", "admin", "password", "123456", "default"} {
		if VerifyAdminCredential(candidate, stub) {
			t.Fatalf("VerifyAdminCredential must reject %q when no credentials configured", candidate)
		}
	}
}

func TestVerifyAdminCredentialRejectsKnownDefaultAdminWithEnvSet(t *testing.T) {
	// Security: when DS2API_ADMIN_KEY is set to a strong value, the literal
	// "admin" must NOT authenticate.
	t.Setenv("DS2API_ADMIN_KEY", "a-strong-and-random-key-12345")
	t.Setenv("DS2API_CONFIG_JSON", "")

	stub := stubStore{}
	if VerifyAdminCredential("admin", stub) {
		t.Fatal("VerifyAdminCredential must reject literal \"admin\" when env key is set to something else")
	}
	if !VerifyAdminCredential("a-strong-and-random-key-12345", stub) {
		t.Fatal("VerifyAdminCredential must accept the configured env key")
	}
}

func TestJWTSecretNotHardcodedAdminWhenUnconfigured(t *testing.T) {
	// Security: when no DS2API_JWT_SECRET, no password hash, and no
	// DS2API_ADMIN_KEY are configured, the JWT signing secret must NOT be
	// the historical hardcoded "admin". A process-local random secret is
	// used instead so attackers cannot forge tokens.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_JWT_SECRET", "")
	t.Setenv("DS2API_CONFIG_JSON", "")

	secret := jwtSecret(nil)
	if secret == "admin" {
		t.Fatal("jwtSecret must not fall back to hardcoded \"admin\"")
	}
	if secret == "" {
		t.Fatal("jwtSecret must be non-empty so token signing is non-trivial")
	}
	// The fallback secret must be process-stable (same value across calls).
	if secret != jwtSecret(nil) {
		t.Fatal("jwtSecret fallback must be process-stable so minted tokens verify")
	}
}

func TestJWTForgedWithAdminSecretFailsVerification(t *testing.T) {
	// Security: an attacker who knows the historical default "admin" cannot
	// forge a token that verifies when no credentials are configured, because
	// the actual signing secret is a process-local random value.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_JWT_SECRET", "")

	// Forge a token signed with the historical "admin" secret.
	header := map[string]any{"alg": "HS256", "typ": "JWT"}
	payload := map[string]any{
		"iat":  0,
		"exp":  9999999999,
		"role": "admin",
	}
	h, _ := json.Marshal(header)
	p, _ := json.Marshal(payload)
	msg := rawB64Encode(h) + "." + rawB64Encode(p)

	mac := hmac.New(sha256.New, []byte("admin"))
	_, _ = mac.Write([]byte(msg))
	forgedSig := mac.Sum(nil)
	forged := msg + "." + rawB64Encode(forgedSig)

	if _, err := VerifyJWT(forged); err == nil {
		t.Fatal("forged token signed with hardcoded \"admin\" secret must NOT verify")
	}
}

func TestAdminLoginDisabledWithoutCredentials(t *testing.T) {
	// Security: end-to-end check that VerifyAdminRequestWithStore rejects
	// Bearer tokens when no credentials are configured, regardless of what
	// string the attacker supplies.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_CONFIG_JSON", "")

	stub := stubStore{}
	for _, token := range []string{"admin", "", "Bearer admin", "anything"} {
		req := httptest.NewRequest(http.MethodGet, "/admin/config", nil)
		req.Header.Set("Authorization", "Bearer "+token)
		if err := VerifyAdminRequestWithStore(req, stub); err == nil {
			t.Fatalf("VerifyAdminRequestWithStore must reject token %q when no credentials configured", token)
		}
	}
}

func TestAdminLoginWithConfiguredPasswordHash(t *testing.T) {
	// Regression: ensure password-hash based login still works after the
	// default-removal change.
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_JWT_SECRET", "")

	stub := stubStore{passwordHash: HashAdminPassword("super-secret-pw")}
	if !VerifyAdminCredential("super-secret-pw", stub) {
		t.Fatal("VerifyAdminCredential must accept the configured password")
	}
	if VerifyAdminCredential("wrong-password", stub) {
		t.Fatal("VerifyAdminCredential must reject wrong password")
	}
	// JWT secret must derive from the password hash, not the empty admin key.
	secret := jwtSecret(stub)
	if secret != strings.TrimSpace(stub.passwordHash) {
		t.Fatalf("jwtSecret must be the password hash when no env secret set, got %q", secret)
	}
}

func TestAdminLoginWithEnvKey(t *testing.T) {
	// Regression: ensure env-key based login still works after the change.
	t.Setenv("DS2API_ADMIN_KEY", "env-key-12345")
	t.Setenv("DS2API_JWT_SECRET", "")

	stub := stubStore{}
	if !VerifyAdminCredential("env-key-12345", stub) {
		t.Fatal("VerifyAdminCredential must accept the configured env key")
	}
	if VerifyAdminCredential("env-key-99999", stub) {
		t.Fatal("VerifyAdminCredential must reject wrong env key")
	}
}

func TestAdminLoginWithJWTSecretEnv(t *testing.T) {
	// Regression: ensure an explicit JWT secret takes precedence and works
	// for both signing and verifying.
	t.Setenv("DS2API_ADMIN_KEY", "env-key-12345")
	t.Setenv("DS2API_JWT_SECRET", "explicit-jwt-secret")

	stub := stubStore{}
	if jwtSecret(stub) != "explicit-jwt-secret" {
		t.Fatalf("jwtSecret must use explicit env value, got %q", jwtSecret(stub))
	}

	token, err := CreateJWTWithStore(1, stub)
	if err != nil {
		t.Fatalf("CreateJWTWithStore failed: %v", err)
	}
	if _, err := VerifyJWTWithStore(token, stub); err != nil {
		t.Fatalf("VerifyJWTWithStore failed: %v", err)
	}
}

// usingRealStoreHelper wraps a minimal config.Store so we exercise the same
// store code paths used in production. We avoid pulling in the full server.
func TestUsingRealStoreNoCredentials(t *testing.T) {
	if os.Getenv("DS2API_RUN_REAL_STORE_TEST") == "" {
		t.Skip("skipping real-store test; set DS2API_RUN_REAL_STORE_TEST=1 to run")
	}
	t.Setenv("DS2API_ADMIN_KEY", "")
	t.Setenv("DS2API_JWT_SECRET", "")
	t.Setenv("DS2API_CONFIG_JSON", "{}")
	store := config.LoadStore()
	if !UsingDefaultAdminKey(store) {
		t.Fatal("UsingDefaultAdminKey must be true when nothing is configured")
	}
	if VerifyAdminCredential("admin", store) {
		t.Fatal("VerifyAdminCredential must reject \"admin\" with no credentials configured")
	}
}