2020-06-12 08:55:57 -05:00
|
|
|
// Copyright 2020 The Matrix.org Foundation C.I.C.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package httputil
|
2017-05-23 11:43:05 -05:00
|
|
|
|
|
|
|
import (
|
2021-03-24 05:25:24 -05:00
|
|
|
"fmt"
|
2020-04-15 11:48:40 -05:00
|
|
|
"io"
|
2017-07-17 11:20:57 -05:00
|
|
|
"net/http"
|
2020-04-15 11:48:40 -05:00
|
|
|
"net/http/httptest"
|
|
|
|
"net/http/httputil"
|
|
|
|
"os"
|
|
|
|
"strings"
|
2017-07-17 11:20:57 -05:00
|
|
|
|
2021-03-24 05:25:24 -05:00
|
|
|
"github.com/getsentry/sentry-go"
|
2017-05-23 11:43:05 -05:00
|
|
|
"github.com/matrix-org/util"
|
2019-08-14 12:34:49 -05:00
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
2019-12-17 10:47:45 -06:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promauto"
|
2018-05-23 09:42:08 -05:00
|
|
|
"github.com/prometheus/client_golang/prometheus/promhttp"
|
2020-04-14 09:54:35 -05:00
|
|
|
"github.com/sirupsen/logrus"
|
2022-12-05 06:53:36 -06:00
|
|
|
|
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth"
|
2023-03-13 10:45:14 -05:00
|
|
|
"github.com/matrix-org/dendrite/internal"
|
2022-12-05 06:53:36 -06:00
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
2023-05-09 17:46:49 -05:00
|
|
|
"github.com/matrix-org/gomatrixserverlib/spec"
|
2017-05-23 11:43:05 -05:00
|
|
|
)
|
|
|
|
|
2020-04-14 09:54:35 -05:00
|
|
|
// BasicAuth is used for authorization on /metrics handlers
|
|
|
|
type BasicAuth struct {
|
|
|
|
Username string `yaml:"username"`
|
|
|
|
Password string `yaml:"password"`
|
|
|
|
}
|
|
|
|
|
2022-11-11 03:52:08 -06:00
|
|
|
type AuthAPIOpts struct {
|
|
|
|
GuestAccessAllowed bool
|
|
|
|
}
|
|
|
|
|
|
|
|
// AuthAPIOption is an option to MakeAuthAPI to add additional checks (e.g. guest access) to verify
|
|
|
|
// the user is allowed to do specific things.
|
|
|
|
type AuthAPIOption func(opts *AuthAPIOpts)
|
|
|
|
|
|
|
|
// WithAllowGuests checks that guest users have access to this endpoint
|
|
|
|
func WithAllowGuests() AuthAPIOption {
|
|
|
|
return func(opts *AuthAPIOpts) {
|
|
|
|
opts.GuestAccessAllowed = true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-16 17:17:03 -05:00
|
|
|
// MakeAuthAPI turns a util.JSONRequestHandler function into an http.Handler which authenticates the request.
|
|
|
|
func MakeAuthAPI(
|
2022-05-05 03:56:03 -05:00
|
|
|
metricsName string, userAPI userapi.QueryAcccessTokenAPI,
|
2020-06-16 08:10:55 -05:00
|
|
|
f func(*http.Request, *userapi.Device) util.JSONResponse,
|
2022-11-11 03:52:08 -06:00
|
|
|
checks ...AuthAPIOption,
|
2018-07-16 17:17:03 -05:00
|
|
|
) http.Handler {
|
2017-09-04 07:14:01 -05:00
|
|
|
h := func(req *http.Request) util.JSONResponse {
|
2022-01-28 05:14:20 -06:00
|
|
|
logger := util.GetLogger(req.Context())
|
2020-06-16 08:10:55 -05:00
|
|
|
device, err := auth.VerifyUserFromRequest(req, userAPI)
|
2018-07-16 17:17:03 -05:00
|
|
|
if err != nil {
|
2022-01-28 05:14:20 -06:00
|
|
|
logger.Debugf("VerifyUserFromRequest %s -> HTTP %d", req.RemoteAddr, err.Code)
|
2018-07-16 17:17:03 -05:00
|
|
|
return *err
|
2017-05-23 11:43:05 -05:00
|
|
|
}
|
2020-03-09 09:37:51 -05:00
|
|
|
// add the user ID to the logger
|
|
|
|
logger = logger.WithField("user_id", device.UserID)
|
|
|
|
req = req.WithContext(util.ContextWithLogger(req.Context(), logger))
|
2021-03-24 05:25:24 -05:00
|
|
|
// add the user to Sentry, if enabled
|
|
|
|
hub := sentry.GetHubFromContext(req.Context())
|
|
|
|
if hub != nil {
|
2022-09-05 11:35:43 -05:00
|
|
|
hub.Scope().SetUser(sentry.User{
|
2022-09-05 11:37:17 -05:00
|
|
|
Username: device.UserID,
|
2022-09-05 11:35:43 -05:00
|
|
|
})
|
2021-03-24 05:25:24 -05:00
|
|
|
hub.Scope().SetTag("user_id", device.UserID)
|
|
|
|
hub.Scope().SetTag("device_id", device.ID)
|
|
|
|
}
|
|
|
|
defer func() {
|
|
|
|
if r := recover(); r != nil {
|
|
|
|
if hub != nil {
|
|
|
|
hub.CaptureException(fmt.Errorf("%s panicked", req.URL.Path))
|
|
|
|
}
|
|
|
|
// re-panic to return the 500
|
|
|
|
panic(r)
|
|
|
|
}
|
|
|
|
}()
|
2018-07-16 17:17:03 -05:00
|
|
|
|
2022-11-11 03:52:08 -06:00
|
|
|
// apply additional checks, if any
|
|
|
|
opts := AuthAPIOpts{}
|
|
|
|
for _, opt := range checks {
|
|
|
|
opt(&opts)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !opts.GuestAccessAllowed && device.AccountType == userapi.AccountTypeGuest {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
2023-05-09 17:46:49 -05:00
|
|
|
JSON: spec.GuestAccessForbidden("Guest access not allowed"),
|
2022-11-11 03:52:08 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-24 05:25:24 -05:00
|
|
|
jsonRes := f(req, device)
|
|
|
|
// do not log 4xx as errors as they are client fails, not server fails
|
|
|
|
if hub != nil && jsonRes.Code >= 500 {
|
|
|
|
hub.Scope().SetExtra("response", jsonRes)
|
|
|
|
hub.CaptureException(fmt.Errorf("%s returned HTTP %d", req.URL.Path, jsonRes.Code))
|
|
|
|
}
|
|
|
|
return jsonRes
|
2017-09-04 07:14:01 -05:00
|
|
|
}
|
2017-09-28 08:50:40 -05:00
|
|
|
return MakeExternalAPI(metricsName, h)
|
2017-05-23 11:43:05 -05:00
|
|
|
}
|
|
|
|
|
2022-08-12 06:00:07 -05:00
|
|
|
// MakeAdminAPI is a wrapper around MakeAuthAPI which enforces that the request can only be
|
|
|
|
// completed by a user that is a server administrator.
|
|
|
|
func MakeAdminAPI(
|
|
|
|
metricsName string, userAPI userapi.QueryAcccessTokenAPI,
|
|
|
|
f func(*http.Request, *userapi.Device) util.JSONResponse,
|
|
|
|
) http.Handler {
|
|
|
|
return MakeAuthAPI(metricsName, userAPI, func(req *http.Request, device *userapi.Device) util.JSONResponse {
|
|
|
|
if device.AccountType != userapi.AccountTypeAdmin {
|
|
|
|
return util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
2023-05-09 17:46:49 -05:00
|
|
|
JSON: spec.Forbidden("This API can only be used by admin users."),
|
2022-08-12 06:00:07 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return f(req, device)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2017-09-28 08:50:40 -05:00
|
|
|
// MakeExternalAPI turns a util.JSONRequestHandler function into an http.Handler.
|
|
|
|
// This is used for APIs that are called from the internet.
|
|
|
|
func MakeExternalAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler {
|
2020-04-15 11:48:40 -05:00
|
|
|
// TODO: We shouldn't be directly reading env vars here, inject it in instead.
|
|
|
|
// Refactor this when we split out config structs.
|
|
|
|
verbose := false
|
|
|
|
if os.Getenv("DENDRITE_TRACE_HTTP") == "1" {
|
|
|
|
verbose = true
|
|
|
|
}
|
2017-09-28 08:50:40 -05:00
|
|
|
h := util.MakeJSONAPI(util.NewJSONRequestHandler(f))
|
|
|
|
withSpan := func(w http.ResponseWriter, req *http.Request) {
|
2020-04-15 11:48:40 -05:00
|
|
|
nextWriter := w
|
|
|
|
if verbose {
|
|
|
|
logger := logrus.NewEntry(logrus.StandardLogger())
|
|
|
|
// Log outgoing response
|
|
|
|
rec := httptest.NewRecorder()
|
|
|
|
nextWriter = rec
|
|
|
|
defer func() {
|
|
|
|
resp := rec.Result()
|
|
|
|
dump, err := httputil.DumpResponse(resp, true)
|
|
|
|
if err != nil {
|
|
|
|
logger.Debugf("Failed to dump outgoing response: %s", err)
|
|
|
|
} else {
|
|
|
|
strSlice := strings.Split(string(dump), "\n")
|
|
|
|
for _, s := range strSlice {
|
|
|
|
logger.Debug(s)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// copy the response to the client
|
|
|
|
for hdr, vals := range resp.Header {
|
|
|
|
for _, val := range vals {
|
|
|
|
w.Header().Add(hdr, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
w.WriteHeader(resp.StatusCode)
|
|
|
|
// discard errors as this is for debugging
|
|
|
|
_, _ = io.Copy(w, resp.Body)
|
|
|
|
_ = resp.Body.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Log incoming request
|
|
|
|
dump, err := httputil.DumpRequest(req, true)
|
|
|
|
if err != nil {
|
|
|
|
logger.Debugf("Failed to dump incoming request: %s", err)
|
|
|
|
} else {
|
|
|
|
strSlice := strings.Split(string(dump), "\n")
|
|
|
|
for _, s := range strSlice {
|
|
|
|
logger.Debug(s)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-13 10:45:14 -05:00
|
|
|
trace, ctx := internal.StartTask(req.Context(), metricsName)
|
|
|
|
defer trace.EndTask()
|
|
|
|
req = req.WithContext(ctx)
|
2020-04-15 11:48:40 -05:00
|
|
|
h.ServeHTTP(nextWriter, req)
|
|
|
|
|
2017-09-28 08:50:40 -05:00
|
|
|
}
|
|
|
|
|
2018-05-23 09:42:08 -05:00
|
|
|
return http.HandlerFunc(withSpan)
|
2017-09-28 08:50:40 -05:00
|
|
|
}
|
|
|
|
|
2019-08-14 12:34:49 -05:00
|
|
|
// MakeHTMLAPI adds Span metrics to the HTML Handler function
|
|
|
|
// This is used to serve HTML alongside JSON error messages
|
2022-12-23 07:11:11 -06:00
|
|
|
func MakeHTMLAPI(metricsName string, enableMetrics bool, f func(http.ResponseWriter, *http.Request)) http.Handler {
|
2019-08-14 12:34:49 -05:00
|
|
|
withSpan := func(w http.ResponseWriter, req *http.Request) {
|
2023-03-13 10:45:14 -05:00
|
|
|
trace, ctx := internal.StartTask(req.Context(), metricsName)
|
|
|
|
defer trace.EndTask()
|
|
|
|
req = req.WithContext(ctx)
|
2022-12-23 07:11:11 -06:00
|
|
|
f(w, req)
|
2019-08-14 12:34:49 -05:00
|
|
|
}
|
|
|
|
|
2022-12-22 04:54:03 -06:00
|
|
|
if !enableMetrics {
|
|
|
|
return http.HandlerFunc(withSpan)
|
|
|
|
}
|
|
|
|
|
2019-12-17 10:47:45 -06:00
|
|
|
return promhttp.InstrumentHandlerCounter(
|
|
|
|
promauto.NewCounterVec(
|
|
|
|
prometheus.CounterOpts{
|
2022-04-08 05:24:40 -05:00
|
|
|
Name: metricsName,
|
|
|
|
Help: "Total number of http requests for HTML resources",
|
|
|
|
Namespace: "dendrite",
|
2019-12-17 10:47:45 -06:00
|
|
|
},
|
|
|
|
[]string{"code"},
|
|
|
|
),
|
|
|
|
http.HandlerFunc(withSpan),
|
|
|
|
)
|
2019-08-14 12:34:49 -05:00
|
|
|
}
|
|
|
|
|
2020-04-14 09:54:35 -05:00
|
|
|
// WrapHandlerInBasicAuth adds basic auth to a handler. Only used for /metrics
|
|
|
|
func WrapHandlerInBasicAuth(h http.Handler, b BasicAuth) http.HandlerFunc {
|
|
|
|
if b.Username == "" || b.Password == "" {
|
|
|
|
logrus.Warn("Metrics are exposed without protection. Make sure you set up protection at proxy level.")
|
|
|
|
}
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Serve without authorization if either Username or Password is unset
|
|
|
|
if b.Username == "" || b.Password == "" {
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
user, pass, ok := r.BasicAuth()
|
|
|
|
|
|
|
|
if !ok || user != b.Username || pass != b.Password {
|
|
|
|
http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-06 03:36:50 -06:00
|
|
|
// WrapHandlerInCORS adds CORS headers to all responses, including all error
|
|
|
|
// responses.
|
|
|
|
// Handles OPTIONS requests directly.
|
|
|
|
func WrapHandlerInCORS(h http.Handler) http.HandlerFunc {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
|
|
|
w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
|
|
|
|
|
2018-03-13 10:55:45 -05:00
|
|
|
if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
2017-12-06 03:36:50 -06:00
|
|
|
// Its easiest just to always return a 200 OK for everything. Whether
|
|
|
|
// this is technically correct or not is a question, but in the end this
|
|
|
|
// is what a lot of other people do (including synapse) and the clients
|
|
|
|
// are perfectly happy with it.
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
} else {
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|