Skip to content
quarry Artifact [360b9e4a13]
Login

Artifact [360b9e4a13]

Artifact 360b9e4a1352722ab9fa98b3715982159b79c1ae9e4ff1a1c8dbf5573d33bbcf:


package pickupclient

import (
	"bytes"
	"context"
	"encoding/base64"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"time"
)

// A login that survives an absent person (RFC 0033): the pickup key and
// the start's particulars are kept in a private file next to the login
// record, so a run that was interrupted, or that left with --no-wait, is
// taken up again by the next one.

// pendingLogin is what is kept for a start that has not been collected.
// Key is the secret the forge holds only the hash of.
type pendingLogin struct {
	Host     string `json:"host"`
	Label    string `json:"label"`
	Key      string `json:"key"`
	Code     string `json:"code"`
	Link     string `json:"link"`
	Expires  string `json:"expires"`
	Interval int    `json:"interval"`
}

func pendingPath(dir, host string) string {
	return filepath.Join(dir, "pending-"+hex.EncodeToString([]byte(host))+".json")
}

func (p pendingLogin) key() []byte {
	k, err := base64.RawURLEncoding.DecodeString(p.Key)
	if err != nil || len(k) != 32 {
		return nil
	}
	return k
}

// expiry is when the start lapses unclaimed; the zero time if unknown.
func (p pendingLogin) expiry() time.Time {
	t, _ := time.Parse(time.RFC3339, p.Expires)
	return t
}

// loadPending reads the kept start for host; a missing or damaged file is
// no start.
func loadPending(dir, host string) (pendingLogin, bool) {
	b, err := os.ReadFile(pendingPath(dir, host))
	if err != nil {
		return pendingLogin{}, false
	}
	var p pendingLogin
	if json.Unmarshal(b, &p) != nil || p.Host != host || p.key() == nil || p.Code == "" {
		return pendingLogin{}, false
	}
	return p, true
}

func savePending(dir string, p pendingLogin) error {
	return writePrivate(dir, pendingPath(dir, p.Host), p)
}

func dropPending(dir, host string) {
	os.Remove(pendingPath(dir, host))
}

// startLogin asks the forge for a new login start under a new key, with
// the key and answer kept in the pending file before it returns. A
// non-nil error is what to tell the person.
func (e *Env) startLogin(ctx context.Context, base *url.URL, label string) (pendingLogin, error) {
	key, hash, err := NewKey()
	if err != nil {
		return pendingLogin{}, err
	}
	body, _ := json.Marshal(map[string]string{"kind": loginKind, "label": label, "pickup": hash})
	req, err := http.NewRequestWithContext(ctx, "POST", base.ResolveReference(&url.URL{Path: "/api/v1/setup/start"}).String(), bytes.NewReader(body))
	if err != nil {
		return pendingLogin{}, errors.New("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 pendingLogin{}, errors.New("the forge could not be reached: " + err.Error())
	}
	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"`
		Interval int    `json:"interval"`
		Error    string `json:"error"`
	}
	json.Unmarshal(raw, &st)
	if resp.StatusCode != http.StatusOK || st.Code == "" || st.Link == "" {
		if st.Error != "" {
			return pendingLogin{}, errors.New("the forge refused: " + show(st.Error))
		}
		return pendingLogin{}, statusError(resp.StatusCode)
	}
	link := base.ResolveReference(&url.URL{Path: "/setup"}).String()
	if lu, err := url.Parse(st.Link); err == nil && sameOrigin(lu, base) {
		link = st.Link
	}
	expires := st.Expires
	if _, err := time.Parse(time.RFC3339, expires); err != nil {
		expires = e.Now().Add(10 * time.Minute).UTC().Format(time.RFC3339)
	}
	p := pendingLogin{Host: hostKey(base), Label: label, Key: base64.RawURLEncoding.EncodeToString(key),
		Code: st.Code, Link: link, Expires: expires, Interval: st.Interval}
	if err := savePending(e.ConfigDir, p); err != nil {
		return pendingLogin{}, errors.New("the pending login could not be saved: " + err.Error())
	}
	return p, nil
}

type pollKind int

const (
	pollDone    pollKind = iota // 200: the token is in the answer
	pollWaiting                 // 202: nobody has entered the code
	pollClaimed                 // 202 pending: the person is on it
	pollExpired                 // 410 expired or lapsed
	pollMissing                 // 404: the forge knows no such start
	pollBusy                    // 429 or 5xx: ask again later
	pollDenied                  // 410 denied or refused
	pollOther                   // anything else; msg says what
)

type pollResult struct {
	kind  pollKind
	retry time.Duration
	ans   pickupAnswer
	msg   string
}

// pollLogin asks once whether the start p has been approved.
func (e *Env) pollLogin(ctx context.Context, base *url.URL, p pendingLogin) (pollResult, error) {
	auth := "Pickup " + base64.RawURLEncoding.EncodeToString(p.key())
	status, retry, b, err := pickupPost(ctx, e, base.ResolveReference(&url.URL{Path: "/api/v1/pickups/collect"}).String(), auth, loginKind)
	if err != nil {
		return pollResult{}, err
	}
	var g pickupAnswer
	json.Unmarshal(b, &g)
	switch {
	case status == http.StatusOK:
		if json.Unmarshal(b, &g) != nil {
			return pollResult{}, errors.New("the forge's answer was not understood")
		}
		return pollResult{kind: pollDone, ans: g}, nil
	case status == http.StatusAccepted:
		if g.State == "pending" {
			return pollResult{kind: pollClaimed}, nil
		}
		return pollResult{kind: pollWaiting}, nil
	case status == http.StatusNotFound:
		return pollResult{kind: pollMissing}, nil
	case status == http.StatusTooManyRequests || status >= 500:
		return pollResult{kind: pollBusy, retry: retry}, nil
	case status == http.StatusGone:
		switch g.State {
		case "expired", "lapsed":
			return pollResult{kind: pollExpired}, nil
		case "denied":
			return pollResult{kind: pollDenied, msg: "the login was denied"}, nil
		}
		return pollResult{kind: pollDenied, msg: "the login cannot be collected: " + pickupWord(g.State)}, nil
	case status == http.StatusConflict:
		return pollResult{kind: pollDenied, msg: "this request is not a login; nothing was collected"}, nil
	}
	return pollResult{kind: pollOther, msg: statusError(status).Error()}, nil
}

// waitingJSON is what --no-wait prints with --json: the person's part of
// the login and the way back to it.
type waitingJSON struct {
	OK      bool      `json:"ok"`
	State   string    `json:"state"`
	Host    string    `json:"host"`
	Link    string    `json:"link"`
	Code    string    `json:"code"`
	Expires string    `json:"expires"`
	Next    *nextJSON `json:"next"`
}

func (p pendingLogin) wait(fallback time.Duration) time.Duration {
	if p.Interval > 0 {
		return time.Duration(p.Interval) * time.Second
	}
	return fallback
}