BlueGit

timfa bluegit

Merge branch 'cursor/webhook-payload-65da' into 'master'

feat: stuur volledige details mee in webhook-payloads

See merge request Timfa/bluegit!38

timfa Tim Falken · pushed by timfa

Authored 2026-10-23 · 3 weeks ago

Hash
9bd978dfef795821506909cf63e5b550ec19bc3d
22 files changed +2280 −43
internal/gitrepo/changes.go added +208 −0
@@ -0,0 +1,208 @@
1 package gitrepo
2
3 import (
4 "context"
5 "fmt"
6 "strconv"
7 "strings"
8 )
9
10 // Change is één bestand in een diff, zonder de difftekst zelf.
11 // Status is added, modified, removed of renamed.
12 type Change struct {
13 Path string
14 OldPath string
15 Status string
16 Added int
17 Deleted int
18 Binary bool
19 }
20
21 // CommitFileChanges geeft de bestanden die sha tegen zijn eerste parent wijzigt.
22 // Een root-commit wordt met de lege boom vergeleken.
23 func CommitFileChanges(ctx context.Context, gitBin, dir, sha string) ([]Change, error) {
24 base, err := diffBase(ctx, gitBin, dir, sha)
25 if err != nil {
26 return nil, err
27 }
28 return diffChanges(ctx, gitBin, dir, base, sha)
29 }
30
31 // CompareChanges is de three-dot diff van from...to, zonder de difftekst.
32 func CompareChanges(ctx context.Context, gitBin, dir, from, to string) ([]Change, error) {
33 if from == "" || to == "" {
34 return nil, fmt.Errorf("lege vergelijking")
35 }
36 return diffChanges(ctx, gitBin, dir, from+"..."+to)
37 }
38
39 // CommitDiff is de unified diff van sha tegen zijn eerste parent.
40 func CommitDiff(ctx context.Context, gitBin, dir, sha string) (string, error) {
41 base, err := diffBase(ctx, gitBin, dir, sha)
42 if err != nil {
43 return "", err
44 }
45 return unifiedDiff(ctx, gitBin, dir, base, sha)
46 }
47
48 // CompareDiff is de unified three-dot diff van from...to.
49 func CompareDiff(ctx context.Context, gitBin, dir, from, to string) (string, error) {
50 if from == "" || to == "" {
51 return "", fmt.Errorf("lege vergelijking")
52 }
53 return unifiedDiff(ctx, gitBin, dir, from+"..."+to)
54 }
55
56 func diffBase(ctx context.Context, gitBin, dir, sha string) (string, error) {
57 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)
58 if err != nil {
59 return "", err
60 }
61 fields := strings.Fields(out)
62 if len(fields) == 0 {
63 return "", fmt.Errorf("commit niet gevonden")
64 }
65 if len(fields) > 1 {
66 return fields[1], nil
67 }
68 empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")
69 if err != nil {
70 return "", err
71 }
72 return strings.TrimSpace(empty), nil
73 }
74
75 func diffChanges(ctx context.Context, gitBin, dir string, revs ...string) ([]Change, error) {
76 nameRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--name-status", "--find-renames", "-z"}, revs...)...)
77 if err != nil {
78 return nil, err
79 }
80 numRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--numstat", "--find-renames", "-z"}, revs...)...)
81 if err != nil {
82 return nil, err
83 }
84 files := parseNameStatus(nameRaw)
85 counts, binary := parseNumstat(numRaw)
86 for i := range files {
87 key := files[i].Path
88 if n, ok := counts[key]; ok {
89 files[i].Added, files[i].Deleted = n[0], n[1]
90 }
91 if binary[key] {
92 files[i].Binary = true
93 files[i].Added, files[i].Deleted = 0, 0
94 }
95 }
96 if files == nil {
97 files = []Change{}
98 }
99 return files, nil
100 }
101
102 func unifiedDiff(ctx context.Context, gitBin, dir string, revs ...string) (string, error) {
103 return gitDiff(ctx, gitBin, dir, append([]string{"--no-color", "--find-renames", "--unified=3"}, revs...)...)
104 }
105
106 func gitDiff(ctx context.Context, gitBin, dir string, flags ...string) (string, error) {
107 args := []string{"-c", "core.quotepath=false", "-C", dir, "diff"}
108 args = append(args, flags...)
109 return runAllow(ctx, gitBin, nil, 1, args...)
110 }
111
112 func parseNameStatus(raw string) []Change {
113 parts := strings.Split(raw, "\x00")
114 var out []Change
115 for i := 0; i < len(parts); {
116 status := parts[i]
117 if status == "" {
118 i++
119 continue
120 }
121 i++
122 if i >= len(parts) {
123 break
124 }
125 if strings.HasPrefix(status, "R") || strings.HasPrefix(status, "C") {
126 old := parts[i]
127 i++
128 if i >= len(parts) {
129 break
130 }
131 path := parts[i]
132 i++
133 st := "renamed"
134 if strings.HasPrefix(status, "C") {
135 st = "modified"
136 }
137 out = append(out, Change{Path: path, OldPath: old, Status: st})
138 continue
139 }
140 out = append(out, Change{Path: parts[i], Status: changeStatus(status)})
141 i++
142 }
143 return out
144 }
145
146 func changeStatus(status string) string {
147 switch status {
148 case "A":
149 return "added"
150 case "D":
151 return "removed"
152 default:
153 return "modified"
154 }
155 }
156
157 func parseNumstat(raw string) (map[string][2]int, map[string]bool) {
158 counts := map[string][2]int{}
159 binary := map[string]bool{}
160 for _, rec := range strings.Split(raw, "\x00") {
161 rec = strings.TrimRight(rec, "\n")
162 if rec == "" {
163 continue
164 }
165 added, deleted, path, ok := splitNumstat(rec)
166 if !ok || path == "" {
167 continue
168 }
169 path = numstatPath(path)
170 if added == "-" || deleted == "-" {
171 binary[path] = true
172 continue
173 }
174 a, aErr := strconv.Atoi(added)
175 d, dErr := strconv.Atoi(deleted)
176 if aErr != nil || dErr != nil {
177 continue
178 }
179 counts[path] = [2]int{a, d}
180 }
181 return counts, binary
182 }
183
184 func splitNumstat(rec string) (added, deleted, path string, ok bool) {
185 tab := strings.IndexByte(rec, '\t')
186 if tab < 0 {
187 return "", "", "", false
188 }
189 tab2 := strings.IndexByte(rec[tab+1:], '\t')
190 if tab2 < 0 {
191 return "", "", "", false
192 }
193 tab2 += tab + 1
194 return rec[:tab], rec[tab+1 : tab2], rec[tab2+1:], true
195 }
196
197 func numstatPath(path string) string {
198 brace := strings.Index(path, "{")
199 arrow := strings.Index(path, " => ")
200 end := strings.Index(path, "}")
201 if brace >= 0 && arrow > brace && end > arrow {
202 return path[:brace] + path[arrow+4:end] + path[end+1:]
203 }
204 if arrow >= 0 {
205 return path[arrow+4:]
206 }
207 return path
208 }
@@ -0,0 +1,208 @@
1package gitrepo
2
3import (
4 "context"
5 "fmt"
6 "strconv"
7 "strings"
8)
9
10// Change is één bestand in een diff, zonder de difftekst zelf.
11// Status is added, modified, removed of renamed.
12type Change struct {
13 Path string
14 OldPath string
15 Status string
16 Added int
17 Deleted int
18 Binary bool
19}
20
21// CommitFileChanges geeft de bestanden die sha tegen zijn eerste parent wijzigt.
22// Een root-commit wordt met de lege boom vergeleken.
23func CommitFileChanges(ctx context.Context, gitBin, dir, sha string) ([]Change, error) {
24 base, err := diffBase(ctx, gitBin, dir, sha)
25 if err != nil {
26 return nil, err
27 }
28 return diffChanges(ctx, gitBin, dir, base, sha)
29}
30
31// CompareChanges is de three-dot diff van from...to, zonder de difftekst.
32func CompareChanges(ctx context.Context, gitBin, dir, from, to string) ([]Change, error) {
33 if from == "" || to == "" {
34 return nil, fmt.Errorf("lege vergelijking")
35 }
36 return diffChanges(ctx, gitBin, dir, from+"..."+to)
37}
38
39// CommitDiff is de unified diff van sha tegen zijn eerste parent.
40func CommitDiff(ctx context.Context, gitBin, dir, sha string) (string, error) {
41 base, err := diffBase(ctx, gitBin, dir, sha)
42 if err != nil {
43 return "", err
44 }
45 return unifiedDiff(ctx, gitBin, dir, base, sha)
46}
47
48// CompareDiff is de unified three-dot diff van from...to.
49func CompareDiff(ctx context.Context, gitBin, dir, from, to string) (string, error) {
50 if from == "" || to == "" {
51 return "", fmt.Errorf("lege vergelijking")
52 }
53 return unifiedDiff(ctx, gitBin, dir, from+"..."+to)
54}
55
56func diffBase(ctx context.Context, gitBin, dir, sha string) (string, error) {
57 out, err := run(ctx, gitBin, nil, "-C", dir, "rev-list", "--parents", "-n", "1", sha)
58 if err != nil {
59 return "", err
60 }
61 fields := strings.Fields(out)
62 if len(fields) == 0 {
63 return "", fmt.Errorf("commit niet gevonden")
64 }
65 if len(fields) > 1 {
66 return fields[1], nil
67 }
68 empty, err := run(ctx, gitBin, nil, "hash-object", "-t", "tree", "--stdin")
69 if err != nil {
70 return "", err
71 }
72 return strings.TrimSpace(empty), nil
73}
74
75func diffChanges(ctx context.Context, gitBin, dir string, revs ...string) ([]Change, error) {
76 nameRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--name-status", "--find-renames", "-z"}, revs...)...)
77 if err != nil {
78 return nil, err
79 }
80 numRaw, err := gitDiff(ctx, gitBin, dir, append([]string{"--numstat", "--find-renames", "-z"}, revs...)...)
81 if err != nil {
82 return nil, err
83 }
84 files := parseNameStatus(nameRaw)
85 counts, binary := parseNumstat(numRaw)
86 for i := range files {
87 key := files[i].Path
88 if n, ok := counts[key]; ok {
89 files[i].Added, files[i].Deleted = n[0], n[1]
90 }
91 if binary[key] {
92 files[i].Binary = true
93 files[i].Added, files[i].Deleted = 0, 0
94 }
95 }
96 if files == nil {
97 files = []Change{}
98 }
99 return files, nil
100}
101
102func unifiedDiff(ctx context.Context, gitBin, dir string, revs ...string) (string, error) {
103 return gitDiff(ctx, gitBin, dir, append([]string{"--no-color", "--find-renames", "--unified=3"}, revs...)...)
104}
105
106func gitDiff(ctx context.Context, gitBin, dir string, flags ...string) (string, error) {
107 args := []string{"-c", "core.quotepath=false", "-C", dir, "diff"}
108 args = append(args, flags...)
109 return runAllow(ctx, gitBin, nil, 1, args...)
110}
111
112func parseNameStatus(raw string) []Change {
113 parts := strings.Split(raw, "\x00")
114 var out []Change
115 for i := 0; i < len(parts); {
116 status := parts[i]
117 if status == "" {
118 i++
119 continue
120 }
121 i++
122 if i >= len(parts) {
123 break
124 }
125 if strings.HasPrefix(status, "R") || strings.HasPrefix(status, "C") {
126 old := parts[i]
127 i++
128 if i >= len(parts) {
129 break
130 }
131 path := parts[i]
132 i++
133 st := "renamed"
134 if strings.HasPrefix(status, "C") {
135 st = "modified"
136 }
137 out = append(out, Change{Path: path, OldPath: old, Status: st})
138 continue
139 }
140 out = append(out, Change{Path: parts[i], Status: changeStatus(status)})
141 i++
142 }
143 return out
144}
145
146func changeStatus(status string) string {
147 switch status {
148 case "A":
149 return "added"
150 case "D":
151 return "removed"
152 default:
153 return "modified"
154 }
155}
156
157func parseNumstat(raw string) (map[string][2]int, map[string]bool) {
158 counts := map[string][2]int{}
159 binary := map[string]bool{}
160 for _, rec := range strings.Split(raw, "\x00") {
161 rec = strings.TrimRight(rec, "\n")
162 if rec == "" {
163 continue
164 }
165 added, deleted, path, ok := splitNumstat(rec)
166 if !ok || path == "" {
167 continue
168 }
169 path = numstatPath(path)
170 if added == "-" || deleted == "-" {
171 binary[path] = true
172 continue
173 }
174 a, aErr := strconv.Atoi(added)
175 d, dErr := strconv.Atoi(deleted)
176 if aErr != nil || dErr != nil {
177 continue
178 }
179 counts[path] = [2]int{a, d}
180 }
181 return counts, binary
182}
183
184func splitNumstat(rec string) (added, deleted, path string, ok bool) {
185 tab := strings.IndexByte(rec, '\t')
186 if tab < 0 {
187 return "", "", "", false
188 }
189 tab2 := strings.IndexByte(rec[tab+1:], '\t')
190 if tab2 < 0 {
191 return "", "", "", false
192 }
193 tab2 += tab + 1
194 return rec[:tab], rec[tab+1 : tab2], rec[tab2+1:], true
195}
196
197func numstatPath(path string) string {
198 brace := strings.Index(path, "{")
199 arrow := strings.Index(path, " => ")
200 end := strings.Index(path, "}")
201 if brace >= 0 && arrow > brace && end > arrow {
202 return path[:brace] + path[arrow+4:end] + path[end+1:]
203 }
204 if arrow >= 0 {
205 return path[arrow+4:]
206 }
207 return path
208}
internal/gitrepo/changes_test.go added +92 −0
@@ -0,0 +1,92 @@
1 package gitrepo
2
3 import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10 )
11
12 func TestParseNameStatusAndNumstat(t *testing.T) {
13 files := parseNameStatus("M\x00README.md\x00A\x00extra.txt\x00D\x00oud.txt\x00R100\x00oude naam.txt\x00nieuwe naam.txt\x00")
14 if len(files) != 4 {
15 t.Fatalf("bestanden %d", len(files))
16 }
17 if files[0].Status != "modified" || files[0].Path != "README.md" {
18 t.Fatalf("gewijzigd %v", files[0])
19 }
20 if files[1].Status != "added" || files[2].Status != "removed" {
21 t.Fatalf("toegevoegd of weg %v %v", files[1], files[2])
22 }
23 if files[3].Status != "renamed" || files[3].OldPath != "oude naam.txt" || files[3].Path != "nieuwe naam.txt" {
24 t.Fatalf("hernoemd %v", files[3])
25 }
26 counts, binary := parseNumstat("1\t2\tREADME.md\x00-\t-\tplaatje.bin\x00")
27 if counts["README.md"] != [2]int{1, 2} || !binary["plaatje.bin"] {
28 t.Fatalf("numstat %v %v", counts, binary)
29 }
30 if got := numstatPath("dir/{oud => nieuw}/a.txt"); got != "dir/nieuw/a.txt" {
31 t.Fatalf("brace %s", got)
32 }
33 }
34
35 func TestCommitChangesAndDiff(t *testing.T) {
36 if _, err := exec.LookPath("git"); err != nil {
37 t.Skip("git ontbreekt")
38 }
39 dir := t.TempDir()
40 git := func(args ...string) {
41 t.Helper()
42 cmd := exec.Command("git", args...)
43 cmd.Dir = dir
44 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=tim", "GIT_AUTHOR_EMAIL=tim@example.com", "GIT_COMMITTER_NAME=tim", "GIT_COMMITTER_EMAIL=tim@example.com")
45 if out, err := cmd.CombinedOutput(); err != nil {
46 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
47 }
48 }
49 git("init", "-b", "master")
50 if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("a\n"), 0o644); err != nil {
51 t.Fatal(err)
52 }
53 git("add", "README.md")
54 git("commit", "-m", "eerste")
55 sha := strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
56 ctx := context.Background()
57 files, err := CommitFileChanges(ctx, "git", dir, sha)
58 if err != nil {
59 t.Fatal(err)
60 }
61 if len(files) != 1 || files[0].Path != "README.md" || files[0].Status != "added" || files[0].Added != 1 || files[0].Deleted != 0 {
62 t.Fatalf("root %v", files)
63 }
64 diff, err := CommitDiff(ctx, "git", dir, sha)
65 if err != nil || !strings.Contains(diff, "diff --git") || !strings.Contains(diff, "+a") {
66 t.Fatalf("diff %v %q", err, diff)
67 }
68 if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("b\n"), 0o644); err != nil {
69 t.Fatal(err)
70 }
71 git("add", "README.md")
72 git("commit", "-m", "tweede")
73 sha = strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
74 files, err = CommitFileChanges(ctx, "git", dir, sha)
75 if err != nil {
76 t.Fatal(err)
77 }
78 if len(files) != 1 || files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 {
79 t.Fatalf("wijziging %v", files)
80 }
81 }
82
83 func mustGit(t *testing.T, dir string, args ...string) string {
84 t.Helper()
85 cmd := exec.Command("git", args...)
86 cmd.Dir = dir
87 out, err := cmd.CombinedOutput()
88 if err != nil {
89 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
90 }
91 return string(out)
92 }
@@ -0,0 +1,92 @@
1package gitrepo
2
3import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "strings"
9 "testing"
10)
11
12func TestParseNameStatusAndNumstat(t *testing.T) {
13 files := parseNameStatus("M\x00README.md\x00A\x00extra.txt\x00D\x00oud.txt\x00R100\x00oude naam.txt\x00nieuwe naam.txt\x00")
14 if len(files) != 4 {
15 t.Fatalf("bestanden %d", len(files))
16 }
17 if files[0].Status != "modified" || files[0].Path != "README.md" {
18 t.Fatalf("gewijzigd %v", files[0])
19 }
20 if files[1].Status != "added" || files[2].Status != "removed" {
21 t.Fatalf("toegevoegd of weg %v %v", files[1], files[2])
22 }
23 if files[3].Status != "renamed" || files[3].OldPath != "oude naam.txt" || files[3].Path != "nieuwe naam.txt" {
24 t.Fatalf("hernoemd %v", files[3])
25 }
26 counts, binary := parseNumstat("1\t2\tREADME.md\x00-\t-\tplaatje.bin\x00")
27 if counts["README.md"] != [2]int{1, 2} || !binary["plaatje.bin"] {
28 t.Fatalf("numstat %v %v", counts, binary)
29 }
30 if got := numstatPath("dir/{oud => nieuw}/a.txt"); got != "dir/nieuw/a.txt" {
31 t.Fatalf("brace %s", got)
32 }
33}
34
35func TestCommitChangesAndDiff(t *testing.T) {
36 if _, err := exec.LookPath("git"); err != nil {
37 t.Skip("git ontbreekt")
38 }
39 dir := t.TempDir()
40 git := func(args ...string) {
41 t.Helper()
42 cmd := exec.Command("git", args...)
43 cmd.Dir = dir
44 cmd.Env = append(os.Environ(), "GIT_AUTHOR_NAME=tim", "GIT_AUTHOR_EMAIL=tim@example.com", "GIT_COMMITTER_NAME=tim", "GIT_COMMITTER_EMAIL=tim@example.com")
45 if out, err := cmd.CombinedOutput(); err != nil {
46 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
47 }
48 }
49 git("init", "-b", "master")
50 if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("a\n"), 0o644); err != nil {
51 t.Fatal(err)
52 }
53 git("add", "README.md")
54 git("commit", "-m", "eerste")
55 sha := strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
56 ctx := context.Background()
57 files, err := CommitFileChanges(ctx, "git", dir, sha)
58 if err != nil {
59 t.Fatal(err)
60 }
61 if len(files) != 1 || files[0].Path != "README.md" || files[0].Status != "added" || files[0].Added != 1 || files[0].Deleted != 0 {
62 t.Fatalf("root %v", files)
63 }
64 diff, err := CommitDiff(ctx, "git", dir, sha)
65 if err != nil || !strings.Contains(diff, "diff --git") || !strings.Contains(diff, "+a") {
66 t.Fatalf("diff %v %q", err, diff)
67 }
68 if err := os.WriteFile(filepath.Join(dir, "README.md"), []byte("b\n"), 0o644); err != nil {
69 t.Fatal(err)
70 }
71 git("add", "README.md")
72 git("commit", "-m", "tweede")
73 sha = strings.TrimSpace(mustGit(t, dir, "rev-parse", "HEAD"))
74 files, err = CommitFileChanges(ctx, "git", dir, sha)
75 if err != nil {
76 t.Fatal(err)
77 }
78 if len(files) != 1 || files[0].Status != "modified" || files[0].Added != 1 || files[0].Deleted != 1 {
79 t.Fatalf("wijziging %v", files)
80 }
81}
82
83func mustGit(t *testing.T, dir string, args ...string) string {
84 t.Helper()
85 cmd := exec.Command("git", args...)
86 cmd.Dir = dir
87 out, err := cmd.CombinedOutput()
88 if err != nil {
89 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
90 }
91 return string(out)
92}
internal/gitrepo/repo.go +20 −0
@@ -639,6 +639,26 @@ func allZero(sha string) bool {
639 639 return strings.Trim(sha, "0") == ""
640 640 }
641 641
642 // RangeLog geeft de commits die newSHA bereikt en old niet, nieuwste eerst.
643 // Een lege of nul-old is de geschiedenis van newSHA.
644 func RangeLog(ctx context.Context, gitBin, dir, old, newSHA string) ([]Commit, error) {
645 if newSHA == "" || allZero(newSHA) {
646 return nil, nil
647 }
648 args := []string{"-C", dir, "log", "--format=%H%x1f%an%x1f%ae%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", newSHA}
649 if old != "" && !allZero(old) {
650 args = append(args, "--not", old)
651 }
652 out, err := run(ctx, gitBin, nil, args...)
653 if err != nil {
654 if emptyHistory(err) {
655 return nil, nil
656 }
657 return nil, err
658 }
659 return parseLog(out), nil
660 }
661
642 662 // BranchOfRef haalt de branch uit refs/heads/… .
643 663 func BranchOfRef(ref string) (string, bool) {
644 664 const p = "refs/heads/"
@@ -639,6 +639,26 @@ func allZero(sha string) bool {
639 return strings.Trim(sha, "0") == ""
639 return strings.Trim(sha, "0") == ""
640}
640}
641
641
642// RangeLog geeft de commits die newSHA bereikt en old niet, nieuwste eerst.
643// Een lege of nul-old is de geschiedenis van newSHA.
644func RangeLog(ctx context.Context, gitBin, dir, old, newSHA string) ([]Commit, error) {
645 if newSHA == "" || allZero(newSHA) {
646 return nil, nil
647 }
648 args := []string{"-C", dir, "log", "--format=%H%x1f%an%x1f%ae%x1f%ad%x1f%at%x1f%s%x1f%b%x1e", "--date=short", newSHA}
649 if old != "" && !allZero(old) {
650 args = append(args, "--not", old)
651 }
652 out, err := run(ctx, gitBin, nil, args...)
653 if err != nil {
654 if emptyHistory(err) {
655 return nil, nil
656 }
657 return nil, err
658 }
659 return parseLog(out), nil
660}
661
642// BranchOfRef haalt de branch uit refs/heads/… .
662// BranchOfRef haalt de branch uit refs/heads/… .
643func BranchOfRef(ref string) (string, bool) {
663func BranchOfRef(ref string) (string, bool) {
644 const p = "refs/heads/"
664 const p = "refs/heads/"
internal/i18n/catalog_webhook.go added +40 −0
@@ -0,0 +1,40 @@
1 package i18n
2
3 func init() {
4 addCatalog(en, webhookEN)
5 addCatalog(nl, webhookNL)
6 addCatalog(de, webhookDE)
7 addCatalog(fr, webhookFR)
8 }
9
10 var webhookEN = map[string]string{
11 "info.sec.webhooks": "Webhook payloads",
12 "info.wh.spec": "OpenAPI",
13 "info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload has no diff text. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. A merge request includes id, title, description, source branch, target branch, status, author, action, reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. That diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Both diff requests need Authorization: Bearer and a personal token that can read the repo. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",
14 "hook.mrMerged": "merge request !%s merged: %s",
15 "hook.mrComment": "comment on merge request !%s",
16 }
17
18 var webhookNL = map[string]string{
19 "info.sec.webhooks": "Webhook-payloads",
20 "info.wh.spec": "OpenAPI",
21 "info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits. Elke commit heeft sha, message, auteur, timestamp, URL, gewijzigde bestanden en diff_url. Een bestand heeft status added, modified, removed of renamed, plus het aantal toegevoegde en verwijderde regels. De payload bevat geen difftekst. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur, actie, reviewers, comments, hoogstens 20 commits, diffstatistieken en diff_url, en geen difftekst. Die diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide diff-aanvragen hebben Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",
22 "hook.mrMerged": "merge request !%s samengevoegd: %s",
23 "hook.mrComment": "reactie op merge request !%s",
24 }
25
26 var webhookDE = map[string]string{
27 "info.sec.webhooks": "Webhook-Nutzdaten",
28 "info.wh.spec": "OpenAPI",
29 "info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits. Jeder Commit hat SHA, Nachricht, Autor, Zeitstempel, URL, geänderte Dateien und diff_url. Eine Datei hat den Status added, modified, removed oder renamed, plus die Zahl hinzugefügter und gelöschter Zeilen. Die Nutzdaten enthalten keinen Diff-Text. diff_url ist GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor, Aktion, Reviewer, Kommentare, höchstens 20 Commits, Diff-Statistik und diff_url, und keinen Diff-Text. Diese diff_url ist GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide Diff-Anfragen brauchen Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",
30 "hook.mrMerged": "Merge-Request !%s zusammengeführt: %s",
31 "hook.mrComment": "Kommentar zu Merge-Request !%s",
32 }
33
34 var webhookFR = map[string]string{
35 "info.sec.webhooks": "Charges utiles des webhooks",
36 "info.wh.spec": "OpenAPI",
37 "info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus. Chaque commit a sha, message, auteur, horodatage, URL, fichiers modifiés et diff_url. Un fichier a le statut added, modified, removed ou renamed, plus le nombre de lignes ajoutées et supprimées. La charge utile ne contient pas le texte du diff. diff_url vaut GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur, action, relecteurs, commentaires, 20 commits au plus, statistiques de diff et diff_url, sans le texte du diff. Cette diff_url vaut GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Les deux requêtes de diff exigent Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",
38 "hook.mrMerged": "merge request !%s fusionnée : %s",
39 "hook.mrComment": "commentaire sur la merge request !%s",
40 }
@@ -0,0 +1,40 @@
1package i18n
2
3func init() {
4 addCatalog(en, webhookEN)
5 addCatalog(nl, webhookNL)
6 addCatalog(de, webhookDE)
7 addCatalog(fr, webhookFR)
8}
9
10var webhookEN = map[string]string{
11 "info.sec.webhooks": "Webhook payloads",
12 "info.wh.spec": "OpenAPI",
13 "info.wh.lead": "An empty body template sends this JSON document. pipeline_success and pipeline_failure include the pipeline id, status, ref, sha, commit message, author and duration, and every job with its name, stage, status, duration, allow_failure, web URL and console output. Each log is the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. log_truncated is true when the log was cut. log_url is then present and is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. That request needs Authorization: Bearer and a personal token that can read the repo. A push includes ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload has no diff text. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. A merge request includes id, title, description, source branch, target branch, status, author, action, reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. That diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Both diff requests need Authorization: Bearer and a personal token that can read the repo. A comment action also includes the comment text. A release includes the tag, name, commit and assets with URLs.",
14 "hook.mrMerged": "merge request !%s merged: %s",
15 "hook.mrComment": "comment on merge request !%s",
16}
17
18var webhookNL = map[string]string{
19 "info.sec.webhooks": "Webhook-payloads",
20 "info.wh.spec": "OpenAPI",
21 "info.wh.lead": "Een leeg body-sjabloon stuurt dit JSON-document. pipeline_success en pipeline_failure bevatten het pipeline-id, de status, ref, sha, commitboodschap, auteur en duur, en elke job met naam, stage, status, duur, allow_failure, web-URL en console-output. Elke log bevat de laatste 200 regels, maximaal 64 KiB. Geheimwaarden van minstens 8 tekens worden [MASKED]. log_truncated is true als de log is afgekapt. log_url staat er dan bij en is GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Die aanvraag heeft Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Een push bevat ref, before, after en hoogstens 20 commits. Elke commit heeft sha, message, auteur, timestamp, URL, gewijzigde bestanden en diff_url. Een bestand heeft status added, modified, removed of renamed, plus het aantal toegevoegde en verwijderde regels. De payload bevat geen difftekst. diff_url is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Een merge request bevat id, titel, beschrijving, bronbranch, doelbranch, status, auteur, actie, reviewers, comments, hoogstens 20 commits, diffstatistieken en diff_url, en geen difftekst. Die diff_url is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide diff-aanvragen hebben Authorization: Bearer en een persoonlijk token dat de repo mag lezen. Bij een commentaar hoort ook de tekst. Een release bevat tag, naam, commit en assets met URL's.",
22 "hook.mrMerged": "merge request !%s samengevoegd: %s",
23 "hook.mrComment": "reactie op merge request !%s",
24}
25
26var webhookDE = map[string]string{
27 "info.sec.webhooks": "Webhook-Nutzdaten",
28 "info.wh.spec": "OpenAPI",
29 "info.wh.lead": "Eine leere Body-Vorlage sendet dieses JSON-Dokument. pipeline_success und pipeline_failure enthalten Pipeline-Id, Status, Ref, SHA, Commit-Nachricht, Autor und Dauer, sowie jeden Job mit Name, Stage, Status, Dauer, allow_failure, Web-URL und Konsolenausgabe. Jedes Log enthält die letzten 200 Zeilen, höchstens 64 KiB. Geheimwerte ab 8 Zeichen werden zu [MASKED]. log_truncated ist true, wenn das Log gekürzt wurde. log_url steht dann dabei und ist GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Diese Anfrage braucht Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Ein Push enthält ref, before, after und höchstens 20 Commits. Jeder Commit hat SHA, Nachricht, Autor, Zeitstempel, URL, geänderte Dateien und diff_url. Eine Datei hat den Status added, modified, removed oder renamed, plus die Zahl hinzugefügter und gelöschter Zeilen. Die Nutzdaten enthalten keinen Diff-Text. diff_url ist GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Ein Merge Request enthält Id, Titel, Beschreibung, Quellbranch, Zielbranch, Status, Autor, Aktion, Reviewer, Kommentare, höchstens 20 Commits, Diff-Statistik und diff_url, und keinen Diff-Text. Diese diff_url ist GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Beide Diff-Anfragen brauchen Authorization: Bearer und ein persönliches Token, das das Repo lesen darf. Bei einem Kommentar steht der Text dabei. Ein Release enthält Tag, Name, Commit und Assets mit URLs.",
30 "hook.mrMerged": "Merge-Request !%s zusammengeführt: %s",
31 "hook.mrComment": "Kommentar zu Merge-Request !%s",
32}
33
34var webhookFR = map[string]string{
35 "info.sec.webhooks": "Charges utiles des webhooks",
36 "info.wh.spec": "OpenAPI",
37 "info.wh.lead": "Un modèle de corps vide envoie ce document JSON. pipeline_success et pipeline_failure contiennent l'id du pipeline, le statut, la ref, le sha, le message de commit, l'auteur et la durée, plus chaque job avec nom, stage, statut, durée, allow_failure, URL web et sortie console. Chaque log contient les 200 dernières lignes, 64 KiB au plus. Les valeurs secrètes d'au moins 8 caractères deviennent [MASKED]. log_truncated vaut true quand le log est coupé. log_url est alors présent et vaut GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Cette requête exige Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Un push contient ref, before, after et 20 commits au plus. Chaque commit a sha, message, auteur, horodatage, URL, fichiers modifiés et diff_url. Un fichier a le statut added, modified, removed ou renamed, plus le nombre de lignes ajoutées et supprimées. La charge utile ne contient pas le texte du diff. diff_url vaut GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Une merge request contient id, titre, description, branche source, branche cible, statut, auteur, action, relecteurs, commentaires, 20 commits au plus, statistiques de diff et diff_url, sans le texte du diff. Cette diff_url vaut GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Les deux requêtes de diff exigent Authorization: Bearer et un jeton personnel qui peut lire le dépôt. Une action commented contient aussi le texte. Une release contient le tag, le nom, le commit et les assets avec leurs URL.",
38 "hook.mrMerged": "merge request !%s fusionnée : %s",
39 "hook.mrComment": "commentaire sur la merge request !%s",
40}
internal/server/api.go +116 −0
@@ -5,9 +5,12 @@ import (
5 5 "net/http"
6 6 "os"
7 7 "path/filepath"
8 "strconv"
8 9 "strings"
9 10
10 11 "gitlab.com/Timfa/bluegit/internal/access"
12 "gitlab.com/Timfa/bluegit/internal/ci"
13 "gitlab.com/Timfa/bluegit/internal/gitrepo"
11 14 "gitlab.com/Timfa/bluegit/internal/i18n"
12 15 "gitlab.com/Timfa/bluegit/internal/store"
13 16 )
@@ -84,6 +87,119 @@ func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
84 87 http.NotFound(w, r)
85 88 }
86 89
90 // jobLogAPI geeft de volledige console-output van een job, met geheimen gemaskeerd.
91 // Een persoonlijk token is verplicht, ook bij een publieke repo. Job-tokens tellen niet.
92 func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {
93 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
94 if err != nil {
95 http.NotFound(w, r)
96 return
97 }
98 if !s.authorizeRepoRead(w, r, repo) {
99 return
100 }
101 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
102 if err != nil || id <= 0 {
103 http.NotFound(w, r)
104 return
105 }
106 job, err := s.Store.JobByID(r.Context(), repo.ID, id)
107 if err != nil {
108 http.NotFound(w, r)
109 return
110 }
111 text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
112 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
113 w.Header().Set("Cache-Control", "no-store")
114 _, _ = w.Write([]byte(text))
115 }
116
117 // authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat
118 // elk geldig token. Op een privérepo moet het token de repo mogen lezen.
119 func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {
120 token := bearer(r)
121 if token == "" {
122 http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
123 return false
124 }
125 if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {
126 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
127 return false
128 }
129 u, err := s.Store.UserByToken(r.Context(), token)
130 if err != nil {
131 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
132 return false
133 }
134 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
135 if err != nil {
136 http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
137 return false
138 }
139 if !role.CanRead() && repo.Visibility != "public" {
140 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
141 return false
142 }
143 return true
144 }
145
146 // commitDiffAPI geeft de unified diff van één commit.
147 func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
148 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
149 if err != nil {
150 http.NotFound(w, r)
151 return
152 }
153 if !s.authorizeRepoRead(w, r, repo) {
154 return
155 }
156 sha := r.PathValue("sha")
157 if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
158 http.NotFound(w, r)
159 return
160 }
161 text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
162 if err != nil {
163 http.NotFound(w, r)
164 return
165 }
166 writePlain(w, text)
167 }
168
169 // mrDiffAPI geeft de three-dot diff van een merge request.
170 func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
171 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
172 if err != nil {
173 http.NotFound(w, r)
174 return
175 }
176 if !s.authorizeRepoRead(w, r, repo) {
177 return
178 }
179 number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
180 if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
181 http.NotFound(w, r)
182 return
183 }
184 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
185 if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
186 http.NotFound(w, r)
187 return
188 }
189 text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
190 if err != nil {
191 http.NotFound(w, r)
192 return
193 }
194 writePlain(w, text)
195 }
196
197 func writePlain(w http.ResponseWriter, text string) {
198 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
199 w.Header().Set("Cache-Control", "no-store")
200 _, _ = w.Write([]byte(text))
201 }
202
87 203 func bearer(r *http.Request) string {
88 204 h := r.Header.Get("Authorization")
89 205 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
@@ -5,9 +5,12 @@ import (
5 "net/http"
5 "net/http"
6 "os"
6 "os"
7 "path/filepath"
7 "path/filepath"
8 "strconv"
8 "strings"
9 "strings"
9
10
10 "gitlab.com/Timfa/bluegit/internal/access"
11 "gitlab.com/Timfa/bluegit/internal/access"
12 "gitlab.com/Timfa/bluegit/internal/ci"
13 "gitlab.com/Timfa/bluegit/internal/gitrepo"
11 "gitlab.com/Timfa/bluegit/internal/i18n"
14 "gitlab.com/Timfa/bluegit/internal/i18n"
12 "gitlab.com/Timfa/bluegit/internal/store"
15 "gitlab.com/Timfa/bluegit/internal/store"
13)
16)
@@ -84,6 +87,119 @@ func (s *Server) releaseAsset(w http.ResponseWriter, r *http.Request) {
84 http.NotFound(w, r)
87 http.NotFound(w, r)
85}
88}
86
89
90// jobLogAPI geeft de volledige console-output van een job, met geheimen gemaskeerd.
91// Een persoonlijk token is verplicht, ook bij een publieke repo. Job-tokens tellen niet.
92func (s *Server) jobLogAPI(w http.ResponseWriter, r *http.Request) {
93 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
94 if err != nil {
95 http.NotFound(w, r)
96 return
97 }
98 if !s.authorizeRepoRead(w, r, repo) {
99 return
100 }
101 id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
102 if err != nil || id <= 0 {
103 http.NotFound(w, r)
104 return
105 }
106 job, err := s.Store.JobByID(r.Context(), repo.ID, id)
107 if err != nil {
108 http.NotFound(w, r)
109 return
110 }
111 text := ci.Mask(job.Log, s.maskSecrets(r.Context(), repo))
112 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
113 w.Header().Set("Cache-Control", "no-store")
114 _, _ = w.Write([]byte(text))
115}
116
117// authorizeRepoRead eist een persoonlijk token. Op een publieke repo volstaat
118// elk geldig token. Op een privérepo moet het token de repo mogen lezen.
119func (s *Server) authorizeRepoRead(w http.ResponseWriter, r *http.Request, repo store.Repo) bool {
120 token := bearer(r)
121 if token == "" {
122 http.Error(w, s.tr(r, "err.tokenAbsent"), http.StatusUnauthorized)
123 return false
124 }
125 if strings.HasPrefix(token, "bgj_") || !strings.HasPrefix(token, "bg_") {
126 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
127 return false
128 }
129 u, err := s.Store.UserByToken(r.Context(), token)
130 if err != nil {
131 http.Error(w, s.tr(r, "err.tokenBad"), http.StatusUnauthorized)
132 return false
133 }
134 role, err := s.Store.EffectiveRole(r.Context(), u.ID, repo.ID)
135 if err != nil {
136 http.Error(w, s.tr(r, "err.rights"), http.StatusInternalServerError)
137 return false
138 }
139 if !role.CanRead() && repo.Visibility != "public" {
140 http.Error(w, s.tr(r, "err.forbidden"), http.StatusForbidden)
141 return false
142 }
143 return true
144}
145
146// commitDiffAPI geeft de unified diff van één commit.
147func (s *Server) commitDiffAPI(w http.ResponseWriter, r *http.Request) {
148 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
149 if err != nil {
150 http.NotFound(w, r)
151 return
152 }
153 if !s.authorizeRepoRead(w, r, repo) {
154 return
155 }
156 sha := r.PathValue("sha")
157 if !safeSHA(sha) || s.Git == "" || s.StoragePath() == "" {
158 http.NotFound(w, r)
159 return
160 }
161 text, err := gitrepo.CommitDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), sha)
162 if err != nil {
163 http.NotFound(w, r)
164 return
165 }
166 writePlain(w, text)
167}
168
169// mrDiffAPI geeft de three-dot diff van een merge request.
170func (s *Server) mrDiffAPI(w http.ResponseWriter, r *http.Request) {
171 repo, err := s.Store.RepoByPath(r.Context(), r.PathValue("owner"), r.PathValue("repo"))
172 if err != nil {
173 http.NotFound(w, r)
174 return
175 }
176 if !s.authorizeRepoRead(w, r, repo) {
177 return
178 }
179 number, err := strconv.ParseInt(r.PathValue("number"), 10, 64)
180 if err != nil || number <= 0 || s.Git == "" || s.StoragePath() == "" {
181 http.NotFound(w, r)
182 return
183 }
184 mr, err := s.Store.MergeRequestByNumber(r.Context(), repo.ID, number)
185 if err != nil || safeRev(mr.SourceBranch, "") != mr.SourceBranch || safeRev(mr.TargetBranch, "") != mr.TargetBranch {
186 http.NotFound(w, r)
187 return
188 }
189 text, err := gitrepo.CompareDiff(r.Context(), s.Git, gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name), mr.TargetBranch, mr.SourceBranch)
190 if err != nil {
191 http.NotFound(w, r)
192 return
193 }
194 writePlain(w, text)
195}
196
197func writePlain(w http.ResponseWriter, text string) {
198 w.Header().Set("Content-Type", "text/plain; charset=utf-8")
199 w.Header().Set("Cache-Control", "no-store")
200 _, _ = w.Write([]byte(text))
201}
202
87func bearer(r *http.Request) string {
203func bearer(r *http.Request) string {
88 h := r.Header.Get("Authorization")
204 h := r.Header.Get("Authorization")
89 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
205 if strings.HasPrefix(strings.ToLower(h), "bearer ") {
internal/server/editor.go +1 −2
@@ -152,11 +152,10 @@ func (s *Server) openCIMergeRequest(r *http.Request, repo store.Repo, author sto
152 152 if err != nil {
153 153 return 0, err
154 154 }
155 num := strconv.FormatInt(mr.Number, 10)
156 155 if sha := gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "refs/heads/"+branch); sha != "" {
157 156 s.startOneMergePipeline(r.Context(), repo, sha, author.Username, "", mr)
158 157 }
159 s.Dispatch(repo.ID, pushEvent(repo, "merge_request", target, "", author.Username, s.tr(r, "hook.mr", num, mr.Title), repoURL(repo)+"/-/merge-requests/"+num))
158 s.mrHook(repo, mr, author.Username, "opened", "")
160 159 s.recordContribution(author.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
161 160 return mr.Number, nil
162 161 }
@@ -152,11 +152,10 @@ func (s *Server) openCIMergeRequest(r *http.Request, repo store.Repo, author sto
152 if err != nil {
152 if err != nil {
153 return 0, err
153 return 0, err
154 }
154 }
155 num := strconv.FormatInt(mr.Number, 10)
156 if sha := gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "refs/heads/"+branch); sha != "" {
155 if sha := gitOne(r.Context(), s.Git, dir, "rev-parse", "--verify", "refs/heads/"+branch); sha != "" {
157 s.startOneMergePipeline(r.Context(), repo, sha, author.Username, "", mr)
156 s.startOneMergePipeline(r.Context(), repo, sha, author.Username, "", mr)
158 }
157 }
159 s.Dispatch(repo.ID, pushEvent(repo, "merge_request", target, "", author.Username, s.tr(r, "hook.mr", num, mr.Title), repoURL(repo)+"/-/merge-requests/"+num))
158 s.mrHook(repo, mr, author.Username, "opened", "")
160 s.recordContribution(author.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
159 s.recordContribution(author.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
161 return mr.Number, nil
160 return mr.Number, nil
162}
161}
internal/server/events.go +19 −14
@@ -54,10 +54,9 @@ func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[s
54 54 }
55 55 commit := s.peeled(repo, sha)
56 56 if strings.HasPrefix(ref, "refs/tags/") {
57 name := strings.TrimPrefix(ref, "refs/tags/")
58 57 s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil)
59 58 s.recordContribution(user.ID, repo.ID, "tag", ref, time.Now().UTC())
60 s.pushHook(repo, actor, name, commit)
59 s.pushHook(repo, actor, ref, before[ref], sha)
61 60 continue
62 61 }
63 62 branch, ok := gitrepo.BranchOfRef(ref)
@@ -69,17 +68,24 @@ func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[s
69 68 s.startMergeRequestPipelines(context.Background(), repo, commit, branch, actor, before[ref])
70 69 s.recordMRPushes(repo, user, branch, before[ref], sha)
71 70 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
72 s.pushHook(repo, actor, branch, commit)
71 s.pushHook(repo, actor, ref, before[ref], sha)
73 72 }
74 73 }
75 74
76 func (s *Server) pushHook(repo store.Repo, actor, branch, commit string) {
75 func (s *Server) pushHook(repo store.Repo, actor, ref, before, after string) {
76 if isZero(before) {
77 before = strings.Repeat("0", 40)
78 }
79 name := refName(ref)
77 80 s.Dispatch(repo.ID, webhook.Event{
78 81 Type: webhook.EventPush,
79 82 Project: repo.FullPath(),
80 Branch: branch,
81 Commit: commit,
82 Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
83 Branch: name,
84 Ref: ref,
85 Before: before,
86 After: after,
87 Commit: after,
88 Summary: i18n.T(i18n.EN, "hook.push", actor, name, repo.FullPath()),
83 89 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(),
84 90 Actor: actor,
85 91 })
@@ -188,13 +194,6 @@ func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []st
188 194 return strings.Split(text, "\n")
189 195 }
190 196
191 func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
192 return webhook.Event{
193 Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
194 Actor: actor, Summary: summary, URL: path,
195 }
196 }
197
198 197 func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
199 198 ctx := context.Background()
200 199 repo, err := s.Store.RepoByID(ctx, repoID)
@@ -212,6 +211,7 @@ func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
212 211 ev.Group = g.Path
213 212 }
214 213 }
214 ev = s.enrichEvent(ctx, repo, ev)
215 215 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
216 216 protected := access.BranchProtected(patterns, ev.Branch)
217 217 s.deliver(ctx, "repo", repo.ID, ev, protected, repo)
@@ -270,6 +270,11 @@ func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev web
270 270 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
271 271 continue
272 272 }
273 if s.hookSink != nil {
274 s.hookSink(body)
275 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, "")
276 continue
277 }
273 278 method := h.Method
274 279 if method == "" {
275 280 method = http.MethodPost
@@ -54,10 +54,9 @@ func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[s
54 }
54 }
55 commit := s.peeled(repo, sha)
55 commit := s.peeled(repo, sha)
56 if strings.HasPrefix(ref, "refs/tags/") {
56 if strings.HasPrefix(ref, "refs/tags/") {
57 name := strings.TrimPrefix(ref, "refs/tags/")
58 s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil)
57 s.startPipeline(context.Background(), repo, commit, ref, actor, "push", before[ref], nil)
59 s.recordContribution(user.ID, repo.ID, "tag", ref, time.Now().UTC())
58 s.recordContribution(user.ID, repo.ID, "tag", ref, time.Now().UTC())
60 s.pushHook(repo, actor, name, commit)
59 s.pushHook(repo, actor, ref, before[ref], sha)
61 continue
60 continue
62 }
61 }
63 branch, ok := gitrepo.BranchOfRef(ref)
62 branch, ok := gitrepo.BranchOfRef(ref)
@@ -69,17 +68,24 @@ func (s *Server) AfterPush(repo store.Repo, user store.User, before, after map[s
69 s.startMergeRequestPipelines(context.Background(), repo, commit, branch, actor, before[ref])
68 s.startMergeRequestPipelines(context.Background(), repo, commit, branch, actor, before[ref])
70 s.recordMRPushes(repo, user, branch, before[ref], sha)
69 s.recordMRPushes(repo, user, branch, before[ref], sha)
71 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
70 s.rerunMergeRequestsOnTarget(context.Background(), repo, branch, actor)
72 s.pushHook(repo, actor, branch, commit)
71 s.pushHook(repo, actor, ref, before[ref], sha)
73 }
72 }
74}
73}
75
74
76func (s *Server) pushHook(repo store.Repo, actor, branch, commit string) {
75func (s *Server) pushHook(repo store.Repo, actor, ref, before, after string) {
76 if isZero(before) {
77 before = strings.Repeat("0", 40)
78 }
79 name := refName(ref)
77 s.Dispatch(repo.ID, webhook.Event{
80 s.Dispatch(repo.ID, webhook.Event{
78 Type: webhook.EventPush,
81 Type: webhook.EventPush,
79 Project: repo.FullPath(),
82 Project: repo.FullPath(),
80 Branch: branch,
83 Branch: name,
81 Commit: commit,
84 Ref: ref,
82 Summary: i18n.T(i18n.EN, "hook.push", actor, branch, repo.FullPath()),
85 Before: before,
86 After: after,
87 Commit: after,
88 Summary: i18n.T(i18n.EN, "hook.push", actor, name, repo.FullPath()),
83 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(),
89 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + "/" + repo.FullPath(),
84 Actor: actor,
90 Actor: actor,
85 })
91 })
@@ -188,13 +194,6 @@ func changedFiles(ctx context.Context, gitBin, dir, sha, before string, all []st
188 return strings.Split(text, "\n")
194 return strings.Split(text, "\n")
189}
195}
190
196
191func pushEvent(repo store.Repo, kind, branch, commit, actor, summary, path string) webhook.Event {
192 return webhook.Event{
193 Type: kind, Project: repo.FullPath(), Branch: branch, Commit: commit,
194 Actor: actor, Summary: summary, URL: path,
195 }
196}
197
198func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
197func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
199 ctx := context.Background()
198 ctx := context.Background()
200 repo, err := s.Store.RepoByID(ctx, repoID)
199 repo, err := s.Store.RepoByID(ctx, repoID)
@@ -212,6 +211,7 @@ func (s *Server) Dispatch(repoID int64, ev webhook.Event) {
212 ev.Group = g.Path
211 ev.Group = g.Path
213 }
212 }
214 }
213 }
214 ev = s.enrichEvent(ctx, repo, ev)
215 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
215 patterns, _ := s.Store.ProtectedPatterns(ctx, repo.ID)
216 protected := access.BranchProtected(patterns, ev.Branch)
216 protected := access.BranchProtected(patterns, ev.Branch)
217 s.deliver(ctx, "repo", repo.ID, ev, protected, repo)
217 s.deliver(ctx, "repo", repo.ID, ev, protected, repo)
@@ -270,6 +270,11 @@ func (s *Server) deliver(ctx context.Context, kind string, scopeID int64, ev web
270 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
270 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, err.Error())
271 continue
271 continue
272 }
272 }
273 if s.hookSink != nil {
274 s.hookSink(body)
275 _ = s.Store.AddDelivery(ctx, h.ID, ev.Type, 0, "")
276 continue
277 }
273 method := h.Method
278 method := h.Method
274 if method == "" {
279 if method == "" {
275 method = http.MethodPost
280 method = http.MethodPost
internal/server/hook_payload.go added +330 −0
@@ -0,0 +1,330 @@
1 package server
2
3 import (
4 "context"
5 "math"
6 "net/url"
7 "strconv"
8 "strings"
9 "time"
10
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/store"
14 "gitlab.com/Timfa/bluegit/internal/webhook"
15 )
16
17 // enrichEvent vult de details die de JSON-body van een webhook meestuurt.
18 func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Event) webhook.Event {
19 switch ev.Type {
20 case webhook.EventPipelineSuccess, webhook.EventPipelineFailure:
21 s.fillPipelineEvent(ctx, repo, &ev)
22 case webhook.EventPush:
23 s.fillPushEvent(ctx, repo, &ev)
24 case webhook.EventMergeRequest:
25 s.fillMREvent(ctx, repo, &ev)
26 }
27 return ev
28 }
29
30 func (s *Server) fillPipelineEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
31 id, err := strconv.ParseInt(ev.PipelineID, 10, 64)
32 if err != nil || id <= 0 || s.Store == nil {
33 return
34 }
35 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
36 if err != nil {
37 return
38 }
39 base := strings.TrimRight(s.Cfg.BaseURL, "/")
40 pipeURL := base + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
41 if ev.URL == "" || !strings.HasPrefix(ev.URL, "http") {
42 ev.URL = pipeURL
43 }
44 if ev.Commit == "" {
45 ev.Commit = p.CommitSHA
46 }
47 if ev.Branch == "" {
48 ev.Branch = refName(p.Ref)
49 }
50 if ev.Actor == "" {
51 ev.Actor = p.Actor
52 }
53 msg := p.CommitTitle
54 author := p.Actor
55 if s.Git != "" && s.StoragePath() != "" && p.CommitSHA != "" {
56 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
57 if c, err := gitrepo.Show(ctx, s.Git, dir, p.CommitSHA); err == nil && c.SHA != "" {
58 if text := commitText(c); text != "" {
59 msg = text
60 }
61 if author == "" {
62 author = commitAuthor(c)
63 }
64 }
65 }
66 ev.PipelineID = strconv.FormatInt(p.ID, 10)
67 ev.Pipeline = &webhook.PipelineInfo{
68 ID: p.ID, Status: p.Status, Ref: p.Ref, SHA: p.CommitSHA,
69 CommitMessage: msg, Author: author, Duration: elapsedSeconds(p.StartedAt, p.FinishedAt),
70 URL: pipeURL,
71 }
72 jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
73 if err != nil {
74 return
75 }
76 secrets := s.maskSecrets(ctx, repo)
77 ev.Jobs = make([]webhook.JobInfo, 0, len(jobs))
78 for _, j := range jobs {
79 logText, truncated := webhook.TailLog(j.Log, secrets)
80 info := webhook.JobInfo{
81 Name: j.Name, Stage: j.Stage, Status: j.Status,
82 Duration: elapsedSeconds(j.StartedAt, j.FinishedAt),
83 AllowFailure: j.AllowFailure,
84 WebURL: pipeURL + "/jobs/" + strconv.FormatInt(j.ID, 10),
85 Log: logText,
86 LogTruncated: truncated,
87 }
88 if truncated {
89 info.LogURL = jobLogAPIURL(s.Cfg.BaseURL, repo, j.ID)
90 }
91 ev.Jobs = append(ev.Jobs, info)
92 }
93 }
94
95 func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
96 if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
97 if ev.Commits == nil {
98 ev.Commits = []webhook.CommitInfo{}
99 }
100 return
101 }
102 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
103 list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
104 if err != nil || len(list) == 0 {
105 ev.Commits = []webhook.CommitInfo{}
106 return
107 }
108 if len(list) > webhook.MaxPushCommits {
109 list = list[:webhook.MaxPushCommits]
110 }
111 ev.Commits = make([]webhook.CommitInfo, 0, len(list))
112 for i := len(list) - 1; i >= 0; i-- {
113 ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))
114 }
115 }
116
117 func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
118 if ev.MergeRequest == nil {
119 return
120 }
121 mr := ev.MergeRequest
122 if mr.Reviewers == nil {
123 mr.Reviewers = []webhook.ReviewerInfo{}
124 }
125 if mr.Comments == nil {
126 mr.Comments = []webhook.CommentInfo{}
127 }
128 if mr.Commits == nil {
129 mr.Commits = []webhook.CommitInfo{}
130 }
131 if mr.DiffStats.Files == nil {
132 mr.DiffStats.Files = []webhook.FileChange{}
133 }
134 mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)
135 if s.Store != nil && mr.ID > 0 {
136 if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {
137 if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {
138 mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))
139 for _, rev := range revs {
140 mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})
141 }
142 }
143 if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {
144 mr.Comments = make([]webhook.CommentInfo, 0, len(notes))
145 for _, n := range notes {
146 mr.Comments = append(mr.Comments, webhook.CommentInfo{
147 ID: n.ID, Author: n.Author, Body: n.Body,
148 CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),
149 FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,
150 ParentID: n.ParentID,
151 })
152 }
153 }
154 }
155 }
156 if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {
157 return
158 }
159 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
160 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
161 stats := webhook.DiffStats{Files: fileChanges(changes)}
162 for _, f := range stats.Files {
163 stats.Additions += f.Additions
164 stats.Deletions += f.Deletions
165 }
166 mr.DiffStats = stats
167 }
168 list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)
169 if err != nil || len(list) == 0 {
170 mr.Commits = []webhook.CommitInfo{}
171 return
172 }
173 mr.Commits = make([]webhook.CommitInfo, 0, len(list))
174 for i := len(list) - 1; i >= 0; i-- {
175 mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))
176 }
177 }
178
179 func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {
180 base := strings.TrimRight(s.Cfg.BaseURL, "/")
181 info := webhook.CommitInfo{
182 SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
183 Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),
184 URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
185 DiffURL: commitDiffAPIURL(base, repo, c.SHA),
186 Files: []webhook.FileChange{},
187 }
188 if s.Git == "" || s.StoragePath() == "" {
189 return info
190 }
191 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
192 files, err := gitrepo.CommitFileChanges(ctx, s.Git, dir, c.SHA)
193 if err != nil {
194 return info
195 }
196 info.Files = fileChanges(files)
197 return info
198 }
199
200 func fileChanges(list []gitrepo.Change) []webhook.FileChange {
201 out := make([]webhook.FileChange, 0, len(list))
202 for _, c := range list {
203 out = append(out, webhook.FileChange{
204 Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,
205 Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,
206 })
207 }
208 return out
209 }
210
211 func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
212 if s.Store == nil {
213 return nil
214 }
215 var out []string
216 add := func(kind string, id int64) {
217 vals, err := s.Store.SecretValues(ctx, kind, id, true)
218 if err != nil {
219 return
220 }
221 for _, v := range vals {
222 out = append(out, v)
223 }
224 }
225 add("repo", repo.ID)
226 if repo.OwnerKind == "group" {
227 add("group", repo.OwnerID)
228 }
229 return out
230 }
231
232 func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
233 num := strconv.FormatInt(mr.Number, 10)
234 path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
235 summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
236 switch action {
237 case "merged":
238 summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
239 case "commented":
240 summary = i18n.T(i18n.EN, "hook.mrComment", num)
241 }
242 return webhook.Event{
243 Type: webhook.EventMergeRequest,
244 Project: repo.FullPath(),
245 Branch: mr.TargetBranch,
246 Actor: actor,
247 Summary: summary,
248 URL: path,
249 Comment: comment,
250 MergeRequest: &webhook.MRInfo{
251 ID: mr.Number, Title: mr.Title, Description: mr.Description,
252 SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
253 Status: mr.Status, Author: mr.Author, Action: action, URL: path,
254 },
255 }
256 }
257
258 func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
259 s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
260 }
261
262 func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
263 base := strings.TrimRight(s.Cfg.BaseURL, "/")
264 page := base + repoURL(repo) + "/-/releases"
265 list := make([]webhook.AssetInfo, 0, len(assets))
266 for _, a := range assets {
267 list = append(list, webhook.AssetInfo{
268 Name: a.Name, Size: a.Size,
269 URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
270 })
271 }
272 return webhook.Event{
273 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
274 ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
275 URL: page,
276 Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
277 }
278 }
279
280 func commitDiffAPIURL(base string, repo store.Repo, sha string) string {
281 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"
282 }
283
284 func mrDiffAPIURL(base string, repo store.Repo, number int64) string {
285 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"
286 }
287
288 func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
289 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
290 }
291
292 func refName(ref string) string {
293 if b, ok := gitrepo.BranchOfRef(ref); ok {
294 return b
295 }
296 if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
297 return name
298 }
299 return ref
300 }
301
302 func commitText(c gitrepo.Commit) string {
303 if c.Subject == "" {
304 return strings.TrimSpace(c.Body)
305 }
306 if strings.TrimSpace(c.Body) == "" {
307 return c.Subject
308 }
309 return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
310 }
311
312 func commitAuthor(c gitrepo.Commit) string {
313 name := strings.TrimSpace(c.Author)
314 email := strings.TrimSpace(c.Email)
315 switch {
316 case name == "":
317 return email
318 case email == "":
319 return name
320 default:
321 return name + " <" + email + ">"
322 }
323 }
324
325 func elapsedSeconds(start, end time.Time) float64 {
326 if start.IsZero() || end.IsZero() || end.Before(start) {
327 return 0
328 }
329 return math.Round(end.Sub(start).Seconds()*1000) / 1000
330 }
@@ -0,0 +1,330 @@
1package server
2
3import (
4 "context"
5 "math"
6 "net/url"
7 "strconv"
8 "strings"
9 "time"
10
11 "gitlab.com/Timfa/bluegit/internal/gitrepo"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/store"
14 "gitlab.com/Timfa/bluegit/internal/webhook"
15)
16
17// enrichEvent vult de details die de JSON-body van een webhook meestuurt.
18func (s *Server) enrichEvent(ctx context.Context, repo store.Repo, ev webhook.Event) webhook.Event {
19 switch ev.Type {
20 case webhook.EventPipelineSuccess, webhook.EventPipelineFailure:
21 s.fillPipelineEvent(ctx, repo, &ev)
22 case webhook.EventPush:
23 s.fillPushEvent(ctx, repo, &ev)
24 case webhook.EventMergeRequest:
25 s.fillMREvent(ctx, repo, &ev)
26 }
27 return ev
28}
29
30func (s *Server) fillPipelineEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
31 id, err := strconv.ParseInt(ev.PipelineID, 10, 64)
32 if err != nil || id <= 0 || s.Store == nil {
33 return
34 }
35 p, err := s.Store.PipelineByID(ctx, repo.ID, id)
36 if err != nil {
37 return
38 }
39 base := strings.TrimRight(s.Cfg.BaseURL, "/")
40 pipeURL := base + "/" + repo.FullPath() + "/-/pipelines/" + strconv.FormatInt(p.ID, 10)
41 if ev.URL == "" || !strings.HasPrefix(ev.URL, "http") {
42 ev.URL = pipeURL
43 }
44 if ev.Commit == "" {
45 ev.Commit = p.CommitSHA
46 }
47 if ev.Branch == "" {
48 ev.Branch = refName(p.Ref)
49 }
50 if ev.Actor == "" {
51 ev.Actor = p.Actor
52 }
53 msg := p.CommitTitle
54 author := p.Actor
55 if s.Git != "" && s.StoragePath() != "" && p.CommitSHA != "" {
56 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
57 if c, err := gitrepo.Show(ctx, s.Git, dir, p.CommitSHA); err == nil && c.SHA != "" {
58 if text := commitText(c); text != "" {
59 msg = text
60 }
61 if author == "" {
62 author = commitAuthor(c)
63 }
64 }
65 }
66 ev.PipelineID = strconv.FormatInt(p.ID, 10)
67 ev.Pipeline = &webhook.PipelineInfo{
68 ID: p.ID, Status: p.Status, Ref: p.Ref, SHA: p.CommitSHA,
69 CommitMessage: msg, Author: author, Duration: elapsedSeconds(p.StartedAt, p.FinishedAt),
70 URL: pipeURL,
71 }
72 jobs, err := s.Store.JobsByPipeline(ctx, p.ID)
73 if err != nil {
74 return
75 }
76 secrets := s.maskSecrets(ctx, repo)
77 ev.Jobs = make([]webhook.JobInfo, 0, len(jobs))
78 for _, j := range jobs {
79 logText, truncated := webhook.TailLog(j.Log, secrets)
80 info := webhook.JobInfo{
81 Name: j.Name, Stage: j.Stage, Status: j.Status,
82 Duration: elapsedSeconds(j.StartedAt, j.FinishedAt),
83 AllowFailure: j.AllowFailure,
84 WebURL: pipeURL + "/jobs/" + strconv.FormatInt(j.ID, 10),
85 Log: logText,
86 LogTruncated: truncated,
87 }
88 if truncated {
89 info.LogURL = jobLogAPIURL(s.Cfg.BaseURL, repo, j.ID)
90 }
91 ev.Jobs = append(ev.Jobs, info)
92 }
93}
94
95func (s *Server) fillPushEvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
96 if ev.Commits != nil || s.Git == "" || s.StoragePath() == "" || ev.After == "" {
97 if ev.Commits == nil {
98 ev.Commits = []webhook.CommitInfo{}
99 }
100 return
101 }
102 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
103 list, err := gitrepo.RangeLog(ctx, s.Git, dir, ev.Before, ev.After)
104 if err != nil || len(list) == 0 {
105 ev.Commits = []webhook.CommitInfo{}
106 return
107 }
108 if len(list) > webhook.MaxPushCommits {
109 list = list[:webhook.MaxPushCommits]
110 }
111 ev.Commits = make([]webhook.CommitInfo, 0, len(list))
112 for i := len(list) - 1; i >= 0; i-- {
113 ev.Commits = append(ev.Commits, s.commitInfo(ctx, repo, list[i]))
114 }
115}
116
117func (s *Server) fillMREvent(ctx context.Context, repo store.Repo, ev *webhook.Event) {
118 if ev.MergeRequest == nil {
119 return
120 }
121 mr := ev.MergeRequest
122 if mr.Reviewers == nil {
123 mr.Reviewers = []webhook.ReviewerInfo{}
124 }
125 if mr.Comments == nil {
126 mr.Comments = []webhook.CommentInfo{}
127 }
128 if mr.Commits == nil {
129 mr.Commits = []webhook.CommitInfo{}
130 }
131 if mr.DiffStats.Files == nil {
132 mr.DiffStats.Files = []webhook.FileChange{}
133 }
134 mr.DiffURL = mrDiffAPIURL(s.Cfg.BaseURL, repo, mr.ID)
135 if s.Store != nil && mr.ID > 0 {
136 if stored, err := s.Store.MergeRequestByNumber(ctx, repo.ID, mr.ID); err == nil {
137 if revs, err := s.Store.ListReviews(ctx, stored.ID); err == nil {
138 mr.Reviewers = make([]webhook.ReviewerInfo, 0, len(revs))
139 for _, rev := range revs {
140 mr.Reviewers = append(mr.Reviewers, webhook.ReviewerInfo{Username: rev.Username, Status: rev.Status})
141 }
142 }
143 if notes, err := s.Store.ListNotes(ctx, stored.ID); err == nil {
144 mr.Comments = make([]webhook.CommentInfo, 0, len(notes))
145 for _, n := range notes {
146 mr.Comments = append(mr.Comments, webhook.CommentInfo{
147 ID: n.ID, Author: n.Author, Body: n.Body,
148 CreatedAt: n.CreatedAt.UTC().Format(time.RFC3339),
149 FilePath: n.FilePath, LineStart: n.LineStart, LineEnd: n.LineEnd,
150 ParentID: n.ParentID,
151 })
152 }
153 }
154 }
155 }
156 if s.Git == "" || s.StoragePath() == "" || mr.SourceBranch == "" || mr.TargetBranch == "" {
157 return
158 }
159 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
160 if changes, err := gitrepo.CompareChanges(ctx, s.Git, dir, mr.TargetBranch, mr.SourceBranch); err == nil {
161 stats := webhook.DiffStats{Files: fileChanges(changes)}
162 for _, f := range stats.Files {
163 stats.Additions += f.Additions
164 stats.Deletions += f.Deletions
165 }
166 mr.DiffStats = stats
167 }
168 list, err := gitrepo.Log(ctx, s.Git, dir, mr.TargetBranch+".."+mr.SourceBranch, webhook.MaxPushCommits)
169 if err != nil || len(list) == 0 {
170 mr.Commits = []webhook.CommitInfo{}
171 return
172 }
173 mr.Commits = make([]webhook.CommitInfo, 0, len(list))
174 for i := len(list) - 1; i >= 0; i-- {
175 mr.Commits = append(mr.Commits, s.commitInfo(ctx, repo, list[i]))
176 }
177}
178
179func (s *Server) commitInfo(ctx context.Context, repo store.Repo, c gitrepo.Commit) webhook.CommitInfo {
180 base := strings.TrimRight(s.Cfg.BaseURL, "/")
181 info := webhook.CommitInfo{
182 SHA: c.SHA, Message: commitText(c), Author: commitAuthor(c),
183 Timestamp: time.Unix(c.Unix, 0).UTC().Format(time.RFC3339),
184 URL: base + "/" + repo.FullPath() + "/-/commit/" + c.SHA,
185 DiffURL: commitDiffAPIURL(base, repo, c.SHA),
186 Files: []webhook.FileChange{},
187 }
188 if s.Git == "" || s.StoragePath() == "" {
189 return info
190 }
191 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
192 files, err := gitrepo.CommitFileChanges(ctx, s.Git, dir, c.SHA)
193 if err != nil {
194 return info
195 }
196 info.Files = fileChanges(files)
197 return info
198}
199
200func fileChanges(list []gitrepo.Change) []webhook.FileChange {
201 out := make([]webhook.FileChange, 0, len(list))
202 for _, c := range list {
203 out = append(out, webhook.FileChange{
204 Path: c.Path, Status: c.Status, PreviousPath: c.OldPath,
205 Additions: c.Added, Deletions: c.Deleted, Binary: c.Binary,
206 })
207 }
208 return out
209}
210
211func (s *Server) maskSecrets(ctx context.Context, repo store.Repo) []string {
212 if s.Store == nil {
213 return nil
214 }
215 var out []string
216 add := func(kind string, id int64) {
217 vals, err := s.Store.SecretValues(ctx, kind, id, true)
218 if err != nil {
219 return
220 }
221 for _, v := range vals {
222 out = append(out, v)
223 }
224 }
225 add("repo", repo.ID)
226 if repo.OwnerKind == "group" {
227 add("group", repo.OwnerID)
228 }
229 return out
230}
231
232func (s *Server) mrEvent(repo store.Repo, mr store.MergeRequest, actor, action, comment string) webhook.Event {
233 num := strconv.FormatInt(mr.Number, 10)
234 path := strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/merge-requests/" + num
235 summary := i18n.T(i18n.EN, "hook.mr", num, mr.Title)
236 switch action {
237 case "merged":
238 summary = i18n.T(i18n.EN, "hook.mrMerged", num, mr.Title)
239 case "commented":
240 summary = i18n.T(i18n.EN, "hook.mrComment", num)
241 }
242 return webhook.Event{
243 Type: webhook.EventMergeRequest,
244 Project: repo.FullPath(),
245 Branch: mr.TargetBranch,
246 Actor: actor,
247 Summary: summary,
248 URL: path,
249 Comment: comment,
250 MergeRequest: &webhook.MRInfo{
251 ID: mr.Number, Title: mr.Title, Description: mr.Description,
252 SourceBranch: mr.SourceBranch, TargetBranch: mr.TargetBranch,
253 Status: mr.Status, Author: mr.Author, Action: action, URL: path,
254 },
255 }
256}
257
258func (s *Server) mrHook(repo store.Repo, mr store.MergeRequest, actor, action, comment string) {
259 s.Dispatch(repo.ID, s.mrEvent(repo, mr, actor, action, comment))
260}
261
262func (s *Server) releaseEvent(repo store.Repo, tag, name, commit string, assets []store.ReleaseAsset) webhook.Event {
263 base := strings.TrimRight(s.Cfg.BaseURL, "/")
264 page := base + repoURL(repo) + "/-/releases"
265 list := make([]webhook.AssetInfo, 0, len(assets))
266 for _, a := range assets {
267 list = append(list, webhook.AssetInfo{
268 Name: a.Name, Size: a.Size,
269 URL: base + repoURL(repo) + "/-/releases/" + url.PathEscape(tag) + "/assets/" + url.PathEscape(a.Name),
270 })
271 }
272 return webhook.Event{
273 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: commit,
274 ReleaseTag: tag, Summary: i18n.T(i18n.EN, "hook.release", tag, repo.FullPath()),
275 URL: page,
276 Release: &webhook.ReleaseInfo{Tag: tag, Name: name, Commit: commit, Assets: list},
277 }
278}
279
280func commitDiffAPIURL(base string, repo store.Repo, sha string) string {
281 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/commits/" + url.PathEscape(sha) + "/diff"
282}
283
284func mrDiffAPIURL(base string, repo store.Repo, number int64) string {
285 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/merge-requests/" + strconv.FormatInt(number, 10) + "/diff"
286}
287
288func jobLogAPIURL(base string, repo store.Repo, jobID int64) string {
289 return strings.TrimRight(base, "/") + "/api/v1/repos/" + url.PathEscape(repo.OwnerPath) + "/" + url.PathEscape(repo.Name) + "/jobs/" + strconv.FormatInt(jobID, 10) + "/log"
290}
291
292func refName(ref string) string {
293 if b, ok := gitrepo.BranchOfRef(ref); ok {
294 return b
295 }
296 if name, ok := strings.CutPrefix(ref, "refs/tags/"); ok && name != "" {
297 return name
298 }
299 return ref
300}
301
302func commitText(c gitrepo.Commit) string {
303 if c.Subject == "" {
304 return strings.TrimSpace(c.Body)
305 }
306 if strings.TrimSpace(c.Body) == "" {
307 return c.Subject
308 }
309 return c.Subject + "\n\n" + strings.TrimSpace(c.Body)
310}
311
312func commitAuthor(c gitrepo.Commit) string {
313 name := strings.TrimSpace(c.Author)
314 email := strings.TrimSpace(c.Email)
315 switch {
316 case name == "":
317 return email
318 case email == "":
319 return name
320 default:
321 return name + " <" + email + ">"
322 }
323}
324
325func elapsedSeconds(start, end time.Time) float64 {
326 if start.IsZero() || end.IsZero() || end.Before(start) {
327 return 0
328 }
329 return math.Round(end.Sub(start).Seconds()*1000) / 1000
330}
internal/server/hook_payload_test.go added +587 −0
@@ -0,0 +1,587 @@
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 }
@@ -0,0 +1,587 @@
1package server
2
3import (
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
23func 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
403func 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
418func 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
434func 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
526func 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
538func 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
557func 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
571func 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
580func 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}
internal/server/info.go +8 −0
@@ -7,6 +7,7 @@ import (
7 7 "gitlab.com/Timfa/bluegit/internal/cispec"
8 8 "gitlab.com/Timfa/bluegit/internal/i18n"
9 9 "gitlab.com/Timfa/bluegit/internal/images"
10 "gitlab.com/Timfa/bluegit/internal/webhook"
10 11 )
11 12
12 13 func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
@@ -21,10 +22,17 @@ func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
21 22 v.Spec = doc
22 23 v.SpecJSON = template.JS(raw)
23 24 v.APIJSON = template.JS(apiIndex())
25 v.HookDoc = webhook.Example()
24 26 s.attachUpdate(&v, s.langOf(r))
25 27 s.render(w, "info", v)
26 28 }
27 29
30 func (s *Server) webhookSpec(w http.ResponseWriter, r *http.Request) {
31 w.Header().Set("Content-Type", "application/json; charset=utf-8")
32 w.Header().Set("Cache-Control", "no-store")
33 _, _ = w.Write(webhook.OpenAPI())
34 }
35
28 36 func (s *Server) ciSpec(w http.ResponseWriter, r *http.Request) {
29 37 lang := i18n.EN
30 38 if q := r.URL.Query().Get("lang"); q != "" {
@@ -7,6 +7,7 @@ import (
7 "gitlab.com/Timfa/bluegit/internal/cispec"
7 "gitlab.com/Timfa/bluegit/internal/cispec"
8 "gitlab.com/Timfa/bluegit/internal/i18n"
8 "gitlab.com/Timfa/bluegit/internal/i18n"
9 "gitlab.com/Timfa/bluegit/internal/images"
9 "gitlab.com/Timfa/bluegit/internal/images"
10 "gitlab.com/Timfa/bluegit/internal/webhook"
10)
11)
11
12
12func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
13func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
@@ -21,10 +22,17 @@ func (s *Server) infoPage(w http.ResponseWriter, r *http.Request) {
21 v.Spec = doc
22 v.Spec = doc
22 v.SpecJSON = template.JS(raw)
23 v.SpecJSON = template.JS(raw)
23 v.APIJSON = template.JS(apiIndex())
24 v.APIJSON = template.JS(apiIndex())
25 v.HookDoc = webhook.Example()
24 s.attachUpdate(&v, s.langOf(r))
26 s.attachUpdate(&v, s.langOf(r))
25 s.render(w, "info", v)
27 s.render(w, "info", v)
26}
28}
27
29
30func (s *Server) webhookSpec(w http.ResponseWriter, r *http.Request) {
31 w.Header().Set("Content-Type", "application/json; charset=utf-8")
32 w.Header().Set("Cache-Control", "no-store")
33 _, _ = w.Write(webhook.OpenAPI())
34}
35
28func (s *Server) ciSpec(w http.ResponseWriter, r *http.Request) {
36func (s *Server) ciSpec(w http.ResponseWriter, r *http.Request) {
29 lang := i18n.EN
37 lang := i18n.EN
30 if q := r.URL.Query().Get("lang"); q != "" {
38 if q := r.URL.Query().Get("lang"); q != "" {
internal/server/ops_ci.go +1 −6
@@ -12,7 +12,6 @@ import (
12 12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 13 "gitlab.com/Timfa/bluegit/internal/names"
14 14 "gitlab.com/Timfa/bluegit/internal/store"
15 "gitlab.com/Timfa/bluegit/internal/webhook"
16 15 )
17 16
18 17 func (s *Server) opRunPipeline(ctx context.Context, user store.User, repo store.Repo, ref, source string) (int64, error) {
@@ -241,11 +240,7 @@ func (s *Server) opPublishRelease(ctx context.Context, repo store.Repo, author s
241 240 if err != nil {
242 241 return 0, fail(400, err)
243 242 }
244 s.Dispatch(repo.ID, webhook.Event{
245 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: req.Commit,
246 ReleaseTag: req.Tag, Summary: i18n.T(i18n.EN, "hook.release", req.Tag, repo.FullPath()),
247 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/releases",
248 })
243 s.Dispatch(repo.ID, s.releaseEvent(repo, req.Tag, req.Name, req.Commit, assets))
249 244 return id, nil
250 245 }
251 246
@@ -12,7 +12,6 @@ import (
12 "gitlab.com/Timfa/bluegit/internal/i18n"
12 "gitlab.com/Timfa/bluegit/internal/i18n"
13 "gitlab.com/Timfa/bluegit/internal/names"
13 "gitlab.com/Timfa/bluegit/internal/names"
14 "gitlab.com/Timfa/bluegit/internal/store"
14 "gitlab.com/Timfa/bluegit/internal/store"
15 "gitlab.com/Timfa/bluegit/internal/webhook"
16)
15)
17
16
18func (s *Server) opRunPipeline(ctx context.Context, user store.User, repo store.Repo, ref, source string) (int64, error) {
17func (s *Server) opRunPipeline(ctx context.Context, user store.User, repo store.Repo, ref, source string) (int64, error) {
@@ -241,11 +240,7 @@ func (s *Server) opPublishRelease(ctx context.Context, repo store.Repo, author s
241 if err != nil {
240 if err != nil {
242 return 0, fail(400, err)
241 return 0, fail(400, err)
243 }
242 }
244 s.Dispatch(repo.ID, webhook.Event{
243 s.Dispatch(repo.ID, s.releaseEvent(repo, req.Tag, req.Name, req.Commit, assets))
245 Type: webhook.EventRelease, Project: repo.FullPath(), Commit: req.Commit,
246 ReleaseTag: req.Tag, Summary: i18n.T(i18n.EN, "hook.release", req.Tag, repo.FullPath()),
247 URL: strings.TrimRight(s.Cfg.BaseURL, "/") + repoURL(repo) + "/-/releases",
248 })
249 return id, nil
244 return id, nil
250}
245}
251
246
internal/server/ops_mr.go +6 −3
@@ -4,7 +4,6 @@ import (
4 4 "context"
5 5 "net/http"
6 6 "os"
7 "strconv"
8 7 "strings"
9 8
10 9 "gitlab.com/Timfa/bluegit/internal/access"
@@ -38,8 +37,7 @@ func (s *Server) opCreateMR(ctx context.Context, user store.User, repo store.Rep
38 37 if sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+source); sha != "" {
39 38 s.startOneMergePipeline(ctx, repo, sha, user.Username, "", mr)
40 39 }
41 num := strconv.FormatInt(mr.Number, 10)
42 s.Dispatch(repo.ID, pushEvent(repo, "merge_request", target, "", user.Username, i18n.T(i18n.EN, "hook.mr", num, mr.Title), repoURL(repo)+"/-/merge-requests/"+num))
40 s.mrHook(repo, mr, user.Username, "opened", "")
43 41 s.recordContribution(user.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
44 42 return mr, nil
45 43 }
@@ -94,12 +92,14 @@ func (s *Server) opAddNote(r *http.Request, user store.User, repo store.Repo, nu
94 92 if err != nil {
95 93 return store.Note{}, fail(400, err)
96 94 }
95 s.mrHook(repo, mr, user.Username, "commented", body)
97 96 return note, nil
98 97 }
99 98 note, err := s.Store.AddNote(ctx, repo.ID, mr.ID, user.ID, body)
100 99 if err != nil {
101 100 return store.Note{}, fail(400, err)
102 101 }
102 s.mrHook(repo, mr, user.Username, "commented", body)
103 103 return note, nil
104 104 }
105 105 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
@@ -118,6 +118,7 @@ func (s *Server) opAddNote(r *http.Request, user store.User, repo store.Repo, nu
118 118 return store.Note{}, fail(400, err)
119 119 }
120 120 s.noteRequestsChanges(r, repo, mr, user.ID, suggestion)
121 s.mrHook(repo, mr, user.Username, "commented", body)
121 122 return note, nil
122 123 }
123 124
@@ -284,6 +285,8 @@ func (s *Server) opMergeMR(r *http.Request, user store.User, repo store.Repo, nu
284 285 }
285 286 _ = s.Store.SetMergeRequestStatus(ctx, mr.ID, "merged")
286 287 _ = s.Store.AddMREvent(ctx, repo.ID, mr.ID, user.ID, "merged", "")
288 mr.Status = "merged"
289 s.mrHook(repo, mr, user.Username, "merged", "")
287 290 return nil
288 291 }
289 292
@@ -4,7 +4,6 @@ import (
4 "context"
4 "context"
5 "net/http"
5 "net/http"
6 "os"
6 "os"
7 "strconv"
8 "strings"
7 "strings"
9
8
10 "gitlab.com/Timfa/bluegit/internal/access"
9 "gitlab.com/Timfa/bluegit/internal/access"
@@ -38,8 +37,7 @@ func (s *Server) opCreateMR(ctx context.Context, user store.User, repo store.Rep
38 if sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+source); sha != "" {
37 if sha := gitOne(ctx, s.Git, dir, "rev-parse", "--verify", "refs/heads/"+source); sha != "" {
39 s.startOneMergePipeline(ctx, repo, sha, user.Username, "", mr)
38 s.startOneMergePipeline(ctx, repo, sha, user.Username, "", mr)
40 }
39 }
41 num := strconv.FormatInt(mr.Number, 10)
40 s.mrHook(repo, mr, user.Username, "opened", "")
42 s.Dispatch(repo.ID, pushEvent(repo, "merge_request", target, "", user.Username, i18n.T(i18n.EN, "hook.mr", num, mr.Title), repoURL(repo)+"/-/merge-requests/"+num))
43 s.recordContribution(user.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
41 s.recordContribution(user.ID, repo.ID, "merge_request", mrRef(mr.ID), mr.CreatedAt)
44 return mr, nil
42 return mr, nil
45}
43}
@@ -94,12 +92,14 @@ func (s *Server) opAddNote(r *http.Request, user store.User, repo store.Repo, nu
94 if err != nil {
92 if err != nil {
95 return store.Note{}, fail(400, err)
93 return store.Note{}, fail(400, err)
96 }
94 }
95 s.mrHook(repo, mr, user.Username, "commented", body)
97 return note, nil
96 return note, nil
98 }
97 }
99 note, err := s.Store.AddNote(ctx, repo.ID, mr.ID, user.ID, body)
98 note, err := s.Store.AddNote(ctx, repo.ID, mr.ID, user.ID, body)
100 if err != nil {
99 if err != nil {
101 return store.Note{}, fail(400, err)
100 return store.Note{}, fail(400, err)
102 }
101 }
102 s.mrHook(repo, mr, user.Username, "commented", body)
103 return note, nil
103 return note, nil
104 }
104 }
105 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
105 dir := gitrepo.Dir(s.StoragePath(), repo.OwnerPath, repo.Name)
@@ -118,6 +118,7 @@ func (s *Server) opAddNote(r *http.Request, user store.User, repo store.Repo, nu
118 return store.Note{}, fail(400, err)
118 return store.Note{}, fail(400, err)
119 }
119 }
120 s.noteRequestsChanges(r, repo, mr, user.ID, suggestion)
120 s.noteRequestsChanges(r, repo, mr, user.ID, suggestion)
121 s.mrHook(repo, mr, user.Username, "commented", body)
121 return note, nil
122 return note, nil
122}
123}
123
124
@@ -284,6 +285,8 @@ func (s *Server) opMergeMR(r *http.Request, user store.User, repo store.Repo, nu
284 }
285 }
285 _ = s.Store.SetMergeRequestStatus(ctx, mr.ID, "merged")
286 _ = s.Store.SetMergeRequestStatus(ctx, mr.ID, "merged")
286 _ = s.Store.AddMREvent(ctx, repo.ID, mr.ID, user.ID, "merged", "")
287 _ = s.Store.AddMREvent(ctx, repo.ID, mr.ID, user.ID, "merged", "")
288 mr.Status = "merged"
289 s.mrHook(repo, mr, user.Username, "merged", "")
287 return nil
290 return nil
288}
291}
289
292
internal/server/server.go +7 −0
@@ -41,6 +41,8 @@ type Server struct {
41 41 HookBin string
42 42 Runner *runner.Runner
43 43 Log *slog.Logger
44 // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
45 hookSink func([]byte)
44 46 // StateDir is de map met database en het bestand storage_path.
45 47 StateDir string
46 48 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
@@ -73,6 +75,7 @@ func (s *Server) Handler() http.Handler {
73 75 s.mountAPI(mux)
74 76 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
75 77 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
78 mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
76 79 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
77 80 w.WriteHeader(http.StatusOK)
78 81 _, _ = w.Write([]byte("ok\n"))
@@ -113,6 +116,9 @@ func (s *Server) Handler() http.Handler {
113 116 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
114 117 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
115 118 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
119 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
120 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
121 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
116 122 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
117 123 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
118 124 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
@@ -541,6 +547,7 @@ type View struct {
541 547 Info bool
542 548 ShowUpdate bool
543 549 Update *UpdateView
550 HookDoc string
544 551 Spec cispec.Doc
545 552 SpecJSON template.JS
546 553 APIJSON template.JS
@@ -41,6 +41,8 @@ type Server struct {
41 HookBin string
41 HookBin string
42 Runner *runner.Runner
42 Runner *runner.Runner
43 Log *slog.Logger
43 Log *slog.Logger
44 // hookSink vangt de JSON-body af in tests, vóór het HTTP-verzoek.
45 hookSink func([]byte)
44 // StateDir is de map met database en het bestand storage_path.
46 // StateDir is de map met database en het bestand storage_path.
45 StateDir string
47 StateDir string
46 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
48 // AfterStorage krijgt het nieuwe datadisk-pad, voor runner en SSH.
@@ -73,6 +75,7 @@ func (s *Server) Handler() http.Handler {
73 s.mountAPI(mux)
75 s.mountAPI(mux)
74 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
76 mux.HandleFunc("GET /api/v1/admin/self-update", s.selfUpdateStatus)
75 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
77 mux.HandleFunc("POST /api/v1/admin/self-update", s.selfUpdate)
78 mux.HandleFunc("GET /api/v1/webhooks/openapi.json", s.webhookSpec)
76 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
79 mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
77 w.WriteHeader(http.StatusOK)
80 w.WriteHeader(http.StatusOK)
78 _, _ = w.Write([]byte("ok\n"))
81 _, _ = w.Write([]byte("ok\n"))
@@ -113,6 +116,9 @@ func (s *Server) Handler() http.Handler {
113 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
116 mux.HandleFunc("POST /{owner}/{repo}/git-upload-pack", s.gitHTTP)
114 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
117 mux.HandleFunc("POST /{owner}/{repo}/git-receive-pack", s.gitHTTP)
115 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
118 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/releases", s.createRelease)
119 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log", s.jobLogAPI)
120 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff", s.commitDiffAPI)
121 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/merge-requests/{number}/diff", s.mrDiffAPI)
116 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
122 mux.HandleFunc("GET /api/v1/repos/{owner}/{repo}/webhook-secrets", s.repoWebhookSecrets)
117 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
123 mux.HandleFunc("POST /api/v1/repos/{owner}/{repo}/webhooks", s.repoWebhookAPI)
118 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
124 mux.HandleFunc("PUT /api/v1/repos/{owner}/{repo}/webhooks/{id}", s.repoWebhookUpdate)
@@ -541,6 +547,7 @@ type View struct {
541 Info bool
547 Info bool
542 ShowUpdate bool
548 ShowUpdate bool
543 Update *UpdateView
549 Update *UpdateView
550 HookDoc string
544 Spec cispec.Doc
551 Spec cispec.Doc
545 SpecJSON template.JS
552 SpecJSON template.JS
546 APIJSON template.JS
553 APIJSON template.JS
internal/server/setup.go +1 −1
@@ -16,7 +16,7 @@ func (s *Server) noStorageText(r *http.Request) string {
16 16
17 17 func allowsWithoutStorage(r *http.Request) bool {
18 18 switch r.URL.Path {
19 case "/healthz", "/login", "/auth/callback", "/logout", "/setup", "/-/info", "/api/v1/ci/spec", "/api/v1/ci/presets", "/api/v1/openapi.json", "/api/v1/admin/storage", "/api/v1/admin/self-update":
19 case "/healthz", "/login", "/auth/callback", "/logout", "/setup", "/-/info", "/api/v1/ci/spec", "/api/v1/ci/presets", "/api/v1/openapi.json", "/api/v1/webhooks/openapi.json", "/api/v1/admin/storage", "/api/v1/admin/self-update":
20 20 return true
21 21 }
22 22 return strings.HasPrefix(r.URL.Path, "/assets/")
@@ -16,7 +16,7 @@ func (s *Server) noStorageText(r *http.Request) string {
16
16
17func allowsWithoutStorage(r *http.Request) bool {
17func allowsWithoutStorage(r *http.Request) bool {
18 switch r.URL.Path {
18 switch r.URL.Path {
19 case "/healthz", "/login", "/auth/callback", "/logout", "/setup", "/-/info", "/api/v1/ci/spec", "/api/v1/ci/presets", "/api/v1/openapi.json", "/api/v1/admin/storage", "/api/v1/admin/self-update":
19 case "/healthz", "/login", "/auth/callback", "/logout", "/setup", "/-/info", "/api/v1/ci/spec", "/api/v1/ci/presets", "/api/v1/openapi.json", "/api/v1/webhooks/openapi.json", "/api/v1/admin/storage", "/api/v1/admin/self-update":
20 return true
20 return true
21 }
21 }
22 return strings.HasPrefix(r.URL.Path, "/assets/")
22 return strings.HasPrefix(r.URL.Path, "/assets/")
internal/server/templates/info.html +4 −0
@@ -58,6 +58,10 @@
58 58 <p>{{t "info.api.auth"}}</p>
59 59 <p>{{t "info.api.ssh"}}</p>
60 60 <p><a href="/api/v1/openapi.json">{{t "info.api.spec"}}</a></p>
61 <h2 id="webhooks">{{t "info.sec.webhooks"}}</h2>
62 <p>{{t "info.wh.lead"}}</p>
63 <p><a href="/api/v1/webhooks/openapi.json">{{t "info.wh.spec"}}</a></p>
64 <pre class="spec-example">{{.HookDoc}}</pre>
61 65 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
62 66 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
63 67 </article>
@@ -58,6 +58,10 @@
58 <p>{{t "info.api.auth"}}</p>
58 <p>{{t "info.api.auth"}}</p>
59 <p>{{t "info.api.ssh"}}</p>
59 <p>{{t "info.api.ssh"}}</p>
60 <p><a href="/api/v1/openapi.json">{{t "info.api.spec"}}</a></p>
60 <p><a href="/api/v1/openapi.json">{{t "info.api.spec"}}</a></p>
61 <h2 id="webhooks">{{t "info.sec.webhooks"}}</h2>
62 <p>{{t "info.wh.lead"}}</p>
63 <p><a href="/api/v1/webhooks/openapi.json">{{t "info.wh.spec"}}</a></p>
64 <pre class="spec-example">{{.HookDoc}}</pre>
61 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
65 <script type="application/json" id="bluegit-ci-spec">{{.SpecJSON}}</script>
62 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
66 <script type="application/json" id="bluegit-api">{{.APIJSON}}</script>
63</article>
67</article>
internal/store/flow.go +13 −0
@@ -858,6 +858,19 @@ func (s *Store) JobByToken(ctx context.Context, token string) (Job, error) {
858 858 return scanJob(rows)
859 859 }
860 860
861 // JobByID leest een job van deze repository.
862 func (s *Store) JobByID(ctx context.Context, repoID, id int64) (Job, error) {
863 rows, err := s.db.QueryContext(ctx, jobSelect+` WHERE j.repo_id = ? AND j.id = ?`, repoID, id)
864 if err != nil {
865 return Job{}, err
866 }
867 defer rows.Close()
868 if !rows.Next() {
869 return Job{}, errNotFound
870 }
871 return scanJob(rows)
872 }
873
861 874 // Artifact verwijst naar een bestand uit een job.
862 875 type Artifact struct {
863 876 ID int64
@@ -858,6 +858,19 @@ func (s *Store) JobByToken(ctx context.Context, token string) (Job, error) {
858 return scanJob(rows)
858 return scanJob(rows)
859}
859}
860
860
861// JobByID leest een job van deze repository.
862func (s *Store) JobByID(ctx context.Context, repoID, id int64) (Job, error) {
863 rows, err := s.db.QueryContext(ctx, jobSelect+` WHERE j.repo_id = ? AND j.id = ?`, repoID, id)
864 if err != nil {
865 return Job{}, err
866 }
867 defer rows.Close()
868 if !rows.Next() {
869 return Job{}, errNotFound
870 }
871 return scanJob(rows)
872}
873
861// Artifact verwijst naar een bestand uit een job.
874// Artifact verwijst naar een bestand uit een job.
862type Artifact struct {
875type Artifact struct {
863 ID int64
876 ID int64
internal/webhook/openapi.go added +260 −0
@@ -0,0 +1,260 @@
1 package webhook
2
3 import "encoding/json"
4
5 // OpenAPI beschrijft de JSON-body die een webhook ontvangt.
6 func OpenAPI() []byte {
7 obj := func(desc string, props map[string]any, required []string) map[string]any {
8 return map[string]any{
9 "type": "object", "description": desc,
10 "properties": props, "required": required,
11 }
12 }
13 str := func(desc string) map[string]any {
14 return map[string]any{"type": "string", "description": desc}
15 }
16 num := func(desc string) map[string]any {
17 return map[string]any{"type": "number", "description": desc}
18 }
19 boolean := func(desc string) map[string]any {
20 return map[string]any{"type": "boolean", "description": desc}
21 }
22 post := func(summary, ref string) map[string]any {
23 return map[string]any{
24 "post": map[string]any{
25 "summary": summary,
26 "requestBody": map[string]any{
27 "required": true,
28 "content": map[string]any{
29 "application/json": map[string]any{
30 "schema": map[string]any{"$ref": ref},
31 },
32 },
33 },
34 "responses": map[string]any{"200": map[string]any{"description": "The receiver accepted the event."}},
35 },
36 }
37 }
38 doc := map[string]any{
39 "openapi": "3.1.0",
40 "info": map[string]any{
41 "title": "BlueGit webhook payloads",
42 "version": "1",
43 "description": "JSON body of a BlueGit webhook when the body template is empty. " +
44 "pipeline_success and pipeline_failure include the pipeline and every job. " +
45 "Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +
46 "log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +
47 "A push lists ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload does not include the diff text. " +
48 "diff_url for a commit is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. " +
49 "A merge request includes reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. " +
50 "diff_url for a merge request is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. " +
51 "Both diff requests need Authorization Bearer and a personal token that can read the repo. " +
52 "A merge request uses action opened, merged or commented, and commented includes the comment text. " +
53 "A release lists the tag, name, commit and asset URLs.",
54 },
55 "servers": []any{map[string]any{"url": "/api/v1"}},
56 "paths": map[string]any{
57 "/repos/{owner}/{repo}/commits/{sha}/diff": map[string]any{
58 "get": map[string]any{
59 "summary": "Commit diff",
60 "description": "Returns the unified diff of the commit against its first parent as text/plain. A root commit is compared with an empty tree. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
61 "security": []any{map[string]any{"bearer": []any{}}},
62 "parameters": []any{
63 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
64 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
65 map[string]any{"name": "sha", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
66 },
67 "responses": map[string]any{
68 "200": map[string]any{
69 "description": "Unified diff.",
70 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
71 },
72 "401": map[string]any{"description": "Missing or invalid token."},
73 "403": map[string]any{"description": "The token cannot read this private repo."},
74 "404": map[string]any{"description": "Unknown repo or commit."},
75 },
76 },
77 },
78 "/repos/{owner}/{repo}/merge-requests/{id}/diff": map[string]any{
79 "get": map[string]any{
80 "summary": "Merge request diff",
81 "description": "Returns the three-dot unified diff from the target branch to the source branch as text/plain. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
82 "security": []any{map[string]any{"bearer": []any{}}},
83 "parameters": []any{
84 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
85 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
86 map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
87 },
88 "responses": map[string]any{
89 "200": map[string]any{
90 "description": "Unified diff.",
91 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
92 },
93 "401": map[string]any{"description": "Missing or invalid token."},
94 "403": map[string]any{"description": "The token cannot read this private repo."},
95 "404": map[string]any{"description": "Unknown repo or merge request."},
96 },
97 },
98 },
99 "/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{
100 "get": map[string]any{
101 "summary": "Full job log",
102 "description": "Returns the full console output as text/plain. Secret values of at least 8 characters are replaced with [MASKED]. Requires a personal access token. A token that can read the repo is enough, and on a public repo any valid personal token is enough. Job tokens are rejected.",
103 "security": []any{map[string]any{"bearer": []any{}}},
104 "parameters": []any{
105 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
106 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
107 map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
108 },
109 "responses": map[string]any{
110 "200": map[string]any{
111 "description": "Full log.",
112 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
113 },
114 "401": map[string]any{"description": "Missing or invalid token."},
115 "403": map[string]any{"description": "The token cannot read this private repo."},
116 "404": map[string]any{"description": "Unknown repo or job."},
117 },
118 },
119 },
120 },
121 "webhooks": map[string]any{
122 "pipeline": post("Pipeline finished", "#/components/schemas/PipelineEvent"),
123 "push": post("Push", "#/components/schemas/PushEvent"),
124 "merge_request": post("Merge request", "#/components/schemas/MergeRequestEvent"),
125 "release": post("Release published", "#/components/schemas/ReleaseEvent"),
126 },
127 "components": map[string]any{
128 "securitySchemes": map[string]any{
129 "bearer": map[string]any{"type": "http", "scheme": "bearer", "description": "Personal access token (bg_)."},
130 },
131 "schemas": map[string]any{
132 "PipelineEvent": obj("pipeline_success or pipeline_failure.", map[string]any{
133 "object_kind": str("Always pipeline."),
134 "type": str("pipeline_success or pipeline_failure."),
135 "project": str("owner/name."),
136 "actor": str("User who started the pipeline."),
137 "summary": str("One-line summary."),
138 "url": str("Pipeline page."),
139 "pipeline_id": str("Same id as pipeline.id, as text."),
140 "pipeline": map[string]any{"$ref": "#/components/schemas/Pipeline"},
141 "jobs": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Job"}},
142 }, []string{"object_kind", "type", "project", "pipeline", "jobs"}),
143 "Pipeline": obj("The pipeline this event is about.", map[string]any{
144 "id": map[string]any{"type": "integer", "description": "Pipeline id."},
145 "status": str("success or failed."),
146 "ref": str("Full ref, such as refs/heads/master."),
147 "sha": str("Commit SHA."),
148 "commit_message": str("Subject and body of the commit."),
149 "author": str("User who started the pipeline."),
150 "duration": num("Seconds from start to finish."),
151 "url": str("Pipeline page."),
152 }, []string{"id", "status", "ref", "sha", "commit_message", "author", "duration"}),
153 "Job": obj("One job. log is always the console tail. log_url is present only when log_truncated is true.", map[string]any{
154 "name": str("Job name."),
155 "stage": str("Stage name."),
156 "status": str("Job status."),
157 "duration": num("Seconds the job ran."),
158 "allow_failure": boolean("True when a failure does not fail the pipeline."),
159 "web_url": str("Job page."),
160 "log": str("Last 200 lines of the console output, at most 64 KiB. Secrets of at least 8 characters are [MASKED]."),
161 "log_truncated": boolean("True when log is shorter than the stored console output."),
162 "log_url": str("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Present only when log_truncated is true. Requires Authorization Bearer and a personal token that can read the repo. The response is the full log as text/plain, with secrets masked."),
163 }, []string{"name", "stage", "status", "duration", "allow_failure", "web_url", "log", "log_truncated"}),
164 "PushEvent": obj("A branch or tag update.", map[string]any{
165 "object_kind": str("Always push."),
166 "type": str("Always push."),
167 "project": str("owner/name."),
168 "actor": str("User who pushed."),
169 "ref": str("Full ref."),
170 "before": str("Previous SHA, or 40 zeros when the ref is new."),
171 "after": str("New SHA."),
172 "commits": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
173 }, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),
174 "Commit": obj("One commit. The diff text is not included.", map[string]any{
175 "sha": str("Commit SHA."),
176 "message": str("Subject and body."),
177 "author": str("Name and email."),
178 "timestamp": str("Author time in RFC3339."),
179 "url": str("Commit page."),
180 "files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
181 "diff_url": str("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the unified diff as text/plain."),
182 }, []string{"sha", "message", "author", "timestamp", "url", "files", "diff_url"}),
183 "FileChange": obj("One changed file, without the diff text.", map[string]any{
184 "path": str("Path after the change."),
185 "status": str("added, modified, removed or renamed."),
186 "previous_path": str("Path before a rename."),
187 "additions": map[string]any{"type": "integer", "description": "Added lines. Zero for a binary file."},
188 "deletions": map[string]any{"type": "integer", "description": "Deleted lines. Zero for a binary file."},
189 "binary": boolean("True when the file is binary."),
190 }, []string{"path", "status", "additions", "deletions"}),
191 "MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{
192 "object_kind": str("Always merge_request."),
193 "type": str("Always merge_request."),
194 "project": str("owner/name."),
195 "actor": str("User who did this action."),
196 "merge_request": map[string]any{"$ref": "#/components/schemas/MergeRequest"},
197 "comment": str("Comment text. Present only when action is commented."),
198 }, []string{"object_kind", "type", "project", "merge_request"}),
199 "MergeRequest": obj("The merge request.", map[string]any{
200 "id": map[string]any{"type": "integer", "description": "Number in the project."},
201 "title": str("Title."),
202 "description": str("Description. May be empty."),
203 "source_branch": str("Source branch."),
204 "target_branch": str("Target branch."),
205 "status": str("open, merged or closed."),
206 "author": str("User who opened the merge request."),
207 "action": str("opened, merged or commented."),
208 "url": str("Merge request page."),
209 "reviewers": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Reviewer"}},
210 "comments": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Comment"}},
211 "commits": map[string]any{"type": "array", "description": "Up to 20 commits on the source branch that the target does not have, oldest first.", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
212 "diff_stats": map[string]any{"$ref": "#/components/schemas/DiffStats"},
213 "diff_url": str("GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the three-dot unified diff as text/plain."),
214 }, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action", "reviewers", "comments", "commits", "diff_stats", "diff_url"}),
215 "Reviewer": obj("The current review of one person.", map[string]any{
216 "username": str("Username."),
217 "status": str("approved, changes, rejected or dismissed."),
218 }, []string{"username", "status"}),
219 "Comment": obj("One comment on the merge request.", map[string]any{
220 "id": map[string]any{"type": "integer", "description": "Comment id."},
221 "author": str("Username."),
222 "body": str("Comment text."),
223 "created_at": str("Time in RFC3339."),
224 "file_path": str("File, when the comment is on a line."),
225 "line_start": map[string]any{"type": "integer", "description": "First line."},
226 "line_end": map[string]any{"type": "integer", "description": "Last line."},
227 "parent_id": map[string]any{"type": "integer", "description": "Parent comment, when this is a reply."},
228 }, []string{"id", "author", "body", "created_at"}),
229 "DiffStats": obj("Line counts of the merge request diff. The diff text is not included.", map[string]any{
230 "additions": map[string]any{"type": "integer", "description": "Added lines."},
231 "deletions": map[string]any{"type": "integer", "description": "Deleted lines."},
232 "files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
233 }, []string{"additions", "deletions", "files"}),
234 "ReleaseEvent": obj("A published release.", map[string]any{
235 "object_kind": str("Always release."),
236 "type": str("Always release_published."),
237 "project": str("owner/name."),
238 "release_tag": str("Same value as release.tag."),
239 "release": map[string]any{"$ref": "#/components/schemas/Release"},
240 }, []string{"object_kind", "type", "project", "release"}),
241 "Release": obj("The release.", map[string]any{
242 "tag": str("Tag name."),
243 "name": str("Release title."),
244 "commit": str("Commit SHA."),
245 "assets": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Asset"}},
246 }, []string{"tag", "name", "commit", "assets"}),
247 "Asset": obj("A file attached to the release.", map[string]any{
248 "name": str("File name."),
249 "url": str("Download URL."),
250 "size": map[string]any{"type": "integer", "description": "Size in bytes."},
251 }, []string{"name", "url", "size"}),
252 },
253 },
254 }
255 raw, err := json.MarshalIndent(doc, "", " ")
256 if err != nil {
257 return []byte("{}\n")
258 }
259 return append(raw, '\n')
260 }
@@ -0,0 +1,260 @@
1package webhook
2
3import "encoding/json"
4
5// OpenAPI beschrijft de JSON-body die een webhook ontvangt.
6func OpenAPI() []byte {
7 obj := func(desc string, props map[string]any, required []string) map[string]any {
8 return map[string]any{
9 "type": "object", "description": desc,
10 "properties": props, "required": required,
11 }
12 }
13 str := func(desc string) map[string]any {
14 return map[string]any{"type": "string", "description": desc}
15 }
16 num := func(desc string) map[string]any {
17 return map[string]any{"type": "number", "description": desc}
18 }
19 boolean := func(desc string) map[string]any {
20 return map[string]any{"type": "boolean", "description": desc}
21 }
22 post := func(summary, ref string) map[string]any {
23 return map[string]any{
24 "post": map[string]any{
25 "summary": summary,
26 "requestBody": map[string]any{
27 "required": true,
28 "content": map[string]any{
29 "application/json": map[string]any{
30 "schema": map[string]any{"$ref": ref},
31 },
32 },
33 },
34 "responses": map[string]any{"200": map[string]any{"description": "The receiver accepted the event."}},
35 },
36 }
37 }
38 doc := map[string]any{
39 "openapi": "3.1.0",
40 "info": map[string]any{
41 "title": "BlueGit webhook payloads",
42 "version": "1",
43 "description": "JSON body of a BlueGit webhook when the body template is empty. " +
44 "pipeline_success and pipeline_failure include the pipeline and every job. " +
45 "Every job includes its console output: the last 200 lines, at most 64 KiB. Secret values of at least 8 characters are replaced with [MASKED]. " +
46 "log_truncated is true when the log was cut. log_url is then GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log and needs Authorization Bearer with a personal token that can read the repo. " +
47 "A push lists ref, before, after and up to 20 commits. Each commit has sha, message, author, timestamp, URL, changed files and diff_url. A file has status added, modified, removed or renamed, plus added and deleted line counts. The payload does not include the diff text. " +
48 "diff_url for a commit is GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. " +
49 "A merge request includes reviewers, comments, up to 20 commits, diff statistics and diff_url, and no diff text. " +
50 "diff_url for a merge request is GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. " +
51 "Both diff requests need Authorization Bearer and a personal token that can read the repo. " +
52 "A merge request uses action opened, merged or commented, and commented includes the comment text. " +
53 "A release lists the tag, name, commit and asset URLs.",
54 },
55 "servers": []any{map[string]any{"url": "/api/v1"}},
56 "paths": map[string]any{
57 "/repos/{owner}/{repo}/commits/{sha}/diff": map[string]any{
58 "get": map[string]any{
59 "summary": "Commit diff",
60 "description": "Returns the unified diff of the commit against its first parent as text/plain. A root commit is compared with an empty tree. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
61 "security": []any{map[string]any{"bearer": []any{}}},
62 "parameters": []any{
63 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
64 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
65 map[string]any{"name": "sha", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
66 },
67 "responses": map[string]any{
68 "200": map[string]any{
69 "description": "Unified diff.",
70 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
71 },
72 "401": map[string]any{"description": "Missing or invalid token."},
73 "403": map[string]any{"description": "The token cannot read this private repo."},
74 "404": map[string]any{"description": "Unknown repo or commit."},
75 },
76 },
77 },
78 "/repos/{owner}/{repo}/merge-requests/{id}/diff": map[string]any{
79 "get": map[string]any{
80 "summary": "Merge request diff",
81 "description": "Returns the three-dot unified diff from the target branch to the source branch as text/plain. Requires a personal access token that can read the repo. On a public repo any valid personal token is enough. Job tokens are rejected.",
82 "security": []any{map[string]any{"bearer": []any{}}},
83 "parameters": []any{
84 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
85 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
86 map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
87 },
88 "responses": map[string]any{
89 "200": map[string]any{
90 "description": "Unified diff.",
91 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
92 },
93 "401": map[string]any{"description": "Missing or invalid token."},
94 "403": map[string]any{"description": "The token cannot read this private repo."},
95 "404": map[string]any{"description": "Unknown repo or merge request."},
96 },
97 },
98 },
99 "/repos/{owner}/{repo}/jobs/{id}/log": map[string]any{
100 "get": map[string]any{
101 "summary": "Full job log",
102 "description": "Returns the full console output as text/plain. Secret values of at least 8 characters are replaced with [MASKED]. Requires a personal access token. A token that can read the repo is enough, and on a public repo any valid personal token is enough. Job tokens are rejected.",
103 "security": []any{map[string]any{"bearer": []any{}}},
104 "parameters": []any{
105 map[string]any{"name": "owner", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
106 map[string]any{"name": "repo", "in": "path", "required": true, "schema": map[string]any{"type": "string"}},
107 map[string]any{"name": "id", "in": "path", "required": true, "schema": map[string]any{"type": "integer"}},
108 },
109 "responses": map[string]any{
110 "200": map[string]any{
111 "description": "Full log.",
112 "content": map[string]any{"text/plain": map[string]any{"schema": map[string]any{"type": "string"}}},
113 },
114 "401": map[string]any{"description": "Missing or invalid token."},
115 "403": map[string]any{"description": "The token cannot read this private repo."},
116 "404": map[string]any{"description": "Unknown repo or job."},
117 },
118 },
119 },
120 },
121 "webhooks": map[string]any{
122 "pipeline": post("Pipeline finished", "#/components/schemas/PipelineEvent"),
123 "push": post("Push", "#/components/schemas/PushEvent"),
124 "merge_request": post("Merge request", "#/components/schemas/MergeRequestEvent"),
125 "release": post("Release published", "#/components/schemas/ReleaseEvent"),
126 },
127 "components": map[string]any{
128 "securitySchemes": map[string]any{
129 "bearer": map[string]any{"type": "http", "scheme": "bearer", "description": "Personal access token (bg_)."},
130 },
131 "schemas": map[string]any{
132 "PipelineEvent": obj("pipeline_success or pipeline_failure.", map[string]any{
133 "object_kind": str("Always pipeline."),
134 "type": str("pipeline_success or pipeline_failure."),
135 "project": str("owner/name."),
136 "actor": str("User who started the pipeline."),
137 "summary": str("One-line summary."),
138 "url": str("Pipeline page."),
139 "pipeline_id": str("Same id as pipeline.id, as text."),
140 "pipeline": map[string]any{"$ref": "#/components/schemas/Pipeline"},
141 "jobs": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Job"}},
142 }, []string{"object_kind", "type", "project", "pipeline", "jobs"}),
143 "Pipeline": obj("The pipeline this event is about.", map[string]any{
144 "id": map[string]any{"type": "integer", "description": "Pipeline id."},
145 "status": str("success or failed."),
146 "ref": str("Full ref, such as refs/heads/master."),
147 "sha": str("Commit SHA."),
148 "commit_message": str("Subject and body of the commit."),
149 "author": str("User who started the pipeline."),
150 "duration": num("Seconds from start to finish."),
151 "url": str("Pipeline page."),
152 }, []string{"id", "status", "ref", "sha", "commit_message", "author", "duration"}),
153 "Job": obj("One job. log is always the console tail. log_url is present only when log_truncated is true.", map[string]any{
154 "name": str("Job name."),
155 "stage": str("Stage name."),
156 "status": str("Job status."),
157 "duration": num("Seconds the job ran."),
158 "allow_failure": boolean("True when a failure does not fail the pipeline."),
159 "web_url": str("Job page."),
160 "log": str("Last 200 lines of the console output, at most 64 KiB. Secrets of at least 8 characters are [MASKED]."),
161 "log_truncated": boolean("True when log is shorter than the stored console output."),
162 "log_url": str("GET /api/v1/repos/{owner}/{repo}/jobs/{id}/log. Present only when log_truncated is true. Requires Authorization Bearer and a personal token that can read the repo. The response is the full log as text/plain, with secrets masked."),
163 }, []string{"name", "stage", "status", "duration", "allow_failure", "web_url", "log", "log_truncated"}),
164 "PushEvent": obj("A branch or tag update.", map[string]any{
165 "object_kind": str("Always push."),
166 "type": str("Always push."),
167 "project": str("owner/name."),
168 "actor": str("User who pushed."),
169 "ref": str("Full ref."),
170 "before": str("Previous SHA, or 40 zeros when the ref is new."),
171 "after": str("New SHA."),
172 "commits": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
173 }, []string{"object_kind", "type", "project", "ref", "before", "after", "commits"}),
174 "Commit": obj("One commit. The diff text is not included.", map[string]any{
175 "sha": str("Commit SHA."),
176 "message": str("Subject and body."),
177 "author": str("Name and email."),
178 "timestamp": str("Author time in RFC3339."),
179 "url": str("Commit page."),
180 "files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
181 "diff_url": str("GET /api/v1/repos/{owner}/{repo}/commits/{sha}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the unified diff as text/plain."),
182 }, []string{"sha", "message", "author", "timestamp", "url", "files", "diff_url"}),
183 "FileChange": obj("One changed file, without the diff text.", map[string]any{
184 "path": str("Path after the change."),
185 "status": str("added, modified, removed or renamed."),
186 "previous_path": str("Path before a rename."),
187 "additions": map[string]any{"type": "integer", "description": "Added lines. Zero for a binary file."},
188 "deletions": map[string]any{"type": "integer", "description": "Deleted lines. Zero for a binary file."},
189 "binary": boolean("True when the file is binary."),
190 }, []string{"path", "status", "additions", "deletions"}),
191 "MergeRequestEvent": obj("Opened, merged or commented.", map[string]any{
192 "object_kind": str("Always merge_request."),
193 "type": str("Always merge_request."),
194 "project": str("owner/name."),
195 "actor": str("User who did this action."),
196 "merge_request": map[string]any{"$ref": "#/components/schemas/MergeRequest"},
197 "comment": str("Comment text. Present only when action is commented."),
198 }, []string{"object_kind", "type", "project", "merge_request"}),
199 "MergeRequest": obj("The merge request.", map[string]any{
200 "id": map[string]any{"type": "integer", "description": "Number in the project."},
201 "title": str("Title."),
202 "description": str("Description. May be empty."),
203 "source_branch": str("Source branch."),
204 "target_branch": str("Target branch."),
205 "status": str("open, merged or closed."),
206 "author": str("User who opened the merge request."),
207 "action": str("opened, merged or commented."),
208 "url": str("Merge request page."),
209 "reviewers": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Reviewer"}},
210 "comments": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Comment"}},
211 "commits": map[string]any{"type": "array", "description": "Up to 20 commits on the source branch that the target does not have, oldest first.", "items": map[string]any{"$ref": "#/components/schemas/Commit"}},
212 "diff_stats": map[string]any{"$ref": "#/components/schemas/DiffStats"},
213 "diff_url": str("GET /api/v1/repos/{owner}/{repo}/merge-requests/{id}/diff. Requires Authorization Bearer and a personal token that can read the repo. The response is the three-dot unified diff as text/plain."),
214 }, []string{"id", "title", "description", "source_branch", "target_branch", "status", "author", "action", "reviewers", "comments", "commits", "diff_stats", "diff_url"}),
215 "Reviewer": obj("The current review of one person.", map[string]any{
216 "username": str("Username."),
217 "status": str("approved, changes, rejected or dismissed."),
218 }, []string{"username", "status"}),
219 "Comment": obj("One comment on the merge request.", map[string]any{
220 "id": map[string]any{"type": "integer", "description": "Comment id."},
221 "author": str("Username."),
222 "body": str("Comment text."),
223 "created_at": str("Time in RFC3339."),
224 "file_path": str("File, when the comment is on a line."),
225 "line_start": map[string]any{"type": "integer", "description": "First line."},
226 "line_end": map[string]any{"type": "integer", "description": "Last line."},
227 "parent_id": map[string]any{"type": "integer", "description": "Parent comment, when this is a reply."},
228 }, []string{"id", "author", "body", "created_at"}),
229 "DiffStats": obj("Line counts of the merge request diff. The diff text is not included.", map[string]any{
230 "additions": map[string]any{"type": "integer", "description": "Added lines."},
231 "deletions": map[string]any{"type": "integer", "description": "Deleted lines."},
232 "files": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/FileChange"}},
233 }, []string{"additions", "deletions", "files"}),
234 "ReleaseEvent": obj("A published release.", map[string]any{
235 "object_kind": str("Always release."),
236 "type": str("Always release_published."),
237 "project": str("owner/name."),
238 "release_tag": str("Same value as release.tag."),
239 "release": map[string]any{"$ref": "#/components/schemas/Release"},
240 }, []string{"object_kind", "type", "project", "release"}),
241 "Release": obj("The release.", map[string]any{
242 "tag": str("Tag name."),
243 "name": str("Release title."),
244 "commit": str("Commit SHA."),
245 "assets": map[string]any{"type": "array", "items": map[string]any{"$ref": "#/components/schemas/Asset"}},
246 }, []string{"tag", "name", "commit", "assets"}),
247 "Asset": obj("A file attached to the release.", map[string]any{
248 "name": str("File name."),
249 "url": str("Download URL."),
250 "size": map[string]any{"type": "integer", "description": "Size in bytes."},
251 }, []string{"name", "url", "size"}),
252 },
253 },
254 }
255 raw, err := json.MarshalIndent(doc, "", " ")
256 if err != nil {
257 return []byte("{}\n")
258 }
259 return append(raw, '\n')
260}
internal/webhook/payload.go added +363 −0
@@ -0,0 +1,363 @@
1 package webhook
2
3 import (
4 "encoding/json"
5 "strings"
6
7 "gitlab.com/Timfa/bluegit/internal/ci"
8 )
9
10 // Grenzen voor wat een webhook van een gefaalde job meestuurt.
11 const (
12 LogMaxLines = 200
13 LogMaxBytes = 64 << 10
14 )
15
16 // MaxPushCommits is het aantal commits in een push-payload.
17 // Dat zijn de nieuwste in het bereik, oudste eerst.
18 const MaxPushCommits = 20
19
20 // Document is de JSON-body van een webhook zonder eigen sjabloon.
21 type Document struct {
22 ObjectKind string `json:"object_kind"`
23 Type string `json:"type"`
24 Project string `json:"project"`
25 Group string `json:"group,omitempty"`
26 Actor string `json:"actor,omitempty"`
27 Summary string `json:"summary,omitempty"`
28 URL string `json:"url,omitempty"`
29 Branch string `json:"branch,omitempty"`
30 Commit string `json:"commit,omitempty"`
31 PipelineID string `json:"pipeline_id,omitempty"`
32 ReleaseTag string `json:"release_tag,omitempty"`
33
34 Pipeline *PipelineInfo `json:"pipeline,omitempty"`
35 Jobs *[]JobInfo `json:"jobs,omitempty"`
36
37 Ref string `json:"ref,omitempty"`
38 Before string `json:"before,omitempty"`
39 After string `json:"after,omitempty"`
40 Commits *[]CommitInfo `json:"commits,omitempty"`
41
42 MergeRequest *MRInfo `json:"merge_request,omitempty"`
43 Comment string `json:"comment,omitempty"`
44
45 Release *ReleaseInfo `json:"release,omitempty"`
46 }
47
48 // PipelineInfo is de pipeline waar het event over gaat.
49 type PipelineInfo struct {
50 ID int64 `json:"id"`
51 Status string `json:"status"`
52 Ref string `json:"ref"`
53 SHA string `json:"sha"`
54 CommitMessage string `json:"commit_message"`
55 Author string `json:"author"`
56 Duration float64 `json:"duration"`
57 URL string `json:"url,omitempty"`
58 }
59
60 // JobInfo is één job in een pipeline-event.
61 // Elke job stuurt de console-output mee. log_url staat er alleen als de log
62 // is afgekapt, en wijst naar de API voor de volledige tekst.
63 type JobInfo struct {
64 Name string `json:"name"`
65 Stage string `json:"stage"`
66 Status string `json:"status"`
67 Duration float64 `json:"duration"`
68 AllowFailure bool `json:"allow_failure"`
69 WebURL string `json:"web_url"`
70 Log string `json:"log"`
71 LogTruncated bool `json:"log_truncated"`
72 LogURL string `json:"log_url,omitempty"`
73 }
74
75 // CommitInfo is één commit in een push of merge request.
76 // Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;
77 // diff_url wijst naar de API die hem teruggeeft.
78 type CommitInfo struct {
79 SHA string `json:"sha"`
80 Message string `json:"message"`
81 Author string `json:"author"`
82 Timestamp string `json:"timestamp"`
83 URL string `json:"url"`
84 Files []FileChange `json:"files"`
85 DiffURL string `json:"diff_url"`
86 }
87
88 // FileChange is één gewijzigd bestand, met status en regelaantallen.
89 // Status is added, modified, removed of renamed.
90 type FileChange struct {
91 Path string `json:"path"`
92 Status string `json:"status"`
93 PreviousPath string `json:"previous_path,omitempty"`
94 Additions int `json:"additions"`
95 Deletions int `json:"deletions"`
96 Binary bool `json:"binary,omitempty"`
97 }
98
99 // MRInfo is de merge request van het event.
100 // DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.
101 type MRInfo struct {
102 ID int64 `json:"id"`
103 Title string `json:"title"`
104 Description string `json:"description"`
105 SourceBranch string `json:"source_branch"`
106 TargetBranch string `json:"target_branch"`
107 Status string `json:"status"`
108 Author string `json:"author"`
109 Action string `json:"action"`
110 URL string `json:"url,omitempty"`
111 Reviewers []ReviewerInfo `json:"reviewers"`
112 Comments []CommentInfo `json:"comments"`
113 Commits []CommitInfo `json:"commits"`
114 DiffStats DiffStats `json:"diff_stats"`
115 DiffURL string `json:"diff_url"`
116 }
117
118 // ReviewerInfo is de huidige review van één persoon.
119 type ReviewerInfo struct {
120 Username string `json:"username"`
121 Status string `json:"status"`
122 }
123
124 // CommentInfo is een reactie op de merge request.
125 type CommentInfo struct {
126 ID int64 `json:"id"`
127 Author string `json:"author"`
128 Body string `json:"body"`
129 CreatedAt string `json:"created_at"`
130 FilePath string `json:"file_path,omitempty"`
131 LineStart int `json:"line_start,omitempty"`
132 LineEnd int `json:"line_end,omitempty"`
133 ParentID int64 `json:"parent_id,omitempty"`
134 }
135
136 // DiffStats telt de regels van de vergelijking, per bestand.
137 type DiffStats struct {
138 Additions int `json:"additions"`
139 Deletions int `json:"deletions"`
140 Files []FileChange `json:"files"`
141 }
142
143 // ReleaseInfo is een gepubliceerde release.
144 type ReleaseInfo struct {
145 Tag string `json:"tag"`
146 Name string `json:"name"`
147 Commit string `json:"commit"`
148 Assets []AssetInfo `json:"assets"`
149 }
150
151 // AssetInfo is een bestand bij een release.
152 type AssetInfo struct {
153 Name string `json:"name"`
154 URL string `json:"url"`
155 Size int64 `json:"size"`
156 }
157
158 // Document bouwt de JSON-structuur. Lege deelobjecten blijven weg.
159 func (ev Event) Document() Document {
160 d := Document{
161 ObjectKind: objectKind(ev.Type),
162 Type: ev.Type,
163 Project: ev.Project,
164 Group: ev.Group,
165 Actor: ev.Actor,
166 Summary: ev.Summary,
167 URL: ev.URL,
168 Branch: ev.Branch,
169 Commit: ev.Commit,
170 PipelineID: ev.PipelineID,
171 ReleaseTag: ev.ReleaseTag,
172 Pipeline: ev.Pipeline,
173 Ref: ev.Ref,
174 Before: ev.Before,
175 After: ev.After,
176 MergeRequest: ev.MergeRequest,
177 Release: ev.Release,
178 }
179 switch ev.Type {
180 case EventPush:
181 commits := ev.Commits
182 if commits == nil {
183 commits = []CommitInfo{}
184 }
185 for i := range commits {
186 if commits[i].Files == nil {
187 commits[i].Files = []FileChange{}
188 }
189 }
190 d.Commits = &commits
191 case EventPipelineSuccess, EventPipelineFailure:
192 jobs := ev.Jobs
193 if jobs == nil {
194 jobs = []JobInfo{}
195 }
196 d.Jobs = &jobs
197 case EventMergeRequest:
198 if ev.MergeRequest != nil {
199 mr := *ev.MergeRequest
200 if mr.Reviewers == nil {
201 mr.Reviewers = []ReviewerInfo{}
202 }
203 if mr.Comments == nil {
204 mr.Comments = []CommentInfo{}
205 }
206 if mr.Commits == nil {
207 mr.Commits = []CommitInfo{}
208 }
209 for i := range mr.Commits {
210 if mr.Commits[i].Files == nil {
211 mr.Commits[i].Files = []FileChange{}
212 }
213 }
214 if mr.DiffStats.Files == nil {
215 mr.DiffStats.Files = []FileChange{}
216 }
217 d.MergeRequest = &mr
218 if mr.Action == "commented" {
219 d.Comment = ev.Comment
220 }
221 }
222 }
223 if d.Release != nil && d.Release.Assets == nil {
224 rel := *d.Release
225 rel.Assets = []AssetInfo{}
226 d.Release = &rel
227 }
228 return d
229 }
230
231 func objectKind(eventType string) string {
232 switch eventType {
233 case EventPipelineSuccess, EventPipelineFailure:
234 return "pipeline"
235 case EventRelease:
236 return "release"
237 case EventMergeRequest:
238 return "merge_request"
239 default:
240 return eventType
241 }
242 }
243
244 // TailLog houdt de laatste LogMaxLines regels en hoogstens LogMaxBytes.
245 // Geheimwaarden van minstens 8 tekens worden [MASKED], net als in de joblog.
246 // truncated is true zodra er regels of bytes af zijn.
247 func TailLog(text string, secrets []string) (string, bool) {
248 text = ci.Mask(text, secrets)
249 if text == "" {
250 return "", false
251 }
252 truncated := false
253 lines := strings.Split(text, "\n")
254 if len(lines) > LogMaxLines {
255 lines = lines[len(lines)-LogMaxLines:]
256 truncated = true
257 }
258 out := strings.Join(lines, "\n")
259 if len(out) > LogMaxBytes {
260 out = cutUTF8Tail(out, LogMaxBytes)
261 truncated = true
262 }
263 return out, truncated
264 }
265
266 func cutUTF8Tail(s string, max int) string {
267 if len(s) <= max {
268 return s
269 }
270 s = s[len(s)-max:]
271 for len(s) > 0 && s[0]&0xC0 == 0x80 {
272 s = s[1:]
273 }
274 return s
275 }
276
277 // Example is het voorbeeld op de infopagina.
278 func Example() string {
279 samples := []Event{
280 {
281 Type: EventPipelineFailure, Project: "tim/app", Actor: "tim",
282 Summary: "pipeline #26 voor tim/app is mislukt",
283 URL: "https://git.example/tim/app/-/pipelines/26",
284 Branch: "master", Commit: "725e6947", PipelineID: "26",
285 Pipeline: &PipelineInfo{
286 ID: 26, Status: "failed", Ref: "refs/heads/master", SHA: "725e6947",
287 CommitMessage: "fix de build", Author: "tim", Duration: 12.4,
288 URL: "https://git.example/tim/app/-/pipelines/26",
289 },
290 Jobs: []JobInfo{
291 {
292 Name: "test", Stage: "test", Status: "failed", Duration: 4.1,
293 AllowFailure: false, WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/7",
294 Log: "go: token [MASKED]\nFAIL", LogTruncated: true,
295 LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log",
296 },
297 {
298 Name: "build", Stage: "build", Status: "success", Duration: 8,
299 WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/8",
300 Log: "built bluegit",
301 },
302 },
303 },
304 {
305 Type: EventPush, Project: "tim/app", Actor: "tim", Branch: "master",
306 Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",
307 Commits: []CommitInfo{{
308 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
309 Timestamp: "2026-10-22T12:00:00Z",
310 URL: "https://git.example/tim/app/-/commit/abc123",
311 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
312 Files: []FileChange{{
313 Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,
314 }},
315 }},
316 },
317 {
318 Type: EventMergeRequest, Project: "tim/app", Actor: "ada",
319 MergeRequest: &MRInfo{
320 ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",
321 SourceBranch: "feature", TargetBranch: "master", Status: "open",
322 Author: "ada", Action: "opened",
323 URL: "https://git.example/tim/app/-/merge-requests/4",
324 DiffURL: "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",
325 Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},
326 Comments: []CommentInfo{},
327 Commits: []CommitInfo{{
328 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
329 Timestamp: "2026-10-22T12:00:00Z",
330 URL: "https://git.example/tim/app/-/commit/abc123",
331 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
332 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
333 }},
334 DiffStats: DiffStats{
335 Additions: 1, Deletions: 1,
336 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
337 },
338 },
339 },
340 {
341 Type: EventRelease, Project: "tim/app", ReleaseTag: "v1.2.0", Commit: "abc123",
342 Release: &ReleaseInfo{
343 Tag: "v1.2.0", Name: "BlueGit 1.2.0", Commit: "abc123",
344 Assets: []AssetInfo{{
345 Name: "bluegit", Size: 8123456,
346 URL: "https://git.example/tim/app/-/releases/v1.2.0/assets/bluegit",
347 }},
348 },
349 },
350 }
351 var b strings.Builder
352 for i, ev := range samples {
353 if i > 0 {
354 b.WriteString("\n\n")
355 }
356 raw, err := json.MarshalIndent(ev.Document(), "", " ")
357 if err != nil {
358 continue
359 }
360 b.Write(raw)
361 }
362 return b.String()
363 }
@@ -0,0 +1,363 @@
1package webhook
2
3import (
4 "encoding/json"
5 "strings"
6
7 "gitlab.com/Timfa/bluegit/internal/ci"
8)
9
10// Grenzen voor wat een webhook van een gefaalde job meestuurt.
11const (
12 LogMaxLines = 200
13 LogMaxBytes = 64 << 10
14)
15
16// MaxPushCommits is het aantal commits in een push-payload.
17// Dat zijn de nieuwste in het bereik, oudste eerst.
18const MaxPushCommits = 20
19
20// Document is de JSON-body van een webhook zonder eigen sjabloon.
21type Document struct {
22 ObjectKind string `json:"object_kind"`
23 Type string `json:"type"`
24 Project string `json:"project"`
25 Group string `json:"group,omitempty"`
26 Actor string `json:"actor,omitempty"`
27 Summary string `json:"summary,omitempty"`
28 URL string `json:"url,omitempty"`
29 Branch string `json:"branch,omitempty"`
30 Commit string `json:"commit,omitempty"`
31 PipelineID string `json:"pipeline_id,omitempty"`
32 ReleaseTag string `json:"release_tag,omitempty"`
33
34 Pipeline *PipelineInfo `json:"pipeline,omitempty"`
35 Jobs *[]JobInfo `json:"jobs,omitempty"`
36
37 Ref string `json:"ref,omitempty"`
38 Before string `json:"before,omitempty"`
39 After string `json:"after,omitempty"`
40 Commits *[]CommitInfo `json:"commits,omitempty"`
41
42 MergeRequest *MRInfo `json:"merge_request,omitempty"`
43 Comment string `json:"comment,omitempty"`
44
45 Release *ReleaseInfo `json:"release,omitempty"`
46}
47
48// PipelineInfo is de pipeline waar het event over gaat.
49type PipelineInfo struct {
50 ID int64 `json:"id"`
51 Status string `json:"status"`
52 Ref string `json:"ref"`
53 SHA string `json:"sha"`
54 CommitMessage string `json:"commit_message"`
55 Author string `json:"author"`
56 Duration float64 `json:"duration"`
57 URL string `json:"url,omitempty"`
58}
59
60// JobInfo is één job in een pipeline-event.
61// Elke job stuurt de console-output mee. log_url staat er alleen als de log
62// is afgekapt, en wijst naar de API voor de volledige tekst.
63type JobInfo struct {
64 Name string `json:"name"`
65 Stage string `json:"stage"`
66 Status string `json:"status"`
67 Duration float64 `json:"duration"`
68 AllowFailure bool `json:"allow_failure"`
69 WebURL string `json:"web_url"`
70 Log string `json:"log"`
71 LogTruncated bool `json:"log_truncated"`
72 LogURL string `json:"log_url,omitempty"`
73}
74
75// CommitInfo is één commit in een push of merge request.
76// Files noemt de wijzigingen. De difftekst zelf staat niet in de payload;
77// diff_url wijst naar de API die hem teruggeeft.
78type CommitInfo struct {
79 SHA string `json:"sha"`
80 Message string `json:"message"`
81 Author string `json:"author"`
82 Timestamp string `json:"timestamp"`
83 URL string `json:"url"`
84 Files []FileChange `json:"files"`
85 DiffURL string `json:"diff_url"`
86}
87
88// FileChange is één gewijzigd bestand, met status en regelaantallen.
89// Status is added, modified, removed of renamed.
90type FileChange struct {
91 Path string `json:"path"`
92 Status string `json:"status"`
93 PreviousPath string `json:"previous_path,omitempty"`
94 Additions int `json:"additions"`
95 Deletions int `json:"deletions"`
96 Binary bool `json:"binary,omitempty"`
97}
98
99// MRInfo is de merge request van het event.
100// DiffStats is de three-dot vergelijking. De difftekst staat op diff_url.
101type MRInfo struct {
102 ID int64 `json:"id"`
103 Title string `json:"title"`
104 Description string `json:"description"`
105 SourceBranch string `json:"source_branch"`
106 TargetBranch string `json:"target_branch"`
107 Status string `json:"status"`
108 Author string `json:"author"`
109 Action string `json:"action"`
110 URL string `json:"url,omitempty"`
111 Reviewers []ReviewerInfo `json:"reviewers"`
112 Comments []CommentInfo `json:"comments"`
113 Commits []CommitInfo `json:"commits"`
114 DiffStats DiffStats `json:"diff_stats"`
115 DiffURL string `json:"diff_url"`
116}
117
118// ReviewerInfo is de huidige review van één persoon.
119type ReviewerInfo struct {
120 Username string `json:"username"`
121 Status string `json:"status"`
122}
123
124// CommentInfo is een reactie op de merge request.
125type CommentInfo struct {
126 ID int64 `json:"id"`
127 Author string `json:"author"`
128 Body string `json:"body"`
129 CreatedAt string `json:"created_at"`
130 FilePath string `json:"file_path,omitempty"`
131 LineStart int `json:"line_start,omitempty"`
132 LineEnd int `json:"line_end,omitempty"`
133 ParentID int64 `json:"parent_id,omitempty"`
134}
135
136// DiffStats telt de regels van de vergelijking, per bestand.
137type DiffStats struct {
138 Additions int `json:"additions"`
139 Deletions int `json:"deletions"`
140 Files []FileChange `json:"files"`
141}
142
143// ReleaseInfo is een gepubliceerde release.
144type ReleaseInfo struct {
145 Tag string `json:"tag"`
146 Name string `json:"name"`
147 Commit string `json:"commit"`
148 Assets []AssetInfo `json:"assets"`
149}
150
151// AssetInfo is een bestand bij een release.
152type AssetInfo struct {
153 Name string `json:"name"`
154 URL string `json:"url"`
155 Size int64 `json:"size"`
156}
157
158// Document bouwt de JSON-structuur. Lege deelobjecten blijven weg.
159func (ev Event) Document() Document {
160 d := Document{
161 ObjectKind: objectKind(ev.Type),
162 Type: ev.Type,
163 Project: ev.Project,
164 Group: ev.Group,
165 Actor: ev.Actor,
166 Summary: ev.Summary,
167 URL: ev.URL,
168 Branch: ev.Branch,
169 Commit: ev.Commit,
170 PipelineID: ev.PipelineID,
171 ReleaseTag: ev.ReleaseTag,
172 Pipeline: ev.Pipeline,
173 Ref: ev.Ref,
174 Before: ev.Before,
175 After: ev.After,
176 MergeRequest: ev.MergeRequest,
177 Release: ev.Release,
178 }
179 switch ev.Type {
180 case EventPush:
181 commits := ev.Commits
182 if commits == nil {
183 commits = []CommitInfo{}
184 }
185 for i := range commits {
186 if commits[i].Files == nil {
187 commits[i].Files = []FileChange{}
188 }
189 }
190 d.Commits = &commits
191 case EventPipelineSuccess, EventPipelineFailure:
192 jobs := ev.Jobs
193 if jobs == nil {
194 jobs = []JobInfo{}
195 }
196 d.Jobs = &jobs
197 case EventMergeRequest:
198 if ev.MergeRequest != nil {
199 mr := *ev.MergeRequest
200 if mr.Reviewers == nil {
201 mr.Reviewers = []ReviewerInfo{}
202 }
203 if mr.Comments == nil {
204 mr.Comments = []CommentInfo{}
205 }
206 if mr.Commits == nil {
207 mr.Commits = []CommitInfo{}
208 }
209 for i := range mr.Commits {
210 if mr.Commits[i].Files == nil {
211 mr.Commits[i].Files = []FileChange{}
212 }
213 }
214 if mr.DiffStats.Files == nil {
215 mr.DiffStats.Files = []FileChange{}
216 }
217 d.MergeRequest = &mr
218 if mr.Action == "commented" {
219 d.Comment = ev.Comment
220 }
221 }
222 }
223 if d.Release != nil && d.Release.Assets == nil {
224 rel := *d.Release
225 rel.Assets = []AssetInfo{}
226 d.Release = &rel
227 }
228 return d
229}
230
231func objectKind(eventType string) string {
232 switch eventType {
233 case EventPipelineSuccess, EventPipelineFailure:
234 return "pipeline"
235 case EventRelease:
236 return "release"
237 case EventMergeRequest:
238 return "merge_request"
239 default:
240 return eventType
241 }
242}
243
244// TailLog houdt de laatste LogMaxLines regels en hoogstens LogMaxBytes.
245// Geheimwaarden van minstens 8 tekens worden [MASKED], net als in de joblog.
246// truncated is true zodra er regels of bytes af zijn.
247func TailLog(text string, secrets []string) (string, bool) {
248 text = ci.Mask(text, secrets)
249 if text == "" {
250 return "", false
251 }
252 truncated := false
253 lines := strings.Split(text, "\n")
254 if len(lines) > LogMaxLines {
255 lines = lines[len(lines)-LogMaxLines:]
256 truncated = true
257 }
258 out := strings.Join(lines, "\n")
259 if len(out) > LogMaxBytes {
260 out = cutUTF8Tail(out, LogMaxBytes)
261 truncated = true
262 }
263 return out, truncated
264}
265
266func cutUTF8Tail(s string, max int) string {
267 if len(s) <= max {
268 return s
269 }
270 s = s[len(s)-max:]
271 for len(s) > 0 && s[0]&0xC0 == 0x80 {
272 s = s[1:]
273 }
274 return s
275}
276
277// Example is het voorbeeld op de infopagina.
278func Example() string {
279 samples := []Event{
280 {
281 Type: EventPipelineFailure, Project: "tim/app", Actor: "tim",
282 Summary: "pipeline #26 voor tim/app is mislukt",
283 URL: "https://git.example/tim/app/-/pipelines/26",
284 Branch: "master", Commit: "725e6947", PipelineID: "26",
285 Pipeline: &PipelineInfo{
286 ID: 26, Status: "failed", Ref: "refs/heads/master", SHA: "725e6947",
287 CommitMessage: "fix de build", Author: "tim", Duration: 12.4,
288 URL: "https://git.example/tim/app/-/pipelines/26",
289 },
290 Jobs: []JobInfo{
291 {
292 Name: "test", Stage: "test", Status: "failed", Duration: 4.1,
293 AllowFailure: false, WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/7",
294 Log: "go: token [MASKED]\nFAIL", LogTruncated: true,
295 LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log",
296 },
297 {
298 Name: "build", Stage: "build", Status: "success", Duration: 8,
299 WebURL: "https://git.example/tim/app/-/pipelines/26/jobs/8",
300 Log: "built bluegit",
301 },
302 },
303 },
304 {
305 Type: EventPush, Project: "tim/app", Actor: "tim", Branch: "master",
306 Ref: "refs/heads/master", Before: strings.Repeat("0", 40), After: "abc123",
307 Commits: []CommitInfo{{
308 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
309 Timestamp: "2026-10-22T12:00:00Z",
310 URL: "https://git.example/tim/app/-/commit/abc123",
311 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
312 Files: []FileChange{{
313 Path: "README.md", Status: "modified", Additions: 1, Deletions: 1,
314 }},
315 }},
316 },
317 {
318 Type: EventMergeRequest, Project: "tim/app", Actor: "ada",
319 MergeRequest: &MRInfo{
320 ID: 4, Title: "Toon de kloon-URL", Description: "SSH en HTTPS.",
321 SourceBranch: "feature", TargetBranch: "master", Status: "open",
322 Author: "ada", Action: "opened",
323 URL: "https://git.example/tim/app/-/merge-requests/4",
324 DiffURL: "https://git.example/api/v1/repos/tim/app/merge-requests/4/diff",
325 Reviewers: []ReviewerInfo{{Username: "tim", Status: "approved"}},
326 Comments: []CommentInfo{},
327 Commits: []CommitInfo{{
328 SHA: "abc123", Message: "fix de build", Author: "Tim <tim@example.com>",
329 Timestamp: "2026-10-22T12:00:00Z",
330 URL: "https://git.example/tim/app/-/commit/abc123",
331 DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc123/diff",
332 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
333 }},
334 DiffStats: DiffStats{
335 Additions: 1, Deletions: 1,
336 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
337 },
338 },
339 },
340 {
341 Type: EventRelease, Project: "tim/app", ReleaseTag: "v1.2.0", Commit: "abc123",
342 Release: &ReleaseInfo{
343 Tag: "v1.2.0", Name: "BlueGit 1.2.0", Commit: "abc123",
344 Assets: []AssetInfo{{
345 Name: "bluegit", Size: 8123456,
346 URL: "https://git.example/tim/app/-/releases/v1.2.0/assets/bluegit",
347 }},
348 },
349 },
350 }
351 var b strings.Builder
352 for i, ev := range samples {
353 if i > 0 {
354 b.WriteString("\n\n")
355 }
356 raw, err := json.MarshalIndent(ev.Document(), "", " ")
357 if err != nil {
358 continue
359 }
360 b.Write(raw)
361 }
362 return b.String()
363}
internal/webhook/payload_test.go added +180 −0
@@ -0,0 +1,180 @@
1 package webhook
2
3 import (
4 "encoding/json"
5 "strings"
6 "testing"
7 )
8
9 func TestTailLogMasksAndCuts(t *testing.T) {
10 secret := "super-secret-token"
11 var lines []string
12 for i := 0; i < LogMaxLines+40; i++ {
13 lines = append(lines, "regel")
14 }
15 lines = append(lines, "token "+secret)
16 got, truncated := TailLog(strings.Join(lines, "\n"), []string{secret})
17 if !truncated {
18 t.Fatal("te lange log hoort afgekapt")
19 }
20 if n := len(strings.Split(got, "\n")); n != LogMaxLines {
21 t.Fatalf("regels %d", n)
22 }
23 if strings.Contains(got, secret) || !strings.Contains(got, "[MASKED]") {
24 t.Fatalf("masker: %s", got[len(got)-80:])
25 }
26 if _, truncated := TailLog("kort\n", []string{secret}); truncated {
27 t.Fatal("korte log")
28 }
29 got, _ = TailLog("code "+secret, nil)
30 if strings.Contains(got, "[MASKED]") {
31 t.Fatal("zonder geheimen niets maskeren")
32 }
33 huge := strings.Repeat("x", LogMaxBytes+100)
34 got, truncated = TailLog(huge, nil)
35 if !truncated || len(got) > LogMaxBytes {
36 t.Fatalf("bytes %d truncated %v", len(got), truncated)
37 }
38 }
39
40 func TestDocumentShapes(t *testing.T) {
41 pipe := Event{
42 Type: EventPipelineFailure, Project: "tim/app", PipelineID: "9",
43 Pipeline: &PipelineInfo{ID: 9, Status: "failed", Ref: "refs/heads/master", SHA: "abc", CommitMessage: "fix", Author: "tim", Duration: 1.5},
44 Jobs: []JobInfo{
45 {Name: "test", Stage: "test", Status: "failed", Duration: 1, AllowFailure: false, WebURL: "https://git.example/job", Log: "boom", LogTruncated: true, LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log"},
46 {Name: "build", Stage: "build", Status: "success", WebURL: "https://git.example/build", Log: "ok"},
47 },
48 }
49 body, err := RenderBody("", pipe, nil)
50 if err != nil {
51 t.Fatal(err)
52 }
53 var doc map[string]any
54 if err := json.Unmarshal(body, &doc); err != nil {
55 t.Fatal(err)
56 }
57 if doc["object_kind"] != "pipeline" || doc["pipeline_id"] != "9" {
58 t.Fatalf("pipeline %s", body)
59 }
60 jobs := doc["jobs"].([]any)
61 failed := jobs[0].(map[string]any)
62 if failed["log"] != "boom" || failed["log_truncated"] != true || failed["allow_failure"] != false || failed["log_url"] == "" {
63 t.Fatalf("gefaalde job %v", failed)
64 }
65 ok := jobs[1].(map[string]any)
66 if ok["log"] != "ok" || ok["log_truncated"] != false {
67 t.Fatalf("geslaagde job %v", ok)
68 }
69 if _, has := ok["log_url"]; has {
70 t.Fatalf("korte log heeft een url: %v", ok)
71 }
72
73 push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b", Commits: []CommitInfo{{
74 SHA: "abc", Message: "fix", Author: "tim <tim@example.com>", Timestamp: "2026-10-22T12:00:00Z",
75 URL: "https://git.example/commit", DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc/diff",
76 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
77 }}}
78 body, err = RenderBody("", push, nil)
79 if err != nil {
80 t.Fatal(err)
81 }
82 if strings.Contains(string(body), "diff --git") {
83 t.Fatalf("push bevat een diff: %s", body)
84 }
85 if err := json.Unmarshal(body, &doc); err != nil {
86 t.Fatal(err)
87 }
88 if doc["object_kind"] != "push" || doc["before"] != "a" || doc["commits"] == nil {
89 t.Fatalf("push %s", body)
90 }
91 commit := doc["commits"].([]any)[0].(map[string]any)
92 file := commit["files"].([]any)[0].(map[string]any)
93 if commit["timestamp"] != "2026-10-22T12:00:00Z" || commit["diff_url"] == "" || file["status"] != "modified" || file["additions"] != float64(1) || file["deletions"] != float64(1) {
94 t.Fatalf("commit %s", body)
95 }
96 if _, has := commit["diff"]; has || file["path"] != "README.md" {
97 t.Fatalf("commit lekt een diff: %s", body)
98 }
99
100 mr := Event{
101 Type: EventMergeRequest, Project: "tim/app", Comment: "hoort niet mee",
102 MergeRequest: &MRInfo{ID: 3, Title: "titel", Description: "tekst", SourceBranch: "f", TargetBranch: "master", Status: "open", Author: "ada", Action: "opened"},
103 }
104 body, err = RenderBody("", mr, nil)
105 if err != nil {
106 t.Fatal(err)
107 }
108 if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) || strings.Contains(string(body), "diff --git") {
109 t.Fatalf("opened lekt commentaar of een diff: %s", body)
110 }
111 if err := json.Unmarshal(body, &doc); err != nil {
112 t.Fatal(err)
113 }
114 openedMR := doc["merge_request"].(map[string]any)
115 if openedMR["reviewers"] == nil || openedMR["comments"] == nil || openedMR["commits"] == nil || openedMR["diff_stats"] == nil || openedMR["diff_url"] == nil {
116 t.Fatalf("mr mist details: %s", body)
117 }
118 mr.MergeRequest.Action = "commented"
119 mr.Comment = "mooie opmerking"
120 body, err = RenderBody("", mr, nil)
121 if err != nil || !strings.Contains(string(body), "mooie opmerking") {
122 t.Fatalf("commented %s %v", body, err)
123 }
124
125 rel := Event{
126 Type: EventRelease, Project: "tim/app", ReleaseTag: "v1",
127 Release: &ReleaseInfo{Tag: "v1", Name: "Een", Commit: "abc", Assets: []AssetInfo{{Name: "bluegit", URL: "https://git.example/a", Size: 4}}},
128 }
129 body, err = RenderBody("", rel, nil)
130 if err != nil {
131 t.Fatal(err)
132 }
133 if err := json.Unmarshal(body, &doc); err != nil {
134 t.Fatal(err)
135 }
136 if doc["object_kind"] != "release" {
137 t.Fatal(string(body))
138 }
139 release := doc["release"].(map[string]any)
140 assets := release["assets"].([]any)
141 if release["tag"] != "v1" || release["commit"] != "abc" || assets[0].(map[string]any)["url"] != "https://git.example/a" {
142 t.Fatalf("release %s", body)
143 }
144
145 rendered, err := Expand("{{event.payload}}", pipe, nil)
146 if err != nil || !strings.Contains(rendered, `"log":"boom"`) {
147 t.Fatalf("payload-placeholder %s %v", rendered, err)
148 }
149 }
150
151 func TestOpenAPIMatchesExample(t *testing.T) {
152 var spec map[string]any
153 if err := json.Unmarshal(OpenAPI(), &spec); err != nil {
154 t.Fatal(err)
155 }
156 if spec["openapi"] != "3.1.0" {
157 t.Fatalf("versie %v", spec["openapi"])
158 }
159 raw := string(OpenAPI())
160 for _, want := range []string{
161 "PipelineEvent", "PushEvent", "MergeRequestEvent", "ReleaseEvent",
162 "commit_message", "allow_failure", "log_truncated", "log_url",
163 "/repos/{owner}/{repo}/jobs/{id}/log",
164 "diff_url", "reviewers", "diff_stats", "/commits/{sha}/diff", "/merge-requests/{id}/diff",
165 "source_branch", "target_branch", "before", "after", "assets",
166 } {
167 if !strings.Contains(raw, want) {
168 t.Errorf("openapi mist %s", want)
169 }
170 }
171 example := Example()
172 for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented", "diff_url", "reviewers", "additions"} {
173 if !strings.Contains(example, want) && want != "commented" {
174 t.Errorf("voorbeeld mist %s", want)
175 }
176 }
177 if !strings.Contains(example, `"action": "opened"`) {
178 t.Fatalf("voorbeeld:\n%s", example)
179 }
180 }
@@ -0,0 +1,180 @@
1package webhook
2
3import (
4 "encoding/json"
5 "strings"
6 "testing"
7)
8
9func TestTailLogMasksAndCuts(t *testing.T) {
10 secret := "super-secret-token"
11 var lines []string
12 for i := 0; i < LogMaxLines+40; i++ {
13 lines = append(lines, "regel")
14 }
15 lines = append(lines, "token "+secret)
16 got, truncated := TailLog(strings.Join(lines, "\n"), []string{secret})
17 if !truncated {
18 t.Fatal("te lange log hoort afgekapt")
19 }
20 if n := len(strings.Split(got, "\n")); n != LogMaxLines {
21 t.Fatalf("regels %d", n)
22 }
23 if strings.Contains(got, secret) || !strings.Contains(got, "[MASKED]") {
24 t.Fatalf("masker: %s", got[len(got)-80:])
25 }
26 if _, truncated := TailLog("kort\n", []string{secret}); truncated {
27 t.Fatal("korte log")
28 }
29 got, _ = TailLog("code "+secret, nil)
30 if strings.Contains(got, "[MASKED]") {
31 t.Fatal("zonder geheimen niets maskeren")
32 }
33 huge := strings.Repeat("x", LogMaxBytes+100)
34 got, truncated = TailLog(huge, nil)
35 if !truncated || len(got) > LogMaxBytes {
36 t.Fatalf("bytes %d truncated %v", len(got), truncated)
37 }
38}
39
40func TestDocumentShapes(t *testing.T) {
41 pipe := Event{
42 Type: EventPipelineFailure, Project: "tim/app", PipelineID: "9",
43 Pipeline: &PipelineInfo{ID: 9, Status: "failed", Ref: "refs/heads/master", SHA: "abc", CommitMessage: "fix", Author: "tim", Duration: 1.5},
44 Jobs: []JobInfo{
45 {Name: "test", Stage: "test", Status: "failed", Duration: 1, AllowFailure: false, WebURL: "https://git.example/job", Log: "boom", LogTruncated: true, LogURL: "https://git.example/api/v1/repos/tim/app/jobs/7/log"},
46 {Name: "build", Stage: "build", Status: "success", WebURL: "https://git.example/build", Log: "ok"},
47 },
48 }
49 body, err := RenderBody("", pipe, nil)
50 if err != nil {
51 t.Fatal(err)
52 }
53 var doc map[string]any
54 if err := json.Unmarshal(body, &doc); err != nil {
55 t.Fatal(err)
56 }
57 if doc["object_kind"] != "pipeline" || doc["pipeline_id"] != "9" {
58 t.Fatalf("pipeline %s", body)
59 }
60 jobs := doc["jobs"].([]any)
61 failed := jobs[0].(map[string]any)
62 if failed["log"] != "boom" || failed["log_truncated"] != true || failed["allow_failure"] != false || failed["log_url"] == "" {
63 t.Fatalf("gefaalde job %v", failed)
64 }
65 ok := jobs[1].(map[string]any)
66 if ok["log"] != "ok" || ok["log_truncated"] != false {
67 t.Fatalf("geslaagde job %v", ok)
68 }
69 if _, has := ok["log_url"]; has {
70 t.Fatalf("korte log heeft een url: %v", ok)
71 }
72
73 push := Event{Type: EventPush, Project: "tim/app", Ref: "refs/heads/master", Before: "a", After: "b", Commits: []CommitInfo{{
74 SHA: "abc", Message: "fix", Author: "tim <tim@example.com>", Timestamp: "2026-10-22T12:00:00Z",
75 URL: "https://git.example/commit", DiffURL: "https://git.example/api/v1/repos/tim/app/commits/abc/diff",
76 Files: []FileChange{{Path: "README.md", Status: "modified", Additions: 1, Deletions: 1}},
77 }}}
78 body, err = RenderBody("", push, nil)
79 if err != nil {
80 t.Fatal(err)
81 }
82 if strings.Contains(string(body), "diff --git") {
83 t.Fatalf("push bevat een diff: %s", body)
84 }
85 if err := json.Unmarshal(body, &doc); err != nil {
86 t.Fatal(err)
87 }
88 if doc["object_kind"] != "push" || doc["before"] != "a" || doc["commits"] == nil {
89 t.Fatalf("push %s", body)
90 }
91 commit := doc["commits"].([]any)[0].(map[string]any)
92 file := commit["files"].([]any)[0].(map[string]any)
93 if commit["timestamp"] != "2026-10-22T12:00:00Z" || commit["diff_url"] == "" || file["status"] != "modified" || file["additions"] != float64(1) || file["deletions"] != float64(1) {
94 t.Fatalf("commit %s", body)
95 }
96 if _, has := commit["diff"]; has || file["path"] != "README.md" {
97 t.Fatalf("commit lekt een diff: %s", body)
98 }
99
100 mr := Event{
101 Type: EventMergeRequest, Project: "tim/app", Comment: "hoort niet mee",
102 MergeRequest: &MRInfo{ID: 3, Title: "titel", Description: "tekst", SourceBranch: "f", TargetBranch: "master", Status: "open", Author: "ada", Action: "opened"},
103 }
104 body, err = RenderBody("", mr, nil)
105 if err != nil {
106 t.Fatal(err)
107 }
108 if strings.Contains(string(body), "hoort niet mee") || !strings.Contains(string(body), `"action":"opened"`) || strings.Contains(string(body), "diff --git") {
109 t.Fatalf("opened lekt commentaar of een diff: %s", body)
110 }
111 if err := json.Unmarshal(body, &doc); err != nil {
112 t.Fatal(err)
113 }
114 openedMR := doc["merge_request"].(map[string]any)
115 if openedMR["reviewers"] == nil || openedMR["comments"] == nil || openedMR["commits"] == nil || openedMR["diff_stats"] == nil || openedMR["diff_url"] == nil {
116 t.Fatalf("mr mist details: %s", body)
117 }
118 mr.MergeRequest.Action = "commented"
119 mr.Comment = "mooie opmerking"
120 body, err = RenderBody("", mr, nil)
121 if err != nil || !strings.Contains(string(body), "mooie opmerking") {
122 t.Fatalf("commented %s %v", body, err)
123 }
124
125 rel := Event{
126 Type: EventRelease, Project: "tim/app", ReleaseTag: "v1",
127 Release: &ReleaseInfo{Tag: "v1", Name: "Een", Commit: "abc", Assets: []AssetInfo{{Name: "bluegit", URL: "https://git.example/a", Size: 4}}},
128 }
129 body, err = RenderBody("", rel, nil)
130 if err != nil {
131 t.Fatal(err)
132 }
133 if err := json.Unmarshal(body, &doc); err != nil {
134 t.Fatal(err)
135 }
136 if doc["object_kind"] != "release" {
137 t.Fatal(string(body))
138 }
139 release := doc["release"].(map[string]any)
140 assets := release["assets"].([]any)
141 if release["tag"] != "v1" || release["commit"] != "abc" || assets[0].(map[string]any)["url"] != "https://git.example/a" {
142 t.Fatalf("release %s", body)
143 }
144
145 rendered, err := Expand("{{event.payload}}", pipe, nil)
146 if err != nil || !strings.Contains(rendered, `"log":"boom"`) {
147 t.Fatalf("payload-placeholder %s %v", rendered, err)
148 }
149}
150
151func TestOpenAPIMatchesExample(t *testing.T) {
152 var spec map[string]any
153 if err := json.Unmarshal(OpenAPI(), &spec); err != nil {
154 t.Fatal(err)
155 }
156 if spec["openapi"] != "3.1.0" {
157 t.Fatalf("versie %v", spec["openapi"])
158 }
159 raw := string(OpenAPI())
160 for _, want := range []string{
161 "PipelineEvent", "PushEvent", "MergeRequestEvent", "ReleaseEvent",
162 "commit_message", "allow_failure", "log_truncated", "log_url",
163 "/repos/{owner}/{repo}/jobs/{id}/log",
164 "diff_url", "reviewers", "diff_stats", "/commits/{sha}/diff", "/merge-requests/{id}/diff",
165 "source_branch", "target_branch", "before", "after", "assets",
166 } {
167 if !strings.Contains(raw, want) {
168 t.Errorf("openapi mist %s", want)
169 }
170 }
171 example := Example()
172 for _, want := range []string{"log_truncated", "commit_message", "source_branch", "refs/heads/master", "assets", "commented", "diff_url", "reviewers", "additions"} {
173 if !strings.Contains(example, want) && want != "commented" {
174 t.Errorf("voorbeeld mist %s", want)
175 }
176 }
177 if !strings.Contains(example, `"action": "opened"`) {
178 t.Fatalf("voorbeeld:\n%s", example)
179 }
180}
internal/webhook/preset_test.go +2 −2
@@ -252,7 +252,7 @@ func TestPresetPayloads(t *testing.T) {
252 252 if err != nil {
253 253 t.Fatal(err)
254 254 }
255 var grok map[string]string
255 var grok map[string]any
256 256 if err := json.Unmarshal(body, &grok); err != nil || grok["project"] != ev.Project || strings.Contains(string(body), "secret-value") {
257 257 t.Fatalf("grok body %s %v", body, err)
258 258 }
@@ -272,7 +272,7 @@ func TestPresetPayloads(t *testing.T) {
272 272 if err != nil {
273 273 t.Fatal(err)
274 274 }
275 var generic map[string]string
275 var generic map[string]any
276 276 if err := json.Unmarshal(body, &generic); err != nil || generic["summary"] != ev.Summary || generic["type"] != EventPush {
277 277 t.Fatalf("generic %s %v", body, err)
278 278 }
@@ -252,7 +252,7 @@ func TestPresetPayloads(t *testing.T) {
252 if err != nil {
252 if err != nil {
253 t.Fatal(err)
253 t.Fatal(err)
254 }
254 }
255 var grok map[string]string
255 var grok map[string]any
256 if err := json.Unmarshal(body, &grok); err != nil || grok["project"] != ev.Project || strings.Contains(string(body), "secret-value") {
256 if err := json.Unmarshal(body, &grok); err != nil || grok["project"] != ev.Project || strings.Contains(string(body), "secret-value") {
257 t.Fatalf("grok body %s %v", body, err)
257 t.Fatalf("grok body %s %v", body, err)
258 }
258 }
@@ -272,7 +272,7 @@ func TestPresetPayloads(t *testing.T) {
272 if err != nil {
272 if err != nil {
273 t.Fatal(err)
273 t.Fatal(err)
274 }
274 }
275 var generic map[string]string
275 var generic map[string]any
276 if err := json.Unmarshal(body, &generic); err != nil || generic["summary"] != ev.Summary || generic["type"] != EventPush {
276 if err := json.Unmarshal(body, &generic); err != nil || generic["summary"] != ev.Summary || generic["type"] != EventPush {
277 t.Fatalf("generic %s %v", body, err)
277 t.Fatalf("generic %s %v", body, err)
278 }
278 }
internal/webhook/webhook.go +20 −13
@@ -41,6 +41,9 @@ const (
41 41 )
42 42
43 43 // Event is de gegevensset die een webhook te zien krijgt.
44 // De platte velden blijven beschikbaar als {{event.veld}}.
45 // Pipeline, Jobs, Ref/Before/After/Commits, MergeRequest en Release
46 // vullen de JSON-body als het sjabloon leeg is.
44 47 type Event struct {
45 48 Type string
46 49 Project string
@@ -52,6 +55,16 @@ type Event struct {
52 55 PipelineID string
53 56 ReleaseTag string
54 57 Actor string
58
59 Pipeline *PipelineInfo
60 Jobs []JobInfo
61 Ref string
62 Before string
63 After string
64 Commits []CommitInfo
65 MergeRequest *MRInfo
66 Comment string
67 Release *ReleaseInfo
55 68 }
56 69
57 70 // Hook is de opgeslagen configuratie, zonder geheimen al ingevuld.
@@ -182,6 +195,12 @@ func eventField(ev Event, field string) (string, bool) {
182 195 return ev.ReleaseTag, true
183 196 case "actor":
184 197 return ev.Actor, true
198 case "payload":
199 b, err := json.Marshal(ev.Document())
200 if err != nil {
201 return "", false
202 }
203 return string(b), true
185 204 default:
186 205 return "", false
187 206 }
@@ -206,19 +225,7 @@ func PresetDefaults(preset string) (headers map[string]string, body string) {
206 225 // RenderBody maakt de HTTP-body. Een lege sjabloon wordt de gebeurtenis als JSON.
207 226 func RenderBody(bodyTemplate string, ev Event, secrets map[string]string) ([]byte, error) {
208 227 if strings.TrimSpace(bodyTemplate) == "" {
209 payload := map[string]string{
210 "type": ev.Type,
211 "project": ev.Project,
212 "group": ev.Group,
213 "branch": ev.Branch,
214 "commit": ev.Commit,
215 "summary": ev.Summary,
216 "url": ev.URL,
217 "pipeline_id": ev.PipelineID,
218 "release_tag": ev.ReleaseTag,
219 "actor": ev.Actor,
220 }
221 return json.Marshal(payload)
228 return json.Marshal(ev.Document())
222 229 }
223 230 s, err := Expand(bodyTemplate, ev, secrets)
224 231 if err != nil {
@@ -41,6 +41,9 @@ const (
41)
41)
42
42
43// Event is de gegevensset die een webhook te zien krijgt.
43// Event is de gegevensset die een webhook te zien krijgt.
44// De platte velden blijven beschikbaar als {{event.veld}}.
45// Pipeline, Jobs, Ref/Before/After/Commits, MergeRequest en Release
46// vullen de JSON-body als het sjabloon leeg is.
44type Event struct {
47type Event struct {
45 Type string
48 Type string
46 Project string
49 Project string
@@ -52,6 +55,16 @@ type Event struct {
52 PipelineID string
55 PipelineID string
53 ReleaseTag string
56 ReleaseTag string
54 Actor string
57 Actor string
58
59 Pipeline *PipelineInfo
60 Jobs []JobInfo
61 Ref string
62 Before string
63 After string
64 Commits []CommitInfo
65 MergeRequest *MRInfo
66 Comment string
67 Release *ReleaseInfo
55}
68}
56
69
57// Hook is de opgeslagen configuratie, zonder geheimen al ingevuld.
70// Hook is de opgeslagen configuratie, zonder geheimen al ingevuld.
@@ -182,6 +195,12 @@ func eventField(ev Event, field string) (string, bool) {
182 return ev.ReleaseTag, true
195 return ev.ReleaseTag, true
183 case "actor":
196 case "actor":
184 return ev.Actor, true
197 return ev.Actor, true
198 case "payload":
199 b, err := json.Marshal(ev.Document())
200 if err != nil {
201 return "", false
202 }
203 return string(b), true
185 default:
204 default:
186 return "", false
205 return "", false
187 }
206 }
@@ -206,19 +225,7 @@ func PresetDefaults(preset string) (headers map[string]string, body string) {
206// RenderBody maakt de HTTP-body. Een lege sjabloon wordt de gebeurtenis als JSON.
225// RenderBody maakt de HTTP-body. Een lege sjabloon wordt de gebeurtenis als JSON.
207func RenderBody(bodyTemplate string, ev Event, secrets map[string]string) ([]byte, error) {
226func RenderBody(bodyTemplate string, ev Event, secrets map[string]string) ([]byte, error) {
208 if strings.TrimSpace(bodyTemplate) == "" {
227 if strings.TrimSpace(bodyTemplate) == "" {
209 payload := map[string]string{
228 return json.Marshal(ev.Document())
210 "type": ev.Type,
211 "project": ev.Project,
212 "group": ev.Group,
213 "branch": ev.Branch,
214 "commit": ev.Commit,
215 "summary": ev.Summary,
216 "url": ev.URL,
217 "pipeline_id": ev.PipelineID,
218 "release_tag": ev.ReleaseTag,
219 "actor": ev.Actor,
220 }
221 return json.Marshal(payload)
222 }
229 }
223 s, err := Expand(bodyTemplate, ev, secrets)
230 s, err := Expand(bodyTemplate, ev, secrets)
224 if err != nil {
231 if err != nil {
internal/webhook/webhook_test.go +2 −2
@@ -92,11 +92,11 @@ func TestExpandAndPresets(t *testing.T) {
92 92 if err != nil {
93 93 t.Fatal(err)
94 94 }
95 var payload map[string]string
95 var payload map[string]any
96 96 if err := json.Unmarshal(body, &payload); err != nil {
97 97 t.Fatal(err)
98 98 }
99 if payload["project"] != "tim/bluegit" || strings.Contains(string(body), "geheim-token") {
99 if payload["project"] != "tim/bluegit" || payload["object_kind"] != "push" || strings.Contains(string(body), "geheim-token") {
100 100 t.Fatalf("body lekt of mist project: %s", body)
101 101 }
102 102
@@ -92,11 +92,11 @@ func TestExpandAndPresets(t *testing.T) {
92 if err != nil {
92 if err != nil {
93 t.Fatal(err)
93 t.Fatal(err)
94 }
94 }
95 var payload map[string]string
95 var payload map[string]any
96 if err := json.Unmarshal(body, &payload); err != nil {
96 if err := json.Unmarshal(body, &payload); err != nil {
97 t.Fatal(err)
97 t.Fatal(err)
98 }
98 }
99 if payload["project"] != "tim/bluegit" || strings.Contains(string(body), "geheim-token") {
99 if payload["project"] != "tim/bluegit" || payload["object_kind"] != "push" || strings.Contains(string(body), "geheim-token") {
100 t.Fatalf("body lekt of mist project: %s", body)
100 t.Fatalf("body lekt of mist project: %s", body)
101 }
101 }
102
102