Skip to content
quarry Artifact [73bd60878d]
Login

Artifact [73bd60878d]

Artifact 73bd60878deba2ecc6e8c09cba69cd0968c790ee6be650f38ae8f52773521a49:


package api

import (
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"time"

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

// RFC 0030 applied to a person's own machine: `quarry login`. A client
// with no credential starts a setup of kind login, naming the machine; the
// person claims its code at /setup and approves; approval mints one token
// on the claiming person's own account, which the pickup key's holder
// collects. It makes no agent and grants nothing. The token has no
// ceiling, so it holds the person's own letters, and refuseToken keeps
// their credentials out of its reach.

const (
	// loginKind is the start kind of a login.
	loginKind = "login"
	// loginOp is the op a claimed login start files for its person to
	// approve. It runs only from that request.
	loginOp = "login.token.new"
	// loginLabelMax is the longest label a machine may give itself.
	loginLabelMax = 64
)

// loginScopes are what a login token opens: the API and sync, marked as a
// login so the browser-only acts are kept from it.
var loginScopes = []string{oltp.ScopeAPI, oltp.ScopeSync, oltp.ScopeLogin}

// validLoginLabel says label is one a login start may carry.
func validLoginLabel(label string) bool {
	return len(label) <= loginLabelMax && oltp.ValidLoginLabel(label)
}

type loginTokenIn struct {
	// Label names the machine; it is the token's name on the list.
	Label string `json:"label" validate:"required,max=64"`
	// Repos limits the token to these repositories, by key; none is
	// every repository the person reaches.
	Repos []string `json:"repos,omitempty" validate:"max=10"`
	// Address is the network the start came from, written by the claim so
	// the approving page can say it again; the op ignores it.
	Address string `json:"address,omitempty" validate:"max=64"`
}

type loginTokenOut struct {
	Account string     `json:"account"`
	Label   string     `json:"label"`
	Token   meTokenRow `json:"token"`
	// Value is the token, readable once, to the holder of the pickup key.
	Value string `json:"value" secret:"once"`
}

// loginSentence is what approving a login does, in words, drawn from the
// same record that sets the token and the same table that refuses it.
func loginSentence(label, account string) string {
	return fmt.Sprintf("This machine (%s) gets a token that acts as you, %s: it can push, open and land landings, and do anything you can on the forge except %s. Revoke it any time on your tokens list.", label, account, hardStopWords())
}

// LoginSentence is loginSentence for the claim page, which says what
// approving will do before there is a request to read it from.
func LoginSentence(label, account string) string { return loginSentence(label, account) }

// loginSummary is the line a login request's row and inbox read.
func loginSummary(label string) string {
	return "Log in " + label + " as you"
}

// loginInOf reads an asked input, a value or a pointer, as a login's.
func loginInOf(in any) loginTokenIn {
	switch v := in.(type) {
	case loginTokenIn:
		return v
	case *loginTokenIn:
		return *v
	}
	return loginTokenIn{}
}

// loginRepos is the repositories a claim limits a login to: none is no
// limit, and at most setupMaxRepos.
func loginRepos(in setupClaimIn) ([]string, error) {
	var src []string
	if in.Repos != "" && len(in.Repositories) > 0 {
		return nil, fmt.Errorf("name the repositories in repos or in repositories, not both: %w", ops.ErrInvalid)
	}
	src = in.Repositories
	if in.Repos != "" {
		src = splitList(in.Repos)
	}
	if len(src) > setupMaxRepos {
		return nil, fmt.Errorf("a login is limited to at most %d repositories, or to none: %w", setupMaxRepos, ops.ErrInvalid)
	}
	return src, nil
}

// loginChoices are the repositories a person may limit a login to: the
// ones they can reach, by name regardless of case.
func (d Deps) loginChoices(who string) []setupRepoChoice {
	octx := ops.WithUser(context.Background(), who)
	var repos []setupRepoChoice
	for _, name := range d.Repos.Names() {
		if d.companionParent(name) != "" || !d.listable(octx, name) {
			continue
		}
		if _, err := d.repoFor(octx, name); err != nil {
			continue
		}
		h, ns, _ := d.repoIdentity(name)
		c := setupRepoChoice{Name: name, Handle: h, Namespace: ns}
		if d.Visibility != nil {
			c.Visibility = d.Visibility(name)
		}
		repos = append(repos, c)
	}
	sortChoices(repos)
	return repos
}

// fileLogin is the claim of a login start: it files the request for the
// claiming person, who must still approve it. Nothing is minted here.
func (d Deps) fileLogin(ctx context.Context, r *ops.Registry, who string, st oltp.SetupStart, in setupClaimIn, now time.Time) (SignOffRequest, bool, error) {
	if in.Name != "" || in.NewRepo != "" || in.Namespace != "" || in.Role != "" {
		return SignOffRequest{}, false, fmt.Errorf("a login takes no name, role or new repository; only the repositories it may be limited to: %w", ops.ErrInvalid)
	}
	picks, err := loginRepos(in)
	if err != nil {
		return SignOffRequest{}, false, err
	}
	keys, err := d.loginKeys(ctx, picks)
	if err != nil {
		return SignOffRequest{}, false, err
	}
	desc, ok := r.Lookup(loginOp)
	if !ok {
		return SignOffRequest{}, false, fmt.Errorf("no operation %q: %w", loginOp, ops.ErrInvalid)
	}
	if err := pickupAllowedFor(desc); err != nil {
		return SignOffRequest{}, false, err
	}
	return d.fileClaimed(ctx, who, st, in.Code, now, loginOp, loginTokenIn{Label: st.Name, Repos: keys, Address: st.Addr}, loginSummary(st.Name))
}

// loginViewOf is the page's account of a login request, nil for any
// other op. Every line is read from the stored input.
func (d Deps) loginViewOf(s SignOffRequest) *SetupView {
	if s.Op != loginOp {
		return nil
	}
	var in loginTokenIn
	if json.Unmarshal([]byte(s.Input), &in) != nil {
		return nil
	}
	v := &SetupView{Kind: loginKind, Label: in.Label, Account: s.Owner, Agent: in.Label, Gives: loginSentence(in.Label, s.Owner),
		Address: in.Address, Repos: orEmpty(in.Repos), Scopes: loginScopes, TokenRepos: orEmpty(in.Repos), Pickup: s.Pickup}
	var done loginTokenOut
	if s.Result != "" && json.Unmarshal([]byte(s.Result), &done) == nil && done.Account != "" {
		v.Done, v.Token = true, done.Token.Name
		v.Scopes, v.TokenRepos, v.Ceiling = done.Token.Scopes, orEmpty(done.Token.Repos), done.Token.Ceiling
	}
	return v
}

// loginKeys is the repositories a login is limited to, as their keys, each
// one the person reads and none on a hold.
func (d Deps) loginKeys(ctx context.Context, names []string) ([]string, error) {
	keys, err := d.repoKeys(ctx, names)
	if err != nil {
		return nil, err
	}
	for _, key := range keys {
		if err := d.refuseHeldRepo(ctx, key); err != nil {
			return nil, err
		}
	}
	return keys, nil
}

func registerLogin(r *ops.Registry, d Deps) error {
	return ops.Register(r, ops.Op[loginTokenIn, loginTokenOut]{
		Name:   loginOp,
		Writes: func(in loginTokenIn) []string { return d.canonAll(in.Repos) },
		Doc: "Mint a token on this person's own account for a machine that logged in with `quarry login` (RFC 0030). " +
			"Never run directly: a client with no credential starts a setup of kind login and shows a short code, the person claims it at /setup, and approving that request runs this as them. " +
			"The token acts as the person, not as an agent: it makes no account and grants nothing, carries no ceiling, so it holds the person's own letters, and holds api and sync scope. `repos` limits it to named repositories; without it every repository the person reaches. " +
			"It has no fixed date and lapses after 90 days unused, and is named by the machine's label. It cannot manage the person's credentials (refuseToken applies to it as to any token) or answer a sign-off. " +
			"The value is the secret half, released once to the holder of the pickup key, and revoked if nobody collects it within 24 hours. An agent cannot ask for it.",
		Kind:  ops.Command,
		Auth:  ops.Token,
		Route: "POST /api/v1/login/token",
		Run: func(ctx context.Context, in loginTokenIn) (loginTokenOut, error) {
			if err := refuseToken(ctx, loginOp); err != nil {
				return loginTokenOut{}, err
			}
			ask, asked := signOffAskOf(ctx)
			if !asked || !isClientAsker(ask.agent) {
				return loginTokenOut{}, fmt.Errorf("%s runs only when a person approves the request their claim of a client's start filed: %w", loginOp, ops.ErrForbidden)
			}
			who := ops.User(ctx)
			if !validLoginLabel(in.Label) {
				return loginTokenOut{}, fmt.Errorf("the label is not one a login may carry: %w", ops.ErrInvalid)
			}
			if !d.SecretBox.Ready() {
				return loginTokenOut{}, fmt.Errorf("this forge has no secret key, so it cannot hold a credential for collection; nothing was made: %w", ops.ErrUnavailable)
			}
			as, err := d.agents()
			if err != nil {
				return loginTokenOut{}, err
			}
			repos, err := d.loginKeys(ctx, in.Repos)
			if err != nil {
				return loginTokenOut{}, err
			}
			value, tok, err := as.MintToken(who, oltp.TokenSpec{Name: in.Label, Scopes: loginScopes, Repos: repos})
			if err != nil {
				return loginTokenOut{}, refusalAsInvalid(err)
			}
			return loginTokenOut{Account: who, Label: in.Label, Token: tokenRows([]oltp.Token{tok}, time.Now())[0], Value: value}, nil
		},
	})
}

// confirmLogin is the check a login from another network than its approver's
// needs, whichever surface approves it: the machine's label, typed. A request
// whose network is unknown to either side is held to it too.
func confirmLogin(ctx context.Context, s SignOffRequest, typed string) error {
	if s.Op != loginOp {
		return nil
	}
	var in loginTokenIn
	if json.Unmarshal([]byte(s.Input), &in) != nil {
		return nil
	}
	here := ops.AddrOf(ctx)
	if here != "" && in.Address != "" && oltp.AddrGroup(here) == in.Address {
		return nil
	}
	if strings.TrimSpace(typed) != in.Label {
		return fmt.Errorf("this machine is on another network than you are: type its name, %s, to approve it: %w", in.Label, ops.ErrInvalid)
	}
	return nil
}