forked from kyma-project/kyma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
signaturehandler.go
executable file
·80 lines (64 loc) · 2.29 KB
/
signaturehandler.go
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
package externalapi
import (
"encoding/base64"
"encoding/json"
"io/ioutil"
"net/http"
"github.com/kyma-project/kyma/components/connector-service/internal/clientcontext"
"github.com/kyma-project/kyma/components/connector-service/internal/httphelpers"
"github.com/kyma-project/kyma/components/connector-service/internal/apperrors"
"github.com/kyma-project/kyma/components/connector-service/internal/certificates"
)
type signatureHandler struct {
connectorClientExtractor clientcontext.ConnectorClientExtractor
certificateService certificates.Service
}
func NewSignatureHandler(certificateService certificates.Service, connectorClientExtractor clientcontext.ConnectorClientExtractor) SignatureHandler {
return &signatureHandler{
connectorClientExtractor: connectorClientExtractor,
certificateService: certificateService,
}
}
func (sh *signatureHandler) SignCSR(w http.ResponseWriter, r *http.Request) {
clientContextService, err := sh.connectorClientExtractor(r.Context())
if err != nil {
httphelpers.RespondWithErrorAndLog(w, err)
return
}
signingRequest, err := readCertRequest(r)
if err != nil {
httphelpers.RespondWithErrorAndLog(w, err)
return
}
rawCSR, err := decodeStringFromBase64(signingRequest.CSR)
if err != nil {
httphelpers.RespondWithErrorAndLog(w, err)
return
}
encodedCertificatesChain, err := sh.certificateService.SignCSR(rawCSR, clientContextService.GetSubject())
if err != nil {
httphelpers.RespondWithErrorAndLog(w, err)
return
}
httphelpers.RespondWithBody(w, http.StatusCreated, toCertResponse(encodedCertificatesChain))
}
func readCertRequest(r *http.Request) (*certRequest, apperrors.AppError) {
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, apperrors.Internal("Error while reading request body: %s", err)
}
defer r.Body.Close()
var tokenRequest certRequest
err = json.Unmarshal(b, &tokenRequest)
if err != nil {
return nil, apperrors.Internal("Error while unmarshalling request body: %s", err)
}
return &tokenRequest, nil
}
func decodeStringFromBase64(string string) ([]byte, apperrors.AppError) {
bytes, err := base64.StdEncoding.DecodeString(string)
if err != nil {
return nil, apperrors.BadRequest("There was an error while parsing the base64 content. An incorrect value was provided.")
}
return bytes, nil
}