196 lines
7.0 KiB
Go
196 lines
7.0 KiB
Go
package store
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
var (
|
|
ErrPathSnapshotChanged = errors.New("semantic paths changed during authorization; retry the operation")
|
|
ErrPathMutationTooLarge = errors.New("too many semantic paths in one operation")
|
|
)
|
|
|
|
// MaxPathMutationPaths bounds both authorization work and a single mutation.
|
|
// Larger trees should be submitted as independently authorized smaller subtrees.
|
|
const MaxPathMutationPaths = 10000
|
|
|
|
// PathMutationSnapshot is issued by the store, never decoded from client input.
|
|
// Its private bindings are the exact set on which the handler checks grants.
|
|
// Checking them again inside the write transaction prevents new descendants,
|
|
// removed entries, or replaced Object bindings from escaping those checks.
|
|
type PathMutationSnapshot struct {
|
|
domainUUID string
|
|
root string
|
|
recursive bool
|
|
bindings []pathRename
|
|
}
|
|
|
|
func (snapshot *PathMutationSnapshot) Root() string { return snapshot.root }
|
|
|
|
func (snapshot *PathMutationSnapshot) Paths() []string {
|
|
paths := make([]string, len(snapshot.bindings))
|
|
for i, binding := range snapshot.bindings {
|
|
paths[i] = binding.OldPath
|
|
}
|
|
return paths
|
|
}
|
|
|
|
type pathQueryer interface {
|
|
Query(string, ...any) (*sql.Rows, error)
|
|
}
|
|
|
|
func pathMutationTransactionError(err error) error {
|
|
var sqliteError interface{ Code() int }
|
|
if errors.As(err, &sqliteError) && sqliteError.Code() == 517 { // SQLITE_BUSY_SNAPSHOT
|
|
return ErrPathSnapshotChanged
|
|
}
|
|
return err
|
|
}
|
|
|
|
// Binary half-open ranges are literal and case-sensitive like paths.path.
|
|
// '/' followed by any suffix sorts before '0', its next ASCII character.
|
|
// Unlike LIKE, neither percent, underscore, backslash nor case changes can
|
|
// expand the requested subtree. The range can use the Domain/Path index.
|
|
func listMutationPaths(q pathQueryer, domainUUID, root string, recursive bool) ([]pathRename, error) {
|
|
return (&Store{}).listMutationPaths(q, domainUUID, root, recursive)
|
|
}
|
|
|
|
func (s *Store) listMutationPaths(q pathQueryer, domainUUID, root string, recursive bool) ([]pathRename, error) {
|
|
collation := "BINARY"
|
|
if s.sqlBackend == storePostgreSQL {
|
|
collation = `"C"`
|
|
}
|
|
prefix := strings.TrimRight(root, "/") + "/"
|
|
upper := strings.TrimSuffix(prefix, "/") + "0"
|
|
query := `
|
|
SELECT path, object_uuid, created_at, COALESCE(is_primary, 0)
|
|
FROM paths WHERE domain_uuid = ` + s.sqlParam(1) + ` AND path = ` + s.sqlParam(2)
|
|
args := []any{domainUUID, root}
|
|
if recursive {
|
|
// Separate indexed arms avoid the Domain-wide scan SQLite may choose
|
|
// for an OR with a runtime recursive flag. Lexical order is stable and
|
|
// puts each parent before its children without a full length sort.
|
|
query += ` UNION ALL
|
|
SELECT path, object_uuid, created_at, COALESCE(is_primary, 0)
|
|
FROM paths WHERE domain_uuid = ` + s.sqlParam(3) + `
|
|
AND path >= ` + s.sqlParam(4) + ` COLLATE ` + collation + ` AND path < ` + s.sqlParam(5) + ` COLLATE ` + collation + ` AND path != ` + s.sqlParam(6)
|
|
args = append(args, domainUUID, prefix, upper, root)
|
|
}
|
|
args = append(args, MaxPathMutationPaths+1)
|
|
// ORDER BY a named output column is portable across compound SELECTs.
|
|
query = `SELECT * FROM (` + query + `) mutation_paths ORDER BY path COLLATE ` + collation + ` LIMIT ` + s.sqlParam(len(args))
|
|
rows, err := q.Query(query, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
var bindings []pathRename
|
|
for rows.Next() {
|
|
var item pathRename
|
|
if err := rows.Scan(&item.OldPath, &item.ObjectUUID, &item.CreatedAt, &item.IsPrimary); err != nil {
|
|
return nil, err
|
|
}
|
|
bindings = append(bindings, item)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(bindings) > MaxPathMutationPaths {
|
|
return nil, ErrPathMutationTooLarge
|
|
}
|
|
return bindings, nil
|
|
}
|
|
|
|
func (s *Store) SnapshotPathsInDomain(domainUUID, root string, recursive bool) (*PathMutationSnapshot, error) {
|
|
root = normalizePath(root)
|
|
bindings, err := s.listMutationPaths(s.DB, domainUUID, root, recursive)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if len(bindings) == 0 {
|
|
return nil, ErrPathNotFound
|
|
}
|
|
return &PathMutationSnapshot{domainUUID: domainUUID, root: root, recursive: recursive, bindings: bindings}, nil
|
|
}
|
|
|
|
func (snapshot *PathMutationSnapshot) validate(domainUUID, root string, recursive bool, bindings []pathRename) error {
|
|
if snapshot == nil || snapshot.domainUUID != domainUUID || snapshot.root != root || snapshot.recursive != recursive || len(snapshot.bindings) != len(bindings) {
|
|
return ErrPathSnapshotChanged
|
|
}
|
|
for i, binding := range bindings {
|
|
if snapshot.bindings[i] != binding {
|
|
return ErrPathSnapshotChanged
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RemovePathsInDomainChecked unlinks the authorized bindings atomically. It
|
|
// deliberately retains Objects, Revisions and content-addressed Documents.
|
|
// Every scope is revalidated before the first DELETE, including overlapping
|
|
// selections. SQLite rejects an upgrade of a stale read snapshot to a write;
|
|
// do not retry this transaction without taking and authorizing a new snapshot.
|
|
func (s *Store) RemovePathsInDomainChecked(domainUUID string, snapshots []*PathMutationSnapshot) (_ int, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("remove checked paths", resultErr) }()
|
|
if err := s.ensureLocalDomain(domainUUID); err != nil {
|
|
return 0, err
|
|
}
|
|
if len(snapshots) == 0 {
|
|
return 0, ErrPathNotFound
|
|
}
|
|
tx, cancel, err := s.beginPathMutation(domainUUID)
|
|
defer cancel()
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer tx.Rollback()
|
|
bindings := map[string]pathRename{}
|
|
for _, snapshot := range snapshots {
|
|
if snapshot == nil || snapshot.domainUUID != domainUUID || snapshot.root == "/" {
|
|
return 0, ErrPathSnapshotChanged
|
|
}
|
|
current, err := s.listMutationPaths(tx, domainUUID, snapshot.root, snapshot.recursive)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if err := snapshot.validate(domainUUID, snapshot.root, snapshot.recursive, current); err != nil {
|
|
return 0, err
|
|
}
|
|
for _, binding := range current {
|
|
bindings[binding.OldPath] = binding
|
|
}
|
|
if len(bindings) > MaxPathMutationPaths {
|
|
return 0, ErrPathMutationTooLarge
|
|
}
|
|
}
|
|
for _, binding := range bindings {
|
|
if _, err := tx.Exec(`DELETE FROM paths WHERE domain_uuid=`+s.sqlParam(1)+` AND path=`+s.sqlParam(2)+` AND object_uuid=`+s.sqlParam(3), domainUUID, binding.OldPath, binding.ObjectUUID); err != nil {
|
|
return 0, pathMutationTransactionError(err)
|
|
}
|
|
}
|
|
operationID := uuid.NewString()
|
|
roots := make([]map[string]any, 0, len(snapshots))
|
|
for _, snapshot := range snapshots {
|
|
roots = append(roots, map[string]any{"path": snapshot.root, "recursive": snapshot.recursive})
|
|
}
|
|
payload, err := json.Marshal(map[string]any{"operation_uuid": operationID, "roots": roots, "count": len(bindings)})
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
if err := s.appendActivityOutboxIfAvailable(tx, ActivityOutboxEvent{
|
|
DomainUUID: domainUUID, EventType: "path.unlinked", TargetKind: "path",
|
|
Payload: string(payload), IdempotencyKey: "path.unlinked:" + operationID,
|
|
}); err != nil {
|
|
return 0, err
|
|
}
|
|
if err := tx.Commit(); err != nil {
|
|
return 0, pathMutationTransactionError(err)
|
|
}
|
|
s.InvalidatePathCaches()
|
|
return len(bindings), nil
|
|
}
|