MCPcopy Index your code
hub / github.com/syncthing/syncthing / ServeHTTP

Method ServeHTTP

lib/api/api_csrf.go:48–96  ·  view source on GitHub ↗
(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

46}
47
48func (m *csrfManager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
49 // Allow requests carrying a valid API key
50 if hasValidAPIKeyHeader(r, m.apiKeyValidator) {
51 // Set the access-control-allow-origin header for CORS requests
52 // since a valid API key has been provided
53 w.Header().Add("Access-Control-Allow-Origin", "*")
54 m.next.ServeHTTP(w, r)
55 return
56 }
57
58 if strings.HasPrefix(r.URL.Path, "/rest/debug") {
59 // Debugging functions are only available when explicitly
60 // enabled, and can be accessed without a CSRF token
61 m.next.ServeHTTP(w, r)
62 return
63 }
64
65 // Allow requests for anything not under the protected path prefix,
66 // and set a CSRF cookie if there isn't already a valid one.
67 if !strings.HasPrefix(r.URL.Path, m.prefix) {
68 cookie, err := r.Cookie("CSRF-Token-" + m.unique)
69 if err != nil || !m.tokens.Check(cookie.Value) {
70 l.Debugln("new CSRF cookie in response to request for", r.URL)
71 cookie = &http.Cookie{
72 Name: "CSRF-Token-" + m.unique,
73 Value: m.tokens.New(),
74 }
75 http.SetCookie(w, cookie)
76 }
77 m.next.ServeHTTP(w, r)
78 return
79 }
80
81 if isNoAuthPath(r.URL.Path, false) {
82 // REST calls that don't require authentication also do not
83 // need a CSRF token.
84 m.next.ServeHTTP(w, r)
85 return
86 }
87
88 // Verify the CSRF token
89 token := r.Header.Get("X-CSRF-Token-" + m.unique)
90 if !m.tokens.Check(token) {
91 http.Error(w, "CSRF Error", http.StatusForbidden)
92 return
93 }
94
95 m.next.ServeHTTP(w, r)
96}
97
98func hasValidAPIKeyHeader(r *http.Request, validator apiKeyValidator) bool {
99 if key := r.Header.Get("X-API-Key"); validator.IsValidAPIKey(key) {

Callers 7

debugMiddlewareFunction · 0.45
corsMiddlewareFunction · 0.45
noCacheMiddlewareFunction · 0.45
withDetailsMiddlewareFunction · 0.45
localhostMiddlewareFunction · 0.45
getSupportBundleMethod · 0.45

Calls 9

hasValidAPIKeyHeaderFunction · 0.85
isNoAuthPathFunction · 0.85
CheckMethod · 0.80
DebuglnMethod · 0.80
NewMethod · 0.65
GetMethod · 0.65
ErrorMethod · 0.65
AddMethod · 0.45
HeaderMethod · 0.45

Tested by

no test coverage detected