|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Use of this software is governed by the CockroachDB Software License |
| 4 | +// included in the /LICENSE file. |
| 5 | + |
| 6 | +package apiinternal |
| 7 | + |
| 8 | +import ( |
| 9 | + "context" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "net/url" |
| 13 | + "reflect" |
| 14 | + |
| 15 | + "github.com/cockroachdb/cockroach/pkg/roachpb" |
| 16 | + "github.com/cockroachdb/cockroach/pkg/rpc/rpcbase" |
| 17 | + "github.com/cockroachdb/cockroach/pkg/server/authserver" |
| 18 | + "github.com/cockroachdb/cockroach/pkg/server/serverpb" |
| 19 | + "github.com/cockroachdb/cockroach/pkg/server/srverrors" |
| 20 | + "github.com/cockroachdb/cockroach/pkg/settings/cluster" |
| 21 | + "github.com/cockroachdb/cockroach/pkg/util/httputil" |
| 22 | + "github.com/cockroachdb/cockroach/pkg/util/log" |
| 23 | + "github.com/cockroachdb/cockroach/pkg/util/protoutil" |
| 24 | + "github.com/cockroachdb/errors" |
| 25 | + "github.com/gogo/protobuf/jsonpb" |
| 26 | + "github.com/gogo/protobuf/proto" |
| 27 | + "github.com/gorilla/mux" |
| 28 | + "github.com/gorilla/schema" |
| 29 | + "github.com/grpc-ecosystem/grpc-gateway/runtime" |
| 30 | + "google.golang.org/grpc/codes" |
| 31 | + "google.golang.org/grpc/status" |
| 32 | +) |
| 33 | + |
| 34 | +// httpMethod represents HTTP methods supported by the API. |
| 35 | +type httpMethod string |
| 36 | + |
| 37 | +// Supported HTTP methods for the internal API. |
| 38 | +const ( |
| 39 | + GET httpMethod = http.MethodGet |
| 40 | + POST httpMethod = http.MethodPost |
| 41 | +) |
| 42 | + |
| 43 | +var decoder = schema.NewDecoder() |
| 44 | + |
| 45 | +// route defines a REST endpoint with its handler and HTTP method. |
| 46 | +type route struct { |
| 47 | + method httpMethod |
| 48 | + path string |
| 49 | + handler http.HandlerFunc |
| 50 | +} |
| 51 | + |
| 52 | +// apiInternalServer provides REST endpoints that proxy to RPC services. It |
| 53 | +// serves as a bridge between HTTP REST clients and internal RPC services. |
| 54 | +type apiInternalServer struct { |
| 55 | + mux *mux.Router |
| 56 | + status serverpb.RPCStatusClient |
| 57 | +} |
| 58 | + |
| 59 | +// NewAPIInternalServer creates a new REST API server that proxies to internal |
| 60 | +// RPC services. It establishes connections to the RPC services and registers |
| 61 | +// all REST endpoints. |
| 62 | +func NewAPIInternalServer( |
| 63 | + ctx context.Context, nd rpcbase.NodeDialer, localNodeID roachpb.NodeID, cs *cluster.Settings, |
| 64 | +) (*apiInternalServer, error) { |
| 65 | + status, err := serverpb.DialStatusClient(nd, ctx, localNodeID, cs) |
| 66 | + if err != nil { |
| 67 | + return nil, err |
| 68 | + } |
| 69 | + |
| 70 | + r := &apiInternalServer{ |
| 71 | + status: status, |
| 72 | + mux: mux.NewRouter(), |
| 73 | + } |
| 74 | + |
| 75 | + r.registerStatusRoutes() |
| 76 | + |
| 77 | + decoder.SetAliasTag("json") |
| 78 | + decoder.IgnoreUnknownKeys(true) |
| 79 | + |
| 80 | + return r, nil |
| 81 | +} |
| 82 | + |
| 83 | +// ServeHTTP implements http.Handler interface |
| 84 | +func (r *apiInternalServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 85 | + r.mux.ServeHTTP(w, req) |
| 86 | +} |
| 87 | + |
| 88 | +// createHandler creates an HTTP handler function that proxies requests to the |
| 89 | +// given RPC method. |
| 90 | +func createHandler[TReq, TResp protoutil.Message]( |
| 91 | + rpcMethod func(context.Context, TReq) (TResp, error), |
| 92 | +) http.HandlerFunc { |
| 93 | + var zero TReq |
| 94 | + msgName := proto.MessageName(zero) |
| 95 | + msgType := proto.MessageType(msgName) |
| 96 | + if msgType == nil { |
| 97 | + panic(errors.AssertionFailedf("failed to determine request protobuf type: %s", msgName)) |
| 98 | + } |
| 99 | + return func(w http.ResponseWriter, req *http.Request) { |
| 100 | + newReq := reflect.New(msgType.Elem()).Interface().(TReq) |
| 101 | + if err := executeRPC(w, req, rpcMethod, newReq); err != nil { |
| 102 | + ctx := req.Context() |
| 103 | + writeHTTPError(ctx, w, req, err) |
| 104 | + } |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +// executeRPC is a generic function that handles the common pattern of: |
| 109 | +// 1. Decoding HTTP request parameters (query string for GET, body for POST) |
| 110 | +// 2. Forwarding HTTP auth information to the RPC context |
| 111 | +// 3. Calling the RPC method |
| 112 | +// 4. Writing the response back to the HTTP client |
| 113 | +// |
| 114 | +// This eliminates boilerplate code across all endpoint handlers. |
| 115 | +func executeRPC[TReq, TResp protoutil.Message]( |
| 116 | + w http.ResponseWriter, |
| 117 | + req *http.Request, |
| 118 | + rpcMethod func(context.Context, TReq) (TResp, error), |
| 119 | + rpcReq TReq, |
| 120 | +) error { |
| 121 | + ctx := req.Context() |
| 122 | + ctx = authserver.ForwardHTTPAuthInfoToRPCCalls(ctx, req) |
| 123 | + |
| 124 | + if err := decoder.Decode(rpcReq, req.URL.Query()); err != nil { |
| 125 | + return err |
| 126 | + } |
| 127 | + if err := decodePathVars(rpcReq, mux.Vars(req)); err != nil { |
| 128 | + return err |
| 129 | + } |
| 130 | + // For POST requests, decode the request body (JSON or protobuf) |
| 131 | + if req.Method == http.MethodPost { |
| 132 | + if err := decodeRequest(req, rpcReq); err != nil { |
| 133 | + return status.Errorf(codes.InvalidArgument, "failed to decode request body: %v", err) |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + resp, err := rpcMethod(ctx, rpcReq) |
| 138 | + if err != nil { |
| 139 | + return err |
| 140 | + } |
| 141 | + return writeResponse(ctx, w, req, http.StatusOK, resp) |
| 142 | +} |
| 143 | + |
| 144 | +func decodePathVars[TReq protoutil.Message](rpcReq TReq, vars map[string]string) error { |
| 145 | + pathParams := make(url.Values) |
| 146 | + for k, v := range vars { |
| 147 | + pathParams[k] = []string{v} |
| 148 | + } |
| 149 | + return decoder.Decode(rpcReq, pathParams) |
| 150 | +} |
| 151 | + |
| 152 | +// writeHTTPError converts an error to an HTTP error response. It handles gRPC |
| 153 | +// status codes and converts them to appropriate HTTP status codes. Internal |
| 154 | +// errors are masked to avoid leaking implementation details. |
| 155 | +func writeHTTPError(ctx context.Context, w http.ResponseWriter, req *http.Request, err error) { |
| 156 | + s, ok := status.FromError(err) |
| 157 | + if !ok { |
| 158 | + s = status.New(codes.Unknown, err.Error()) |
| 159 | + } |
| 160 | + |
| 161 | + message := s.Message() |
| 162 | + if s.Code() == codes.Internal { |
| 163 | + message = srverrors.ErrAPIInternalErrorString |
| 164 | + log.Dev.Errorf(ctx, "failed internal API [%s] %s - %v", req.Method, req.URL.Path, err) |
| 165 | + } else { |
| 166 | + log.Ops.Errorf(ctx, "failed internal API [%s] %s - %v", req.Method, req.URL.Path, err) |
| 167 | + } |
| 168 | + |
| 169 | + data := &serverpb.ResponseError{ |
| 170 | + Error: message, |
| 171 | + Message: message, |
| 172 | + Code: int32(s.Code()), |
| 173 | + // Details field is intentionally not populated as it's unused |
| 174 | + } |
| 175 | + |
| 176 | + // Convert gRPC status code to HTTP status code |
| 177 | + // TODO(server): eliminate this dependency on grpc-gateway when |
| 178 | + // migrating away from it |
| 179 | + httpCode := runtime.HTTPStatusFromCode(s.Code()) |
| 180 | + |
| 181 | + if err := writeResponse(ctx, w, req, httpCode, data); err != nil { |
| 182 | + log.Dev.Errorf(ctx, "failed to respond with error: %v", err) |
| 183 | + const fallback = `{"code": 13, "message": "failed to marshal error message"}` |
| 184 | + if _, err := io.WriteString(w, fallback); err != nil { |
| 185 | + log.Dev.Errorf(ctx, "failed to write fallback error: %v", err) |
| 186 | + } |
| 187 | + } |
| 188 | +} |
| 189 | + |
| 190 | +// writeResponse writes a protobuf message as an HTTP response. It supports both |
| 191 | +// JSON and protobuf content types based on the request headers. |
| 192 | +func writeResponse( |
| 193 | + ctx context.Context, |
| 194 | + w http.ResponseWriter, |
| 195 | + req *http.Request, |
| 196 | + code int, |
| 197 | + payload protoutil.Message, |
| 198 | +) error { |
| 199 | + // Determine the response content type by checking Accept header first, then |
| 200 | + // falling back to Content-Type header. Default to JSON if neither specifies |
| 201 | + // a supported type. |
| 202 | + resContentType := selectContentType(append( |
| 203 | + req.Header[httputil.AcceptEncodingHeader], |
| 204 | + req.Header[httputil.ContentTypeHeader]...)) |
| 205 | + |
| 206 | + var buf []byte |
| 207 | + switch resContentType { |
| 208 | + case httputil.ProtoContentType: |
| 209 | + b, err := protoutil.Marshal(payload) |
| 210 | + if err != nil { |
| 211 | + return status.Errorf(codes.Internal, "failed to marshal the protobuf response: %v", err) |
| 212 | + } |
| 213 | + buf = b |
| 214 | + case httputil.JSONContentType, httputil.MIMEWildcard: |
| 215 | + jsonpb := &protoutil.JSONPb{ |
| 216 | + EnumsAsInts: true, |
| 217 | + EmitDefaults: true, |
| 218 | + Indent: " ", |
| 219 | + } |
| 220 | + b, err := jsonpb.Marshal(payload) |
| 221 | + if err != nil { |
| 222 | + return status.Errorf(codes.Internal, "failed to marshal the JSON response: %v", err) |
| 223 | + } |
| 224 | + buf = b |
| 225 | + } |
| 226 | + |
| 227 | + w.Header().Set("Content-Type", resContentType) |
| 228 | + w.WriteHeader(code) |
| 229 | + if _, err := w.Write(buf); err != nil { |
| 230 | + return status.Errorf(codes.Internal, "failed to write HTTP response: %v", err) |
| 231 | + } |
| 232 | + return nil |
| 233 | +} |
| 234 | + |
| 235 | +// decodeRequest decodes the request body into a protobuf message. It supports |
| 236 | +// both JSON and protobuf content types, defaulting to JSON. |
| 237 | +func decodeRequest(req *http.Request, target protoutil.Message) error { |
| 238 | + if req.Body == nil { |
| 239 | + return nil |
| 240 | + } |
| 241 | + reqContentType := selectContentType(req.Header[httputil.ContentTypeHeader]) |
| 242 | + switch reqContentType { |
| 243 | + case httputil.JSONContentType, httputil.MIMEWildcard: |
| 244 | + return jsonpb.Unmarshal(req.Body, target) |
| 245 | + case httputil.ProtoContentType: |
| 246 | + bytes, err := io.ReadAll(req.Body) |
| 247 | + if err != nil { |
| 248 | + return err |
| 249 | + } |
| 250 | + return protoutil.Unmarshal(bytes, target) |
| 251 | + default: |
| 252 | + return jsonpb.Unmarshal(req.Body, target) |
| 253 | + } |
| 254 | +} |
| 255 | + |
| 256 | +// selectContentType chooses the appropriate content type from a list of |
| 257 | +// options. It prefers protobuf or JSON if available, defaulting to JSON if none |
| 258 | +// match. |
| 259 | +func selectContentType(contentTypes []string) string { |
| 260 | + for _, c := range contentTypes { |
| 261 | + switch c { |
| 262 | + case httputil.ProtoContentType: |
| 263 | + return httputil.ProtoContentType |
| 264 | + case httputil.JSONContentType, httputil.MIMEWildcard: |
| 265 | + return httputil.JSONContentType |
| 266 | + } |
| 267 | + } |
| 268 | + return httputil.JSONContentType |
| 269 | +} |
0 commit comments