| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "net/http" |
| 7 | "net/http/cookiejar" |
| 8 | "net/http/httptest" |
| 9 | "net/url" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "gitlab.com/Timfa/bluegit/internal/auth" |
| 18 | "gitlab.com/Timfa/bluegit/internal/config" |
| 19 | "gitlab.com/Timfa/bluegit/internal/store" |
| 20 | "gitlab.com/Timfa/bluegit/internal/webhook" |
| 21 | ) |
| 22 | |
| 23 | func TestWebhookPayloads(t *testing.T) { |
| 24 | if _, err := exec.LookPath("git"); err != nil { |
| 25 | t.Skip("git ontbreekt") |
| 26 | } |
| 27 | storage := t.TempDir() |
| 28 | st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32()) |
| 29 | if err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | t.Cleanup(func() { _ = st.Close() }) |
| 33 | cfg := config.Config{ |
| 34 | BaseURL: "http://git.example", Listen: "127.0.0.1:0", StoragePath: storage, |
| 35 | Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"}, |
| 36 | Git: config.Git{Binary: "git", DefaultBranch: "master"}, |
| 37 | } |
| 38 | var bodies [][]byte |
| 39 | srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git", HookBin: "/bin/true"} |
| 40 | srv.hookSink = func(b []byte) { |
| 41 | bodies = append(bodies, append([]byte(nil), b...)) |
| 42 | } |
| 43 | ts := httptest.NewServer(srv.Handler()) |
| 44 | t.Cleanup(ts.Close) |
| 45 | jar, _ := cookiejar.New(nil) |
| 46 | tim := &http.Client{Jar: jar} |
| 47 | page := read(t, mustGet(t, tim, ts.URL+"/login")) |
| 48 | page = read(t, mustPost(t, tim, ts.URL+"/new/repo", url.Values{ |
| 49 | "csrf": {csrfOf(t, page)}, "name": {"hooks"}, "visibility": {"public"}, |
| 50 | })) |
| 51 | ctx := context.Background() |
| 52 | repo, err := st.RepoByPath(ctx, "tim", "hooks") |
| 53 | if err != nil { |
| 54 | t.Fatal(err) |
| 55 | } |
| 56 | if _, err := st.CreateWebhook(ctx, store.Webhook{ |
| 57 | ScopeKind: "repo", ScopeID: repo.ID, Name: "alles", Preset: "generic", |
| 58 | URLTemplate: "https://example.test/hook", |
| 59 | Events: []string{"push", "merge_request", "pipeline_failure", "release_published"}, |
| 60 | }); err != nil { |
| 61 | t.Fatal(err) |
| 62 | } |
| 63 | if err := st.PutSecret(ctx, "repo", repo.ID, "DEPLOY_TOKEN", "super-secret-token", true); err != nil { |
| 64 | t.Fatal(err) |
| 65 | } |
| 66 | |
| 67 | page = read(t, mustPost(t, tim, ts.URL+"/settings/tokens", url.Values{ |
| 68 | "csrf": {csrfOf(t, page)}, "name": {"laptop"}, |
| 69 | })) |
| 70 | token := between(page, `<p class="code">`, "</p>") |
| 71 | remote := strings.Replace(ts.URL, "http://", "http://tim:"+token+"@", 1) + "/tim/hooks.git" |
| 72 | work := t.TempDir() |
| 73 | git(t, work, "init", "-b", "master") |
| 74 | git(t, work, "config", "user.email", "tim@users.git.timfalken.com") |
| 75 | git(t, work, "config", "user.name", "tim") |
| 76 | writeFile(t, filepath.Join(work, "README.md"), "a\n") |
| 77 | git(t, work, "add", "README.md") |
| 78 | git(t, work, "commit", "-m", "eerste regel", "-m", "meer tekst") |
| 79 | writeFile(t, filepath.Join(work, "README.md"), "b\n") |
| 80 | git(t, work, "add", "README.md") |
| 81 | git(t, work, "commit", "-m", "tweede") |
| 82 | git(t, work, "remote", "add", "origin", remote) |
| 83 | git(t, work, "push", "-u", "origin", "master") |
| 84 | |
| 85 | push := decodeKind(t, bodies, "push") |
| 86 | if push["ref"] != "refs/heads/master" || push["before"] != strings.Repeat("0", 40) { |
| 87 | t.Fatalf("push ref/before %v", push) |
| 88 | } |
| 89 | commits := push["commits"].([]any) |
| 90 | if len(commits) != 2 { |
| 91 | t.Fatalf("commits %d %s", len(commits), mustJSON(t, push)) |
| 92 | } |
| 93 | first := commits[0].(map[string]any) |
| 94 | second := commits[1].(map[string]any) |
| 95 | if first["message"] != "eerste regel\n\nmeer tekst" || second["message"] != "tweede" { |
| 96 | t.Fatalf("berichten %v %v", first["message"], second["message"]) |
| 97 | } |
| 98 | if first["author"] != "tim <tim@users.git.timfalken.com>" || !strings.Contains(first["url"].(string), "/tim/hooks/-/commit/") { |
| 99 | t.Fatalf("auteur of url %v", first) |
| 100 | } |
| 101 | if push["after"] != second["sha"] { |
| 102 | t.Fatalf("after %v tip %v", push["after"], second["sha"]) |
| 103 | } |
| 104 | if strings.Contains(mustJSON(t, push), "diff --git") { |
| 105 | t.Fatal("push bevat een diff") |
| 106 | } |
| 107 | if _, err := time.Parse(time.RFC3339, first["timestamp"].(string)); err != nil { |
| 108 | t.Fatalf("timestamp %v", first["timestamp"]) |
| 109 | } |
| 110 | readme := fileByPath(t, first["files"].([]any), "README.md") |
| 111 | if readme["status"] != "added" || readme["additions"] != float64(1) || readme["deletions"] != float64(0) { |
| 112 | t.Fatalf("eerste bestand %v", readme) |
| 113 | } |
| 114 | changed := fileByPath(t, second["files"].([]any), "README.md") |
| 115 | if changed["status"] != "modified" || changed["additions"] != float64(1) || changed["deletions"] != float64(1) { |
| 116 | t.Fatalf("tweede bestand %v", changed) |
| 117 | } |
| 118 | diffPath := mustParse(t, first["diff_url"].(string)).Path |
| 119 | if !strings.Contains(diffPath, "/api/v1/repos/tim/hooks/commits/") || !strings.HasSuffix(diffPath, "/diff") { |
| 120 | t.Fatalf("diff_url %s", diffPath) |
| 121 | } |
| 122 | noDiff := mustGet(t, http.DefaultClient, ts.URL+diffPath) |
| 123 | if noDiff.StatusCode != http.StatusUnauthorized { |
| 124 | t.Fatalf("diff zonder token %d", noDiff.StatusCode) |
| 125 | } |
| 126 | noDiff.Body.Close() |
| 127 | diffRes := getBearer(t, ts.URL+diffPath, token) |
| 128 | if diffRes.StatusCode != http.StatusOK || !strings.HasPrefix(diffRes.Header.Get("Content-Type"), "text/plain") { |
| 129 | t.Fatalf("commitdiff %d %s", diffRes.StatusCode, diffRes.Header.Get("Content-Type")) |
| 130 | } |
| 131 | diffText := read(t, diffRes) |
| 132 | if !strings.Contains(diffText, "diff --git") || !strings.Contains(diffText, "README.md") || !strings.Contains(diffText, "+a") { |
| 133 | t.Fatalf("commitdiff tekst %s", diffText) |
| 134 | } |
| 135 | |
| 136 | git(t, work, "checkout", "-b", "topic") |
| 137 | writeFile(t, filepath.Join(work, "extra.txt"), "c\n") |
| 138 | git(t, work, "add", "extra.txt") |
| 139 | git(t, work, "commit", "-m", "derde") |
| 140 | git(t, work, "push", "-u", "origin", "topic") |
| 141 | |
| 142 | page = read(t, mustGet(t, tim, ts.URL+"/tim/hooks/-/merge-requests/new?source=topic&target=master")) |
| 143 | page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests", url.Values{ |
| 144 | "csrf": {csrfOf(t, page)}, "source": {"topic"}, "target": {"master"}, |
| 145 | "title": {"Toon de kloon-URL"}, "description": {"SSH en HTTPS."}, |
| 146 | })) |
| 147 | opened := decodeAction(t, bodies, "opened") |
| 148 | mr := opened["merge_request"].(map[string]any) |
| 149 | if mr["title"] != "Toon de kloon-URL" || mr["description"] != "SSH en HTTPS." || mr["source_branch"] != "topic" || mr["target_branch"] != "master" || mr["status"] != "open" || mr["author"] != "tim" || mr["id"] != float64(1) { |
| 150 | t.Fatalf("opened %s", mustJSON(t, mr)) |
| 151 | } |
| 152 | if _, ok := opened["comment"]; ok { |
| 153 | t.Fatalf("opened heeft een comment: %s", mustJSON(t, opened)) |
| 154 | } |
| 155 | if strings.Contains(mustJSON(t, opened), "diff --git") { |
| 156 | t.Fatal("merge request bevat een diff") |
| 157 | } |
| 158 | if len(mr["reviewers"].([]any)) != 0 || len(mr["comments"].([]any)) != 0 { |
| 159 | t.Fatalf("opened heeft al reviewers of comments: %s", mustJSON(t, mr)) |
| 160 | } |
| 161 | mrCommits := mr["commits"].([]any) |
| 162 | if len(mrCommits) != 1 || mrCommits[0].(map[string]any)["message"] != "derde" { |
| 163 | t.Fatalf("mr commits %s", mustJSON(t, mrCommits)) |
| 164 | } |
| 165 | extra := fileByPath(t, mrCommits[0].(map[string]any)["files"].([]any), "extra.txt") |
| 166 | if extra["status"] != "added" || extra["additions"] != float64(1) { |
| 167 | t.Fatalf("mr bestand %v", extra) |
| 168 | } |
| 169 | stats := mr["diff_stats"].(map[string]any) |
| 170 | statFile := fileByPath(t, stats["files"].([]any), "extra.txt") |
| 171 | if stats["additions"] != float64(1) || stats["deletions"] != float64(0) || statFile["status"] != "added" { |
| 172 | t.Fatalf("diff_stats %s", mustJSON(t, stats)) |
| 173 | } |
| 174 | mrDiffPath := mustParse(t, mr["diff_url"].(string)).Path |
| 175 | if mrDiffPath != "/api/v1/repos/tim/hooks/merge-requests/1/diff" { |
| 176 | t.Fatalf("mr diff_url %s", mrDiffPath) |
| 177 | } |
| 178 | timUser, err := st.UserByUsername(ctx, "tim") |
| 179 | if err != nil { |
| 180 | t.Fatal(err) |
| 181 | } |
| 182 | storedMR, err := st.MergeRequestByNumber(ctx, repo.ID, 1) |
| 183 | if err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | if err := st.UpsertReview(ctx, repo.ID, storedMR.ID, timUser.ID, "approved"); err != nil { |
| 187 | t.Fatal(err) |
| 188 | } |
| 189 | |
| 190 | page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/notes", url.Values{ |
| 191 | "csrf": {csrfOf(t, page)}, "body": {"dit is het commentaar"}, |
| 192 | })) |
| 193 | commented := decodeAction(t, bodies, "commented") |
| 194 | if commented["comment"] != "dit is het commentaar" { |
| 195 | t.Fatalf("comment %s", mustJSON(t, commented)) |
| 196 | } |
| 197 | commentedMR := commented["merge_request"].(map[string]any) |
| 198 | reviewers := commentedMR["reviewers"].([]any) |
| 199 | if len(reviewers) != 1 || reviewers[0].(map[string]any)["username"] != "tim" || reviewers[0].(map[string]any)["status"] != "approved" { |
| 200 | t.Fatalf("reviewers %s", mustJSON(t, reviewers)) |
| 201 | } |
| 202 | notes := commentedMR["comments"].([]any) |
| 203 | if len(notes) != 1 || notes[0].(map[string]any)["body"] != "dit is het commentaar" || notes[0].(map[string]any)["author"] != "tim" { |
| 204 | t.Fatalf("comments %s", mustJSON(t, notes)) |
| 205 | } |
| 206 | mrDiff := getBearer(t, ts.URL+mrDiffPath, token) |
| 207 | if mrDiff.StatusCode != http.StatusOK || !strings.HasPrefix(mrDiff.Header.Get("Content-Type"), "text/plain") { |
| 208 | t.Fatalf("mr diff %d", mrDiff.StatusCode) |
| 209 | } |
| 210 | mrDiffText := read(t, mrDiff) |
| 211 | if !strings.Contains(mrDiffText, "diff --git") || !strings.Contains(mrDiffText, "extra.txt") { |
| 212 | t.Fatalf("mr diff tekst %s", mrDiffText) |
| 213 | } |
| 214 | |
| 215 | page = read(t, mustPost(t, tim, ts.URL+"/tim/hooks/-/merge-requests/1/merge", url.Values{ |
| 216 | "csrf": {csrfOf(t, page)}, |
| 217 | })) |
| 218 | if strings.Contains(page, "flash") && strings.Contains(strings.ToLower(page), "error") { |
| 219 | t.Fatalf("merge pagina:\n%s", page) |
| 220 | } |
| 221 | merged := decodeAction(t, bodies, "merged") |
| 222 | if merged["merge_request"].(map[string]any)["status"] != "merged" { |
| 223 | t.Fatalf("merged %s", mustJSON(t, merged)) |
| 224 | } |
| 225 | |
| 226 | sha := second["sha"].(string) |
| 227 | id, err := st.CreatePipeline(ctx, repo.ID, sha, "refs/heads/master", "push", "tim", "tweede", []store.NewJob{ |
| 228 | {Name: "test", Stage: "test", Script: "exit 1"}, |
| 229 | {Name: "build", Stage: "build", Script: "echo ok"}, |
| 230 | {Name: "soft", Stage: "test", Script: "exit 1", AllowFailure: true}, |
| 231 | }) |
| 232 | if err != nil { |
| 233 | t.Fatal(err) |
| 234 | } |
| 235 | jobs, err := st.JobsByPipeline(ctx, id) |
| 236 | if err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | var lines []string |
| 240 | for i := 0; i < webhook.LogMaxLines+40; i++ { |
| 241 | lines = append(lines, "regel") |
| 242 | } |
| 243 | lines = append(lines, "token super-secret-token") |
| 244 | log := strings.Join(lines, "\n") |
| 245 | for _, j := range jobs { |
| 246 | if _, err := st.MarkJobRunning(ctx, j.ID); err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | switch j.Name { |
| 250 | case "test": |
| 251 | if err := st.AppendJobLog(ctx, j.ID, log); err != nil { |
| 252 | t.Fatal(err) |
| 253 | } |
| 254 | if err := st.FinishJob(ctx, j.ID, "failed", ""); err != nil { |
| 255 | t.Fatal(err) |
| 256 | } |
| 257 | case "soft": |
| 258 | if err := st.AppendJobLog(ctx, j.ID, "zacht super-secret-token\n"); err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | if err := st.FinishJob(ctx, j.ID, "failed", ""); err != nil { |
| 262 | t.Fatal(err) |
| 263 | } |
| 264 | default: |
| 265 | if err := st.AppendJobLog(ctx, j.ID, "gebouwd\n"); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | if err := st.FinishJob(ctx, j.ID, "success", ""); err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | if _, err := st.RefreshPipelineStatus(ctx, id); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | before := len(bodies) |
| 277 | srv.Dispatch(repo.ID, webhook.Event{ |
| 278 | Type: webhook.EventPipelineFailure, PipelineID: strconv.FormatInt(id, 10), |
| 279 | }) |
| 280 | if len(bodies) == before { |
| 281 | t.Fatal("geen pipeline-payload") |
| 282 | } |
| 283 | var pipe map[string]any |
| 284 | if err := json.Unmarshal(bodies[len(bodies)-1], &pipe); err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | if pipe["object_kind"] != "pipeline" || pipe["type"] != "pipeline_failure" { |
| 288 | t.Fatalf("pipeline %s", bodies[len(bodies)-1]) |
| 289 | } |
| 290 | detail := pipe["pipeline"].(map[string]any) |
| 291 | if detail["id"] != float64(id) || detail["status"] != "failed" || detail["ref"] != "refs/heads/master" || detail["sha"] != sha || detail["author"] != "tim" { |
| 292 | t.Fatalf("detail %s", mustJSON(t, detail)) |
| 293 | } |
| 294 | if !strings.Contains(detail["commit_message"].(string), "tweede") { |
| 295 | t.Fatalf("commit_message %v", detail["commit_message"]) |
| 296 | } |
| 297 | if _, ok := detail["duration"]; !ok { |
| 298 | t.Fatal("duur ontbreekt") |
| 299 | } |
| 300 | var fullLogURL string |
| 301 | for _, item := range pipe["jobs"].([]any) { |
| 302 | job := item.(map[string]any) |
| 303 | raw, _ := json.Marshal(job) |
| 304 | if strings.Contains(string(raw), "super-secret-token") { |
| 305 | t.Fatalf("geheim in job %s", raw) |
| 306 | } |
| 307 | if _, ok := job["log"]; !ok { |
| 308 | t.Fatalf("elke job heeft een log: %s", raw) |
| 309 | } |
| 310 | if _, ok := job["log_truncated"]; !ok { |
| 311 | t.Fatalf("elke job heeft log_truncated: %s", raw) |
| 312 | } |
| 313 | switch job["name"] { |
| 314 | case "test": |
| 315 | if job["log_truncated"] != true || job["allow_failure"] != false { |
| 316 | t.Fatalf("test %s", raw) |
| 317 | } |
| 318 | text := job["log"].(string) |
| 319 | if !strings.Contains(text, "[MASKED]") || len(strings.Split(text, "\n")) != webhook.LogMaxLines { |
| 320 | t.Fatalf("log %d regels, staart %q", len(strings.Split(text, "\n")), text[max(0, len(text)-40):]) |
| 321 | } |
| 322 | fullLogURL, _ = job["log_url"].(string) |
| 323 | if !strings.Contains(fullLogURL, "/api/v1/repos/tim/hooks/jobs/") || !strings.HasSuffix(fullLogURL, "/log") || !strings.Contains(job["web_url"].(string), "/jobs/") { |
| 324 | t.Fatalf("urls %s", raw) |
| 325 | } |
| 326 | case "build": |
| 327 | if job["status"] != "success" || job["log"] != "gebouwd\n" || job["log_truncated"] != false { |
| 328 | t.Fatalf("build %s", raw) |
| 329 | } |
| 330 | if _, ok := job["log_url"]; ok { |
| 331 | t.Fatalf("korte geslaagde log heeft een url: %s", raw) |
| 332 | } |
| 333 | case "soft": |
| 334 | if job["allow_failure"] != true || job["log_truncated"] != false || !strings.Contains(job["log"].(string), "[MASKED]") { |
| 335 | t.Fatalf("soft %s", raw) |
| 336 | } |
| 337 | if _, ok := job["log_url"]; ok { |
| 338 | t.Fatalf("korte log heeft een url: %s", raw) |
| 339 | } |
| 340 | } |
| 341 | } |
| 342 | if fullLogURL == "" { |
| 343 | t.Fatal("geen log_url") |
| 344 | } |
| 345 | logPath := mustParse(t, fullLogURL).Path |
| 346 | noAuth := mustGet(t, http.DefaultClient, ts.URL+logPath) |
| 347 | if noAuth.StatusCode != http.StatusUnauthorized { |
| 348 | t.Fatalf("zonder token %d", noAuth.StatusCode) |
| 349 | } |
| 350 | noAuth.Body.Close() |
| 351 | full := getBearer(t, ts.URL+logPath, token) |
| 352 | if full.StatusCode != http.StatusOK || !strings.HasPrefix(full.Header.Get("Content-Type"), "text/plain") { |
| 353 | t.Fatalf("volle log %d %s", full.StatusCode, full.Header.Get("Content-Type")) |
| 354 | } |
| 355 | fullText := read(t, full) |
| 356 | if strings.Contains(fullText, "super-secret-token") || !strings.Contains(fullText, "[MASKED]") { |
| 357 | t.Fatal("volle log maskeert het geheim niet") |
| 358 | } |
| 359 | if n := len(strings.Split(fullText, "\n")); n <= webhook.LogMaxLines { |
| 360 | t.Fatalf("volle log heeft %d regels", n) |
| 361 | } |
| 362 | bad := getBearer(t, ts.URL+logPath, "bgj_geen-job") |
| 363 | if bad.StatusCode != http.StatusUnauthorized { |
| 364 | t.Fatalf("job-token %d", bad.StatusCode) |
| 365 | } |
| 366 | bad.Body.Close() |
| 367 | |
| 368 | rel := srv.releaseEvent(repo, "v1.2.0", "BlueGit 1.2.0", sha, []store.ReleaseAsset{{Name: "blue git", Size: 9}}) |
| 369 | raw, err := webhook.RenderBody("", rel, nil) |
| 370 | if err != nil { |
| 371 | t.Fatal(err) |
| 372 | } |
| 373 | var release map[string]any |
| 374 | if err := json.Unmarshal(raw, &release); err != nil { |
| 375 | t.Fatal(err) |
| 376 | } |
| 377 | info := release["release"].(map[string]any) |
| 378 | asset := info["assets"].([]any)[0].(map[string]any) |
| 379 | if info["tag"] != "v1.2.0" || info["name"] != "BlueGit 1.2.0" || info["commit"] != sha || !strings.Contains(asset["url"].(string), "/-/releases/v1.2.0/assets/blue%20git") { |
| 380 | t.Fatalf("release %s", raw) |
| 381 | } |
| 382 | |
| 383 | if elapsedSeconds(time.Unix(10, 0), time.Unix(12, 0)) != 2 { |
| 384 | t.Fatal("duur") |
| 385 | } |
| 386 | |
| 387 | infoPage := read(t, mustGet(t, tim, ts.URL+"/-/info")) |
| 388 | for _, want := range []string{"Webhook payloads", "log_truncated", "log_url", "/api/v1/webhooks/openapi.json", "/api/v1/repos/{owner}/{repo}/jobs/{id}/log", "diff_url", "reviewers", "commit_message", "source_branch"} { |
| 389 | if !strings.Contains(infoPage, want) { |
| 390 | t.Errorf("infopagina mist %q", want) |
| 391 | } |
| 392 | } |
| 393 | specRes, err := http.Get(ts.URL + "/api/v1/webhooks/openapi.json") |
| 394 | if err != nil { |
| 395 | t.Fatal(err) |
| 396 | } |
| 397 | spec := read(t, specRes) |
| 398 | if specRes.StatusCode != 200 || !strings.Contains(spec, `"openapi": "3.1.0"`) || !strings.Contains(spec, "log_truncated") || !strings.Contains(spec, "/repos/{owner}/{repo}/jobs/{id}/log") { |
| 399 | t.Fatalf("spec %d %s", specRes.StatusCode, spec[:min(200, len(spec))]) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | func decodeKind(t *testing.T, bodies [][]byte, kind string) map[string]any { |
| 404 | t.Helper() |
| 405 | for i := len(bodies) - 1; i >= 0; i-- { |
| 406 | var doc map[string]any |
| 407 | if err := json.Unmarshal(bodies[i], &doc); err != nil { |
| 408 | continue |
| 409 | } |
| 410 | if doc["object_kind"] == kind { |
| 411 | return doc |
| 412 | } |
| 413 | } |
| 414 | t.Fatalf("geen %s in %d payloads", kind, len(bodies)) |
| 415 | return nil |
| 416 | } |
| 417 | |
| 418 | func decodeAction(t *testing.T, bodies [][]byte, action string) map[string]any { |
| 419 | t.Helper() |
| 420 | for i := len(bodies) - 1; i >= 0; i-- { |
| 421 | var doc map[string]any |
| 422 | if err := json.Unmarshal(bodies[i], &doc); err != nil { |
| 423 | continue |
| 424 | } |
| 425 | mr, _ := doc["merge_request"].(map[string]any) |
| 426 | if mr != nil && mr["action"] == action { |
| 427 | return doc |
| 428 | } |
| 429 | } |
| 430 | t.Fatalf("geen actie %s", action) |
| 431 | return nil |
| 432 | } |
| 433 | |
| 434 | func TestJobLogAPI(t *testing.T) { |
| 435 | storage := t.TempDir() |
| 436 | st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32()) |
| 437 | if err != nil { |
| 438 | t.Fatal(err) |
| 439 | } |
| 440 | t.Cleanup(func() { _ = st.Close() }) |
| 441 | ctx := context.Background() |
| 442 | tim, err := st.UpsertUser(ctx, 1, "tim", "", false) |
| 443 | if err != nil { |
| 444 | t.Fatal(err) |
| 445 | } |
| 446 | ada, err := st.UpsertUser(ctx, 2, "ada", "", false) |
| 447 | if err != nil { |
| 448 | t.Fatal(err) |
| 449 | } |
| 450 | priv, err := st.CreateRepo(ctx, "user", tim.ID, "priv", "", "master", "private") |
| 451 | if err != nil { |
| 452 | t.Fatal(err) |
| 453 | } |
| 454 | open, err := st.CreateRepo(ctx, "user", tim.ID, "open", "", "master", "public") |
| 455 | if err != nil { |
| 456 | t.Fatal(err) |
| 457 | } |
| 458 | if err := st.PutSecret(ctx, "repo", priv.ID, "DEPLOY_TOKEN", "super-secret-token", true); err != nil { |
| 459 | t.Fatal(err) |
| 460 | } |
| 461 | if err := st.PutSecret(ctx, "repo", open.ID, "DEPLOY_TOKEN", "super-secret-token", true); err != nil { |
| 462 | t.Fatal(err) |
| 463 | } |
| 464 | privJob := seedJobLog(t, st, priv.ID, "regel\nsuper-secret-token\n") |
| 465 | openJob := seedJobLog(t, st, open.ID, "publiek super-secret-token\n") |
| 466 | ownerTok, err := st.CreateToken(ctx, tim.ID, "laptop") |
| 467 | if err != nil { |
| 468 | t.Fatal(err) |
| 469 | } |
| 470 | adaTok, err := st.CreateToken(ctx, ada.ID, "ada") |
| 471 | if err != nil { |
| 472 | t.Fatal(err) |
| 473 | } |
| 474 | cfg := config.Config{ |
| 475 | BaseURL: "http://git.example", Listen: "127.0.0.1:0", StoragePath: storage, |
| 476 | Auth: config.Auth{Mode: "dev", DevUser: "tim", DevAuthID: 1, UserAgent: "test", BaseURL: "https://auth.timfalken.com"}, |
| 477 | Git: config.Git{Binary: "git", DefaultBranch: "master"}, |
| 478 | } |
| 479 | srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "tim", AuthID: 1}, Dev: true, Git: "git"} |
| 480 | ts := httptest.NewServer(srv.Handler()) |
| 481 | t.Cleanup(ts.Close) |
| 482 | |
| 483 | privPath := ts.URL + "/api/v1/repos/tim/priv/jobs/" + strconv.FormatInt(privJob, 10) + "/log" |
| 484 | openPath := ts.URL + "/api/v1/repos/tim/open/jobs/" + strconv.FormatInt(openJob, 10) + "/log" |
| 485 | |
| 486 | missing := mustGet(t, http.DefaultClient, privPath) |
| 487 | if missing.StatusCode != http.StatusUnauthorized { |
| 488 | t.Fatalf("zonder token %d", missing.StatusCode) |
| 489 | } |
| 490 | missing.Body.Close() |
| 491 | for _, tok := range []string{"nope", "bg_onbekend", "bgj_job"} { |
| 492 | res := getBearer(t, privPath, tok) |
| 493 | if res.StatusCode != http.StatusUnauthorized { |
| 494 | t.Fatalf("token %s geeft %d", tok, res.StatusCode) |
| 495 | } |
| 496 | res.Body.Close() |
| 497 | } |
| 498 | stranger := getBearer(t, privPath, adaTok) |
| 499 | if stranger.StatusCode != http.StatusForbidden { |
| 500 | t.Fatalf("vreemde op prive %d", stranger.StatusCode) |
| 501 | } |
| 502 | stranger.Body.Close() |
| 503 | other := getBearer(t, ts.URL+"/api/v1/repos/tim/priv/jobs/"+strconv.FormatInt(openJob, 10)+"/log", ownerTok) |
| 504 | if other.StatusCode != http.StatusNotFound { |
| 505 | t.Fatalf("job van andere repo %d", other.StatusCode) |
| 506 | } |
| 507 | other.Body.Close() |
| 508 | |
| 509 | own := getBearer(t, privPath, ownerTok) |
| 510 | if own.StatusCode != http.StatusOK || !strings.HasPrefix(own.Header.Get("Content-Type"), "text/plain") { |
| 511 | t.Fatalf("eigenaar %d %s", own.StatusCode, own.Header.Get("Content-Type")) |
| 512 | } |
| 513 | body := read(t, own) |
| 514 | if body != "regel\n[MASKED]\n" { |
| 515 | t.Fatalf("prive log %q", body) |
| 516 | } |
| 517 | pub := getBearer(t, openPath, adaTok) |
| 518 | if pub.StatusCode != http.StatusOK { |
| 519 | t.Fatalf("publiek met vreemd token %d", pub.StatusCode) |
| 520 | } |
| 521 | if got := read(t, pub); got != "publiek [MASKED]\n" { |
| 522 | t.Fatalf("publieke log %q", got) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | func fileByPath(t *testing.T, files []any, path string) map[string]any { |
| 527 | t.Helper() |
| 528 | for _, item := range files { |
| 529 | file := item.(map[string]any) |
| 530 | if file["path"] == path { |
| 531 | return file |
| 532 | } |
| 533 | } |
| 534 | t.Fatalf("geen bestand %s in %v", path, files) |
| 535 | return nil |
| 536 | } |
| 537 | |
| 538 | func seedJobLog(t *testing.T, st *store.Store, repoID int64, log string) int64 { |
| 539 | t.Helper() |
| 540 | ctx := context.Background() |
| 541 | id, err := st.CreatePipeline(ctx, repoID, strings.Repeat("a", 40), "refs/heads/master", "push", "tim", "titel", []store.NewJob{ |
| 542 | {Name: "build", Stage: "build", Script: "echo ok"}, |
| 543 | }) |
| 544 | if err != nil { |
| 545 | t.Fatal(err) |
| 546 | } |
| 547 | jobs, err := st.JobsByPipeline(ctx, id) |
| 548 | if err != nil || len(jobs) != 1 { |
| 549 | t.Fatal(err) |
| 550 | } |
| 551 | if err := st.AppendJobLog(ctx, jobs[0].ID, log); err != nil { |
| 552 | t.Fatal(err) |
| 553 | } |
| 554 | return jobs[0].ID |
| 555 | } |
| 556 | |
| 557 | func getBearer(t *testing.T, raw, token string) *http.Response { |
| 558 | t.Helper() |
| 559 | req, err := http.NewRequest(http.MethodGet, raw, nil) |
| 560 | if err != nil { |
| 561 | t.Fatal(err) |
| 562 | } |
| 563 | req.Header.Set("Authorization", "Bearer "+token) |
| 564 | res, err := http.DefaultClient.Do(req) |
| 565 | if err != nil { |
| 566 | t.Fatal(err) |
| 567 | } |
| 568 | return res |
| 569 | } |
| 570 | |
| 571 | func mustParse(t *testing.T, raw string) *url.URL { |
| 572 | t.Helper() |
| 573 | u, err := url.Parse(raw) |
| 574 | if err != nil { |
| 575 | t.Fatal(err) |
| 576 | } |
| 577 | return u |
| 578 | } |
| 579 | |
| 580 | func mustJSON(t *testing.T, v any) string { |
| 581 | t.Helper() |
| 582 | b, err := json.Marshal(v) |
| 583 | if err != nil { |
| 584 | t.Fatal(err) |
| 585 | } |
| 586 | return string(b) |
| 587 | } |