feat(17-04): public menu API with registry resolution, throttle bucket and README
- GET /_menu/api/v1/menus/{code}?locale=xx, anonymous, menu-public-api bucket (120/min per client IP)
- classes.BuildTree: published entries nested by parent, sort_order then id, scheme-checked URLs
- registry entries resolved through signpost with url_pattern as the item override and the locale's alternate
- list types keep stored URL and title, generated children follow stored ones; unresolvable entries left out
- TestMenuAPISmoke; README with API, CORS paths, import workflow and Winter adaptations
- go mod tidy records the test dependencies
This commit is contained in:
@@ -544,3 +544,219 @@ func TestMenuImportSmoke(t *testing.T) {
|
||||
t.Fatalf("empty files changed the tables: %d menus, %d entries", m, n)
|
||||
}
|
||||
}
|
||||
|
||||
// publicGet sends an anonymous GET to a public path from remote, or from a
|
||||
// fresh client address when remote is "".
|
||||
func (e *menuEnv) publicGet(t *testing.T, path, remote string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Host = "api.example.test"
|
||||
if remote == "" {
|
||||
remote = fmt.Sprintf("203.0.113.%d:5000", adminSeq.Add(1)%250+1)
|
||||
}
|
||||
req.RemoteAddr = remote
|
||||
rec := httptest.NewRecorder()
|
||||
e.h.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// rawEntry is an entry written with raw SQL, past the admin save gate.
|
||||
type rawEntry struct {
|
||||
menu uint
|
||||
parent *uint
|
||||
sort int
|
||||
typ string
|
||||
title string
|
||||
url *string
|
||||
reference *string
|
||||
pattern *string
|
||||
target *string
|
||||
css *string
|
||||
code *string
|
||||
published bool
|
||||
}
|
||||
|
||||
func (e *menuEnv) insertMenu(t *testing.T, name, code string, active bool) uint {
|
||||
t.Helper()
|
||||
var id uint
|
||||
if err := e.gdb.Raw(`INSERT INTO golem15_menu_menus (name, code, is_active, css_class, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW()) RETURNING id`,
|
||||
name, code, active, "nav-"+code).Scan(&id).Error; err != nil || id == 0 {
|
||||
t.Fatalf("insert menu %s: id=%d err=%v", code, id, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func (e *menuEnv) insertEntry(t *testing.T, r rawEntry) uint {
|
||||
t.Helper()
|
||||
var id uint
|
||||
if err := e.gdb.Raw(`INSERT INTO golem15_menu_menu_entries (menu_id, parent_id, nest_left, nest_right, nest_depth, sort_order, type, title, url, reference, url_pattern, target, css_class, code, is_published, created_at, updated_at)
|
||||
VALUES (?, ?, 0, 0, 0, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW()) RETURNING id`,
|
||||
r.menu, r.parent, r.sort, r.typ, r.title, r.url, r.reference, r.pattern, r.target, r.css, r.code, r.published).Scan(&id).Error; err != nil || id == 0 {
|
||||
t.Fatalf("insert entry %s: id=%d err=%v", r.title, id, err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func str(s string) *string { return &s }
|
||||
|
||||
// apiItem is one item of the public menu tree.
|
||||
type apiItem struct {
|
||||
ID *uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Type string `json:"type"`
|
||||
URL *string `json:"url"`
|
||||
Target *string `json:"target"`
|
||||
CSSClass *string `json:"css_class"`
|
||||
Icon *string `json:"icon"`
|
||||
Code *string `json:"code"`
|
||||
Items []apiItem `json:"items"`
|
||||
}
|
||||
|
||||
type menuBody struct {
|
||||
Data struct {
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
CSSClass *string `json:"css_class"`
|
||||
Items []apiItem `json:"items"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (e *menuEnv) getMenu(t *testing.T, path string) menuBody {
|
||||
t.Helper()
|
||||
rec := e.publicGet(t, path, "")
|
||||
var body menuBody
|
||||
if rec.Code != http.StatusOK || json.Unmarshal(rec.Body.Bytes(), &body) != nil {
|
||||
t.Fatalf("GET %s: %d %s", path, rec.Code, rec.Body.String())
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func deref(s *string) string {
|
||||
if s == nil {
|
||||
return "<nil>"
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
// TestMenuAPISmoke reads a menu through the anonymous public API: 404 JSON
|
||||
// for unknown and inactive codes, unpublished entries and their subtrees
|
||||
// absent, order by sort_order then id, a javascript: URL stored with raw SQL
|
||||
// served as null, a list type keeping its stored title and URL and carrying
|
||||
// generated children after the stored ones, a url_pattern override, the
|
||||
// requested locale's alternate, unresolvable entries left out and the
|
||||
// per-client throttle.
|
||||
func TestMenuAPISmoke(t *testing.T) {
|
||||
e := bootMenu(t)
|
||||
mainID := e.insertMenu(t, "Main", "main", true)
|
||||
e.insertMenu(t, "Hidden", "hidden", false)
|
||||
|
||||
home := e.insertEntry(t, rawEntry{menu: mainID, sort: 1, typ: "url", title: "Home", url: str("/"), target: str("_blank"), css: str("nav-home"), code: str("home"), published: true})
|
||||
bad := e.insertEntry(t, rawEntry{menu: mainID, sort: 2, typ: "url", title: "Bad", url: str("javascript:alert(1)"), target: str("_top"), published: true})
|
||||
divider := e.insertEntry(t, rawEntry{menu: mainID, sort: 2, typ: "divider", title: "", published: true})
|
||||
about := e.insertEntry(t, rawEntry{menu: mainID, sort: 0, typ: "acme-page", title: "", reference: str("2"), published: true})
|
||||
start := e.insertEntry(t, rawEntry{menu: mainID, sort: 5, typ: "acme-page", title: "Start", reference: str("1"), pattern: str("/p/:slug"), published: true})
|
||||
list := e.insertEntry(t, rawEntry{menu: mainID, sort: 6, typ: "acme-list", title: "Pages", url: str("/pages"), published: true})
|
||||
stored := e.insertEntry(t, rawEntry{menu: mainID, parent: &list, sort: 1, typ: "url", title: "Child", url: str("https://example.test/x"), published: true})
|
||||
hidden := e.insertEntry(t, rawEntry{menu: mainID, sort: 7, typ: "url", title: "Hidden", url: str("/hidden"), published: false})
|
||||
e.insertEntry(t, rawEntry{menu: mainID, parent: &hidden, sort: 1, typ: "url", title: "Hidden child", url: str("/hidden/child"), published: true})
|
||||
e.insertEntry(t, rawEntry{menu: mainID, sort: 8, typ: "acme-page", title: "Gone", reference: str("99"), published: true})
|
||||
e.insertEntry(t, rawEntry{menu: mainID, sort: 9, typ: "gone-type", title: "Unregistered", published: true})
|
||||
e.insertEntry(t, rawEntry{menu: mainID, parent: &home, sort: 1, typ: "gone-type", title: "Unregistered child", published: true})
|
||||
|
||||
body := e.getMenu(t, "/_menu/api/v1/menus/main")
|
||||
if body.Data.Code != "main" || body.Data.Name != "Main" || deref(body.Data.CSSClass) != "nav-main" {
|
||||
t.Fatalf("menu = %+v", body.Data)
|
||||
}
|
||||
items := body.Data.Items
|
||||
var order []uint
|
||||
for _, it := range items {
|
||||
if it.ID == nil {
|
||||
t.Fatalf("top-level item without id: %+v", it)
|
||||
}
|
||||
order = append(order, *it.ID)
|
||||
}
|
||||
if want := []uint{about, home, bad, divider, start, list}; fmt.Sprint(order) != fmt.Sprint(want) {
|
||||
t.Fatalf("order = %v, want %v (%+v)", order, want, items)
|
||||
}
|
||||
|
||||
// The single type without a stored title takes the resolved title and
|
||||
// URL of the default pattern.
|
||||
if it := items[0]; it.Title != "about" || deref(it.URL) != "/pages/about" || it.Type != "acme-page" || len(it.Items) != 0 {
|
||||
t.Fatalf("about = %+v", it)
|
||||
}
|
||||
// A url entry keeps its fields; its unregistered child is left out.
|
||||
if it := items[1]; it.Title != "Home" || deref(it.URL) != "/" || deref(it.Target) != "_blank" || deref(it.CSSClass) != "nav-home" || deref(it.Code) != "home" || it.Icon != nil || it.Items == nil || len(it.Items) != 0 {
|
||||
t.Fatalf("home = %+v", it)
|
||||
}
|
||||
// A javascript: URL and an unknown target come back null.
|
||||
if it := items[2]; it.URL != nil || it.Target != nil {
|
||||
t.Fatalf("bad = %+v", it)
|
||||
}
|
||||
if it := items[3]; it.Type != "divider" || it.URL != nil {
|
||||
t.Fatalf("divider = %+v", it)
|
||||
}
|
||||
// The url_pattern override and the stored title.
|
||||
if it := items[4]; it.Title != "Start" || deref(it.URL) != "/p/home" {
|
||||
t.Fatalf("start = %+v", it)
|
||||
}
|
||||
// The list keeps its stored title and URL; the stored child comes first,
|
||||
// then the generated children without an id.
|
||||
it := items[5]
|
||||
if it.Title != "Pages" || deref(it.URL) != "/pages" || len(it.Items) != 3 {
|
||||
t.Fatalf("list = %+v", it)
|
||||
}
|
||||
if c := it.Items[0]; c.ID == nil || *c.ID != stored || deref(c.URL) != "https://example.test/x" {
|
||||
t.Fatalf("stored child = %+v", c)
|
||||
}
|
||||
for i, slug := range []string{"home", "about"} {
|
||||
c := it.Items[i+1]
|
||||
if c.ID != nil || c.Type != "acme-list" || c.Title != slug || deref(c.URL) != "/pages/"+slug || c.Target != nil || c.CSSClass != nil || c.Items == nil {
|
||||
t.Fatalf("generated child %d = %+v", i, c)
|
||||
}
|
||||
}
|
||||
raw := e.publicGet(t, "/_menu/api/v1/menus/main", "").Body.String()
|
||||
for _, absent := range []string{"Hidden", "Gone", "Unregistered", "javascript"} {
|
||||
if strings.Contains(raw, absent) {
|
||||
t.Fatalf("body holds %q: %s", absent, raw)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(raw, `"id":null`) || !strings.Contains(raw, `"items":[]`) {
|
||||
t.Fatalf("nulls and empty lists not encoded: %s", raw)
|
||||
}
|
||||
|
||||
// ?locale=en picks the en alternates; stored titles stay.
|
||||
items = e.getMenu(t, "/_menu/api/v1/menus/main?locale=en").Data.Items
|
||||
if it := items[0]; it.Title != "about (en)" || deref(it.URL) != "/en/pages/about" {
|
||||
t.Fatalf("about en = %+v", it)
|
||||
}
|
||||
if it := items[4]; it.Title != "Start" || deref(it.URL) != "/en/p/home" {
|
||||
t.Fatalf("start en = %+v", it)
|
||||
}
|
||||
if c := items[5].Items[1]; c.Title != "home (en)" || deref(c.URL) != "/en/pages/home" {
|
||||
t.Fatalf("generated child en = %+v", c)
|
||||
}
|
||||
// A locale without alternates keeps the resolved values.
|
||||
if it := e.getMenu(t, "/_menu/api/v1/menus/main?locale=de").Data.Items[0]; it.Title != "about" || deref(it.URL) != "/pages/about" {
|
||||
t.Fatalf("about de = %+v", it)
|
||||
}
|
||||
|
||||
// Misses are 404 JSON: an unknown code, an inactive menu, a malformed code.
|
||||
for _, path := range []string{"/_menu/api/v1/menus/nope", "/_menu/api/v1/menus/hidden", "/_menu/api/v1/menus/main.json"} {
|
||||
rec := e.publicGet(t, path, "")
|
||||
if rec.Code != http.StatusNotFound || rec.Body.String() != `{"error":"Menu not found"}` {
|
||||
t.Errorf("GET %s: %d %s", path, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// One client gets 120 requests a minute, then surf's 429 body.
|
||||
const client = "192.0.2.77:6000"
|
||||
for i := 0; i < 120; i++ {
|
||||
if rec := e.publicGet(t, "/_menu/api/v1/menus/nope", client); rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("request %d: %d %s", i+1, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
rec := e.publicGet(t, "/_menu/api/v1/menus/main", client)
|
||||
if rec.Code != http.StatusTooManyRequests || !strings.Contains(rec.Body.String(), "Too Many Attempts.") {
|
||||
t.Fatalf("121st request: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user