package pickupclient
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
)
// quarry login and quarry whoami: log a machine in as the person (RFC
// 0032). The client makes the pickup key, starts a login, shows the link
// and code, waits for the one approval, and keeps the token it collects
// where only this user reads it.
const (
defaultForge = "https://zeitforge.app"
loginKind = "login"
labelMax = 64
)
var (
// ErrNoLogin is a host with no stored token.
ErrNoLogin = errors.New("no token is stored for this host")
labelOK = regexp.MustCompile(`^[A-Za-z0-9 .,_-]{1,64}$`)
labelBad = regexp.MustCompile(`[^A-Za-z0-9 .,_-]+`)
// keychainSafe is what may be written on a `security -i` command line
// inside double quotes; anything else goes to the file store.
keychainSafe = regexp.MustCompile(`^[A-Za-z0-9._~:+/=@,-]+$`)
)
// Record is what is kept for a host. Token is empty in the file when the
// keychain holds it. Host is the normalised host the record belongs to.
type Record struct {
Host string `json:"host"`
Account string `json:"account"`
Token string `json:"token,omitempty"`
// Revoke is the page the forge named, at login, that ends this token;
// kept so that a logout the forge cannot hear can still point at it.
Revoke string `json:"revoke,omitempty"`
}
// Store keeps a login by host key (see hostKey); Put says where it went.
// A host holds one login: a second replaces the first.
type Store interface {
Put(host string, r Record) (where string, err error)
Get(host string) (Record, error)
// Delete forgets the host's login from every place Put kept it; an
// error means some copy may remain.
Delete(host string) error
}
// Keychain is the OS secret store, holding the token alone. Put leaves
// the host with one item, for account; Get reads the item for account.
type Keychain interface {
Put(host, account, value string) error
Get(host, account string) (string, error)
// Delete removes the host's item; Get afterwards says whether it went.
Delete(host, account string) error
}
// hostKey names a forge's host the one way: lower case, with the
// scheme's default port dropped.
func hostKey(u *url.URL) string {
h := strings.ToLower(u.Hostname())
if strings.Contains(h, ":") {
h = "[" + h + "]"
}
port := u.Port()
if port == "" || (u.Scheme == "https" && port == "443") || (u.Scheme == "http" && port == "80") {
return h
}
return h + ":" + port
}
// dirStore keeps a small JSON record per host under Dir (0600), and the
// token in Keychain when there is one that works, else in the record.
type dirStore struct {
Dir string
Keychain Keychain
}
// hostFile is injective: two hosts never share a file.
func hostFile(host string) string {
return hex.EncodeToString([]byte(host)) + ".json"
}
func (s *dirStore) Put(host string, r Record) (string, error) {
where := ""
token := r.Token
r.Host = host
if s.Keychain != nil && s.Keychain.Put(host, r.Account, token) == nil {
r.Token = ""
where = "in the login keychain"
}
path := filepath.Join(s.Dir, hostFile(host))
if err := writePrivate(s.Dir, path, r); err != nil {
return where, err
}
if where == "" {
where = "in " + path + " (private to you)"
}
return where, nil
}
// writePrivate writes r to path through a fresh 0600 temp file in dir,
// which is made 0700 and tightened if it was looser.
func writePrivate(dir, path string, r Record) error {
if err := os.MkdirAll(dir, 0o700); err != nil {
return err
}
if err := os.Chmod(dir, 0o700); err != nil {
return err
}
f, err := os.CreateTemp(dir, ".login-*")
if err != nil {
return err
}
b, _ := json.Marshal(r)
_, werr := f.Write(b)
if serr := f.Sync(); werr == nil {
werr = serr
}
if cerr := f.Close(); werr == nil {
werr = cerr
}
if werr == nil {
werr = os.Rename(f.Name(), path)
}
if werr != nil {
os.Remove(f.Name())
}
return werr
}
func (s *dirStore) Get(host string) (Record, error) {
b, err := os.ReadFile(filepath.Join(s.Dir, hostFile(host)))
if err != nil {
return Record{}, ErrNoLogin
}
var r Record
if json.Unmarshal(b, &r) != nil || r.Host != host {
return Record{}, ErrNoLogin
}
if r.Token == "" && s.Keychain != nil {
r.Token, _ = s.Keychain.Get(host, r.Account)
}
if r.Token == "" {
return Record{}, ErrNoLogin
}
return r, nil
}
// Delete forgets the host's login: the keychain item, which must be
// gone when this returns nil, and then the record file.
func (s *dirStore) Delete(host string) error {
path := filepath.Join(s.Dir, hostFile(host))
if s.Keychain != nil {
if b, err := os.ReadFile(path); err == nil {
var r Record
if json.Unmarshal(b, &r) == nil && r.Account != "" {
s.Keychain.Delete(host, r.Account)
if v, gerr := s.Keychain.Get(host, r.Account); gerr == nil && v != "" {
return errors.New("the login keychain still holds the token")
}
}
}
}
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return err
}
return nil
}
// macKeychain uses security(1). The value goes in on the interactive
// mode's stdin, never on a command line or in the environment. sec runs
// it (nil: the real one) and returns its output.
type macKeychain struct {
sec func(stdin string, args ...string) (string, error)
}
func (m macKeychain) run(stdin string, args ...string) (string, error) {
if m.sec != nil {
return m.sec(stdin, args...)
}
cmd := exec.Command("security", args...)
cmd.Stdin = strings.NewReader(stdin)
var out bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &out
err := cmd.Run()
return out.String(), err
}
func (m macKeychain) Put(host, account, value string) error {
for _, s := range []string{host, account, value} {
if !keychainSafe.MatchString(s) {
return errors.New("not storable in the keychain")
}
}
// One host, one login: whatever else is held for it goes first.
for i := 0; i < 8; i++ {
if _, err := m.run("", "delete-generic-password", "-s", "quarry:"+host); err != nil {
break
}
}
line := fmt.Sprintf("add-generic-password -U -s \"quarry:%s\" -a \"%s\" -w \"%s\"\n", host, account, value)
out, err := m.run(line, "-i")
if err != nil {
return err
}
if strings.Contains(out, "security: ") {
return errors.New("the keychain refused it")
}
return nil
}
func (m macKeychain) Delete(host, account string) error {
for i := 0; i < 8; i++ {
if _, err := m.run("", "delete-generic-password", "-s", "quarry:"+host); err != nil {
break
}
}
return nil
}
func (m macKeychain) Get(host, account string) (string, error) {
if !keychainSafe.MatchString(account) {
return "", errors.New("no such item")
}
out, err := m.run("", "find-generic-password", "-s", "quarry:"+host, "-a", account, "-w")
return strings.TrimSpace(out), err
}
// ConfigDir is where the client keeps its settings and logins.
func ConfigDir() string {
dir := os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
if h, err := os.UserHomeDir(); err == nil {
dir = filepath.Join(h, ".config")
}
}
return filepath.Join(dir, "quarry")
}
// DefaultHost is the forge a verb works against when none is named: the
// one the installer recorded in dir's config.json, else the default
// forge. A record that is not a plain forge address is ignored.
func DefaultHost(dir string) string {
b, err := os.ReadFile(filepath.Join(dir, "config.json"))
if err != nil {
return defaultForge
}
var c struct {
Host string `json:"host"`
}
if json.Unmarshal(b, &c) != nil {
return defaultForge
}
if _, err := forgeOf(c.Host); err != nil || c.Host == "" {
return defaultForge
}
return c.Host
}
func defaultStore(dir string) Store {
s := &dirStore{Dir: dir}
if runtime.GOOS == "darwin" {
s.Keychain = macKeychain{}
}
return s
}
// cleanLabel keeps the characters the forge accepts, at most 64.
func cleanLabel(s string) string {
s = strings.TrimSpace(labelBad.ReplaceAllString(s, ""))
if len(s) > labelMax {
s = strings.TrimSpace(s[:labelMax])
}
if s == "" {
return "machine"
}
return s
}
func (e *Env) fillLogin() {
e.fill()
if e.ConfigDir == "" {
e.ConfigDir = ConfigDir()
}
if e.Keys == nil {
e.Keys = defaultStore(e.ConfigDir)
}
if e.Poll == 0 {
e.Poll = 12 * time.Second
}
if e.Hostname == nil {
e.Hostname = os.Hostname
}
if e.Getwd == nil {
e.Getwd = os.Getwd
}
if e.Getenv == nil {
e.Getenv = os.Getenv
}
}
func LoginMain(args []string) int {
return Login(context.Background(), args, &Env{Stdout: os.Stdout, Stderr: os.Stderr})
}
func WhoamiMain(args []string) int {
return Whoami(context.Background(), args, &Env{Stdout: os.Stdout, Stderr: os.Stderr})
}
const loginHelp = `usage: quarry auth login [URL] [--label NAME] [--json]
Log this machine in as you. Prints a link and a code, waits while you
approve on that page, then keeps the token it is given in the OS keychain
(a private file where there is none). The token is never printed.
URL the forge (default: the one the installer recorded, else ` + defaultForge + `)
--label what to call this machine (default: this machine's name)
--json one JSON object on stdout (the link and code go to stderr)
Exit: 0 signed in, 1 refused, 2 usage, 3 code expired or timed out.
Example:
quarry auth login
`
const whoamiHelp = `usage: quarry auth status [URL] [--json]
Show who this machine is signed in as on a forge, the token's label, the
repositories it reaches and where to revoke it. Prints no token.
URL the forge (default: the one the installer recorded, else ` + defaultForge + `)
--json one JSON object on stdout
Uses QUARRY_TOKEN when it is set, else the stored login.
Exit: 0 signed in, 1 the forge refuses the token, 2 usage, 4 not logged in.
Example:
quarry auth status
`
// forgeOf is the origin a verb works against; with none named, the
// installer's recorded one.
func (e *Env) forgeOf(raw string) (*url.URL, error) {
if raw == "" {
raw = DefaultHost(e.ConfigDir)
}
return forgeOf(raw)
}
func forgeOf(raw string) (*url.URL, error) {
u, _, err := pickupURL(raw)
if err != nil {
return nil, err
}
if p := strings.Trim(u.Path, "/"); p != "" {
return nil, errors.New("give the forge's address alone, with no path")
}
return u, nil
}
// Exit statuses: 0 done, 1 refused or denied, 2 usage, 3 the code
// expired or the wait ended.
func Login(ctx context.Context, args []string, e *Env) int {
e.fillLogin()
args, asJSON := stripJSON(args)
v := voice{e, e.named("login"), asJSON}
fail := func(code int, format string, a ...any) int {
next := &nextJSON{Say: "Start again.", Cmd: loginCmd, Help: credsHelp}
ecode := "refused"
switch code {
case 2:
ecode = "usage"
next = &nextJSON{Say: "See quarry auth login --help.", Cmd: "quarry auth login --help"}
case 3:
ecode = "expired"
}
return v.refuse(code, ecode, fmt.Sprintf(format, a...), false, next)
}
progress := e.Stdout
if asJSON {
progress = e.Stderr
}
fs := flag.NewFlagSet("login", flag.ContinueOnError)
fs.SetOutput(io.Discard)
label := fs.String("label", "", "")
var rawURL string
rest := args
for {
if err := fs.Parse(rest); err != nil {
if errors.Is(err, flag.ErrHelp) {
fmt.Fprint(e.Stdout, loginHelp)
return 0
}
return fail(2, "%v (quarry login --help)", err)
}
if fs.NArg() == 0 {
break
}
if rawURL != "" {
return fail(2, "one URL only")
}
rawURL, rest = fs.Arg(0), fs.Args()[1:]
}
base, err := e.forgeOf(rawURL)
if err != nil {
return fail(2, "%v", err)
}
lab := *label
if lab == "" {
host, _ := e.Hostname()
lab = cleanLabel(host)
} else if !labelOK.MatchString(lab) || strings.TrimSpace(lab) != lab {
return fail(2, "a label is letters, digits, space, '.', ',', '-' or '_', at most %d characters", labelMax)
}
key, code, err := NewKey()
if err != nil {
return fail(1, "%v", err)
}
body, _ := json.Marshal(map[string]string{"kind": loginKind, "label": lab, "pickup": code})
startURL := base.ResolveReference(&url.URL{Path: "/api/v1/setup/start"}).String()
req, err := http.NewRequestWithContext(ctx, "POST", startURL, bytes.NewReader(body))
if err != nil {
return fail(1, "bad URL")
}
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 fail(1, "the forge could not be reached: %v", err)
}
raw, _ := io.ReadAll(io.LimitReader(resp.Body, pickupBodyMax))
resp.Body.Close()
var st struct {
Code string `json:"code"`
Link string `json:"link"`
Expires string `json:"expires"`
Error string `json:"error"`
}
json.Unmarshal(raw, &st)
if resp.StatusCode != http.StatusOK || st.Code == "" || st.Link == "" {
if st.Error != "" {
return fail(1, "the forge refused: %s", show(st.Error))
}
return fail(1, "the forge answered %d", resp.StatusCode)
}
deadline := e.Now().Add(10 * time.Minute)
if t, err := time.Parse(time.RFC3339, st.Expires); err == nil {
deadline = t
}
if limit := e.Now().Add(pickupDefaultWait); deadline.After(limit) {
deadline = limit
}
mins := int((deadline.Sub(e.Now()) + 30*time.Second) / time.Minute)
link := base.ResolveReference(&url.URL{Path: "/setup"}).String()
if lu, err := url.Parse(st.Link); err == nil && sameOrigin(lu, base) {
link = st.Link
}
fmt.Fprintf(progress, "Open %s and type %s (%d minutes)\n", show(link), show(st.Code), mins)
fmt.Fprintln(progress, "Waiting for your approval ...")
auth := "Pickup " + base64.RawURLEncoding.EncodeToString(key)
collectURL := base.ResolveReference(&url.URL{Path: "/api/v1/pickups/collect"}).String()
var ans pickupAnswer
for {
status, retry, b, err := pickupPost(ctx, e, collectURL, auth, loginKind)
if err != nil {
return fail(1, "%v", err)
}
if status == http.StatusOK {
if json.Unmarshal(b, &ans) != nil {
return fail(1, "the forge's answer was not understood")
}
break
}
var g pickupAnswer
json.Unmarshal(b, &g)
pause := e.Poll
switch {
case status == http.StatusGone:
switch g.State {
case "expired", "lapsed":
return fail(3, "the code is no longer good")
case "denied":
return fail(1, "the login was denied")
}
return fail(1, "the login cannot be collected: %s", pickupWord(g.State))
case status == http.StatusConflict:
return fail(1, "this request is not a login; nothing was collected")
case status == http.StatusNotFound, status == http.StatusAccepted, status >= 500:
// Before the code is claimed the forge knows no such pickup;
// that and a busy answer both mean wait.
case status == http.StatusTooManyRequests:
if retry > pause {
pause = retry
}
default:
return fail(1, "the forge answered %d", status)
}
if !e.Now().Add(pause).Before(deadline) {
return fail(3, "no approval before the code expired")
}
if err := e.Sleep(ctx, pause); err != nil {
return fail(1, "interrupted")
}
}
token := ans.Secret.Value
var res struct {
Account string `json:"account"`
}
b, _ := json.Marshal(ans.Result)
json.Unmarshal(b, &res)
lost := func(format string, a ...any) int {
return v.refuse(1, "refused", fmt.Sprintf(format, a...)+fmt.Sprintf("; a live token was released and saved nowhere; revoke it on your tokens list (request %s, token %s)", orUnknown(ans.Request), orUnknown(ans.Result.Token.ID)), true, nil)
}
if ans.Op != "login.token.new" || token == "" {
return lost("the answer is not a login token")
}
me, merr := e.readMe(ctx, base, token)
account := me.Name
if account == "" {
account = res.Account
}
if account == "" {
return lost("the forge did not say whose token this is")
}
rec := Record{Account: account, Token: token}
if merr == nil {
rec.Revoke = revokeURL(base, me)
}
where, err := e.Keys.Put(hostKey(base), rec)
if err != nil && where != "" {
return v.refuse(1, "refused", fmt.Sprintf("the token is in the login keychain but its record could not be written (%v); run quarry login again", err), false, nil)
}
if err != nil {
return lost("the token could not be stored: %v", err)
}
if asJSON {
out := meResultJSON{OK: true, Host: base.Host, Account: show(account), Kept: where}
if merr == nil {
out.Token = tokenOut(base, me)
}
v.print(out)
return 0
}
if merr != nil || me.Token == nil {
fmt.Fprintf(e.Stdout, "Signed in to %s as %s, token kept %s\n", base.Host, show(account), where)
return 0
}
e.printHolding(base, me, where)
return 0
}
// printHolding prints what the forge says this token holds, as given.
func (e *Env) printHolding(base *url.URL, me meAnswer, where string) {
fmt.Fprintf(e.Stdout, "Signed in to %s as %s\n", base.Host, show(me.Name))
if t := me.Token; t != nil {
fmt.Fprintf(e.Stdout, " may %s\n", show(t.May))
fmt.Fprintf(e.Stdout, " may not %s\n", show(strings.Join(t.MayNot, "; ")))
fmt.Fprintf(e.Stdout, " token %q", show(t.Label))
if where != "" {
fmt.Fprintf(e.Stdout, ", kept %s", where)
}
fmt.Fprintln(e.Stdout)
}
e.printRevoke(base, me)
}
// printRevoke prints the page the forge says ends this token, when it
// says one on its own origin. The client makes up no address.
func (e *Env) printRevoke(base *url.URL, me meAnswer) {
if u := revokeURL(base, me); u != "" {
fmt.Fprintf(e.Stdout, " revoke %s\n", show(u))
}
}
type meAnswer struct {
Name string `json:"name"`
Token *struct {
Label string `json:"label"`
May string `json:"may"`
MayNot []string `json:"mayNot"`
Revoke string `json:"revoke"`
} `json:"token"`
Repos []struct {
Repo string `json:"repo"`
Role string `json:"role"`
} `json:"repos"`
}
func (e *Env) readMe(ctx context.Context, base *url.URL, token string) (meAnswer, error) {
var me meAnswer
req, err := http.NewRequestWithContext(ctx, "GET", base.ResolveReference(&url.URL{Path: "/api/v1/me"}).String(), nil)
if err != nil {
return me, err
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := e.Client.Do(req)
if err != nil {
var ue *url.Error
if errors.As(err, &ue) {
err = ue.Err
}
return me, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return me, statusError(resp.StatusCode)
}
err = json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&me)
return me, err
}
// Whoami exits 0 when the token works, 1 when the forge no longer takes
// it, 2 on usage, 4 when there is no token.
func Whoami(ctx context.Context, args []string, e *Env) int {
e.fillLogin()
args, asJSON := stripJSON(args)
v := voice{e, e.named("whoami"), asJSON}
for _, a := range args {
if a == "-h" || a == "--help" || a == "-help" {
fmt.Fprint(e.Stdout, whoamiHelp)
return 0
}
}
usage := func(msg string) int {
return v.refuse(2, "usage", msg, false, &nextJSON{Say: "See quarry auth status --help.", Cmd: "quarry auth status --help"})
}
if len(args) > 1 || len(args) == 1 && strings.HasPrefix(args[0], "-") {
return usage("usage: quarry whoami [URL] [--json] (quarry whoami --help)")
}
raw := ""
if len(args) == 1 {
raw = args[0]
}
base, err := e.forgeOf(raw)
if err != nil {
return usage(show(err.Error()))
}
rec, ok := e.token(hostKey(base))
if !ok {
return v.noLogin(base)
}
me, err := e.readMe(ctx, base, rec.Token)
if err != nil {
code, why := "unreachable", "the forge could not be reached: "
var se statusError
if errors.As(err, &se) {
code, why = "refused", "the forge does not take the token: "
}
return v.refuse(1, code, why+show(err.Error()), false,
&nextJSON{Say: "Log this machine in again.", Cmd: loginCmd, Help: credsHelp})
}
if asJSON {
out := meResultJSON{OK: true, Host: base.Host, Account: show(me.Name), Token: tokenOut(base, me)}
repos := []repoJSON{}
for _, r := range me.Repos {
repos = append(repos, repoJSON{show(r.Repo), show(r.Role)})
}
out.Repos = &repos
v.print(out)
return 0
}
fmt.Fprintf(e.Stdout, "Signed in to %s as %s\n", base.Host, show(me.Name))
if me.Token != nil {
fmt.Fprintf(e.Stdout, " token %q\n", show(me.Token.Label))
}
if len(me.Repos) == 0 {
fmt.Fprintln(e.Stdout, " reaches no repositories")
}
for i, r := range me.Repos {
lead := " "
if i == 0 {
lead = " reaches "
}
fmt.Fprintf(e.Stdout, "%s%s (%s)\n", lead, show(r.Repo), show(r.Role))
}
e.printRevoke(base, me)
return 0
}
var terminalEscape = regexp.MustCompile(`\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b.?`)
// show makes a server string safe to print: escape sequences and control
// characters (C0, DEL, C1) are dropped, so a forge cannot write to the
// terminal.
func show(s string) string {
s = terminalEscape.ReplaceAllString(s, "")
return strings.Map(func(r rune) rune {
if r < 0x20 || r == 0x7f || (r >= 0x80 && r <= 0x9f) {
return -1
}
return r
}, s)
}