2023-01-27 21:37:20 +00:00
|
|
|
// Copyright (c) Tailscale Inc & AUTHORS
|
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2020-02-25 16:07:41 +00:00
|
|
|
|
2020-03-18 03:35:59 +00:00
|
|
|
// Package tsweb contains code used in various Tailscale webservers.
|
2020-02-25 16:07:41 +00:00
|
|
|
package tsweb
|
|
|
|
|
|
|
|
import (
|
2020-03-19 00:37:40 +00:00
|
|
|
"bufio"
|
2020-03-04 21:49:18 +00:00
|
|
|
"bytes"
|
2020-03-18 03:35:59 +00:00
|
|
|
"context"
|
2020-03-19 00:37:40 +00:00
|
|
|
"errors"
|
2020-02-25 16:07:41 +00:00
|
|
|
"expvar"
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
_ "net/http/pprof"
|
2022-07-26 03:55:44 +00:00
|
|
|
"net/netip"
|
2020-02-25 16:07:41 +00:00
|
|
|
"os"
|
|
|
|
"path/filepath"
|
2022-05-13 20:36:39 +00:00
|
|
|
"strconv"
|
2020-02-25 16:07:41 +00:00
|
|
|
"strings"
|
2022-05-13 20:56:55 +00:00
|
|
|
"sync"
|
2020-02-25 16:07:41 +00:00
|
|
|
"time"
|
|
|
|
|
2022-05-04 04:42:24 +00:00
|
|
|
"go4.org/mem"
|
2022-01-24 18:52:57 +00:00
|
|
|
"tailscale.com/envknob"
|
2021-01-26 23:00:05 +00:00
|
|
|
"tailscale.com/net/tsaddr"
|
2023-04-10 10:28:16 +00:00
|
|
|
"tailscale.com/tsweb/varz"
|
2020-03-18 03:35:59 +00:00
|
|
|
"tailscale.com/types/logger"
|
2023-06-08 02:46:59 +00:00
|
|
|
"tailscale.com/util/cmpx"
|
2023-02-01 00:01:02 +00:00
|
|
|
"tailscale.com/util/vizerror"
|
2020-02-25 16:07:41 +00:00
|
|
|
)
|
|
|
|
|
2020-03-03 19:33:22 +00:00
|
|
|
// DevMode controls whether extra output in shown, for when the binary is being run in dev mode.
|
|
|
|
var DevMode bool
|
|
|
|
|
2020-02-25 16:07:41 +00:00
|
|
|
func DefaultCertDir(leafDir string) string {
|
|
|
|
cacheDir, err := os.UserCacheDir()
|
|
|
|
if err == nil {
|
|
|
|
return filepath.Join(cacheDir, "tailscale", leafDir)
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsProd443 reports whether addr is a Go listen address for port 443.
|
|
|
|
func IsProd443(addr string) bool {
|
|
|
|
_, port, _ := net.SplitHostPort(addr)
|
|
|
|
return port == "443" || port == "https"
|
|
|
|
}
|
|
|
|
|
|
|
|
// AllowDebugAccess reports whether r should be permitted to access
|
|
|
|
// various debug endpoints.
|
|
|
|
func AllowDebugAccess(r *http.Request) bool {
|
2023-08-25 18:12:11 +00:00
|
|
|
if allowDebugAccessWithKey(r) {
|
|
|
|
return true
|
|
|
|
}
|
2020-02-25 16:07:41 +00:00
|
|
|
if r.Header.Get("X-Forwarded-For") != "" {
|
|
|
|
// TODO if/when needed. For now, conservative:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
ipStr, _, err := net.SplitHostPort(r.RemoteAddr)
|
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2022-07-26 03:55:44 +00:00
|
|
|
ip, err := netip.ParseAddr(ipStr)
|
2021-01-26 23:00:05 +00:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
2022-01-24 18:52:57 +00:00
|
|
|
if tsaddr.IsTailscaleIP(ip) || ip.IsLoopback() || ipStr == envknob.String("TS_ALLOW_DEBUG_IP") {
|
2020-03-04 21:49:18 +00:00
|
|
|
return true
|
|
|
|
}
|
2023-08-25 18:12:11 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func allowDebugAccessWithKey(r *http.Request) bool {
|
|
|
|
if r.Method != "GET" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
urlKey := r.FormValue("debugkey")
|
|
|
|
keyPath := envknob.String("TS_DEBUG_KEY_PATH")
|
|
|
|
if urlKey != "" && keyPath != "" {
|
|
|
|
slurp, err := os.ReadFile(keyPath)
|
|
|
|
if err == nil && string(bytes.TrimSpace(slurp)) == urlKey {
|
|
|
|
return true
|
2020-03-04 21:49:18 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
2020-02-25 16:07:41 +00:00
|
|
|
}
|
|
|
|
|
2022-05-04 04:42:24 +00:00
|
|
|
// AcceptsEncoding reports whether r accepts the named encoding
|
|
|
|
// ("gzip", "br", etc).
|
|
|
|
func AcceptsEncoding(r *http.Request, enc string) bool {
|
|
|
|
h := r.Header.Get("Accept-Encoding")
|
|
|
|
if h == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if !strings.Contains(h, enc) && !mem.ContainsFold(mem.S(h), mem.S(enc)) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
remain := h
|
|
|
|
for len(remain) > 0 {
|
|
|
|
var part string
|
|
|
|
part, remain, _ = strings.Cut(remain, ",")
|
|
|
|
part = strings.TrimSpace(part)
|
|
|
|
part, _, _ = strings.Cut(part, ";")
|
|
|
|
if part == enc {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2020-02-25 16:07:41 +00:00
|
|
|
// Protected wraps a provided debug handler, h, returning a Handler
|
2021-08-24 14:36:48 +00:00
|
|
|
// that enforces AllowDebugAccess and returns forbidden replies for
|
2020-02-25 16:07:41 +00:00
|
|
|
// unauthorized requests.
|
|
|
|
func Protected(h http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if !AllowDebugAccess(r) {
|
2020-03-03 19:33:22 +00:00
|
|
|
msg := "debug access denied"
|
|
|
|
if DevMode {
|
|
|
|
ipStr, _, _ := net.SplitHostPort(r.RemoteAddr)
|
2020-03-04 21:49:18 +00:00
|
|
|
msg += fmt.Sprintf("; to permit access, set TS_ALLOW_DEBUG_IP=%v", ipStr)
|
2020-03-03 19:33:22 +00:00
|
|
|
}
|
|
|
|
http.Error(w, msg, http.StatusForbidden)
|
2020-02-25 16:07:41 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// Port80Handler is the handler to be given to
|
|
|
|
// autocert.Manager.HTTPHandler. The inner handler is the mux
|
|
|
|
// returned by NewMux containing registered /debug handlers.
|
2022-03-18 16:46:58 +00:00
|
|
|
type Port80Handler struct {
|
|
|
|
Main http.Handler
|
|
|
|
// FQDN is used to redirect incoming requests to https://<FQDN>.
|
|
|
|
// If it is not set, the hostname is calculated from the incoming
|
|
|
|
// request.
|
|
|
|
FQDN string
|
|
|
|
}
|
2020-02-25 16:07:41 +00:00
|
|
|
|
|
|
|
func (h Port80Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
path := r.RequestURI
|
|
|
|
if path == "/debug" || strings.HasPrefix(path, "/debug") {
|
|
|
|
h.Main.ServeHTTP(w, r)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if r.Method != "GET" && r.Method != "HEAD" {
|
|
|
|
http.Error(w, "Use HTTPS", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if path == "/" && AllowDebugAccess(r) {
|
|
|
|
// Redirect authorized user to the debug handler.
|
|
|
|
path = "/debug/"
|
|
|
|
}
|
2023-06-08 02:46:59 +00:00
|
|
|
host := cmpx.Or(h.FQDN, r.Host)
|
2022-03-18 16:46:58 +00:00
|
|
|
target := "https://" + host + path
|
|
|
|
http.Redirect(w, r, target, http.StatusFound)
|
2020-02-25 16:07:41 +00:00
|
|
|
}
|
2020-03-03 19:33:22 +00:00
|
|
|
|
2020-04-05 16:29:24 +00:00
|
|
|
// ReturnHandler is like net/http.Handler, but the handler can return an
|
2020-03-18 05:06:30 +00:00
|
|
|
// error instead of writing to its ResponseWriter.
|
2020-04-05 16:29:24 +00:00
|
|
|
type ReturnHandler interface {
|
|
|
|
// ServeHTTPReturn is like http.Handler.ServeHTTP, except that
|
2020-03-18 16:53:14 +00:00
|
|
|
// it can choose to return an error instead of writing to its
|
|
|
|
// http.ResponseWriter.
|
|
|
|
//
|
2020-04-05 16:29:24 +00:00
|
|
|
// If ServeHTTPReturn returns an error, it caller should handle
|
2020-03-18 16:53:14 +00:00
|
|
|
// an error by serving an HTTP 500 response to the user. The
|
|
|
|
// error details should not be sent to the client, as they may
|
|
|
|
// contain sensitive information. If the error is an
|
|
|
|
// HTTPError, though, callers should use the HTTP response
|
|
|
|
// code and message as the response to the client.
|
2020-04-05 16:29:24 +00:00
|
|
|
ServeHTTPReturn(http.ResponseWriter, *http.Request) error
|
2020-03-18 03:35:59 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 20:55:42 +00:00
|
|
|
type HandlerOptions struct {
|
2022-09-23 17:19:13 +00:00
|
|
|
QuietLoggingIfSuccessful bool // if set, do not log successfully handled HTTP requests (200 and 304 status codes)
|
|
|
|
Logf logger.Logf
|
2023-11-28 23:37:21 +00:00
|
|
|
Now func() time.Time // if nil, defaults to time.Now
|
2020-10-29 22:44:46 +00:00
|
|
|
|
|
|
|
// If non-nil, StatusCodeCounters maintains counters
|
|
|
|
// of status codes for handled responses.
|
|
|
|
// The keys are "1xx", "2xx", "3xx", "4xx", and "5xx".
|
|
|
|
StatusCodeCounters *expvar.Map
|
2022-05-13 20:36:39 +00:00
|
|
|
// If non-nil, StatusCodeCountersFull maintains counters of status
|
|
|
|
// codes for handled responses.
|
|
|
|
// The keys are HTTP numeric response codes e.g. 200, 404, ...
|
|
|
|
StatusCodeCountersFull *expvar.Map
|
2022-06-08 20:05:15 +00:00
|
|
|
|
|
|
|
// OnError is called if the handler returned a HTTPError. This
|
|
|
|
// is intended to be used to present pretty error pages if
|
|
|
|
// the user agent is determined to be a browser.
|
|
|
|
OnError ErrorHandlerFunc
|
2020-10-29 20:55:42 +00:00
|
|
|
}
|
|
|
|
|
2022-06-08 20:05:15 +00:00
|
|
|
// ErrorHandlerFunc is called to present a error response.
|
|
|
|
type ErrorHandlerFunc func(http.ResponseWriter, *http.Request, HTTPError)
|
|
|
|
|
2020-04-22 22:34:03 +00:00
|
|
|
// ReturnHandlerFunc is an adapter to allow the use of ordinary
|
|
|
|
// functions as ReturnHandlers. If f is a function with the
|
|
|
|
// appropriate signature, ReturnHandlerFunc(f) is a ReturnHandler that
|
|
|
|
// calls f.
|
|
|
|
type ReturnHandlerFunc func(http.ResponseWriter, *http.Request) error
|
|
|
|
|
2023-11-28 23:37:21 +00:00
|
|
|
// A Middleware is a function that wraps an http.Handler to extend or modify
|
|
|
|
// its behaviour.
|
|
|
|
//
|
|
|
|
// The implementation of the wrapper is responsible for delegating its input
|
|
|
|
// request to the underlying handler, if appropriate.
|
|
|
|
type Middleware func(h http.Handler) http.Handler
|
|
|
|
|
2020-04-22 22:34:03 +00:00
|
|
|
// ServeHTTPReturn calls f(w, r).
|
|
|
|
func (f ReturnHandlerFunc) ServeHTTPReturn(w http.ResponseWriter, r *http.Request) error {
|
|
|
|
return f(w, r)
|
|
|
|
}
|
|
|
|
|
2021-06-16 04:48:47 +00:00
|
|
|
// StdHandler converts a ReturnHandler into a standard http.Handler.
|
2020-10-29 20:55:42 +00:00
|
|
|
// Handled requests are logged using opts.Logf, as are any errors.
|
|
|
|
// Errors are handled as specified by the Handler interface.
|
2021-06-16 04:48:47 +00:00
|
|
|
func StdHandler(h ReturnHandler, opts HandlerOptions) http.Handler {
|
2020-10-29 20:55:42 +00:00
|
|
|
if opts.Now == nil {
|
|
|
|
opts.Now = time.Now
|
|
|
|
}
|
2021-06-16 04:48:47 +00:00
|
|
|
if opts.Logf == nil {
|
|
|
|
opts.Logf = logger.Discard
|
|
|
|
}
|
2020-10-29 20:55:42 +00:00
|
|
|
return retHandler{h, opts}
|
2020-03-19 00:37:40 +00:00
|
|
|
}
|
|
|
|
|
2020-04-05 16:29:24 +00:00
|
|
|
// retHandler is an http.Handler that wraps a Handler and handles errors.
|
|
|
|
type retHandler struct {
|
2020-10-29 20:55:42 +00:00
|
|
|
rh ReturnHandler
|
|
|
|
opts HandlerOptions
|
2020-03-18 03:35:59 +00:00
|
|
|
}
|
|
|
|
|
2020-03-18 05:06:30 +00:00
|
|
|
// ServeHTTP implements the http.Handler interface.
|
2020-04-05 16:29:24 +00:00
|
|
|
func (h retHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2020-03-19 00:37:40 +00:00
|
|
|
msg := AccessLogRecord{
|
2020-10-29 20:55:42 +00:00
|
|
|
When: h.opts.Now(),
|
2020-03-19 00:37:40 +00:00
|
|
|
RemoteAddr: r.RemoteAddr,
|
|
|
|
Proto: r.Proto,
|
|
|
|
TLS: r.TLS != nil,
|
|
|
|
Host: r.Host,
|
|
|
|
Method: r.Method,
|
|
|
|
RequestURI: r.URL.RequestURI(),
|
|
|
|
UserAgent: r.UserAgent(),
|
|
|
|
Referer: r.Referer(),
|
2023-11-28 23:37:21 +00:00
|
|
|
RequestID: RequestIDFromContext(r.Context()),
|
2020-03-19 00:37:40 +00:00
|
|
|
}
|
|
|
|
|
2020-10-29 20:55:42 +00:00
|
|
|
lw := &loggingResponseWriter{ResponseWriter: w, logf: h.opts.Logf}
|
2020-04-05 16:29:24 +00:00
|
|
|
err := h.rh.ServeHTTPReturn(lw, r)
|
2023-02-01 00:01:02 +00:00
|
|
|
|
|
|
|
var hErr HTTPError
|
|
|
|
var hErrOK bool
|
|
|
|
if errors.As(err, &hErr) {
|
|
|
|
hErrOK = true
|
2023-02-01 22:07:24 +00:00
|
|
|
} else if vizErr, ok := vizerror.As(err); ok {
|
2023-02-01 00:01:02 +00:00
|
|
|
hErrOK = true
|
|
|
|
hErr = HTTPError{Msg: vizErr.Error()}
|
|
|
|
}
|
2020-03-19 00:37:40 +00:00
|
|
|
|
2020-04-04 15:55:10 +00:00
|
|
|
if lw.code == 0 && err == nil && !lw.hijacked {
|
|
|
|
// If the handler didn't write and didn't send a header, that still means 200.
|
|
|
|
// (See https://play.golang.org/p/4P7nx_Tap7p)
|
|
|
|
lw.code = 200
|
|
|
|
}
|
|
|
|
|
2020-10-29 20:55:42 +00:00
|
|
|
msg.Seconds = h.opts.Now().Sub(msg.When).Seconds()
|
2020-03-19 00:37:40 +00:00
|
|
|
msg.Code = lw.code
|
|
|
|
msg.Bytes = lw.bytes
|
|
|
|
|
|
|
|
switch {
|
|
|
|
case lw.hijacked:
|
|
|
|
// Connection no longer belongs to us, just log that we
|
|
|
|
// switched protocols away from HTTP.
|
|
|
|
if msg.Code == 0 {
|
|
|
|
msg.Code = http.StatusSwitchingProtocols
|
|
|
|
}
|
|
|
|
case err != nil && r.Context().Err() == context.Canceled:
|
|
|
|
msg.Code = 499 // nginx convention: Client Closed Request
|
|
|
|
msg.Err = context.Canceled.Error()
|
|
|
|
case hErrOK:
|
|
|
|
// Handler asked us to send an error. Do so, if we haven't
|
|
|
|
// already sent a response.
|
2020-09-17 13:56:12 +00:00
|
|
|
msg.Err = hErr.Msg
|
2020-04-03 17:35:31 +00:00
|
|
|
if hErr.Err != nil {
|
2020-09-17 13:56:12 +00:00
|
|
|
if msg.Err == "" {
|
|
|
|
msg.Err = hErr.Err.Error()
|
|
|
|
} else {
|
|
|
|
msg.Err = msg.Err + ": " + hErr.Err.Error()
|
|
|
|
}
|
2020-04-03 17:35:31 +00:00
|
|
|
}
|
2020-03-19 00:37:40 +00:00
|
|
|
if lw.code != 0 {
|
2020-10-29 20:55:42 +00:00
|
|
|
h.opts.Logf("[unexpected] handler returned HTTPError %v, but already sent a response with code %d", hErr, lw.code)
|
2020-03-19 00:37:40 +00:00
|
|
|
break
|
2020-03-18 16:53:14 +00:00
|
|
|
}
|
2020-03-19 00:37:40 +00:00
|
|
|
msg.Code = hErr.Code
|
|
|
|
if msg.Code == 0 {
|
2020-10-29 20:55:42 +00:00
|
|
|
h.opts.Logf("[unexpected] HTTPError %v did not contain an HTTP status code, sending internal server error", hErr)
|
2020-03-19 00:37:40 +00:00
|
|
|
msg.Code = http.StatusInternalServerError
|
|
|
|
}
|
2022-06-08 20:05:15 +00:00
|
|
|
if h.opts.OnError != nil {
|
|
|
|
h.opts.OnError(lw, r, hErr)
|
|
|
|
} else {
|
2022-08-02 05:57:04 +00:00
|
|
|
// Default headers set by http.Error.
|
|
|
|
lw.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
|
|
lw.Header().Set("X-Content-Type-Options", "nosniff")
|
|
|
|
for k, vs := range hErr.Header {
|
|
|
|
lw.Header()[k] = vs
|
|
|
|
}
|
|
|
|
lw.WriteHeader(msg.Code)
|
|
|
|
fmt.Fprintln(lw, hErr.Msg)
|
2023-11-28 23:37:21 +00:00
|
|
|
if msg.RequestID != "" {
|
|
|
|
fmt.Fprintln(lw, msg.RequestID)
|
2023-08-11 20:41:58 +00:00
|
|
|
}
|
2022-06-08 20:05:15 +00:00
|
|
|
}
|
2020-03-19 00:37:40 +00:00
|
|
|
case err != nil:
|
2023-08-11 20:41:58 +00:00
|
|
|
const internalServerError = "internal server error"
|
|
|
|
errorMessage := internalServerError
|
2023-11-28 23:37:21 +00:00
|
|
|
if msg.RequestID != "" {
|
|
|
|
errorMessage += "\n" + string(msg.RequestID)
|
2023-08-11 20:41:58 +00:00
|
|
|
}
|
2020-03-19 00:37:40 +00:00
|
|
|
// Handler returned a generic error. Serve an internal server
|
|
|
|
// error, if necessary.
|
|
|
|
msg.Err = err.Error()
|
|
|
|
if lw.code == 0 {
|
|
|
|
msg.Code = http.StatusInternalServerError
|
2023-08-11 20:41:58 +00:00
|
|
|
http.Error(lw, errorMessage, msg.Code)
|
2020-03-19 00:37:40 +00:00
|
|
|
}
|
2020-03-18 03:35:59 +00:00
|
|
|
}
|
|
|
|
|
2022-09-23 17:19:13 +00:00
|
|
|
if !h.opts.QuietLoggingIfSuccessful || (msg.Code != http.StatusOK && msg.Code != http.StatusNotModified) {
|
2020-10-29 20:55:42 +00:00
|
|
|
h.opts.Logf("%s", msg)
|
|
|
|
}
|
2020-10-29 22:44:46 +00:00
|
|
|
|
|
|
|
if h.opts.StatusCodeCounters != nil {
|
2022-05-13 20:56:55 +00:00
|
|
|
h.opts.StatusCodeCounters.Add(responseCodeString(msg.Code/100), 1)
|
2020-04-05 07:14:22 +00:00
|
|
|
}
|
2022-05-13 20:36:39 +00:00
|
|
|
|
|
|
|
if h.opts.StatusCodeCountersFull != nil {
|
2022-05-13 20:56:55 +00:00
|
|
|
h.opts.StatusCodeCountersFull.Add(responseCodeString(msg.Code), 1)
|
2022-05-13 20:36:39 +00:00
|
|
|
}
|
2020-03-18 03:35:59 +00:00
|
|
|
}
|
|
|
|
|
2022-05-13 20:56:55 +00:00
|
|
|
func responseCodeString(code int) string {
|
|
|
|
if v, ok := responseCodeCache.Load(code); ok {
|
|
|
|
return v.(string)
|
|
|
|
}
|
|
|
|
|
|
|
|
var ret string
|
|
|
|
if code < 10 {
|
|
|
|
ret = fmt.Sprintf("%dxx", code)
|
|
|
|
} else {
|
|
|
|
ret = strconv.Itoa(code)
|
|
|
|
}
|
|
|
|
responseCodeCache.Store(code, ret)
|
|
|
|
return ret
|
|
|
|
}
|
|
|
|
|
|
|
|
// responseCodeCache memoizes the string form of HTTP response codes,
|
|
|
|
// so that the hot request-handling codepath doesn't have to allocate
|
|
|
|
// in strconv/fmt for every request.
|
|
|
|
//
|
|
|
|
// Keys are either full HTTP response code ints (200, 404) or "family"
|
|
|
|
// ints representing entire families (e.g. 2 for 2xx codes). Values
|
|
|
|
// are the string form of that code/family.
|
|
|
|
var responseCodeCache sync.Map
|
|
|
|
|
2020-03-19 00:37:40 +00:00
|
|
|
// loggingResponseWriter wraps a ResponseWriter and record the HTTP
|
|
|
|
// response code that gets sent, if any.
|
|
|
|
type loggingResponseWriter struct {
|
|
|
|
http.ResponseWriter
|
|
|
|
code int
|
|
|
|
bytes int
|
|
|
|
hijacked bool
|
|
|
|
logf logger.Logf
|
|
|
|
}
|
|
|
|
|
|
|
|
// WriteHeader implements http.Handler.
|
|
|
|
func (l *loggingResponseWriter) WriteHeader(statusCode int) {
|
|
|
|
if l.code != 0 {
|
|
|
|
l.logf("[unexpected] HTTP handler set statusCode twice (%d and %d)", l.code, statusCode)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
l.code = statusCode
|
|
|
|
l.ResponseWriter.WriteHeader(statusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write implements http.Handler.
|
|
|
|
func (l *loggingResponseWriter) Write(bs []byte) (int, error) {
|
|
|
|
if l.code == 0 {
|
|
|
|
l.code = 200
|
|
|
|
}
|
|
|
|
n, err := l.ResponseWriter.Write(bs)
|
|
|
|
l.bytes += n
|
|
|
|
return n, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// Hijack implements http.Hijacker. Note that hijacking can still fail
|
|
|
|
// because the wrapped ResponseWriter is not required to implement
|
|
|
|
// Hijacker, as this breaks HTTP/2.
|
|
|
|
func (l *loggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
|
|
|
h, ok := l.ResponseWriter.(http.Hijacker)
|
|
|
|
if !ok {
|
|
|
|
return nil, nil, errors.New("ResponseWriter is not a Hijacker")
|
|
|
|
}
|
|
|
|
conn, buf, err := h.Hijack()
|
|
|
|
if err == nil {
|
|
|
|
l.hijacked = true
|
|
|
|
}
|
|
|
|
return conn, buf, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l loggingResponseWriter) Flush() {
|
|
|
|
f, _ := l.ResponseWriter.(http.Flusher)
|
|
|
|
if f == nil {
|
|
|
|
l.logf("[unexpected] tried to Flush a ResponseWriter that can't flush")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
f.Flush()
|
2020-03-18 03:35:59 +00:00
|
|
|
}
|
|
|
|
|
2020-03-18 05:06:30 +00:00
|
|
|
// HTTPError is an error with embedded HTTP response information.
|
2020-03-18 16:53:14 +00:00
|
|
|
//
|
2020-04-05 16:29:24 +00:00
|
|
|
// It is the error type to be (optionally) used by Handler.ServeHTTPReturn.
|
2020-03-18 05:06:30 +00:00
|
|
|
type HTTPError struct {
|
2023-11-28 23:37:21 +00:00
|
|
|
Code int // HTTP response code to send to client; 0 means 500
|
|
|
|
Msg string // Response body to send to client
|
|
|
|
Err error // Detailed error to log on the server
|
|
|
|
Header http.Header // Optional set of HTTP headers to set in the response
|
2020-03-18 05:06:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Error implements the error interface.
|
2023-11-28 23:37:21 +00:00
|
|
|
func (e HTTPError) Error() string { return fmt.Sprintf("httperror{%d, %q, %v}", e.Code, e.Msg, e.Err) }
|
2022-10-05 03:39:10 +00:00
|
|
|
func (e HTTPError) Unwrap() error { return e.Err }
|
|
|
|
|
2020-03-18 05:06:30 +00:00
|
|
|
// Error returns an HTTPError containing the given information.
|
|
|
|
func Error(code int, msg string, err error) HTTPError {
|
|
|
|
return HTTPError{Code: code, Msg: msg, Err: err}
|
|
|
|
}
|
|
|
|
|
2023-04-10 10:28:16 +00:00
|
|
|
// VarzHandler writes expvar values as Prometheus metrics.
|
|
|
|
// TODO: migrate all users to varz.Handler or promvarz.Handler and remove this.
|
2021-08-11 21:18:52 +00:00
|
|
|
func VarzHandler(w http.ResponseWriter, r *http.Request) {
|
2023-04-10 10:28:16 +00:00
|
|
|
varz.Handler(w, r)
|
2023-04-03 10:23:37 +00:00
|
|
|
}
|
2023-07-11 18:53:46 +00:00
|
|
|
|
|
|
|
// AddBrowserHeaders sets various HTTP security headers for browser-facing endpoints.
|
|
|
|
//
|
|
|
|
// The specific headers:
|
|
|
|
// - require HTTPS access (HSTS)
|
|
|
|
// - disallow iframe embedding
|
|
|
|
// - mitigate MIME confusion attacks
|
|
|
|
//
|
|
|
|
// These headers are based on
|
|
|
|
// https://infosec.mozilla.org/guidelines/web_security
|
|
|
|
func AddBrowserHeaders(w http.ResponseWriter) {
|
|
|
|
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
|
2024-01-03 17:00:57 +00:00
|
|
|
w.Header().Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; block-all-mixed-content; object-src 'none'")
|
2023-07-11 18:53:46 +00:00
|
|
|
w.Header().Set("X-Frame-Options", "DENY")
|
|
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
|
|
}
|
|
|
|
|
|
|
|
// BrowserHeaderHandler wraps the provided http.Handler with a call to
|
|
|
|
// AddBrowserHeaders.
|
|
|
|
func BrowserHeaderHandler(h http.Handler) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
AddBrowserHeaders(w)
|
|
|
|
h.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
// BrowserHeaderHandlerFunc wraps the provided http.HandlerFunc with a call to
|
|
|
|
// AddBrowserHeaders.
|
|
|
|
func BrowserHeaderHandlerFunc(h http.HandlerFunc) http.HandlerFunc {
|
2023-11-28 23:37:21 +00:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2023-07-11 18:53:46 +00:00
|
|
|
AddBrowserHeaders(w)
|
|
|
|
h.ServeHTTP(w, r)
|
2023-11-28 23:37:21 +00:00
|
|
|
}
|
2023-07-11 18:53:46 +00:00
|
|
|
}
|