package nextstep
import (
"bytes"
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"io/fs"
"net/url"
"path/filepath"
"strconv"
"strings"
"testing"
)
func mustURL(t *testing.T, s string) *url.URL {
t.Helper()
u, err := url.Parse(s)
if err != nil {
t.Fatal(err)
}
return u
}
// The shape is one: the wire keys are literal, an empty cmd, call, open
// and help are left out, and ask is always there.
func TestNextRendersTheOneJSONShape(t *testing.T) {
full, _ := json.Marshal(Next{Say: "s", Call: "POST /a", Cmd: "quarry x", Open: "/r/a/settings", Ask: true, Help: "/llms.txt#h"})
var m map[string]any
json.Unmarshal(full, &m)
for _, k := range []string{"say", "call", "cmd", "open", "ask", "help"} {
if _, ok := m[k]; !ok {
t.Errorf("FAIL: a full next lacks %q: %s", k, full)
}
}
bare, _ := json.Marshal(Next{Say: "s"})
if string(bare) != `{"say":"s","ask":false}` {
t.Errorf("FAIL: a bare next is %s", bare)
}
if !t.Failed() {
t.Log("ok")
}
}
// The human form is say, then open, then run, with escapes stripped from
// every field and an open of another origin left out.
func TestNextRendersTheHumanLines(t *testing.T) {
base := mustURL(t, "https://forge.test")
var b bytes.Buffer
(&Next{Say: "Do it.\x1b[31m", Open: "https://forge.test/r/a/settings", Cmd: "quarry\x07 x"}).Render(&b, " ", base)
if got, want := b.String(), " Do it.\n open https://forge.test/r/a/settings\n run quarry x\n"; got != want {
t.Errorf("FAIL: rendered %q, want %q", got, want)
}
for _, open := range []string{"https://evil.test/x", "http://forge.test/x", "//evil.test/x", "javascript:alert(1)"} {
b.Reset()
(&Next{Say: "s", Open: open}).Render(&b, "", base)
if strings.Contains(b.String(), "open") {
t.Errorf("FAIL: printed open %q: %q", open, b.String())
}
}
b.Reset()
(&Next{Say: "s", Open: "/r/a"}).Render(&b, "", nil)
if !strings.Contains(b.String(), "open /r/a") {
t.Errorf("FAIL: a path was not printed without a base: %q", b.String())
}
if !t.Failed() {
t.Log("ok")
}
}
func TestNextValidate(t *testing.T) {
const origin = "https://forge.test"
for open, ok := range map[string]bool{
"": true, "/r/a/settings": true, "https://forge.test/r/a": true, "https://FORGE.test:443/x": true,
"https://evil.test/r": false, "http://forge.test/r": false, "//evil.test": false, `/\evil.test`: false,
"ftp://forge.test/": false, "/a\x1b[2J": false,
"/a\u202eb": false, "/a\u202ab": false, "/a\u2066b": false, "/a\u2069b": false, "/a\u200eb": false,
"/a\u200fb": false, "/a\u061cb": false, "/a\u200bb": false, "/a\u200cb": false, "/a\u200db": false,
"/a\u2028b": false, "/a\u2029b": false,
} {
if err := (&Next{Say: "s", Open: open}).Validate(origin); (err == nil) != ok {
t.Errorf("FAIL: open %q: %v", open, err)
}
}
if (&Next{}).Validate(origin) == nil || (&Next{Say: " "}).Validate(origin) == nil || (*Next)(nil).Validate(origin) == nil {
t.Error("FAIL: a next with no say passed")
}
if (&Next{Say: "s", Open: "https://forge.test/x"}).Validate("") == nil {
t.Error("FAIL: an absolute open passed with no origin to compare")
}
if !t.Failed() {
t.Log("ok")
}
}
// Every place the module builds a Next as a literal says something and
// never hard-codes an address: an open comes from the forge's own link
// builder, not from a string in the source.
func TestEveryNextBuiltInTheModuleHasASayAndNoFixedOpen(t *testing.T) {
seen := 0
filepath.WalkDir("..", func(path string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
fset := token.NewFileSet()
f, perr := parser.ParseFile(fset, path, nil, 0)
if perr != nil {
t.Errorf("FAIL: %s: %v", path, perr)
return nil
}
ast.Inspect(f, func(n ast.Node) bool {
lit, ok := n.(*ast.CompositeLit)
if !ok {
return true
}
sel, ok := lit.Type.(*ast.SelectorExpr)
if !ok || sel.Sel.Name != "Next" {
return true
}
if id, ok := sel.X.(*ast.Ident); !ok || id.Name != "nextstep" {
return true
}
seen++
at := fset.Position(lit.Pos()).String()
hasSay := false
for _, el := range lit.Elts {
kv, ok := el.(*ast.KeyValueExpr)
if !ok {
t.Errorf("FAIL: %s: a Next with positional fields", at)
continue
}
key, _ := kv.Key.(*ast.Ident)
bl, isLit := kv.Value.(*ast.BasicLit)
var val string
if isLit && bl.Kind == token.STRING {
val, _ = strconv.Unquote(bl.Value)
}
switch key.Name {
case "Say":
hasSay = !isLit || strings.TrimSpace(val) != ""
case "Open":
if isLit && !strings.HasPrefix(val, "/") {
t.Errorf("FAIL: %s: open %q is a fixed address", at, val)
}
}
}
if !hasSay {
t.Errorf("FAIL: %s: a Next with no say", at)
}
return true
})
return nil
})
if seen < 20 {
t.Errorf("FAIL: the walk saw %d Next literals; it is not finding them", seen)
}
if !t.Failed() {
t.Logf("ok: %d", seen)
}
}
// Format characters and line separators are not printed, and a command
// with a line break is never shown, joined or sent.
func TestCleanDropsFormatCharactersAndACmdWithALineBreakIsRefused(t *testing.T) {
for _, r := range []rune{0x202a, 0x202e, 0x2066, 0x2069, 0x200e, 0x200f, 0x061c, 0x200b, 0x200c, 0x200d, 0x2028, 0x2029} {
if got := Clean("a" + string(r) + "b"); got != "ab" {
t.Errorf("FAIL: U+%04X survived Clean: %q", r, got)
}
}
for _, cmd := range []string{"a\nb", "a\rb"} {
n := &Next{Say: "s", Cmd: cmd}
if n.Validate("") == nil {
t.Errorf("FAIL: cmd %q passed Validate", cmd)
}
if n.Safe("").Cmd != "" {
t.Errorf("FAIL: cmd %q survived Safe", cmd)
}
var b bytes.Buffer
n.Render(&b, "", nil)
if strings.Contains(b.String(), "ab") || strings.Count(b.String(), "\n") != 2 {
t.Errorf("FAIL: cmd %q was joined or printed: %q", cmd, b.String())
}
}
if got := (&Next{Say: "s", Open: "https://evil.test/", Cmd: "x"}).Safe("https://forge.test"); got.Open != "" || got.Cmd != "x" {
t.Errorf("FAIL: Safe kept an off-origin open: %+v", got)
}
if !t.Failed() {
t.Log("ok")
}
}