Files
pages/internal/server/path_snapshot_test.go
T
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

206 lines
8.1 KiB
Go

package server
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"strings"
"testing"
"pageswiki/internal/db"
"pageswiki/internal/store"
)
func pathMutationServerFixture(t *testing.T) (*Server, string, string) {
t.Helper()
database, err := db.Open(t.TempDir() + "/path-server.db")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = database.Close() })
if err := db.Migrate(database); err != nil {
t.Fatal(err)
}
st := store.NewWithDocumentRoot(database, t.TempDir()+"/documents")
if err := st.EnsureConfigTable(); err != nil {
t.Fatal(err)
}
domain, err := st.GetDefaultDomain()
if err != nil {
t.Fatal(err)
}
owner, err := st.BootstrapOwner(domain.UUID, "admin", "a long test password", "Admin", "")
if err != nil {
t.Fatal(err)
}
token, err := st.CreateAuthSession(domain.UUID, owner.UUID)
if err != nil {
t.Fatal(err)
}
if err := st.SetConfigInDomain(domain.UUID, "authorization_mode", "enforcing"); err != nil {
t.Fatal(err)
}
return &Server{store: st}, token, domain.UUID
}
func restrictedPathMutationFixture(t *testing.T) (*Server, string, string, string) {
t.Helper()
s, token, domain := pathMutationServerFixture(t)
principal, err := s.store.PrincipalForSession(domain, token)
if err != nil {
t.Fatal(err)
}
var role string
if err := s.store.DB.QueryRow(`SELECT b.role_uuid FROM auth_role_bindings b JOIN domain_memberships m ON m.uuid=b.membership_uuid
WHERE m.domain_uuid=? AND m.principal_uuid=? LIMIT 1`, domain, principal.UUID).Scan(&role); err != nil {
t.Fatal(err)
}
if _, err := s.store.DB.Exec(`DELETE FROM auth_capability_grants WHERE role_uuid=?`, role); err != nil {
t.Fatal(err)
}
return s, token, domain, role
}
func grantMutationPath(t *testing.T, s *Server, role, capability, path string) {
t.Helper()
if _, err := s.store.DB.Exec(`INSERT INTO auth_capability_grants(uuid,role_uuid,capability,target_type,target_id,created_at_ms)
VALUES(?, ?, ?, 'path', ?, 1)`, capability+":"+path, role, capability, path); err != nil {
t.Fatal(err)
}
}
func pathMutationRequest(handler http.HandlerFunc, token, method, target string, data any) *httptest.ResponseRecorder {
body, _ := json.Marshal(data)
r := httptest.NewRequest(method, "http://localhost"+target, strings.NewReader(string(body)))
if token != "" {
r.Header.Set("Authorization", "Bearer "+token)
}
w := httptest.NewRecorder()
handler(w, r)
return w
}
func TestRecursiveMutationDeniesUngrantableDescendants(t *testing.T) {
s, token, domain, role := restrictedPathMutationFixture(t)
for _, path := range []string{"/source/allowed", "/source/hidden"} {
if _, err := s.store.CreatePageAtPathInDomain(domain, path); err != nil {
t.Fatal(err)
}
}
for _, capability := range []string{"read", "rename", "delete"} {
grantMutationPath(t, s, role, capability, "/source/allowed")
}
grantMutationPath(t, s, role, "create", "/target/allowed")
for _, test := range []struct {
name string
handler http.HandlerFunc
target string
body any
}{
{"rename", s.handleRenamePath, "/_/api/v1/path/rename", map[string]any{"old_path": "/source", "new_path": "/target", "recursive": true}},
{"copy", s.handleCopyPathAPI, "/_/api/v1/path/copy", map[string]any{"source_path": "/source", "destination_path": "/target", "recursive": true}},
{"remove", s.handleRemovePathAPI, "/_/api/v1/path/remove", map[string]any{"path": "/source", "recursive": true}},
{"preview", s.handleRenamePreview, "/_/api/v1/path/rename-preview?old_path=/source", nil},
} {
t.Run(test.name, func(t *testing.T) {
w := pathMutationRequest(test.handler, token, "POST", test.target, test.body)
if w.Code != http.StatusForbidden || strings.Contains(w.Body.String(), "/source/hidden") {
t.Fatalf("ungranted subtree response = %d, %s", w.Code, w.Body.String())
}
for _, path := range []string{"/source/allowed", "/source/hidden"} {
if !s.store.PathExistsInDomain(domain, path) {
t.Fatalf("denied mutation removed %s", path)
}
}
if s.store.PathExistsInDomain(domain, "/target/allowed") {
t.Fatal("denied operation created a destination")
}
})
}
}
func TestRecursiveMutationHandlersUseLiteralAuthorizedSnapshot(t *testing.T) {
for _, operation := range []string{"rename", "copy", "remove"} {
t.Run(operation, func(t *testing.T) {
s, token, domain, role := restrictedPathMutationFixture(t)
root := "/Case%_"
for _, path := range []string{root + "/allowed", "/CaseXY/hidden", "/case%_/hidden"} {
if _, err := s.store.CreatePageAtPathInDomain(domain, path); err != nil {
t.Fatal(err)
}
}
for _, capability := range []string{"read", "rename", "delete"} {
grantMutationPath(t, s, role, capability, root+"/allowed")
}
grantMutationPath(t, s, role, "create", "/target/allowed")
w := pathMutationRequest(s.handleRenamePreview, token, "POST", "/_/api/v1/path/rename-preview?old_path="+url.QueryEscape(" "+root+"/// "), nil)
var preview renamePreviewResponse
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &preview) != nil || !reflect.DeepEqual(preview.Targets, []string{root + "/allowed"}) {
t.Fatalf("literal preview = %d, %s", w.Code, w.Body.String())
}
switch operation {
case "rename":
w = pathMutationRequest(s.handleRenamePath, token, "POST", "/_/api/v1/path/rename", map[string]any{"old_path": " " + root + "/// ", "new_path": " /target/ ", "recursive": true})
case "copy":
w = pathMutationRequest(s.handleCopyPathAPI, token, "POST", "/_/api/v1/path/copy", map[string]any{"source_path": " " + root + "/// ", "destination_path": " /target/ ", "recursive": true})
case "remove":
w = pathMutationRequest(s.handleRemovePathAPI, token, "POST", "/_/api/v1/path/remove", map[string]any{"path": " " + root + "/// ", "recursive": true})
}
if w.Code < 200 || w.Code >= 300 {
t.Fatalf("%s failed: %d, %s", operation, w.Code, w.Body.String())
}
for _, path := range []string{"/CaseXY/hidden", "/case%_/hidden"} {
if !s.store.PathExistsInDomain(domain, path) {
t.Fatalf("unrelated literal/case subtree changed: %s", path)
}
}
})
}
}
func TestRecursiveMutationRequiresMethodAndDestinationGrant(t *testing.T) {
s, token, domain, role := restrictedPathMutationFixture(t)
if _, err := s.store.CreatePageAtPathInDomain(domain, "/source/allowed"); err != nil {
t.Fatal(err)
}
grantMutationPath(t, s, role, "rename", "/source/allowed")
grantMutationPath(t, s, role, "read", "/source/allowed")
for name, handler := range map[string]http.HandlerFunc{"rename": s.handleRenamePath, "legacy-rename": s.handleRenamePathAPI, "copy": s.handleCopyPathAPI, "remove": s.handleRemovePathAPI, "preview": s.handleRenamePreview} {
for _, method := range []string{"GET", "PUT", "DELETE"} {
w := pathMutationRequest(handler, token, method, "/_/api/v1/path/"+name, nil)
if w.Code != http.StatusMethodNotAllowed || w.Header().Get("Allow") != "POST" {
t.Fatalf("%s %s = %d", method, name, w.Code)
}
}
}
w := pathMutationRequest(s.handleRenamePath, token, "POST", "/_/api/v1/path/rename", map[string]any{"old_path": "/source", "new_path": "/target", "recursive": true})
if w.Code != http.StatusForbidden {
t.Fatalf("rename without destination grant = %d, %s", w.Code, w.Body.String())
}
w = pathMutationRequest(s.handleCopyPathAPI, token, "POST", "/_/api/v1/path/copy", map[string]any{"source_path": "/source", "destination_path": "/target", "recursive": true})
if w.Code != http.StatusForbidden {
t.Fatalf("copy without destination grant = %d, %s", w.Code, w.Body.String())
}
for _, token := range []string{token, ""} {
for _, path := range []string{"/source", "/absent"} {
w := pathMutationRequest(s.handleRemovePathAPI, token, "POST", "/_/api/v1/path/remove", map[string]any{"path": path, "recursive": true})
if w.Code != http.StatusForbidden {
t.Fatalf("unauthorized existence oracle for %s: %d, %s", path, w.Code, w.Body.String())
}
}
}
for _, test := range []struct {
err error
status int
}{{store.ErrPathSnapshotChanged, 409}, {store.ErrPathMutationTooLarge, 413}} {
w := httptest.NewRecorder()
writePathMutationError(w, fmt.Errorf("wrapped: %w", test.err))
if w.Code != test.status {
t.Fatalf("%v mapped to %d, want %d", test.err, w.Code, test.status)
}
}
}