-
-
Notifications
You must be signed in to change notification settings - Fork 101
Expand file tree
/
Copy pathapi.go
More file actions
219 lines (184 loc) · 6.12 KB
/
api.go
File metadata and controls
219 lines (184 loc) · 6.12 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
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
// The OTS Server
package main
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"time"
"github.com/gofrs/uuid"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
"github.com/Luzifer/ots/pkg/metrics"
"github.com/Luzifer/ots/pkg/storage"
)
const (
errorReasonInvalidExpiry = "invalid_expiry"
errorReasonInvalidJSON = "invalid_json"
errorReasonSecretMissing = "secret_missing"
errorReasonSecretNotFound = "secret_not_found"
errorReasonSecretSize = "secret_size"
errorReasonStorageError = "storage_error"
maxExpirySeconds = int64(1<<63-1) / int64(time.Second)
)
type apiServer struct {
collector *metrics.Collector
store storage.Storage
}
type apiResponse struct {
Success bool `json:"success"`
Error string `json:"error,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
Secret string `json:"secret,omitempty"` //#nosec:G117 // This application works with secrets
SecretID string `json:"secret_id,omitempty"`
}
type apiRequest struct {
Secret string `json:"secret"` //#nosec:G117 // This application works with secrets
}
func newAPI(s storage.Storage, c *metrics.Collector) *apiServer {
return &apiServer{
collector: c,
store: s,
}
}
func (a apiServer) Register(r *mux.Router) {
r.HandleFunc("/create", a.handleCreate)
r.HandleFunc("/get/{id}", a.handleRead)
r.HandleFunc("/isWritable", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusNoContent) })
r.HandleFunc("/settings", a.handleSettings).Methods(http.MethodGet)
r.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) })
}
func (a apiServer) errorResponse(res http.ResponseWriter, status int, err error, desc string) {
errID := uuid.Must(uuid.NewV4()).String()
if desc != "" {
// No description: Nothing interesting for the server log
logrus.WithField("err_id", errID).WithError(err).Error(desc)
}
a.jsonResponse(res, status, apiResponse{
Error: errID,
})
}
func (a apiServer) handleCreate(res http.ResponseWriter, r *http.Request) {
if cust.MaxSecretSize > 0 {
// As a safeguard against HUGE payloads behind a misconfigured
// proxy we take double the maximum secret size after which we
// just close the read and cut the connection to the sender.
r.Body = http.MaxBytesReader(res, r.Body, cust.MaxSecretSize*2)
}
var (
expiry = cfg.SecretExpiry
secret string
)
if !cust.DisableExpiryOverride {
var err error
if expiry, err = a.parseExpiryOverride(r, expiry); err != nil {
a.collector.CountSecretCreateError(errorReasonInvalidExpiry)
a.errorResponse(res, http.StatusBadRequest, err, "")
return
}
}
if strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
tmp := apiRequest{}
if err := json.NewDecoder(r.Body).Decode(&tmp); err != nil {
if _, ok := err.(*http.MaxBytesError); ok {
a.collector.CountSecretCreateError(errorReasonSecretSize)
// We don't do an error response here as the MaxBytesReader
// automatically cuts the ResponseWriter and we simply cannot
// answer them.
return
}
a.collector.CountSecretCreateError(errorReasonInvalidJSON)
a.errorResponse(res, http.StatusBadRequest, err, "decoding request body")
return
}
secret = tmp.Secret
} else {
secret = r.FormValue("secret")
}
if secret == "" {
a.collector.CountSecretCreateError(errorReasonSecretMissing)
a.errorResponse(res, http.StatusBadRequest, errors.New("secret missing"), "")
return
}
if cust.MaxSecretSize > 0 && len(secret) > int(cust.MaxSecretSize) {
a.collector.CountSecretCreateError(errorReasonSecretSize)
a.errorResponse(res, http.StatusBadRequest, errors.New("secret size exceeds maximum"), "")
return
}
id, err := a.store.Create(secret, time.Duration(expiry)*time.Second)
if err != nil {
a.collector.CountSecretCreateError(errorReasonStorageError)
a.errorResponse(res, http.StatusInternalServerError, err, "creating secret")
return
}
var expiresAt *time.Time
if expiry > 0 {
expiresAt = func(v time.Time) *time.Time { return &v }(time.Now().UTC().Add(time.Duration(expiry) * time.Second))
}
a.collector.CountSecretCreated()
go updateStoredSecretsCount(a.store, a.collector)
a.jsonResponse(res, http.StatusCreated, apiResponse{
ExpiresAt: expiresAt,
Success: true,
SecretID: id,
})
}
func (a apiServer) handleRead(res http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
if id == "" {
a.errorResponse(res, http.StatusBadRequest, errors.New("id missing"), "")
return
}
secret, err := a.store.ReadAndDestroy(id)
if err != nil {
status := http.StatusInternalServerError
if errors.Is(err, storage.ErrSecretNotFound) {
a.collector.CountSecretReadError(errorReasonSecretNotFound)
status = http.StatusNotFound
} else {
a.collector.CountSecretReadError(errorReasonStorageError)
}
a.errorResponse(res, status, err, "reading & destroying secret")
return
}
a.collector.CountSecretRead()
go updateStoredSecretsCount(a.store, a.collector)
a.jsonResponse(res, http.StatusOK, apiResponse{
Success: true,
Secret: secret,
})
}
func (a apiServer) handleSettings(w http.ResponseWriter, _ *http.Request) {
a.jsonResponse(w, http.StatusOK, cust)
}
func (apiServer) jsonResponse(res http.ResponseWriter, status int, response any) {
res.Header().Set("Content-Type", "application/json")
res.Header().Set("Cache-Control", "no-store, max-age=0")
res.WriteHeader(status)
if err := json.NewEncoder(res).Encode(response); err != nil {
logrus.WithError(err).Error("encoding JSON response")
http.Error(res, `{"error":"could not encode response"}`, http.StatusInternalServerError)
}
}
func (apiServer) parseExpiryOverride(r *http.Request, expiry int64) (int64, error) {
expiryValues, ok := r.URL.Query()["expire"]
if !ok {
return expiry, nil
}
ev, err := strconv.ParseInt(expiryValues[0], 10, 64)
if err != nil {
return 0, errors.New("invalid expiry")
}
if ev < 0 {
return 0, errors.New("expiry must be greater than or equal to zero")
}
if ev > maxExpirySeconds {
return 0, errors.New("expiry exceeds maximum duration")
}
if ev < expiry || cfg.SecretExpiry == 0 {
return ev, nil
}
return expiry, nil
}