• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

umputun / stash / 20473316693

23 Dec 2025 10:47PM UTC coverage: 83.53% (+0.04%) from 83.488%
20473316693

push

github

umputun
test(e2e): add secrets vault UI tests

- lock icon visibility for secret keys
- permission enforcement (user without secrets access)
- card view lock icon display
- scoped secrets access verification

3043 of 3643 relevant lines covered (83.53%)

83.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

89.32
/app/server/api/handler.go
1
// Package api provides HTTP handlers for the KV API.
2
package api
3

4
import (
5
        "context"
6
        "encoding/base64"
7
        "errors"
8
        "io"
9
        "net/http"
10
        "strings"
11
        "time"
12

13
        log "github.com/go-pkgz/lgr"
14
        "github.com/go-pkgz/rest"
15
        "github.com/go-pkgz/routegroup"
16

17
        "github.com/umputun/stash/app/enum"
18
        "github.com/umputun/stash/app/git"
19
        "github.com/umputun/stash/app/server/internal/cookie"
20
        "github.com/umputun/stash/app/store"
21
        "github.com/umputun/stash/lib/stash"
22
)
23

24
//go:generate moq -out mocks/kvstore.go -pkg mocks -skip-ensure -fmt goimports . KVStore
25
//go:generate moq -out mocks/authprovider.go -pkg mocks -skip-ensure -fmt goimports . AuthProvider
26
//go:generate moq -out mocks/formatvalidator.go -pkg mocks -skip-ensure -fmt goimports . FormatValidator
27
//go:generate moq -out mocks/gitservice.go -pkg mocks -skip-ensure -fmt goimports . GitService
28

29
// GitService defines the interface for git operations.
30
type GitService interface {
31
        Commit(req git.CommitRequest) error
32
        Delete(key string, author git.Author) error
33
        History(key string, limit int) ([]git.HistoryEntry, error)
34
        GetRevision(key string, rev string) ([]byte, string, error)
35
}
36

37
// KVStore defines the interface for key-value storage operations.
38
type KVStore interface {
39
        Get(ctx context.Context, key string) ([]byte, error)
40
        GetWithFormat(ctx context.Context, key string) ([]byte, string, error)
41
        Set(ctx context.Context, key string, value []byte, format string) error
42
        Delete(ctx context.Context, key string) error
43
        List(ctx context.Context, filter enum.SecretsFilter) ([]store.KeyInfo, error)
44
        SecretsEnabled() bool
45
}
46

47
// AuthProvider defines the interface for authentication operations.
48
type AuthProvider interface {
49
        Enabled() bool
50
        GetSessionUser(ctx context.Context, token string) (string, bool)
51
        FilterUserKeys(username string, keys []string) []string
52
        FilterTokenKeys(token string, keys []string) []string
53
        FilterPublicKeys(keys []string) []string
54
        HasTokenACL(token string) bool
55
}
56

57
// FormatValidator defines the interface for format validation.
58
type FormatValidator interface {
59
        IsValidFormat(format string) bool
60
}
61

62
// Handler handles API requests for /kv/* endpoints.
63
type Handler struct {
64
        store           KVStore
65
        auth            AuthProvider
66
        formatValidator FormatValidator
67
        git             GitService
68
}
69

70
// New creates a new API handler.
71
func New(st KVStore, auth AuthProvider, fv FormatValidator, gs GitService) *Handler {
38✔
72
        return &Handler{
38✔
73
                store:           st,
38✔
74
                auth:            auth,
38✔
75
                formatValidator: fv,
38✔
76
                git:             gs,
38✔
77
        }
38✔
78
}
38✔
79

80
// Register registers API routes on the given router.
81
func (h *Handler) Register(r *routegroup.Bundle) {
×
82
        r.HandleFunc("GET /{$}", h.handleList)                 // list keys (must be before {key...})
×
83
        r.HandleFunc("GET /history/{key...}", h.handleHistory) // get key history (before generic key)
×
84
        r.HandleFunc("GET /{key...}", h.handleGet)             // get specific key
×
85
        r.HandleFunc("PUT /{key...}", h.handleSet)             // set key
×
86
        r.HandleFunc("DELETE /{key...}", h.handleDelete)
×
87
}
×
88

89
// handleList returns all keys the caller has read access to.
90
// GET /kv?prefix=app/config (filter by prefix)
91
// GET /kv?filter=secrets (filter to secrets only)
92
// GET /kv?filter=keys (filter to non-secrets only)
93
func (h *Handler) handleList(w http.ResponseWriter, r *http.Request) {
5✔
94
        // parse secrets filter query param
5✔
95
        filter := enum.SecretsFilterAll
5✔
96
        if filterParam := r.URL.Query().Get("filter"); filterParam != "" {
7✔
97
                if parsed, err := enum.ParseSecretsFilter(filterParam); err == nil {
4✔
98
                        filter = parsed
2✔
99
                }
2✔
100
        }
101

102
        keys, err := h.store.List(r.Context(), filter)
5✔
103
        if err != nil {
6✔
104
                rest.SendErrorJSON(w, r, log.Default(), http.StatusInternalServerError, err, "failed to list keys")
1✔
105
                return
1✔
106
        }
1✔
107

108
        // extract key names for filtering
109
        keyNames := make([]string, len(keys))
4✔
110
        for i, k := range keys {
11✔
111
                keyNames[i] = k.Key
7✔
112
        }
7✔
113

114
        // filter by auth permissions
115
        filteredNames := h.filterKeysByAuth(r, keyNames)
4✔
116
        if filteredNames == nil {
4✔
117
                // no valid auth, but this shouldn't happen since tokenAuth middleware already checked
×
118
                rest.SendErrorJSON(w, r, log.Default(), http.StatusUnauthorized, nil, "unauthorized")
×
119
                return
×
120
        }
×
121

122
        // convert filtered names back to KeyInfo slice
123
        nameSet := make(map[string]bool, len(filteredNames))
4✔
124
        for _, name := range filteredNames {
11✔
125
                nameSet[name] = true
7✔
126
        }
7✔
127
        filtered := make([]store.KeyInfo, 0, len(filteredNames))
4✔
128
        for _, k := range keys {
11✔
129
                if nameSet[k.Key] {
14✔
130
                        filtered = append(filtered, k)
7✔
131
                }
7✔
132
        }
133

134
        // filter by prefix if specified
135
        prefix := r.URL.Query().Get("prefix")
4✔
136
        if prefix != "" {
5✔
137
                var prefixed []store.KeyInfo
1✔
138
                for _, k := range filtered {
4✔
139
                        if strings.HasPrefix(k.Key, prefix) {
5✔
140
                                prefixed = append(prefixed, k)
2✔
141
                        }
2✔
142
                }
143
                filtered = prefixed
1✔
144
        }
145

146
        log.Printf("[DEBUG] list keys: %d found, %d after auth filter", len(keys), len(filtered))
4✔
147
        rest.RenderJSON(w, filtered)
4✔
148
}
149

150
// filterKeysByAuth filters keys based on the caller's auth credentials.
151
// returns nil if auth is required but caller has no valid credentials.
152
// priority: session cookie > Bearer token > public ACL
153
func (h *Handler) filterKeysByAuth(r *http.Request, keys []string) []string {
13✔
154
        // no auth = return all keys
13✔
155
        if h.auth == nil || !h.auth.Enabled() {
21✔
156
                return keys
8✔
157
        }
8✔
158

159
        // check session cookie first (authenticated user has priority over public)
160
        for _, cookieName := range cookie.SessionCookieNames {
15✔
161
                c, err := r.Cookie(cookieName)
10✔
162
                if err != nil {
19✔
163
                        continue
9✔
164
                }
165
                username, valid := h.auth.GetSessionUser(r.Context(), c.Value)
1✔
166
                if valid {
2✔
167
                        return h.auth.FilterUserKeys(username, keys)
1✔
168
                }
1✔
169
        }
170

171
        // check Bearer token (authenticated token has priority over public)
172
        authHeader := r.Header.Get("Authorization")
4✔
173
        if token, found := strings.CutPrefix(authHeader, "Bearer "); found {
5✔
174
                if filtered := h.auth.FilterTokenKeys(token, keys); filtered != nil {
2✔
175
                        return filtered
1✔
176
                }
1✔
177
        }
178

179
        // fall back to public access for unauthenticated requests
180
        if filtered := h.auth.FilterPublicKeys(keys); filtered != nil {
4✔
181
                return filtered
1✔
182
        }
1✔
183

184
        return nil // no valid auth
2✔
185
}
186

187
// handleGet retrieves the value for a key.
188
// GET /kv/{key...}
189
func (h *Handler) handleGet(w http.ResponseWriter, r *http.Request) {
5✔
190
        key := store.NormalizeKey(r.PathValue("key"))
5✔
191
        if key == "" {
6✔
192
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, nil, "key is required")
1✔
193
                return
1✔
194
        }
1✔
195

196
        value, format, err := h.store.GetWithFormat(r.Context(), key)
4✔
197
        if errors.Is(err, store.ErrSecretsNotConfigured) {
5✔
198
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, err, "secrets not configured")
1✔
199
                return
1✔
200
        }
1✔
201
        if errors.Is(err, store.ErrNotFound) {
4✔
202
                rest.SendErrorJSON(w, r, log.Default(), http.StatusNotFound, err, "key not found")
1✔
203
                return
1✔
204
        }
1✔
205
        if err != nil {
2✔
206
                rest.SendErrorJSON(w, r, log.Default(), http.StatusInternalServerError, err, "failed to get key")
×
207
                return
×
208
        }
×
209

210
        log.Printf("[DEBUG] get %s (%d bytes, format=%s)", key, len(value), format)
2✔
211

2✔
212
        w.Header().Set("Content-Type", h.formatToContentType(format))
2✔
213
        w.WriteHeader(http.StatusOK)
2✔
214
        if _, err := w.Write(value); err != nil {
2✔
215
                log.Printf("[WARN] failed to write response: %v", err)
×
216
        }
×
217
}
218

219
// formatToContentType maps storage format to HTTP Content-Type
220
func (h *Handler) formatToContentType(format string) string {
11✔
221
        if f, err := stash.ParseFormat(format); err == nil {
21✔
222
                return f.ContentType()
10✔
223
        }
10✔
224
        return "application/octet-stream"
1✔
225
}
226

227
// handleSet stores a value for a key.
228
// PUT /kv/{key...}
229
// accepts format via X-Stash-Format header or ?format= query param (defaults to "text")
230
func (h *Handler) handleSet(w http.ResponseWriter, r *http.Request) {
8✔
231
        key := store.NormalizeKey(r.PathValue("key"))
8✔
232
        if key == "" {
9✔
233
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, nil, "key is required")
1✔
234
                return
1✔
235
        }
1✔
236

237
        value, err := io.ReadAll(r.Body)
7✔
238
        if err != nil {
7✔
239
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, err, "failed to read body")
×
240
                return
×
241
        }
×
242

243
        // get format from header or query param, default to "text"
244
        format := r.Header.Get("X-Stash-Format")
7✔
245
        if format == "" {
12✔
246
                format = r.URL.Query().Get("format")
5✔
247
        }
5✔
248
        if !h.formatValidator.IsValidFormat(format) {
12✔
249
                format = "text"
5✔
250
        }
5✔
251

252
        if err := h.store.Set(r.Context(), key, value, format); err != nil {
9✔
253
                if errors.Is(err, store.ErrSecretsNotConfigured) {
3✔
254
                        rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, err, "secrets not configured")
1✔
255
                        return
1✔
256
                }
1✔
257
                rest.SendErrorJSON(w, r, log.Default(), http.StatusInternalServerError, err, "failed to set key")
1✔
258
                return
1✔
259
        }
260

261
        log.Printf("[INFO] set %q (%d bytes, format=%s) by %s", key, len(value), format, h.getIdentityForLog(r))
5✔
262

5✔
263
        // commit to git if enabled
5✔
264
        if h.git != nil {
6✔
265
                req := git.CommitRequest{Key: key, Value: value, Operation: "set", Format: format, Author: h.getAuthorFromRequest(r)}
1✔
266
                if err := h.git.Commit(req); err != nil {
1✔
267
                        log.Printf("[WARN] git commit failed for %s: %v", key, err)
×
268
                }
×
269
        }
270

271
        w.WriteHeader(http.StatusOK)
5✔
272
}
273

274
// handleDelete removes a key from the store.
275
// DELETE /kv/{key...}
276
func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request) {
5✔
277
        key := store.NormalizeKey(r.PathValue("key"))
5✔
278
        if key == "" {
6✔
279
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, nil, "key is required")
1✔
280
                return
1✔
281
        }
1✔
282

283
        err := h.store.Delete(r.Context(), key)
4✔
284
        if errors.Is(err, store.ErrNotFound) {
5✔
285
                rest.SendErrorJSON(w, r, log.Default(), http.StatusNotFound, err, "key not found")
1✔
286
                return
1✔
287
        }
1✔
288
        if err != nil {
4✔
289
                rest.SendErrorJSON(w, r, log.Default(), http.StatusInternalServerError, err, "failed to delete key")
1✔
290
                return
1✔
291
        }
1✔
292

293
        log.Printf("[INFO] delete %q by %s", key, h.getIdentityForLog(r))
2✔
294

2✔
295
        // delete from git if enabled
2✔
296
        if h.git != nil {
3✔
297
                if err := h.git.Delete(key, h.getAuthorFromRequest(r)); err != nil {
1✔
298
                        log.Printf("[WARN] git delete failed for %s: %v", key, err)
×
299
                }
×
300
        }
301

302
        w.WriteHeader(http.StatusNoContent)
2✔
303
}
304

305
// historyResponse represents a single entry in the history response.
306
type historyResponse struct {
307
        Hash      string `json:"hash"`
308
        Timestamp string `json:"timestamp"`
309
        Author    string `json:"author"`
310
        Operation string `json:"operation"`
311
        Format    string `json:"format"`
312
        Value     string `json:"value"` // base64 encoded
313
}
314

315
// handleHistory returns the commit history for a key.
316
// GET /kv/history/{key...}
317
func (h *Handler) handleHistory(w http.ResponseWriter, r *http.Request) {
6✔
318
        if h.git == nil {
7✔
319
                rest.SendErrorJSON(w, r, log.Default(), http.StatusServiceUnavailable, nil, "git integration not enabled")
1✔
320
                return
1✔
321
        }
1✔
322

323
        key := store.NormalizeKey(r.PathValue("key"))
5✔
324
        if key == "" {
6✔
325
                rest.SendErrorJSON(w, r, log.Default(), http.StatusBadRequest, nil, "key is required")
1✔
326
                return
1✔
327
        }
1✔
328

329
        // check read permission
330
        filtered := h.filterKeysByAuth(r, []string{key})
4✔
331
        if len(filtered) == 0 {
5✔
332
                rest.SendErrorJSON(w, r, log.Default(), http.StatusForbidden, nil, "access denied")
1✔
333
                return
1✔
334
        }
1✔
335

336
        history, err := h.git.History(key, 50)
3✔
337
        if err != nil {
4✔
338
                rest.SendErrorJSON(w, r, log.Default(), http.StatusInternalServerError, err, "failed to get history")
1✔
339
                return
1✔
340
        }
1✔
341

342
        // base64-encode values to safely transmit arbitrary binary data in JSON
343
        resp := make([]historyResponse, len(history))
2✔
344
        for i, entry := range history {
4✔
345
                resp[i] = historyResponse{
2✔
346
                        Hash:      entry.Hash,
2✔
347
                        Timestamp: entry.Timestamp.UTC().Format(time.RFC3339),
2✔
348
                        Author:    entry.Author,
2✔
349
                        Operation: entry.Operation,
2✔
350
                        Format:    entry.Format,
2✔
351
                        Value:     base64.StdEncoding.EncodeToString(entry.Value),
2✔
352
                }
2✔
353
        }
2✔
354

355
        rest.RenderJSON(w, resp)
2✔
356
}
357

358
// identityType represents the type of identity detected from a request.
359
type identityType int
360

361
const (
362
        identityAnonymous identityType = iota
363
        identityUser
364
        identityToken
365
)
366

367
// identity holds information about who made a request.
368
type identity struct {
369
        typ  identityType
370
        name string // username or token prefix
371
}
372

373
// getIdentity extracts identity from request context.
374
// returns user identity from session cookie, token identity from Authorization header, or anonymous.
375
func (h *Handler) getIdentity(r *http.Request) identity {
17✔
376
        if h.auth == nil {
19✔
377
                return identity{typ: identityAnonymous}
2✔
378
        }
2✔
379

380
        // check session cookie for web UI users
381
        for _, cookieName := range cookie.SessionCookieNames {
45✔
382
                c, err := r.Cookie(cookieName)
30✔
383
                if err != nil {
57✔
384
                        continue
27✔
385
                }
386
                if username, valid := h.auth.GetSessionUser(r.Context(), c.Value); valid && username != "" {
6✔
387
                        return identity{typ: identityUser, name: username}
3✔
388
                }
3✔
389
        }
390

391
        // check API token from Authorization header
392
        if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") {
14✔
393
                token := strings.TrimPrefix(authHeader, "Bearer ")
2✔
394
                if h.auth.HasTokenACL(token) {
4✔
395
                        prefix := token
2✔
396
                        if len(prefix) > 8 {
4✔
397
                                prefix = prefix[:8]
2✔
398
                        }
2✔
399
                        return identity{typ: identityToken, name: "token:" + prefix}
2✔
400
                }
401
        }
402

403
        return identity{typ: identityAnonymous}
10✔
404
}
405

406
// getAuthorFromRequest extracts the git author from request context.
407
// returns username from session cookie for web UI users, token prefix for API tokens, default author otherwise.
408
func (h *Handler) getAuthorFromRequest(r *http.Request) git.Author {
5✔
409
        id := h.getIdentity(r)
5✔
410
        switch id.typ {
5✔
411
        case identityUser, identityToken:
2✔
412
                return git.Author{Name: id.name, Email: id.name + "@stash"}
2✔
413
        default:
3✔
414
                return git.DefaultAuthor()
3✔
415
        }
416
}
417

418
// getIdentityForLog returns identity string for audit logging.
419
// returns "user:xxx" for web UI users, "token:xxx" for API tokens, "anonymous" otherwise.
420
func (h *Handler) getIdentityForLog(r *http.Request) string {
9✔
421
        id := h.getIdentity(r)
9✔
422
        switch id.typ {
9✔
423
        case identityUser:
1✔
424
                return "user:" + id.name
1✔
425
        case identityToken:
×
426
                return id.name // already has "token:" prefix
×
427
        default:
8✔
428
                return "anonymous"
8✔
429
        }
430
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc