package main
import (
"net/http"
"testing"
"time"
"craftdesign.group/quarry/internal/oltp"
)
// An address is read as readers see it (RFC 0025): a private team's
// repository is at its owner's namespace while the team is private, and
// at the team's when it is public, never at both.
func TestAnAddressIsWhereReadersSeeTheRepository(t *testing.T) {
db := newTestRegistrar(t, 25).odb
if err := db.AddRepo("quiet", t.TempDir(), "", oltp.Public); err != nil {
t.Fatal(err)
}
if err := db.SetOwner("quiet", "alice"); err != nil {
t.Fatal(err)
}
if err := db.AddTeam("hush", "Hush", "", "alice"); err != nil {
t.Fatal(err)
}
if err := db.SetTeamRepo("hush", "quiet", "alice"); err != nil {
t.Fatal(err)
}
a := addressesOf(db)
if ns, handle, ok := a.Of("quiet"); !ok || ns != "hush" || handle != "quiet" {
t.Errorf("FAIL: quiet is at %s/%s (%v), want hush/quiet", ns, handle, ok)
}
if key, ok := a.At("hush", "quiet"); !ok || key != "quiet" {
t.Errorf("FAIL: hush/quiet is %q (%v)", key, ok)
}
if _, err := db.SetTeamPrivate("hush", true); err != nil {
t.Fatal(err)
}
if key, ok := a.At("alice", "quiet"); !ok || key != "quiet" {
t.Errorf("FAIL: with the team private, alice/quiet is %q (%v)", key, ok)
}
if _, ok := a.At("hush", "quiet"); ok {
t.Error("FAIL: a private team's name reaches its repository")
}
if got := a.Named("quiet"); len(got) != 1 || got[0] != "quiet" {
t.Errorf("FAIL: the handle quiet names %v", got)
}
if _, _, ok := a.Of("nothere"); ok {
t.Error("FAIL: a name no repository has has an address")
}
}
// The API reads an address through the server as it is wired, not just
// through the middleware: /api/v1/r/<namespace>/<handle> answers as the
// flat path does, a private repository's included (RFC 0025).
func TestTheAPIReadsAnAddressThroughTheServer(t *testing.T) {
g := newSiteRig(t)
for _, name := range []string{"granted", "secret"} {
if err := g.db.SetNamespace(name, "alice", "alice", time.Now()); err != nil {
t.Fatal(err)
}
}
site, _ := g.mint(t, oltp.ScopeAPI, oltp.ScopeWeb, oltp.ScopeSite)
for _, name := range []string{"granted", "secret"} {
flat, _ := g.do(http.MethodGet, "/api/v1/r/"+name+"/info", site, "", nil)
at, body := g.do(http.MethodGet, "/api/v1/r/alice/"+name+"/info", site, "", nil)
if at != flat {
t.Errorf("FAIL: %s at its address answered %d, its flat path %d: %s", name, at, flat, body)
}
}
if code, _ := g.do(http.MethodGet, "/api/v1/r/alice/granted/info", site, "", nil); code != http.StatusOK {
t.Errorf("FAIL: granted at alice/granted: %d", code)
}
}