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 (
|
2022-02-15 04:07:24 -06:00
|
|
|
"bytes"
|
2020-06-02 06:42:36 -05:00
|
|
|
"context"
|
2022-02-15 04:07:24 -06:00
|
|
|
"crypto/hmac"
|
|
|
|
"crypto/sha256"
|
|
|
|
"encoding/hex"
|
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"
|
2022-03-07 02:45:24 -06:00
|
|
|
"net/url"
|
2020-04-15 11:48:40 -05:00
|
|
|
"os"
|
|
|
|
"strings"
|
2020-06-02 06:42:36 -05:00
|
|
|
"sync"
|
2017-09-04 07:14:01 -05:00
|
|
|
"time"
|
2017-07-17 11:20:57 -05:00
|
|
|
|
2021-03-24 05:25:24 -05:00
|
|
|
"github.com/getsentry/sentry-go"
|
2020-05-22 05:43:17 -05:00
|
|
|
"github.com/gorilla/mux"
|
2017-05-23 11:43:05 -05:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/auth"
|
2022-02-14 11:11:56 -06:00
|
|
|
"github.com/matrix-org/dendrite/clientapi/jsonerror"
|
2021-11-24 04:45:23 -06:00
|
|
|
federationapiAPI "github.com/matrix-org/dendrite/federationapi/api"
|
2022-02-14 11:11:56 -06:00
|
|
|
"github.com/matrix-org/dendrite/setup/config"
|
2020-06-16 08:10:55 -05:00
|
|
|
userapi "github.com/matrix-org/dendrite/userapi/api"
|
2017-09-04 07:14:01 -05:00
|
|
|
"github.com/matrix-org/gomatrixserverlib"
|
2017-05-23 11:43:05 -05:00
|
|
|
"github.com/matrix-org/util"
|
2017-09-28 08:50:40 -05:00
|
|
|
opentracing "github.com/opentracing/opentracing-go"
|
|
|
|
"github.com/opentracing/opentracing-go/ext"
|
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"
|
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-03-04 10:01:18 -06:00
|
|
|
// AuthAPICheck is an option to MakeAuthAPI to add additional checks (e.g. WithConsentCheck) to verify
|
|
|
|
// the user is allowed to do specific things.
|
|
|
|
type AuthAPICheck func(ctx context.Context, device *userapi.Device) *util.JSONResponse
|
2022-02-21 09:23:28 -06:00
|
|
|
|
2022-03-04 10:01:18 -06:00
|
|
|
// WithConsentCheck checks that a user has given his consent.
|
|
|
|
func WithConsentCheck(options config.UserConsentOptions, api userapi.UserInternalAPI) AuthAPICheck {
|
|
|
|
return func(ctx context.Context, device *userapi.Device) *util.JSONResponse {
|
|
|
|
if !options.Enabled {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return checkConsent(ctx, device.UserID, api, options)
|
|
|
|
}
|
|
|
|
}
|
2022-02-21 09:23:28 -06:00
|
|
|
|
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-02-14 11:11:56 -06:00
|
|
|
metricsName string,
|
|
|
|
userAPI userapi.UserInternalAPI,
|
2022-03-04 10:01:18 -06:00
|
|
|
f func(*http.Request, *userapi.Device) util.JSONResponse, checks ...AuthAPICheck,
|
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 {
|
|
|
|
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-03-04 10:01:18 -06:00
|
|
|
// apply additional checks, if any
|
|
|
|
for _, opt := range checks {
|
|
|
|
resp := opt(req.Context(), device)
|
|
|
|
if resp != nil {
|
|
|
|
return *resp
|
2022-02-14 11:11:56 -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-03-04 10:01:18 -06:00
|
|
|
func checkConsent(ctx context.Context, userID string, userAPI userapi.UserInternalAPI, userConsentCfg config.UserConsentOptions) *util.JSONResponse {
|
2022-03-07 02:45:24 -06:00
|
|
|
localpart, _, err := gomatrixserverlib.SplitID('@', userID)
|
2022-02-15 04:07:24 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
// check which version of the policy the user accepted
|
|
|
|
res := &userapi.QueryPolicyVersionResponse{}
|
|
|
|
err = userAPI.QueryPolicyVersion(ctx, &userapi.QueryPolicyVersionRequest{
|
2022-03-07 02:45:24 -06:00
|
|
|
Localpart: localpart,
|
2022-02-15 04:07:24 -06:00
|
|
|
}, res)
|
|
|
|
if err != nil {
|
2022-03-04 10:01:18 -06:00
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("unable to get policy version"),
|
|
|
|
}
|
2022-02-15 04:07:24 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
// user hasn't accepted any policy, block access.
|
|
|
|
if userConsentCfg.Version != res.PolicyVersion {
|
|
|
|
uri, err := getConsentURL(userID, userConsentCfg)
|
|
|
|
if err != nil {
|
2022-03-04 10:01:18 -06:00
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("unable to get consent URL"),
|
|
|
|
}
|
2022-02-15 04:07:24 -06:00
|
|
|
}
|
|
|
|
msg := &bytes.Buffer{}
|
|
|
|
c := struct {
|
|
|
|
ConsentURL string
|
|
|
|
}{
|
|
|
|
ConsentURL: uri,
|
|
|
|
}
|
2022-02-21 07:27:13 -06:00
|
|
|
if err = userConsentCfg.TextTemplates.ExecuteTemplate(msg, "blockEventsError", c); err != nil {
|
2022-02-15 04:07:24 -06:00
|
|
|
logrus.Infof("error consent message: %+v", err)
|
2022-03-04 10:01:18 -06:00
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusInternalServerError,
|
|
|
|
JSON: jsonerror.Unknown("unable to execute template"),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return &util.JSONResponse{
|
|
|
|
Code: http.StatusForbidden,
|
|
|
|
JSON: jsonerror.ConsentNotGiven(uri, msg.String()),
|
2022-02-15 04:07:24 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// getConsentURL constructs the URL shown to users to accept the TOS
|
2022-03-07 02:45:24 -06:00
|
|
|
func getConsentURL(userID string, config config.UserConsentOptions) (string, error) {
|
2022-02-15 04:07:24 -06:00
|
|
|
mac := hmac.New(sha256.New, []byte(config.FormSecret))
|
2022-03-07 02:45:24 -06:00
|
|
|
_, err := mac.Write([]byte(userID))
|
2022-02-15 04:07:24 -06:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
hmac := hex.EncodeToString(mac.Sum(nil))
|
|
|
|
|
2022-03-07 02:45:24 -06:00
|
|
|
params := url.Values{}
|
|
|
|
params.Add("u", userID)
|
|
|
|
params.Add("h", string(hmac))
|
|
|
|
params.Add("v", config.Version)
|
|
|
|
|
|
|
|
return fmt.Sprintf("%s/_matrix/client/consent?%s", config.BaseURL, params.Encode()), nil
|
2022-02-15 04:07:24 -06:00
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-28 08:50:40 -05:00
|
|
|
span := opentracing.StartSpan(metricsName)
|
|
|
|
defer span.Finish()
|
|
|
|
req = req.WithContext(opentracing.ContextWithSpan(req.Context(), span))
|
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
|
|
|
|
func MakeHTMLAPI(metricsName string, f func(http.ResponseWriter, *http.Request) *util.JSONResponse) http.Handler {
|
|
|
|
withSpan := func(w http.ResponseWriter, req *http.Request) {
|
|
|
|
span := opentracing.StartSpan(metricsName)
|
|
|
|
defer span.Finish()
|
|
|
|
req = req.WithContext(opentracing.ContextWithSpan(req.Context(), span))
|
|
|
|
if err := f(w, req); err != nil {
|
|
|
|
h := util.MakeJSONAPI(util.NewJSONRequestHandler(func(req *http.Request) util.JSONResponse {
|
|
|
|
return *err
|
|
|
|
}))
|
|
|
|
h.ServeHTTP(w, req)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
2017-09-28 08:50:40 -05:00
|
|
|
// MakeInternalAPI turns a util.JSONRequestHandler function into an http.Handler.
|
|
|
|
// This is used for APIs that are internal to dendrite.
|
|
|
|
// If we are passed a tracing context in the request headers then we use that
|
|
|
|
// as the parent of any tracing spans we create.
|
|
|
|
func MakeInternalAPI(metricsName string, f func(*http.Request) util.JSONResponse) http.Handler {
|
|
|
|
h := util.MakeJSONAPI(util.NewJSONRequestHandler(f))
|
|
|
|
withSpan := func(w http.ResponseWriter, req *http.Request) {
|
|
|
|
carrier := opentracing.HTTPHeadersCarrier(req.Header)
|
|
|
|
tracer := opentracing.GlobalTracer()
|
|
|
|
clientContext, err := tracer.Extract(opentracing.HTTPHeaders, carrier)
|
|
|
|
var span opentracing.Span
|
|
|
|
if err == nil {
|
|
|
|
// Default to a span without RPC context.
|
|
|
|
span = tracer.StartSpan(metricsName)
|
|
|
|
} else {
|
|
|
|
// Set the RPC context.
|
|
|
|
span = tracer.StartSpan(metricsName, ext.RPCServerOption(clientContext))
|
|
|
|
}
|
|
|
|
defer span.Finish()
|
|
|
|
req = req.WithContext(opentracing.ContextWithSpan(req.Context(), span))
|
|
|
|
h.ServeHTTP(w, req)
|
|
|
|
}
|
|
|
|
|
2022-04-08 05:24:40 -05:00
|
|
|
return promhttp.InstrumentHandlerCounter(
|
|
|
|
promauto.NewCounterVec(
|
|
|
|
prometheus.CounterOpts{
|
|
|
|
Name: metricsName + "_requests_total",
|
|
|
|
Help: "Total number of internal API calls",
|
|
|
|
Namespace: "dendrite",
|
|
|
|
},
|
|
|
|
[]string{"code"},
|
|
|
|
),
|
|
|
|
promhttp.InstrumentHandlerResponseSize(
|
|
|
|
promauto.NewHistogramVec(
|
|
|
|
prometheus.HistogramOpts{
|
|
|
|
Namespace: "dendrite",
|
|
|
|
Name: metricsName + "_response_size_bytes",
|
|
|
|
Help: "A histogram of response sizes for requests.",
|
|
|
|
Buckets: []float64{200, 500, 900, 1500, 5000, 15000, 50000, 100000},
|
|
|
|
},
|
|
|
|
[]string{},
|
|
|
|
),
|
|
|
|
http.HandlerFunc(withSpan),
|
|
|
|
),
|
|
|
|
)
|
2017-05-23 11:43:05 -05:00
|
|
|
}
|
2017-08-03 09:10:39 -05:00
|
|
|
|
2017-09-04 07:14:01 -05:00
|
|
|
// MakeFedAPI makes an http.Handler that checks matrix federation authentication.
|
|
|
|
func MakeFedAPI(
|
|
|
|
metricsName string,
|
|
|
|
serverName gomatrixserverlib.ServerName,
|
2020-06-15 10:57:59 -05:00
|
|
|
keyRing gomatrixserverlib.JSONVerifier,
|
2020-06-02 06:42:36 -05:00
|
|
|
wakeup *FederationWakeups,
|
2020-06-04 05:14:08 -05:00
|
|
|
f func(*http.Request, *gomatrixserverlib.FederationRequest, map[string]string) util.JSONResponse,
|
2017-09-04 07:14:01 -05:00
|
|
|
) http.Handler {
|
|
|
|
h := func(req *http.Request) util.JSONResponse {
|
|
|
|
fedReq, errResp := gomatrixserverlib.VerifyHTTPRequest(
|
|
|
|
req, time.Now(), serverName, keyRing,
|
|
|
|
)
|
|
|
|
if fedReq == nil {
|
|
|
|
return errResp
|
|
|
|
}
|
2021-03-24 05:25:24 -05:00
|
|
|
// add the user to Sentry, if enabled
|
|
|
|
hub := sentry.GetHubFromContext(req.Context())
|
|
|
|
if hub != nil {
|
|
|
|
hub.Scope().SetTag("origin", string(fedReq.Origin()))
|
|
|
|
hub.Scope().SetTag("uri", fedReq.RequestURI())
|
|
|
|
}
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
}()
|
2020-06-02 06:42:36 -05:00
|
|
|
go wakeup.Wakeup(req.Context(), fedReq.Origin())
|
2020-06-04 05:14:08 -05:00
|
|
|
vars, err := URLDecodeMapValues(mux.Vars(req))
|
|
|
|
if err != nil {
|
2021-03-24 05:25:24 -05:00
|
|
|
return util.MatrixErrorResponse(400, "M_UNRECOGNISED", "badly encoded query params")
|
2020-06-04 05:14:08 -05:00
|
|
|
}
|
|
|
|
|
2021-03-24 05:25:24 -05:00
|
|
|
jsonRes := f(req, fedReq, vars)
|
|
|
|
// 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-09-04 07:14:01 -05:00
|
|
|
}
|
|
|
|
|
2020-06-02 06:42:36 -05:00
|
|
|
type FederationWakeups struct {
|
2021-11-24 04:45:23 -06:00
|
|
|
FsAPI federationapiAPI.FederationInternalAPI
|
2020-06-02 06:42:36 -05:00
|
|
|
origins sync.Map
|
|
|
|
}
|
|
|
|
|
|
|
|
func (f *FederationWakeups) Wakeup(ctx context.Context, origin gomatrixserverlib.ServerName) {
|
|
|
|
key, keyok := f.origins.Load(origin)
|
|
|
|
if keyok {
|
|
|
|
lastTime, ok := key.(time.Time)
|
|
|
|
if ok && time.Since(lastTime) < time.Minute {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
2021-11-24 04:45:23 -06:00
|
|
|
aliveReq := federationapiAPI.PerformServersAliveRequest{
|
2020-06-02 06:42:36 -05:00
|
|
|
Servers: []gomatrixserverlib.ServerName{origin},
|
|
|
|
}
|
2021-11-24 04:45:23 -06:00
|
|
|
aliveRes := federationapiAPI.PerformServersAliveResponse{}
|
2020-06-02 06:42:36 -05:00
|
|
|
if err := f.FsAPI.PerformServersAlive(ctx, &aliveReq, &aliveRes); err != nil {
|
|
|
|
util.GetLogger(ctx).WithError(err).WithFields(logrus.Fields{
|
|
|
|
"origin": origin,
|
|
|
|
}).Warn("incoming federation request failed to notify server alive")
|
|
|
|
} else {
|
|
|
|
f.origins.Store(origin, time.Now())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|