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

import (
	"crypto/hmac"
	"crypto/rand"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/base64"
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"
)

var (
	warnOnce sync.Once

	// fallbackSecretOnce lazily generates a process-local random secret used
	// only when no explicit JWT secret AND no admin credentials are configured.
	// Because admin login is also disabled in that state (see
	// effectiveAdminKey), no real token can be minted with this secret; it
	// exists solely so token signing never falls back to a hardcoded value.
	fallbackSecretOnce sync.Once
	fallbackSecret     []byte
)

type AdminConfigReader interface {
	AdminPasswordHash() string
	AdminJWTExpireHours() int
	AdminJWTValidAfterUnix() int64
}

func AdminKey() string {
	return effectiveAdminKey(nil)
}

func effectiveAdminKey(store AdminConfigReader) string {
	if store != nil {
		if hash := strings.TrimSpace(store.AdminPasswordHash()); hash != "" {
			return ""
		}
	}
	if v := strings.TrimSpace(os.Getenv("DS2API_ADMIN_KEY")); v != "" {
		return v
	}
	warnOnce.Do(func() {
		slog.Warn("DS2API_ADMIN_KEY is not set and no admin password hash is configured. " +
			"Admin login is DISABLED until you set DS2API_ADMIN_KEY or configure a password via the admin panel. " +
			"Set a strong DS2API_ADMIN_KEY in your deployment secrets.")
	})
	// Security: do NOT fall back to an insecure hardcoded default like "admin".
	// Returning empty disables admin password login until the operator
	// configures credentials, which is the safe-by-default behavior.
	return ""
}

// fallbackJWTSecret returns a process-local random secret used only when no
// explicit JWT secret and no admin credentials are configured. Because admin
// login is also disabled in that state (see effectiveAdminKey), no real token
// can be minted with this secret; it exists solely so token signing uses a
// non-predictable key rather than the historical hardcoded "admin" value.
func fallbackJWTSecret() []byte {
	fallbackSecretOnce.Do(func() {
		buf := make([]byte, 32)
		if _, err := rand.Read(buf); err != nil {
			// Extremely unlikely; derive from time + pid as a last resort so
			// we never return an empty secret.
			binary.BigEndian.PutUint64(buf[0:8], uint64(time.Now().UnixNano()))
			binary.BigEndian.PutUint64(buf[8:16], uint64(os.Getpid()))
		}
		fallbackSecret = buf
	})
	return fallbackSecret
}

func jwtSecret(store AdminConfigReader) string {
	if v := strings.TrimSpace(os.Getenv("DS2API_JWT_SECRET")); v != "" {
		return v
	}
	if store != nil {
		if hash := strings.TrimSpace(store.AdminPasswordHash()); hash != "" {
			return hash
		}
	}
	if key := effectiveAdminKey(store); key != "" {
		return key
	}
	// Security: never fall back to a hardcoded value. Use a process-local
	// random secret so tokens cannot be forged even if minting were possible.
	return string(fallbackJWTSecret())
}

func jwtExpireHours(store AdminConfigReader) int {
	if store != nil {
		if n := store.AdminJWTExpireHours(); n > 0 {
			return n
		}
	}
	if v := strings.TrimSpace(os.Getenv("DS2API_JWT_EXPIRE_HOURS")); v != "" {
		if n, err := strconv.Atoi(v); err == nil && n > 0 {
			return n
		}
	}
	return 24
}

func CreateJWT(expireHours int) (string, error) {
	return CreateJWTWithStore(expireHours, nil)
}

func CreateJWTWithStore(expireHours int, store AdminConfigReader) (string, error) {
	if expireHours <= 0 {
		expireHours = jwtExpireHours(store)
	}
	issuedAt := time.Now().Unix()
	// If sessions were invalidated in this same second, move iat forward by
	// one second so newly minted tokens remain valid with strict cutoff checks.
	if store != nil {
		if validAfter := store.AdminJWTValidAfterUnix(); validAfter >= issuedAt {
			issuedAt = validAfter + 1
		}
	}
	expireAt := time.Unix(issuedAt, 0).Add(time.Duration(expireHours) * time.Hour).Unix()
	header := map[string]any{"alg": "HS256", "typ": "JWT"}
	payload := map[string]any{"iat": issuedAt, "exp": expireAt, "role": "admin"}
	h, _ := json.Marshal(header)
	p, _ := json.Marshal(payload)
	headerB64 := rawB64Encode(h)
	payloadB64 := rawB64Encode(p)
	msg := headerB64 + "." + payloadB64
	sig := signHS256(msg, store)
	return msg + "." + rawB64Encode(sig), nil
}

func VerifyJWT(token string) (map[string]any, error) {
	return VerifyJWTWithStore(token, nil)
}

func VerifyJWTWithStore(token string, store AdminConfigReader) (map[string]any, error) {
	parts := strings.Split(token, ".")
	if len(parts) != 3 {
		return nil, errors.New("invalid token format")
	}
	msg := parts[0] + "." + parts[1]
	expected := signHS256(msg, store)
	actual, err := rawB64Decode(parts[2])
	if err != nil {
		return nil, errors.New("invalid signature")
	}
	if !hmac.Equal(expected, actual) {
		return nil, errors.New("invalid signature")
	}
	payloadBytes, err := rawB64Decode(parts[1])
	if err != nil {
		return nil, errors.New("invalid payload")
	}
	var payload map[string]any
	if err := json.Unmarshal(payloadBytes, &payload); err != nil {
		return nil, errors.New("invalid payload")
	}
	exp, _ := payload["exp"].(float64)
	if int64(exp) < time.Now().Unix() {
		return nil, errors.New("token expired")
	}
	if store != nil {
		validAfter := store.AdminJWTValidAfterUnix()
		if validAfter > 0 {
			iat, _ := payload["iat"].(float64)
			if int64(iat) <= validAfter {
				return nil, errors.New("token expired")
			}
		}
	}
	return payload, nil
}

func VerifyAdminRequest(r *http.Request) error {
	return VerifyAdminRequestWithStore(r, nil)
}

func VerifyAdminRequestWithStore(r *http.Request, store AdminConfigReader) error {
	authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
	if !strings.HasPrefix(strings.ToLower(authHeader), "bearer ") {
		return errors.New("authentication required")
	}
	token := strings.TrimSpace(authHeader[7:])
	if token == "" {
		return errors.New("authentication required")
	}
	if VerifyAdminCredential(token, store) {
		return nil
	}
	if _, err := VerifyJWTWithStore(token, store); err == nil {
		return nil
	}
	return errors.New("invalid credentials")
}

func VerifyAdminCredential(candidate string, store AdminConfigReader) bool {
	candidate = strings.TrimSpace(candidate)
	if candidate == "" {
		return false
	}
	if store != nil {
		hash := strings.TrimSpace(store.AdminPasswordHash())
		if hash != "" {
			return verifyAdminPasswordHash(candidate, hash)
		}
	}
	key := effectiveAdminKey(store)
	if key == "" {
		return false
	}
	return subtle.ConstantTimeCompare([]byte(candidate), []byte(key)) == 1
}

func UsingDefaultAdminKey(store AdminConfigReader) bool {
	if store != nil && strings.TrimSpace(store.AdminPasswordHash()) != "" {
		return false
	}
	return strings.TrimSpace(os.Getenv("DS2API_ADMIN_KEY")) == ""
}

func HashAdminPassword(raw string) string {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return ""
	}
	sum := sha256.Sum256([]byte(raw))
	return "sha256:" + hex.EncodeToString(sum[:])
}

func verifyAdminPasswordHash(candidate, encoded string) bool {
	encoded = strings.TrimSpace(strings.ToLower(encoded))
	if encoded == "" {
		return false
	}
	if strings.HasPrefix(encoded, "sha256:") {
		want := strings.TrimPrefix(encoded, "sha256:")
		sum := sha256.Sum256([]byte(candidate))
		got := hex.EncodeToString(sum[:])
		return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
	}
	return subtle.ConstantTimeCompare([]byte(candidate), []byte(encoded)) == 1
}

func signHS256(msg string, store AdminConfigReader) []byte {
	h := hmac.New(sha256.New, []byte(jwtSecret(store)))
	_, _ = h.Write([]byte(msg))
	return h.Sum(nil)
}

func rawB64Encode(b []byte) string {
	return base64.RawURLEncoding.EncodeToString(b)
}

func rawB64Decode(s string) ([]byte, error) {
	return base64.RawURLEncoding.DecodeString(s)
}