API: branches met slash en pipeline-retry in OpenAPI
DELETE en PUT van branches werken ook via query of body
(?name=feature/x), zodat een ingress die %2F weigert (Apache zonder
AllowEncodedSlashes NoDecode) geen 404 meer geeft. Hetzelfde voor
protected branches/tags (?pattern=) en bestanden (?path=).
De mux blijft {branch...} en {pattern...} met PathValue/EscapedPath
en decodeBranch gebruiken, zodat letterlijke slashes en %2F in het
pad werken als de proxy ze doorlaat.
INGRESS.md documenteert AllowEncodedSlashes NoDecode en ProxyPass
nocanon. De Caddy-ingress van git.timfalken.com geeft %2F al door;
daar is niets gewijzigd.
POST .../pipelines/{id}/retry heeft in OpenAPI een request body
PipelineRetry met enum all|failed en default failed. Een weggelaten
of lege mode betekent failed, net als in de implementatie.
@@ -112,7 +112,7 @@ git clone http://tim:bg_…@127.0.0.1:8080/tim/demo.git
112
112
113
113
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) beschrijft het proces, de schijf en waarom het één binary is.
114
114
- [docs/AUTH.md](docs/AUTH.md) beschrijft de OAuth-koppeling en Microsoft Entra ID.
115
- [docs/INGRESS.md](docs/INGRESS.md) beschrijft TLS en de publieke SSH-poort.
115
- [docs/INGRESS.md](docs/INGRESS.md) beschrijft TLS, de publieke SSH-poort, en hoe Apache encoded slashes (`%2F`) doorlaat.
116
116
- [docs/CI.md](docs/CI.md) beschrijft `blue-ci-cd.yml` en Steve.
117
117
- [docs/AUR.md](docs/AUR.md) beschrijft het pakket en de self-update.
118
118
- [docs/BEHEER.md](docs/BEHEER.md) beschrijft de installatie op git.timfalken.com.
@@ -112,7 +112,7 @@ git clone http://tim:bg_…@127.0.0.1:8080/tim/demo.git112
112
113
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) beschrijft het proces, de schijf en waarom het één binary is.113
- [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) beschrijft het proces, de schijf en waarom het één binary is.114
- [docs/AUTH.md](docs/AUTH.md) beschrijft de OAuth-koppeling en Microsoft Entra ID.114
- [docs/AUTH.md](docs/AUTH.md) beschrijft de OAuth-koppeling en Microsoft Entra ID.115
- [docs/INGRESS.md](docs/INGRESS.md) beschrijft TLS en de publieke SSH-poort.115
- [docs/INGRESS.md](docs/INGRESS.md) beschrijft TLS, de publieke SSH-poort, en hoe Apache encoded slashes (`%2F`) doorlaat.116
- [docs/CI.md](docs/CI.md) beschrijft `blue-ci-cd.yml` en Steve.116
- [docs/CI.md](docs/CI.md) beschrijft `blue-ci-cd.yml` en Steve.117
- [docs/AUR.md](docs/AUR.md) beschrijft het pakket en de self-update.117
- [docs/AUR.md](docs/AUR.md) beschrijft het pakket en de self-update.118
- [docs/BEHEER.md](docs/BEHEER.md) beschrijft de installatie op git.timfalken.com.118
- [docs/BEHEER.md](docs/BEHEER.md) beschrijft de installatie op git.timfalken.com.@@ -62,3 +62,34 @@ stream {
62
62
```
63
63
64
64
De clone-URL op de website is dan `git@git.timfalken.com:eigenaar/naam.git` (de korte vorm, zoals GitHub). Bij een andere publieke poort wordt het `ssh://git@host:poort/eigenaar/naam.git`. Op de mini-PC blijft git-SSH op poort 2222 luisteren, naast de SSH van Arch.
65
66
## Encoded slashes (`%2F`)
67
68
Branchnamen, bestandspaden en patterns van beschermde branches bevatten vaak een `/`. Clients sturen die slash in het URL-pad soms als `%2F`, bijvoorbeeld `DELETE /api/v1/projects/{owner}/{repo}/repository/branches/feature%2Fx`.
69
70
Caddy (het voorbeeld hierboven, en de ingress van git.timfalken.com) geeft `%2F` ongewijzigd door. Dat is op git.timfalken.com gecontroleerd: een verzoek met `%2F` in het pad komt bij BlueGit uit (een authenticatiefout, geen 404 van de ingress). Daar is geen extra instelling nodig.
71
72
Apache weigert `%2F` standaard met een 404, nog voordat de proxy het verzoek doorstuurt. Zet in de `VirtualHost` (of de `Directory`/`Location` van de site):
73
74
```apache
75
AllowEncodedSlashes NoDecode
76
```
77
78
En als je `ProxyPass` gebruikt, ook `nocanon`. Zonder die vlag canoniseert Apache het pad alsnog en blijft `%2F` stuk:
79
80
```apache
81
ProxyPass / http://10.0.0.5:8080/ nocanon
82
ProxyPassReverse / http://10.0.0.5:8080/
83
```
84
85
Vervang `10.0.0.5:8080` door het adres van BlueGit, hetzelfde als in het Caddy-voorbeeld.
86
87
BlueGit zelf accepteert zowel een letterlijke slash (`feature/x`) als `%2F` in een wildcard-pad. Voor een ingress die `%2F` niet doorlaat is er een variant zonder slash in het pad:
88
89
- `DELETE /api/v1/projects/{owner}/{repo}/repository/branches?name=feature/x`
90
- `PUT /api/v1/projects/{owner}/{repo}/repository/branches?name=feature/x` (nieuwe naam in de JSON-body)
91
- `DELETE /api/v1/projects/{owner}/{repo}/protected_branches?pattern=feature/*`
92
- `DELETE /api/v1/projects/{owner}/{repo}/protected_tags?pattern=releases/*`
93
- `GET /api/v1/projects/{owner}/{repo}/repository/files?path=docs/INGRESS.md&ref=master`
94
95
De naam mag bij verwijderen ook in de JSON-body. Tagnamen mogen geen `/` bevatten; hun pad hoeft dus niet om `%2F` heen. Vergelijken in de UI gebruikt al queryparameters (`/-/compare?from=&to=`).
@@ -62,3 +62,34 @@ stream {62
```62
```63
63
64
De clone-URL op de website is dan `git@git.timfalken.com:eigenaar/naam.git` (de korte vorm, zoals GitHub). Bij een andere publieke poort wordt het `ssh://git@host:poort/eigenaar/naam.git`. Op de mini-PC blijft git-SSH op poort 2222 luisteren, naast de SSH van Arch.64
De clone-URL op de website is dan `git@git.timfalken.com:eigenaar/naam.git` (de korte vorm, zoals GitHub). Bij een andere publieke poort wordt het `ssh://git@host:poort/eigenaar/naam.git`. Op de mini-PC blijft git-SSH op poort 2222 luisteren, naast de SSH van Arch.65
66
## Encoded slashes (`%2F`)67
68
Branchnamen, bestandspaden en patterns van beschermde branches bevatten vaak een `/`. Clients sturen die slash in het URL-pad soms als `%2F`, bijvoorbeeld `DELETE /api/v1/projects/{owner}/{repo}/repository/branches/feature%2Fx`.69
70
Caddy (het voorbeeld hierboven, en de ingress van git.timfalken.com) geeft `%2F` ongewijzigd door. Dat is op git.timfalken.com gecontroleerd: een verzoek met `%2F` in het pad komt bij BlueGit uit (een authenticatiefout, geen 404 van de ingress). Daar is geen extra instelling nodig.71
72
Apache weigert `%2F` standaard met een 404, nog voordat de proxy het verzoek doorstuurt. Zet in de `VirtualHost` (of de `Directory`/`Location` van de site):73
74
```apache75
AllowEncodedSlashes NoDecode76
```77
78
En als je `ProxyPass` gebruikt, ook `nocanon`. Zonder die vlag canoniseert Apache het pad alsnog en blijft `%2F` stuk:79
80
```apache81
ProxyPass / http://10.0.0.5:8080/ nocanon82
ProxyPassReverse / http://10.0.0.5:8080/83
```84
85
Vervang `10.0.0.5:8080` door het adres van BlueGit, hetzelfde als in het Caddy-voorbeeld.86
87
BlueGit zelf accepteert zowel een letterlijke slash (`feature/x`) als `%2F` in een wildcard-pad. Voor een ingress die `%2F` niet doorlaat is er een variant zonder slash in het pad:88
89
- `DELETE /api/v1/projects/{owner}/{repo}/repository/branches?name=feature/x`90
- `PUT /api/v1/projects/{owner}/{repo}/repository/branches?name=feature/x` (nieuwe naam in de JSON-body)91
- `DELETE /api/v1/projects/{owner}/{repo}/protected_branches?pattern=feature/*`92
- `DELETE /api/v1/projects/{owner}/{repo}/protected_tags?pattern=releases/*`93
- `GET /api/v1/projects/{owner}/{repo}/repository/files?path=docs/INGRESS.md&ref=master`94
95
De naam mag bij verwijderen ook in de JSON-body. Tagnamen mogen geen `/` bevatten; hun pad hoeft dus niet om `%2F` heen. Vergelijken in de UI gebruikt al queryparameters (`/-/compare?from=&to=`).@@ -785,11 +785,24 @@ func (s *Server) apiUnprotect(w http.ResponseWriter, r *http.Request, tag bool)
785
785
if !ok {
786
786
return
787
787
}
788
name := "pattern"
789
if tag {
790
name = "pattern"
788
pattern := pathWildcard(r, "pattern")
789
if pattern == "" {
790
pattern = decodeBranch(r.URL.Query().Get("pattern"))
791
}
792
if pattern == "" {
793
var body struct {
794
Pattern string `json:"pattern"`
795
}
796
if err := readJSON(r, &body); err != nil {
797
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
798
return
799
}
800
pattern = decodeBranch(body.Pattern)
801
}
802
if pattern == "" {
803
s.writeAPIErr(w, r, fail(400, i18n.E("err.notFound")))
804
return
791
805
}
792
pattern := r.PathValue(name)
793
806
if !s.apiOK(w, r, s.opUnprotect(r.Context(), apiUser(r), repo, pattern, tag)) {
794
807
return
795
808
}
@@ -785,11 +785,24 @@ func (s *Server) apiUnprotect(w http.ResponseWriter, r *http.Request, tag bool)785
if !ok {785
if !ok {786
return786
return787
}787
}788
name := "pattern"788
pattern := pathWildcard(r, "pattern")789
if tag {789
if pattern == "" {790
name = "pattern"790
pattern = decodeBranch(r.URL.Query().Get("pattern"))791
}792
if pattern == "" {793
var body struct {794
Pattern string `json:"pattern"`795
}796
if err := readJSON(r, &body); err != nil {797
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))798
return799
}800
pattern = decodeBranch(body.Pattern)801
}802
if pattern == "" {803
s.writeAPIErr(w, r, fail(400, i18n.E("err.notFound")))804
return791
}805
}792
pattern := r.PathValue(name)793
if !s.apiOK(w, r, s.opUnprotect(r.Context(), apiUser(r), repo, pattern, tag)) {806
if !s.apiOK(w, r, s.opUnprotect(r.Context(), apiUser(r), repo, pattern, tag)) {794
return807
return795
}808
}@@ -470,6 +470,7 @@ func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) {
470
470
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
471
471
return
472
472
}
473
body.Mode = retryPipelineMode(body.Mode)
473
474
id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)
474
475
if !s.apiOK(w, r, err) {
475
476
return
@@ -470,6 +470,7 @@ func (s *Server) apiRetryPipeline(w http.ResponseWriter, r *http.Request) {470
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))470
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))471
return471
return472
}472
}473
body.Mode = retryPipelineMode(body.Mode)473
id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)474
id, err := s.opRetryPipeline(r.Context(), apiUser(r), repo, pipeID, body.Mode)474
if !s.apiOK(w, r, err) {475
if !s.apiOK(w, r, err) {475
return476
return@@ -11,6 +11,10 @@ import (
11
11
)
12
12
13
13
func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {
14
if r.Method == http.MethodDelete || r.Method == http.MethodPut {
15
s.apiBranchNamed(w, r, "", false)
16
return
17
}
14
18
repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)
15
19
if !ok {
16
20
return
@@ -47,20 +51,39 @@ func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {
47
51
}
48
52
49
53
func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {
54
s.apiBranchNamed(w, r, pathWildcard(r, "branch"), true)
55
}
56
57
// apiBranchNamed verwijdert of hernoemt een branch. nameFromPath is de tak uit
58
// het URL-pad; anders komt de naam uit ?name= of uit de JSON-body (name).
59
// Die laatste vorm vermijdt een slash in het pad, voor ingresses die %2F weigeren.
60
func (s *Server) apiBranchNamed(w http.ResponseWriter, r *http.Request, name string, nameFromPath bool) {
50
61
repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)
51
62
if !ok {
52
63
return
53
64
}
54
name := r.PathValue("branch")
55
65
if r.Method == http.MethodDelete {
56
66
var body struct {
67
Name string `json:"name"`
57
68
Confirm string `json:"confirm"`
58
69
}
59
70
if err := readJSON(r, &body); err != nil {
60
71
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
61
72
return
62
73
}
63
if !s.apiOK(w, r, s.opDeleteBranch(r.Context(), apiUser(r), repo, name, body.Confirm)) {
74
if !nameFromPath {
75
if name == "" {
76
name = decodeBranch(r.URL.Query().Get("name"))
77
}
78
if name == "" {
79
name = decodeBranch(body.Name)
80
}
81
}
82
confirm := decodeBranch(body.Confirm)
83
if !nameFromPath && confirm == "" {
84
confirm = name
85
}
86
if !s.apiOK(w, r, s.opDeleteBranch(r.Context(), apiUser(r), repo, name, confirm)) {
64
87
return
65
88
}
66
89
writeJSON(w, http.StatusNoContent, nil)
@@ -74,7 +97,14 @@ func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {
74
97
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))
75
98
return
76
99
}
77
if !s.apiOK(w, r, s.opRenameBranch(r.Context(), apiUser(r), repo, name, body.Name, body.Confirm)) {
100
if !nameFromPath && name == "" {
101
name = decodeBranch(r.URL.Query().Get("name"))
102
}
103
confirm := decodeBranch(body.Confirm)
104
if !nameFromPath && confirm == "" {
105
confirm = name
106
}
107
if !s.apiOK(w, r, s.opRenameBranch(r.Context(), apiUser(r), repo, name, body.Name, confirm)) {
78
108
return
79
109
}
80
110
writeJSON(w, http.StatusOK, map[string]any{"name": body.Name})
@@ -177,7 +207,10 @@ func (s *Server) apiFile(w http.ResponseWriter, r *http.Request) {
177
207
if !ok {
178
208
return
179
209
}
180
path, pathOK := repoPath(r.PathValue("path"))
210
path, pathOK := repoPath(pathWildcard(r, "path"))
211
if path == "" {
212
path, pathOK = repoPath(r.URL.Query().Get("path"))
213
}
181
214
if !pathOK || path == "" {
182
215
s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))
183
216
return
@@ -11,6 +11,10 @@ import (11
)11
)12
12
13
func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {13
func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {14
if r.Method == http.MethodDelete || r.Method == http.MethodPut {15
s.apiBranchNamed(w, r, "", false)16
return17
}14
repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)18
repo, _, ok := s.apiRepo(w, r, access.RoleReadonly)15
if !ok {19
if !ok {16
return20
return@@ -47,20 +51,39 @@ func (s *Server) apiBranches(w http.ResponseWriter, r *http.Request) {47
}51
}48
52
49
func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {53
func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {54
s.apiBranchNamed(w, r, pathWildcard(r, "branch"), true)55
}56
57
// apiBranchNamed verwijdert of hernoemt een branch. nameFromPath is de tak uit58
// het URL-pad; anders komt de naam uit ?name= of uit de JSON-body (name).59
// Die laatste vorm vermijdt een slash in het pad, voor ingresses die %2F weigeren.60
func (s *Server) apiBranchNamed(w http.ResponseWriter, r *http.Request, name string, nameFromPath bool) {50
repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)61
repo, _, ok := s.apiRepo(w, r, access.RoleDeveloper)51
if !ok {62
if !ok {52
return63
return53
}64
}54
name := r.PathValue("branch")55
if r.Method == http.MethodDelete {65
if r.Method == http.MethodDelete {56
var body struct {66
var body struct {67
Name string `json:"name"`57
Confirm string `json:"confirm"`68
Confirm string `json:"confirm"`58
}69
}59
if err := readJSON(r, &body); err != nil {70
if err := readJSON(r, &body); err != nil {60
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))71
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))61
return72
return62
}73
}63
if !s.apiOK(w, r, s.opDeleteBranch(r.Context(), apiUser(r), repo, name, body.Confirm)) {74
if !nameFromPath {75
if name == "" {76
name = decodeBranch(r.URL.Query().Get("name"))77
}78
if name == "" {79
name = decodeBranch(body.Name)80
}81
}82
confirm := decodeBranch(body.Confirm)83
if !nameFromPath && confirm == "" {84
confirm = name85
}86
if !s.apiOK(w, r, s.opDeleteBranch(r.Context(), apiUser(r), repo, name, confirm)) {64
return87
return65
}88
}66
writeJSON(w, http.StatusNoContent, nil)89
writeJSON(w, http.StatusNoContent, nil)@@ -74,7 +97,14 @@ func (s *Server) apiBranch(w http.ResponseWriter, r *http.Request) {74
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))97
s.writeAPIErr(w, r, fail(400, i18n.E("err.json")))75
return98
return76
}99
}77
if !s.apiOK(w, r, s.opRenameBranch(r.Context(), apiUser(r), repo, name, body.Name, body.Confirm)) {100
if !nameFromPath && name == "" {101
name = decodeBranch(r.URL.Query().Get("name"))102
}103
confirm := decodeBranch(body.Confirm)104
if !nameFromPath && confirm == "" {105
confirm = name106
}107
if !s.apiOK(w, r, s.opRenameBranch(r.Context(), apiUser(r), repo, name, body.Name, confirm)) {78
return108
return79
}109
}80
writeJSON(w, http.StatusOK, map[string]any{"name": body.Name})110
writeJSON(w, http.StatusOK, map[string]any{"name": body.Name})@@ -177,7 +207,10 @@ func (s *Server) apiFile(w http.ResponseWriter, r *http.Request) {177
if !ok {207
if !ok {178
return208
return179
}209
}180
path, pathOK := repoPath(r.PathValue("path"))210
path, pathOK := repoPath(pathWildcard(r, "path"))211
if path == "" {212
path, pathOK = repoPath(r.URL.Query().Get("path"))213
}181
if !pathOK || path == "" {214
if !pathOK || path == "" {182
s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))215
s.writeAPIErr(w, r, fail(400, i18n.E("err.sugFile")))183
return216
return@@ -20,10 +20,26 @@ func decorateAPI(paths map[string]map[string]any, schemas map[string]any) {
20
20
}
21
21
}
22
22
op["requestBody"] = map[string]any{
23
"required": true,
23
"required": !b.optional,
24
24
"content": content,
25
25
}
26
26
}
27
if len(b.query) > 0 {
28
params, _ := op["parameters"].([]any)
29
for _, q := range b.query {
30
params = append(params, map[string]any{
31
"name": q.name,
32
"in": "query",
33
"required": q.required,
34
"description": q.desc,
35
"schema": map[string]any{"type": "string"},
36
})
37
}
38
op["parameters"] = params
39
}
40
if b.resp == "" && !b.empty {
41
continue
42
}
27
43
responses, _ := op["responses"].(map[string]any)
28
44
if responses == nil {
29
45
responses = map[string]any{}
@@ -83,6 +99,17 @@ func jsonSchema(schema map[string]any) map[string]any {
83
99
type apiBind struct {
84
100
path, method, body, resp, code string
85
101
array, empty, multipart bool
102
optional bool
103
query []apiQuery
104
}
105
106
type apiQuery struct {
107
name, desc string
108
required bool
109
}
110
111
func q(name, desc string, required bool) apiQuery {
112
return apiQuery{name: name, desc: desc, required: required}
86
113
}
87
114
88
115
func apiBinds() []apiBind {
@@ -121,7 +148,7 @@ func apiBinds() []apiBind {
121
148
{path: pipes, method: "POST", code: "201", body: "PipelineCreate", resp: "Pipeline"},
122
149
{path: pipe, method: "GET", code: "200", resp: "Pipeline"},
123
150
{path: pipe + "/cancel", method: "POST", code: "200", resp: "Pipeline"},
124
{path: pipe + "/retry", method: "POST", code: "200", body: "PipelineRetry", resp: "Pipeline"},
151
{path: pipe + "/retry", method: "POST", code: "200", body: "PipelineRetry", resp: "Pipeline", optional: true},
125
152
{path: pipe + "/jobs", method: "GET", code: "200", resp: "Job", array: true},
126
153
{path: job, method: "GET", code: "200", resp: "Job"},
127
154
{path: job + "/play", method: "POST", code: "200", resp: "Job"},
@@ -130,6 +157,12 @@ func apiBinds() []apiBind {
130
157
131
158
{path: branches, method: "GET", code: "200", resp: "Branch", array: true},
132
159
{path: branches, method: "POST", code: "201", body: "BranchCreate", resp: "Branch"},
160
{path: branches, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch", optional: true, query: []apiQuery{
161
q("name", "Current branch name. Preferred when the name contains a slash and the ingress rejects %2F.", true),
162
}},
163
{path: branches, method: "DELETE", code: "204", body: "BranchDelete", empty: true, optional: true, query: []apiQuery{
164
q("name", "Branch to delete. May also be sent in the JSON body. Use this when the name contains a slash and the ingress rejects %2F.", false),
165
}},
133
166
{path: branch, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch"},
134
167
{path: branch, method: "DELETE", code: "204", body: "BranchDelete", empty: true},
135
168
@@ -159,7 +192,17 @@ func apiBinds() []apiBind {
159
192
{path: "/projects/{owner}/{repo}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
160
193
{path: "/groups/{path}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},
161
194
{path: "/projects/{owner}/{repo}/protected_branches", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
195
{path: "/projects/{owner}/{repo}/protected_branches", method: "DELETE", code: "204", body: "ProtectedPattern", empty: true, optional: true, query: []apiQuery{
196
q("pattern", "Pattern to unprotect. May also be sent in the JSON body. Use this when the pattern contains a slash and the ingress rejects %2F.", false),
197
}},
162
198
{path: "/projects/{owner}/{repo}/protected_tags", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},
199
{path: "/projects/{owner}/{repo}/protected_tags", method: "DELETE", code: "204", body: "ProtectedPattern", empty: true, optional: true, query: []apiQuery{
200
q("pattern", "Pattern to unprotect. May also be sent in the JSON body. Use this when the pattern contains a slash and the ingress rejects %2F.", false),
201
}},
202
{path: "/projects/{owner}/{repo}/repository/files", method: "GET", query: []apiQuery{
203
q("path", "File path, including slashes. Preferred when the ingress rejects %2F in the URL path.", true),
204
q("ref", "Branch, tag or commit. Default: the project's default branch.", false),
205
}},
163
206
{path: "/projects/{owner}/{repo}/ci/lint", method: "POST", code: "200", body: "CILint", resp: "CILintResult"},
164
207
}
165
208
}
@@ -275,11 +318,12 @@ func apiSchemas() map[string]any {
275
318
"PipelineCreate": obj("Start a pipeline.", map[string]any{
276
319
"ref": str("Branch, tag or full ref to run."),
277
320
}),
278
"PipelineRetry": obj("Retry a pipeline. all starts a new pipeline on the same commit, ref, source and merge request. failed requeues failed jobs and the skipped or never-started jobs that depend on them. The response is 201 for all and 200 for failed.", map[string]any{
321
"PipelineRetry": obj("Retry a pipeline. all starts a new pipeline on the same commit, ref, source and merge request. failed requeues failed jobs and the skipped or never-started jobs that depend on them. The response is 201 for all and 200 for failed. An omitted or empty body uses failed.", map[string]any{
279
322
"mode": map[string]any{
280
323
"type": "string",
281
"description": "all or failed.",
324
"description": "all or failed. Omitted or empty means failed.",
282
325
"enum": []any{"all", "failed"},
326
"default": "failed",
283
327
},
284
328
}),
285
329
"Job": obj("CI job.", map[string]any{
@@ -307,12 +351,13 @@ func apiSchemas() map[string]any {
307
351
"name": str("New branch name."),
308
352
"from": str("Existing branch or commit to start from."),
309
353
}),
310
"BranchUpdate": obj("Rename a branch.", map[string]any{
354
"BranchUpdate": obj("Rename a branch. On PUT /repository/branches the current name is the name query. confirm may then be omitted and defaults to that name.", map[string]any{
311
355
"name": str("New branch name."),
312
"confirm": str("Current branch name, repeated as confirmation."),
356
"confirm": str("Current branch name, repeated as confirmation. Required when the current name is in the path."),
313
357
}),
314
"BranchDelete": obj("Delete a branch.", map[string]any{
315
"confirm": str("Branch name, repeated as confirmation."),
358
"BranchDelete": obj("Delete a branch. On DELETE /repository/branches the name may be the name query or this name field. confirm may then be omitted and defaults to the name.", map[string]any{
359
"name": str("Branch name, when not in the path or the name query."),
360
"confirm": str("Branch name, repeated as confirmation. Required when the name is in the path."),
316
361
}),
317
362
"Webhook": obj("Webhook.", map[string]any{
318
363
"id": integer("Webhook id."),
@@ -20,10 +20,26 @@ func decorateAPI(paths map[string]map[string]any, schemas map[string]any) {20
}20
}21
}21
}22
op["requestBody"] = map[string]any{22
op["requestBody"] = map[string]any{23
"required": true,23
"required": !b.optional,24
"content": content,24
"content": content,25
}25
}26
}26
}27
if len(b.query) > 0 {28
params, _ := op["parameters"].([]any)29
for _, q := range b.query {30
params = append(params, map[string]any{31
"name": q.name,32
"in": "query",33
"required": q.required,34
"description": q.desc,35
"schema": map[string]any{"type": "string"},36
})37
}38
op["parameters"] = params39
}40
if b.resp == "" && !b.empty {41
continue42
}27
responses, _ := op["responses"].(map[string]any)43
responses, _ := op["responses"].(map[string]any)28
if responses == nil {44
if responses == nil {29
responses = map[string]any{}45
responses = map[string]any{}@@ -83,6 +99,17 @@ func jsonSchema(schema map[string]any) map[string]any {83
type apiBind struct {99
type apiBind struct {84
path, method, body, resp, code string100
path, method, body, resp, code string85
array, empty, multipart bool101
array, empty, multipart bool102
optional bool103
query []apiQuery104
}105
106
type apiQuery struct {107
name, desc string108
required bool109
}110
111
func q(name, desc string, required bool) apiQuery {112
return apiQuery{name: name, desc: desc, required: required}86
}113
}87
114
88
func apiBinds() []apiBind {115
func apiBinds() []apiBind {@@ -121,7 +148,7 @@ func apiBinds() []apiBind {121
{path: pipes, method: "POST", code: "201", body: "PipelineCreate", resp: "Pipeline"},148
{path: pipes, method: "POST", code: "201", body: "PipelineCreate", resp: "Pipeline"},122
{path: pipe, method: "GET", code: "200", resp: "Pipeline"},149
{path: pipe, method: "GET", code: "200", resp: "Pipeline"},123
{path: pipe + "/cancel", method: "POST", code: "200", resp: "Pipeline"},150
{path: pipe + "/cancel", method: "POST", code: "200", resp: "Pipeline"},124
{path: pipe + "/retry", method: "POST", code: "200", body: "PipelineRetry", resp: "Pipeline"},151
{path: pipe + "/retry", method: "POST", code: "200", body: "PipelineRetry", resp: "Pipeline", optional: true},125
{path: pipe + "/jobs", method: "GET", code: "200", resp: "Job", array: true},152
{path: pipe + "/jobs", method: "GET", code: "200", resp: "Job", array: true},126
{path: job, method: "GET", code: "200", resp: "Job"},153
{path: job, method: "GET", code: "200", resp: "Job"},127
{path: job + "/play", method: "POST", code: "200", resp: "Job"},154
{path: job + "/play", method: "POST", code: "200", resp: "Job"},@@ -130,6 +157,12 @@ func apiBinds() []apiBind {130
157
131
{path: branches, method: "GET", code: "200", resp: "Branch", array: true},158
{path: branches, method: "GET", code: "200", resp: "Branch", array: true},132
{path: branches, method: "POST", code: "201", body: "BranchCreate", resp: "Branch"},159
{path: branches, method: "POST", code: "201", body: "BranchCreate", resp: "Branch"},160
{path: branches, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch", optional: true, query: []apiQuery{161
q("name", "Current branch name. Preferred when the name contains a slash and the ingress rejects %2F.", true),162
}},163
{path: branches, method: "DELETE", code: "204", body: "BranchDelete", empty: true, optional: true, query: []apiQuery{164
q("name", "Branch to delete. May also be sent in the JSON body. Use this when the name contains a slash and the ingress rejects %2F.", false),165
}},133
{path: branch, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch"},166
{path: branch, method: "PUT", code: "200", body: "BranchUpdate", resp: "Branch"},134
{path: branch, method: "DELETE", code: "204", body: "BranchDelete", empty: true},167
{path: branch, method: "DELETE", code: "204", body: "BranchDelete", empty: true},135
168
@@ -159,7 +192,17 @@ func apiBinds() []apiBind {159
{path: "/projects/{owner}/{repo}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},192
{path: "/projects/{owner}/{repo}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},160
{path: "/groups/{path}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},193
{path: "/groups/{path}/logo", method: "POST", code: "200", body: "LogoUpload", resp: "LogoResult", multipart: true},161
{path: "/projects/{owner}/{repo}/protected_branches", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},194
{path: "/projects/{owner}/{repo}/protected_branches", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},195
{path: "/projects/{owner}/{repo}/protected_branches", method: "DELETE", code: "204", body: "ProtectedPattern", empty: true, optional: true, query: []apiQuery{196
q("pattern", "Pattern to unprotect. May also be sent in the JSON body. Use this when the pattern contains a slash and the ingress rejects %2F.", false),197
}},162
{path: "/projects/{owner}/{repo}/protected_tags", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},198
{path: "/projects/{owner}/{repo}/protected_tags", method: "POST", code: "201", body: "ProtectedPattern", resp: "ProtectedPattern"},199
{path: "/projects/{owner}/{repo}/protected_tags", method: "DELETE", code: "204", body: "ProtectedPattern", empty: true, optional: true, query: []apiQuery{200
q("pattern", "Pattern to unprotect. May also be sent in the JSON body. Use this when the pattern contains a slash and the ingress rejects %2F.", false),201
}},202
{path: "/projects/{owner}/{repo}/repository/files", method: "GET", query: []apiQuery{203
q("path", "File path, including slashes. Preferred when the ingress rejects %2F in the URL path.", true),204
q("ref", "Branch, tag or commit. Default: the project's default branch.", false),205
}},163
{path: "/projects/{owner}/{repo}/ci/lint", method: "POST", code: "200", body: "CILint", resp: "CILintResult"},206
{path: "/projects/{owner}/{repo}/ci/lint", method: "POST", code: "200", body: "CILint", resp: "CILintResult"},164
}207
}165
}208
}@@ -275,11 +318,12 @@ func apiSchemas() map[string]any {275
"PipelineCreate": obj("Start a pipeline.", map[string]any{318
"PipelineCreate": obj("Start a pipeline.", map[string]any{276
"ref": str("Branch, tag or full ref to run."),319
"ref": str("Branch, tag or full ref to run."),277
}),320
}),278
"PipelineRetry": obj("Retry a pipeline. all starts a new pipeline on the same commit, ref, source and merge request. failed requeues failed jobs and the skipped or never-started jobs that depend on them. The response is 201 for all and 200 for failed.", map[string]any{321
"PipelineRetry": obj("Retry a pipeline. all starts a new pipeline on the same commit, ref, source and merge request. failed requeues failed jobs and the skipped or never-started jobs that depend on them. The response is 201 for all and 200 for failed. An omitted or empty body uses failed.", map[string]any{279
"mode": map[string]any{322
"mode": map[string]any{280
"type": "string",323
"type": "string",281
"description": "all or failed.",324
"description": "all or failed. Omitted or empty means failed.",282
"enum": []any{"all", "failed"},325
"enum": []any{"all", "failed"},326
"default": "failed",283
},327
},284
}),328
}),285
"Job": obj("CI job.", map[string]any{329
"Job": obj("CI job.", map[string]any{@@ -307,12 +351,13 @@ func apiSchemas() map[string]any {307
"name": str("New branch name."),351
"name": str("New branch name."),308
"from": str("Existing branch or commit to start from."),352
"from": str("Existing branch or commit to start from."),309
}),353
}),310
"BranchUpdate": obj("Rename a branch.", map[string]any{354
"BranchUpdate": obj("Rename a branch. On PUT /repository/branches the current name is the name query. confirm may then be omitted and defaults to that name.", map[string]any{311
"name": str("New branch name."),355
"name": str("New branch name."),312
"confirm": str("Current branch name, repeated as confirmation."),356
"confirm": str("Current branch name, repeated as confirmation. Required when the current name is in the path."),313
}),357
}),314
"BranchDelete": obj("Delete a branch.", map[string]any{358
"BranchDelete": obj("Delete a branch. On DELETE /repository/branches the name may be the name query or this name field. confirm may then be omitted and defaults to the name.", map[string]any{315
"confirm": str("Branch name, repeated as confirmation."),359
"name": str("Branch name, when not in the path or the name query."),360
"confirm": str("Branch name, repeated as confirmation. Required when the name is in the path."),316
}),361
}),317
"Webhook": obj("Webhook.", map[string]any{362
"Webhook": obj("Webhook.", map[string]any{318
"id": integer("Webhook id."),363
"id": integer("Webhook id."),@@ -2,6 +2,7 @@ package server
2
2
3
3
import (
4
4
"context"
5
"fmt"
5
6
"path/filepath"
6
7
"strconv"
7
8
"strings"
@@ -52,6 +53,22 @@ func TestOpenAPISchemas(t *testing.T) {
52
53
assertBody(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "PipelineRetry")
53
54
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "200", "#/components/schemas/Pipeline")
54
55
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "201", "#/components/schemas/Pipeline")
56
retryBody := operation(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post")["requestBody"].(map[string]any)
57
if retryBody["required"] != false {
58
t.Fatal("PipelineRetry requestBody hoort optioneel te zijn")
59
}
60
mode := schemas["PipelineRetry"].(map[string]any)["properties"].(map[string]any)["mode"].(map[string]any)
61
if mode["default"] != "failed" {
62
t.Fatalf("PipelineRetry default %v", mode["default"])
63
}
64
got := map[string]bool{}
65
ev, _ := mode["enum"].([]any)
66
for _, v := range ev {
67
got[fmt.Sprint(v)] = true
68
}
69
if !got["all"] || !got["failed"] || len(ev) != 2 {
70
t.Fatalf("PipelineRetry enum %v", mode["enum"])
71
}
55
72
assertItems(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs", "get", "200", "#/components/schemas/Job")
56
73
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}", "get", "200", "#/components/schemas/Job")
57
74
@@ -267,3 +284,46 @@ func TestOpenAPIProjectRequestBodies(t *testing.T) {
267
284
}
268
285
}
269
286
}
287
288
func TestOpenAPISlashAvoidingEndpoints(t *testing.T) {
289
doc := openAPIDoc()
290
paths := doc["paths"].(map[string]any)
291
assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches", "delete", "BranchDelete")
292
assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches", "put", "BranchUpdate")
293
assertBody(t, paths, "/projects/{owner}/{repo}/protected_branches", "delete", "ProtectedPattern")
294
assertBody(t, paths, "/projects/{owner}/{repo}/protected_tags", "delete", "ProtectedPattern")
295
296
del := operation(t, paths, "/projects/{owner}/{repo}/repository/branches", "delete")
297
if del["requestBody"].(map[string]any)["required"] != false {
298
t.Fatal("collection DELETE branches body hoort optioneel te zijn")
299
}
300
params, _ := del["parameters"].([]any)
301
var hasName bool
302
for _, raw := range params {
303
p, _ := raw.(map[string]any)
304
if p["name"] == "name" && p["in"] == "query" {
305
hasName = true
306
}
307
}
308
if !hasName {
309
t.Fatal("DELETE /repository/branches mist query name")
310
}
311
312
file := operation(t, paths, "/projects/{owner}/{repo}/repository/files", "get")
313
var hasPath, hasRef bool
314
for _, raw := range file["parameters"].([]any) {
315
p, _ := raw.(map[string]any)
316
if p["in"] != "query" {
317
continue
318
}
319
switch p["name"] {
320
case "path":
321
hasPath = p["required"] == true
322
case "ref":
323
hasRef = true
324
}
325
}
326
if !hasPath || !hasRef {
327
t.Fatalf("files query params onvolledig: %v", file["parameters"])
328
}
329
}
@@ -2,6 +2,7 @@ package server2
2
3
import (3
import (4
"context"4
"context"5
"fmt"5
"path/filepath"6
"path/filepath"6
"strconv"7
"strconv"7
"strings"8
"strings"@@ -52,6 +53,22 @@ func TestOpenAPISchemas(t *testing.T) {52
assertBody(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "PipelineRetry")53
assertBody(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "PipelineRetry")53
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "200", "#/components/schemas/Pipeline")54
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "200", "#/components/schemas/Pipeline")54
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "201", "#/components/schemas/Pipeline")55
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post", "201", "#/components/schemas/Pipeline")56
retryBody := operation(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/retry", "post")["requestBody"].(map[string]any)57
if retryBody["required"] != false {58
t.Fatal("PipelineRetry requestBody hoort optioneel te zijn")59
}60
mode := schemas["PipelineRetry"].(map[string]any)["properties"].(map[string]any)["mode"].(map[string]any)61
if mode["default"] != "failed" {62
t.Fatalf("PipelineRetry default %v", mode["default"])63
}64
got := map[string]bool{}65
ev, _ := mode["enum"].([]any)66
for _, v := range ev {67
got[fmt.Sprint(v)] = true68
}69
if !got["all"] || !got["failed"] || len(ev) != 2 {70
t.Fatalf("PipelineRetry enum %v", mode["enum"])71
}55
assertItems(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs", "get", "200", "#/components/schemas/Job")72
assertItems(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs", "get", "200", "#/components/schemas/Job")56
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}", "get", "200", "#/components/schemas/Job")73
assertResp(t, paths, "/projects/{owner}/{repo}/pipelines/{id}/jobs/{job}", "get", "200", "#/components/schemas/Job")57
74
@@ -267,3 +284,46 @@ func TestOpenAPIProjectRequestBodies(t *testing.T) {267
}284
}268
}285
}269
}286
}287
288
func TestOpenAPISlashAvoidingEndpoints(t *testing.T) {289
doc := openAPIDoc()290
paths := doc["paths"].(map[string]any)291
assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches", "delete", "BranchDelete")292
assertBody(t, paths, "/projects/{owner}/{repo}/repository/branches", "put", "BranchUpdate")293
assertBody(t, paths, "/projects/{owner}/{repo}/protected_branches", "delete", "ProtectedPattern")294
assertBody(t, paths, "/projects/{owner}/{repo}/protected_tags", "delete", "ProtectedPattern")295
296
del := operation(t, paths, "/projects/{owner}/{repo}/repository/branches", "delete")297
if del["requestBody"].(map[string]any)["required"] != false {298
t.Fatal("collection DELETE branches body hoort optioneel te zijn")299
}300
params, _ := del["parameters"].([]any)301
var hasName bool302
for _, raw := range params {303
p, _ := raw.(map[string]any)304
if p["name"] == "name" && p["in"] == "query" {305
hasName = true306
}307
}308
if !hasName {309
t.Fatal("DELETE /repository/branches mist query name")310
}311
312
file := operation(t, paths, "/projects/{owner}/{repo}/repository/files", "get")313
var hasPath, hasRef bool314
for _, raw := range file["parameters"].([]any) {315
p, _ := raw.(map[string]any)316
if p["in"] != "query" {317
continue318
}319
switch p["name"] {320
case "path":321
hasPath = p["required"] == true322
case "ref":323
hasRef = true324
}325
}326
if !hasPath || !hasRef {327
t.Fatalf("files query params onvolledig: %v", file["parameters"])328
}329
}@@ -116,13 +116,17 @@ var apiCatalog = []apiRoute{
116
116
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},
117
117
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},
118
118
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeWrite, authUser, "Protect branch pattern", (*Server).apiProtectBranches},
119
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeWrite, authUser, "Unprotect branch pattern. Query or body pattern, for names with a slash when the ingress rejects %2F.", (*Server).apiUnprotectBranch},
119
120
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_branches/{pattern...}", access.ScopeWrite, authUser, "Unprotect branch pattern", (*Server).apiUnprotectBranch},
120
121
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeRead, authUser, "List protected tags", (*Server).apiProtectTags},
121
122
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeWrite, authUser, "Protect tag pattern", (*Server).apiProtectTags},
123
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeWrite, authUser, "Unprotect tag pattern. Query or body pattern, for names with a slash when the ingress rejects %2F.", (*Server).apiUnprotectTag},
122
124
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_tags/{pattern...}", access.ScopeWrite, authUser, "Unprotect tag pattern", (*Server).apiUnprotectTag},
123
125
124
126
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoRead, authOptional, "List branches", (*Server).apiBranches},
125
127
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Create branch", (*Server).apiBranches},
128
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Rename branch. Query name is the current branch, for names with a slash when the ingress rejects %2F.", (*Server).apiBranches},
129
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Delete branch by query name or JSON name. Use this when the branch name contains a slash and the ingress rejects %2F.", (*Server).apiBranches},
126
130
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Rename branch", (*Server).apiBranch},
127
131
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Delete branch", (*Server).apiBranch},
128
132
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags", access.ScopeRepoRead, authOptional, "List tags", (*Server).apiTags},
@@ -130,6 +134,7 @@ var apiCatalog = []apiRoute{
130
134
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}", access.ScopeRepoWrite, authUser, "Delete tag", (*Server).apiDeleteTag},
131
135
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}/archive", access.ScopeRepoRead, authOptional, "Download tag archive", (*Server).apiTagArchive},
132
136
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tree", access.ScopeRepoRead, authOptional, "List tree", (*Server).apiTree},
137
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/files", access.ScopeRepoRead, authOptional, "Read file by query path and optional ref, for paths with a slash when the ingress rejects %2F.", (*Server).apiFile},
133
138
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/files/{path...}", access.ScopeRepoRead, authOptional, "Read file", (*Server).apiFile},
134
139
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoRead, authOptional, "List commits", (*Server).apiCommits},
135
140
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoWrite, authUser, "Create commit", (*Server).apiCommits},
@@ -116,13 +116,17 @@ var apiCatalog = []apiRoute{116
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},116
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/approvals", access.ScopeWrite, authUser, "Save project approvals", (*Server).apiProjectApproval},117
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},117
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeRead, authUser, "List protected branches", (*Server).apiProtectBranches},118
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeWrite, authUser, "Protect branch pattern", (*Server).apiProtectBranches},118
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeWrite, authUser, "Protect branch pattern", (*Server).apiProtectBranches},119
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_branches", access.ScopeWrite, authUser, "Unprotect branch pattern. Query or body pattern, for names with a slash when the ingress rejects %2F.", (*Server).apiUnprotectBranch},119
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_branches/{pattern...}", access.ScopeWrite, authUser, "Unprotect branch pattern", (*Server).apiUnprotectBranch},120
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_branches/{pattern...}", access.ScopeWrite, authUser, "Unprotect branch pattern", (*Server).apiUnprotectBranch},120
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeRead, authUser, "List protected tags", (*Server).apiProtectTags},121
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeRead, authUser, "List protected tags", (*Server).apiProtectTags},121
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeWrite, authUser, "Protect tag pattern", (*Server).apiProtectTags},122
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeWrite, authUser, "Protect tag pattern", (*Server).apiProtectTags},123
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_tags", access.ScopeWrite, authUser, "Unprotect tag pattern. Query or body pattern, for names with a slash when the ingress rejects %2F.", (*Server).apiUnprotectTag},122
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_tags/{pattern...}", access.ScopeWrite, authUser, "Unprotect tag pattern", (*Server).apiUnprotectTag},124
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/protected_tags/{pattern...}", access.ScopeWrite, authUser, "Unprotect tag pattern", (*Server).apiUnprotectTag},123
125
124
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoRead, authOptional, "List branches", (*Server).apiBranches},126
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoRead, authOptional, "List branches", (*Server).apiBranches},125
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Create branch", (*Server).apiBranches},127
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Create branch", (*Server).apiBranches},128
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Rename branch. Query name is the current branch, for names with a slash when the ingress rejects %2F.", (*Server).apiBranches},129
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/branches", access.ScopeRepoWrite, authUser, "Delete branch by query name or JSON name. Use this when the branch name contains a slash and the ingress rejects %2F.", (*Server).apiBranches},126
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Rename branch", (*Server).apiBranch},130
{http.MethodPut, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Rename branch", (*Server).apiBranch},127
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Delete branch", (*Server).apiBranch},131
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/branches/{branch...}", access.ScopeRepoWrite, authUser, "Delete branch", (*Server).apiBranch},128
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags", access.ScopeRepoRead, authOptional, "List tags", (*Server).apiTags},132
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags", access.ScopeRepoRead, authOptional, "List tags", (*Server).apiTags},@@ -130,6 +134,7 @@ var apiCatalog = []apiRoute{130
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}", access.ScopeRepoWrite, authUser, "Delete tag", (*Server).apiDeleteTag},134
{http.MethodDelete, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}", access.ScopeRepoWrite, authUser, "Delete tag", (*Server).apiDeleteTag},131
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}/archive", access.ScopeRepoRead, authOptional, "Download tag archive", (*Server).apiTagArchive},135
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tags/{tag}/archive", access.ScopeRepoRead, authOptional, "Download tag archive", (*Server).apiTagArchive},132
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tree", access.ScopeRepoRead, authOptional, "List tree", (*Server).apiTree},136
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/tree", access.ScopeRepoRead, authOptional, "List tree", (*Server).apiTree},137
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/files", access.ScopeRepoRead, authOptional, "Read file by query path and optional ref, for paths with a slash when the ingress rejects %2F.", (*Server).apiFile},133
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/files/{path...}", access.ScopeRepoRead, authOptional, "Read file", (*Server).apiFile},138
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/files/{path...}", access.ScopeRepoRead, authOptional, "Read file", (*Server).apiFile},134
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoRead, authOptional, "List commits", (*Server).apiCommits},139
{http.MethodGet, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoRead, authOptional, "List commits", (*Server).apiCommits},135
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoWrite, authUser, "Create commit", (*Server).apiCommits},140
{http.MethodPost, "/api/v1/projects/{owner}/{repo}/repository/commits", access.ScopeRepoWrite, authUser, "Create commit", (*Server).apiCommits},@@ -44,10 +44,14 @@ func TestAPICatalogCoversResources(t *testing.T) {
44
44
"DELETE /api/v1/projects/{owner}/{repo}\n",
45
45
"POST /api/v1/projects/{owner}/{repo}/members\n",
46
46
"POST /api/v1/projects/{owner}/{repo}/protected_branches\n",
47
"DELETE /api/v1/projects/{owner}/{repo}/protected_branches\n",
47
48
"POST /api/v1/projects/{owner}/{repo}/protected_tags\n",
49
"DELETE /api/v1/projects/{owner}/{repo}/protected_tags\n",
48
50
"POST /api/v1/projects/{owner}/{repo}/repository/branches\n",
51
"DELETE /api/v1/projects/{owner}/{repo}/repository/branches\n",
49
52
"DELETE /api/v1/projects/{owner}/{repo}/repository/branches/{branch...}\n",
50
53
"POST /api/v1/projects/{owner}/{repo}/repository/tags\n",
54
"GET /api/v1/projects/{owner}/{repo}/repository/files\n",
51
55
"GET /api/v1/projects/{owner}/{repo}/repository/files/{path...}\n",
52
56
"POST /api/v1/projects/{owner}/{repo}/repository/commits\n",
53
57
"GET /api/v1/projects/{owner}/{repo}/repository/commits/{sha}/diff\n",
@@ -44,10 +44,14 @@ func TestAPICatalogCoversResources(t *testing.T) {44
"DELETE /api/v1/projects/{owner}/{repo}\n",44
"DELETE /api/v1/projects/{owner}/{repo}\n",45
"POST /api/v1/projects/{owner}/{repo}/members\n",45
"POST /api/v1/projects/{owner}/{repo}/members\n",46
"POST /api/v1/projects/{owner}/{repo}/protected_branches\n",46
"POST /api/v1/projects/{owner}/{repo}/protected_branches\n",47
"DELETE /api/v1/projects/{owner}/{repo}/protected_branches\n",47
"POST /api/v1/projects/{owner}/{repo}/protected_tags\n",48
"POST /api/v1/projects/{owner}/{repo}/protected_tags\n",49
"DELETE /api/v1/projects/{owner}/{repo}/protected_tags\n",48
"POST /api/v1/projects/{owner}/{repo}/repository/branches\n",50
"POST /api/v1/projects/{owner}/{repo}/repository/branches\n",51
"DELETE /api/v1/projects/{owner}/{repo}/repository/branches\n",49
"DELETE /api/v1/projects/{owner}/{repo}/repository/branches/{branch...}\n",52
"DELETE /api/v1/projects/{owner}/{repo}/repository/branches/{branch...}\n",50
"POST /api/v1/projects/{owner}/{repo}/repository/tags\n",53
"POST /api/v1/projects/{owner}/{repo}/repository/tags\n",54
"GET /api/v1/projects/{owner}/{repo}/repository/files\n",51
"GET /api/v1/projects/{owner}/{repo}/repository/files/{path...}\n",55
"GET /api/v1/projects/{owner}/{repo}/repository/files/{path...}\n",52
"POST /api/v1/projects/{owner}/{repo}/repository/commits\n",56
"POST /api/v1/projects/{owner}/{repo}/repository/commits\n",53
"GET /api/v1/projects/{owner}/{repo}/repository/commits/{sha}/diff\n",57
"GET /api/v1/projects/{owner}/{repo}/repository/commits/{sha}/diff\n",@@ -110,6 +110,175 @@ func TestDeleteBranchWithSlash(t *testing.T) {
110
110
if !exists() {
111
111
t.Fatal("foute bevestiging mag de branch niet verwijderen")
112
112
}
113
114
// Varianten zonder slash in het pad, voor een ingress die %2F weigert.
115
recreate()
116
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches?name="+url.QueryEscape(name), "")
117
if code != http.StatusNoContent {
118
t.Fatalf("DELETE ?name= %d %s", code, body)
119
}
120
if exists() {
121
t.Fatal("query name hoort de branch te verwijderen")
122
}
123
recreate()
124
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches", `{"name":"`+name+`"}`)
125
if code != http.StatusNoContent {
126
t.Fatalf("DELETE body name %d %s", code, body)
127
}
128
if exists() {
129
t.Fatal("body name hoort de branch te verwijderen")
130
}
131
recreate()
132
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches", `{"name":"`+name+`","confirm":"andere-tak"}`)
133
if code != http.StatusBadRequest {
134
t.Fatalf("DELETE body verkeerde confirm %d %s", code, body)
135
}
136
if !exists() {
137
t.Fatal("verkeerde confirm mag de branch niet verwijderen")
138
}
139
code, body = call(http.MethodPut, "/api/v1/projects/ada/demo/repository/branches?name="+url.QueryEscape(name), `{"name":"cursor/hernoemd"}`)
140
if code != http.StatusOK {
141
t.Fatalf("PUT ?name= %d %s", code, body)
142
}
143
if exists() {
144
t.Fatal("oude naam hoort weg te zijn na hernoemen")
145
}
146
out, err := exec.Command("git", "-C", dir, "rev-parse", "--verify", "--quiet", "refs/heads/cursor/hernoemd").Output()
147
if err != nil || strings.TrimSpace(string(out)) == "" {
148
t.Fatal("nieuwe naam ontbreekt")
149
}
150
}
151
152
func TestSlashAvoidingRefEndpoints(t *testing.T) {
153
if _, err := exec.LookPath("git"); err != nil {
154
t.Skip("git ontbreekt")
155
}
156
storage := t.TempDir()
157
st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())
158
if err != nil {
159
t.Fatal(err)
160
}
161
t.Cleanup(func() { _ = st.Close() })
162
ctx := context.Background()
163
ada, err := st.UpsertUser(ctx, 1, "ada", "", false)
164
if err != nil {
165
t.Fatal(err)
166
}
167
token, _, err := st.IssueToken(ctx, ada.ID, store.TokenRequest{Name: "ada", Scopes: "api"})
168
if err != nil {
169
t.Fatal(err)
170
}
171
cfg := config.Config{
172
BaseURL: "http://127.0.0.1:9", StoragePath: storage,
173
Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},
174
Git: config.Git{Binary: "git", DefaultBranch: "master"},
175
}
176
srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}
177
ts := httptest.NewServer(srv.Handler())
178
t.Cleanup(ts.Close)
179
180
call := func(method, path, body string) (int, string) {
181
t.Helper()
182
req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))
183
if err != nil {
184
t.Fatal(err)
185
}
186
req.Header.Set("Authorization", "Bearer "+token)
187
if body != "" {
188
req.Header.Set("Content-Type", "application/json")
189
}
190
res, err := http.DefaultClient.Do(req)
191
if err != nil {
192
t.Fatal(err)
193
}
194
return res.StatusCode, read(t, res)
195
}
196
code, body := call(http.MethodPost, "/api/v1/projects", `{"name":"demo","visibility":"public","initialize_with_readme":true}`)
197
if code != 201 {
198
t.Fatalf("project %d %s", code, body)
199
}
200
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/repository/commits", `{"branch":"master","commit_message":"pad","actions":[{"action":"create","file_path":"docs/INGRESS.md","content":"# Ingress\n"}]}`)
201
if code != 201 {
202
t.Fatalf("commit %d %s", code, body)
203
}
204
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/repository/files?path="+url.QueryEscape("docs/INGRESS.md")+"&ref=master", "")
205
if code != 200 || !strings.Contains(body, "# Ingress") {
206
t.Fatalf("GET files?path= %d %s", code, body)
207
}
208
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/repository/files/docs%2FINGRESS.md?ref=master", "")
209
if code != 200 || !strings.Contains(body, "# Ingress") {
210
t.Fatalf("GET files %%2F %d %s", code, body)
211
}
212
213
const pattern = "feature/*"
214
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)
215
if code != 201 {
216
t.Fatalf("protect %d %s", code, body)
217
}
218
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_branches?pattern="+url.QueryEscape(pattern), "")
219
if code != http.StatusNoContent {
220
t.Fatalf("unprotect ?pattern= %d %s", code, body)
221
}
222
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)
223
if code != 201 {
224
t.Fatalf("protect opnieuw %d %s", code, body)
225
}
226
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)
227
if code != http.StatusNoContent {
228
t.Fatalf("unprotect body pattern %d %s", code, body)
229
}
230
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/protected_branches", "")
231
if code != 200 || strings.Contains(body, "feature/") {
232
t.Fatalf("pattern zou weg moeten zijn: %d %s", code, body)
233
}
234
235
const tagPat = "releases/*"
236
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_tags", `{"pattern":"`+tagPat+`"}`)
237
if code != 201 {
238
t.Fatalf("protect tag %d %s", code, body)
239
}
240
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_tags?pattern="+url.QueryEscape(tagPat), "")
241
if code != http.StatusNoContent {
242
t.Fatalf("unprotect tag ?pattern= %d %s", code, body)
243
}
244
}
245
246
func TestPathWildcardEncodedSlash(t *testing.T) {
247
mux := http.NewServeMux()
248
var got string
249
mux.HandleFunc("DELETE /branches/{branch...}", func(w http.ResponseWriter, r *http.Request) {
250
got = pathWildcard(r, "branch")
251
w.WriteHeader(http.StatusNoContent)
252
})
253
ts := httptest.NewServer(mux)
254
t.Cleanup(ts.Close)
255
for _, path := range []string{"/branches/feature/x", "/branches/feature%2Fx", "/branches/feature%252Fx"} {
256
got = ""
257
req, err := http.NewRequest(http.MethodDelete, ts.URL+path, nil)
258
if err != nil {
259
t.Fatal(err)
260
}
261
res, err := http.DefaultClient.Do(req)
262
if err != nil {
263
t.Fatal(err)
264
}
265
res.Body.Close()
266
if res.StatusCode != http.StatusNoContent {
267
t.Fatalf("%s: %d", path, res.StatusCode)
268
}
269
if got != "feature/x" {
270
t.Fatalf("%s: pathWildcard=%q", path, got)
271
}
272
}
273
}
274
275
func TestRetryPipelineModeDefault(t *testing.T) {
276
if retryPipelineMode("") != "failed" || retryPipelineMode(" ") != "failed" {
277
t.Fatal("lege mode hoort failed te zijn")
278
}
279
if retryPipelineMode("all") != "all" || retryPipelineMode("failed") != "failed" {
280
t.Fatal("expliciete mode moet blijven")
281
}
113
282
}
114
283
115
284
func TestPushDeletesSourceBranch(t *testing.T) {
@@ -110,6 +110,175 @@ func TestDeleteBranchWithSlash(t *testing.T) {110
if !exists() {110
if !exists() {111
t.Fatal("foute bevestiging mag de branch niet verwijderen")111
t.Fatal("foute bevestiging mag de branch niet verwijderen")112
}112
}113
114
// Varianten zonder slash in het pad, voor een ingress die %2F weigert.115
recreate()116
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches?name="+url.QueryEscape(name), "")117
if code != http.StatusNoContent {118
t.Fatalf("DELETE ?name= %d %s", code, body)119
}120
if exists() {121
t.Fatal("query name hoort de branch te verwijderen")122
}123
recreate()124
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches", `{"name":"`+name+`"}`)125
if code != http.StatusNoContent {126
t.Fatalf("DELETE body name %d %s", code, body)127
}128
if exists() {129
t.Fatal("body name hoort de branch te verwijderen")130
}131
recreate()132
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/repository/branches", `{"name":"`+name+`","confirm":"andere-tak"}`)133
if code != http.StatusBadRequest {134
t.Fatalf("DELETE body verkeerde confirm %d %s", code, body)135
}136
if !exists() {137
t.Fatal("verkeerde confirm mag de branch niet verwijderen")138
}139
code, body = call(http.MethodPut, "/api/v1/projects/ada/demo/repository/branches?name="+url.QueryEscape(name), `{"name":"cursor/hernoemd"}`)140
if code != http.StatusOK {141
t.Fatalf("PUT ?name= %d %s", code, body)142
}143
if exists() {144
t.Fatal("oude naam hoort weg te zijn na hernoemen")145
}146
out, err := exec.Command("git", "-C", dir, "rev-parse", "--verify", "--quiet", "refs/heads/cursor/hernoemd").Output()147
if err != nil || strings.TrimSpace(string(out)) == "" {148
t.Fatal("nieuwe naam ontbreekt")149
}150
}151
152
func TestSlashAvoidingRefEndpoints(t *testing.T) {153
if _, err := exec.LookPath("git"); err != nil {154
t.Skip("git ontbreekt")155
}156
storage := t.TempDir()157
st, err := store.Open(filepath.Join(storage, "bluegit.db"), bytes32())158
if err != nil {159
t.Fatal(err)160
}161
t.Cleanup(func() { _ = st.Close() })162
ctx := context.Background()163
ada, err := st.UpsertUser(ctx, 1, "ada", "", false)164
if err != nil {165
t.Fatal(err)166
}167
token, _, err := st.IssueToken(ctx, ada.ID, store.TokenRequest{Name: "ada", Scopes: "api"})168
if err != nil {169
t.Fatal(err)170
}171
cfg := config.Config{172
BaseURL: "http://127.0.0.1:9", StoragePath: storage,173
Auth: config.Auth{Mode: "dev", DevUser: "ada", DevAuthID: 1},174
Git: config.Git{Binary: "git", DefaultBranch: "master"},175
}176
srv := &Server{Cfg: cfg, Store: st, Auth: auth.Dev{Username: "ada", AuthID: 1}, Git: "git", HookBin: "/bin/true", StateDir: t.TempDir()}177
ts := httptest.NewServer(srv.Handler())178
t.Cleanup(ts.Close)179
180
call := func(method, path, body string) (int, string) {181
t.Helper()182
req, err := http.NewRequest(method, ts.URL+path, strings.NewReader(body))183
if err != nil {184
t.Fatal(err)185
}186
req.Header.Set("Authorization", "Bearer "+token)187
if body != "" {188
req.Header.Set("Content-Type", "application/json")189
}190
res, err := http.DefaultClient.Do(req)191
if err != nil {192
t.Fatal(err)193
}194
return res.StatusCode, read(t, res)195
}196
code, body := call(http.MethodPost, "/api/v1/projects", `{"name":"demo","visibility":"public","initialize_with_readme":true}`)197
if code != 201 {198
t.Fatalf("project %d %s", code, body)199
}200
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/repository/commits", `{"branch":"master","commit_message":"pad","actions":[{"action":"create","file_path":"docs/INGRESS.md","content":"# Ingress\n"}]}`)201
if code != 201 {202
t.Fatalf("commit %d %s", code, body)203
}204
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/repository/files?path="+url.QueryEscape("docs/INGRESS.md")+"&ref=master", "")205
if code != 200 || !strings.Contains(body, "# Ingress") {206
t.Fatalf("GET files?path= %d %s", code, body)207
}208
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/repository/files/docs%2FINGRESS.md?ref=master", "")209
if code != 200 || !strings.Contains(body, "# Ingress") {210
t.Fatalf("GET files %%2F %d %s", code, body)211
}212
213
const pattern = "feature/*"214
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)215
if code != 201 {216
t.Fatalf("protect %d %s", code, body)217
}218
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_branches?pattern="+url.QueryEscape(pattern), "")219
if code != http.StatusNoContent {220
t.Fatalf("unprotect ?pattern= %d %s", code, body)221
}222
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)223
if code != 201 {224
t.Fatalf("protect opnieuw %d %s", code, body)225
}226
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_branches", `{"pattern":"`+pattern+`"}`)227
if code != http.StatusNoContent {228
t.Fatalf("unprotect body pattern %d %s", code, body)229
}230
code, body = call(http.MethodGet, "/api/v1/projects/ada/demo/protected_branches", "")231
if code != 200 || strings.Contains(body, "feature/") {232
t.Fatalf("pattern zou weg moeten zijn: %d %s", code, body)233
}234
235
const tagPat = "releases/*"236
code, body = call(http.MethodPost, "/api/v1/projects/ada/demo/protected_tags", `{"pattern":"`+tagPat+`"}`)237
if code != 201 {238
t.Fatalf("protect tag %d %s", code, body)239
}240
code, body = call(http.MethodDelete, "/api/v1/projects/ada/demo/protected_tags?pattern="+url.QueryEscape(tagPat), "")241
if code != http.StatusNoContent {242
t.Fatalf("unprotect tag ?pattern= %d %s", code, body)243
}244
}245
246
func TestPathWildcardEncodedSlash(t *testing.T) {247
mux := http.NewServeMux()248
var got string249
mux.HandleFunc("DELETE /branches/{branch...}", func(w http.ResponseWriter, r *http.Request) {250
got = pathWildcard(r, "branch")251
w.WriteHeader(http.StatusNoContent)252
})253
ts := httptest.NewServer(mux)254
t.Cleanup(ts.Close)255
for _, path := range []string{"/branches/feature/x", "/branches/feature%2Fx", "/branches/feature%252Fx"} {256
got = ""257
req, err := http.NewRequest(http.MethodDelete, ts.URL+path, nil)258
if err != nil {259
t.Fatal(err)260
}261
res, err := http.DefaultClient.Do(req)262
if err != nil {263
t.Fatal(err)264
}265
res.Body.Close()266
if res.StatusCode != http.StatusNoContent {267
t.Fatalf("%s: %d", path, res.StatusCode)268
}269
if got != "feature/x" {270
t.Fatalf("%s: pathWildcard=%q", path, got)271
}272
}273
}274
275
func TestRetryPipelineModeDefault(t *testing.T) {276
if retryPipelineMode("") != "failed" || retryPipelineMode(" ") != "failed" {277
t.Fatal("lege mode hoort failed te zijn")278
}279
if retryPipelineMode("all") != "all" || retryPipelineMode("failed") != "failed" {280
t.Fatal("expliciete mode moet blijven")281
}113
}282
}114
283
115
func TestPushDeletesSourceBranch(t *testing.T) {284
func TestPushDeletesSourceBranch(t *testing.T) {@@ -116,7 +116,16 @@ func (s *Server) opJobActionForce(ctx context.Context, user store.User, repo sto
116
116
return job, nil
117
117
}
118
118
119
func retryPipelineMode(mode string) string {
120
mode = strings.TrimSpace(mode)
121
if mode == "" {
122
return "failed"
123
}
124
return mode
125
}
126
119
127
func (s *Server) opRetryPipeline(ctx context.Context, user store.User, repo store.Repo, pipeID int64, mode string) (int64, error) {
128
mode = retryPipelineMode(mode)
120
129
role, err := s.repoRole(ctx, user, repo)
121
130
if err != nil {
122
131
return 0, err
@@ -116,7 +116,16 @@ func (s *Server) opJobActionForce(ctx context.Context, user store.User, repo sto116
return job, nil116
return job, nil117
}117
}118
118
119
func retryPipelineMode(mode string) string {120
mode = strings.TrimSpace(mode)121
if mode == "" {122
return "failed"123
}124
return mode125
}126
119
func (s *Server) opRetryPipeline(ctx context.Context, user store.User, repo store.Repo, pipeID int64, mode string) (int64, error) {127
func (s *Server) opRetryPipeline(ctx context.Context, user store.User, repo store.Repo, pipeID int64, mode string) (int64, error) {128
mode = retryPipelineMode(mode)120
role, err := s.repoRole(ctx, user, repo)129
role, err := s.repoRole(ctx, user, repo)121
if err != nil {130
if err != nil {122
return 0, err131
return 0, err@@ -2,6 +2,7 @@ package server
2
2
3
3
import (
4
4
"context"
5
"net/http"
5
6
"net/url"
6
7
"os"
7
8
"strings"
@@ -28,6 +29,13 @@ func decodeBranch(raw string) string {
28
29
return name
29
30
}
30
31
32
// pathWildcard leest een ServeMux-wildcard. De mux matcht op de escaped path
33
// (EscapedPath/RawPath), zodat zowel feature/x als feature%2Fx bij {name...}
34
// horen. PathValue laat %2F ongecodeerd; decodeBranch maakt daar een taknaam van.
35
func pathWildcard(r *http.Request, key string) string {
36
return decodeBranch(r.PathValue(key))
37
}
38
31
39
func (s *Server) repoRole(ctx context.Context, user store.User, repo store.Repo) (access.Role, error) {
32
40
role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)
33
41
if err != nil {
@@ -2,6 +2,7 @@ package server2
2
3
import (3
import (4
"context"4
"context"5
"net/http"5
"net/url"6
"net/url"6
"os"7
"os"7
"strings"8
"strings"@@ -28,6 +29,13 @@ func decodeBranch(raw string) string {28
return name29
return name29
}30
}30
31
32
// pathWildcard leest een ServeMux-wildcard. De mux matcht op de escaped path33
// (EscapedPath/RawPath), zodat zowel feature/x als feature%2Fx bij {name...}34
// horen. PathValue laat %2F ongecodeerd; decodeBranch maakt daar een taknaam van.35
func pathWildcard(r *http.Request, key string) string {36
return decodeBranch(r.PathValue(key))37
}38
31
func (s *Server) repoRole(ctx context.Context, user store.User, repo store.Repo) (access.Role, error) {39
func (s *Server) repoRole(ctx context.Context, user store.User, repo store.Repo) (access.Role, error) {32
role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)40
role, err := s.Store.EffectiveRole(ctx, user.ID, repo.ID)33
if err != nil {41
if err != nil {@@ -210,6 +210,14 @@ func TestPipelineRetryButtonAndAPI(t *testing.T) {
210
210
if code != 409 {
211
211
t.Fatalf("tweede failed %d %s", code, body)
212
212
}
213
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{}`)
214
if code != 409 {
215
t.Fatalf("leeg object default failed %d %s", code, body)
216
}
217
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, "")
218
if code != 409 {
219
t.Fatalf("lege body default failed %d %s", code, body)
220
}
213
221
// Zonder gefaalde job weigert ook "all" (zelfde regel als de UI).
214
222
for _, pid := range []int64{id, okID} {
215
223
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(pid, 10)+"/retry", ownerToken, `{"mode":"all"}`)
@@ -210,6 +210,14 @@ func TestPipelineRetryButtonAndAPI(t *testing.T) {210
if code != 409 {210
if code != 409 {211
t.Fatalf("tweede failed %d %s", code, body)211
t.Fatalf("tweede failed %d %s", code, body)212
}212
}213
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, `{}`)214
if code != 409 {215
t.Fatalf("leeg object default failed %d %s", code, body)216
}217
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(id, 10)+"/retry", ownerToken, "")218
if code != 409 {219
t.Fatalf("lege body default failed %d %s", code, body)220
}213
// Zonder gefaalde job weigert ook "all" (zelfde regel als de UI).221
// Zonder gefaalde job weigert ook "all" (zelfde regel als de UI).214
for _, pid := range []int64{id, okID} {222
for _, pid := range []int64{id, okID} {215
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(pid, 10)+"/retry", ownerToken, `{"mode":"all"}`)223
code, body = retryAPI(t, ts, http.MethodPost, "/api/v1/projects/tim/opnieuw/pipelines/"+strconv.FormatInt(pid, 10)+"/retry", ownerToken, `{"mode":"all"}`)