package api
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
// A bare name that is no repository, but is the name of one the caller
// can read, answers 404 with the OWNER/NAME path; one the caller cannot
// read is answered exactly as a name nobody holds.
func TestBareNameRefusalNamesTheReadableRepository(t *testing.T) {
SetRepoKnown(func(name string) bool { return false })
defer SetRepoKnown(func(string) bool { return true })
SetReposNamed(func(handle string) []RepoAddr {
switch handle {
case "tools":
return []RepoAddr{{"r1", "dan", "tools"}, {"r2", "crew", "tools"}}
case "hidden":
return []RepoAddr{{"r3", "crew", "hidden"}}
}
return nil
})
defer SetReposNamed(func(string) []RepoAddr { return nil })
r := ops.NewRegistry()
if err := RegisterAll(r, Deps{Version: "v", Repos: NewRepos(map[string]*Repo{})}); err != nil {
t.Fatal(err)
}
h, err := RouterWithCaps(r, "v",
func(string, string) CapSet { return oltp.CapSet("") },
func(_ context.Context, repo string) bool { return repo != "r2" && repo != "r3" },
func(_, _, _ string, _ ops.Auth) Decision { return Allowed })
if err != nil {
t.Fatal(err)
}
get := func(path string) (int, map[string]any) {
w := httptest.NewRecorder()
h.ServeHTTP(w, httptest.NewRequest("GET", path, nil))
var body map[string]any
json.Unmarshal(w.Body.Bytes(), &body)
return w.Code, body
}
code, body := get("/api/v1/r/tools/ticket")
next, _ := body["next"].(map[string]any)
if code != http.StatusNotFound || next == nil || next["call"] != "GET /api/v1/r/dan/tools/ticket" {
t.Errorf("FAIL: readable bare name = %d %v, want 404 with next.call for dan/tools", code, body)
}
if s, _ := next["say"].(string); s == "" || strings.Contains(s, "crew/tools") {
t.Errorf("FAIL: the hint is empty or names an unreadable repository: %q", s)
}
c1, b1 := get("/api/v1/r/hidden/ticket")
c2, b2 := get("/api/v1/r/nobody/ticket")
if c1 != c2 || len(b1) != len(b2) || b1["next"] != nil {
t.Errorf("FAIL: unreadable name answered %d %v, a missing one %d %v", c1, b1, c2, b2)
}
delete(b1, "error")
delete(b2, "error")
if len(b1) != len(b2) {
t.Errorf("FAIL: bodies differ in shape: %v vs %v", b1, b2)
}
if !t.Failed() {
t.Log("ok")
}
}