Skip to content
quarry Artifact [9cb17186d2]
Login

Artifact [9cb17186d2]

Artifact 9cb17186d22c4082926bb67c723f849c6eb99a4f0fa5ca1e7ab4578d655342ec:


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 {
	SetProtectionBy(repo, branch string, owners []string, actor, via 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
}

// 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 bad []string
	for _, o := range owners {
		for _, name := range strings.Fields(o) {
			if !have[name] {
				bad = append(bad, name)
			}
		}
	}
	return bad, nil
}

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)
			}
			bad, err := d.unknownOwners(in.Owners)
			if err != nil {
				return branchProtectionsOut{}, err
			}
			if len(bad) > 0 {
				return branchProtectionsOut{}, fmt.Errorf("no account named %s here: %w", strings.Join(bad, ", "), ops.ErrInvalid)
			}
			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)
				}
			}
			if err := w.SetProtectionBy(in.Repo, branch, in.Owners, ops.User(ctx), ops.Via(ctx)); err != nil {
				return branchProtectionsOut{}, err
			}
			return d.protectionList(in.Repo)
		},
	})
}