feat: enable csrf token header (#11283)

* feat: enable csrf token header

* Exempt external auth requets
* ensure dev server bypasses CSRF
* external auth is just get requests
* Add some more routes
* Extra assurance nothing breaks
This commit is contained in:
Steven Masley
2023-12-19 15:42:05 -06:00
committed by GitHub
parent fbda21a9f2
commit 24080b121c
2 changed files with 26 additions and 9 deletions

View File

@ -19,25 +19,23 @@ func CSRF(secureCookie bool) func(next http.Handler) http.Handler {
mw.SetFailureHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Something is wrong with your CSRF token. Please refresh the page. If this error persists, try clearing your cookies.", http.StatusBadRequest)
}))
// Exempt all requests that do not require CSRF protection.
// All GET requests are exempt by default.
mw.ExemptPath("/api/v2/csp/reports")
// Top level agent routes.
mw.ExemptRegexp(regexp.MustCompile("api/v2/workspaceagents/[^/]*$"))
// Agent authenticated routes
mw.ExemptRegexp(regexp.MustCompile("api/v2/workspaceagents/me/*"))
mw.ExemptRegexp(regexp.MustCompile("api/v2/workspaceagents/*"))
// Workspace Proxy routes
mw.ExemptRegexp(regexp.MustCompile("api/v2/workspaceproxies/me/*"))
// Derp routes
mw.ExemptRegexp(regexp.MustCompile("derp/*"))
// Scim
mw.ExemptRegexp(regexp.MustCompile("api/v2/scim/*"))
// Provisioner daemon routes
mw.ExemptRegexp(regexp.MustCompile("/organizations/[^/]+/provisionerdaemons/*"))
mw.ExemptFunc(func(r *http.Request) bool {
// Enable CSRF in November 2022 by deleting this "return true" line.
// CSRF is not enforced to ensure backwards compatibility with older
// cli versions.
//nolint:revive
return true
// CSRF only affects requests that automatically attach credentials via a cookie.
// If no cookie is present, then there is no risk of CSRF.
//nolint:govet
@ -59,6 +57,13 @@ func CSRF(secureCookie bool) func(next http.Handler) http.Handler {
return true
}
if r.Header.Get(codersdk.ProvisionerDaemonPSK) != "" {
// If present, the provisioner daemon also is providing an api key
// that will make them exempt from CSRF. But this is still useful
// for enumerating the external auths.
return true
}
// If the X-CSRF-TOKEN header is set, we can exempt the func if it's valid.
// This is the CSRF check.
sent := r.Header.Get("X-CSRF-TOKEN")