Repository navigation
Expand file tree
/
Copy pathhandlers.go
More file actions
617 lines (572 loc) · 23.7 KB
/
Copy pathhandlers.go
File metadata and controls
617 lines (572 loc) · 23.7 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
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Contributor: Julien Vehent jvehent@mozilla.com [:ulfr]
package main
import (
"context"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"net/url"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/mozilla-services/autograph/formats"
"github.com/mozilla-services/autograph/signer"
log "github.com/sirupsen/logrus"
)
const (
// MinNamedFiles is the minimum number of named files a single
// multi-file signing request can include
MinNamedFiles = 1
// MaxNamedFiles is the maximum number of named files a single
// multi-file signing request can include
MaxNamedFiles = 32
)
// heartbeatConfig configures the heartbeat handler. It sets timeouts
// for each backing service to check.
//
// `hsmHeartbeatSignerConf` is determined added on boot in initHSM
type heartbeatConfig struct {
HSMCheckTimeout time.Duration
DBCheckTimeout time.Duration
HSMTestSignerId *string
// hsmSignerConf is the cached signer conf to use to check
// HSM connectivity. Set based on HSMTestSignerId.
hsmSignerConf *signer.Configuration
}
// hashSHA256AsHex returns the hex encoded string of the SHA256 sum
// the arg toHash bytes
func hashSHA256AsHex(toHash []byte) string {
h := sha256.New()
h.Write(toHash)
return fmt.Sprintf("%X", h.Sum(nil))
}
func logSigningRequestFailure(sigreq formats.SignatureRequest, sigresp formats.SignatureResponse, rid string, userid string, reqSize int, inputHash string, inputHashes []string, starttime time.Time, err error) {
log.WithFields(log.Fields{
"rid": rid,
"options": sigreq.Options,
"mode": sigresp.Mode,
"ref": sigresp.Ref,
"type": sigresp.Type,
"signer_id": sigresp.SignerID,
"used_default_signer": strconv.FormatBool(sigreq.KeyID == ""),
"input_hash": inputHash,
"input_hashes": inputHashes,
"output_hash": nil,
"output_hashes": nil,
"user_id": userid,
"size": reqSize,
"t": int32(time.Since(starttime) / time.Millisecond), // request processing time in ms
}).Warn(fmt.Sprintf("signing operation failed with error: %v", err))
}
// rewriteLocalX5U checks for X5U certificate chains using the `file://` scheme
// and rewrites them to use the `/x5u/:keyid/` endpoint instead, which should
// mirror the contents of the signer's X5U location, and returns the updated URL.
//
// If the X5U certificate chain uses any other scheme, then the original URL is returned
// without change.
func rewriteLocalX5U(r *http.Request, keyid string, x5u string) string {
parsedX5U, err := url.Parse(x5u)
if err == nil && parsedX5U.Scheme == "file" {
newX5U := url.URL{
Scheme: "http",
Host: r.Host,
Path: path.Join("x5u", keyid, path.Base(parsedX5U.Path)),
}
return newX5U.String()
}
// Otherwise, return the X5U unmodified
return x5u
}
// handleSignature endpoint accepts a list of signature requests in a HAWK authenticated POST request
// and calls the signers to generate signature responses.
func (a *autographer) handleSignature(w http.ResponseWriter, r *http.Request) {
rid := getRequestID(r)
starttime := getRequestStartTime(r)
auth, userid, err := a.authorizeHeader(r)
if err != nil {
signerRequestsTiming.With(prometheus.Labels{
"step": "hawk_authorize_header_failed",
}).Observe(float64(time.Since(starttime).Milliseconds()))
httpError(w, r, http.StatusUnauthorized, "handlers/handleSignature: Extracting authorization info from header failed: %v", err)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: failed to read request body: %s", err)
return
}
if r.Header.Get("Content-Type") != "application/json" {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: invalid content type, expected application/json")
return
}
requestBodySize := len(body)
if requestBodySize < 10 {
// it's impossible to have a valid request body smaller than 10 bytes
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: empty or invalid request request body")
return
}
// Default max request body size set to 1.5GB
var maxBodySizeMB int64 = 1500
if os.Getenv("MAX_BODY_SIZE_IN_MB") != "" {
maxBodySizeMB, err = strconv.ParseInt(os.Getenv("MAX_BODY_SIZE_IN_MB"), 10, 0)
if err != nil {
log.Fatalf("handlers/handleSignature: Error parsing environment variable MAX_BODY_SIZE_IN_MB: %s", err)
}
}
maxBodySizeBytes := maxBodySizeMB * 1000000
if int64(requestBodySize) > maxBodySizeBytes {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: request exceeded max size of %d B", maxBodySizeBytes)
return
}
err = a.authorizeBody(auth, r, body)
signerRequestsTiming.With(prometheus.Labels{
"step": "authorize_finished",
}).Observe(float64(time.Since(starttime).Milliseconds()))
if err != nil {
httpError(w, r, http.StatusUnauthorized, "handlers/handleSignature: %q user authorization verification failed: %v", userid, err)
return
}
var sigreqs []formats.SignatureRequest
err = json.Unmarshal(body, &sigreqs)
signerRequestsTiming.With(prometheus.Labels{
"step": "body_unmarshaled",
}).Observe(float64(time.Since(starttime).Milliseconds()))
if err != nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: failed to parse request body: %v", err)
return
}
for i, sigreq := range sigreqs {
if r.URL.RequestURI() == "/sign/files" {
if sigreq.Input != "" {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: input should be empty in sign files signature request %d", i)
}
if sigreq.Files == nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: missing Files in sign files signature request %d", i)
}
if len(sigreq.Files) < MinNamedFiles {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: Did not receive enough files to sign. Need at least %d", MinNamedFiles)
return
} else if len(sigreq.Files) > MaxNamedFiles {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: Received too many files to sign (max is %d)", MaxNamedFiles)
return
}
} else if sigreq.Input == "" {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: missing input in signature request %d", i)
}
}
log.Tracef("handlers/handleSignature: signature request\n-----------------\n%s\n", body)
sigReqsCount := len(sigreqs)
sigresps := make([]formats.SignatureResponse, sigReqsCount)
// Each signature requested in the http request body is processed individually.
// For each, a signer is looked up, and used to compute a raw signature
// the signature is then encoded appropriately, and added to the response slice
for i, sigreq := range sigreqs {
var (
input []byte
unsignedNamedFiles []signer.NamedUnsignedFile
sig signer.Signature
signedfile []byte
signedfiles []signer.NamedSignedFile
inputHash, outputHash string
inputHashes, outputHashes []string
)
if r.URL.RequestURI() == "/sign/files" {
for i, inputFile := range sigreq.Files {
log.Debugf("handlers/handleSignature: base64 decoding file %d", i)
unsignedNamedFile, err := signer.NewNamedUnsignedFile(inputFile)
if err != nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: error loading unsigned file. %q", err)
return
}
log.Debugf("handlers/handleSignature: base64 decoded unsigned named file %d: %s", i, unsignedNamedFile.Name)
unsignedNamedFiles = append(unsignedNamedFiles, *unsignedNamedFile)
}
log.Debugf("handlers/handleSignature: signing %d unsigned named files", len(unsignedNamedFiles))
} else {
// Decode the base64 input data
input, err = base64.StdEncoding.DecodeString(sigreq.Input)
if err != nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: error decoding string %v", err)
return
}
}
// returns an error if the signer is not found or if
// the user is not allowed to use this signer
requestedSigner, err := a.authBackend.getSignerForUser(userid, sigreq.KeyID)
if err != nil {
httpError(w, r, http.StatusUnauthorized, "handlers/handleSignature: error getting signer for user %s . %v", userid, err)
return
}
requestedSignerConfig := requestedSigner.Config()
signerRequestsCounter.With(prometheus.Labels{
"keyid": requestedSignerConfig.ID,
"user": userid,
// TODO(AUT-206): remove this when we've migrate everyone off of the default keyid
"used_default_signer": strconv.FormatBool(sigreq.KeyID == ""),
}).Inc()
signerRequestsGauge.With(prometheus.Labels{
"keyid": requestedSignerConfig.ID,
"user": userid,
// TODO(AUT-206): remove this when we've migrate everyone off of the default keyid
"used_default_signer": strconv.FormatBool(sigreq.KeyID == ""),
}).Inc()
sigresps[i] = formats.SignatureResponse{
Ref: id(),
Type: requestedSignerConfig.Type,
Mode: requestedSignerConfig.Mode,
SignerID: requestedSignerConfig.ID,
PublicKey: requestedSignerConfig.PublicKey,
SignedFile: base64.StdEncoding.EncodeToString(signedfile),
X5U: rewriteLocalX5U(r, requestedSignerConfig.ID, requestedSignerConfig.X5U),
SignerOpts: requestedSignerConfig.SignerOpts,
}
var sigSize int
var inputSize int
multiSigning := false
// Make sure the signer implements the right interface, then sign the data
switch r.URL.RequestURI() {
case "/sign/hash":
hashSigner, ok := requestedSigner.(signer.HashSigner)
if !ok {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: requested signer %q does not implement hash signing", requestedSignerConfig.ID)
return
}
// the input is already a hash just convert it to hex
inputHash = fmt.Sprintf("%X", input)
sig, err = hashSigner.SignHash(input, sigreq.Options)
if err != nil {
logSigningRequestFailure(sigreq, sigresps[i], rid, userid, requestBodySize, inputHash, inputHashes, starttime, err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: signing request %s failed with error: %v", sigresps[i].Ref, err)
return
}
sigresps[i].Signature, err = sig.Marshal()
if err != nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: encoding failed with error: %v", err)
return
}
inputSize = len(input)
sigSize = len(sigresps[i].Signature)
outputHash = "unimplemented"
case "/sign/data":
dataSigner, ok := requestedSigner.(signer.DataSigner)
if !ok {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: requested signer %q does not implement data signing", requestedSignerConfig.ID)
return
}
// calculate a hash of the input to store in the signing logs
inputHash = hashSHA256AsHex(input)
sig, err = dataSigner.SignData(input, sigreq.Options)
if err != nil {
logSigningRequestFailure(sigreq, sigresps[i], rid, userid, requestBodySize, inputHash, inputHashes, starttime, err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: signing request %s failed with error: %v", sigresps[i].Ref, err)
return
}
// Random testing added latency due to multi-signing for key agility
// testKeyAgility is 0, we will sign 100% of the time. Otherwise probability of multi-signing is 1/(testKeyAgility+1)
if strings.Contains(a.keyAgilitySignerIds, requestedSignerConfig.ID) && a.testKeyAgility > -1 && rand.Intn(a.testKeyAgility+1) == 0 {
a.secondarySignData(userid, sigreq, input, sigresps[i].Ref)
multiSigning = true
}
sigresps[i].Signature, err = sig.Marshal()
if err != nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: encoding failed with error: %v", err)
return
}
inputSize = len(input)
sigSize = len(sigresps[i].Signature)
outputHash = hashSHA256AsHex([]byte(sigresps[i].Signature))
case "/sign/file":
fileSigner, ok := requestedSigner.(signer.FileSigner)
if !ok {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: requested signer %q does not implement file signing", requestedSignerConfig.ID)
return
}
// calculate a hash of the input to store in the signing logs
inputHash = hashSHA256AsHex(input)
signedfile, err = fileSigner.SignFile(input, sigreq.Options)
if err != nil {
logSigningRequestFailure(sigreq, sigresps[i], rid, userid, requestBodySize, inputHash, inputHashes, starttime, err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: signing request %s failed with error: %v", sigresps[i].Ref, err)
return
}
sigresps[i].SignedFile = base64.StdEncoding.EncodeToString(signedfile)
inputSize = len(input)
sigSize = len(sigresps[i].SignedFile)
outputHash = hashSHA256AsHex(signedfile)
case "/sign/files":
multiFileSigner, ok := requestedSigner.(signer.MultipleFileSigner)
if !ok {
httpError(w, r, http.StatusBadRequest, "handlers/handleSignature: requested signer %q does not implement multiple file signing", requestedSignerConfig.ID)
return
}
// calculate a hash of the input files to log
for _, inputFile := range unsignedNamedFiles {
inputSize += len(inputFile.Bytes)
inputHashes = append(inputHashes, hashSHA256AsHex(inputFile.Bytes))
}
signedfiles, err = multiFileSigner.SignFiles(unsignedNamedFiles, sigreq.Options)
if err != nil {
logSigningRequestFailure(sigreq, sigresps[i], rid, userid, requestBodySize, inputHash, inputHashes, starttime, err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: signing request %s failed with error: %v", sigresps[i].Ref, err)
return
}
for _, signedFile := range signedfiles {
sigSize += len(signedFile.Bytes)
outputHashes = append(outputHashes, hashSHA256AsHex(signedFile.Bytes))
sigresps[i].SignedFiles = append(sigresps[i].SignedFiles, *signedFile.RESTSigningFile())
}
}
log.WithFields(log.Fields{
"rid": rid,
"request_uri": r.URL.RequestURI(),
"options": sigreq.Options,
"mode": sigresps[i].Mode,
"ref": sigresps[i].Ref,
"type": sigresps[i].Type,
"signer_id": sigresps[i].SignerID,
"used_default_signer": strconv.FormatBool(sigreq.KeyID == ""),
"input_hash": inputHash,
"input_hashes": inputHashes,
"output_hash": outputHash,
"output_hashes": outputHashes,
"user_id": userid,
"signed_size": sigSize,
"size": inputSize,
"multi_signing": multiSigning,
"t": int32(time.Since(starttime) / time.Millisecond), // request processing time in ms
}).Info("handlers/handleSignature: signing operation succeeded")
}
respdata, err := json.Marshal(sigresps)
if err != nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleSignature: signing failed with error: %v", err)
return
}
log.Tracef("handlers/handleSignature: signature response\n------------------\n%s\n", respdata)
log.WithFields(log.Fields{
"rid": rid,
"request_uri": r.URL.RequestURI(),
"user_id": userid,
"num_signing_requests": sigReqsCount,
"resp_size": len(respdata),
"req_size": requestBodySize,
"t": int32(time.Since(starttime) / time.Millisecond), // request processing time in ms
}).Info("handlers/handleSignature: signing request succeeded")
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
_, err = w.Write(respdata)
if err != nil {
log.Errorf("handlers/handleSignature: error writing response: %v", err)
}
log.WithFields(log.Fields{
"rid": rid,
"num_signing_requests": sigReqsCount,
}).Debug("handlers/handleSignature: signing request completed successfully")
}
// handleLBHeartbeat returns a simple message indicating that the API is alive and well
func (a *autographer) handleLBHeartbeat(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
httpError(w, r, http.StatusMethodNotAllowed, "handlers/handleLBHeartbeat: %s method not allowed; endpoint accepts GET only", r.Method)
return
}
if !a.authsLoaded || !a.signersLoaded {
httpError(w, r, http.StatusRequestTimeout, "handlers/handleLBHeartbeat: Auths and signers not yet loaded")
}
_, err := w.Write([]byte("ohai"))
if err != nil {
log.Errorf("handlers/handleLBHeartbeat: error writing response: %v", err)
}
}
// handleHeartbeat checks whether backing services are enabled and
// accessible and returns 200 when they are and 502 when the
// aren't. Currently it only checks whether the HSM is accessible.
func (a *autographer) handleHeartbeat(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
httpError(w, r, http.StatusMethodNotAllowed, "handlers/handleHeartbeat: %s method not allowed; endpoint accepts GET only", r.Method)
return
}
if a.heartbeatConf == nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleHeartbeat: Missing heartbeat config")
return
}
var (
// a map of backing service name to up or down/inaccessible status
result = map[string]bool{}
status = http.StatusOK
requestContext = r.Context()
rid = getRequestID(r)
)
// try to fetch the private key from the HSM for the first
// signer conf with a non-PEM private key that we saved on
// server start
if a.heartbeatConf.hsmSignerConf != nil {
var (
err error
hsmSignerConf = a.heartbeatConf.hsmSignerConf
hsmHBTimeout = a.heartbeatConf.HSMCheckTimeout
checkResult = make(chan error, 1)
hsmHeartbeatStartTs = time.Now()
)
go func() {
checkResult <- hsmSignerConf.CheckHSMConnection()
}()
select {
case <-time.After(hsmHBTimeout):
err = fmt.Errorf("handlers/handleHeartbeat: checking HSM connection for signer %s private key timed out", hsmSignerConf.ID)
case err = <-checkResult:
}
if err == nil {
log.WithFields(log.Fields{
"rid": rid,
"t": int32(time.Since(hsmHeartbeatStartTs) / time.Millisecond),
"timeout": hsmHBTimeout.String(),
}).Debug("handlers/handleHeartbeat: HSM heartbeat completed successfully")
result["hsmAccessible"] = true
status = http.StatusOK
} else {
log.Errorf("handlers/handleHeartbeat: error checking HSM connection for signer %s: %s", hsmSignerConf.ID, err)
result["hsmAccessible"] = false
status = http.StatusInternalServerError
}
}
// check the database connection and return its status, but
// don't fail the heartbeat since we only care about DB
// connectivity on server start
if a.db != nil {
dbHeartbeatStartTs := time.Now()
dbCheckCtx, dbCancel := context.WithTimeout(requestContext, a.heartbeatConf.DBCheckTimeout)
defer dbCancel()
err := a.db.CheckConnectionContext(dbCheckCtx)
if err == nil {
log.WithFields(log.Fields{
"rid": rid,
"t": int32(time.Since(dbHeartbeatStartTs) / time.Millisecond),
"timeout": a.heartbeatConf.DBCheckTimeout.String(),
}).Info("handlers/handleHeartbeat: DB heartbeat completed successfully")
result["dbAccessible"] = true
} else {
log.Errorf("handlers/handleHeartbeat: error checking DB connection: %s", err)
result["dbAccessible"] = false
}
}
respdata, err := json.Marshal(result)
if err != nil {
log.Errorf("handlers/handleHeartbeat: heartbeat failed to marshal JSON with error: %s", err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleHeartbeat: error marshaling response JSON")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(respdata)
if err != nil {
log.Errorf("handlers/handleHeartbeat: error writing response: %v", err)
}
}
func handleVersion(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
httpError(w, r, http.StatusMethodNotAllowed, "handlers/handleVersion: %s method not allowed; endpoint accepts GET only", r.Method)
return
}
dir, err := os.Getwd()
if err != nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleVersion: Could not get CWD")
return
}
filename := path.Clean(dir + string(os.PathSeparator) + "version.json")
f, err := os.Open(filename)
if err != nil {
httpError(w, r, http.StatusNotFound, "handlers/handleVersion: version.json file not found")
return
}
stat, err := f.Stat()
if err != nil {
httpError(w, r, http.StatusInternalServerError, "handlers/handleVersion: stat failed on version.json")
return
}
w.Header().Set("Content-Type", "application/json")
http.ServeContent(w, r, "version.json", stat.ModTime(), f)
}
// handleGetAuthKeyIDs returns the signer (keyID param for the API)
// for the authenticated user
func (a *autographer) handleGetAuthKeyIDs(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
httpError(w, r, http.StatusMethodNotAllowed, "handlers/handleGetAuthKeyIDs: %s method not allowed; endpoint accepts GET only", r.Method)
return
}
if r.Body != nil {
body, err := io.ReadAll(r.Body)
if err != nil {
httpError(w, r, http.StatusBadRequest, "handlers/handleGetAuthKeyIDs: failed to read request body: %s", err)
return
}
if len(body) > 0 {
httpError(w, r, http.StatusBadRequest, "handlers/handleGetAuthKeyIDs: endpoint received unexpected request body")
return
}
}
pathAuthID, ok := mux.Vars(r)["auth_id"]
if !ok {
httpError(w, r, http.StatusInternalServerError, "handlers/handleGetAuthKeyIDs: route is improperly configured")
return
}
if !authIDFormatRegexp.MatchString(pathAuthID) {
httpError(w, r, http.StatusBadRequest, "handlers/handleGetAuthKeyIDs: auth_id in URL path '%s' is invalid, it must match %s", pathAuthID, authIDFormat)
return
}
_, headerAuthID, err := a.authorizeHeader(r)
if err != nil {
httpError(w, r, http.StatusUnauthorized, "handlers/handleGetAuthKeyIDs: Extracting authorization info from header failed: %v", err)
return
}
if headerAuthID != pathAuthID {
httpError(w, r, http.StatusForbidden, "handlers/handleGetAuthKeyIDs: Authorized user %q cannot request keyids for user %q", headerAuthID, pathAuthID)
return
}
signerIDsJSON, err := json.Marshal(a.authBackend.getSignerIDsForUser(pathAuthID))
if err != nil {
log.Errorf("handlers/handleGetAuthKeyIDs: failed to marshal JSON with error: %s", err)
httpError(w, r, http.StatusInternalServerError, "handlers/handleGetAuthKeyIDs: error marshaling response JSON")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(signerIDsJSON)
if err != nil {
log.Errorf("handlers/handleGetAuthKeyIDs: error writing response: %v", err)
}
}
func (a *autographer) secondarySignData(userid string, sigreq formats.SignatureRequest, input []byte, sigRespRef string) {
if a.secondarySignerId == "" {
log.Errorf("handlers/secondarySignData: no signer ID set in environment variable SECONDARY_SIGNER_ID for user %s.", userid)
return
}
// returns an error if the signer is not found or if
// the user is not allowed to use this signer
requestedSecondarySigner, err := a.authBackend.getSignerForUser(userid, a.secondarySignerId)
if err != nil {
log.Errorf("handlers/secondarySignData: error getting signer for user %s . %v", userid, err)
return
}
requestedSignerConfig := requestedSecondarySigner.Config()
dataSigner, ok := requestedSecondarySigner.(signer.DataSigner)
if !ok {
log.Errorf("handlers/secondarySignData: requested signer %q does not implement data signing", requestedSignerConfig.ID)
return
}
_, err = dataSigner.SignData(input, sigreq.Options)
if err != nil {
log.Errorf("handlers/secondarySignData: signing request %s failed with error: %v", sigRespRef, err)
return
}
}