| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "net" |
| 6 | "net/http" |
| 7 | "os" |
| 8 | "os/exec" |
| 9 | "path/filepath" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | func TestPlaceholderNeverOpensActivationDatabase(t *testing.T) { |
| 16 | dir := t.TempDir() |
| 17 | binary := filepath.Join(dir, "home-placeholder") |
| 18 | build := exec.Command("go", "build", "-o", binary, ".") |
| 19 | if out, err := build.CombinedOutput(); err != nil { |
| 20 | t.Fatalf("build: %v: %s", err, out) |
| 21 | } |
| 22 | l, err := net.Listen("tcp", "127.0.0.1:0") |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | addr := l.Addr().String() |
| 27 | l.Close() |
| 28 | // The parent is deliberately missing: any database open must fail boot. |
| 29 | database := filepath.Join(dir, "absent", "must-not-exist.db") |
| 30 | cmd := exec.Command(binary, "-addr", addr, "-db", database) |
| 31 | cmd.Env = []string{"PATH=" + os.Getenv("PATH")} |
| 32 | if err := cmd.Start(); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() }) |
| 36 | client := &http.Client{Timeout: time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| 37 | origin := "http://" + addr |
| 38 | deadline := time.Now().Add(10 * time.Second) |
| 39 | for { |
| 40 | response, err := client.Get(origin + "/healthz") |
| 41 | if err == nil { |
| 42 | response.Body.Close() |
| 43 | if response.StatusCode == 200 { |
| 44 | break |
| 45 | } |
| 46 | } |
| 47 | if time.Now().After(deadline) { |
| 48 | t.Fatal("placeholder did not start without secrets and with an unusable database path") |
| 49 | } |
| 50 | time.Sleep(25 * time.Millisecond) |
| 51 | } |
| 52 | for path, status := range map[string]int{"/": 200, "/static/brand/icon.svg": 200, "/signin": 404, "/authorize": 404, "/static/brand/": 404} { |
| 53 | response, err := client.Get(origin + path) |
| 54 | if err != nil { |
| 55 | t.Fatal(err) |
| 56 | } |
| 57 | body, err := io.ReadAll(response.Body) |
| 58 | response.Body.Close() |
| 59 | if err != nil { |
| 60 | t.Fatal(err) |
| 61 | } |
| 62 | if response.StatusCode != status { |
| 63 | t.Errorf("%s: status %d, want %d", path, response.StatusCode, status) |
| 64 | } |
| 65 | if len(response.Cookies()) != 0 { |
| 66 | t.Errorf("%s set cookies", path) |
| 67 | } |
| 68 | if path == "/" && !strings.Contains(string(body), `href="/static/brand/icon.svg"`) { |
| 69 | t.Error("missing favicon") |
| 70 | } |
| 71 | } |
| 72 | if _, err := os.Stat(filepath.Dir(database)); !os.IsNotExist(err) { |
| 73 | t.Fatalf("database parent created or unreadable: %v", err) |
| 74 | } |
| 75 | } |
| 76 | |