package api
import (
"context"
"fmt"
"log"
"sort"
"strings"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// CheckRulesStore is a repository's required-checks rules (RFC 0009),
// read and written: the store behind the settings page's rule rows.
// *oltp.DB satisfies it.
type CheckRulesStore interface {
CheckRules(repo string) ([]oltp.CheckRule, error)
SetCheckRule(repo, branch string, checks []string) error
}
type checkRulesIn struct {
Repo string `json:"repo" validate:"required,max=64"`
}
type checkRuleRow struct {
Branch string `json:"branch"`
Checks []string `json:"checks"`
}
type checkRulesOut struct {
Rules []checkRuleRow `json:"rules"`
}
type checkRuleSetIn struct {
Repo string `json:"repo" validate:"required,max=64"`
Branch string `json:"branch" validate:"required,max=200"`
Checks []string `json:"checks" validate:"max=100"`
}
func (d Deps) checkRuleList(repo string) (checkRulesOut, error) {
rules, err := d.CheckRules.CheckRules(repo)
if err != nil {
return checkRulesOut{}, err
}
out := checkRulesOut{Rules: []checkRuleRow{}}
for _, c := range rules {
out.Rules = append(out.Rules, checkRuleRow{Branch: c.Branch, Checks: c.Checks})
}
return out, nil
}
// tightensChecks says a ci.checks.set call only adds to what is there: its
// list holds every check the branch's current rule holds, in any order, or
// there is no rule to hold. The current rule is read here, now, never from
// the caller. Anything unreadable is not a tightening.
func (d Deps) tightensChecks(in any) bool {
var c checkRuleSetIn
switch v := in.(type) {
case checkRuleSetIn:
c = v
case *checkRuleSetIn:
if v == nil {
return false
}
c = *v
default:
return false
}
if d.CheckRules == nil {
return false
}
was, err := d.CheckRules.CheckRules(c.Repo)
if err != nil {
return false
}
branch := strings.TrimSpace(c.Branch)
have := map[string]bool{}
for _, n := range strings.Fields(strings.Join(c.Checks, " ")) {
have[n] = true
}
for _, r := range was {
if r.Branch != branch {
continue
}
for _, n := range r.Checks {
if !have[n] {
return false
}
}
}
return true
}
func registerRequiredChecks(r *ops.Registry, d Deps) error {
noStore := fmt.Errorf("no required-checks store is configured here: %w", ops.ErrNotFound)
if err := ops.Register(r, ops.Op[checkRulesIn, checkRulesOut]{
Name: "ci.checks.list",
Caps: "a",
Doc: "List the repository's required-checks rules: for each branch name or glob, the check names a " +
"landing onto it needs green on its merge (RFC 0009). Whoever may open the repository's settings may read them.",
Kind: ops.Query,
Auth: ops.Token,
Route: "GET /api/v1/r/{repo}/ci/required-checks",
Run: func(ctx context.Context, in checkRulesIn) (checkRulesOut, error) {
if d.CheckRules == nil {
return checkRulesOut{}, noStore
}
if _, err := d.repoFor(ctx, in.Repo); err != nil {
return checkRulesOut{}, err
}
if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
return checkRulesOut{}, err
}
return d.checkRuleList(in.Repo)
},
}); err != nil {
return err
}
return ops.Register(r, ops.Op[checkRuleSetIn, checkRulesOut]{
Name: "ci.checks.set",
Ask: "Set the required checks on {branch} of {repo}",
Caps: "a",
Doc: "Set the checks a landing onto a branch needs green on its merge, as the settings page does: " +
"branch is a name or a glob, checks the check names; an empty list removes the rule. Adding checks (a list that holds every check the rule already has, or a first rule) runs for a person's login token or an agent that holds the letter a on the repository. " +
"Removing a check or the rule is for a person signed in at a browser; a login token or an agent is refused and may ask with `Quarry-Ask`. A name that is " +
"only another name for a branch is refused, since check-ins on it resolve to the other and the rule could never fire. " +
"Returns the repository's rules. An agent that loosens one decides what may land on a branch: it is refused, " +
"and may ask the person who answers for it with `Quarry-Ask`, who then sets it as themselves. Recorded in the settings log.",
Kind: ops.Command,
Auth: ops.Token,
Route: "POST /api/v1/r/{repo}/ci/required-checks",
Run: func(ctx context.Context, in checkRuleSetIn) (checkRulesOut, error) {
if d.CheckRules == nil {
return checkRulesOut{}, noStore
}
if who := ops.User(ctx); who != "" && !d.tightensChecks(in) {
if op := d.operatorOf(who); op != "" {
return checkRulesOut{}, fmt.Errorf("%s is an agent, operated by %s, and an agent does not loosen what may land on a branch; ask %s: %w",
who, op, op, ops.ErrForbidden)
}
}
repo, err := d.repoFor(ctx, in.Repo)
if err != nil {
return checkRulesOut{}, err
}
if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
return checkRulesOut{}, err
}
branch := strings.TrimSpace(in.Branch)
if branch == "" {
return checkRulesOut{}, fmt.Errorf("a rule names a branch or a glob: %w", ops.ErrInvalid)
}
names := strings.Fields(strings.Join(in.Checks, " "))
if len(names) > 0 && repo.Index != nil {
if alias, is, err := repo.Index.AliasOf(branch); err == nil && is && alias != "" {
return checkRulesOut{}, fmt.Errorf("%s is another name for %s here: check-ins on it resolve to %s, so a rule naming %s could never fire. Set it on %s instead: %w",
branch, alias, alias, branch, alias, ops.ErrInvalid)
}
}
was, err := d.CheckRules.CheckRules(in.Repo)
if err != nil {
return checkRulesOut{}, err
}
before := ""
for _, c := range was {
if c.Branch == branch {
before = strings.Join(c.Checks, " ")
}
}
if err := d.CheckRules.SetCheckRule(in.Repo, branch, names); err != nil {
return checkRulesOut{}, err
}
d.logCheckRule(ctx, in.Repo, branch, before, names)
return d.checkRuleList(in.Repo)
},
})
}
// logCheckRule records a changed rule in the settings log, in the
// branch-keyed field protection uses. A failure to write the row is
// logged, not returned: the rule is already set.
func (d Deps) logCheckRule(ctx context.Context, repo, branch, was string, names []string) {
if d.SettingLog == nil {
return
}
set := append([]string(nil), names...)
sort.Strings(set)
now := strings.Join(set, " ")
if was == now {
return
}
if was == "" {
was = "(no required checks)"
}
if now == "" {
now = "(no required checks)"
}
if ask, ok := signOffAskOf(ctx); ok {
now = fmt.Sprintf("%s (asked by %s, request %s)", now, ask.agent, ask.id)
}
if err := d.SettingLog.LogSetting(repo, ops.User(ctx), ops.Via(ctx), "checks:"+branch, was, now); err != nil {
log.Printf("settings log: required checks on %s: %v", repo, err)
}
}