oficina / base Public

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

Plain git — no account needed to clone.

Download

Download this file

1package install
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/base64"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "io"
13 "log/slog"
14 "net/http"
15 "net/http/httptest"
16 "os"
17 "sync/atomic"
18 "testing"
19 "time"
20
21 "amadan.net/rastrillo/rastrillo/budget"
22 "amadan.net/rastrillo/rastrillo/crypto"
23 "amadan.net/rastrillo/rastrillo/dbtest"
24
25 "amadan.net/oficina/base/internal/config"
26 "amadan.net/oficina/base/internal/platform"
27 "amadan.net/oficina/base/internal/store"
28)
29
30var template = dbtest.FromSet(store.BootSchema)
31
32func TestMain(m *testing.M) {
33 code := budget.Main(m)
34 template.Remove()
35 os.Exit(code)
36}
37
38func setup(t *testing.T, probe func(context.Context, string) error) (*Installer, *platform.Fake, *sql.DB, config.Config) {
39 t.Helper()
40 kp, err := crypto.Generate()
41 if err != nil {
42 t.Fatal(err)
43 }
44 cfg := config.Config{Origin: "https://base.example.com", Name: "Acme", Slug: "acme", AppsDomain: "bab.oncarlos.com", AssertionKey: kp}
45 db := template.Open(t)
46 pf := platform.NewFake()
47 if probe == nil {
48 probe = func(context.Context, string) error { return nil }
49 }
50 return New(db, cfg, pf, probe, slog.New(slog.NewTextHandler(io.Discard, nil))), pf, db, cfg
51}
52
53func state(t *testing.T, db *sql.DB, app string) store.Install {
54 t.Helper()
55 all, err := store.Installs(context.Background(), db)
56 if err != nil {
57 t.Fatal(err)
58 }
59 for _, i := range all {
60 if i.App == app {
61 return i
62 }
63 }
64 return store.Install{}
65}
66
67func TestInstallWritesEnvThenCreates(t *testing.T) {
68 in, pf, db, cfg := setup(t, nil)
69 if err := in.Install(context.Background(), "scratchpad"); err != nil {
70 t.Fatal(err)
71 }
72 calls := pf.Calls()
73 if len(calls) != 2 || calls[0].Method != "SetEnv" || calls[1].Method != "CreateInstance" {
74 t.Fatalf("calls = %+v", calls)
75 }
76 label := "acme-scratchpad"
77 kid, pub := KeySet(cfg.AssertionKey)
78 keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)})
79 want := map[string]string{
80 "BASE_APP_ORIGIN": "https://acme-scratchpad.bab.oncarlos.com",
81 "BASE_APP_ISSUER": cfg.Origin,
82 "BASE_APP_CONSUMER_ID": "scratchpad",
83 "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys),
84 }
85 if calls[0].Environment != label || len(calls[0].Vars) != 4 {
86 t.Fatalf("setenv = %+v", calls[0])
87 }
88 for k, v := range want {
89 if calls[0].Vars[k] != v {
90 t.Errorf("%s = %q, want %q", k, calls[0].Vars[k], v)
91 }
92 }
93 if c := calls[1]; c.App != "scratchpad" || c.Host != label+".bab.oncarlos.com" || c.Environment != label {
94 t.Errorf("create = %+v", c)
95 }
96 if s := state(t, db, "scratchpad"); s.State != "installed" || s.Host != label+".bab.oncarlos.com" {
97 t.Errorf("row = %+v", s)
98 }
99}
100
101func TestKeySetIsHexSHA256OfSignPub(t *testing.T) {
102 kp, _ := crypto.Generate()
103 sum := sha256.Sum256(kp.SignPub())
104 kid, pub := KeySet(kp)
105 if kid != hex.EncodeToString(sum[:]) || !bytes.Equal(pub, kp.SignPub()) || len(pub) != 65 {
106 t.Fatalf("kid %q pub %x", kid, pub)
107 }
108}
109
110func TestInstallTwiceIsOneInstance(t *testing.T) {
111 entered := make(chan struct{}, 2)
112 gate := make(chan struct{})
113 in, pf, _, _ := setup(t, func(context.Context, string) error { entered <- struct{}{}; <-gate; return nil })
114 errs := make(chan error, 2)
115 go func() { errs <- in.Install(context.Background(), "scratchpad") }()
116 <-entered // first call is now mid-install
117 go func() { errs <- in.Install(context.Background(), "scratchpad") }()
118 if err := <-errs; err != nil { // the second returns while the first is still held
119 t.Fatalf("second Install: %v", err)
120 }
121 close(gate)
122 if err := <-errs; err != nil {
123 t.Fatalf("first Install: %v", err)
124 }
125 creates := 0
126 for _, c := range pf.Calls() {
127 if c.Method == "CreateInstance" {
128 creates++
129 }
130 }
131 if creates != 1 || len(entered) != 0 {
132 t.Fatalf("creates %d extra probes %d", creates, len(entered))
133 }
134}
135
136func TestInstallCreateRefusedMarksFailed(t *testing.T) {
137 in, pf, db, _ := setup(t, nil)
138 pf.Fail("CreateInstance", errors.New("platform said no: secret body"))
139 if err := in.Install(context.Background(), "scratchpad"); err == nil {
140 t.Error("want an error")
141 }
142 s := state(t, db, "scratchpad")
143 if s.State != "failed" || s.Error == "" {
144 t.Fatalf("row = %+v", s)
145 }
146 pf.Fail("CreateInstance", nil)
147 if err := in.Install(context.Background(), "scratchpad"); err != nil {
148 t.Fatal(err)
149 }
150 if s := state(t, db, "scratchpad"); s.State != "installed" {
151 t.Errorf("after retry: %+v", s)
152 }
153}
154
155func TestInstallNeverAnswersMarksFailed(t *testing.T) {
156 in, _, db, _ := setup(t, func(context.Context, string) error { return context.DeadlineExceeded })
157 _ = in.Install(context.Background(), "scratchpad")
158 if s := state(t, db, "scratchpad"); s.State != "failed" || s.Error == "" {
159 t.Fatalf("row = %+v", s)
160 }
161}
162
163func TestInstallUnknownApp(t *testing.T) {
164 in, pf, _, _ := setup(t, nil)
165 if err := in.Install(context.Background(), "nope"); err == nil {
166 t.Error("want error")
167 }
168 if len(pf.Calls()) != 0 {
169 t.Error("platform called")
170 }
171}
172
173func TestUninstallDeletesInstanceKeepsNothingInBase(t *testing.T) {
174 in, pf, db, _ := setup(t, nil)
175 if err := in.Install(context.Background(), "scratchpad"); err != nil {
176 t.Fatal(err)
177 }
178 if err := in.Uninstall(context.Background(), "scratchpad"); err != nil {
179 t.Fatal(err)
180 }
181 calls := pf.Calls()
182 last := calls[len(calls)-1]
183 if last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" || last.App != "scratchpad" {
184 t.Errorf("last = %+v", last)
185 }
186 if s := state(t, db, "scratchpad"); s.App != "" {
187 t.Errorf("row remains: %+v", s)
188 }
189}
190
191func TestEnsureDefaultsInstallsWelcomeOnce(t *testing.T) {
192 in, pf, db, _ := setup(t, nil)
193 for range 2 {
194 if err := in.EnsureDefaults(context.Background()); err != nil {
195 t.Fatal(err)
196 }
197 }
198 creates := 0
199 for _, c := range pf.Calls() {
200 if c.Method == "CreateInstance" {
201 creates++
202 if c.App != "welcome" {
203 t.Errorf("app = %s", c.App)
204 }
205 }
206 }
207 if creates != 1 {
208 t.Errorf("creates = %d", creates)
209 }
210 if s := state(t, db, "welcome"); s.State != "installed" {
211 t.Errorf("row = %+v", s)
212 }
213 if s := state(t, db, "scratchpad"); s.App != "" {
214 t.Error("scratchpad installed")
215 }
216}
217
218func TestProbeVersion(t *testing.T) {
219 var hits atomic.Int32
220 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
221 if r.URL.Path != "/api/version" {
222 http.NotFound(w, r)
223 return
224 }
225 if hits.Add(1) < 3 {
226 w.WriteHeader(http.StatusBadGateway)
227 return
228 }
229 }))
230 defer srv.Close()
231 p := probeVersion(srv.Client(), 5*time.Millisecond, 2*time.Second)
232 if err := p(context.Background(), srv.URL); err != nil || hits.Load() != 3 {
233 t.Fatalf("err %v hits %d", err, hits.Load())
234 }
235}
236
237func TestProbeVersionGivesUp(t *testing.T) {
238 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(502) }))
239 defer srv.Close()
240 p := probeVersion(srv.Client(), 5*time.Millisecond, 50*time.Millisecond)
241 if err := p(context.Background(), srv.URL); err == nil {
242 t.Fatal("want error")
243 }
244}
245
246// blockingClient pauses CreateInstance until released.
247type blockingClient struct {
248 platform.Client
249 entered chan struct{}
250 release chan struct{}
251}
252
253func (b *blockingClient) CreateInstance(ctx context.Context, app, host, env string) error {
254 b.entered <- struct{}{}
255 <-b.release
256 return b.Client.CreateInstance(ctx, app, host, env)
257}
258
259func TestUninstallRefusedWhileInstalling(t *testing.T) {
260 in, pf, db, _ := setup(t, nil)
261 bc := &blockingClient{Client: pf, entered: make(chan struct{}), release: make(chan struct{})}
262 in.pc = bc
263 done := make(chan error, 1)
264 go func() { done <- in.Install(context.Background(), "scratchpad") }()
265 <-bc.entered
266 if err := in.Uninstall(context.Background(), "scratchpad"); !errors.Is(err, ErrBusy) {
267 t.Fatalf("Uninstall = %v, want ErrBusy", err)
268 }
269 for _, c := range pf.Calls() {
270 if c.Method == "DeleteInstance" {
271 t.Fatal("DeleteInstance called while installing")
272 }
273 }
274 close(bc.release)
275 if err := <-done; err != nil {
276 t.Fatal(err)
277 }
278 if s := state(t, db, "scratchpad"); s.State != "installed" {
279 t.Errorf("row = %+v", s)
280 }
281}
282
283func TestInstallFinalStateSurvivesCancelledContext(t *testing.T) {
284 ctx, cancel := context.WithCancel(context.Background())
285 in, _, db, _ := setup(t, func(context.Context, string) error { cancel(); return nil })
286 if err := in.Install(ctx, "scratchpad"); err != nil {
287 t.Fatal(err)
288 }
289 if s := state(t, db, "scratchpad"); s.State != "installed" {
290 t.Errorf("row = %+v", s)
291 }
292}
293
294func TestInstallFailsWhenRowVanishes(t *testing.T) {
295 var in *Installer
296 var db *sql.DB
297 in, _, db, _ = setup(t, nil)
298 in.probe = func(ctx context.Context, _ string) error {
299 _, err := db.ExecContext(ctx, `DELETE FROM installs`)
300 return err
301 }
302 if err := in.Install(context.Background(), "scratchpad"); err == nil {
303 t.Fatal("want an error when the row is gone")
304 }
305}
306
307func TestUninstallMissingRowMakesNoPlatformCall(t *testing.T) {
308 in, pf, _, _ := setup(t, nil)
309 if err := in.Uninstall(context.Background(), "scratchpad"); !errors.Is(err, store.ErrNoInstall) {
310 t.Fatalf("Uninstall = %v, want ErrNoInstall", err)
311 }
312 if len(pf.Calls()) != 0 {
313 t.Fatalf("calls = %+v", pf.Calls())
314 }
315}
316
317func TestUninstallRefusedWhileReinstallingFailedRow(t *testing.T) {
318 in, pf, db, _ := setup(t, nil)
319 ctx := context.Background()
320 if ok, err := store.ClaimInstall(ctx, db, "scratchpad", "acme-scratchpad.bab.oncarlos.com"); err != nil || !ok {
321 t.Fatal(ok, err)
322 }
323 if err := store.SetInstallState(ctx, db, "scratchpad", "failed", "x"); err != nil {
324 t.Fatal(err)
325 }
326 bc := &blockingClient{Client: pf, entered: make(chan struct{}), release: make(chan struct{})}
327 in.pc = bc
328 done := make(chan error, 1)
329 go func() { done <- in.Install(ctx, "scratchpad") }()
330 <-bc.entered
331 if err := in.Uninstall(ctx, "scratchpad"); !errors.Is(err, ErrBusy) {
332 t.Fatalf("Uninstall = %v, want ErrBusy", err)
333 }
334 for _, c := range pf.Calls() {
335 if c.Method == "DeleteInstance" {
336 t.Fatal("DeleteInstance called during reinstall")
337 }
338 }
339 close(bc.release)
340 if err := <-done; err != nil {
341 t.Fatal(err)
342 }
343 if s := state(t, db, "scratchpad"); s.State != "installed" {
344 t.Errorf("row = %+v", s)
345 }
346}
347
348func TestInstalledWriteFailsRowEndsFailed(t *testing.T) {
349 in, _, db, _ := setup(t, nil)
350 _, err := db.Exec(`CREATE TRIGGER no_installed BEFORE UPDATE ON installs WHEN NEW.state = 'installed'
351 BEGIN SELECT RAISE(ABORT, 'nope'); END`)
352 if err != nil {
353 t.Fatal(err)
354 }
355 if err := in.Install(context.Background(), "scratchpad"); err == nil {
356 t.Fatal("want an error")
357 }
358 if s := state(t, db, "scratchpad"); s.State != "failed" || s.Error == "" {
359 t.Fatalf("row = %+v", s)
360 }
361}
362
363// Finding 1: the instance Base removes is the one it recorded, even after
364// the slug or apps domain changed.
365func TestUninstallDeletesRecordedHost(t *testing.T) {
366 in, pf, db, _ := setup(t, nil)
367 if err := in.Install(context.Background(), "scratchpad"); err != nil {
368 t.Fatal(err)
369 }
370 in.cfg.Slug, in.cfg.AppsDomain = "newco", "elsewhere.example"
371 if err := in.Uninstall(context.Background(), "scratchpad"); err != nil {
372 t.Fatal(err)
373 }
374 calls := pf.Calls()
375 if last := calls[len(calls)-1]; last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" {
376 t.Fatalf("deleted %+v, want the recorded host", last)
377 }
378 if s := state(t, db, "scratchpad"); s.App != "" {
379 t.Errorf("row remains: %+v", s)
380 }
381}
382
383// cancelOnDelete cancels the caller's context the moment Platform accepts the
384// delete, as a browser that disconnects then would.
385type cancelOnDelete struct {
386 platform.Client
387 cancel context.CancelFunc
388}
389
390func (c cancelOnDelete) DeleteInstance(ctx context.Context, app, host string) error {
391 err := c.Client.DeleteInstance(ctx, app, host)
392 c.cancel()
393 return err
394}
395
396// Finding 2: once Platform has removed the instance, Base forgets the
397// install even if the request that asked has gone.
398func TestUninstallFinishesAfterCallerCancels(t *testing.T) {
399 in, pf, db, _ := setup(t, nil)
400 if err := in.Install(context.Background(), "scratchpad"); err != nil {
401 t.Fatal(err)
402 }
403 ctx, cancel := context.WithCancel(context.Background())
404 in.pc = cancelOnDelete{Client: pf, cancel: cancel}
405 if err := in.Uninstall(ctx, "scratchpad"); err != nil {
406 t.Fatalf("Uninstall: %v", err)
407 }
408 if s := state(t, db, "scratchpad"); s.App != "" {
409 t.Fatalf("a removed instance is still marked %q", s.State)
410 }
411}
412
413func creates(pf *platform.Fake, app string) int {
414 n := 0
415 for _, c := range pf.Calls() {
416 if c.Method == "CreateInstance" && c.App == app {
417 n++
418 }
419 }
420 return n
421}
422
423// Finding 4 (R28): an owner who uninstalls Welcome does not get it back on
424// the next boot; installing it from the Store brings it back.
425func TestUninstalledDefaultStaysRemoved(t *testing.T) {
426 in, pf, db, _ := setup(t, nil)
427 ctx := context.Background()
428 if err := in.EnsureDefaults(ctx); err != nil {
429 t.Fatal(err)
430 }
431 if err := in.Uninstall(ctx, "welcome"); err != nil {
432 t.Fatal(err)
433 }
434 for range 2 { // two more boots
435 if err := in.EnsureDefaults(ctx); err != nil {
436 t.Fatal(err)
437 }
438 }
439 if n := creates(pf, "welcome"); n != 1 {
440 t.Fatalf("Welcome created %d times, want once", n)
441 }
442 if s := state(t, db, "welcome"); s.App != "" {
443 t.Fatalf("Welcome came back: %+v", s)
444 }
445 if err := in.Install(ctx, "welcome"); err != nil { // the Store's install
446 t.Fatal(err)
447 }
448 if s := state(t, db, "welcome"); s.State != "installed" {
449 t.Fatalf("Store install: %+v", s)
450 }
451 // Installed again by hand, it is a default like any other: a failed
452 // install is retried at boot.
453 if err := in.EnsureDefaults(ctx); err != nil {
454 t.Fatal(err)
455 }
456 if n := creates(pf, "welcome"); n != 2 {
457 t.Fatalf("Welcome created %d times, want twice", n)
458 }
459}
460
461// blockSetEnv holds the first platform write until released.
462type blockSetEnv struct {
463 platform.Client
464 entered chan struct{}
465 release chan struct{}
466}
467
468func (b *blockSetEnv) SetEnv(ctx context.Context, app, env string, vars map[string]string) error {
469 b.entered <- struct{}{}
470 <-b.release
471 return b.Client.SetEnv(ctx, app, env, vars)
472}
473
474// Finding 5 (R33): Start has claimed the install by the time it returns, and
475// the rest runs on after the caller's context is cancelled.
476func TestStartClaimsThenProvisionsInBackground(t *testing.T) {
477 in, pf, db, _ := setup(t, nil)
478 bc := &blockSetEnv{Client: pf, entered: make(chan struct{}, 1), release: make(chan struct{})}
479 in.pc = bc
480 ctx, cancel := context.WithCancel(context.Background())
481 if err := in.Start(ctx, "scratchpad"); err != nil {
482 t.Fatal(err)
483 }
484 cancel() // the request has ended
485 if s := state(t, db, "scratchpad"); s.State != "installing" {
486 t.Fatalf("after Start the row is %+v, want installing", s)
487 }
488 <-bc.entered
489 // A second Start while the first is running does nothing.
490 if err := in.Start(context.Background(), "scratchpad"); err != nil {
491 t.Fatal(err)
492 }
493 close(bc.release)
494 deadline := time.Now().Add(5 * time.Second)
495 for state(t, db, "scratchpad").State != "installed" {
496 if time.Now().After(deadline) {
497 t.Fatalf("install did not finish: %+v", state(t, db, "scratchpad"))
498 }
499 time.Sleep(5 * time.Millisecond)
500 }
501 if n := creates(pf, "scratchpad"); n != 1 {
502 t.Fatalf("creates = %d", n)
503 }
504}
505
506func TestStartUnknownAppIsAnError(t *testing.T) {
507 in, pf, _, _ := setup(t, nil)
508 if err := in.Start(context.Background(), "nope"); err == nil {
509 t.Fatal("want an error")
510 }
511 if len(pf.Calls()) != 0 {
512 t.Fatal("platform called")
513 }
514}
515