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"`
}
// 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)
}
// 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)
}
// 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
}
// 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) 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
}
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", 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(e.Stdout, "Open %s and type %s (%d minutes)\n", show(link), show(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(hostKey(base), Record{Account: account, Token: token})
if err != nil && where != "" {
fmt.Fprintf(e.Stderr, "quarry login: the token is in the login keychain but its record could not be written (%v); run quarry login again\n", err)
return 1
}
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, show(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, 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)
}
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(hostKey(base))
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, 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))
}
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
}
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)
}