Files
aksdb 9f0700fa1c 🐛 Reject invalid changes instead of failing the whole sync batch
Every whitelisted field was written, so a tombstone or a partial change
without the required fields failed the validation and rolled back the
whole batch with 400, which a client would retry forever. Only the keys
present in the change are set now, a change is validated on its own and
answered as invalid with the message, and a tombstone for an unknown
row is answered ok without writing anything.
2026-12-01 16:41:57 +01:00

256 lines
7.2 KiB
Go

package syncapi
import (
"database/sql"
"errors"
"fmt"
"net/http"
"regexp"
"slices"
"strings"
"time"
"github.com/pocketbase/dbx"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
"github.com/wotra/wotra/internal/collections"
)
const (
MaxChanges = 500
MaxBodyBytes = 32 << 20
)
// Status codes reported back per change. A change that fails the validation is
// answered with statusInvalid and not written; the other changes of the batch
// are applied anyway.
const (
statusOK = "ok"
statusStale = "stale"
statusForbidden = "forbidden"
statusReadOnly = "readonly"
statusInvalid = "invalid"
)
const (
dayKeyLayout = "2006-01-02"
maxHoursPerWeek = 168
)
var idPattern = regexp.MustCompile(`^[a-z0-9]{15}$`)
type Change struct {
Collection string `json:"collection"`
Id string `json:"id"`
Data map[string]any `json:"data"`
ClientUpdatedAt int64 `json:"client_updated_at"`
Deleted bool `json:"deleted"`
}
type PushRequest struct {
Changes []Change `json:"changes"`
}
type Result struct {
Id string `json:"id"`
Collection string `json:"collection"`
Status string `json:"status"`
Error string `json:"error,omitempty"` // set when the status is invalid
Record *core.Record `json:"record,omitempty"`
}
func Register(app core.App) {
RegisterHooks(app)
app.OnServe().BindFunc(func(se *core.ServeEvent) error {
se.Router.POST("/api/sync/push", handlePush).
Bind(apis.RequireAuth("users"), apis.BodyLimit(MaxBodyBytes))
return se.Next()
})
}
func validate(req *PushRequest) error {
if len(req.Changes) > MaxChanges {
return fmt.Errorf("too many changes (max %d)", MaxChanges)
}
for i, c := range req.Changes {
if !collections.IsSynced(c.Collection) {
return fmt.Errorf("changes[%d]: invalid collection %q", i, c.Collection)
}
if !idPattern.MatchString(c.Id) {
return fmt.Errorf("changes[%d]: invalid id", i)
}
if c.ClientUpdatedAt < 0 {
return fmt.Errorf("changes[%d]: invalid client_updated_at", i)
}
for field := range c.Data {
if !slices.Contains(collections.DataFields[c.Collection], field) {
return fmt.Errorf("changes[%d]: unknown field %q", i, field)
}
}
}
return nil
}
func handlePush(e *core.RequestEvent) error {
var req PushRequest
if err := e.BindBody(&req); err != nil {
return e.BadRequestError("Invalid request body.", err)
}
if err := validate(&req); err != nil {
return e.BadRequestError(err.Error(), nil)
}
authId := e.Auth.Id
results := make([]Result, 0, len(req.Changes))
err := e.App.RunInTransaction(func(tx core.App) error {
for _, c := range req.Changes {
res, err := apply(tx, authId, c)
if err != nil {
return err
}
results = append(results, res)
}
return nil
})
if err != nil {
return e.BadRequestError("Failed to apply changes.", err)
}
return e.JSON(http.StatusOK, map[string]any{"results": results})
}
func apply(tx core.App, authId string, c Change) (Result, error) {
res := Result{Id: c.Id, Collection: c.Collection}
if collections.IsReadOnly(c.Collection) {
res.Status = statusReadOnly
return res, nil
}
record, err := tx.FindRecordById(c.Collection, c.Id)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return res, err
}
if record == nil {
if c.Deleted {
// Deleting a row the server never saw leaves nothing to do.
res.Status = statusOK
return res, nil
}
col, err := tx.FindCachedCollectionByNameOrId(c.Collection)
if err != nil {
return res, err
}
record = core.NewRecord(col)
record.Id = c.Id
record.Set("owner", authId)
record.Set("rev", 1)
} else {
if record.GetString("owner") != authId {
res.Status = statusForbidden
return res, nil
}
if c.ClientUpdatedAt < record.GetInt64("client_updated_at") {
res.Status = statusStale
res.Record = record
return res, nil
}
if c.Deleted && !record.GetBool("deleted") && c.Collection == "settings_history" {
keep, err := isLastLiveSettings(tx, authId, c.Id)
if err != nil {
return res, err
}
if keep {
res.Status = statusStale
res.Record = record
return res, nil
}
}
record.Set("rev", record.GetInt("rev")+1)
}
setData(record, c)
record.Set("client_updated_at", c.ClientUpdatedAt)
record.Set("deleted", c.Deleted)
if err := validateRecord(tx, record); err != nil {
res.Status = statusInvalid
res.Error = err.Error()
return res, nil
}
if err := tx.Save(record); err != nil {
return res, fmt.Errorf("%s/%s: %w", c.Collection, c.Id, err)
}
res.Status = statusOK
res.Record = record
return res, nil
}
// validateRecord checks the record against the PocketBase field validation and
// the rules the field options cannot express. The returned error message is
// meant for the client.
func validateRecord(tx core.App, r *core.Record) error {
if err := tx.Validate(r); err != nil {
// PocketBase appends a period to every validation message, sometimes two
return errors.New(strings.TrimRight(err.Error(), "."))
}
return semanticError(r)
}
// semanticError reports the violation of a rule that the PocketBase field options
// cannot express, for example a day_key that passes the pattern without being a
// real date.
func semanticError(r *core.Record) error {
switch r.Collection().Name {
case "entries":
dayKey := r.GetString("day_key")
if _, err := time.Parse(dayKeyLayout, dayKey); err != nil {
return fmt.Errorf("day_key %q is not a calendar date", dayKey)
}
start, end := r.GetInt64("start_time"), r.GetInt64("end_time")
if start < 0 {
return errors.New("start_time must not be negative")
}
if end != 0 && end < start {
return errors.New("end_time must be 0 or not before start_time")
}
case "settings_history":
from := r.GetString("effective_from")
if _, err := time.Parse(dayKeyLayout, from); err != nil {
return fmt.Errorf("effective_from %q is not a calendar date", from)
}
if hours := r.GetFloat("hours_per_week"); hours <= 0 || hours > maxHoursPerWeek {
return fmt.Errorf("hours_per_week must be greater than 0 and at most %d", maxHoursPerWeek)
}
if mask := r.GetInt("workdays_mask"); mask < 1 || mask > 127 {
return errors.New("workdays_mask must be between 1 and 127")
}
if _, err := time.LoadLocation(r.GetString("timezone")); err != nil {
return fmt.Errorf("timezone %q is not a known IANA time zone", r.GetString("timezone"))
}
case "balance_adjustments":
if r.GetInt64("delta_ms") == 0 {
return errors.New("delta_ms must not be 0")
}
}
return nil
}
// setData copies the fields present in the change data onto the record. Fields
// the change leaves out keep their value, so a tombstone or a partial update
// does not wipe them. The request validation has already rejected unknown fields.
func setData(r *core.Record, c Change) {
for field, value := range c.Data {
r.Set(field, value)
}
}
// isLastLiveSettings reports whether id is the only non-deleted settings row of the owner.
func isLastLiveSettings(tx core.App, ownerId, id string) (bool, error) {
_, err := tx.FindFirstRecordByFilter("settings_history",
"owner = {:owner} && id != {:id} && deleted = false",
dbx.Params{"owner": ownerId, "id": id},
)
if errors.Is(err, sql.ErrNoRows) {
return true, nil
}
return false, err
}