Debian Codegraph @

resources/resource_factories/create/create_integration_test.go

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