package pickupclient
import (
"bytes"
"context"
"encoding/base64"
"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.
type Record struct {
Account string `json:"account"`
Token string `json:"token,omitempty"`
}
// Store keeps a login by host; Put says where it went.
type Store interface {
Put(host string, r Record) (where string, err error)
Get(host string) (Record, error)
}
// Keychain is the OS secret store, holding the token alone.
type Keychain interface {
Put(host, account, value string) error
Get(host string) (string, error)
}
// 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
}
func hostFile(host string) string {
return strings.NewReplacer(":", "_", "/", "_", "\\", "_").Replace(host) + ".json"
}
func (s *dirStore) Put(host string, r Record) (string, error) {
where := ""
token := r.Token
if s.Keychain != nil && s.Keychain.Put(host, r.Account, token) == nil {
r.Token = ""
where = "in the login keychain"
}
if err := os.MkdirAll(s.Dir, 0o700); err != nil {
return "", err
}
b, _ := json.Marshal(r)
path := filepath.Join(s.Dir, hostFile(host))
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return "", err
}
if err := os.Rename(tmp, path); err != nil {
os.Remove(tmp)
return "", err
}
if where == "" {
where = "in " + path + " (private to you)"
}
return where, nil
}
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 {
return Record{}, ErrNoLogin
}
if r.Token == "" && s.Keychain != nil {
r.Token, _ = s.Keychain.Get(host)
}
if r.Token == "" {
return Record{}, ErrNoLogin
}
return r, nil
}
// macKeychain uses security(1). The value goes in on the interactive
// mode's stdin, never on a command line or in the environment.
type macKeychain struct{}
func (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")
}
}
line := fmt.Sprintf("add-generic-password -U -s \"quarry:%s\" -a \"%s\" -w \"%s\"\n", host, account, value)
cmd := exec.Command("security", "-i")
cmd.Stdin = strings.NewReader(line)
var out bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &out
if err := cmd.Run(); err != nil {
return err
}
if strings.Contains(out.String(), "security: ") {
return errors.New("the keychain refused it")
}
return nil
}
func (macKeychain) Get(host string) (string, error) {
out, err := exec.Command("security", "find-generic-password", "-s", "quarry:"+host, "-w").Output()
return strings.TrimSpace(string(out)), err
}
func defaultStore() Store {
dir := os.Getenv("XDG_CONFIG_HOME")
if dir == "" {
if h, err := os.UserHomeDir(); err == nil {
dir = filepath.Join(h, ".config")
}
}
s := &dirStore{Dir: filepath.Join(dir, "quarry")}
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.Keys == nil {
e.Keys = defaultStore()
}
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
}
}
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 login [URL] [--label NAME]
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 ` + defaultForge + `)
--label what to call this machine (default: HOSTNAME, DIRECTORY)
Exit: 0 signed in, 1 refused, 2 usage, 3 code expired or timed out.
Example:
quarry login
`
const whoamiHelp = `usage: quarry whoami [URL]
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 ` + defaultForge + `)
Exit: 0 signed in, 1 not signed in or the token no longer works, 2 usage.
Example:
quarry whoami
`
// forgeOf is the origin a verb works against.
func forgeOf(raw string) (*url.URL, error) {
if raw == "" {
raw = defaultForge
}
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()
fail := func(code int, format string, a ...any) int {
fmt.Fprintf(e.Stderr, "quarry login: "+format+"\n", a...)
return code
}
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 := forgeOf(rawURL)
if err != nil {
return fail(2, "%v", err)
}
lab := *label
if lab == "" {
host, _ := e.Hostname()
wd, _ := e.Getwd()
lab = cleanLabel(strings.Join(nonEmpty(host, filepath.Base(wd)), ", "))
} 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", 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
}
mins := int((deadline.Sub(e.Now()) + 30*time.Second) / time.Minute)
fmt.Fprintf(e.Stdout, "Open %s and type %s (%d minutes)\n", st.Link, st.Code, mins)
fmt.Fprintln(e.Stdout, "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; start again with quarry login")
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; start again with quarry login")
}
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 {
fmt.Fprintf(e.Stderr, "quarry login: "+format+"\n", a...)
fmt.Fprintf(e.Stderr, "quarry login: a live token was released and saved nowhere; revoke it on your tokens list (request %s, token %s)\n", orUnknown(ans.Request), orUnknown(ans.Result.Token.ID))
return 1
}
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")
}
where, err := e.Keys.Put(base.Host, Record{Account: account, Token: token})
if err != nil {
return lost("the token could not be stored: %v", err)
}
if merr != nil || me.Token == nil {
fmt.Fprintf(e.Stdout, "Signed in to %s as %s, token kept %s\n", base.Host, account, where)
fmt.Fprintf(e.Stdout, " revoke %s/me#push\n", base.Scheme+"://"+base.Host)
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, me.Name)
if t := me.Token; t != nil {
fmt.Fprintf(e.Stdout, " may %s\n", t.May)
fmt.Fprintf(e.Stdout, " may not %s\n", strings.Join(t.MayNot, "; "))
fmt.Fprintf(e.Stdout, " token %q", t.Label)
if where != "" {
fmt.Fprintf(e.Stdout, ", kept %s", where)
}
fmt.Fprintln(e.Stdout)
}
fmt.Fprintf(e.Stdout, " revoke %s/me#push\n", base.Scheme+"://"+base.Host)
}
type meAnswer struct {
Name string `json:"name"`
Token *struct {
Label string `json:"label"`
May string `json:"may"`
MayNot []string `json:"mayNot"`
} `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, fmt.Errorf("the forge answered %d", resp.StatusCode)
}
err = json.NewDecoder(io.LimitReader(resp.Body, pickupBodyMax)).Decode(&me)
return me, err
}
// Whoami exits 0 when the stored token works, 1 when there is none or
// the forge no longer takes it, 2 on usage.
func Whoami(ctx context.Context, args []string, e *Env) int {
e.fillLogin()
fail := func(code int, format string, a ...any) int {
fmt.Fprintf(e.Stderr, "quarry whoami: "+format+"\n", a...)
return code
}
for _, a := range args {
if a == "-h" || a == "--help" || a == "-help" {
fmt.Fprint(e.Stdout, whoamiHelp)
return 0
}
}
if len(args) > 1 || len(args) == 1 && strings.HasPrefix(args[0], "-") {
return fail(2, "usage: quarry whoami [URL] (quarry whoami --help)")
}
raw := ""
if len(args) == 1 {
raw = args[0]
}
base, err := forgeOf(raw)
if err != nil {
return fail(2, "%v", err)
}
rec, err := e.Keys.Get(base.Host)
if err != nil {
return fail(1, "no token is stored for %s; run quarry login", base.Host)
}
me, err := e.readMe(ctx, base, rec.Token)
if err != nil {
return fail(1, "the stored token did not work (%v); run quarry login", err)
}
fmt.Fprintf(e.Stdout, "Signed in to %s as %s\n", base.Host, me.Name)
if me.Token != nil {
fmt.Fprintf(e.Stdout, " token %q\n", 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, r.Repo, r.Role)
}
fmt.Fprintf(e.Stdout, " revoke %s/me#push\n", base.Scheme+"://"+base.Host)
return 0
}
func nonEmpty(s ...string) []string {
var out []string
for _, x := range s {
if x != "" && x != "." && x != "/" {
out = append(out, x)
}
}
return out
}