This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/pages/pages_handler_test.go
Jeffrey Smith 3ae959c8a9
All checks were successful
CI/CD / detect-changes (pull_request) Successful in 4s
CI/CD / test-runners (pull_request) Has been skipped
CI/CD / e2e-smoke (pull_request) Has been skipped
CI/CD / test-frontend (pull_request) Successful in 5s
CI/CD / test-go-pg (pull_request) Successful in 2m50s
CI/CD / test-sqlite (pull_request) Successful in 3m1s
CI/CD / build-and-deploy (pull_request) Successful in 1m27s
Feat v0.9.1 server-side sub-path routing
Hardens multi-surface routing: unified root/catch-all dispatcher,
aggregateAccess() early auth short-circuit for all-authenticated
packages, SDK history.replaceState() for back-button resilience.

13 new tests (5 aggregateAccess unit + 8 handler integration).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 13:11:20 +00:00

294 lines
10 KiB
Go

package pages
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"armature/config"
"armature/store"
)
// ── mock PackageStore ────────────────────────────────────────
// mockPackageStore implements store.PackageStore with in-memory data.
// Only Get and List are wired; everything else is a no-op stub.
type mockPackageStore struct {
pkgs map[string]*store.PackageRegistration
}
func newMockPackageStore(pkgs ...*store.PackageRegistration) *mockPackageStore {
m := &mockPackageStore{pkgs: make(map[string]*store.PackageRegistration)}
for _, p := range pkgs {
m.pkgs[p.ID] = p
}
return m
}
func (m *mockPackageStore) Get(_ context.Context, id string) (*store.PackageRegistration, error) {
if p, ok := m.pkgs[id]; ok {
return p, nil
}
return nil, nil
}
func (m *mockPackageStore) List(_ context.Context) ([]store.PackageRegistration, error) {
var out []store.PackageRegistration
for _, p := range m.pkgs {
out = append(out, *p)
}
return out, nil
}
func (m *mockPackageStore) ListEnabled(_ context.Context) ([]string, error) {
var ids []string
for id, p := range m.pkgs {
if p.Enabled {
ids = append(ids, id)
}
}
return ids, nil
}
// Stubs — not exercised by the pages handler tests.
func (m *mockPackageStore) Seed(context.Context, string, string, string, map[string]any) error { return nil }
func (m *mockPackageStore) SetEnabled(context.Context, string, bool) error { return nil }
func (m *mockPackageStore) SetStatus(context.Context, string, string) error { return nil }
func (m *mockPackageStore) Delete(context.Context, string) error { return nil }
func (m *mockPackageStore) Create(context.Context, *store.PackageRegistration) error { return nil }
func (m *mockPackageStore) Update(context.Context, string, *store.PackageRegistration) error { return nil }
func (m *mockPackageStore) ListByType(context.Context, string) ([]store.PackageRegistration, error) { return nil, nil }
func (m *mockPackageStore) ListEnabledByType(context.Context, string) ([]store.PackageRegistration, error) { return nil, nil }
func (m *mockPackageStore) ListForUser(context.Context, string) ([]store.UserPackage, error) { return nil, nil }
func (m *mockPackageStore) GetUserSettings(context.Context, string, string) (*store.PackageUserSettings, error) { return nil, nil }
func (m *mockPackageStore) SetUserSettings(context.Context, *store.PackageUserSettings) error { return nil }
func (m *mockPackageStore) DeleteUserSettings(context.Context, string, string) error { return nil }
func (m *mockPackageStore) ListVisiblePackages(context.Context, string) ([]store.PackageRegistration, error) { return nil, nil }
func (m *mockPackageStore) SetSchemaVersion(context.Context, string, int) error { return nil }
func (m *mockPackageStore) GetPackageSettings(context.Context, string) (json.RawMessage, error) { return nil, nil }
func (m *mockPackageStore) SetPackageSettings(context.Context, string, json.RawMessage) error { return nil }
func (m *mockPackageStore) GetTeamSettings(context.Context, string, string) (json.RawMessage, error) { return nil, nil }
func (m *mockPackageStore) SetTeamSettings(context.Context, string, string, json.RawMessage) error { return nil }
func (m *mockPackageStore) DeleteTeamSettings(context.Context, string, string) error { return nil }
// ── test helpers ─────────────────────────────────────────────
// testEngine creates a minimal Engine with parsed templates and mock stores.
func testEngine(t *testing.T, pkgs ...*store.PackageRegistration) *Engine {
t.Helper()
gin.SetMode(gin.TestMode)
e := &Engine{
cfg: &config.Config{BasePath: ""},
stores: store.Stores{Packages: newMockPackageStore(pkgs...)},
loaders: make(map[string]DataLoaderFunc),
}
e.parseTemplates()
e.registerCoreSurfaces()
return e
}
// testRouter builds a Gin router with extension routes registered.
func testRouter(t *testing.T, pkgs ...*store.PackageRegistration) *gin.Engine {
t.Helper()
engine := testEngine(t, pkgs...)
r := gin.New()
// OptionalAuth — set user_id if "X-User-ID" header is present (test shortcut)
optAuth := func(c *gin.Context) {
if uid := c.GetHeader("X-User-ID"); uid != "" {
c.Set("user_id", uid)
c.Set("role", "user")
}
c.Next()
}
// API auth — for ext API sub-paths (not exercised in surface tests)
apiAuth := func(c *gin.Context) { c.Next() }
// Ext API handler stub
apiHandler := func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) }
engine.RegisterExtensionRoutes(r.Group(""), optAuth, apiAuth, apiHandler)
return r
}
func doGet(r *gin.Engine, path string, headers ...string) *httptest.ResponseRecorder {
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", path, nil)
for i := 0; i+1 < len(headers); i += 2 {
req.Header.Set(headers[i], headers[i+1])
}
r.ServeHTTP(w, req)
return w
}
// ── handler integration tests ───────────────────────────────
func TestHandler_RootPathRefresh(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "authenticated", "title": "Dashboard"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg", "X-User-ID", "user-1")
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
}
func TestHandler_SubPathStaticRefresh(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "authenticated", "title": "Dashboard"},
map[string]any{"path": "/monitor", "access": "authenticated", "title": "Monitor"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg/monitor", "X-User-ID", "user-1")
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
}
func TestHandler_SubPathParamRefresh(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "authenticated", "title": "Dashboard"},
map[string]any{"path": "/:id", "access": "authenticated", "title": "Detail"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg/abc123", "X-User-ID", "user-1")
if w.Code != http.StatusOK {
t.Errorf("expected 200, got %d", w.Code)
}
body := w.Body.String()
if !strings.Contains(body, `"id":"abc123"`) {
t.Errorf("expected __SURFACE_PARAMS__ to contain id=abc123")
}
}
func TestHandler_UnauthRedirect(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/dashboard", "access": "authenticated", "title": "Dashboard"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg/dashboard") // no auth header
if w.Code != http.StatusTemporaryRedirect {
t.Errorf("expected 307, got %d", w.Code)
}
loc := w.Header().Get("Location")
if !strings.Contains(loc, "/login") {
t.Errorf("expected redirect to /login, got %s", loc)
}
}
func TestHandler_PublicSurfaceAnonymous(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/submit", "access": "public", "title": "Submit"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg/submit") // no auth
if w.Code != http.StatusOK {
t.Errorf("expected 200 for public surface, got %d", w.Code)
}
}
func TestHandler_MixedAccessPackage(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/submit", "access": "public", "title": "Submit"},
map[string]any{"path": "/dashboard", "access": "authenticated", "title": "Dashboard"},
},
},
}
r := testRouter(t, pkg)
// Public surface — anonymous OK
w1 := doGet(r, "/s/test-pkg/submit")
if w1.Code != http.StatusOK {
t.Errorf("public surface: expected 200, got %d", w1.Code)
}
// Authenticated surface — anonymous gets redirect
w2 := doGet(r, "/s/test-pkg/dashboard")
if w2.Code != http.StatusTemporaryRedirect {
t.Errorf("auth surface: expected 307, got %d", w2.Code)
}
}
func TestHandler_NonMatchingSubPath(t *testing.T) {
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "authenticated", "title": "Dashboard"},
},
},
}
r := testRouter(t, pkg)
w := doGet(r, "/s/test-pkg/nonexistent", "X-User-ID", "user-1")
if w.Code != http.StatusNotFound {
t.Errorf("expected 404, got %d", w.Code)
}
}
func TestHandler_EarlyAuthShortCircuit(t *testing.T) {
// All surfaces require auth → early short-circuit before surface matching
pkg := &store.PackageRegistration{
ID: "test-pkg", Title: "Test", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "authenticated", "title": "Dashboard"},
map[string]any{"path": "/settings", "access": "admin", "title": "Settings"},
},
},
}
r := testRouter(t, pkg)
// Any path — should redirect before even matching surfaces
w := doGet(r, "/s/test-pkg/anything") // no auth
if w.Code != http.StatusTemporaryRedirect {
t.Errorf("expected 307 (early short-circuit), got %d", w.Code)
}
loc := w.Header().Get("Location")
if !strings.Contains(loc, "/login") {
t.Errorf("expected redirect to /login, got %s", loc)
}
}