oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "context"
5 "io"
6 "log/slog"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "os"
11 "os/exec"
12 "path/filepath"
13 "reflect"
14 "regexp"
15 "sort"
16 "strconv"
17 "strings"
18 "testing"
19
20 "amadan.net/oficina/equipo/internal/equipo"
21 "amadan.net/oficina/equipo/internal/testci"
22 "amadan.net/rastrillo/rastrillo/db"
23 "amadan.net/rastrillo/rastrillo/mail"
24 "amadan.net/rastrillo/rastrillo/migrate"
25)
26
27func foundationDB(t *testing.T) (*db.DB, *slog.Logger) {
28 t.Helper()
29 logger := slog.New(slog.NewTextHandler(io.Discard, nil))
30 d, err := db.Open(filepath.Join(t.TempDir(), "equipo.db"), logger)
31 if err != nil {
32 t.Fatal(err)
33 }
34 t.Cleanup(func() {
35 if err := d.Close(); err != nil {
36 t.Error(err)
37 }
38 })
39 return d, logger
40}
41
42func TestFoundationFailsClosed(t *testing.T) {
43 base := map[string]string{
44 "EQUIPO_ORIGIN": "https://equipo.example.com",
45 "EQUIPO_INSTANCE_KEY": "test-instance-key",
46 "CARLOS_SMTP_HOST": "smtp.example.com",
47 "CARLOS_SMTP_FROM": "equipo@example.com",
48 }
49 for _, tc := range []struct {
50 name string
51 overrides map[string]string
52 }{
53 {"empty key", map[string]string{"EQUIPO_INSTANCE_KEY": ""}},
54 {"blank key", map[string]string{"EQUIPO_INSTANCE_KEY": " "}},
55 {"missing origin", map[string]string{"EQUIPO_ORIGIN": ""}},
56 {"relative origin", map[string]string{"EQUIPO_ORIGIN": "/equipo"}},
57 {"invalid origin", map[string]string{"EQUIPO_ORIGIN": "://broken"}},
58 {"origin path", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com/private"}},
59 {"origin credentials", map[string]string{"EQUIPO_ORIGIN": "https://user:pass@equipo.example.com"}},
60 {"origin query", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com?x=1"}},
61 {"origin fragment", map[string]string{"EQUIPO_ORIGIN": "https://equipo.example.com#x"}},
62 {"insecure public origin", map[string]string{"EQUIPO_ORIGIN": "http://equipo.example.com"}},
63 {"SMTP host missing", map[string]string{"CARLOS_SMTP_HOST": ""}},
64 {"SMTP from missing", map[string]string{"CARLOS_SMTP_FROM": ""}},
65 {"SMTP missing", map[string]string{"CARLOS_SMTP_HOST": "", "CARLOS_SMTP_FROM": ""}},
66 {"public logged mail", map[string]string{"EQUIPO_ALLOW_LOGGED_MAIL": "1"}},
67 {"localhost suffix", map[string]string{"EQUIPO_ORIGIN": "http://localhost.example.com", "EQUIPO_ALLOW_LOGGED_MAIL": "1"}},
68 } {
69 t.Run(tc.name, func(t *testing.T) {
70 _, err := equipo.LoadConfig(func(k string) string {
71 if v, ok := tc.overrides[k]; ok {
72 return v
73 }
74 return base[k]
75 })
76 if err == nil {
77 t.Fatal("missing production configuration accepted")
78 }
79 })
80 }
81 t.Run("valid without owners", func(t *testing.T) {
82 cfg, err := equipo.LoadConfig(func(k string) string { return base[k] })
83 if err != nil {
84 t.Fatal(err)
85 }
86 if len(cfg.Owners) != 0 {
87 t.Fatalf("unexpected owners: %v", cfg.Owners)
88 }
89 })
90 for _, origin := range []string{"http://127.0.0.1:8080", "http://localhost:8080", "http://[::1]:8080"} {
91 t.Run("local "+origin, func(t *testing.T) {
92 _, err := equipo.LoadConfig(func(k string) string {
93 return map[string]string{
94 "EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_KEY": "test-key", "EQUIPO_ALLOW_LOGGED_MAIL": "1",
95 }[k]
96 })
97 if err != nil {
98 t.Fatal(err)
99 }
100 })
101 }
102 t.Run("private routes", func(t *testing.T) {
103 d, logger := foundationDB(t)
104 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)
105 if err != nil {
106 t.Fatal(err)
107 }
108 for _, path := range []string{"/", "/conversation", "/work", "/projects", "/people", "/settings"} {
109 response := httptest.NewRecorder()
110 mux.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
111 if response.Code != http.StatusSeeOther || response.Header().Get("Location") != "/signin?return_to="+url.QueryEscape(path) {
112 t.Errorf("%s: private page served before auth: status %d", path, response.Code)
113 }
114 }
115 })
116 t.Run("direct construction", func(t *testing.T) {
117 d, logger := foundationDB(t)
118 for _, cfg := range []equipo.Config{
119 {},
120 {Origin: "http://127.0.0.1", AllowLoggedMail: true},
121 {Origin: "https://equipo.example.com", InstanceKey: "test-key", AllowLoggedMail: true},
122 {Origin: "https://equipo.example.com", InstanceKey: "test-key"},
123 } {
124 if _, err := equipo.App(d, cfg, mail.Logged(logger), logger); err == nil {
125 t.Errorf("unsafe direct config accepted: %+v", cfg)
126 }
127 }
128 if _, err := equipo.App(d, equipo.Config{Origin: "https://equipo.example.com", InstanceKey: "test-key"}, nil, logger); err == nil {
129 t.Error("nil mailer accepted")
130 }
131 })
132}
133
134func TestFoundationMigratesTwice(t *testing.T) {
135 d, _ := foundationDB(t)
136 first, err := migrate.Apply(context.Background(), d, equipo.BootSchema)
137 if err != nil {
138 t.Fatal(err)
139 }
140 if len(first.Applied) == 0 {
141 t.Fatal("no boot migrations applied")
142 }
143 _, 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")
144 if err != nil {
145 t.Fatal(err)
146 }
147 second, err := migrate.Apply(context.Background(), d, equipo.BootSchema)
148 if err != nil {
149 t.Fatal(err)
150 }
151 if len(second.Applied) != 0 {
152 t.Fatal("migration repeated on second boot")
153 }
154 var subject string
155 if err := d.Writer().QueryRow(`SELECT subject FROM sessions WHERE token_hash = ?`, "test-hash").Scan(&subject); err != nil {
156 t.Fatal(err)
157 }
158 if subject != "owner@example.com" {
159 t.Fatalf("row changed: %q", subject)
160 }
161 var notes int
162 if err := d.Writer().QueryRow(`SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = 'notes'`).Scan(&notes); err != nil {
163 t.Fatal(err)
164 }
165 if notes != 0 {
166 t.Fatal("example Note table shipped")
167 }
168}
169
170// Mutation check: remove build from ci and a wrapper, one at a time;
171// each must fail. Executing with a fake make also checks shell behavior.
172//
173// The steps run through scripts/ci-box.py, which on a hosted CI machine
174// puts the command in the CI box. EQUIPO_CI_BOX=off runs it directly, as
175// on a runner host, so the fake make sees what each step asks for.
176func TestCIGateSteps(t *testing.T) {
177 root := filepath.Join("..", "..")
178 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"}
179 sort.Strings(want)
180 // The step scripts run outside this process; their bytes are inputs.
181 testci.Files(t, filepath.Join(root, ".amadan"), filepath.Join(root, "scripts", "ci-test.py"), filepath.Join(root, "scripts", "ci-box.py"))
182 contents, err := os.ReadFile(filepath.Join(root, "Makefile"))
183 if err != nil {
184 t.Fatal(err)
185 }
186 var targets []string
187 for _, line := range strings.Split(string(contents), "\n") {
188 if strings.HasPrefix(line, "ci:") {
189 targets = append(targets, strings.Fields(strings.TrimPrefix(line, "ci:"))...)
190 }
191 }
192 sort.Strings(targets)
193 if !reflect.DeepEqual(targets, want) {
194 t.Errorf("make ci targets = %v, want %v", targets, want)
195 }
196 // The shards after the lanes, as ci-test.py lists them: one line of
197 // make targets each.
198 script, err := os.ReadFile(filepath.Join(root, "scripts", "ci-test.py"))
199 if err != nil {
200 t.Fatal(err)
201 }
202 extra := regexp.MustCompile(`(?s)\nEXTRA_SHARDS = \[\n(.*?)\n\]\n`).FindSubmatch(script)
203 if extra == nil {
204 t.Fatal("scripts/ci-test.py has no EXTRA_SHARDS list")
205 }
206 extraLines := strings.Split(string(extra[1]), "\n")
207 extraTargets := strings.Fields(strings.NewReplacer(`"`, "", ",", " ", "[", "", "]", "").Replace(string(extra[1])))
208 lanes := strings.Count(string(script), "\n (\"")
209 bin := t.TempDir()
210 if err := os.WriteFile(filepath.Join(bin, "make"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0755); err != nil {
211 t.Fatal(err)
212 }
213 run := func(path string) []string {
214 t.Helper()
215 info, err := os.Stat(path)
216 if err != nil {
217 t.Fatal(err)
218 }
219 if info.Mode().Perm()&0111 == 0 {
220 t.Errorf("%s is not executable", path)
221 }
222 cmd := exec.Command(path)
223 cmd.Env = append(os.Environ(), "PATH="+bin+":"+os.Getenv("PATH"), "EQUIPO_CI_BOX=off")
224 out, err := cmd.CombinedOutput()
225 if err != nil {
226 t.Fatalf("%s: %v: %s", path, err, out)
227 }
228 return strings.Fields(string(out))
229 }
230 if got := run(filepath.Join(root, ".amadan", "ci")); !reflect.DeepEqual(got, []string{"ci"}) {
231 t.Errorf("CI wrapper = %v", got)
232 }
233 paths, err := filepath.Glob(filepath.Join(root, ".amadan", "ci.d", "*"))
234 if err != nil {
235 t.Fatal(err)
236 }
237 var steps []string
238 for _, path := range paths {
239 _, shards, _ := strings.Cut(filepath.Base(path), "@")
240 for _, target := range run(path) {
241 if target == "ci-compile" {
242 continue // fills the build cache for the shards; checks nothing itself
243 }
244 if target != "ci-shard" {
245 steps = append(steps, target)
246 continue
247 }
248 // CI runs make test as its lanes, then the extra shards.
249 if want := strconv.Itoa(lanes + len(extraLines)); shards != want {
250 t.Errorf("%s: %d lanes and %d extra shards need @%s", path, lanes, len(extraLines), want)
251 }
252 steps = append(steps, "test")
253 steps = append(steps, extraTargets...)
254 }
255 }
256 sort.Strings(steps)
257 if !reflect.DeepEqual(steps, want) {
258 t.Errorf("CI step targets = %v, want %v", steps, want)
259 }
260}
261