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 414b2290ce
All checks were successful
CI/CD / detect-changes (push) Successful in 3s
CI/CD / test-runners (push) Has been skipped
CI/CD / e2e-smoke (push) Has been skipped
CI/CD / test-frontend (push) Successful in 5s
CI/CD / test-go-pg (push) Successful in 2m49s
CI/CD / test-sqlite (push) Successful in 2m59s
CI/CD / build-and-deploy (push) Successful in 1m28s
Feat v0.9.9 surface access roles (#83)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com>
Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
2026-04-03 20:06:25 +00:00

489 lines
19 KiB
Go

package pages
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"armature/config"
"armature/models"
"armature/store"
)
// ── mock TeamStore ───────────────────────────────────────────
// mockTeamStore implements store.TeamStore with a simple role lookup map.
// Only HasRoleInAnyTeam is functional; everything else is a no-op stub.
type mockTeamStore struct {
// userRoles maps userID → set of roles they hold in any team
userRoles map[string]map[string]bool
}
func newMockTeamStore() *mockTeamStore {
return &mockTeamStore{userRoles: make(map[string]map[string]bool)}
}
func (m *mockTeamStore) addRole(userID, role string) {
if m.userRoles[userID] == nil {
m.userRoles[userID] = make(map[string]bool)
}
m.userRoles[userID][role] = true
}
func (m *mockTeamStore) HasRoleInAnyTeam(_ context.Context, userID, role string) (bool, error) {
if roles, ok := m.userRoles[userID]; ok {
return roles[role], nil
}
return false, nil
}
// Stubs — not exercised by surface access tests.
func (m *mockTeamStore) Create(context.Context, *models.Team) error { return nil }
func (m *mockTeamStore) GetByID(context.Context, string) (*models.Team, error) { return nil, nil }
func (m *mockTeamStore) Update(context.Context, string, map[string]interface{}) error { return nil }
func (m *mockTeamStore) Delete(context.Context, string) error { return nil }
func (m *mockTeamStore) List(context.Context) ([]models.Team, error) { return nil, nil }
func (m *mockTeamStore) ListForUser(context.Context, string) ([]models.Team, error) { return nil, nil }
func (m *mockTeamStore) AddMember(context.Context, string, string, string) error { return nil }
func (m *mockTeamStore) RemoveMember(context.Context, string, string) error { return nil }
func (m *mockTeamStore) UpdateMemberRole(context.Context, string, string, string) error { return nil }
func (m *mockTeamStore) ListMembers(context.Context, string) ([]models.TeamMember, error) { return nil, nil }
func (m *mockTeamStore) GetMember(context.Context, string, string) (*models.TeamMember, error) { return nil, nil }
func (m *mockTeamStore) GetUserTeamIDs(context.Context, string) ([]string, error) { return nil, nil }
func (m *mockTeamStore) IsTeamAdmin(context.Context, string, string) (bool, error) { return false, nil }
func (m *mockTeamStore) IsMember(context.Context, string, string) (bool, error) { return false, nil }
func (m *mockTeamStore) Exists(context.Context, string) (bool, error) { return false, nil }
func (m *mockTeamStore) UpdateMemberRoleByID(context.Context, string, string, string) (int64, error) { return 0, nil }
func (m *mockTeamStore) DeleteMemberByID(context.Context, string, string) (int64, error) { return 0, nil }
func (m *mockTeamStore) ListTeamAuditActions(context.Context, string) ([]string, error) { return nil, nil }
func (m *mockTeamStore) GetFirstTeamIDForUser(context.Context, string) (string, error) { return "", nil }
func (m *mockTeamStore) AddMemberReturningID(context.Context, string, string, string) (string, error) { return "", nil }
func (m *mockTeamStore) MergeSettings(context.Context, string, string) error { return nil }
func (m *mockTeamStore) AddUserRole(context.Context, string, string, string, string) error { return nil }
func (m *mockTeamStore) RemoveUserRole(context.Context, string, string, string) error { return nil }
func (m *mockTeamStore) ListUserRoles(context.Context, string, string) ([]string, error) { return nil, nil }
func (m *mockTeamStore) GetMemberRoles(context.Context, string, string) ([]string, error) { return nil, nil }
func (m *mockTeamStore) HasRole(context.Context, string, string, string) (bool, error) { return false, nil }
func (m *mockTeamStore) RemoveAllUserRoles(context.Context, string, string) error { return nil }
func (m *mockTeamStore) AddRoleToCatalog(context.Context, string, string, string) error { return nil }
func (m *mockTeamStore) ListRoleCatalog(context.Context, string) ([]store.TeamRoleCatalogEntry, error) { return nil, nil }
func (m *mockTeamStore) RemoveRoleCatalogBySource(context.Context, string, string) error { return nil }
// ── 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 }
func (m *mockPackageStore) ListAdoptable(context.Context) ([]store.PackageRegistration, error) { return nil, nil }
func (m *mockPackageStore) GetByAdoptedFrom(context.Context, string, string) (*store.PackageRegistration, error) { return nil, 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)
}
}
// ── v0.9.9 — role-based surface access ──────────────────────
// testRouterWithTeams builds a router whose Engine has a mock TeamStore.
// The optAuth middleware also checks X-Admin header to set is_admin.
func testRouterWithTeams(t *testing.T, teams *mockTeamStore, pkgs ...*store.PackageRegistration) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
engine := &Engine{
cfg: &config.Config{BasePath: ""},
stores: store.Stores{Packages: newMockPackageStore(pkgs...), Teams: teams},
loaders: make(map[string]DataLoaderFunc),
}
engine.parseTemplates()
engine.registerCoreSurfaces()
r := gin.New()
optAuth := func(c *gin.Context) {
if uid := c.GetHeader("X-User-ID"); uid != "" {
c.Set("user_id", uid)
c.Set("role", "user")
}
if c.GetHeader("X-Admin") == "true" {
c.Set("is_admin", true)
}
c.Next()
}
apiAuth := func(c *gin.Context) { c.Next() }
apiHandler := func(c *gin.Context) { c.JSON(200, gin.H{"ok": true}) }
engine.RegisterExtensionRoutes(r.Group(""), optAuth, apiAuth, apiHandler)
return r
}
func TestHandler_RoleAccess_Granted(t *testing.T) {
teams := newMockTeamStore()
teams.addRole("user-1", "approver")
pkg := &store.PackageRegistration{
ID: "role-pkg", Title: "Role Pkg", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "role:approver", "title": "Approvals"},
},
},
}
r := testRouterWithTeams(t, teams, pkg)
w := doGet(r, "/s/role-pkg", "X-User-ID", "user-1")
if w.Code != http.StatusOK {
t.Errorf("expected 200 for user with role, got %d", w.Code)
}
}
func TestHandler_RoleAccess_Denied(t *testing.T) {
teams := newMockTeamStore()
// user-2 has no roles
pkg := &store.PackageRegistration{
ID: "role-pkg", Title: "Role Pkg", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "role:approver", "title": "Approvals"},
},
},
}
r := testRouterWithTeams(t, teams, pkg)
w := doGet(r, "/s/role-pkg", "X-User-ID", "user-2")
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 for user without role, got %d", w.Code)
}
}
func TestHandler_RoleAccess_Unauthenticated(t *testing.T) {
teams := newMockTeamStore()
pkg := &store.PackageRegistration{
ID: "role-pkg", Title: "Role Pkg", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "role:approver", "title": "Approvals"},
},
},
}
r := testRouterWithTeams(t, teams, pkg)
w := doGet(r, "/s/role-pkg") // no auth
if w.Code != http.StatusTemporaryRedirect {
t.Errorf("expected 307 redirect, 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_RoleAccess_AdminBypass(t *testing.T) {
teams := newMockTeamStore()
// admin-user has no "approver" role but is_admin=true
pkg := &store.PackageRegistration{
ID: "role-pkg", Title: "Role Pkg", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "role:approver", "title": "Approvals"},
},
},
}
r := testRouterWithTeams(t, teams, pkg)
w := doGet(r, "/s/role-pkg", "X-User-ID", "admin-user", "X-Admin", "true")
if w.Code != http.StatusOK {
t.Errorf("expected 200 for admin bypass, got %d", w.Code)
}
}
func TestHandler_RoleAccess_NilTeamStore(t *testing.T) {
// Engine with no team store — role access should deny gracefully
pkg := &store.PackageRegistration{
ID: "role-pkg", Title: "Role Pkg", Type: "surface", Source: "extension",
Enabled: true, Status: "active",
Manifest: map[string]any{
"surfaces": []any{
map[string]any{"path": "/", "access": "role:approver", "title": "Approvals"},
},
},
}
r := testRouter(t, pkg) // testRouter uses nil Teams store
w := doGet(r, "/s/role-pkg", "X-User-ID", "user-1")
if w.Code != http.StatusForbidden {
t.Errorf("expected 403 when Teams store is nil, got %d", w.Code)
}
}