package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"craftdesign.group/quarry/internal/ops"
)
// RFC 0027: an agent refused for want of authority its person holds may
// ask them instead. The transports find this through the registry
// (ops.Registry.AskerOf) and call it only when the caller sent
// Quarry-Ask; it decides whether this caller may ask for this call,
// files the request and tells the person.
// personFor is who answers for agent: a personal agent's operator, a
// forge agent's answerable admin. "" for a person, for an agent whose
// person is gone or shut, or for an agent that answers to another
// agent.
func (d Deps) personFor(agent string) string {
acct, ok := d.accountNamed(agent)
if !ok || acct.Operator == "" || acct.Disabled != "" {
return ""
}
person := acct.Operator
if person == forgeOperator {
person = acct.Answerable
}
p, ok := d.accountNamed(person)
if !ok || p.Disabled != "" || p.Operator != "" {
return ""
}
return person
}
// selfAskerPrefix begins the asker of a call a person's own login token
// asked of themselves. The asker names the token too, so each login token
// has its own quota and its own pickup claims, and a revoked token's asks
// can be told apart. An account name never holds a space, so no account
// can be this asker.
const (
selfAskerPrefix = "signed-in client of "
selfAskerVia = " via "
)
func selfAsker(person, token string) string { return selfAskerPrefix + person + selfAskerVia + token }
// IsSelfAsker reports whether agent is the asker of a login token's own ask.
func IsSelfAsker(agent string) bool { return strings.HasPrefix(agent, selfAskerPrefix) }
// selfAskerOf is the person and the token a self asker names.
func selfAskerOf(agent string) (person, token string, ok bool) {
rest, ok := strings.CutPrefix(agent, selfAskerPrefix)
if !ok {
return "", "", false
}
person, token, ok = strings.Cut(rest, selfAskerVia)
return person, token, ok && person != "" && token != ""
}
// selfAskerFor is the self asker of ctx's caller when it is a person's own
// login token, else "".
func selfAskerFor(ctx context.Context) string {
if tok, ok := ops.TokenOf(ctx); ok && tok.Login && tok.ID != "" && ops.User(ctx) != "" {
return selfAsker(ops.User(ctx), tok.ID)
}
return ""
}
// selfVia is what the approval page shows of the asking client: the
// token's label and the address the call came from.
func selfVia(ctx context.Context) string {
tok, _ := ops.TokenOf(ctx)
raw, _ := json.Marshal(map[string]string{"label": tok.Name, "addr": ops.AddrOf(ctx)})
return string(raw)
}
// selfTokenLive says the login token a self-asked request names is still
// the person's and still live: not ended, not revoked, not lapsed. It
// fails closed when the forge cannot say.
func (d Deps) selfTokenLive(s SignOffRequest) bool {
person, id, ok := selfAskerOf(s.Agent)
if !ok || person != s.Owner {
return false
}
list, ok := d.SyncTokens.(TokenList)
if !ok {
return false
}
toks, err := list.Tokens(person)
if err != nil {
return false
}
for _, t := range toks {
if t.ID == id {
return t.Live(d.now())
}
}
return false
}
// selfAsk reports the person whose login token this is when the call is
// one a hard stop refuses it: only a person's login token, never a
// scoped token, and never a call the hard stops let through.
func (d Deps) selfAsk(ctx context.Context, desc *ops.Descriptor, in any) (string, bool) {
if selfAskerFor(ctx) == "" || d.hardStopGate(ctx, desc, in) == nil {
return "", false
}
who := ops.User(ctx)
acct, ok := d.accountNamed(who)
if !ok || acct.Operator != "" || acct.Disabled != "" {
return "", false
}
return who, true
}
// askPerson is the forge's ops.Asker.
func (d Deps) askPerson(ctx context.Context, desc *ops.Descriptor, repo string, in any, reason string) (any, bool, error) {
if d.SignOffs == nil {
return nil, false, nil
}
agent := ops.User(ctx)
person := d.personFor(agent)
repo, in = d.canonRepoAs(ctx, repo), d.canonAsked(ctx, desc.Name, in)
self, via := false, ""
if person == "" {
// A person's own login token, refused by a hard stop, asks its
// person: themselves, from a browser.
if p, ok := d.selfAsk(ctx, desc, in); ok {
person, agent, self, via = p, selfAsker(p, ops.Via(ctx)), true, selfVia(ctx)
}
}
if person == "" || !askableFor(desc.Name, person, in) {
return nil, false, nil
}
if !self && !d.agentAsks(agent) {
return nil, true, fmt.Errorf("%s takes no requests from %s: %w", person, agent, ops.ErrForbidden)
}
if self && desc.HasOnceSecret() && pickupCodeOf(ctx) == "" {
return nil, true, fmt.Errorf("this call leaves a credential; ask with Quarry-Pickup so it is collected with your key, not read from the request: %w", ops.ErrInvalid)
}
if !d.mayAsk(ctx, desc, repo, person, in) {
return nil, false, nil
}
// What is wrong with the request's own shape is said in words: it
// reads nothing of the forge, so refusing tells an asker nothing it
// did not send.
if desc.Name == loginOp {
return nil, true, fmt.Errorf("a login is filed only when its person claims a client's start; an agent cannot ask for one: %w", ops.ErrInvalid)
}
if desc.Name == setupOp {
si := setupInOf(in)
if si.Ceiling != "" {
return nil, true, fmt.Errorf("ceiling is fixed by the kind and the role; leave it out: %w", ops.ErrInvalid)
}
if si.NewRepo || si.Namespace != "" {
return nil, true, fmt.Errorf("a repository is made for a setup only when its person claims a client's start; ask for one that exists: %w", ops.ErrInvalid)
}
if _, _, _, err := setupShape(si); err != nil {
return nil, true, err
}
}
if desc.Name == autoOp {
if err := autoOnGiven(in); err != nil {
return nil, true, err
}
}
// A request is checked when it is asked: one the owner could not
// run, or that names what the agent itself cannot see, is not asked
// at all, and the agent is left with the refusal its plain call
// already got. Asking never says more than refusing would, so no
// distinct answer for a missing repository, a missing agent or
// somebody else's agent is ever given.
if !d.preflightAsk(ctx, desc.Name, person, in) {
return nil, false, nil
}
// What the owner will be shown is decided once, now, and stored in
// the request: who the agent will belong to and the letters of the
// credential. Approval runs those, or refuses; it never falls back.
if desc.Name == setupOp {
si := setupInOf(in)
plan, err := d.planSetup(person, si)
if err != nil {
return nil, false, nil
}
si.BelongsTo, si.Ceiling = plan.Belongs, plan.Ceiling
if plan.Kind == "push" {
si.Role = plan.Role
}
in = si
}
pickup := pickupCodeOf(ctx)
if err := checkPickupCode(pickup); err != nil {
return nil, true, err
}
if desc.Name == reissueOp {
ri, err := d.planReissue(ctx, person, pickup, in)
if err != nil {
return nil, true, err
}
in = ri
}
if pickup != "" {
if err := pickupAllowedFor(desc); err != nil {
return nil, true, err
}
}
code := ""
if repo != "" {
r, err := d.repo(repo)
if err != nil {
return nil, false, nil
}
code = r.Code
}
raw, err := json.Marshal(in)
if err != nil {
return nil, true, err
}
reason = strings.TrimSpace(reason)
if len(reason) > 200 {
reason = reason[:200]
}
summary := desc.Sentence(d.labelled(desc.Name, in))
if desc.Name == setupOp {
summary = setupSummary(in)
}
if desc.Name == "branch.protection.set" {
summary = d.protectSummary(in)
}
if desc.Name == autoOp {
summary = autoSummary(in)
}
if desc.Name == "ci.worker.token.new" {
// Only a request that names pools gets the longer sentence; a
// plain one keeps the op's own ("Mint a worker token for pi").
if ps := workerTokenSummary(in); ps != "" {
summary = ps
}
}
if summary == "" {
summary = describeCall(desc.Name, repo, in)
}
held := ""
if forgeEdgeOps[desc.Name] && d.operatorOf(agent) == forgeOperator {
held = d.heldNow(desc.Name, repo, string(raw))
}
s, err := d.SignOffs.RequestSignOff(SignOffRequest{Agent: agent, Owner: person, Op: desc.Name, Repo: repo,
Code: code, Input: string(raw), Summary: summary, Reason: reason, Pickup: pickup, Held: held, Via: via})
if err != nil {
if errors.Is(err, ErrPickupBound) || errors.Is(err, ErrPickupMismatch) {
return nil, true, pickupAskError(err)
}
if errors.Is(err, ErrTooManySignOffs) {
return nil, true, fmt.Errorf("%s already has as many requests waiting for %s as it may: %w", agent, person, ops.ErrInvalid)
}
return nil, true, err
}
d.tellPerson(s)
return askedOut{SignOff: s}, true, nil
}
// preflights are the ops that can say, before a request is recorded,
// whether the owner could run them with this input. An op with no entry
// is asked as it always was and judged when the owner approves. caller
// is the asking agent's own context and owner the person's.
var preflights = map[string]func(d Deps, caller, owner context.Context, in any) bool{
setupOp: setupPreflight,
// A replacement is asked only for an agent the person could replace
// the tokens of themselves: another person's is refused as the plain
// call is.
reissueOp: func(d Deps, caller, owner context.Context, in any) bool {
as, err := d.agents()
if err != nil {
return false
}
// The person's own agent, with no site-admin reach: an asked
// replacement hands the new secret to the asker.
op := as.Operator(nameOf(in))
return op != "" && op == ops.User(owner)
},
"agent.token.new": tokenReposPreflight,
"agent.token.repos": tokenReposPreflight,
"agent.grant": func(d Deps, caller, owner context.Context, in any) bool {
repo := inputField(in, "Repo")
// A repository the agent cannot read does not exist for it, by
// asking as by refusing.
if d.CanRead != nil && !d.CanRead(caller, repo) {
return false
}
as, err := d.agents()
if err != nil || d.agentToPutToWork(owner, as, inputField(in, "Agent")) != nil {
return false
}
if _, err = d.repoFor(owner, repo); err != nil {
return false
}
if inputField(in, "Role") != "" || strings.TrimSpace(inputField(in, "Caps")) != "" {
return d.refuseOutOfScope(owner, as.Operator(inputField(in, "Agent")), repo) == nil
}
return true
},
}
// tokenReposPreflight is asking-time judgment of a token's repositories:
// each must be one the asker reads, and the owner too, judged as the
// agent. A private repository the asker cannot read, an unknown one and
// one still registering are alike refused, as a plain call refuses them.
func tokenReposPreflight(d Deps, caller, owner context.Context, in any) bool {
names := splitList(inputField(in, "Repos"))
for _, n := range names {
if _, err := d.repoFor(caller, n); err != nil {
return false
}
if _, err := d.repoFor(owner, n); err != nil {
return false
}
}
return true
}
// preflightAsk runs op's preflight, if it has one: false means do not
// ask.
func (d Deps) preflightAsk(caller context.Context, op, owner string, in any) bool {
check, ok := preflights[op]
if !ok {
return true
}
return check(d, caller, ops.WithUser(context.Background(), owner), in)
}
// mayAsk reports whether the calling agent may ask person for this call
// (RFC 0027): inside the agent's own scope, something the person holds,
// on a repository the agent can see. A plan's steps pass the same test.
func (d Deps) mayAsk(ctx context.Context, desc *ops.Descriptor, repo, person string, in any) bool {
// The agent's own scope bounds what it may ask about: a token
// limited to repositories asks only about those, and nothing
// forge-wide.
if tok, byToken := ops.TokenOf(ctx); byToken {
// One exception: an agent asking about its OWN token, for a new
// one or a wider reach. Without it an agent on a token limited to
// repositories could never be given more than it has (#411); the
// person sees and approves exactly what is granted.
if repo == "" && tok.Limited && !ownCredential(desc.Name, ops.User(ctx), in) && !askedWithinReach(tok, desc.Name, in) {
return false
}
if repo != "" && tok.Reaches != nil && !tok.Reaches(repo) {
return false
}
}
// And the person must hold what the call needs. Judged without the
// agent's token: these are the person's own letters, or their site
// flag for an operator op. An op that names no letters is judged
// when it runs, as them.
if desc.Caps != "" {
holds := d.CapsFor != nil && d.CapsFor(person, repo).HasAny(desc.Caps)
if !holds && (desc.Operator || desc.Scope == ops.ScopeFleet) {
holds = d.isSiteAdmin(context.Background(), person)
}
if !holds {
return false
}
}
// A repository the agent cannot read is answered as one that does
// not exist, by asking as by refusing.
if repo != "" && d.CanRead != nil && !d.CanRead(ctx, repo) {
return false
}
return true
}
// ErrTooManySignOffs is a SignOffStore's refusal of a request from an
// agent that already has as many waiting as it may (RFC 0027, Limits).
var ErrTooManySignOffs = errors.New("too many sign-off requests waiting")
// askedOut is what an agent that asked is answered with.
type askedOut struct {
SignOff SignOffRequest `json:"signoff"`
}
// describeCall names a call for the person in words that carry no
// secrets: the op, and the repository and account it names. Never the
// input itself, which may hold a password.
func describeCall(op, repo string, in any) string {
s := op
name := inputField(in, "Agent")
if name == "" {
name = nameOf(in)
}
if name != "" && name != repo {
s += " for " + name
}
if repo != "" {
s += " on " + repo
}
return s
}
// tellPerson reaches the person wherever they are: the page's attention
// stream, push and email, as every sign-off does.
func (d Deps) tellPerson(s SignOffRequest) {
summary := s.Summary
if s.Reason != "" {
summary += ` ("` + s.Reason + `")`
}
d.attend(s.Owner, AttentionEvent{Kind: "signoff", Repo: s.Repo, From: s.Agent, Summary: summary, Link: "/me/requests/" + s.ID})
d.fireSignOff(s.Owner, s.Repo, s.Agent, summary, s.ID)
}
// tellAsker tells the asking agent, and nobody else, that its request
// left pending: on the agent's own attention stream, which only that
// account can read, so a private request's existence, op and repository
// reach no other account and no repository's event stream. It carries
// the request's id (in the link signoff.get answers at), the op and the
// new state, and never a credential, a pickup code or a reason; those
// stay behind signoff.get. Called once the decision and its result are
// held, and best-effort like every attend: it cannot undo the decision.
func (d Deps) tellAsker(s SignOffRequest) {
if isClientAsker(s.Agent) || isRunnerAsker(s.Agent) || IsSelfAsker(s.Agent) {
// A client has no account and no stream to tell; it polls its
// pickup.
return
}
d.attend(s.Agent, AttentionEvent{
Kind: "signoff.decided", Repo: s.Repo, From: s.Owner,
Summary: s.Op + " " + s.State, Link: "/api/v1/signoffs/" + s.ID,
})
}
// fireSignOff tells a person about a request beyond an open tab: the
// inbox row and the push at once, and the email through a five-minute
// digest per agent, so a burst is one email (RFC 0028).
func (d Deps) fireSignOff(to, repo, agent, summary, id string) {
d.fireSignOffWith(to, repo, agent, summary, id, true)
}
// fireSignOffWith is fireSignOff with the email optional: the inbox row
// and the push always go.
func (d Deps) fireSignOffWith(to, repo, agent, summary, id string, email bool) {
payload := func() map[string]any {
p := map[string]any{
"repo": repo, "from": agent, "actor": agent, "summary": summary, "surface": "signoff",
"link": d.link("/me/requests/" + id), "waiting": d.link("/me/requests"),
}
if repo == "" {
p["repoName"] = "Requests" // what the email's header names
}
return p
}
d.fireNotify(NotifyEvent{Workflow: "quarry-signoff", To: to, Payload: payload(), TxnID: "signoff:" + id})
if email {
d.fireNotify(NotifyEvent{Workflow: "quarry-signoff-email", To: to, Payload: payload(), TxnID: "signoff-email:" + id})
}
}
// prefAsk is the agent account's setting that turns asking off: "off",
// or unset for on (RFC 0027, Limits).
const prefAsk = "ask"
// agentAsks reports whether agent may ask its person.
func (d Deps) agentAsks(agent string) bool {
return d.Prefs == nil || d.Prefs.AccountPref(agent, prefAsk) != "off"
}
// inputField is an input's string field by name, or "".
func inputField(in any, field string) string {
v := reflect.ValueOf(in)
if v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return ""
}
if f := v.FieldByName(field); f.IsValid() && f.Kind() == reflect.String {
return f.String()
}
return ""
}
// ownCredential is a call about the caller's own tokens: a new one for
// itself, or a change to which repositories one of its own reaches.
func ownCredential(op, caller string, in any) bool {
switch op {
case "agent.token.new", "agent.token.repos":
return caller != "" && inputField(in, "Agent") == caller
case "agent.token.reissue":
return caller != "" && nameOf(in) == caller
}
return false
}
// pickupAllowedFor refuses a pickup code on a call that cannot use one:
// its answer holds no credential, or holds one a lapse cannot revoke,
// which must not be held where nobody may collect it (decided by
// lapseOps, the one table of what a lapse revokes).
func pickupAllowedFor(desc *ops.Descriptor) error {
if !desc.HasOnceSecret() {
return fmt.Errorf("this call leaves no credential for a pickup code to collect; leave Quarry-Pickup out: %w", ops.ErrInvalid)
}
if !parkable(desc.Name) {
return fmt.Errorf("this kind of value cannot be held for pickup: nothing could revoke it if it were never collected; leave Quarry-Pickup out: %w", ops.ErrInvalid)
}
return nil
}
const autoOp = "landing.auto"
func autoInOf(in any) landingAutoIn {
switch v := in.(type) {
case landingAutoIn:
return v
case *landingAutoIn:
if v != nil {
return *v
}
}
return landingAutoIn{}
}
// autoOnGiven refuses a landing.auto call that leaves "on" out: with a
// bool that defaulted to false, an agent meaning to arm disarmed.
func autoOnGiven(in any) error {
if autoInOf(in).On == nil {
return fmt.Errorf(`"on" is required: send "on": true to arm auto-land or "on": false to disarm it: %w`, ops.ErrInvalid)
}
return nil
}
// autoSummary is the sign-off line for landing.auto, which reads two
// ways by its input.
func autoSummary(in any) string {
a := autoInOf(in)
if a.On == nil || a.ID == "" {
return ""
}
verb := "Disarm"
if *a.On {
verb = "Arm"
}
return verb + " auto-land on !" + strings.TrimPrefix(a.ID, "!")
}