81 lines
2.4 KiB
Go
81 lines
2.4 KiB
Go
package httpadapter
|
|
|
|
import (
|
|
"net/http"
|
|
"os"
|
|
"slices"
|
|
"testing"
|
|
|
|
"github.com/ogen-go/ogen"
|
|
)
|
|
|
|
// publicContractBundle is the bundled public contract that the generated
|
|
// server is built from, relative to this package.
|
|
const publicContractBundle = "../../../../../api/core/openapi.bundle.yml"
|
|
|
|
const (
|
|
sessionCookieScheme = "sessionCookie"
|
|
sessionCSRFScheme = "sessionCsrf"
|
|
)
|
|
|
|
// A browser sends the session cookie with every same-site request, so an
|
|
// unsafe operation that accepts the session must also demand the
|
|
// session-bound CSRF token. A new operation that forgets sessionCsrf would
|
|
// otherwise compile and pass every other check.
|
|
func TestUnsafeSessionOperationsRequireCSRFToken(t *testing.T) {
|
|
data, err := os.ReadFile(publicContractBundle)
|
|
if err != nil {
|
|
t.Fatalf("read the public contract bundle: %v", err)
|
|
}
|
|
spec, err := ogen.Parse(data)
|
|
if err != nil {
|
|
t.Fatalf("parse the public contract bundle: %v", err)
|
|
}
|
|
|
|
checked := 0
|
|
for path, item := range spec.Paths {
|
|
for method, operation := range unsafeOperations(item) {
|
|
// An operation without its own security list inherits the root
|
|
// one; an explicit empty list makes it public.
|
|
requirements := operation.Security
|
|
if requirements == nil {
|
|
requirements = spec.Security
|
|
}
|
|
for _, requirement := range requirements {
|
|
if _, usesSession := requirement[sessionCookieScheme]; !usesSession {
|
|
continue
|
|
}
|
|
checked++
|
|
if _, usesCSRF := requirement[sessionCSRFScheme]; !usesCSRF {
|
|
t.Errorf("%s %s (%s) accepts %s without %s", method, path, operation.OperationID, sessionCookieScheme, sessionCSRFScheme)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
// Logout is an unsafe session operation, so an empty result means the
|
|
// bundle was not read as expected.
|
|
if checked == 0 {
|
|
t.Fatal("found no unsafe operation that requires a session; the check would pass vacuously")
|
|
}
|
|
}
|
|
|
|
func unsafeOperations(item *ogen.PathItem) map[string]*ogen.Operation {
|
|
operations := map[string]*ogen.Operation{
|
|
http.MethodPost: item.Post,
|
|
http.MethodPut: item.Put,
|
|
http.MethodPatch: item.Patch,
|
|
http.MethodDelete: item.Delete,
|
|
}
|
|
for method, operation := range item.AdditionalOperations {
|
|
if !slices.Contains([]string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace}, method) {
|
|
operations[method] = operation
|
|
}
|
|
}
|
|
for method, operation := range operations {
|
|
if operation == nil {
|
|
delete(operations, method)
|
|
}
|
|
}
|
|
return operations
|
|
}
|