-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandleWrap.go
More file actions
74 lines (64 loc) · 1.76 KB
/
Copy pathhandleWrap.go
File metadata and controls
74 lines (64 loc) · 1.76 KB
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
// Copyright © 2025 Karl Bateman. All Rights Reserved. Use of this software is
// governed by a BSD-style license that can be found in the LICENSE file.
// The /wrap HTTP handler and its WrapResponse payload.
package praetorian
import (
"encoding/base64"
"encoding/json"
"io"
"log"
"net/http"
)
// WrapResponse is returned from the HTTP server after a successful wrap
// operation.
type WrapResponse struct {
ID string `json:"id"`
Token string `json:"token"`
}
// HandleWrap encrypts the POSTed request body under activeKey and returns
// the resulting token.
func HandleWrap(activeKey string, keys KeyFinder) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonResponse(w, http.StatusNotFound, &ErrorResponse{
Message: "Not Found",
})
return
}
maxBytes := int64(1 << 20) // 1MB limit
b, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBytes))
if err != nil {
jsonResponse(w, http.StatusBadRequest, &ErrorResponse{
Message: "failed to read request body",
})
return
}
if !json.Valid(b) {
jsonResponse(w, http.StatusBadRequest, &ErrorResponse{
Message: "invalid JSON",
})
return
}
key, err := keys.Find(activeKey)
if err != nil {
log.Printf("wrap: find active key: %v", err)
jsonResponse(w, http.StatusInternalServerError, &ErrorResponse{
Message: "unable to wrap data",
})
return
}
enc, err := key.Encrypt(b)
if err != nil {
log.Printf("wrap: encrypt: %v", err)
jsonResponse(w, http.StatusInternalServerError, &ErrorResponse{
Message: "unable to wrap data",
})
return
}
token := base64.StdEncoding.EncodeToString(enc)
jsonResponse(w, http.StatusCreated, &WrapResponse{
ID: key.ID(),
Token: token,
})
}
}