package equipotest import ( "context" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "os" "os/exec" "path/filepath" "reflect" "regexp" "sort" "strconv" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/testci" "amadan.net/rastrillo/rastrillo/db" "amadan.net/rastrillo/rastrillo/mail" "amadan.net/rastrillo/rastrillo/migrate" ) func foundationDB(t *testing.T) (*db.DB, *slog.Logger) { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "equipo.db"), logger) if err != nil { t.Fatal(err) } t.Cleanup(func() { if err := d.Close(); err != nil { t.Error(err) } }) return d, logger } func TestFoundationFailsClosed(t *testing.T) { base := map[string]string{ "EQUIPO_ORIGIN": "https://equipo.example.com", "EQUIPO_INSTANCE_KEY": "test-instance-key", "CARLOS_SMTP_HOST": "smtp.example.com", "CARLOS_SMTP_FROM": "equipo@example.com", } for _, tc := range []struct { name string overrides map[string]string }{ {"empty key", map[string]string{"EQUIPO_INSTANCE_KEY": ""}}, {"blank key", map[string]string{"EQUIPO_INSTANCE_KEY": " "}}, {"missing origin", map[string]string{"EQUIPO_ORIGIN": ""}}, {"relative origin", map[string]string{"EQUIPO_ORIGIN": "/equipo"}}, {"invalid origin", map[string]string{"EQUIPO_ORIGIN": "://broken"}}, {"origin path", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com/private"}}, {"origin credentials", map[string]string{"EQUIPO_ORIGIN": "https://user:pass@equipo.example.com"}}, {"origin query", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com?x=1"}}, {"origin fragment", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com#x"}}, {"insecure public origin", map[string]string{"EQUIPO_ORIGIN": "http://equipo.example.com"}}, {"SMTP host missing", map[string]string{"CARLOS_SMTP_HOST": ""}}, {"SMTP from missing", map[string]string{"CARLOS_SMTP_FROM": ""}}, {"SMTP missing", map[string]string{"CARLOS_SMTP_HOST": "", "CARLOS_SMTP_FROM": ""}}, {"public logged mail", map[string]string{"EQUIPO_ALLOW_LOGGED_MAIL": "1"}}, {"localhost suffix", map[string]string{"EQUIPO_ORIGIN": "http://localhost.example.com", "EQUIPO_ALLOW_LOGGED_MAIL": "1"}}, } { t.Run(tc.name, func(t *testing.T) { _, err := equipo.LoadConfig(func(k string) string { if v, ok := tc.overrides[k]; ok { return v } return base[k] }) if err == nil { t.Fatal("missing production configuration accepted") } }) } t.Run("valid without owners", func(t *testing.T) { cfg, err := equipo.LoadConfig(func(k string) string { return base[k] }) if err != nil { t.Fatal(err) } if len(cfg.Owners) != 0 { t.Fatalf("unexpected owners: %v", cfg.Owners) } }) for _, origin := range []string{"http://127.0.0.1:8080", "http://localhost:8080", "http://[::1]:8080"} { t.Run("local "+origin, func(t *testing.T) { _, err := equipo.LoadConfig(func(k string) string { return map[string]string{ "EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_KEY": "test-key", "EQUIPO_ALLOW_LOGGED_MAIL": "1", }[k] }) if err != nil { t.Fatal(err) } }) } t.Run("private routes", func(t *testing.T) { d, logger := foundationDB(t) mux, err := equipo.App(d, equipo.Config{Origin: "http://127.0.0.1:8080", InstanceKey: "test-key", AllowLoggedMail: true, Owners: []string{ownerAddress}}, mail.Logged(logger), logger) if err != nil { t.Fatal(err) } for _, path := range []string{"/", "/conversation", "/work", "/projects", "/people", "/settings"} { response := httptest.NewRecorder() mux.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil)) if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/signin?return_to="+url.QueryEscape(path) { t.Errorf("%s: private page served before auth: status %d", path, response.Code) } } }) t.Run("direct construction", func(t *testing.T) { d, logger := foundationDB(t) for _, cfg := range []equipo.Config{ {}, {Origin: "http://127.0.0.1", AllowLoggedMail: true}, {Origin: "https://equipo.example.com", InstanceKey: "test-key", AllowLoggedMail: true}, {Origin: "https://equipo.example.com", InstanceKey: "test-key"}, } { if _, err := equipo.App(d, cfg, mail.Logged(logger), logger); err == nil { t.Errorf("unsafe direct config accepted: %+v", cfg) } } if _, err := equipo.App(d, equipo.Config{Origin: "https://equipo.example.com", InstanceKey: "test-key"}, nil, logger); err == nil { t.Error("nil mailer accepted") } }) } func TestFoundationMigratesTwice(t *testing.T) { d, _ := foundationDB(t) first, err := migrate.Apply(context.Background(), d, equipo.BootSchema) if err != nil { t.Fatal(err) } if len(first.Applied) == 0 { t.Fatal("no boot migrations applied") } _, err = d.Writer().Exec(`INSERT INTO sessions (token_hash, subject, created_at, expires_at) VALUES (?, ?, ?, ?)`, "test-hash", "owner@example.com", "2026-11-01", "2026-11-02") if err != nil { t.Fatal(err) } second, err := migrate.Apply(context.Background(), d, equipo.BootSchema) if err != nil { t.Fatal(err) } if len(second.Applied) != 0 { t.Fatal("migration repeated on second boot") } var subject string if err := d.Writer().QueryRow(`SELECT subject FROM sessions WHERE token_hash = ?`, "test-hash").Scan(&subject); err != nil { t.Fatal(err) } if subject != "owner@example.com" { t.Fatalf("row changed: %q", subject) } var notes int if err := d.Writer().QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'notes'`).Scan(¬es); err != nil { t.Fatal(err) } if notes != 0 { t.Fatal("example Note table shipped") } } // Mutation check: remove build from ci and a wrapper, one at a time; // each must fail. Executing with a fake make also checks shell behavior. // // The steps run through scripts/ci-box.py, which on a hosted CI machine // puts the command in the CI box. EQUIPO_CI_BOX=off runs it directly, as // on a runner host, so the fake make sees what each step asks for. func TestCIGateSteps(t *testing.T) { root := filepath.Join("..", "..") want := []string{"copy-release-check", "build", "vet", "fmt-check", "spacing", "staticcheck", "govulncheck", "gitleaks", "budget", "test", "test-quarantine", "runner-host", "runner-dead-references", "lanes-check", "migration-check", "perf"} sort.Strings(want) // The step scripts run outside this process; their bytes are inputs. testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"), filepath.Join(root, "scripts", "ci-box.py")) contents, err := os.ReadFile(filepath.Join(root, "Makefile")) if err != nil { t.Fatal(err) } var targets []string for _, line := range strings.Split(string(contents), "\n") { if strings.HasPrefix(line, "ci:") { targets = append(targets, strings.Fields(strings.TrimPrefix(line, "ci:"))...) } } sort.Strings(targets) if !reflect.DeepEqual(targets, want) { t.Errorf("make ci targets = %v, want %v", targets, want) } // The shards after the lanes, as ci-test.py lists them: one line of // make targets each. script, err := os.ReadFile(filepath.Join(root, "scripts", "ci-test.py")) if err != nil { t.Fatal(err) } extra := regexp.MustCompile(`(?s)\nEXTRA_SHARDS = \[\n(.*?)\n\]\n`).FindSubmatch(script) if extra == nil { t.Fatal("scripts/ci-test.py has no EXTRA_SHARDS list") } extraLines := strings.Split(string(extra[1]), "\n") extraTargets := strings.Fields(strings.NewReplacer(`"`, "", ",", " ", "[", "", "]", "").Replace(string(extra[1]))) lanes := strings.Count(string(script), "\n (\"") bin := t.TempDir() if err := os.WriteFile(filepath.Join(bin, "make"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0755); err != nil { t.Fatal(err) } run := func(path string) []string { t.Helper() info, err := os.Stat(path) if err != nil { t.Fatal(err) } if info.Mode().Perm()&0111 == 0 { t.Errorf("%s is not executable", path) } cmd := exec.Command(path) cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"), "EQUIPO_CI_BOX=off") out, err := cmd.CombinedOutput() if err != nil { t.Fatalf("%s: %v: %s", path, err, out) } return strings.Fields(string(out)) } if got := run(filepath.Join(root, ".amadan", "ci")); !reflect.DeepEqual(got, []string{"ci"}) { t.Errorf("CI wrapper = %v", got) } paths, err := filepath.Glob(filepath.Join(root, ".amadan", "ci.d", "*")) if err != nil { t.Fatal(err) } var steps []string for _, path := range paths { _, shards, _ := strings.Cut(filepath.Base(path), "@") for _, target := range run(path) { if target == "ci-compile" { continue // fills the build cache for the shards; checks nothing itself } if target != "ci-shard" { steps = append(steps, target) continue } // CI runs make test as its lanes, then the extra shards. if want := strconv.Itoa(lanes + len(extraLines)); shards != want { t.Errorf("%s: %d lanes and %d extra shards need @%s", path, lanes, len(extraLines), want) } steps = append(steps, "test") steps = append(steps, extraTargets...) } } sort.Strings(steps) if !reflect.DeepEqual(steps, want) { t.Errorf("CI step targets = %v, want %v", steps, want) } }