-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
209 lines (174 loc) · 6.11 KB
/
server.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
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
// Copyright (c) Mondoo, Inc.
// SPDX-License-Identifier: MPL-2.0
package ranger
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"go.mondoo.com/ranger-rpc/codes"
"go.mondoo.com/ranger-rpc/status"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
const (
ContentTypeProtobuf = "application/protobuf"
ContentTypeOctetProtobuf = "application/octet-stream"
ContentTypeGrpcProtobuf = "application/grpc+proto"
ContentTypeJson = "application/json"
)
var validContentTypes = map[string]struct{}{
ContentTypeProtobuf: {},
ContentTypeOctetProtobuf: {},
ContentTypeGrpcProtobuf: {},
ContentTypeJson: {},
}
var tracer = otel.Tracer("go.mondoo.com/mondoo/ranger-rpc")
// Method represents a RPC method and is used by protoc-gen-rangerrpc
type Method func(ctx context.Context, reqBytes *[]byte) (proto.Message, error)
// Service is the struct that holds all available methods. The protoc-gen-rangerrpc will generate the
// correct client and service definition to be used.
type Service struct {
Name string
Methods map[string]Method
}
// NewServer creates a new server. This function is used by the protoc-gen-rangerrpc generated code and
// should not be used directly.
func NewRPCServer(service *Service) *server {
var b strings.Builder
b.WriteString("/")
b.WriteString(service.Name)
b.WriteString("/")
return &server{service: service, prefix: b.String()}
}
type server struct {
service *Service
prefix string
}
// ServeHTTP is the main entry point for the http server.
func (s *server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
ctx, span := tracer.Start(req.Context(), "ranger.server.ServeHTTP", trace.WithAttributes(
attribute.String("mondoo.ranger.service", s.service.Name)))
defer span.End()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
req = req.WithContext(ctx)
contentType := req.Header.Get("Content-Type")
// verify content type
err := verifyContentType(req, contentType)
if err != nil {
HttpError(span, w, req, err)
return
}
if !strings.HasPrefix(req.URL.Path, s.prefix) {
HttpError(span, w, req, status.Error(codes.NotFound, req.URL.Path+" is not available"))
return
}
// extract the rpc method name and invoke the method
name := strings.TrimPrefix(req.URL.Path, s.prefix)
span.SetAttributes(attribute.String("mondoo.ranger.method", name))
method, ok := s.service.Methods[name]
if !ok {
err := status.Error(codes.NotFound, "method not defined")
HttpError(span, w, req, err)
return
}
rctx, rcancel, body, err := preProcessRequest(ctx, span, req)
if err != nil {
HttpError(span, w, req, err)
return
}
defer rcancel()
// invoke method and send the response
resp, err := method(rctx, &body)
if err != nil {
HttpError(span, w, req, err)
return
}
// check if the accept header is set, otherwise use the incoming content type
encodingType := determineResponseType(contentType, req.Header.Get("Accept"))
s.sendResponse(w, req, resp, encodingType)
}
// preProcessRequest is used to preprocess the incoming request.
// It returns the context, a cancel function and the body of the request. The cancel function can be used to cancel
// the context. It also adds the http headers to the context.
func preProcessRequest(ctx context.Context, span trace.Span, req *http.Request) (context.Context, context.CancelFunc, []byte, error) {
// read body content
body, err := io.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
span.RecordError(err)
return nil, nil, nil, status.Error(codes.DataLoss, "unrecoverable data loss or corruption")
}
// pass-through the http headers
rctx, rcancel, err := AnnotateContext(ctx, req)
if err != nil {
return nil, rcancel, nil, err
}
return rctx, rcancel, body, nil
}
func (s *server) sendResponse(w http.ResponseWriter, req *http.Request, resp proto.Message, contentType string) {
payload, contentType, err := convertProtoToPayload(resp, contentType)
if err != nil {
span := trace.SpanFromContext(req.Context())
HttpError(span, w, req, status.Error(codes.Internal, "error encoding response"))
return
}
h := w.Header()
h.Set("Content-Type", contentType)
w.WriteHeader(http.StatusOK)
w.Write(payload)
}
// convertProtoToPayload converts a proto message to the approaptiate formatted payload.
// Depending on the accept header it will return the payload as marshalled protobuf or json.
func convertProtoToPayload(resp proto.Message, contentType string) ([]byte, string, error) {
var err error
var payload []byte
switch contentType {
case ContentTypeProtobuf, ContentTypeGrpcProtobuf, ContentTypeOctetProtobuf:
contentType = ContentTypeProtobuf
payload, err = proto.Marshal(resp)
// as default, we return json to be compatible with browsers, since they do not
// request as application/json as default
default:
contentType = ContentTypeJson
payload, err = jsonpb.MarshalOptions{UseProtoNames: true}.Marshal(resp)
}
return payload, contentType, err
}
// verifyContentType validates the content type of the request is known.
func verifyContentType(req *http.Request, contentType string) error {
// we assume "application/protobuf" if no content-type is set
if contentType == "" {
return nil
}
i := strings.Index(contentType, ";")
if i == -1 {
i = len(contentType)
}
ct := strings.TrimSpace(strings.ToLower(contentType[:i]))
// check that the incoming request has a valid content type
_, ok := validContentTypes[ct]
if ok {
return nil
}
// if we reached here, we have to handle an unexpected incoming type
return status.Error(codes.InvalidArgument, fmt.Sprintf("unexpected content-type: %q", req.Header.Get("Content-Type")))
}
// determineResponseType returns the content type based on the Content-Type and Accept header.
func determineResponseType(contenttype string, accept string) string {
// use provided content type if no accept header was provided
if accept == "" {
accept = contenttype
}
switch accept {
case ContentTypeProtobuf, ContentTypeGrpcProtobuf, ContentTypeOctetProtobuf:
return ContentTypeProtobuf
default:
return ContentTypeJson
}
}