Reports are taken only as application/json (closes #126)
check / check (push) Canceled after 0s
check / check (push) Canceled after 0s
A page on another origin can POST text/plain or a form without a CORS preflight, so its visitors' browsers could store reports although the server sends no CORS headers. decodeJSON now refuses a request whose Content-Type is not application/json (parameters such as charset allowed), and the report handler answers it 415 with the usual error body, storing nothing. A JSON POST waits for the preflight, which only an origin in CORS_ALLOWED_ORIGINS passes; the page already sends application/json. Model: opus-5-5
This commit is contained in:
@@ -5,7 +5,9 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"mime"
|
||||
"net/http"
|
||||
|
||||
"sneak.berlin/go/netwatch/internal/globals"
|
||||
@@ -18,6 +20,10 @@ import (
|
||||
|
||||
const jsonContentType = "application/json; charset=utf-8"
|
||||
|
||||
// errNotJSON is what decodeJSON returns for a request whose
|
||||
// Content-Type is not application/json.
|
||||
var errNotJSON = errors.New("content type is not application/json")
|
||||
|
||||
// reportAppender is the subset of the report buffer the handlers
|
||||
// depend on. Defining it here keeps the storage failure path
|
||||
// exercisable with a stub in tests.
|
||||
@@ -80,14 +86,25 @@ func (s *Handlers) respondJSON(
|
||||
}
|
||||
}
|
||||
|
||||
// decodeJSON decodes the request body into v. The body is
|
||||
// expected to already be bounded by the body-size middleware, so
|
||||
// a caller can distinguish an over-limit body from malformed
|
||||
// JSON by testing the returned error for *http.MaxBytesError.
|
||||
// decodeJSON decodes the request body into v. It returns errNotJSON,
|
||||
// reading nothing, unless the request's Content-Type is
|
||||
// application/json, with or without parameters such as charset. The
|
||||
// body is expected to already be bounded by the body-size middleware,
|
||||
// so a caller can distinguish an over-limit body from malformed JSON
|
||||
// by testing the returned error for *http.MaxBytesError.
|
||||
func (s *Handlers) decodeJSON(
|
||||
_ http.ResponseWriter,
|
||||
r *http.Request,
|
||||
v any,
|
||||
) error {
|
||||
// A page on another origin can POST text/plain or a form without
|
||||
// a CORS preflight, so its visitors' browsers would send it
|
||||
// whatever the CORS settings. A JSON POST waits for the
|
||||
// preflight, so only JSON is taken.
|
||||
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return errNotJSON
|
||||
}
|
||||
|
||||
return json.NewDecoder(r.Body).Decode(v)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user