Skip to content
quarry Artifact [44bb974a47]
Login

Artifact [44bb974a47]

Artifact 44bb974a47370eeb5a2bee4f10b7dfff514fde0de3ca8fb2f45aacc03598af79:


package api

import (
	"context"
	"encoding/json"
	"errors"
	"net/http/httptest"
	"path/filepath"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/zitcli"
)

func autoRig(t *testing.T) (*ops.Registry, *oltp.DB, string) {
	t.Helper()
	dir, id, ix, pipeSync := acceptStore(t)
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	if err := db.AddAccount("dan", "a-long-enough-password", false); err != nil {
		t.Fatal(err)
	}
	d := Deps{Version: "v", Auto: db, Repos: NewRepos(map[string]*Repo{
		"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: pipeSync}})}
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	return r, db, id
}

func flag(b bool) *bool { return &b }

// A call that leaves "on" out is refused instead of reading as "off":
// an agent meaning to arm got {} and nothing armed (ticket 463).
func TestLandingAutoRefusesACallWithoutOn(t *testing.T) {
	r, db, id := autoRig(t)
	_, err := r.Invoke(as("dan", "i"), "landing.auto", landingAutoIn{Repo: "test", ID: id})
	if !errors.Is(err, ops.ErrInvalid) {
		t.Errorf("FAIL: a call without on: %v, want ErrInvalid", err)
	}
	h, herr := RouterWithCaps(r, "v", func(string, string) CapSet { return oltp.CapSet("i") }, nil)
	if herr != nil {
		t.Fatal(herr)
	}
	req := httptest.NewRequest("POST", "/api/v1/r/test/landing/"+id+"/auto", strings.NewReader(`{}`)).
		WithContext(ops.WithUser(context.Background(), "dan"))
	req.Header.Set("Content-Type", "application/json")
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)
	if rec.Code != 400 {
		t.Errorf("FAIL: POST without on answered %d: %s", rec.Code, rec.Body)
	}
	if rows, _ := db.AutoAccepts(); len(rows) != 0 {
		t.Errorf("FAIL: a refused call stored %+v", rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

func TestLandingAutoSaysWhatChanged(t *testing.T) {
	r, db, id := autoRig(t)
	call := func(on bool) landingAutoOut {
		t.Helper()
		out, err := r.Invoke(as("dan", "i"), "landing.auto", landingAutoIn{Repo: "test", ID: id, On: flag(on)})
		if err != nil {
			t.Fatalf("FAIL: on=%v: %v", on, err)
		}
		return out.(landingAutoOut)
	}
	if o := call(false); o.Armed || o.Changed || o.Say == "" {
		t.Errorf("FAIL: disarming an unarmed landing: %+v", o)
	}
	if o := call(true); !o.Armed || !o.Changed || o.AutoBy != "dan" || o.Say == "" {
		t.Errorf("FAIL: arming: %+v", o)
	}
	if rows, _ := db.AutoAccepts(); len(rows) != 1 {
		t.Errorf("FAIL: the arm stored %+v", rows)
	}
	if o := call(false); o.Armed || !o.Changed || o.AutoBy != "" {
		t.Errorf("FAIL: disarming an armed landing: %+v", o)
	}
	if rows, _ := db.AutoAccepts(); len(rows) != 0 {
		t.Errorf("FAIL: the disarm left %+v", rows)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The request an agent's ask leaves for its person says which way the
// switch goes, so approving "arm" cannot be approving "disarm".
func TestLandingAutoAskReadsAsArmOrDisarm(t *testing.T) {
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	if err := db.AddAccount("dmestas", "a-long-enough-password", true); err != nil {
		t.Fatal(err)
	}
	if err := db.NewForgeAgent("fbot", "dmestas"); err != nil {
		t.Fatal(err)
	}
	if err := db.Grant("dmestas", "test", oltp.RepoAdmin); err != nil {
		t.Fatal(err)
	}
	r := ops.NewRegistry()
	if err := RegisterAll(r, Deps{Version: "v", Accounts: adminAdapter{acctAdapter{db}}, SignOffs: testSignOffs{db}, Auto: db,
		Repos:   NewRepos(map[string]*Repo{"test": {Code: "code-test", Chat: "code-test"}}),
		CapsFor: func(a, repo string) CapSet { return db.EffectiveCaps(a, repo) }}); err != nil {
		t.Fatal(err)
	}
	h, err := RouterWithCaps(r, "v", func(string, string) CapSet { return oltp.CapSet("") }, nil)
	if err != nil {
		t.Fatal(err)
	}
	ctx := ops.WithToken(ops.WithUser(context.Background(), "fbot"), ops.TokenAuth{ID: "T",
		Caps:       func(string) ops.Caps { return oltp.CapSet("") },
		ForgeAgent: func() bool { return true }})
	ask := func(body string) (int, SignOffRequest) {
		req := httptest.NewRequest("POST", "/api/v1/r/test/landing/!12/auto", strings.NewReader(body)).WithContext(ctx)
		req.Header.Set("Content-Type", "application/json")
		req.Header.Set("Quarry-Ask", "land when green")
		rec := httptest.NewRecorder()
		h.ServeHTTP(rec, req)
		var a struct {
			SignOff SignOffRequest `json:"signoff"`
		}
		_ = json.Unmarshal(rec.Body.Bytes(), &a)
		return rec.Code, a.SignOff
	}
	if c, _ := ask(`{}`); c != 400 {
		t.Errorf("FAIL: asking without on answered %d, not a refusal", c)
	}
	c1, on := ask(`{"on":true}`)
	c2, off := ask(`{"on":false}`)
	if c1 != 202 || c2 != 202 {
		t.Fatalf("FAIL: asks answered %d and %d", c1, c2)
	}
	if on.Summary == off.Summary || strings.Contains(on.Summary, "landing.auto") || !strings.Contains(on.Summary, "12") {
		t.Errorf("FAIL: summaries %q and %q do not tell arm from disarm", on.Summary, off.Summary)
	}
	if strings.Contains(strings.ToLower(on.Summary), "disarm") || !strings.Contains(strings.ToLower(off.Summary), "disarm") {
		t.Errorf("FAIL: summaries %q and %q name the wrong direction", on.Summary, off.Summary)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}