Skip to content
quarry Artifact [cf0bb2c36e]
Login

Artifact [cf0bb2c36e]

Artifact cf0bb2c36e494000d943794e3ac85549ac5b0685b72d0bf97c8ca7872bb20b98:


package pickupclient

import (
	"bytes"
	"encoding/json"
	"net/url"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/nextstep"
)

// Every envelope the client builds without a forge call to carry it
// (the closed set a verb refuses with) keeps the one next shape: a
// sentence, and an open on the forge's own origin. The same envelopes
// are printed for a person and for a program from the one type.
func TestClientEnvelopesKeepTheOneNextShape(t *testing.T) {
	base, _ := url.Parse("https://forge.test")
	var out, errOut bytes.Buffer
	e := &Env{Stdout: &out, Stderr: &errOut}
	cases := map[string]*nextstep.Next{
		"no login": nil,
		"hostile":  {Say: "Go on.\x1b]0;owned\x07", Open: "https://evil.test/x", Cmd: "run\x1b[2J this"},
		"own page": {Say: "Approve it.", Open: "https://forge.test/me#machines"},
	}
	v := voice{e, "doctor", false, base}
	if code := v.noLogin(base); code != exitNoLogin {
		t.Fatalf("FAIL: no login exit %d", code)
	}
	for name, n := range cases {
		if n == nil {
			continue
		}
		errOut.Reset()
		v.refuse(1, "x", "bad", false, n)
		if strings.ContainsAny(errOut.String(), "\x1b\x07") {
			t.Errorf("FAIL: %s: a terminal escape reached the screen: %q", name, errOut.String())
		}
		if strings.Contains(errOut.String(), "evil.test") {
			t.Errorf("FAIL: %s: another origin's page was printed: %q", name, errOut.String())
		}
		if name == "own page" && !strings.Contains(errOut.String(), "open   https://forge.test/me#machines") {
			t.Errorf("FAIL: %s: the forge's own page was not printed: %q", name, errOut.String())
		}
	}
	// As a program reads it.
	var j bytes.Buffer
	vj := voice{&Env{Stdout: &j, Stderr: &errOut}, "doctor", true, base}
	vj.noLogin(base)
	var m struct {
		OK   bool           `json:"ok"`
		Code string         `json:"code"`
		Next *nextstep.Next `json:"next"`
	}
	if err := json.Unmarshal(j.Bytes(), &m); err != nil || m.OK || m.Code != noLoginCode {
		t.Fatalf("FAIL: %v %s", err, j.String())
	}
	if err := m.Next.Validate("https://forge.test"); err != nil || m.Next.Cmd != loginCmd {
		t.Errorf("FAIL: the no-login next is malformed: %v %+v", err, m.Next)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}