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.
348 lines
13 KiB
Go
348 lines
13 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"golang.org/x/net/html"
|
|
"pageswiki/internal/db"
|
|
"pageswiki/internal/store"
|
|
)
|
|
|
|
func configFixture(t *testing.T) (*Server, string, string) {
|
|
t.Helper()
|
|
t.Chdir("../..")
|
|
database, err := db.Open(t.TempDir() + "/config.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", "Test 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)
|
|
}
|
|
if err = st.SetConfigInDomain(domain.UUID, "locale", "ja"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := &Server{store: st, mux: http.NewServeMux()}
|
|
s.mustLoadTemplates()
|
|
s.registerStaticRoutes()
|
|
s.mux.HandleFunc("/-/sys/config", s.handleConfig)
|
|
s.mux.HandleFunc("/-/sys/config/auth", s.handleAuthAdmin)
|
|
s.mux.HandleFunc("/-/sys/config/adapters", s.handleAdapterPluginConfig)
|
|
s.mux.HandleFunc("/_/api/v1/assets", s.handleAssetsAPI)
|
|
s.mux.HandleFunc("/_/api/v1/adapter", s.handleAdapterAPI)
|
|
s.mux.HandleFunc("/_/api/v1/queue", s.handleQueueAPI)
|
|
s.mux.HandleFunc("/_/api/v1/queue/", s.handleQueueAPI)
|
|
s.mux.HandleFunc("/_/api/v1/event", s.handleEventAPI)
|
|
s.mux.HandleFunc("/_/api/v1/event/", s.handleEventAPI)
|
|
s.mux.HandleFunc("/o/path:/system/static/css/", func(w http.ResponseWriter, r *http.Request) {
|
|
http.ServeFile(w, r, filepath.Join("static/css", filepath.Base(r.URL.Path)))
|
|
})
|
|
if err = s.saveAdapterPlugins(domain.UUID, []adapterPlugin{{ID: "hosted.test", Name: "Test Editor", Mode: "editor", Enabled: true, URLTemplate: "https://editor.example/open?ticket={ticket}"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, _, err = st.PutAsset(domain.UUID, "asset:image:test", []byte("test"), "image/png", "test.png", "", owner.UUID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return s, token, domain.UUID
|
|
}
|
|
|
|
func configRequest(s *Server, token, method, path string, form url.Values) *httptest.ResponseRecorder {
|
|
r := httptest.NewRequest(method, "http://localhost"+path, strings.NewReader(form.Encode()))
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
if form != nil {
|
|
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
}
|
|
w := httptest.NewRecorder()
|
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
|
return w
|
|
}
|
|
|
|
func TestConfigOIDCAccountMatchingMode(t *testing.T) {
|
|
s, token, domain := configFixture(t)
|
|
w := configRequest(s, token, http.MethodGet, "/-/sys/config?panel=auth-providers", nil)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `name="oidc_match_by"`) || !strings.Contains(w.Body.String(), `value="email" selected`) {
|
|
t.Fatalf("default OIDC matching selector: %d", w.Code)
|
|
}
|
|
form := url.Values{
|
|
"action": {"save_oidc"},
|
|
"enabled": {"on"},
|
|
"issuer": {"https://id.example.test"},
|
|
"client_id": {"pages"},
|
|
"client_secret": {"secret"},
|
|
"oidc_match_by": {"display_name"},
|
|
}
|
|
w = configRequest(s, token, http.MethodPost, "/-/sys/config/auth", form)
|
|
if w.Code != http.StatusSeeOther || !strings.Contains(w.Header().Get("Location"), "panel=auth-providers") {
|
|
t.Fatalf("save OIDC matching mode: %d %s", w.Code, w.Body.String())
|
|
}
|
|
config, err := s.store.AuthProviderConfig(domain, "oidc")
|
|
if err != nil || config.OIDCMatchBy != "display_name" {
|
|
t.Fatalf("stored OIDC matching mode: %#v %v", config, err)
|
|
}
|
|
w = configRequest(s, token, http.MethodGet, "/-/sys/config?panel=auth-providers", nil)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `value="display_name" selected`) {
|
|
t.Fatalf("selected OIDC matching mode: %d", w.Code)
|
|
}
|
|
form.Set("oidc_match_by", "preferred_username")
|
|
w = configRequest(s, token, http.MethodPost, "/-/sys/config/auth", form)
|
|
if w.Code != http.StatusSeeOther {
|
|
t.Fatalf("save preferred_username matching mode: %d %s", w.Code, w.Body.String())
|
|
}
|
|
config, err = s.store.AuthProviderConfig(domain, "oidc")
|
|
if err != nil || config.OIDCMatchBy != "preferred_username" {
|
|
t.Fatalf("stored preferred_username matching mode: %#v %v", config, err)
|
|
}
|
|
w = configRequest(s, token, http.MethodGet, "/-/sys/config?panel=auth-providers", nil)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `value="preferred_username" selected`) {
|
|
t.Fatalf("selected preferred_username matching mode: %d", w.Code)
|
|
}
|
|
form.Set("oidc_match_by", "username")
|
|
w = configRequest(s, token, http.MethodPost, "/-/sys/config/auth", form)
|
|
if w.Code != http.StatusBadRequest {
|
|
t.Fatalf("invalid OIDC matching mode accepted: %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestConfigLDAPProviderPanelAndSecretPreservation(t *testing.T) {
|
|
s, token, domain := configFixture(t)
|
|
w := configRequest(s, token, http.MethodGet, "/-/sys/config?panel=auth-providers", nil)
|
|
if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), `name="ldap_search_filter"`) || !strings.Contains(w.Body.String(), `{{username}}`) {
|
|
t.Fatalf("LDAP provider panel: %d %s", w.Code, w.Body.String())
|
|
}
|
|
form := url.Values{
|
|
"action": {"save_ldap"},
|
|
"enabled": {"on"},
|
|
"ldap_url": {"ldaps://directory.example.test:636"},
|
|
"ldap_bind_dn": {"cn=pageswiki,ou=services,dc=example,dc=test"},
|
|
"ldap_bind_password": {"directory-secret"},
|
|
"ldap_search_base": {"ou=people,dc=example,dc=test"},
|
|
"ldap_search_filter": {"(&(objectClass=person)(uid={{username}}))"},
|
|
"ldap_verify_tls": {"on"},
|
|
"ldap_uid_attribute": {"entryUUID"},
|
|
"ldap_username_attribute": {"uid"},
|
|
"ldap_email_attribute": {"mail"},
|
|
"ldap_display_attribute": {"displayName"},
|
|
"ldap_match_by": {"username"},
|
|
"ldap_auto_provision": {"on"},
|
|
}
|
|
w = configRequest(s, token, http.MethodPost, "/-/sys/config/auth", form)
|
|
if w.Code != http.StatusSeeOther || !strings.Contains(w.Header().Get("Location"), "panel=auth-providers") {
|
|
t.Fatalf("save LDAP provider: %d %s", w.Code, w.Body.String())
|
|
}
|
|
config, err := s.store.AuthProviderConfig(domain, "ldap")
|
|
if err != nil || config.LDAPBindPassword != "directory-secret" || config.LDAPSkipTLSVerify || !config.LDAPAutoProvision || config.UUID == "" {
|
|
t.Fatalf("stored LDAP provider: %#v %v", config, err)
|
|
}
|
|
form.Set("ldap_bind_password", "")
|
|
form.Set("ldap_search_filter", "(mail={{username}})")
|
|
w = configRequest(s, token, http.MethodPost, "/-/sys/config/auth", form)
|
|
if w.Code != http.StatusSeeOther {
|
|
t.Fatalf("update LDAP provider: %d %s", w.Code, w.Body.String())
|
|
}
|
|
config, err = s.store.AuthProviderConfig(domain, "ldap")
|
|
if err != nil || config.LDAPBindPassword != "directory-secret" || config.LDAPSearchFilter != "(mail={{username}})" {
|
|
t.Fatalf("LDAP secret preservation: %#v %v", config, err)
|
|
}
|
|
}
|
|
|
|
func TestAssetsListingAdminAllowedAndMemberDenied(t *testing.T) {
|
|
s, token, domain := configFixture(t)
|
|
w := configRequest(s, token, "GET", "/_/api/v1/assets", nil)
|
|
var data map[string]json.RawMessage
|
|
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &data) != nil || data["assets"] == nil {
|
|
t.Fatalf("asset list: %d %s", w.Code, w.Body.String())
|
|
}
|
|
member, err := s.store.CreatePasswordAccount(domain, "reader", "another long password", "Reader", "")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
memberToken, err := s.store.CreateAuthSession(domain, member.UUID)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
w = configRequest(s, memberToken, "GET", "/_/api/v1/assets", nil)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("member can list assets: %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestConfigBookmarksSaveAndPanelRegistry(t *testing.T) {
|
|
s, token, domain := configFixture(t)
|
|
form := url.Values{"section": {"bookmarks"}, "bookmark_label": {"Docs", "External"}, "bookmark_kind": {"path", "url"}, "bookmark_target": {"/docs/100% complete", "https://example.com/help"}}
|
|
w := configRequest(s, token, "POST", "/-/sys/config", form)
|
|
if w.Code != 302 {
|
|
t.Fatalf("save bookmarks: %d %s", w.Code, w.Body.String())
|
|
}
|
|
items := s.homeBookmarks(domain)
|
|
if len(items) != 2 || items[0].Href != "/docs/100%25%20complete" {
|
|
t.Fatalf("bookmarks: %#v", items)
|
|
}
|
|
form["bookmark_target"][1] = "javascript:alert(1)"
|
|
w = configRequest(s, token, "POST", "/-/sys/config", form)
|
|
if w.Code != 400 || len(s.homeBookmarks(domain)) != 2 {
|
|
t.Fatal("unsafe bookmark accepted or prior state lost")
|
|
}
|
|
w = configRequest(s, token, "GET", "/-/sys/config?panel=bookmarks", nil)
|
|
if w.Code != 200 {
|
|
t.Fatalf("config: %d %s", w.Code, w.Body.String())
|
|
}
|
|
root, err := html.Parse(strings.NewReader(w.Body.String()))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ids := map[string]bool{}
|
|
var panels []string
|
|
var scripts []string
|
|
var walk func(*html.Node)
|
|
walk = func(n *html.Node) {
|
|
if n.Type == html.ElementNode {
|
|
if n.Data == "table" {
|
|
var class, parentClass string
|
|
for _, attr := range n.Attr {
|
|
if attr.Key == "class" {
|
|
class = attr.Val
|
|
}
|
|
}
|
|
if n.Parent != nil {
|
|
for _, attr := range n.Parent.Attr {
|
|
if attr.Key == "class" {
|
|
parentClass = attr.Val
|
|
}
|
|
}
|
|
}
|
|
if (strings.Contains(class, "recent-table") || strings.Contains(class, "config-form-table")) && !strings.Contains(parentClass, "table-scroll") {
|
|
t.Errorf("configuration table has no horizontal scroll container: %s", class)
|
|
}
|
|
}
|
|
for _, a := range n.Attr {
|
|
if a.Key == "id" {
|
|
if ids[a.Val] {
|
|
t.Errorf("duplicate ID %s", a.Val)
|
|
}
|
|
ids[a.Val] = true
|
|
}
|
|
if a.Key == "data-panel" {
|
|
panels = append(panels, a.Val)
|
|
}
|
|
}
|
|
}
|
|
if n.Type == html.ElementNode && n.Data == "script" && n.FirstChild != nil {
|
|
scripts = append(scripts, n.FirstChild.Data)
|
|
}
|
|
for c := n.FirstChild; c != nil; c = c.NextSibling {
|
|
walk(c)
|
|
}
|
|
}
|
|
walk(root)
|
|
for _, panel := range panels {
|
|
if !ids["panel-"+panel] {
|
|
t.Errorf("missing panel %s", panel)
|
|
}
|
|
}
|
|
if len(panels) < 18 || !ids["panel-adapter-hosted.test"] {
|
|
t.Fatalf("incomplete panel registry: %v", panels)
|
|
}
|
|
if node, err := exec.LookPath("node"); err == nil {
|
|
for _, script := range scripts {
|
|
cmd := exec.Command(node, "--check")
|
|
cmd.Stdin = strings.NewReader(script)
|
|
if out, err := cmd.CombinedOutput(); err != nil {
|
|
t.Fatalf("invalid inline JS: %s", out)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestIntegratedAdapterSettingsPersistAndRedirect(t *testing.T) {
|
|
s, token, domain := configFixture(t)
|
|
form := url.Values{"id": {"hosted.test"}, "connection_fields": {"1"}, "name": {"Edited"}, "mode": {"editor"},
|
|
"url_template": {"https://editor.example/open?ticket={ticket}"}, "enabled": {"on"}, "new_tab": {"on"}, "html_markdown": {"on"}, "default_editor": {"on"}, "extensions": {".html, .txt"}}
|
|
w := configRequest(s, token, "POST", "/-/sys/config/adapters?id=hosted.test", form)
|
|
if w.Code != 302 || !strings.Contains(w.Header().Get("Location"), "panel=adapter-hosted.test") {
|
|
t.Fatalf("save adapter: %d %s", w.Code, w.Body.String())
|
|
}
|
|
plugins, err := s.adapterPlugins(domain)
|
|
if err != nil || len(plugins) != 1 || !plugins[0].NewTab || !plugins[0].HTMLMarkdown || !plugins[0].DefaultEditor || plugins[0].Name != "Edited" {
|
|
t.Fatalf("plugin=%#v %v", plugins, err)
|
|
}
|
|
}
|
|
|
|
func TestConfigChromiumSmoke(t *testing.T) {
|
|
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
|
|
t.Skip("opt-in Chromium smoke test")
|
|
}
|
|
s, token, _ := configFixture(t)
|
|
if err := s.store.EnsureBuiltinResourceEvent(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := s.runEvent(&store.EventJob{UUID: "resource-browser", Type: store.ResourceEventType}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
r.Host = "localhost"
|
|
r.Header.Set("Authorization", "Bearer "+token)
|
|
s.withAuthorization(s.mux).ServeHTTP(w, r)
|
|
}))
|
|
defer server.Close()
|
|
for _, panel := range []string{"assets", "events", "queue", "scheduler", "logs", "resources", "bookmarks", "adapter-hosted.test", "extensions"} {
|
|
t.Run(panel, func(t *testing.T) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(ctx, "chromium", "--headless", "--no-sandbox", "--disable-gpu", "--disable-background-networking", "--no-proxy-server", "--enable-logging=stderr", "--log-level=0", "--user-data-dir="+t.TempDir(), "--dump-dom", "--virtual-time-budget=1500", server.URL+"/-/sys/config?panel="+panel)
|
|
if dir := os.Getenv("PAGESWIKI_BROWSER_ARTIFACTS"); dir != "" {
|
|
if err := os.MkdirAll(dir, 0755); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cmd.Args = append(cmd.Args, "--window-size=1440,1000", "--screenshot="+filepath.Join(dir, panel+".png"))
|
|
}
|
|
out, err := cmd.CombinedOutput()
|
|
if err != nil {
|
|
t.Fatalf("browser: %v %s", err, out)
|
|
}
|
|
body := string(out)
|
|
target, classes := panel, "config-section config-panel active"
|
|
if panel == "resources" || panel == "scheduler" {
|
|
target, classes = "scheduler", "config-section config-panel execution-dashboard active"
|
|
}
|
|
if strings.Contains(body, "Uncaught ") || !strings.Contains(body, `id="panel-`+target+`" class="`+classes+`"`) {
|
|
t.Fatalf("browser panel failed: %s", body)
|
|
}
|
|
if panel == "assets" && !strings.Contains(body, `data-asset-copy-hash=`) {
|
|
t.Fatalf("assets did not load: %s", body)
|
|
}
|
|
if panel == "resources" && !strings.Contains(body, `class="chart-line"`) {
|
|
t.Fatalf("resource chart did not load: %s", body)
|
|
}
|
|
})
|
|
}
|
|
}
|