Debian Codegraph @

resources/resource_factories/create/create_integration_test.go

raw ◀ ▶
1 Debian patch touch this file
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package create_test
15
16 import (
17 "fmt"
18 "math/rand"
19 "net/http"
20 "net/http/httptest"
•21 "os"
22 "strings"
23 "sync"
24 "testing"
25 "time"
26
27 qt "github.com/frankban/quicktest"
28 "github.com/gohugoio/hugo/htesting"
29 "github.com/gohugoio/hugo/hugolib"
30 )
31
32 func TestGetRemoteHead(t *testing.T) {
•33 if os.Getenv("AUTOPKGTEST_TMP") == "" {
34 t.Skip("Skip test as network is inaccessible during Debian package build")
35 }
36 files := `
37 -- hugo.toml --
38 [security]
39 [security.http]
40 methods = ['(?i)GET|POST|HEAD']
41 urls = ['.*gohugo\.io.*']
42 -- layouts/home.html --
43 {{ $url := "https://gohugo.io/img/hugo.png" }}
44 {{ $opts := dict "method" "head" }}
45 {{ with try (resources.GetRemote $url $opts) }}
46 {{ with .Err }}
47 {{ errorf "Unable to get remote resource: %s" . }}
48 {{ else with .Value }}
49 Head Content: {{ .Content }}. Head Data: {{ .Data }}
50 {{ else }}
51 {{ errorf "Unable to get remote resource: %s" $url }}
52 {{ end }}
53 {{ end }}
54 `
55
56 b := hugolib.Test(t, files)
57
58 b.AssertFileContent("public/index.html",
59 "Head Content: .",
60 "Head Data: map[ContentLength:18210 ContentType:image/png Headers:map[] Status:200 OK StatusCode:200 TransferEncoding:[]]",
61 )
62 }
63
64 func TestGetRemoteResponseHeaders(t *testing.T) {
•65 t.Skip("This tests needs internet access")
66 files := `
67 -- hugo.toml --
68 [security]
69 [security.http]
70 methods = ['(?i)GET|POST|HEAD']
71 urls = ['.*gohugo\.io.*']
72 -- layouts/home.html --
73 {{ $url := "https://gohugo.io/img/hugo.png" }}
74 {{ $opts := dict "method" "head" "responseHeaders" (slice "X-Frame-Options" "Server") }}
75 {{ with try (resources.GetRemote $url $opts) }}
76 {{ with .Err }}
77 {{ errorf "Unable to get remote resource: %s" . }}
78 {{ else with .Value }}
79 Response Headers: {{ .Data.Headers }}
80 {{ else }}
81 {{ errorf "Unable to get remote resource: %s" $url }}
82 {{ end }}
83 {{ end }}
84 `
85
86 b := hugolib.Test(t, files)
87
88 b.AssertFileContent("public/index.html",
89 "Response Headers: map[Server:[Netlify] X-Frame-Options:[DENY]]",
90 )
91 }
92
93 func TestGetRemoteRetry(t *testing.T) {
•94 t.Skip("This tests needs internet access")
95 t.Parallel()
96 htesting.SkipSlowTestUnlessCI(t)
97
98 temporaryHTTPCodes := []int{408, 429, 500, 502, 503, 504}
99 numPages := 20
100
101 handler := func(w http.ResponseWriter, r *http.Request) {
102 if rand.Intn(3) == 0 {
103 w.WriteHeader(temporaryHTTPCodes[rand.Intn(len(temporaryHTTPCodes))])
104 return
105 }
106 w.Header().Add("Content-Type", "text/plain")
107 w.Write([]byte("Response for " + r.URL.Path + "."))
108 }
109
110 srv := httptest.NewServer(http.HandlerFunc(handler))
111 t.Cleanup(func() { srv.Close() })
112
113 filesTemplate := `
114 -- hugo.toml --
115 disableKinds = ["home", "taxonomy", "term"]
116 timeout = "TIMEOUT"
117 [security]
118 [security.http]
119 urls = ['.*']
120 mediaTypes = ['text/plain']
121 -- layouts/single.html --
122 {{ $url := printf "%s%s" "URL" .RelPermalink}}
123 {{ $opts := dict }}
124 {{ with try (resources.GetRemote $url $opts) }}
125 {{ with .Err }}
126 {{ errorf "Got Err: %s" . }}
127 {{ with .Cause }}{{ errorf "Data: %s" .Data }}{{ end }}
128 {{ else with .Value }}
129 Content: {{ .Content }}
130 {{ else }}
131 {{ errorf "Unable to get remote resource: %s" $url }}
132 {{ end }}
133 {{ end }}
134 `
135
136 for i := range numPages {
137 filesTemplate += fmt.Sprintf("-- content/post/p%d.md --\n", i)
138 }
139
140 filesTemplate = strings.ReplaceAll(filesTemplate, "URL", srv.URL)
141
142 t.Run("OK", func(t *testing.T) {
143 files := strings.ReplaceAll(filesTemplate, "TIMEOUT", "60s")
144 b := hugolib.Test(t, files)
145
146 for i := range numPages {
147 b.AssertFileContent(fmt.Sprintf("public/post/p%d/index.html", i), fmt.Sprintf("Content: Response for /post/p%d/.", i))
148 }
149 })
150
151 t.Run("Timeout", func(t *testing.T) {
152 files := strings.ReplaceAll(filesTemplate, "TIMEOUT", "100ms")
153 b, err := hugolib.TestE(t, files)
154 // This is hard to get stable on GitHub Actions, it sometimes succeeds due to timing issues.
155 if err != nil {
156 b.AssertLogContains("Got Err")
157 b.AssertLogContains("retry timeout")
158 }
159 })
160 }
161
162 func TestGetRemotePerRequestTimeout(t *testing.T) {
163 t.Parallel()
164 htesting.SkipSlowTestUnlessCI(t)
165
166 // A server that always sleeps longer than the per-request timeout.
167 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
168 time.Sleep(2 * time.Second)
169 w.Header().Add("Content-Type", "text/plain")
170 w.Write([]byte("too late"))
171 }))
172 t.Cleanup(func() { srv.Close() })
173
174 files := `
175 -- hugo.toml --
176 timeout = "30s"
177 [security]
178 [security.http]
179 urls = ['.*']
180 mediaTypes = ['text/plain']
181 -- layouts/home.html --
182 {{ $url := "URL" }}
183 {{ $opts := dict "timeout" "200ms" }}
184 {{ with try (resources.GetRemote $url $opts) }}
185 {{ with .Err }}
186 Err: {{ . }}
187 {{ else with .Value }}
188 Content: {{ .Content }}
189 {{ end }}
190 {{ end }}
191 `
192 files = strings.ReplaceAll(files, "URL", srv.URL)
193
194 b := hugolib.Test(t, files)
195
196 // The per-request timeout of 200ms should fire well before the global 30s timeout.
197 b.AssertFileContent("public/index.html", "Err:")
198 }
199
200 // Issue 14828.
201 func TestGetRemoteRetryAfterIssue14828(t *testing.T) {
202 t.Parallel()
203
204 t.Run("Honored", func(t *testing.T) {
205 var (
206 mu sync.Mutex
207 reqTimes []time.Time
208 )
209
210 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
211 mu.Lock()
212 reqTimes = append(reqTimes, time.Now())
213 n := len(reqTimes)
214 mu.Unlock()
215
216 if n == 1 {
217 w.Header().Set("Retry-After", "2")
218 w.WriteHeader(http.StatusServiceUnavailable)
219 return
220 }
221 w.Header().Add("Content-Type", "text/plain")
222 w.Write([]byte("OK"))
223 }))
224 t.Cleanup(func() { srv.Close() })
225
226 files := `
227 -- hugo.toml --
228 timeout = "30s"
229 [security]
230 [security.http]
231 urls = ['.*']
232 mediaTypes = ['text/plain']
233 -- layouts/home.html --
234 {{ $url := "URL" }}
235 {{ with try (resources.GetRemote $url) }}
236 {{ with .Err }}
237 {{ errorf "Got Err: %s" . }}
238 {{ else with .Value }}
239 Content: {{ .Content }}
240 {{ end }}
241 {{ end }}
242 `
243 files = strings.ReplaceAll(files, "URL", srv.URL)
244
245 b := hugolib.Test(t, files)
246 b.AssertFileContent("public/index.html", "Content: OK")
247
248 mu.Lock()
249 defer mu.Unlock()
250 b.Assert(len(reqTimes) >= 2, qt.IsTrue, qt.Commentf("expected at least 2 requests, got %d", len(reqTimes)))
251 // Default exponential backoff caps the initial sleep at 1100ms.
252 // A Retry-After of 2s should produce a gap well above that.
253 gap := reqTimes[1].Sub(reqTimes[0])
254 b.Assert(gap >= 1500*time.Millisecond, qt.IsTrue, qt.Commentf("expected gap of at least 1500ms (Retry-After: 2), got %s", gap))
255 })
256
257 t.Run("TimeoutMessage", func(t *testing.T) {
258 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
259 w.Header().Set("Retry-After", "1")
260 w.WriteHeader(http.StatusServiceUnavailable)
261 }))
262 t.Cleanup(func() { srv.Close() })
263
264 files := `
265 -- hugo.toml --
266 timeout = "200ms"
267 [security]
268 [security.http]
269 urls = ['.*']
270 -- layouts/home.html --
271 {{ $url := "URL" }}
272 {{ with try (resources.GetRemote $url) }}
273 {{ with .Err }}
274 {{ errorf "Got Err: %s" . }}
275 {{ end }}
276 {{ end }}
277 `
278 files = strings.ReplaceAll(files, "URL", srv.URL)
279
280 b, _ := hugolib.TestE(t, files)
281 b.AssertLogContains("Retry-After: 1s")
282 })
283 }
284
285 // Issue 14871.
286 func TestGetRemoteRedirectSecurityCheckIssue14871(t *testing.T) {
287 t.Parallel()
288
289 // Final server: the redirect target. Its host must be denied by security.http.urls.
290 target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
291 w.Header().Add("Content-Type", "text/plain")
292 w.Write([]byte("should not reach here"))
293 }))
294 t.Cleanup(func() { target.Close() })
295
296 // Redirector: the allowed host. Redirects to the denied target.
297 redirector := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
298 http.Redirect(w, r, target.URL+"/", http.StatusFound)
299 }))
300 t.Cleanup(func() { redirector.Close() })
301
302 files := `
303 -- hugo.toml --
304 [security]
305 [security.http]
306 urls = ['REDIRECTOR']
307 mediaTypes = ['text/plain']
308 -- layouts/home.html --
309 {{ $url := "REDIRECTOR/" }}
310 {{ with try (resources.GetRemote $url) }}
311 {{ with .Err }}
312 Err: {{ . }}
313 {{ else with .Value }}
314 Content: {{ .Content }}
315 {{ end }}
316 {{ end }}
317 `
318 files = strings.ReplaceAll(files, "REDIRECTOR", redirector.URL)
319
320 b := hugolib.Test(t, files)
321
322 b.AssertFileContent("public/index.html", "Err:", "security.http.urls")
323 b.AssertFileContent("public/index.html", "! should not reach here")
324 }
325
326 // Issue 14611.
327 func TestGetRemotePerRequestTimeoutBodyRead(t *testing.T) {
328 t.Parallel()
329
330 // Server sends headers immediately but streams body with a delay.
331 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
332 w.Header().Add("Content-Type", "text/plain")
333 w.WriteHeader(200)
334 if f, ok := w.(http.Flusher); ok {
335 f.Flush()
336 }
337 time.Sleep(300 * time.Millisecond)
338 w.Write([]byte("Hello from remote."))
339 }))
340 t.Cleanup(func() { srv.Close() })
341
342 files := `
343 -- hugo.toml --
344 timeout = "30s"
345 [security]
346 [security.http]
347 urls = ['.*']
348 mediaTypes = ['text/plain']
349 -- layouts/home.html --
350 {{ $url := "URL" }}
351 {{ $opts := dict "timeout" "5s" }}
352 {{ with try (resources.GetRemote $url $opts) }}
353 {{ with .Err }}
354 Err: {{ . }}
355 {{ else with .Value }}
356 Content: {{ .Content }}
357 {{ end }}
358 {{ end }}
359 `
360 files = strings.ReplaceAll(files, "URL", srv.URL)
361
362 b := hugolib.Test(t, files)
363
364 b.AssertFileContent("public/index.html", "Content: Hello from remote.")
365 }