package pickupclient
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"regexp"
"runtime"
"strconv"
"strings"
"time"
"unicode/utf8"
"craftdesign.group/quarry/internal/nextstep"
)
// apiBodyLimit is the largest answer printed; a larger one is refused,
// never cut off.
var apiBodyLimit int64 = 64 << 20
var errBodyTooBig = errors.New("answer too big")
const (
apiPrefix = "/api/v1"
apiInputMax = 8 << 20
apiWaitLimit = 10 * time.Minute
browserOnlyCode = "browser_only"
)
const apiHelp = `usage: quarry api METHOD PATH [-d JSON|@FILE|-] [-f FIELD]... [flags]
Call the forge's API as this machine's login. PATH is under /api/v1 and
stays on the forge; the answer is the forge's JSON, printed as it came.
"quarry api GET /" is the index of every op.
-d JSON|@FILE|- the request body: JSON text, a file's, or standard input
-f key=value a string field -f key=@FILE a file's text
-f key=@- standard input -f key:=JSON a number, boolean,
array or object
--host URL the forge (default: QUARRY_HOST, else the checkout's
remote, else the installer's)
--wait when the call is for a browser, follow the repository's
events and retry it when something changes (up to 10 min)
--open open the page the refusal names, on a terminal only
--json accepted; the answer is always the forge's JSON
Fields are the body (a JSON object) on POST, PUT, PATCH and DELETE, and
the query on GET. -f and -d together are a usage error. Standard input is
read only when - or @- is given. {repo} in PATH is the checkout's O/N.
Exit: 0 done, 1 refused, 2 usage, 3 still waiting, 4 not logged in.
Example:
quarry api POST /r/{repo}/forum -f title='Release plan' -f [email protected]
`
type apiField struct {
key, val string // val: the text, "@file", "@-", or JSON when typed
file bool
stdin bool
typed bool
}
type apiArgs struct {
method, path, host string
data string
hasData bool
fields []apiField
wait, open, jsonFlag bool
}
func parseAPIArgs(args []string) (apiArgs, string) {
var a apiArgs
var pos []string
next := func(i *int, name string) (string, bool) {
if *i+1 >= len(args) {
return "", false
}
*i++
return args[*i], true
}
for i := 0; i < len(args); i++ {
s := args[i]
switch {
case s == "-d" || s == "--data":
v, ok := next(&i, s)
if !ok {
return a, s + " needs a value"
}
a.data, a.hasData = v, true
case strings.HasPrefix(s, "--data="):
a.data, a.hasData = strings.TrimPrefix(s, "--data="), true
case s == "-f" || s == "--field":
v, ok := next(&i, s)
if !ok {
return a, s + " needs key=value"
}
f, msg := parseField(v)
if msg != "" {
return a, msg
}
a.fields = append(a.fields, f)
case s == "--host":
v, ok := next(&i, s)
if !ok {
return a, "--host needs a URL"
}
a.host = v
case strings.HasPrefix(s, "--host="):
a.host = strings.TrimPrefix(s, "--host=")
case s == "--wait":
a.wait = true
case s == "--open":
a.open = true
case s == "--json" || s == "-F=json":
a.jsonFlag = true
case s == "-F" && i+1 < len(args) && args[i+1] == "json":
a.jsonFlag, i = true, i+1
case len(s) > 1 && strings.HasPrefix(s, "-"):
return a, "unknown flag " + s
default:
pos = append(pos, s)
}
}
if len(pos) != 2 {
return a, "give a METHOD and a PATH"
}
a.method, a.path = pos[0], pos[1]
if a.hasData && len(a.fields) > 0 {
return a, "use -d or -f, not both"
}
return a, ""
}
func parseField(s string) (apiField, string) {
i := strings.Index(s, "=")
if i <= 0 {
return apiField{}, "a field is key=value, key=@FILE, key=@- or key:=JSON"
}
f := apiField{key: s[:i], val: s[i+1:]}
if strings.HasSuffix(f.key, ":") {
f.key, f.typed = strings.TrimSuffix(f.key, ":"), true
if f.key == "" {
return apiField{}, "a field has no name"
}
if f.val == "@-" {
f.stdin = true
} else if strings.HasPrefix(f.val, "@") {
f.file, f.val = true, f.val[1:]
}
return f, ""
}
switch {
case f.val == "@-":
f.stdin = true
case strings.HasPrefix(f.val, "@"):
f.file, f.val = true, f.val[1:]
}
return f, ""
}
// apiPath checks PATH and returns the request's path, as written, and
// raw query; the checks run on its decoded form. The
// forge's origin is put in front of it by the caller, so the only way to
// reach another origin is a path that is not a path.
func apiPath(p string) (path, query string, err error) {
if p == "" || p[0] != '/' || strings.HasPrefix(p, "//") {
return "", "", errors.New("PATH starts with one / and is under /api/v1")
}
if strings.ContainsAny(p, "\\#") || nextstep.Clean(p) != p || strings.ContainsAny(p, " \t") {
return "", "", errors.New("PATH has a character it may not")
}
path, query, _ = strings.Cut(p, "?")
dec, derr := url.PathUnescape(path)
if derr != nil {
return "", "", errors.New("PATH is not a valid path")
}
if strings.ContainsAny(dec, "\\") || nextstep.Clean(dec) != dec {
return "", "", errors.New("PATH has a character it may not")
}
for _, seg := range strings.Split(dec, "/") {
if seg == ".." || seg == "." {
return "", "", errors.New("PATH may not climb out of /api/v1 with . or ..")
}
}
// A segment that decodes to a slash is another path; it is refused
// rather than sent encoded.
for _, seg := range strings.Split(path, "/") {
if d, _ := url.PathUnescape(seg); strings.Contains(d, "/") {
return "", "", errors.New("PATH may not hide a / inside a segment as %2F")
}
}
for _, seg := range strings.Split(path, "/") {
if strings.Contains(seg, ":") && strings.Contains(seg, "//") {
return "", "", errors.New("PATH may not carry an address")
}
}
return path, query, nil
}
// apiTarget is base with an escaped path: Path decoded, RawPath kept when
// the writing differs, so a path sent as written is not encoded twice.
func apiTarget(base *url.URL, escaped string) (*url.URL, error) {
p, err := url.Parse(escaped)
if err != nil || p.Host != "" || p.Scheme != "" {
return nil, errors.New("PATH is not a valid path")
}
u := *base
u.Path, u.RawPath, u.RawQuery, u.Fragment, u.User = p.Path, p.RawPath, "", "", nil
return &u, nil
}
func (e *Env) apiStdin() io.Reader {
if e.Stdin != nil {
return e.Stdin
}
return os.Stdin
}
func readCapped(r io.Reader, what string) (string, error) {
b, err := io.ReadAll(io.LimitReader(r, apiInputMax+1))
if err != nil {
return "", fmt.Errorf("%s cannot be read: %v", what, err)
}
if len(b) > apiInputMax {
return "", fmt.Errorf("%s is over %d MB", what, apiInputMax>>20)
}
if !utf8.Valid(b) {
return "", fmt.Errorf("%s is not text", what)
}
return string(b), nil
}
// resolve fills each field's text from its file or standard input, once.
func (e *Env) apiResolve(a *apiArgs) error {
usedStdin := false
stdin := func() (string, error) {
if usedStdin {
return "", errors.New("standard input is named twice")
}
usedStdin = true
return readCapped(e.apiStdin(), "standard input")
}
if a.hasData {
switch {
case a.data == "-":
s, err := stdin()
if err != nil {
return err
}
a.data = s
case strings.HasPrefix(a.data, "@"):
b, err := readFileCapped(a.data[1:])
if err != nil {
return err
}
a.data = b
}
if !json.Valid([]byte(a.data)) {
return errors.New("-d is not JSON; for text use -f key=value")
}
}
for i := range a.fields {
f := &a.fields[i]
switch {
case f.stdin:
s, err := stdin()
if err != nil {
return err
}
f.val = s
case f.file:
s, err := readFileCapped(f.val)
if err != nil {
return err
}
f.val = s
}
if f.typed && !json.Valid([]byte(f.val)) {
return fmt.Errorf("-f %s:= is not JSON", f.key)
}
}
return nil
}
func readFileCapped(name string) (string, error) {
f, err := os.Open(name)
if err != nil {
return "", fmt.Errorf("%s cannot be read", name)
}
defer f.Close()
return readCapped(f, name)
}
// fieldsBody is the fields as one JSON object.
func fieldsBody(fs []apiField) ([]byte, error) {
m := map[string]json.RawMessage{}
for _, f := range fs {
if f.typed {
m[f.key] = json.RawMessage(f.val)
continue
}
b, err := json.Marshal(f.val)
if err != nil {
return nil, err
}
m[f.key] = b
}
return json.Marshal(m)
}
// fieldsQuery is the fields as a query. A typed field must be a scalar
// or an array of scalars; an array repeats the key.
func fieldsQuery(fs []apiField) (url.Values, error) {
q := url.Values{}
for _, f := range fs {
if !f.typed {
q.Add(f.key, f.val)
continue
}
dec := json.NewDecoder(strings.NewReader(f.val))
dec.UseNumber()
var v any
if err := dec.Decode(&v); err != nil {
return nil, err
}
items, isArr := v.([]any)
if !isArr {
items = []any{v}
}
for _, it := range items {
switch x := it.(type) {
case string:
q.Add(f.key, x)
case json.Number:
q.Add(f.key, x.String())
case bool:
q.Add(f.key, strconv.FormatBool(x))
default:
return nil, fmt.Errorf("-f %s:= is null, an object or a nested array, which a query cannot carry", f.key)
}
}
}
return q, nil
}
func (e *Env) isTerminal(w io.Writer) bool {
if e.IsTerminal != nil {
return e.IsTerminal(w)
}
f, ok := w.(*os.File)
if !ok {
return false
}
st, err := f.Stat()
return err == nil && st.Mode()&os.ModeCharDevice != 0
}
func openBrowser(u string) error {
switch runtime.GOOS {
case "darwin":
return exec.Command("open", u).Start()
case "windows":
return exec.Command("rundll32", "url.dll,FileProtocolHandler", u).Start()
}
return exec.Command("xdg-open", u).Start()
}
var repoName = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._-]*/[A-Za-z0-9_][A-Za-z0-9._-]*$`)
type apiRefusal struct {
Code string `json:"code"`
Error string `json:"error"`
Next *nextstep.Next `json:"next"`
}
// API is quarry api: 0 done, 1 refused, 2 usage, 3 still waiting (--wait
// ran out), 4 not logged in. The forge's answer goes to stdout as it
// came, indented; what a person needs from a refusal goes to stderr.
func API(ctx context.Context, args []string, e *Env) int {
e.fillLogin()
if e.Stdin == nil {
e.Stdin = os.Stdin
}
for _, s := range args {
if s == "-h" || s == "--help" || s == "-help" {
fmt.Fprint(e.Stdout, apiHelp)
return 0
}
}
a, msg := parseAPIArgs(args)
v := voice{e, e.named("api"), a.jsonFlag, nil}
usage := func(msg string) int {
return v.refuse(2, "usage", msg, false, &nextstep.Next{Say: "See quarry api --help.", Cmd: "quarry api --help"})
}
if msg != "" {
return usage(show(msg))
}
switch a.method = strings.ToUpper(a.method); a.method {
case "GET", "POST", "PUT", "PATCH", "DELETE":
default:
return usage("METHOD is GET, POST, PUT, PATCH or DELETE")
}
if a.method == "GET" && a.hasData {
return usage("a GET has no body; put its parameters in -f fields")
}
var remote *url.URL
if strings.Contains(a.path, "{repo}") {
cwd, err := e.Getwd()
if err != nil {
return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
}
kind, root := checkoutKind(cwd)
if kind != "" {
remote = e.checkoutRemote(ctx, kind, root)
}
var repo string
if remote != nil {
if rest, ok := strings.CutPrefix(remote.EscapedPath(), "/r/"); ok {
repo = strings.Trim(rest, "/")
}
}
if repo != "" && !repoName.MatchString(repo) {
return v.refuse(2, "usage", "the checkout's remote names a repository with characters a name may not have", false,
&nextstep.Next{Say: "Write the repository out as OWNER/NAME."})
}
if repo == "" {
return v.refuse(1, "no_repo", "{repo} needs a checkout whose remote is a repository of the forge", false,
&nextstep.Next{Say: "Run this inside a checkout, or write the repository out as OWNER/NAME."})
}
a.path = strings.ReplaceAll(a.path, "{repo}", repo)
}
path, rawQuery, err := apiPath(a.path)
if err != nil {
return usage(show(err.Error()))
}
base, err := e.forgeFor(a.host, remote)
if err != nil {
return usage(show(err.Error()))
}
v.base = base
if remote != nil && a.host == "" && !nextstep.SameOrigin(remote, base) {
return v.refuse(1, "other_forge", "the checkout's remote is on "+show(remote.Host)+", not "+show(base.Host), false, nil)
}
if base.Scheme == "http" && !isLoopbackHost(base.Host) {
return v.refuse(1, "insecure_forge", "the forge is plain http at "+show(base.Host)+"; a login is not sent that way", false,
&nextstep.Next{Say: "Use the forge's https address with --host."})
}
if err := e.apiResolve(&a); err != nil {
return usage(show(err.Error()))
}
var body []byte
query := rawQuery
switch {
case a.hasData:
body = []byte(a.data)
case len(a.fields) > 0 && a.method == "GET":
q, err := fieldsQuery(a.fields)
if err != nil {
return usage(show(err.Error()))
}
if query != "" {
query += "&"
}
query += q.Encode()
case len(a.fields) > 0:
if body, err = fieldsBody(a.fields); err != nil {
return usage(show(err.Error()))
}
}
rec, ok := e.token(base)
if !ok {
return v.noLogin(base)
}
target, err := apiTarget(base, apiPrefix+path)
if err != nil {
return usage(show(err.Error()))
}
target.RawQuery = query
do := func() (int, []byte, error) {
var rd io.Reader
if body != nil {
rd = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, a.method, target.String(), rd)
if err != nil {
return 0, nil, err
}
req.Header.Set("Authorization", "Bearer "+rec.Token)
req.Header.Set("Accept", "application/json")
if body != nil {
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 0, nil, err
}
defer resp.Body.Close()
raw, err := io.ReadAll(io.LimitReader(resp.Body, apiBodyLimit+1))
if err == nil && int64(len(raw)) > apiBodyLimit {
err = errBodyTooBig
}
return resp.StatusCode, raw, err
}
fail := func(err error) int {
if errors.Is(err, errBodyTooBig) {
return v.refuse(1, "too_big", "the forge's answer is over the client's limit and was not printed", false,
&nextstep.Next{Say: "Ask for less, with a narrower path or a query."})
}
return v.refuse(1, "unreachable", "the forge could not be reached: "+show(err.Error()), false, nil)
}
status, raw, err := do()
if err != nil {
return fail(err)
}
shown := false
limit := e.WaitMax
if limit <= 0 {
limit = apiWaitLimit
}
waitCtx, cancel := context.WithTimeout(ctx, limit)
defer cancel()
for a.wait && status == http.StatusForbidden {
if code, _ := apiRefusalOf(status, raw); code != browserOnlyCode {
break
}
if !shown {
e.apiShowRefusal(&v, status, raw)
shown = true
}
if werr := e.apiWaitEvent(waitCtx, base, rec.Token, path); werr != nil {
e.apiOut(raw)
if !v.json {
fmt.Fprintf(e.Stderr, "%s: still waiting: %s\n", v.verb, show(werr.Error()))
}
return 3
}
if status, raw, err = do(); err != nil {
return fail(err)
}
}
return e.apiFinish(&v, a, base, status, raw, shown)
}
func apiRefusalOf(status int, raw []byte) (string, *nextstep.Next) {
var r apiRefusal
if status/100 != 2 {
_ = json.Unmarshal(raw, &r)
}
return r.Code, r.Next
}
// apiOut writes the body to stdout as the forge sent it, indented when
// it is JSON.
func (e *Env) apiOut(raw []byte) {
if len(raw) == 0 {
return
}
var buf bytes.Buffer
if json.Valid(raw) && json.Indent(&buf, bytes.TrimSpace(raw), "", " ") == nil {
buf.WriteByte('\n')
} else {
buf.Write(raw)
if raw[len(raw)-1] != '\n' {
buf.WriteByte('\n')
}
}
out := buf.Bytes()
if e.isTerminal(e.Stdout) {
// A forge cannot write to a terminal: escapes, C1 and bidi
// characters go, line by line so the line breaks stay.
lines := strings.Split(string(out), "\n")
for i, l := range lines {
lines[i] = nextstep.Clean(l)
}
out = []byte(strings.Join(lines, "\n"))
}
e.Stdout.Write(out)
}
func (e *Env) apiShowRefusal(v *voice, status int, raw []byte) {
if v.json {
return
}
var r apiRefusal
_ = json.Unmarshal(raw, &r)
msg := r.Error
if msg == "" {
msg = fmt.Sprintf("the forge answered %d", status)
}
fmt.Fprintf(e.Stderr, "%s: %s\n", v.verb, show(msg))
r.Next.Render(e.Stderr, " ", v.base)
}
func (e *Env) apiFinish(v *voice, a apiArgs, base *url.URL, status int, raw []byte, shown bool) int {
if status/100 == 3 {
return v.refuse(1, "redirect", fmt.Sprintf("the forge answered %d with a redirect, which is not followed with a login", status), false, nil)
}
e.apiOut(raw)
if status/100 == 2 {
return 0
}
var r apiRefusal
_ = json.Unmarshal(raw, &r)
if !v.json && !shown {
e.apiShowRefusal(v, status, raw)
}
if a.open && r.Next != nil && r.Next.Open != "" && e.isTerminal(e.Stdout) {
if u, err := base.Parse(r.Next.Open); err == nil && (u.Scheme == "http" || u.Scheme == "https") &&
nextstep.SameOrigin(u, base) && nextstep.Clean(u.String()) == u.String() {
open := e.Open
if open == nil {
open = openBrowser
}
_ = open(u.String())
}
}
if status == http.StatusUnauthorized && r.Code == noLoginCode {
return exitNoLogin
}
return 1
}
// apiWaitEvent blocks until the forge's event stream for the call's
// repository delivers an event or ctx (the one deadline) ends.
func (e *Env) apiWaitEvent(ctx context.Context, base *url.URL, token, path string) error {
stream := apiPrefix + "/events/stream"
if rest, ok := strings.CutPrefix(path, "/r/"); ok {
if parts := strings.SplitN(rest, "/", 3); len(parts) >= 2 && parts[0] != "" && parts[1] != "" {
stream = apiPrefix + "/r/" + parts[0] + "/" + parts[1] + "/events/stream"
}
}
u, err := apiTarget(base, stream)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Accept", "text/event-stream")
c := *e.Client
c.Timeout = 0
resp, err := c.Do(req)
if err != nil {
if ctx.Err() != nil {
return errors.New("nothing changed in time")
}
return errors.New("the event stream could not be opened")
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("the event stream answered %d", resp.StatusCode)
}
sc := bufio.NewScanner(resp.Body)
sc.Buffer(make([]byte, 64<<10), 1<<20)
name, data := "", false
for sc.Scan() {
line := sc.Text()
switch {
case line == "":
if data && name != "live" && name != "gap" {
return nil
}
name, data = "", false
case strings.HasPrefix(line, "event:"):
name = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
case strings.HasPrefix(line, "data:"):
data = true
}
}
if ctx.Err() != nil {
return errors.New("nothing changed in time")
}
return errors.New("the event stream ended")
}