Source file src/net/http/csrf.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package http
     6  
     7  import (
     8  	"errors"
     9  	"fmt"
    10  	"net/url"
    11  	"sync"
    12  	"sync/atomic"
    13  )
    14  
    15  // CrossOriginProtection implements protections against [Cross-Site Request
    16  // Forgery (CSRF)] by rejecting non-safe cross-origin browser requests.
    17  //
    18  // Cross-origin requests are currently detected with the [Sec-Fetch-Site]
    19  // header, available in all browsers since 2023, or by comparing the hostname of
    20  // the [Origin] header with the Host header.
    21  //
    22  // The GET, HEAD, and OPTIONS methods are [safe methods] and are always allowed.
    23  // It's important that applications do not perform any state changing actions
    24  // due to requests with safe methods.
    25  //
    26  // Requests without Sec-Fetch-Site or Origin headers are currently assumed to be
    27  // either same-origin or non-browser requests, and are allowed.
    28  //
    29  // [Sec-Fetch-Site]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Site
    30  // [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
    31  // [Cross-Site Request Forgery (CSRF)]: https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF
    32  // [safe methods]: https://developer.mozilla.org/en-US/docs/Glossary/Safe/HTTP
    33  type CrossOriginProtection struct {
    34  	bypass    *ServeMux
    35  	trustedMu sync.RWMutex
    36  	trusted   map[string]bool
    37  	deny      atomic.Pointer[Handler]
    38  }
    39  
    40  // NewCrossOriginProtection returns a new [CrossOriginProtection] value.
    41  func NewCrossOriginProtection() *CrossOriginProtection {
    42  	return &CrossOriginProtection{
    43  		bypass:  NewServeMux(),
    44  		trusted: make(map[string]bool),
    45  	}
    46  }
    47  
    48  // AddTrustedOrigin allows all requests with an [Origin] header
    49  // which exactly matches the given value.
    50  //
    51  // Origin header values are of the form "scheme://host[:port]".
    52  //
    53  // AddTrustedOrigin can be called concurrently with other methods
    54  // or request handling, and applies to future requests.
    55  //
    56  // [Origin]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin
    57  func (c *CrossOriginProtection) AddTrustedOrigin(origin string) error {
    58  	u, err := url.Parse(origin)
    59  	if err != nil {
    60  		return fmt.Errorf("invalid origin %q: %w", origin, err)
    61  	}
    62  	if u.Scheme == "" {
    63  		return fmt.Errorf("invalid origin %q: scheme is required", origin)
    64  	}
    65  	if u.Host == "" {
    66  		return fmt.Errorf("invalid origin %q: host is required", origin)
    67  	}
    68  	if u.Path != "" || u.RawQuery != "" || u.Fragment != "" {
    69  		return fmt.Errorf("invalid origin %q: path, query, and fragment are not allowed", origin)
    70  	}
    71  	c.trustedMu.Lock()
    72  	defer c.trustedMu.Unlock()
    73  	c.trusted[origin] = true
    74  	return nil
    75  }
    76  
    77  var noopHandler = HandlerFunc(func(w ResponseWriter, r *Request) {})
    78  
    79  // AddInsecureBypassPattern permits all requests that match the given pattern.
    80  // The pattern syntax and precedence rules are the same as [ServeMux].
    81  //
    82  // AddInsecureBypassPattern can be called concurrently with other methods
    83  // or request handling, and applies to future requests.
    84  func (c *CrossOriginProtection) AddInsecureBypassPattern(pattern string) {
    85  	c.bypass.Handle(pattern, noopHandler)
    86  }
    87  
    88  // SetDenyHandler sets a handler to invoke when a request is rejected.
    89  // The default error handler responds with a 403 Forbidden status.
    90  //
    91  // SetDenyHandler can be called concurrently with other methods
    92  // or request handling, and applies to future requests.
    93  //
    94  // Check does not call the error handler.
    95  func (c *CrossOriginProtection) SetDenyHandler(h Handler) {
    96  	if h == nil {
    97  		c.deny.Store(nil)
    98  		return
    99  	}
   100  	c.deny.Store(&h)
   101  }
   102  
   103  // Check applies cross-origin checks to a request.
   104  // It returns an error if the request should be rejected.
   105  func (c *CrossOriginProtection) Check(req *Request) error {
   106  	switch req.Method {
   107  	case "GET", "HEAD", "OPTIONS":
   108  		// Safe methods are always allowed.
   109  		return nil
   110  	}
   111  
   112  	switch req.Header.Get("Sec-Fetch-Site") {
   113  	case "":
   114  		// No Sec-Fetch-Site header is present.
   115  		// Fallthrough to check the Origin header.
   116  	case "same-origin", "none":
   117  		return nil
   118  	default:
   119  		if c.isRequestExempt(req) {
   120  			return nil
   121  		}
   122  		return errors.New("cross-origin request detected from Sec-Fetch-Site header")
   123  	}
   124  
   125  	origin := req.Header.Get("Origin")
   126  	if origin == "" {
   127  		// Neither Sec-Fetch-Site nor Origin headers are present.
   128  		// Either the request is same-origin or not a browser request.
   129  		return nil
   130  	}
   131  
   132  	if o, err := url.Parse(origin); err == nil && o.Host == req.Host {
   133  		// The Origin header matches the Host header. Note that the Host header
   134  		// doesn't include the scheme, so we don't know if this might be an
   135  		// HTTP→HTTPS cross-origin request. We fail open, since all modern
   136  		// browsers support Sec-Fetch-Site since 2023, and running an older
   137  		// browser makes a clear security trade-off already. Sites can mitigate
   138  		// this with HTTP Strict Transport Security (HSTS).
   139  		return nil
   140  	}
   141  
   142  	if c.isRequestExempt(req) {
   143  		return nil
   144  	}
   145  	return errors.New("cross-origin request detected, and/or browser is out of date: " +
   146  		"Sec-Fetch-Site is missing, and Origin does not match Host")
   147  }
   148  
   149  // isRequestExempt checks the bypasses which require taking a lock, and should
   150  // be deferred until the last moment.
   151  func (c *CrossOriginProtection) isRequestExempt(req *Request) bool {
   152  	if _, pattern := c.bypass.Handler(req); pattern != "" {
   153  		// The request matches a bypass pattern.
   154  		return true
   155  	}
   156  
   157  	c.trustedMu.RLock()
   158  	defer c.trustedMu.RUnlock()
   159  	origin := req.Header.Get("Origin")
   160  	// The request matches a trusted origin.
   161  	return origin != "" && c.trusted[origin]
   162  }
   163  
   164  // Handler returns a handler that applies cross-origin checks
   165  // before invoking the handler h.
   166  //
   167  // If a request fails cross-origin checks, the request is rejected
   168  // with a 403 Forbidden status or handled with the handler passed
   169  // to [CrossOriginProtection.SetDenyHandler].
   170  func (c *CrossOriginProtection) Handler(h Handler) Handler {
   171  	return HandlerFunc(func(w ResponseWriter, r *Request) {
   172  		if err := c.Check(r); err != nil {
   173  			if deny := c.deny.Load(); deny != nil {
   174  				(*deny).ServeHTTP(w, r)
   175  				return
   176  			}
   177  			Error(w, err.Error(), StatusForbidden)
   178  			return
   179  		}
   180  		h.ServeHTTP(w, r)
   181  	})
   182  }
   183  

View as plain text