Skip to content
quarry Artifact [044e740834]
Login

Artifact [044e740834]

Artifact 044e7408340a3e05f9e1284280792ea437b841757b45c557088c4eb50dfb8261:


package api

import (
	"context"
	"errors"
	"fmt"
	"reflect"
	"slices"
	"strings"
	"sync/atomic"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
)

// takedown.go is RFC 0023's operator acts: disable a repository on a
// notice, put one on legal hold, and end either. A site admin's, at the
// forge, since a site admin holds no letters on other people's
// repositories (#318). A site token may disable and restore, because a
// host complaint needs an answer in minutes; placing or lifting a hold
// is a judgment about evidence and stays with a person.

// TakedownStore is the takedown table (oltp/takedown.go).
type TakedownStore interface {
	TakedownOf(repo string) (oltp.Takedown, bool, error)
	SetTakedown(oltp.Takedown) error
	EndTakedown(repo, strength, actor, via, reason string) error
	TakedownLog(repo string, limit int) ([]oltp.TakedownAct, error)
	Takedowns() (map[string]oltp.Takedown, error)
}

type takedownIn struct {
	Repo     string `json:"repo" validate:"required,max=200"`
	Category string `json:"category" validate:"required,max=40"`
	Notice   string `json:"notice" validate:"max=200"`
	Reason   string `json:"reason" validate:"max=4000"`
}

type takedownEndIn struct {
	Repo   string `json:"repo" validate:"required,max=200"`
	Reason string `json:"reason" validate:"max=4000"`
}

type takedownOut struct {
	Repo     string `json:"repo"`
	Strength string `json:"strength,omitempty"`
}

type takedownLogIn struct {
	Repo  string `json:"repo" validate:"max=200"`
	Limit int    `json:"limit"`
}

type takedownActOut struct {
	Repo     string `json:"repo"`
	Owner    string `json:"owner"`
	Act      string `json:"act"`
	Strength string `json:"strength"`
	Category string `json:"category"`
	Notice   string `json:"notice"`
	Reason   string `json:"reason"`
	Actor    string `json:"actor"`
	Via      string `json:"via"`
	At       string `json:"at"`
}

type takedownCurOut struct {
	Repo     string `json:"repo"`
	Strength string `json:"strength"`
	Category string `json:"category"`
	Notice   string `json:"notice"`
	At       string `json:"at"`
}

type takedownLogOut struct {
	Acts []takedownActOut `json:"acts"`
	// Current is every takedown in force, for the fleet's rows.
	Current []takedownCurOut `json:"current"`
}

// takedownReach is the line every takedown act holds before it writes:
// a token reaches only a repository it can read, so a private one it
// holds no grant on answers as a name nobody serves; and a forge
// agent's s stops at a deed a site admin or another forge agent holds.
func (d Deps) takedownReach(ctx context.Context, repo string) error {
	if d.Takedowns == nil {
		return fmt.Errorf("this deployment keeps no takedowns: %w", ops.ErrUnavailable)
	}
	if _, err := d.repo(repo); err != nil || !d.siteReaches(ctx, repo) {
		return fmt.Errorf("no repository %q: %w", repo, ops.ErrNotFound)
	}
	if d.Owners != nil {
		owner, err := d.Owners.OwnerOf(repo)
		if err != nil {
			return err
		}
		if owner != "" {
			if err := d.refuseForgeAgentOn(ctx, owner); err != nil {
				return err
			}
		}
	}
	return nil
}

// refuseHeldRepo is the router's takedown gate for an op that names its
// repository in the body rather than the path, so the router never sees
// it: moving a repository between teams, accepting an offer, granting an
// agent. Silent for a repository the caller cannot read, which the op's
// own not-found answers.
func (d Deps) refuseHeldRepo(ctx context.Context, repo string) error {
	if d.Held == nil || repo == "" || (d.CanRead != nil && !d.CanRead(ctx, repo)) {
		return nil
	}
	if why := d.Held(ctx, repo); why != "" {
		return fmt.Errorf("%s: %w", why, ops.ErrForbidden)
	}
	return nil
}

// listable is the one question every cross-repository read asks of a
// repository before it contributes a row, a count, a title or a name:
// may this caller read it, and does RFC 0023 let the repository answer
// them. Held is already per caller, so a disabled repository stays
// listed for its own admins and a legal hold for a site admin person
// alone. A held repository is skipped exactly as a private one is, so
// it adds nothing a private one does not.
func (d Deps) listable(ctx context.Context, repo string) bool {
	if d.CanRead != nil && !d.CanRead(ctx, repo) {
		return false
	}
	// A companion store (RFC 0015) is the parent's content under another
	// name; Held resolves it to the parent itself, from a cached map.
	return d.Held == nil || d.Held(ctx, repo) == ""
}

func refuseTokenHold(ctx context.Context) error {
	if _, byToken := ops.TokenOf(ctx); byToken {
		return fmt.Errorf("a legal hold is a judgment about evidence and reporting; placing or lifting one needs a person signed in, not a token: %w", ops.ErrForbidden)
	}
	return nil
}

func takedownErr(err error) error {
	if errors.Is(err, oltp.ErrTakedownState) {
		return fmt.Errorf("%v: %w", err, ops.ErrInvalid)
	}
	return err
}

// holdGen counts the takedown changes this process has made. A stream
// that caches who may see what drops its cache when it moves, so a hold
// placed while it is open stops it at the next event, not a TTL later.
var holdGen atomic.Uint64

func (d Deps) takedownChanged() {
	if d.TakedownsChanged != nil {
		d.TakedownsChanged()
	}
	holdGen.Add(1)
}

func (d Deps) registerTakedowns(r *ops.Registry) error {
	set := func(name, strength, route, doc string) error {
		return ops.Register(r, ops.Op[takedownIn, takedownOut]{
			Name: name, Caps: "s", Scope: ops.ScopeFleet, Kind: ops.Command, Auth: ops.Admin,
			Route: route, Doc: doc,
			Run: func(ctx context.Context, in takedownIn) (takedownOut, error) {
				if strength == oltp.LegalHold {
					if err := refuseTokenHold(ctx); err != nil {
						return takedownOut{}, err
					}
				}
				if err := d.takedownReach(ctx, in.Repo); err != nil {
					return takedownOut{}, err
				}
				if err := d.Takedowns.SetTakedown(oltp.Takedown{Repo: in.Repo, Strength: strength,
					Category: in.Category, Notice: in.Notice, Reason: in.Reason,
					Actor: ops.User(ctx), Via: ops.Via(ctx)}); err != nil {
					return takedownOut{}, takedownErr(err)
				}
				d.takedownChanged()
				return takedownOut{Repo: in.Repo, Strength: strength}, nil
			},
		})
	}
	end := func(name, strength, route, doc string) error {
		return ops.Register(r, ops.Op[takedownEndIn, takedownOut]{
			Name: name, Caps: "s", Scope: ops.ScopeFleet, Kind: ops.Command, Auth: ops.Admin,
			Route: route, Doc: doc,
			Run: func(ctx context.Context, in takedownEndIn) (takedownOut, error) {
				if strength == oltp.LegalHold {
					if err := refuseTokenHold(ctx); err != nil {
						return takedownOut{}, err
					}
				}
				if err := d.takedownReach(ctx, in.Repo); err != nil {
					return takedownOut{}, err
				}
				if err := d.Takedowns.EndTakedown(in.Repo, strength, ops.User(ctx), ops.Via(ctx), in.Reason); err != nil {
					return takedownOut{}, takedownErr(err)
				}
				d.takedownChanged()
				return takedownOut{Repo: in.Repo}, nil
			},
		})
	}
	if err := set("repo.disable", oltp.Disabled, "POST /api/v1/repos/disable",
		"Disable a repository on a notice (RFC 0023): every surface answers 451 to everybody but its own admins, "+
			"who keep access to remove what was reported. The store and settings are kept; delete and stop serving "+
			"are refused until it is restored. `category` is one of copyright, host, unlawful, terms, terrorism, "+
			"child-abuse, preservation, law-enforcement."); err != nil {
		return err
	}
	if err := set("repo.hold", oltp.LegalHold, "POST /api/v1/repos/hold",
		"Put a repository on legal hold (RFC 0023): 451 to everybody, its owner included, and no writes, so what "+
			"is held stays as it was. May follow a disable. A person's act; a token is refused."); err != nil {
		return err
	}
	if err := end("repo.restore", oltp.Disabled, "POST /api/v1/repos/restore",
		"Restore a disabled repository: every surface answers as before. Does not lift a legal hold."); err != nil {
		return err
	}
	if err := end("repo.lift", oltp.LegalHold, "POST /api/v1/repos/lift",
		"Lift a legal hold. A person's act; a token is refused."); err != nil {
		return err
	}
	return ops.Register(r, ops.Op[takedownLogIn, takedownLogOut]{
		Name: "repo.takedowns", Caps: "s", Scope: ops.ScopeFleet, Kind: ops.Query, Auth: ops.Admin,
		Route: "GET /api/v1/fleet/takedowns",
		Doc:   "The takedowns in force, and the takedown log newest first: every disable, hold, restore and lift, for one repository or the whole forge.",
		Run: func(ctx context.Context, in takedownLogIn) (takedownLogOut, error) {
			if d.Takedowns == nil {
				return takedownLogOut{}, fmt.Errorf("this deployment keeps no takedowns: %w", ops.ErrUnavailable)
			}
			limit := in.Limit
			if limit <= 0 || limit > 500 {
				limit = 100
			}
			acts, err := d.Takedowns.TakedownLog(in.Repo, limit)
			if err != nil {
				return takedownLogOut{}, err
			}
			cur, err := d.Takedowns.Takedowns()
			if err != nil {
				return takedownLogOut{}, err
			}
			out := takedownLogOut{Acts: []takedownActOut{}, Current: []takedownCurOut{}}
			for _, t := range cur {
				if (in.Repo == "" || t.Repo == in.Repo) && d.siteReaches(ctx, t.Repo) {
					out.Current = append(out.Current, takedownCurOut{Repo: t.Repo, Strength: t.Strength,
						Category: t.Category, Notice: t.Notice, At: t.At})
				}
			}
			slices.SortFunc(out.Current, func(a, b takedownCurOut) int { return strings.Compare(a.Repo, b.Repo) })
			for _, a := range acts {
				// A token sees only the rows of repositories it can read,
				// the private line every other site-token read holds.
				if !d.siteReaches(ctx, a.Repo) {
					continue
				}
				out.Acts = append(out.Acts, takedownActOut{Repo: a.Repo, Owner: a.Owner, Act: a.Act,
					Strength: a.Strength, Category: a.Category, Notice: a.Notice, Reason: a.Reason,
					Actor: a.Actor, Via: a.Via, At: a.At})
			}
			return out, nil
		},
	})
}

// noticeDeliverable says whether a notice may be delivered: to a person,
// not when it is about a repository they may not read or a takedown shuts
// them out of; to a topic, not while the repository is under a takedown. Asked at delivery, so no stored name
// outlives the access behind it.
func (d Deps) noticeDeliverable(e NotifyEvent) bool {
	repo, _ := e.Payload["repo"].(string)
	if repo == "" {
		return true
	}
	if !personTo(e.To) {
		// A topic reaches everybody subscribed to it, none of whom is
		// asked what they may read: a repository under either strength
		// of takedown is silent to them, as it is to an anonymous
		// reader. The site admins' own topic is the operator's.
		return e.To == "admins" || d.Held == nil || d.Held(context.Background(), repo) == ""
	}
	return d.listable(ops.WithUser(context.Background(), e.To), repo)
}

func (d Deps) takenDownMark(repo string) string {
	if d.TakenDown == nil {
		return ""
	}
	return d.TakenDown(repo)
}

// takedownOps are the commands a legal hold must still admit: they are
// how it is lifted, and how a disable under it is ended. RFC 0023 allows
// nothing else on a held repository ("Writes | refused for everybody"; the
// only act it names is its lifting, by a site admin person).
var takedownOps = map[string]bool{"repo.disable": true, "repo.hold": true, "repo.restore": true, "repo.lift": true}

// legalHoldGate refuses every command that names a repository on legal
// hold, for every caller, a site admin person too: the router's gate
// admits that person to READ, and a write that never reaches the store
// (a setting, a grant, a chat line, a webhook) changes the held state as
// surely as a push. Asked at the registry's one Invoke, so no surface
// and no op can reach past it.
func (d Deps) legalHoldGate(ctx context.Context, desc *ops.Descriptor, in any) error {
	if d.LegalHold == nil || takedownOps[desc.Name] {
		return nil
	}
	repos := []string{repoNamed(in, desc.Scope == ops.ScopeRepo)}
	if desc.Writes != nil {
		repos = append(repos, desc.Writes(in)...)
	}
	for _, repo := range repos {
		if repo != "" && d.LegalHold(repo) {
			return fmt.Errorf("%s is on legal hold and takes no writes: %w", repo, ops.ErrForbidden)
		}
	}
	return nil
}

// teamRepoNames are the repositories bound to a team, for the commands
// that change the team and so the access or standing of each.
func (d Deps) teamRepoNames(team string) []string {
	if d.Teams == nil {
		return nil
	}
	rows, err := d.Teams.TeamRepos(team)
	if err != nil {
		return nil
	}
	out := make([]string, 0, len(rows))
	for _, r := range rows {
		out = append(out, r.Repo)
	}
	return out
}

// repoNamed is the repository a command's input names: the field tagged
// `json:"repo"`, or, for an op scoped to a repository (repo.update,
// repo.remove), the one tagged `json:"name"`, as the router's own gate
// reads it.
func repoNamed(in any, byName bool) string {
	v := reflect.ValueOf(in)
	for v.IsValid() && (v.Kind() == reflect.Pointer || v.Kind() == reflect.Interface) {
		v = v.Elem()
	}
	if !v.IsValid() || v.Kind() != reflect.Struct {
		return ""
	}
	t := v.Type()
	for i := 0; i < t.NumField(); i++ {
		name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
		if name == "repo" && v.Field(i).Kind() == reflect.String {
			return v.Field(i).String()
		}
	}
	if byName {
		for i := 0; i < t.NumField(); i++ {
			if name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ","); name == "name" && v.Field(i).Kind() == reflect.String {
				return v.Field(i).String()
			}
		}
	}
	return ""
}