| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/sha256" |
| 7 | "encoding/hex" |
| 8 | "encoding/json" |
| 9 | "io" |
| 10 | "net/http" |
| 11 | "net/http/httptest" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "sync" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "git.timfalken.com/timfa/bluegit-backup/internal/config" |
| 20 | "git.timfalken.com/timfa/bluegit-backup/internal/protocol" |
| 21 | ) |
| 22 | |
| 23 | // fakeBlueGit is een minimale backup-API met bestanden in het geheugen. |
| 24 | type fakeBlueGit struct { |
| 25 | mu sync.Mutex |
| 26 | key string |
| 27 | inst string |
| 28 | files map[string]string |
| 29 | fetches map[string]int |
| 30 | ts *httptest.Server |
| 31 | } |
| 32 | |
| 33 | func newFake(t *testing.T) *fakeBlueGit { |
| 34 | f := &fakeBlueGit{key: "bgbk_test", inst: "inst-1", fetches: map[string]int{}, |
| 35 | files: map[string]string{"state/bluegit.db": "db1", "state/secret.key": "k", "data/repos/tim/a.git/HEAD": "ref"}} |
| 36 | f.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 37 | if r.Header.Get("Authorization") != "Bearer "+f.key { |
| 38 | http.Error(w, `{"error":"key"}`, 401) |
| 39 | return |
| 40 | } |
| 41 | f.mu.Lock() |
| 42 | defer f.mu.Unlock() |
| 43 | switch r.URL.Path { |
| 44 | case "/api/v1/backup/info": |
| 45 | _ = json.NewEncoder(w).Encode(protocol.Info{InstanceID: f.inst}) |
| 46 | case "/api/v1/backup/connect": |
| 47 | w.WriteHeader(200) |
| 48 | case "/api/v1/backup/manifest": |
| 49 | m := protocol.Manifest{Instance: f.inst} |
| 50 | for p, c := range f.files { |
| 51 | e := protocol.Entry{Path: p, Size: int64(len(c)), MTime: int64(len(c)) * 1000, Mode: 0o644} |
| 52 | if p == protocol.DBPath { |
| 53 | s := sha256.Sum256([]byte(c)) |
| 54 | e.SHA256 = hex.EncodeToString(s[:]) |
| 55 | } |
| 56 | m.Files = append(m.Files, e) |
| 57 | } |
| 58 | m.Files = append(m.Files, protocol.Entry{Path: "../../etc/passwd", Size: 1}) |
| 59 | _ = json.NewEncoder(w).Encode(m) |
| 60 | case "/api/v1/backup/file": |
| 61 | p := r.URL.Query().Get("path") |
| 62 | c, ok := f.files[p] |
| 63 | if !ok { |
| 64 | http.Error(w, `{"error":"weg"}`, 404) |
| 65 | return |
| 66 | } |
| 67 | f.fetches[p]++ |
| 68 | _, _ = io.WriteString(w, c) |
| 69 | default: |
| 70 | http.NotFound(w, r) |
| 71 | } |
| 72 | })) |
| 73 | t.Cleanup(f.ts.Close) |
| 74 | return f |
| 75 | } |
| 76 | |
| 77 | func newTestServer(t *testing.T) *Server { |
| 78 | cfg := config.Config{DataDir: t.TempDir(), PublicURL: "http://backup.test"} |
| 79 | cfg.Defaults() |
| 80 | cfg.RateLimitKiB = 0 |
| 81 | s, err := New(cfg, nil) |
| 82 | if err != nil { |
| 83 | t.Fatal(err) |
| 84 | } |
| 85 | return s |
| 86 | } |
| 87 | |
| 88 | func adminReq(s *Server, method, p, body string) *httptest.ResponseRecorder { |
| 89 | r := httptest.NewRequest(method, p, strings.NewReader(body)) |
| 90 | r.Header.Set("Authorization", "Bearer "+s.AdminToken()) |
| 91 | w := httptest.NewRecorder() |
| 92 | s.Handler().ServeHTTP(w, r) |
| 93 | return w |
| 94 | } |
| 95 | |
| 96 | func TestSyncIncrementalAndDeletes(t *testing.T) { |
| 97 | f := newFake(t) |
| 98 | s := newTestServer(t) |
| 99 | if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 200 { |
| 100 | t.Fatalf("connect %d %s", w.Code, w.Body) |
| 101 | } |
| 102 | if _, err := s.SyncNow(context.Background()); err != nil { |
| 103 | t.Fatal(err) |
| 104 | } |
| 105 | if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "mirror", "data/repos/tim/a.git/HEAD")); err != nil { |
| 106 | t.Fatal(err) |
| 107 | } |
| 108 | if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "etc", "passwd")); err == nil { |
| 109 | t.Fatal("pad buiten de kopie geschreven") |
| 110 | } |
| 111 | // Ongewijzigd: niets opnieuw. Gewijzigde database: alleen die. |
| 112 | st, _ := s.SyncNow(context.Background()) |
| 113 | if st.Downloaded != 0 { |
| 114 | t.Fatalf("tweede sync %+v", st) |
| 115 | } |
| 116 | f.mu.Lock() |
| 117 | f.files["state/bluegit.db"] = "db2" |
| 118 | delete(f.files, "data/repos/tim/a.git/HEAD") |
| 119 | f.mu.Unlock() |
| 120 | st, _ = s.SyncNow(context.Background()) |
| 121 | if st.Downloaded != 1 || st.Deleted != 1 { |
| 122 | t.Fatalf("derde sync %+v", st) |
| 123 | } |
| 124 | if b, _ := os.ReadFile(filepath.Join(s.Cfg.DataDir, "mirror", "state/bluegit.db")); string(b) != "db2" { |
| 125 | t.Fatalf("db %q", b) |
| 126 | } |
| 127 | if _, err := os.Stat(filepath.Join(s.Cfg.DataDir, "mirror", "data/repos/tim")); err == nil { |
| 128 | t.Fatal("lege map blijft staan") |
| 129 | } |
| 130 | // Bestaat state.json en is het 0600 (er staat een key in). |
| 131 | fi, err := os.Stat(filepath.Join(s.Cfg.DataDir, "state.json")) |
| 132 | if err != nil || fi.Mode().Perm() != 0o600 { |
| 133 | t.Fatalf("state.json %v %v", err, fi) |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | func TestSignedEndpoints(t *testing.T) { |
| 138 | f := newFake(t) |
| 139 | s := newTestServer(t) |
| 140 | if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 200 { |
| 141 | t.Fatalf("connect %d", w.Code) |
| 142 | } |
| 143 | h := s.Handler() |
| 144 | call := func(method, p, body, secret, inst string) int { |
| 145 | r := httptest.NewRequest(method, p, bytes.NewReader([]byte(body))) |
| 146 | if secret != "" { |
| 147 | protocol.Sign(r, secret, inst, []byte(body), time.Now()) |
| 148 | } |
| 149 | w := httptest.NewRecorder() |
| 150 | h.ServeHTTP(w, r) |
| 151 | return w.Code |
| 152 | } |
| 153 | good := protocol.SigningSecret("bgbk_test") |
| 154 | if c := call("POST", "/api/v1/notify", "{}", "", ""); c != 401 { |
| 155 | t.Fatalf("zonder handtekening %d", c) |
| 156 | } |
| 157 | if c := call("POST", "/api/v1/notify", "{}", protocol.SigningSecret("bgbk_ander"), "inst-1"); c != 401 { |
| 158 | t.Fatalf("verkeerd geheim %d", c) |
| 159 | } |
| 160 | if c := call("POST", "/api/v1/notify", "{}", good, "inst-2"); c != 401 { |
| 161 | t.Fatalf("andere instantie %d", c) |
| 162 | } |
| 163 | if c := call("POST", "/api/v1/notify", "{}", good, "inst-1"); c != 204 { |
| 164 | t.Fatalf("melding %d", c) |
| 165 | } |
| 166 | if c := call("GET", "/api/v1/archives", "", good, "inst-1"); c != 200 { |
| 167 | t.Fatalf("archieven %d", c) |
| 168 | } |
| 169 | if c := call("POST", "/api/v1/rollback", `{"archive":"../x"}`, good, "inst-1"); c != 400 { |
| 170 | t.Fatalf("ongeldige naam %d", c) |
| 171 | } |
| 172 | if c := call("POST", "/api/v1/rollback", `{"archive":"bluegit-20261115-120000.tar.gz"}`, good, "inst-1"); c != 404 { |
| 173 | t.Fatalf("onbekend archief %d", c) |
| 174 | } |
| 175 | // Beheer-API zonder token. |
| 176 | r := httptest.NewRequest("GET", "/api/v1/admin/status", nil) |
| 177 | w := httptest.NewRecorder() |
| 178 | h.ServeHTTP(w, r) |
| 179 | if w.Code != 401 { |
| 180 | t.Fatalf("status zonder token %d", w.Code) |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | func TestConnectValidation(t *testing.T) { |
| 185 | f := newFake(t) |
| 186 | s := newTestServer(t) |
| 187 | for body, want := range map[string]int{ |
| 188 | `{"url":"ftp://x","key":"bgbk_test"}`: 400, |
| 189 | `{"url":"` + f.ts.URL + `","key":"zonder-prefix"}`: 400, |
| 190 | `{"url":"` + f.ts.URL + `","key":"bgbk_fout"}`: 401, |
| 191 | `{"url":"` + f.ts.URL + `","key":"bgbk_test","on_conflict":"x"}`: 400, |
| 192 | } { |
| 193 | if w := adminReq(s, "POST", "/api/v1/admin/connect", body); w.Code != want { |
| 194 | t.Errorf("%s: %d, wil %d (%s)", body, w.Code, want, w.Body) |
| 195 | } |
| 196 | } |
| 197 | s.Cfg.PublicURL = "" |
| 198 | if w := adminReq(s, "POST", "/api/v1/admin/connect", `{"url":"`+f.ts.URL+`","key":"bgbk_test"}`); w.Code != 400 { |
| 199 | t.Fatalf("zonder public_url %d", w.Code) |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func TestSelfUpdateEndpoint(t *testing.T) { |
| 204 | s := newTestServer(t) |
| 205 | h := s.Handler() |
| 206 | var got string |
| 207 | UpdateStarter = func(_ context.Context, ref string) error { got = ref; return nil } |
| 208 | call := func(tok, body string) int { |
| 209 | r := httptest.NewRequest("POST", "/api/v1/admin/self-update", strings.NewReader(body)) |
| 210 | if tok != "" { |
| 211 | r.Header.Set("Authorization", "Bearer "+tok) |
| 212 | } |
| 213 | w := httptest.NewRecorder() |
| 214 | h.ServeHTTP(w, r) |
| 215 | return w.Code |
| 216 | } |
| 217 | t.Setenv("BLUEGIT_BACKUP_UPDATE_TOKEN", "") |
| 218 | if c := call("x", `{}`); c != 404 { |
| 219 | t.Fatalf("uit: %d", c) |
| 220 | } |
| 221 | t.Setenv("BLUEGIT_BACKUP_UPDATE_TOKEN", "geheim") |
| 222 | if c := call("fout", `{}`); c != 401 { |
| 223 | t.Fatalf("fout token: %d", c) |
| 224 | } |
| 225 | if c := call("geheim", `{"ref":"master"}`); c != 400 { |
| 226 | t.Fatalf("geen sha: %d", c) |
| 227 | } |
| 228 | sha := strings.Repeat("a", 40) |
| 229 | if c := call("geheim", `{"ref":"`+sha+`"}`); c != 202 || got != sha { |
| 230 | t.Fatalf("start: %d %q", c, got) |
| 231 | } |
| 232 | } |