package api import ( "bytes" "encoding/json" "errors" "io" "mime" "net/http" "net/url" "strconv" "strings" "unicode/utf8" ) // decodeJSON enforces the contract's JSON rules: application/json, strict // UTF-8, exactly one object with exactly the documented top-level keys, no // unknown/duplicate fields and a bounded body size. // // encoding/json matches struct fields case-insensitively even with // DisallowUnknownFields, so the exact key set is checked separately on the // token stream. That also rejects Unicode case-folding aliases and duplicates. func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError { if raw := r.Header.Get("Content-Type"); raw != "" { mediaType, _, err := mime.ParseMediaType(raw) if err != nil || mediaType != "application/json" { return statusUnsupportedMediaType } } body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1)) if err != nil { return invalidRequest("could not read request body") } if int64(len(body)) > a.maxBody { return statusPayloadTooLarge } if len(bytes.TrimSpace(body)) == 0 { return invalidRequest("request body must not be empty") } if !utf8.Valid(body) { return invalidRequest("request body must be valid UTF-8") } if problem := validateTopLevelKeys(body, allowedKeys); problem != nil { return problem } decoder := json.NewDecoder(bytes.NewReader(body)) decoder.DisallowUnknownFields() if err := decoder.Decode(destination); err != nil { return invalidRequest("request body does not match the documented schema") } var extra any if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { return invalidRequest("request body must contain exactly one JSON value") } return nil } func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError { allowed := make(map[string]struct{}, len(allowedKeys)) for _, key := range allowedKeys { allowed[key] = struct{}{} } decoder := json.NewDecoder(bytes.NewReader(body)) token, err := decoder.Token() if err != nil { return invalidRequest("request body must be valid JSON") } opening, ok := token.(json.Delim) if !ok || opening != '{' { return invalidRequest("request body must be a JSON object") } seen := make(map[string]struct{}, len(allowedKeys)) for decoder.More() { token, err := decoder.Token() if err != nil { return invalidRequest("request body must be valid JSON") } key, ok := token.(string) if !ok { return invalidRequest("request body must contain string field names") } if _, duplicate := seen[key]; duplicate { return invalidRequest("request body must not contain duplicate fields") } seen[key] = struct{}{} if _, ok := allowed[key]; !ok { return invalidRequest("request body contains an unknown field") } var value json.RawMessage if err := decoder.Decode(&value); err != nil { return invalidRequest("request body must be valid JSON") } } if _, err := decoder.Token(); err != nil { return invalidRequest("request body must be valid JSON") } var extra any if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) { return invalidRequest("request body must contain exactly one JSON value") } return nil } // pageParams parses limit/cursor. Cursor decoding happens after membership is // verified so a foreign chat cannot be probed with a malformed cursor. func (a *App) pageParams(r *http.Request) (int, string, *apiError) { query, err := url.ParseQuery(r.URL.RawQuery) if err != nil { return 0, "", invalidRequest("query string is not valid") } limit := 50 if values, present := query["limit"]; present { if len(values) != 1 { return 0, "", invalidRequest("limit must be specified once") } parsed, err := strconv.Atoi(values[0]) if err != nil || parsed < 1 || parsed > 100 { return 0, "", invalidRequest("limit must be an integer between 1 and 100") } limit = parsed } cursor := "" if values, present := query["cursor"]; present { if len(values) != 1 || values[0] == "" { return 0, "", invalidRequest("cursor must be a non-empty string") } cursor = values[0] } return limit, cursor, nil } func validateUsername(value string) *apiError { if !usernameAllowed(value) { return invalidRequest("username must match [a-z0-9_]{3,32}") } return nil } func validateDisplayName(value string) *apiError { if isBlank(value) { return invalidRequest("display_name must not be blank") } if count := utf8.RuneCountInString(value); count < 1 || count > 100 { return invalidRequest("display_name must contain 1 to 100 Unicode code points") } return nil } func validateTitle(value string) *apiError { if isBlank(value) { return invalidRequest("title must not be blank") } if count := utf8.RuneCountInString(value); count < 1 || count > 100 { return invalidRequest("title must contain 1 to 100 Unicode code points") } return nil } func validateMessageText(value string) *apiError { if isBlank(value) { return invalidRequest("text must not be blank") } if count := utf8.RuneCountInString(value); count < 1 || count > 4000 { return invalidRequest("text must contain 1 to 4000 Unicode code points") } return nil } // validatePassword implements the registration rule: 12 to 128 Unicode code // points, not only whitespace. The exact bytes are handed to Argon2id, so // Unicode passwords are neither truncated nor normalized by the server. func validatePassword(value string) *apiError { if !utf8.ValidString(value) { return invalidRequest("password must be valid UTF-8") } if isBlank(value) { return invalidRequest("password must not be blank") } if count := utf8.RuneCountInString(value); count < 12 || count > 128 { return invalidRequest("password must contain 12 to 128 Unicode code points") } return nil } func isBlank(value string) bool { return strings.TrimSpace(value) == "" } // usernameAllowed is a byte-wise equivalent of the contract pattern // ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match. func usernameAllowed(value string) bool { if len(value) < 3 || len(value) > 32 { return false } for i := 0; i < len(value); i++ { c := value[i] if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' { continue } return false } return true }