Skip to content
quarry Artifact [fb83847419]
Login

Artifact [fb83847419]

Artifact fb8384741976f3b3344446c545699c516d3f9c0433c761d0aab69ecfd65ecf4e:


package api

import (
	"context"
	"fmt"
	"path"
	"strings"

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

// ProtectWriter is the write half of ProtectStore: the rules as the
// settings page edits them, the change recorded in the settings log.
// *oltp.DB satisfies it.
type ProtectWriter interface {
	SetProtectionAsked(repo, branch string, owners []string, actor, via, note string) error
}

type branchProtectionsIn struct {
	Repo string `json:"repo" validate:"required,max=64"`
}

type branchProtectionsOut struct {
	Rules []oltp.Protection `json:"rules"`
}

type branchProtectionSetIn struct {
	Repo   string   `json:"repo" validate:"required,max=64"`
	Branch string   `json:"branch" validate:"required,max=200"`
	Owners []string `json:"owners" validate:"max=100"`
}

// ProtectAliasRefusal is the refusal for a rule naming another name of a
// branch: a pushed check-in resolves to one name, so a rule on the
// other could never fire. Shared by the settings form and the API.
func ProtectAliasRefusal(branch, alias string) error {
	return fmt.Errorf(
		"%s is another name for %s here: check-ins on it resolve to %s, so a rule naming "+
			"%s could never refuse anything. Protect %s instead: %w",
		branch, alias, alias, branch, alias, ops.ErrInvalid)
}

func (d Deps) protectionList(repo string) (branchProtectionsOut, error) {
	rules, err := d.Protect.Protections(repo)
	if err != nil {
		return branchProtectionsOut{}, err
	}
	if rules == nil {
		rules = []oltp.Protection{}
	}
	return branchProtectionsOut{Rules: rules}, nil
}

// ProtectOwnersRefusal is the refusal for owners that are no account;
// nil when there are none. Shared by the API and the form.
func ProtectOwnersRefusal(unknown []string) error {
	if len(unknown) == 0 {
		return nil
	}
	return fmt.Errorf("no account named %s here: %w", strings.Join(unknown, ", "), ops.ErrInvalid)
}

// unknownOwners names the logins that are no account here.
func (d Deps) unknownOwners(owners []string) ([]string, error) {
	if d.Accounts == nil {
		return nil, nil
	}
	accts, err := d.Accounts.Accounts()
	if err != nil {
		return nil, err
	}
	have := make(map[string]bool, len(accts))
	for _, a := range accts {
		have[a.Name] = true
	}
	var unknown []string
	for _, o := range owners {
		for _, name := range strings.Fields(o) {
			if !have[name] {
				unknown = append(unknown, name)
			}
		}
	}
	return unknown, nil
}

// protectSummary is the sign-off line for a protection change: the
// branch and every owner, each agent marked "(agent)", or the removal,
// so an approver sees what they are deciding.
func (d Deps) protectSummary(in any) string {
	si, ok := in.(branchProtectionSetIn)
	if !ok {
		if p, isP := in.(*branchProtectionSetIn); isP && p != nil {
			si, ok = *p, true
		}
	}
	if !ok {
		return ""
	}
	owners := strings.Fields(strings.Join(si.Owners, " "))
	if len(owners) == 0 {
		return "Remove protection from " + si.Branch + " of " + si.Repo
	}
	for i, o := range owners {
		if d.operatorOf(o) != "" {
			owners[i] = o + " (agent)"
		}
	}
	return "Protect " + si.Branch + " of " + si.Repo + ", owners: " + strings.Join(owners, ", ")
}

func registerBranchProtection(r *ops.Registry, d Deps) error {
	noStore := fmt.Errorf("no branch-protection store is configured here: %w", ops.ErrNotFound)
	if err := ops.Register(r, ops.Op[branchProtectionsIn, branchProtectionsOut]{
		Name: "branch.protection.list",
		Caps: "a",
		Doc: "List the repository's protected-branch rules (RFC 0007): for each branch name or glob, the accounts " +
			"whose hand a check-in onto it needs. Whoever may open the repository's settings may read them.",
		Kind:  ops.Query,
		Auth:  ops.Token,
		Route: "GET /api/v1/r/{repo}/branch-protection",
		Run: func(ctx context.Context, in branchProtectionsIn) (branchProtectionsOut, error) {
			if d.Protect == nil {
				return branchProtectionsOut{}, noStore
			}
			if _, err := d.repoFor(ctx, in.Repo); err != nil {
				return branchProtectionsOut{}, err
			}
			if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
				return branchProtectionsOut{}, err
			}
			return d.protectionList(in.Repo)
		},
	}); err != nil {
		return err
	}
	return ops.Register(r, ops.Op[branchProtectionSetIn, branchProtectionsOut]{
		Name: "branch.protection.set",
		Ask:  "Protect {branch} of {repo}",
		Caps: "a",
		Doc: "Protect a branch, as the settings page does: branch is a name or a glob, owners the account logins " +
			"whose hand a check-in onto it needs; an empty list removes the rule. An owner that is no account, a glob " +
			"that cannot parse, and a name that is only another name for a branch are refused. Returns the repository's " +
			"rules. An agent does not set one, since it 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}/branch-protection",
		Run: func(ctx context.Context, in branchProtectionSetIn) (branchProtectionsOut, error) {
			w, ok := d.Protect.(ProtectWriter)
			if d.Protect == nil || !ok {
				return branchProtectionsOut{}, noStore
			}
			if who := ops.User(ctx); who != "" {
				if op := d.operatorOf(who); op != "" {
					return branchProtectionsOut{}, fmt.Errorf("%s is an agent, operated by %s, and an agent does not set 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 branchProtectionsOut{}, err
			}
			if err := d.refuseWithout(ctx, in.Repo, "a", false); err != nil {
				return branchProtectionsOut{}, err
			}
			branch := strings.TrimSpace(in.Branch)
			if branch == "" || strings.ContainsAny(branch, "\x00\n\r") {
				return branchProtectionsOut{}, fmt.Errorf("a rule names a branch or a glob: %w", ops.ErrInvalid)
			}
			if _, err := path.Match(branch, ""); err != nil {
				return branchProtectionsOut{}, fmt.Errorf("%q is not a branch name or a glob: %w", branch, ops.ErrInvalid)
			}
			unknown, err := d.unknownOwners(in.Owners)
			if err != nil {
				return branchProtectionsOut{}, err
			}
			if err := ProtectOwnersRefusal(unknown); err != nil {
				return branchProtectionsOut{}, err
			}
			if len(strings.Fields(strings.Join(in.Owners, " "))) > 0 && repo.Index != nil {
				if alias, is, err := repo.Index.AliasOf(branch); err == nil && is && alias != "" {
					return branchProtectionsOut{}, ProtectAliasRefusal(branch, alias)
				}
			}
			note := ""
			if ask, ok := signOffAskOf(ctx); ok {
				note = fmt.Sprintf("asked by %s, request %s", ask.agent, ask.id)
			}
			if err := w.SetProtectionAsked(in.Repo, branch, in.Owners, ops.User(ctx), ops.Via(ctx), note); err != nil {
				return branchProtectionsOut{}, err
			}
			return d.protectionList(in.Repo)
		},
	})
}