Repository navigation
Expand file tree
/
Copy pathparser_context_test.go
More file actions
216 lines (168 loc) · 5.85 KB
/
Copy pathparser_context_test.go
File metadata and controls
216 lines (168 loc) · 5.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package publiccode
import (
"bytes"
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
)
// cancelBound is far below the waits the cancelled work would otherwise
// take: one minute for the first blind retry after a 429, 30 seconds for
// the HTTP timeout.
const cancelBound = 10 * time.Second
// cancelOnRequest returns a handler that cancels the test context on the
// first request it gets and then runs next.
func cancelOnRequest(cancel context.CancelFunc, next http.HandlerFunc) http.HandlerFunc {
var once sync.Once
return func(w http.ResponseWriter, r *http.Request) {
once.Do(cancel)
next(w, r)
}
}
// waitForClient blocks until the client gives up on the request.
func waitForClient(_ http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}
func newNetworkParser(t *testing.T, baseURL string) *Parser {
t.Helper()
p, err := NewParser(ParserConfig{AllowNetworkToPrivateHosts: true, BaseURL: baseURL})
if err != nil {
t.Fatal(err)
}
return p
}
func checkCancelled(t *testing.T, start time.Time, publiccode PublicCode, err error) {
t.Helper()
if !errors.Is(err, context.Canceled) {
t.Fatalf("got error %v, want context.Canceled", err)
}
if publiccode != nil {
t.Error("got a PublicCode from a cancelled validation")
}
if elapsed := time.Since(start); elapsed > cancelBound {
t.Errorf("the parser returned %s after the cancellation", elapsed)
}
}
func TestParseStreamWithContextStopsRateLimitWait(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
// No Retry-After: the client would wait one minute before the next try.
srv := httptest.NewServer(cancelOnRequest(cancel, func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusTooManyRequests)
}))
defer srv.Close()
content := bytes.ReplaceAll(validPubliccode(t), []byte("https://"), []byte(srv.URL+"/"))
start := time.Now()
publiccode, err := newNetworkParser(t, srv.URL).ParseStreamWithContext(ctx, bytes.NewReader(content))
checkCancelled(t, start, publiccode, err)
}
func TestParseWithContextStopsRemoteFetch(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
srv := httptest.NewServer(cancelOnRequest(cancel, waitForClient))
defer srv.Close()
start := time.Now()
publiccode, err := newNetworkParser(t, "").ParseWithContext(ctx, srv.URL+"/publiccode.yml")
checkCancelled(t, start, publiccode, err)
}
// Without a base URL, the parser asks go-vcsurl for the raw root of the
// repository in url. go-vcsurl builds its requests without a context.
func TestParseStreamWithContextStopsRepositoryLookup(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
lookup := cancelOnRequest(cancel, waitForClient)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// The host probes run to the end, so answer them and stop on the
// next request.
if isHostProbe(r) {
w.WriteHeader(http.StatusNotFound)
return
}
lookup(w, r)
}))
defer srv.Close()
content := bytes.ReplaceAll(validPubliccode(t), []byte("https://"), []byte(srv.URL+"/"))
start := time.Now()
publiccode, err := newNetworkParser(t, "").ParseStreamWithContext(ctx, bytes.NewReader(content))
checkCancelled(t, start, publiccode, err)
}
// go-vcsurl caches which software a host runs, a failed probe included. A
// validation cancelled during the GitLab probe must not make the host look
// like no repository host to the next one.
func TestParseStreamWithContextKeepsHostClassification(t *testing.T) {
for _, redirect := range []bool{false, true} {
name := "direct"
if redirect {
name = "redirects"
}
t.Run(name, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
firstDone := make(chan struct{})
probe := cancelOnRequest(cancel, func(w http.ResponseWriter, r *http.Request) {
// Answer only after the cancelled validation returned.
select {
case <-firstDone:
case <-r.Context().Done():
return
}
http.SetCookie(w, &http.Cookie{
Name: "_gitlab_session", Value: "1", Secure: true, HttpOnly: true, SameSite: http.SameSiteStrictMode,
})
})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if redirect && r.URL.Path == "/api" {
http.Redirect(w, r, "/signin", http.StatusFound)
return
}
if redirect && r.URL.Path == "/signin" {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if (!redirect && r.URL.Path == "/api") || (redirect && r.URL.Path == "/login") {
probe(w, r)
return
}
w.WriteHeader(http.StatusNotFound)
}))
defer srv.Close()
content := bytes.ReplaceAll(validPubliccode(t), []byte("https://"), []byte(srv.URL+"/"))
p := newNetworkParser(t, "")
start := time.Now()
publiccode, err := p.ParseStreamWithContext(ctx, bytes.NewReader(content))
close(firstDone)
checkCancelled(t, start, publiccode, err)
_, err = p.ParseStreamWithContext(t.Context(), bytes.NewReader(content))
results, ok := errors.AsType[ValidationResults](err)
if !ok {
t.Fatalf("got error %v, want ValidationResults", err)
}
for _, res := range results {
var e ValidationError
if !errors.As(res, &e) || e.Key != "url" {
continue
}
if strings.Contains(e.Description, "valid code repository") || strings.Contains(e.Description, "raw URL") {
t.Errorf("the GitLab repository was rejected after a cancelled validation: %s", e.Description)
}
}
})
}
}
func TestParseStreamWithContextKeepsResultsWhenNotCancelled(t *testing.T) {
p, err := NewParser(ParserConfig{DisableNetwork: true})
if err != nil {
t.Fatal(err)
}
publiccode, err := p.ParseStreamWithContext(t.Context(), bytes.NewReader(validPubliccode(t)))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if publiccode == nil {
t.Fatal("got a nil PublicCode")
}
}