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.Landing.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.Landing.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")
}
}
// autoBy is in one place: landing.autoBy, in landing.get and in the
// answer to landing.auto alike, and at the top level of neither.
func TestAutoByIsOnTheLandingInEveryAnswer(t *testing.T) {
r, _, id := autoRig(t)
wire := func(v any) map[string]json.RawMessage {
t.Helper()
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
var m map[string]json.RawMessage
if err := json.Unmarshal(raw, &m); err != nil {
t.Fatal(err)
}
return m
}
inLanding := func(m map[string]json.RawMessage) string {
t.Helper()
var l struct {
AutoBy string `json:"autoBy"`
}
if err := json.Unmarshal(m["landing"], &l); err != nil {
t.Fatal(err)
}
return l.AutoBy
}
armed, err := r.Invoke(as("dan", "i"), "landing.auto", landingAutoIn{Repo: "test", ID: id, On: flag(true)})
if err != nil {
t.Fatal(err)
}
got, err := r.Invoke(as("dan", "i"), "landing.get", landingGetIn{Repo: "test", ID: id})
if err != nil {
t.Fatal(err)
}
for which, m := range map[string]map[string]json.RawMessage{"landing.auto": wire(armed), "landing.get": wire(got)} {
if _, top := m["autoBy"]; top {
t.Errorf("FAIL: %s answers autoBy at the top level", which)
}
if by := inLanding(m); by != "dan" {
t.Errorf("FAIL: %s answers landing.autoBy %q, want dan", which, by)
}
}
if !t.Failed() {
t.Log("ok")
}
}
// The sweep that lands a record keeps that fact, and landing.get says
// so while the index still reads the record open (it can lag the
// merge). A manual disarm says nothing of the kind.
func TestLandingGetSaysTheSweepLandedItWhileTheIndexReadsOpen(t *testing.T) {
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", ZitVersion: zitcli.MinVersion, 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)
}
get := func() map[string]json.RawMessage {
t.Helper()
got, err := r.Invoke(as("dan", "i"), "landing.get", landingGetIn{Repo: "test", ID: id})
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(got)
var m map[string]json.RawMessage
if err := json.Unmarshal(b, &m); err != nil {
t.Fatal(err)
}
return m
}
// The record reads open and its arm was marked landed: the index lag.
if err := db.SetAutoAccept("test", id, "dan", ""); err != nil {
t.Fatal(err)
}
if err := db.MarkAutoLanded("test", id, "abc123"); err != nil {
t.Fatal(err)
}
m := get()
var al struct {
Hash string `json:"hash"`
At string `json:"at"`
}
if raw, ok := m["autoLanded"]; !ok {
t.Errorf("FAIL: landing.get of an open record the sweep landed has no autoLanded")
} else if err := json.Unmarshal(raw, &al); err != nil || al.Hash != "abc123" || al.At == "" {
t.Errorf("FAIL: autoLanded = %s (%v); want hash and time", raw, err)
}
var l struct {
AutoBy string `json:"autoBy"`
}
_ = json.Unmarshal(m["landing"], &l)
if l.AutoBy != "" {
t.Errorf("FAIL: a landed arm still says armed by %q", l.AutoBy)
}
// A manual disarm leaves no landed mark.
if err := db.SetAutoAccept("test", id, "dan", ""); err != nil {
t.Fatal(err)
}
if _, err := r.Invoke(as("dan", "i"), "landing.auto", landingAutoIn{Repo: "test", ID: id, On: flag(false)}); err != nil {
t.Fatal(err)
}
if _, ok := get()["autoLanded"]; ok {
t.Errorf("FAIL: a manual disarm reads as autoLanded")
}
// The sweep records it when it writes the accept.
if err := db.SetAutoAccept("test", id, "dan", ""); err != nil {
t.Fatal(err)
}
if landed := d.AutoAcceptSweep(db); len(landed) != 1 {
t.Fatalf("FAIL: the sweep landed %v, want the record", landed)
}
st, found := db.AutoStateOf("test", id)
if !found || st.LandedAt == "" || st.LandedHash == "" {
t.Errorf("FAIL: the sweep left %+v found=%v; want a landed marker with the merge hash", st, found)
}
if !t.Failed() {
t.Log("ok")
}
}