Skip to content
quarry Artifact [639e9aa622]
Login

Artifact [639e9aa622]

Artifact 639e9aa622bddc384507ade3c727a48bd189283a8dde5845b548aa81ad66b081:


package pickupclient

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
)

// The conventions every verb of the client keeps (RFC 0033): with
// --json (or -F json) stdout is exactly one object with an ok field, and
// a refusal adds code, error and next; the exit status is 0 done, 1
// refused, 2 usage, 3 still waiting, 4 not logged in.

const (
	exitNoLogin = 4
	noLoginCode = "no_login"
	loginCmd    = "quarry auth login"
	credsHelp   = "/llms.txt#credentials"
	tokenEnvVar = "QUARRY_TOKEN"
	envHostVar  = "QUARRY_HOST"
)

// stripJSON removes --json, -F json and -F=json from args and says
// whether any was there.
func stripJSON(args []string) ([]string, bool) {
	var rest []string
	found := false
	for i := 0; i < len(args); i++ {
		switch a := args[i]; {
		case a == "--json" || a == "-F=json":
			found = true
		case a == "-F" && i+1 < len(args) && args[i+1] == "json":
			found, i = true, i+1
		default:
			rest = append(rest, a)
		}
	}
	return rest, found
}

type nextJSON struct {
	Say  string `json:"say"`
	Open string `json:"open,omitempty"`
	Cmd  string `json:"cmd,omitempty"`
	Ask  bool   `json:"ask"`
	Help string `json:"help,omitempty"`
}

type refusalJSON struct {
	OK    bool      `json:"ok"`
	Code  string    `json:"code"`
	Error string    `json:"error"`
	Live  bool      `json:"live,omitempty"`
	Next  *nextJSON `json:"next,omitempty"`
}

type tokenJSON struct {
	Label  string   `json:"label"`
	May    string   `json:"may"`
	MayNot []string `json:"mayNot"`
	Revoke string   `json:"revoke,omitempty"`
}

type repoJSON struct {
	Repo string `json:"repo"`
	Role string `json:"role"`
}

type meResultJSON struct {
	OK      bool        `json:"ok"`
	Host    string      `json:"host"`
	Account string      `json:"account"`
	Source  string      `json:"source,omitempty"`
	Kept    string      `json:"kept,omitempty"`
	Token   *tokenJSON  `json:"token,omitempty"`
	Repos   *[]repoJSON `json:"repos,omitempty"`
}

// voice is how one verb speaks: to a person on stderr, or to a program
// as one object on stdout.
type voice struct {
	e    *Env
	verb string
	json bool
}

func (v voice) print(obj any) {
	b, _ := json.Marshal(obj)
	fmt.Fprintln(v.e.Stdout, string(b))
}

// refuse says why, and what to do next, and returns the exit status.
func (v voice) refuse(exit int, code, msg string, live bool, next *nextJSON) int {
	if v.json {
		v.print(refusalJSON{Code: code, Error: msg, Live: live, Next: next})
		return exit
	}
	fmt.Fprintf(v.e.Stderr, "%s: %s\n", v.verb, msg)
	if next != nil {
		if next.Say != "" {
			fmt.Fprintf(v.e.Stderr, "  %s\n", next.Say)
		}
		if next.Open != "" {
			fmt.Fprintf(v.e.Stderr, "  open   %s\n", next.Open)
		}
		if next.Cmd != "" {
			fmt.Fprintf(v.e.Stderr, "  run    %s\n", next.Cmd)
		}
	}
	return exit
}

func (v voice) noLogin(base *url.URL) int {
	return v.refuse(exitNoLogin, noLoginCode, "this machine is not logged in to "+base.Host, false,
		&nextJSON{Say: "Log this machine in; one approval, in a browser.", Cmd: loginCmd, Help: credsHelp})
}

// errTokenDead is the forge's no_login answer to a call on the token.
var errTokenDead = errors.New("the forge does not know this token")

// statusError is a forge answer that was not 200.
type statusError int

func (s statusError) Error() string { return fmt.Sprintf("the forge answered %d", int(s)) }

// token is the credential a verb presents for base: QUARRY_TOKEN when
// the environment has one and base is the host it is for (the default
// host, or QUARRY_HOST when that is set), else the stored login's. A
// token in the environment is never sent to another host.
func (e *Env) token(base *url.URL) (Record, bool) {
	if t := strings.TrimSpace(e.Getenv(tokenEnvVar)); t != "" && e.envHostIs(base) {
		return Record{Token: t, Source: "env"}, true
	}
	rec, err := e.Keys.Get(hostKey(base))
	return rec, err == nil
}

// envHostIs says QUARRY_TOKEN is for base.
func (e *Env) envHostIs(base *url.URL) bool {
	raw := strings.TrimSpace(e.Getenv(envHostVar))
	if raw == "" {
		raw = DefaultHost(e.ConfigDir)
	}
	u, err := forgeOf(raw)
	return err == nil && hostKey(u) == hostKey(base)
}

// revokeURL is the page the forge says ends this token, when it says
// one on its own origin. The client makes up no address.
func revokeURL(base *url.URL, me meAnswer) string {
	if me.Token == nil || me.Token.Revoke == "" {
		return ""
	}
	u, err := base.Parse(me.Token.Revoke)
	if err != nil || !sameOrigin(u, base) {
		return ""
	}
	return u.String()
}

func tokenOut(base *url.URL, me meAnswer) *tokenJSON {
	if me.Token == nil {
		return nil
	}
	mayNot := me.Token.MayNot
	if mayNot == nil {
		mayNot = []string{}
	}
	return &tokenJSON{Label: show(me.Token.Label), May: show(me.Token.May), MayNot: showAll(mayNot), Revoke: show(revokeURL(base, me))}
}

func showAll(in []string) []string {
	out := make([]string, len(in))
	for i, s := range in {
		out[i] = show(s)
	}
	return out
}

const logoutHelp = `usage: quarry auth logout [URL] [--json]

End this machine's token on the forge, then remove it from the keychain
and the file. A token that cannot be ended is not forgotten: if the forge
cannot be reached or does not say yes, nothing is removed, the token is
reported as still live, and the page that revokes it is named.

  URL      the forge (default: the one the installer recorded, else ` + defaultForge + `)
  --json   one JSON object on stdout

Exit: 0 ended and removed, 1 not ended (still live) or not removed,
2 usage, 4 not logged in.

Example:
  quarry auth logout
`

// Logout ends the stored token on the forge and then forgets it. It
// never forgets a token it did not see ended or refused.
func Logout(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	args, asJSON := stripJSON(args)
	v := voice{e, e.named("auth logout"), asJSON}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextJSON{Say: "See quarry auth logout --help.", Cmd: "quarry auth logout --help"})
	}
	raw := ""
	for _, a := range args {
		switch {
		case a == "-h" || a == "--help" || a == "-help":
			fmt.Fprint(e.Stdout, logoutHelp)
			return 0
		case strings.HasPrefix(a, "-"):
			return usage("usage: quarry auth logout [URL] [--json]")
		case raw != "":
			return usage("one URL only")
		default:
			raw = a
		}
	}
	base, err := e.forgeOf(raw)
	if err != nil {
		return usage(show(err.Error()))
	}
	host := hostKey(base)
	rec, err := e.Keys.Get(host)
	if err != nil {
		if e.envHostIs(base) && strings.TrimSpace(e.Getenv(tokenEnvVar)) != "" {
			return v.refuse(1, "env_token", "the token for "+base.Host+" is the one in "+tokenEnvVar+", which logout did not store and cannot end", false,
				&nextJSON{Say: "Unset " + tokenEnvVar + " in this shell, and end the token where it was made.", Help: credsHelp})
		}
		return v.noLogin(base)
	}
	revoke := base.ResolveReference(&url.URL{Path: "/me"})
	if u, err := base.Parse(rec.Revoke); err == nil && rec.Revoke != "" && sameOrigin(u, base) {
		revoke = u
	}
	stillLive := func(code, why string) int {
		return v.refuse(1, code, "the token is still live on "+base.Host+" and nothing was removed here: "+why, true,
			&nextJSON{Say: "End it signed in at a browser, then run this again.", Open: revoke.String(), Cmd: "quarry auth logout", Help: credsHelp})
	}
	ended, err := e.endToken(ctx, base, rec.Token)
	var se statusError
	switch {
	case err == nil:
	case errors.Is(err, errTokenDead):
		// The forge says it does not know this token: nothing is live.
	case errors.As(err, &se):
		return stillLive("refused", show(err.Error()))
	default:
		return stillLive("unreachable", "the forge could not be reached: "+show(err.Error()))
	}
	if err := e.Keys.Delete(host); err != nil {
		msg := "the local copy could not be removed: " + show(err.Error())
		if ended {
			msg = "the token was ended on " + base.Host + ", but " + msg
		}
		return v.refuse(1, "not_removed", msg, false, &nextJSON{Say: "Run this again to remove it.", Cmd: "quarry auth logout"})
	}
	if asJSON {
		v.print(struct {
			OK      bool   `json:"ok"`
			Host    string `json:"host"`
			Account string `json:"account"`
			Ended   bool   `json:"ended"`
		}{true, base.Host, show(rec.Account), ended})
		return 0
	}
	if ended {
		fmt.Fprintf(e.Stdout, "Ended this machine's token on %s and removed it from this machine.\n", base.Host)
	} else {
		fmt.Fprintf(e.Stdout, "%s no longer takes this machine's token; removed it from this machine.\n", base.Host)
	}
	return 0
}

// endToken asks the forge to end the token it is presented on. A nil
// error is a yes; statusError is any other answer.
func (e *Env) endToken(ctx context.Context, base *url.URL, token string) (bool, error) {
	req, err := http.NewRequestWithContext(ctx, "POST", base.ResolveReference(&url.URL{Path: "/api/v1/me/token/end"}).String(), strings.NewReader("{}"))
	if err != nil {
		return false, err
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Content-Type", "application/json")
	resp, err := e.Client.Do(req)
	if err != nil {
		var ue *url.Error
		if errors.As(err, &ue) {
			err = ue.Err
		}
		return false, err
	}
	raw, _ := io.ReadAll(io.LimitReader(resp.Body, pickupBodyMax))
	resp.Body.Close()
	if resp.StatusCode == http.StatusUnauthorized {
		// Only the forge's own no_login says the token is dead; a 401 from
		// a proxy or an access gate says nothing about it.
		var b struct {
			Code string `json:"code"`
		}
		if json.Unmarshal(raw, &b) == nil && b.Code == noLoginCode {
			return false, errTokenDead
		}
	}
	if resp.StatusCode != http.StatusOK {
		return false, statusError(resp.StatusCode)
	}
	return true, nil
}