224 lines
7.8 KiB
Go
224 lines
7.8 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"pageswiki/internal/db"
|
|
"pageswiki/internal/store"
|
|
)
|
|
|
|
const nativeTestDomain = "35ff2304-a401-49ba-b21a-6129d4be2af2"
|
|
|
|
func nativeRuntimeFixture(t *testing.T) *store.Store {
|
|
t.Helper()
|
|
dsn := os.Getenv("PAGESWIKI_TEST_POSTGRES_DSN")
|
|
if dsn == "" {
|
|
t.Skip("set PAGESWIKI_TEST_POSTGRES_DSN to a disposable PostgreSQL URL")
|
|
}
|
|
u, err := url.Parse(dsn)
|
|
if err != nil {
|
|
t.Fatal("invalid test DSN")
|
|
}
|
|
ctx := context.Background()
|
|
admin, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: dsn, AllowInsecure: true})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
schema := "pageswiki_http_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
|
if _, err = admin.Exec(`CREATE SCHEMA "` + schema + `"`); err != nil {
|
|
admin.Close()
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() {
|
|
defer admin.Close()
|
|
if _, err := admin.Exec(`DROP SCHEMA "` + schema + `" CASCADE`); err != nil {
|
|
t.Error(err)
|
|
}
|
|
})
|
|
q := u.Query()
|
|
q.Set("search_path", schema)
|
|
u.RawQuery = q.Encode()
|
|
database, err := db.OpenPostgreSQL(ctx, db.PostgreSQLOptions{DSN: u.String(), AllowInsecure: true})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Cleanup(func() { database.Close() })
|
|
root := filepath.Join(t.TempDir(), "documents")
|
|
if err = os.Mkdir(root, 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PAGESWIKI_AUTH_KEY", "synthetic runtime key")
|
|
// Initial bootstrap creates schema but refuses to invent namespace IDs.
|
|
if _, err = store.NewPostgreSQLWithDocumentRoot(ctx, database, root); err == nil {
|
|
t.Fatal("unprovisioned namespace accepted")
|
|
}
|
|
if _, err = database.Exec(`INSERT INTO campuses(uuid,name,title,created_at) VALUES('campus','default','Test Campus',1);
|
|
INSERT INTO domains(uuid,name,title,created_at,campus_uuid) VALUES('35ff2304-a401-49ba-b21a-6129d4be2af2','default','Test Domain',1,'campus')`); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s, err := store.NewPostgreSQLWithDocumentRoot(ctx, database, root)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Chdir("../..")
|
|
return s
|
|
}
|
|
|
|
func TestPostgreSQLRuntimeHTTPAndRestart(t *testing.T) {
|
|
st := nativeRuntimeFixture(t)
|
|
ctx := context.Background()
|
|
owner, err := st.BootstrapOwner(nativeTestDomain, "owner", "synthetic runtime password", "Owner", "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
token, err := st.CreateAuthSession(nativeTestDomain, owner.UUID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err = st.SetConfigInDomain(nativeTestDomain, "authorization_mode", "enforcing"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
obj, err := st.CreatePageAtPathInDomain(nativeTestDomain, "/native-startup")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = st.SaveRevisionContentInDomain(ctx, nativeTestDomain, owner.UUID, obj, []byte("<h1>Native startup page</h1><p>Canonical document</p>"), "initial", "en", "text/html", "", nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for iteration := 0; iteration < 2; iteration++ {
|
|
if iteration > 0 {
|
|
st, err = store.NewPostgreSQLWithDocumentRoot(ctx, st.DB, st.DocumentRoot)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
s, err := NewChecked(st)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
closeServer := func() {
|
|
closeCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
|
defer cancel()
|
|
if err := s.Close(closeCtx); err != nil {
|
|
t.Error(err)
|
|
}
|
|
}
|
|
t.Cleanup(closeServer)
|
|
listener := httptest.NewServer(s.handler())
|
|
request, _ := http.NewRequest(http.MethodGet, listener.URL+"/native-startup", nil)
|
|
request.Host = "localhost"
|
|
request.Header.Set("Authorization", "Bearer "+token)
|
|
response, err := listener.Client().Do(request)
|
|
if err != nil {
|
|
listener.Close()
|
|
t.Fatal(err)
|
|
}
|
|
body, err := io.ReadAll(response.Body)
|
|
response.Body.Close()
|
|
listener.Close()
|
|
if err != nil || response.StatusCode != 200 || !bytes.Contains(body, []byte("Canonical document")) {
|
|
t.Fatalf("listener roundtrip: %d %v", response.StatusCode, err)
|
|
}
|
|
job := &store.EventJob{UUID: "synthetic-runtime-resource", Type: store.ResourceEventType}
|
|
for range 2 {
|
|
if err := s.runEvent(job); err != nil {
|
|
t.Fatal("resource worker", err)
|
|
}
|
|
}
|
|
var samples int
|
|
if err := st.DB.QueryRow(`SELECT count(*) FROM resource_samples WHERE job_uuid='synthetic-runtime-resource'`).Scan(&samples); err != nil || samples != 1 {
|
|
t.Fatal("resource deduplication", samples, err)
|
|
}
|
|
for _, target := range []string{"/health", "/", "/native-startup", "/e/-/native-startup", "/v/search?q=native-startup", "/_/api/v1/search/suggest?q=native", "/-/sys/config?panel=auth", "/v/tree", "/v/browser", "/v/plan/tasks", "/v/plan/cal/2026/11", "/v/plan/contacts", "/v/plan/dashboard", "/v/feeds"} {
|
|
r := httptest.NewRequest(http.MethodGet, "http://localhost"+target, nil)
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
w := httptest.NewRecorder()
|
|
s.handler().ServeHTTP(w, r)
|
|
if w.Code != http.StatusOK {
|
|
t.Errorf("iteration %d %s: HTTP %d %.400s", iteration, target, w.Code, w.Body.String())
|
|
}
|
|
if strings.HasPrefix(target, "/v/search") && w.Header().Get("X-PagesWiki-Search-Profile") != "metadata-only" {
|
|
t.Error("SQLite search selected")
|
|
}
|
|
if target == "/native-startup" && !strings.Contains(w.Body.String(), "Canonical document") {
|
|
t.Error("page body missing")
|
|
}
|
|
}
|
|
base, err := st.GetRevisionForExactLanguage(obj, "en")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
payload, _ := json.Marshal(map[string]any{"object_uuid": obj, "body": "<h1>Native startup page</h1><p>Canonical document updated</p>", "lang": "en", "content_type": "text/html", "base_revision_uuid": base.UUID, "editor_principal_uuid": owner.UUID})
|
|
save := func(auth string) *httptest.ResponseRecorder {
|
|
r := httptest.NewRequest(http.MethodPost, "http://localhost/_/api/v1/revisions/save", bytes.NewReader(payload))
|
|
r.Header.Set("Authorization", "Bearer "+auth)
|
|
r.Header.Set("Content-Type", "application/json")
|
|
w := httptest.NewRecorder()
|
|
s.handler().ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
if w := save(token); w.Code != 200 {
|
|
t.Fatalf("save: %d %s", w.Code, w.Body)
|
|
}
|
|
if w := save(token); w.Code != 409 {
|
|
t.Fatalf("stale save: %d %s", w.Code, w.Body)
|
|
}
|
|
if w := save("expired"); w.Code != 401 {
|
|
t.Fatalf("expired save: %d %s", w.Code, w.Body)
|
|
}
|
|
for _, target := range []string{calendarDAV, taskDAVCollection, contactDAV} {
|
|
r := httptest.NewRequest("PROPFIND", "http://localhost"+target, strings.NewReader(`<d:propfind xmlns:d="DAV:"><d:allprop/></d:propfind>`))
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
r.Header.Set("Depth", "1")
|
|
r.Header.Set("Content-Type", "application/xml")
|
|
w := httptest.NewRecorder()
|
|
s.handler().ServeHTTP(w, r)
|
|
if w.Code != 207 {
|
|
t.Errorf("DAV %s: %d %.300s", target, w.Code, w.Body.String())
|
|
}
|
|
}
|
|
for _, panel := range []string{"objects", "assets", "auth-providers", "auth-sessions", "groups", "campuses", "domains", "scheduler", "logs", "queue", "organizer"} {
|
|
r := httptest.NewRequest("GET", "http://localhost/-/sys/config?panel="+panel, nil)
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
w := httptest.NewRecorder()
|
|
s.handler().ServeHTTP(w, r)
|
|
if w.Code != 200 {
|
|
t.Errorf("panel %s: %d %.300s", panel, w.Code, w.Body.String())
|
|
}
|
|
}
|
|
// Another Server must not take ownership while this worker is alive.
|
|
if peer, e := NewChecked(st); e == nil {
|
|
peer.Close(ctx)
|
|
t.Error("duplicate worker accepted")
|
|
}
|
|
if iteration == 1 {
|
|
if err := st.RevokeAuthSession(token); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if w := save(token); w.Code != 401 {
|
|
t.Errorf("revoked session accepted: %d", w.Code)
|
|
}
|
|
r := httptest.NewRequest("GET", "http://localhost/native-startup", nil)
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
w := httptest.NewRecorder()
|
|
s.handler().ServeHTTP(w, r)
|
|
if w.Code == 200 || strings.Contains(w.Body.String(), "Canonical document") {
|
|
t.Error("revoked session exposed private page")
|
|
}
|
|
}
|
|
closeServer()
|
|
}
|
|
}
|