-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathattest.go
More file actions
162 lines (140 loc) · 4.82 KB
/
Copy pathattest.go
File metadata and controls
162 lines (140 loc) · 4.82 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
// Copyright 2025 Edgeless Systems GmbH
// SPDX-License-Identifier: BUSL-1.1
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime"
"net/http"
"github.com/edgelesssys/contrast/apitypes"
"github.com/edgelesssys/contrast/coordinator/internal/stateguard"
"github.com/edgelesssys/contrast/coordinator/internal/userapi"
"github.com/edgelesssys/contrast/internal/atls"
"github.com/edgelesssys/contrast/internal/constants"
"github.com/edgelesssys/contrast/internal/manifest"
"google.golang.org/grpc/status"
)
var (
errContentType = errors.New("invalid Content-Type")
errNonceLength = errors.New("invalid nonce length")
errGettingState = errors.New("getting state")
errGettingHistory = errors.New("getting history")
errGettingAttestation = errors.New("getting attestation report")
)
// StateGuard is a stateguard.Guard at runtime, but can be stubbed in tests.
type StateGuard interface {
GetState(context.Context) (*stateguard.State, error)
GetHistory(ctx context.Context) ([][]byte, map[manifest.HexString][]byte, error)
}
// AttestationHandler handles POST requests to /attest.
type AttestationHandler struct {
Issuer atls.Issuer
StateGuard StateGuard
}
func (h *AttestationHandler) getResponse(ctx context.Context, nonce []byte) (*apitypes.AttestationResponse, int, error) {
// state knows the latest transition
state, err := h.StateGuard.GetState(ctx)
switch {
case errors.Is(err, stateguard.ErrNoState):
return nil, http.StatusPreconditionFailed, userapi.ErrNoManifest
case errors.Is(err, stateguard.ErrStaleState):
return nil, http.StatusPreconditionFailed, userapi.ErrNeedsRecovery
case err != nil:
return nil, http.StatusInternalServerError, fmt.Errorf("%w: %w", errGettingState, err)
}
manifests, policies, err := h.StateGuard.GetHistory(ctx)
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("%w: %w", errGettingHistory, err)
}
ca := state.CA()
coordinatorState := &apitypes.CoordinatorState{
Manifests: manifests,
RootCA: ca.GetRootCACert(),
MeshCA: ca.GetMeshCACert(),
}
for _, policy := range policies {
coordinatorState.Policies = append(coordinatorState.Policies, policy)
}
transitionHash := state.LatestTransition().TransitionHash
reportData := apitypes.ConstructReportData(nonce, transitionHash[:], coordinatorState)
attestation, err := h.Issuer.Issue(ctx, reportData)
if err != nil {
return nil, http.StatusInternalServerError, fmt.Errorf("%w: %w", errGettingAttestation, err)
}
resp := &apitypes.AttestationResponse{
Version: constants.Version,
AttestationType: h.Issuer.OID(),
RawAttestationDoc: attestation,
CoordinatorState: *coordinatorState,
}
return resp, http.StatusOK, nil
}
func (h *AttestationHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
contentType := r.Header.Get("Content-Type")
mediaType, _, err := mime.ParseMediaType(contentType)
if err != nil {
writeJSONError(w, http.StatusBadRequest, err)
return
}
if mediaType != "application/json" {
writeJSONError(w, http.StatusUnsupportedMediaType, errContentType)
return
}
// Limit size to a small value to avoid abuse (nonce only expected).
bodyReader := http.MaxBytesReader(w, r.Body, 1024)
defer bodyReader.Close()
body, err := io.ReadAll(bodyReader)
if err != nil {
var maxBytesErr *http.MaxBytesError
if errors.As(err, &maxBytesErr) {
writeJSONError(w, http.StatusRequestEntityTooLarge, maxBytesErr)
return
}
writeJSONError(w, http.StatusBadRequest, err)
return
}
var req apitypes.AttestationRequest
if err := json.Unmarshal(body, &req); err != nil {
writeJSONError(w, http.StatusBadRequest, err)
return
}
if len(req.Nonce) != 32 {
writeJSONError(w, http.StatusBadRequest, fmt.Errorf("%w: got %d, expected 32", errNonceLength, len(req.Nonce)))
return
}
ctx := r.Context()
resp, errCode, err := h.getResponse(ctx, req.Nonce)
if err != nil {
writeJSONError(w, errCode, err)
return
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
if err := enc.Encode(resp); err != nil {
writeJSONError(w, http.StatusInternalServerError, err)
}
}
func writeJSONError(w http.ResponseWriter, statusCode int, err error) {
log.Print(err.Error())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
apiErr := &apitypes.APIError{
Version: constants.Version,
StatusCode: statusCode,
// Unwrap gRPC status errors, so that clients don't see the gRPC framing of an
// error that didn't travel over gRPC. For other errors, this is err.Error().
Err: status.Convert(err).Message(),
}
if errEncode := json.NewEncoder(w).Encode(apiErr); errEncode != nil {
log.Printf("encoding error response %v failed: %v", err, errEncode)
}
}