|
| 1 | +package attestation |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/base64" |
| 7 | + "fmt" |
| 8 | + "io" |
| 9 | + "log/slog" |
| 10 | + "net/http" |
| 11 | + |
| 12 | + "github.com/0xsequence/nitrocontrol/enclave" |
| 13 | + "github.com/0xsequence/nitrocontrol/tracing" |
| 14 | + "github.com/go-chi/chi/v5/middleware" |
| 15 | +) |
| 16 | + |
| 17 | +// Middleware is an HTTP middleware that issues an attestation document request to the enclave's NSM. |
| 18 | +// The result wrapped in the Attestation type is then set in the context available to subsequent handlers. |
| 19 | +// It also sets the X-Attestation-Document HTTP header to the Base64-encoded representation of the document. |
| 20 | +// |
| 21 | +// If the HTTP request includes an X-Attestation-Nonce header, its value is sent to the NSM and included in |
| 22 | +// the final attestation document. |
| 23 | +func Middleware(enc *enclave.Enclave, errorFn func(http.ResponseWriter, error), loggerFromContextFn func(context.Context) *slog.Logger) func(http.Handler) http.Handler { |
| 24 | + runPreMiddleware := func(r *http.Request) (ctx context.Context, cancelFunc func(), err error) { |
| 25 | + ctx, span := tracing.Trace(r.Context(), "attestation.Middleware") |
| 26 | + defer func() { |
| 27 | + span.RecordError(err) |
| 28 | + span.End() |
| 29 | + }() |
| 30 | + |
| 31 | + log := loggerFromContextFn(ctx) |
| 32 | + att, err := enc.GetAttestation(ctx, nil, nil) |
| 33 | + if err != nil { |
| 34 | + return nil, nil, err |
| 35 | + } |
| 36 | + |
| 37 | + cancelFunc = func() { |
| 38 | + if err := att.Close(); err != nil { |
| 39 | + log.Error("failed to close attestation", "error", err) |
| 40 | + return |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + return context.WithValue(r.Context(), contextKey, att), cancelFunc, nil |
| 45 | + } |
| 46 | + |
| 47 | + runPostMiddleware := func(w http.ResponseWriter, r *http.Request, body []byte, nonce []byte) (err error) { |
| 48 | + log := loggerFromContextFn(r.Context()) |
| 49 | + ctx, span := tracing.Trace(r.Context(), "attestation.Middleware") |
| 50 | + defer func() { |
| 51 | + span.RecordError(err) |
| 52 | + span.End() |
| 53 | + }() |
| 54 | + |
| 55 | + userData, err := generateUserData(r, body) |
| 56 | + if err != nil { |
| 57 | + return err |
| 58 | + } |
| 59 | + |
| 60 | + att, err := enc.GetAttestation(ctx, nonce, userData) |
| 61 | + if err != nil { |
| 62 | + return err |
| 63 | + } |
| 64 | + defer func() { |
| 65 | + if err := att.Close(); err != nil { |
| 66 | + log.Error("failed to close attestation", "error", err) |
| 67 | + return |
| 68 | + } |
| 69 | + }() |
| 70 | + |
| 71 | + w.Header().Set("X-Attestation-Document", base64.StdEncoding.EncodeToString(att.Document())) |
| 72 | + return nil |
| 73 | + } |
| 74 | + |
| 75 | + return func(next http.Handler) http.Handler { |
| 76 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 77 | + reqBody, err := io.ReadAll(r.Body) |
| 78 | + if err != nil { |
| 79 | + errorFn(w, fmt.Errorf("failed to read request body: %w", err)) |
| 80 | + return |
| 81 | + } |
| 82 | + r.Body = io.NopCloser(bytes.NewBuffer(reqBody)) |
| 83 | + |
| 84 | + var nonce []byte |
| 85 | + if nonceVal := r.Header.Get("X-Attestation-Nonce"); nonceVal != "" { |
| 86 | + if len(nonceVal) > 32 { |
| 87 | + errorFn(w, fmt.Errorf("X-Attestation-Nonce value cannot be longer than 32")) |
| 88 | + return |
| 89 | + } |
| 90 | + if !isNonceValid(nonceVal) { |
| 91 | + errorFn(w, fmt.Errorf("X-Attestation-Nonce value contains invalid characters")) |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + nonce = []byte(nonceVal) |
| 96 | + } |
| 97 | + |
| 98 | + ctx, cancel, err := runPreMiddleware(r) |
| 99 | + if err != nil { |
| 100 | + errorFn(w, err) |
| 101 | + return |
| 102 | + } |
| 103 | + defer cancel() |
| 104 | + |
| 105 | + var body bytes.Buffer |
| 106 | + ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor) |
| 107 | + ww.Tee(&body) |
| 108 | + ww.Discard() |
| 109 | + |
| 110 | + next.ServeHTTP(ww, r.WithContext(ctx)) |
| 111 | + |
| 112 | + r.Body = io.NopCloser(bytes.NewBuffer(reqBody)) |
| 113 | + if err := runPostMiddleware(ww, r, body.Bytes(), nonce); err != nil { |
| 114 | + errorFn(w, err) |
| 115 | + return |
| 116 | + } |
| 117 | + |
| 118 | + w.WriteHeader(ww.Status()) |
| 119 | + if _, err := body.WriteTo(w); err != nil { |
| 120 | + errorFn(w, err) |
| 121 | + } |
| 122 | + }) |
| 123 | + } |
| 124 | +} |
| 125 | + |
| 126 | +func isNonceValid(s string) bool { |
| 127 | + for i := 0; i < len(s); i++ { |
| 128 | + c := s[i] |
| 129 | + if (c >= 'a' && c <= 'z') || |
| 130 | + (c >= 'A' && c <= 'Z') || |
| 131 | + (c >= '0' && c <= '9') || |
| 132 | + c == '.' || c == '_' || c == '-' || c == '/' || c == '+' || c == '=' { |
| 133 | + continue |
| 134 | + } |
| 135 | + return false |
| 136 | + } |
| 137 | + return true |
| 138 | +} |
0 commit comments