(w http.ResponseWriter, r *http.Request)
| 46 | } |
| 47 | |
| 48 | func (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 | |
| 98 | func hasValidAPIKeyHeader(r *http.Request, validator apiKeyValidator) bool { |
| 99 | if key := r.Header.Get("X-API-Key"); validator.IsValidAPIKey(key) { |
no test coverage detected