package pickupclient
import (
"bytes"
"context"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"time"
"craftdesign.group/quarry/internal/nextstep"
)
// 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"`
// Started is when this client made the start, by its own clock, and
// Life how many seconds the forge gave it: the code is judged by
// those two, never by the forge's clock against this one.
Started string `json:"started"`
Life int `json:"life"`
}
const (
intervalMin = 5
intervalMax = 60
// pendingKeep is how long an approved login stays collectable.
pendingKeep = 24 * time.Hour
)
// pollInterval is the forge's interval in seconds if it is a number in
// [5, 60]; any other value, or none, is 0 and means the fallback.
func pollInterval(raw json.RawMessage) int {
var f float64
if json.Unmarshal(raw, &f) != nil || f != f || f < intervalMin || f > intervalMax {
return 0
}
return int(f)
}
// deadline is when the code lapses unclaimed, by this client's clock.
func (p pendingLogin) deadline() time.Time {
t, err := time.Parse(time.RFC3339, p.Started)
if err != nil {
return time.Time{}
}
return t.Add(time.Duration(p.Life) * time.Second)
}
func lockPath(dir, host string) string {
return filepath.Join(dir, "pending-"+hex.EncodeToString([]byte(host))+".lock")
}
func (p pendingLogin) startedAt() time.Time {
t, _ := time.Parse(time.RFC3339, p.Started)
return t
}
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
}
// 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 == "" || p.startedAt().IsZero() {
return pendingLogin{}, false
}
if p.Interval < intervalMin || p.Interval > intervalMax {
p.Interval = 0
}
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 json.RawMessage `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 && nextstep.SameOrigin(lu, base) {
link = st.Link
}
// The lifetime is the forge's own two clocks subtracted (its expiry
// less its Date), so a fast or slow clock here changes nothing; with
// no Date it is the forge's ten minutes.
life := 10 * time.Minute
if exp, err := time.Parse(time.RFC3339, st.Expires); err == nil {
if d, err := http.ParseTime(resp.Header.Get("Date")); err == nil {
life = exp.Sub(d)
}
}
life = max(0, min(life, time.Hour))
now := e.Now()
p := pendingLogin{Host: hostKey(base), Label: label, Key: base64.RawURLEncoding.EncodeToString(key),
Code: st.Code, Link: link, Expires: now.Add(life).UTC().Format(time.RFC3339), Interval: pollInterval(st.Interval),
Started: now.UTC().Format(time.RFC3339), Life: int(life / time.Second)}
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 *nextstep.Next `json:"next"`
}
func (p pendingLogin) wait(fallback time.Duration) time.Duration {
if p.Interval > 0 {
return time.Duration(p.Interval) * time.Second
}
return fallback
}