Files
OwnCord/Server/admin/setup_wizard_test.go
T
Claude 7a4e5dc357 refactor: rename the Go module to github.com/J3vb/OwnCord/Server (RL-13)
`Server/go.mod` declared `github.com/owncord/server` while the public
repository is `github.com/J3vb/OwnCord`. Nothing resolves that path — there is
no `owncord` GitHub org and no vanity-import host serving go-import metadata
for it — so every import line in the tree named a location that does not
exist. It compiles because a main module's own path is never fetched, which is
exactly why it went unnoticed.

The obvious fix — an AST-aware import rewriter (`gomvpkg`, `go mod edit`) —
is wrong here, and provably so. Six of the 722 occurrences are not imports at
all: `api/main_test.go:20` (a goleak `IgnoreTopFunction` pattern),
`telemetry/metrics.go:17-19` (three OTel instrumentation-scope names),
`invariants/syncutil_locks.go:73` (a diagnostic message), and
`invariants/syncutil_locks_test.go:56` (an import line inside a raw-string Go
fixture). An import rewriter touches none of them, and the compiler cannot
see any of them either.

Done as one scripted substitution over `git ls-files`, anchored on the full
`github.com/owncord/server` string. The anchor matters: `owncord-server` is a
different identifier — the OTel `service.name` (`config/config.go`,
`telemetry/telemetry_otel.go`) and the GHCR image name
(`.github/workflows/release.yml`, `docker-compose.yml`) — and a looser pattern
would have moved it. It is untouched: 10 occurrences across 9 files, before
and after.

350 files, 728 insertions, 728 deletions. 722 occurrences in 344 Go files,
plus `go.mod:1`, the `sed` at `Makefile:67`, `Server/CLAUDE.md:3`,
`docs/architecture/server.md:5`, and the ledger pair
(`findings-ledger.json:3758` plus a `render-ledger.mjs` re-render of
`FINDINGS.md`). Zero in any workflow, zero in the Dockerfile, zero in
`Server/.golangci.yml` (no `local-prefixes`, `gci`, `importas` or `depguard`
rule keys on the module path, so import grouping is not configured anywhere).

The plan's blast-radius estimate missed one thing, and it is the one that
would have gone red: **gofmt**. `J` (0x4A) sorts before every lowercase
letter, so in the 36 files where a module-local import shares a contiguous
group with a third-party one, the module's imports must move above
`github.com/go-chi/...`. `gofmt -l` was clean before the substitution and
listed exactly 36 files after it; `gofmt -w` on those 36 restores it to
clean. `gofmt` is an enforced gate — the `formatters` block in
`Server/.golangci.yml`, which is S-05 — so a substitution-only commit fails
Lint.

Verified: both directions, and the line accounting is exact. Every added line
in this diff contains the new module path (728) and every removed line
contains the old one (728); the count of changed lines containing neither is
**zero**, so the gofmt re-sort moved module-path lines only and touched no
third-party import. The residual check
(`git ls-files -z | xargs -0 grep -n 'github\.com/owncord/server'`) returns
exactly two hits, both deliberately out of scope: the RL-13 row in
`docs/audit-2026-08-23-repository-layout.md` and the measurement row in this
phase's own plan. The compiler-invisible half was proven by reverting *only*
`api/main_test.go:20` to the old path on the otherwise-renamed tree:
`go build ./...` and `go vet ./api/` both still pass — they see nothing wrong
— while `go test ./api/` FAILS, because the runtime function name now carries
the new path and goleak stops ignoring `ws.(*Hub).Run.func1`. Restoring the
line makes it pass. `go.sum` is byte-identical (no `go mod tidy` was run and
none was needed). All four build-tag variants compile; `go vet ./...`,
`go vet -tags otel,wazero ./...` and `go vet -tags deadlock ./...` pass;
`go test -race ./...` is 16/16 packages green; `go test -tags deadlock ./...`
passes; the tag-gated `./plugin/...` (wazero) and `./telemetry/...` (otel)
runs pass. `golangci-lint` v2.11.3 — the pinned CI version, rebuilt locally
against Go 1.26 because the packaged binary cannot load a 1.26 config —
reports **0 issues**. `go run ./cmd/genprotocol` leaves
`git diff --exit-code ws/message_types.go ../Client/src/lib/protocolTypes.ts`
clean, so the rename does not reach the generated protocol constants.
`npx prettier --check .` and `node .superpowers/render-ledger.mjs --check`
pass.

Not included: `docs/audit-2026-08-23-repository-layout.md` and
`docs/plans/b1-repository-foundation-2026-08-25.md` keep the old path — they
are the audit row and the measurement that motivated this change, and
rewriting them would erase the record of what was measured. They are why the
residual check needs a two-path allowance rather than being empty; that
allowance is stated above rather than hidden in a pathspec.
`telemetry/metrics.go:19` declares `scopeVoice` for a `Server/voice` package
that does not exist; the substitution carried the dead path forward verbatim
as `github.com/J3vb/OwnCord/Server/voice` rather than fixing it, because
correcting a real observability bug inside a mechanical rename would hide it
in a 350-file diff. It needs its own item. No `go.work`, no second module,
and no vanity-import host was set up — the new path resolves against the real
repository, but nothing imports this module as a library, so `go get`
reachability was not exercised either way.

Refs RL-13, L-12
2026-08-26 20:23:49 +00:00

469 lines
16 KiB
Go

package admin_test
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/J3vb/OwnCord/Server/admin"
"github.com/J3vb/OwnCord/Server/config"
"github.com/J3vb/OwnCord/Server/db"
)
// wizardRunningCfg mimics the config a fresh server boots with: file defaults
// plus the runtime-generated LiveKit credentials.
func wizardRunningCfg() *config.Config {
return &config.Config{
Server: config.ServerConfig{Port: 8443, Name: "OwnCord Server"},
TLS: config.TLSConfig{Mode: "self_signed"},
Upload: config.UploadConfig{MaxSizeMB: 100},
Voice: config.VoiceConfig{
LiveKitAPIKey: "key-generated123",
LiveKitAPISecret: "generated-secret-0123456789abcdef",
Quality: "medium",
},
}
}
// wizardHandler builds the admin API with wizard options and a restart stub
// that signals restarted (buffered) instead of restarting the process. A
// wizard run that triggers a restart leaves the process-global
// restart-serialization guard in restart-pending, so it is reset after every
// wizard test.
func wizardHandler(t *testing.T, database *db.DB, cfgPath string, restarted chan string) http.Handler {
t.Helper()
t.Cleanup(admin.ResetRestartState)
return admin.NewAdminAPI(database, "1.0.0", nil, nil, nil, nil, nil, newTestModService(database), newTestRoleService(database),
admin.SetupOptions{
ConfigPath: cfgPath,
RunningCfg: wizardRunningCfg(),
Restart: func(reason string) { restarted <- reason },
})
}
func getSetting(t *testing.T, database *db.DB, key string) string {
t.Helper()
v, err := database.GetSetting(context.Background(), key)
if err != nil {
t.Fatalf("GetSetting(%q): %v", key, err)
}
return v
}
func TestSetupWizard_FullFlow(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "POST", "/setup", "", map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": map[string]any{
"server_name": "My Cool Server",
"motd": "Welcome friends!",
"registration_open": true,
"port": 9000,
"tls_mode": "off",
"upload_max_size_mb": 250,
"voice_quality": "high",
"voice_auto_download": true,
},
})
if rr.Code != http.StatusCreated {
t.Fatalf("POST /setup = %d, want 201; body=%s", rr.Code, rr.Body.String())
}
var resp struct {
Token string `json:"token"`
InviteCode string `json:"invite_code"`
RestartRequired bool `json:"restart_required"`
RestartURL string `json:"restart_url"`
Warnings []string `json:"warnings"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Token == "" || resp.InviteCode == "" {
t.Error("token/invite_code missing — account creation should be unchanged")
}
if len(resp.Warnings) != 0 {
t.Errorf("warnings = %v, want none", resp.Warnings)
}
if !resp.RestartRequired {
t.Fatal("restart_required = false, want true (port and tls changed)")
}
// httptest requests carry Host "example.com"; tls off → http scheme.
if resp.RestartURL != "http://example.com:9000/admin" {
t.Errorf("restart_url = %q, want %q", resp.RestartURL, "http://example.com:9000/admin")
}
select {
case reason := <-restarted:
if reason != "setup_wizard" {
t.Errorf("restart reason = %q, want setup_wizard", reason)
}
case <-time.After(5 * time.Second):
t.Fatal("restart hook was never invoked")
}
// DB settings the app reads live.
if got := getSetting(t, database, "server_name"); got != "My Cool Server" {
t.Errorf("server_name = %q", got)
}
if got := getSetting(t, database, "motd"); got != "Welcome friends!" {
t.Errorf("motd = %q", got)
}
if got := getSetting(t, database, "registration_open"); got != "1" {
t.Errorf("registration_open = %q, want 1", got)
}
if got := getSetting(t, database, "max_upload_bytes"); got != "262144000" {
t.Errorf("max_upload_bytes = %q, want 262144000 (250 MB)", got)
}
if got := getSetting(t, database, "voice_quality"); got != "high" {
t.Errorf("voice_quality = %q, want high", got)
}
// config.yaml written with the wizard values + persisted voice creds.
cfg, err := config.Load(cfgPath)
if err != nil {
t.Fatalf("loading wizard-written config: %v", err)
}
if cfg.Server.Port != 9000 {
t.Errorf("config port = %d, want 9000", cfg.Server.Port)
}
if cfg.Server.Name != "My Cool Server" {
t.Errorf("config server name = %q", cfg.Server.Name)
}
if cfg.TLS.Mode != "off" {
t.Errorf("config tls mode = %q, want off", cfg.TLS.Mode)
}
if cfg.Upload.MaxSizeMB != 250 {
t.Errorf("config upload max = %d, want 250", cfg.Upload.MaxSizeMB)
}
if cfg.Voice.Quality != "high" {
t.Errorf("config voice quality = %q, want high", cfg.Voice.Quality)
}
if cfg.Voice.LiveKitAPIKey != "key-generated123" {
t.Errorf("LiveKit key = %q — the running credentials were not persisted", cfg.Voice.LiveKitAPIKey)
}
if cfg.Voice.LiveKitAPISecret != "generated-secret-0123456789abcdef" {
t.Errorf("LiveKit secret = %q — the running credentials were not persisted", cfg.Voice.LiveKitAPISecret)
}
if !cfg.Voice.AutoDownloadLiveKit {
t.Error("config voice.auto_download_livekit = false, want true from wizard toggle")
}
}
func TestSetupWizard_NoRestartWhenValuesMatchRunning(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
// Same port/tls/upload/voice as the running config; only live-read
// values (name, motd) change.
rr := doRequest(t, handler, "POST", "/setup", "", map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": map[string]any{
"server_name": "Renamed Server",
"motd": "hi",
"port": 8443,
"tls_mode": "self_signed",
"upload_max_size_mb": 100,
"voice_quality": "medium",
},
})
if rr.Code != http.StatusCreated {
t.Fatalf("POST /setup = %d, want 201; body=%s", rr.Code, rr.Body.String())
}
var resp struct {
RestartRequired bool `json:"restart_required"`
RestartURL string `json:"restart_url"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.RestartRequired {
t.Error("restart_required = true, want false (no startup-only value changed)")
}
if resp.RestartURL != "" {
t.Errorf("restart_url = %q, want empty", resp.RestartURL)
}
select {
case <-restarted:
t.Error("restart hook invoked though nothing needed a restart")
case <-time.After(100 * time.Millisecond):
}
// Config is still written (server.name changed on disk).
cfg, err := config.Load(cfgPath)
if err != nil {
t.Fatalf("loading wizard-written config: %v", err)
}
if cfg.Server.Name != "Renamed Server" {
t.Errorf("config server name = %q, want Renamed Server", cfg.Server.Name)
}
}
// TestSetupWizard_IdentityFieldsStoredRawNotEscaped pins OC-0173: the wizard
// must store server_name/motd the same way handlePatchSettings does later
// (raw survivors, not HTML-entity-escaped), so a name set at first run and
// the identical name set afterwards through the admin Settings page produce
// the same stored value. Before the fix, wizardValidateIdentity ran these
// fields through the bare bluemonday sanitizer, which HTML-escapes
// survivors (' -> &#39;, " -> &#34;, & -> &amp;) — see service.SanitizeText's
// doc comment, which the setup_handler.go username path already follows for
// exactly this reason.
func TestSetupWizard_IdentityFieldsStoredRawNotEscaped(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "POST", "/setup", "", map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": map[string]any{
"server_name": "Bob's Place",
"motd": `Say "hi" & relax`,
},
})
if rr.Code != http.StatusCreated {
t.Fatalf("POST /setup = %d, want 201; body=%s", rr.Code, rr.Body.String())
}
if got, want := getSetting(t, database, "server_name"), "Bob's Place"; got != want {
t.Errorf("server_name = %q, want %q (stored HTML-escaped instead of raw)", got, want)
}
if got, want := getSetting(t, database, "motd"), `Say "hi" & relax`; got != want {
t.Errorf("motd = %q, want %q (stored HTML-escaped instead of raw)", got, want)
}
}
func TestSetupWizard_InvalidValuesRejectBeforeAccountCreation(t *testing.T) {
cases := map[string]map[string]any{
"port too low": {"port": 0},
"port too high": {"port": 70000},
"bad tls mode": {"tls_mode": "quantum"},
"acme without domain": {"tls_mode": "acme"},
"bad domain chars": {"tls_mode": "acme", "tls_domain": "not a domain!"},
"single-label domain": {"tls_mode": "acme", "tls_domain": "localhost"},
"upload zero": {"upload_max_size_mb": 0},
"upload too large": {"upload_max_size_mb": 20000},
"bad voice quality": {"voice_quality": "ultra"},
"empty server name": {"server_name": " "},
"tag-only server name": {"server_name": "<b></b>"},
}
for name, wizard := range cases {
t.Run(name, func(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "POST", "/setup", "", map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": wizard,
})
if rr.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body=%s", rr.Code, rr.Body.String())
}
count, err := database.UserCount(context.Background())
if err != nil {
t.Fatalf("UserCount: %v", err)
}
if count != 0 {
t.Errorf("user count = %d, want 0 — invalid wizard payload must reject before account creation", count)
}
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
t.Error("config file written despite rejected payload")
}
})
}
}
func TestSetupWizard_ConfigWriteFailureWarnsButCreatesAccount(t *testing.T) {
database := openAdminTestDB(t)
// Point at a directory that does not exist so the atomic write fails.
cfgPath := filepath.Join(t.TempDir(), "missing-dir", "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "POST", "/setup", "", map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": map[string]any{"port": 9000},
})
if rr.Code != http.StatusCreated {
t.Fatalf("POST /setup = %d, want 201 despite config failure; body=%s", rr.Code, rr.Body.String())
}
var resp struct {
Token string `json:"token"`
RestartRequired bool `json:"restart_required"`
Warnings []string `json:"warnings"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Token == "" {
t.Error("token missing — the account must still be created")
}
if len(resp.Warnings) == 0 {
t.Error("warnings empty, want a config-write warning")
}
if resp.RestartRequired {
t.Error("restart_required = true, but the config was never written — restarting would change nothing")
}
select {
case <-restarted:
t.Error("restart hook invoked after a failed config write")
case <-time.After(100 * time.Millisecond):
}
count, err := database.UserCount(context.Background())
if err != nil {
t.Fatalf("UserCount: %v", err)
}
if count != 1 {
t.Errorf("user count = %d, want 1", count)
}
}
func TestSetupWizard_LegacyPayloadUnchangedBehaviour(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "POST", "/setup", "", map[string]string{
"username": "owner",
"password": "SecurePass123!",
})
if rr.Code != http.StatusCreated {
t.Fatalf("legacy POST /setup = %d, want 201; body=%s", rr.Code, rr.Body.String())
}
var resp struct {
RestartRequired bool `json:"restart_required"`
Warnings []string `json:"warnings"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.RestartRequired || len(resp.Warnings) != 0 {
t.Error("legacy payload must not trigger restarts or warnings")
}
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
t.Error("legacy payload must not write config.yaml")
}
select {
case <-restarted:
t.Error("legacy payload must not restart the server")
case <-time.After(100 * time.Millisecond):
}
}
func TestSetupStatus_DefaultsOnlyPreSetupAndSecretFree(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
rr := doRequest(t, handler, "GET", "/setup/status", "", nil)
if rr.Code != http.StatusOK {
t.Fatalf("GET /setup/status = %d, want 200", rr.Code)
}
var resp struct {
NeedsSetup bool `json:"needs_setup"`
Defaults *struct {
ServerName string `json:"server_name"`
Motd string `json:"motd"`
Port int `json:"port"`
TLSMode string `json:"tls_mode"`
UploadMaxSizeMB int `json:"upload_max_size_mb"`
VoiceQuality string `json:"voice_quality"`
} `json:"defaults"`
}
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if !resp.NeedsSetup || resp.Defaults == nil {
t.Fatalf("pre-setup status should carry defaults; body=%s", rr.Body.String())
}
// server_name/motd come from the seeded settings table, the rest from the
// running config.
if resp.Defaults.ServerName != "Test Server" {
t.Errorf("defaults.server_name = %q, want Test Server (DB value)", resp.Defaults.ServerName)
}
if resp.Defaults.Motd != "Hello" {
t.Errorf("defaults.motd = %q, want Hello (DB value)", resp.Defaults.Motd)
}
if resp.Defaults.Port != 8443 || resp.Defaults.TLSMode != "self_signed" ||
resp.Defaults.UploadMaxSizeMB != 100 || resp.Defaults.VoiceQuality != "medium" {
t.Errorf("config-derived defaults wrong: %+v", resp.Defaults)
}
// Never leak credentials through the unauthenticated status endpoint.
lower := strings.ToLower(rr.Body.String())
for _, needle := range []string{"livekit", "secret", "api_key", "token", "cidr"} {
if strings.Contains(lower, needle) {
t.Errorf("status response leaks %q: %s", needle, rr.Body.String())
}
}
// After setup completes, defaults disappear along with needs_setup.
rr2 := doRequest(t, handler, "POST", "/setup", "", map[string]string{
"username": "owner", "password": "SecurePass123!",
})
if rr2.Code != http.StatusCreated {
t.Fatalf("setup = %d, want 201", rr2.Code)
}
rr3 := doRequest(t, handler, "GET", "/setup/status", "", nil)
if !strings.Contains(rr3.Body.String(), `"needs_setup":false`) {
t.Errorf("post-setup status = %s, want needs_setup false", rr3.Body.String())
}
if strings.Contains(rr3.Body.String(), "defaults") {
t.Errorf("post-setup status still exposes defaults: %s", rr3.Body.String())
}
}
func TestSetupWizard_ForeignOriginBlocked(t *testing.T) {
database := openAdminTestDB(t)
cfgPath := filepath.Join(t.TempDir(), "config.yaml")
restarted := make(chan string, 1)
handler := wizardHandler(t, database, cfgPath, restarted)
body := map[string]any{
"username": "owner",
"password": "SecurePass123!",
"wizard": map[string]any{"port": 9000},
}
raw, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal: %v", err)
}
req := httptest.NewRequest("POST", "/setup", bytes.NewReader(raw))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", "https://evil.example")
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusForbidden {
t.Fatalf("wizard POST from foreign origin = %d, want 403", rr.Code)
}
if _, err := os.Stat(cfgPath); !os.IsNotExist(err) {
t.Error("config file written from a cross-origin request")
}
}