tobogganSe connecter

packages

The Louise packages, each released on its own

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

942 lignes · 24964 octetsBrut · Historique
1// Fetches over loopback sockets (native only: the interpreter has no
2// sockets). They run when LOUISE_NET_TESTS is set, and are skipped
3// otherwise:
4//
5// LOUISE_NET_TESTS=1 louise test --native
6//
7// The servers are std/http, a raw TCP server that answers what it is
8// given, and a TLS server with the certificates of test/fixtures/tls
9// (`localhost` and `127.0.0.1`, from the "Louise test CA").
10
11import fetch.
12{ type Options
13, type PendingRequest
14, type RequestOutcome
15, type Response
16, AnyAddress
17, BadHeader
18, BadUrl
19, Cancelled
20, Completed
21, Connect
22, Malformed
23, NoAddress
24, Options
25, PublicOnly
26, Refused
27, Response
28, TimedOut
29, Tls
30}
31import std/bytes
32import std/ffi.{type Resource}
33import std/http.{type Request, Settings, Streamed, Whole}
34import std/list
35import std/net.{type TcpListener, type TcpStream}
36import std/option
37import std/os
38import std/process.{type Subject, type proc}
39import std/result
40import std/string
41import std/test.{assert, assert_equal}
42import std/time.{type clock}
43import std/tls.{type TlsConfig, type TlsServerConfig}
44import url.{type Url, Url}
45
46fn enabled :: -> Bool / <io>
47{
48 option.is_some (os.env "LOUISE_NET_TESTS")
49}
50
51fn fixture :: name: String -> String
52{
53 "test/fixtures/tls/" <> name
54}
55
56fn client_tls :: -> Resource<TlsConfig> / <io>
57{
58 result.expect
59 (tls.config (tls.with_ca_file (tls.defaults ()) (fixture "ca.pem")))
60 "the client's TLS configuration"
61}
62
63fn local :: -> Options / <io, clock>
64{
65 Options( ..fetch.options (client_tls ())
66 , policy: AnyAddress
67 , deadline: fetch.deadline_in 5000
68 )
69}
70
71fn at :: text: String -> Url
72{
73 result.expect (url.parse text) text
74}
75
76fn now_ms :: -> Int / <clock>
77{
78 time.in_milliseconds (time.monotonic ())
79}
80
81// ---- servers -------------------------------------------------------------------
82
83/// A std/http server for `connections` connections; its port.
84fn http_server :: connections: Int -> Int / <io, proc>
85{
86 let server = result.expect (http.listen "127.0.0.1" 0) "listen"
87 let port = net.port server
88 let _ =
89 process.spawn
90 fn
91 {
92 http.serve_with
93 server
94 Settings(..http.defaults (), connections: connections)
95 fn req { handler req }
96 }
97 port
98}
99
100fn handler :: req: Request -> http.Response
101{
102 match http.path req
103 { "/hello" -> http.text 200 "hello"
104 , "/no-content" -> no_body_response 204
105 , "/not-modified" -> no_body_response 304
106 , "/chunked" ->
107 http.Response( 200
108 , [("Content-Type", "text/plain")]
109 , Streamed(fn w { pieces w ["hel", "lo"] })
110 )
111 , "/big" -> http.response 200 "text/plain" (filled 102400)
112 , "/big-chunked" ->
113 http.Response( 200
114 , [("Content-Type", "text/plain")]
115 , Streamed( fn w
116 {
117 pieces
118 w
119 (list.map (list.range 1 10) fn _ { string.repeat "x" 10240 })
120 }
121 )
122 )
123 , "/redirect" ->
124 http.Response(302, [("Location", "/hello")], Whole(bytes.empty ()))
125 // what came: the method, the length it said, the body
126 , "/echo" ->
127 http.text
128 200
129 "{req.method} {option.unwrap_or (http.header req "Content-Length") "-"} {bytes.to_string_lossy req.body}"
130 , _ -> http.not_found ()
131 }
132}
133
134fn no_body_response :: status: Int -> http.Response
135{
136 http.Response( status
137 , [("ETag", "\"v1\""), ("Cache-Control", "max-age=60")]
138 , Whole(bytes.from_string "not sent")
139 )
140}
141
142fn pieces :: w: http.Writer texts: List<String> -> () / <io, proc>
143{
144 match texts
145 { [] -> ()
146 , [t, ..rest] -> match http.write_string w t
147 { Ok(_) -> pieces w rest, Error(_) -> () }
148 }
149}
150
151fn filled :: n: Int -> Bytes
152{
153 bytes.from_string (string.repeat "x" n)
154}
155
156/// A server for one connection: it reads the request head, writes what
157/// `answer` makes of it, and closes.
158fn raw_server :: answer: send fn(Bytes) -> Bytes -> Int / <io, proc>
159{
160 let listener = result.expect (net.listen "127.0.0.1" 0) "listen"
161 let port = net.port listener
162 let _ = process.spawn fn { answer_once listener answer }
163 port
164}
165
166fn answer_once ::
167 listener: Resource<TcpListener>
168 answer: fn(Bytes) -> Bytes
169 -> () / <io>
170{
171 match net.accept listener
172 { Ok(conn) ->
173 {
174 let request = head_from conn (bytes.empty ())
175 let _ = net.write conn (answer request)
176 net.close conn
177 }
178 , Error(_) -> ()
179 }
180}
181
182fn head_from :: conn: Resource<TcpStream> have: Bytes -> Bytes / <io>
183{
184 if string.contains (bytes.to_string_lossy have) "\r\n\r\n"
185 {
186 have
187 }
188 else
189 {
190 match net.read conn 4096
191 { Ok(more) if bytes.length more > 0 ->
192 head_from conn (bytes.concat have more)
193 , _ -> have
194 }
195 }
196}
197
198fn answering :: text: String -> Int / <io, proc>
199{
200 raw_server fn _ { bytes.from_string text }
201}
202
203/// A server that accepts and never answers.
204fn stalling_server :: -> Int / <io, proc>
205{
206 let listener = result.expect (net.listen "127.0.0.1" 0) "listen"
207 let port = net.port listener
208 let _ =
209 process.spawn
210 fn
211 {
212 match net.accept listener
213 { Ok(conn) ->
214 {
215 process.sleep 10000
216 net.close conn
217 }
218 , Error(_) -> ()
219 }
220 }
221 port
222}
223
224type CancellationPoint
225{ BeforeResponse, DuringBody, TlsHandshake, LateResponse }
226
227/// One server connection at a known stall. The server, not the waiting
228/// caller, owns the cancellation-handoff subject. It cancels twice and then
229/// reports whether it observed the client close.
230fn cancelling_server ::
231 point: CancellationPoint
232 -> (Int, Subject<PendingRequest>, Subject<Bool>) / <io, proc>
233{
234 let listener = result.expect (net.listen "127.0.0.1" 0) "listen"
235 let port = net.port listener
236 let handoff = process.subject ()
237 let closed = process.subject ()
238 let _ =
239 process.spawn
240 fn
241 {
242 let requests = process.subject ()
243 process.send handoff requests
244 match net.accept listener
245 { Ok(conn) ->
246 {
247 match point
248 { TlsHandshake ->
249 {
250 let _ = net.read conn 4096
251 ()
252 }
253 , _ ->
254 {
255 let _ = head_from conn (bytes.empty ())
256 ()
257 }
258 }
259 match point
260 { DuringBody ->
261 {
262 let _ =
263 net.write
264 conn
265 ( bytes.from_string
266 "HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial"
267 )
268 // Let the exchange consume the head and enter its body read.
269 // The assertion still waits on the observed close, not this pause.
270 process.sleep 50
271 }
272 , _ -> ()
273 }
274 match process.receive requests 5000
275 { Some(pending) ->
276 {
277 fetch.cancel_request pending
278 fetch.cancel_request pending
279 }
280 , None -> ()
281 }
282 match point
283 { LateResponse ->
284 {
285 let _ =
286 net.write
287 conn
288 ( bytes.from_string
289 "HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nlate"
290 )
291 ()
292 }
293 , _ -> ()
294 }
295 let did_close = until_closed conn
296 net.close conn
297 process.send closed did_close
298 }
299 , Error(_) -> process.send closed False
300 }
301 }
302 match process.receive handoff 5000
303 { Some(requests) -> (port, requests, closed)
304 , None -> panic "the server never sent its request handoff"
305 }
306}
307
308fn until_closed :: conn: Resource<TcpStream> -> Bool / <io>
309{
310 match net.read conn 4096
311 { Ok(more) if bytes.length more > 0 -> until_closed conn
312 , Ok(_) -> True
313 , Error(_) -> True
314 }
315}
316
317/// A TLS server for one connection with `cert`; it answers `text`, then
318/// ends the TLS stream properly or (`clean` false) just closes the socket.
319fn tls_server :: cert: String text: String clean: Bool -> Int / <io, proc>
320{
321 let config =
322 result.expect
323 ( tls.server_config
324 ( tls.server_options
325 (fixture (cert <> ".pem"))
326 (fixture (cert <> ".key"))
327 )
328 )
329 "the server's TLS configuration"
330 let listener = result.expect (net.listen "127.0.0.1" 0) "listen"
331 let port = net.port listener
332 let _ = process.spawn fn { tls_once listener config text clean }
333 port
334}
335
336fn tls_once ::
337 listener: Resource<TcpListener>
338 config: Resource<TlsServerConfig>
339 text: String
340 clean: Bool
341 -> () / <io>
342{
343 match net.accept listener
344 { Ok(conn) -> match tls.accept conn config
345 { Ok(stream) ->
346 {
347 let _ = tls.read stream 65536
348 let _ = tls.write_string stream text
349 if clean
350 {
351 tls.close stream
352 }
353 else
354 {
355 net.close conn
356 }
357 }
358 , Error(_) -> net.close conn
359 }
360 , Error(_) -> ()
361 }
362}
363
364fn body_text ::
365 answer: Result<Response, fetch.Error>
366 -> Result<(Int, String, Bool), fetch.Error>
367{
368 answer
369 |> result.map fn r { (r.status, bytes.to_string_lossy r.body, r.truncated) }
370}
371
372fn pending_get ::
373 scheme: String
374 port: Int
375 opts: Options
376 -> PendingRequest / <proc, clock>
377{
378 result.expect
379 ( fetch.start_request
380 "GET"
381 (at "{scheme}://127.0.0.1:{port}/")
382 []
383 (bytes.empty ())
384 opts
385 )
386 "start the request"
387}
388
389fn completed_body ::
390 outcome: RequestOutcome
391 -> Result<(Int, String, Bool), fetch.Error>
392{
393 match outcome
394 { Completed(answer) -> body_text answer
395 , Cancelled -> Error(Malformed("the test request was cancelled"))
396 }
397}
398
399fn expect_cancelled ::
400 point: CancellationPoint
401 scheme: String
402 -> () / <io, proc, clock>
403{
404 let (port, requests, closed) = cancelling_server point
405 let pending = pending_get scheme port (local ())
406 process.send requests pending
407 match fetch.await_request pending
408 { Cancelled -> ()
409 , Completed(answer) -> panic "a cancelled request completed: {show answer}"
410 }
411 fetch.cancel_request pending
412 fetch.cancel_request pending
413 assert_equal (process.receive closed 3000) Some(True)
414}
415
416// ---- bodies --------------------------------------------------------------------
417
418@test
419fn a_body_by_content_length :: -> () / <io, proc, clock>
420{
421 if enabled ()
422 {
423 let port = http_server 1
424 let answer = fetch.get (at "http://127.0.0.1:{port}/hello") [] (local ())
425 assert_equal (body_text answer) Ok((200, "hello", False))
426 match answer
427 { Ok(resp) -> assert_equal (fetch.header resp "CONTENT-LENGTH") Some("5")
428 , Error(_) -> ()
429 }
430 }
431}
432
433@test
434fn final_statuses_without_bodies_reach_the_client :: -> () / <io, proc, clock>
435{
436 if enabled ()
437 {
438 let port = http_server 2
439 let no_content =
440 fetch.get (at "http://127.0.0.1:{port}/no-content") [] (local ())
441 assert_equal (body_text no_content) Ok((204, "", False))
442 match no_content
443 { Ok(resp) ->
444 {
445 assert_equal (fetch.header resp "Content-Length") None
446 assert_equal (fetch.header resp "Transfer-Encoding") None
447 assert_equal (fetch.header resp "ETag") Some("\"v1\"")
448 assert_equal (fetch.header resp "Cache-Control") Some("max-age=60")
449 }
450 , Error(e) -> panic (show e)
451 }
452 let not_modified =
453 fetch.get (at "http://127.0.0.1:{port}/not-modified") [] (local ())
454 assert_equal (body_text not_modified) Ok((304, "", False))
455 match not_modified
456 { Ok(resp) ->
457 {
458 assert_equal (fetch.header resp "Content-Length") None
459 assert_equal (fetch.header resp "Transfer-Encoding") None
460 assert_equal (fetch.header resp "ETag") Some("\"v1\"")
461 assert_equal (fetch.header resp "Cache-Control") Some("max-age=60")
462 }
463 , Error(e) -> panic (show e)
464 }
465 }
466}
467
468@test
469fn a_chunked_body :: -> () / <io, proc, clock>
470{
471 if enabled ()
472 {
473 let port = http_server 1
474 assert_equal
475 ( body_text
476 (fetch.get (at "http://127.0.0.1:{port}/chunked") [] (local ()))
477 )
478 Ok((200, "hello", False))
479 }
480}
481
482@test
483fn a_body_until_the_server_closes :: -> () / <io, proc, clock>
484{
485 if enabled ()
486 {
487 let port =
488 answering "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\nall of it"
489 assert_equal
490 (body_text (fetch.get (at "http://127.0.0.1:{port}/") [] (local ())))
491 Ok((200, "all of it", False))
492 let port = answering "HTTP/1.0 200 OK\r\n\r\nall of it"
493 assert_equal
494 ( body_text
495 ( fetch.get
496 (at "http://127.0.0.1:{port}/")
497 []
498 Options(..local (), max_body: 3)
499 )
500 )
501 Ok((200, "all", True))
502 }
503}
504
505@test
506fn bodies_are_cut_at_max_body :: -> () / <io, proc, clock>
507{
508 if enabled ()
509 {
510 let port = http_server 2
511 let opts = Options(..local (), max_body: 1000)
512 assert_equal
513 (body_text (fetch.get (at "http://127.0.0.1:{port}/big") [] opts))
514 Ok((200, string.repeat "x" 1000, True))
515 assert_equal
516 (body_text (fetch.get (at "http://127.0.0.1:{port}/big-chunked") [] opts))
517 Ok((200, string.repeat "x" 1000, True))
518 }
519}
520
521@test
522fn informational_responses_are_skipped :: -> () / <io, proc, clock>
523{
524 if enabled ()
525 {
526 let port =
527 answering
528 "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 103 Early Hints\r\nLink: </a.css>\r\n\r\nHTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"
529 assert_equal
530 (body_text (fetch.get (at "http://127.0.0.1:{port}/") [] (local ())))
531 Ok((200, "ok", False))
532 }
533}
534
535@test
536fn a_redirect_is_returned_not_followed :: -> () / <io, proc, clock>
537{
538 if enabled ()
539 {
540 let port = http_server 1
541 match fetch.get (at "http://127.0.0.1:{port}/redirect") [] (local ())
542 { Ok(resp) ->
543 {
544 assert_equal resp.status 302
545 assert_equal (fetch.header resp "location") Some("/hello")
546 }
547 , Error(e) -> panic (show e)
548 }
549 }
550}
551
552@test
553fn what_is_sent :: -> () / <io, proc, clock>
554{
555 if enabled ()
556 {
557 let port =
558 raw_server
559 fn request
560 {
561 bytes.concat
562 ( bytes.from_string
563 "HTTP/1.1 200 OK\r\nContent-Length: {bytes.length request}\r\n\r\n"
564 )
565 request
566 }
567 let headers =
568 [ ("User-Agent", "test/1")
569 , ("Host", "evil.example")
570 , ("accept-encoding", "gzip")
571 , ("Connection", "keep-alive")
572 , ("Accept", "text/html")
573 ]
574 let answer =
575 fetch.get (at "http://127.0.0.1:{port}/a b/é?q=1#frag") headers (local ())
576 assert_equal
577 (body_text answer)
578 Ok( ( 200
579 , "GET /a%20b/%C3%A9?q=1 HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\nAccept-Encoding: identity\r\nUser-Agent: test/1\r\nAccept: text/html\r\n\r\n"
580 , False
581 )
582 )
583 }
584}
585
586// ---- requests with a body --------------------------------------------------------
587
588@test
589fn a_post_sends_its_body_and_its_length :: -> () / <io, proc, clock>
590{
591 if enabled ()
592 {
593 let port = http_server 3
594 let post = fn headers body
595 {
596 fetch.request
597 "POST"
598 (at "http://127.0.0.1:{port}/echo")
599 headers
600 (bytes.from_string body)
601 (local ())
602 |> body_text
603 }
604 assert_equal
605 (post [("Content-Type", "application/json")] "\{\"a\":\"é\"\}")
606 Ok((200, "POST 10 \{\"a\":\"é\"\}", False))
607 // the caller's own length is dropped for the body's
608 assert_equal
609 (post [("Content-Length", "999")] "abc")
610 Ok((200, "POST 3 abc", False))
611 // an empty POST still says its length
612 assert_equal (post [] "") Ok((200, "POST 0 ", False))
613 }
614}
615
616@test
617fn a_method_that_is_not_a_token_is_refused :: -> () / <io, proc, clock>
618{
619 if enabled ()
620 {
621 match fetch.request
622 "GE T"
623 (at "http://127.0.0.1:1/")
624 []
625 (bytes.empty ())
626 (local ())
627 { Error(fetch.BadHeader(_)) -> ()
628 , other -> panic "expected BadHeader, got {other}"
629 }
630 }
631}
632
633// ---- failures ------------------------------------------------------------------
634
635@test
636fn malformed_responses :: -> () / <io, proc, clock>
637{
638 if enabled ()
639 {
640 let malformed = fn text
641 {
642 let port = answering text
643 match fetch.get (at "http://127.0.0.1:{port}/") [] (local ())
644 { Error(Malformed(_)) -> True, _ -> False }
645 }
646 assert
647 (malformed "HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip\r\n\r\nxx")
648 "malformed HTTP/1.1 200 OKrnTransfer-Encoding: gziprnrnxx"
649 assert
650 (malformed "HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nabc")
651 "malformed HTTP/1.1 200 OKrnContent-Length: 10rnrnabc"
652 assert
653 (malformed "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nab")
654 "malformed HTTP/1.1 200 OKrnTransfer-Encoding: chunkedrnrn5rnab"
655 assert
656 (malformed "SSH-2.0-OpenSSH_9.6\r\n\r\n")
657 "malformed SSH-2.0-OpenSSH_9.6rnrn"
658 assert (malformed "") "malformed "
659 assert
660 ( malformed
661 ("HTTP/1.1 200 OK\r\nX: " <> string.repeat "a" 70000 <> "\r\n\r\n")
662 )
663 "malformed (HTTP/1.1 200 OKrnX: <> string.repeat a 70000 <> rnrn)"
664 }
665}
666
667@test
668fn public_only_refuses_loopback :: -> () / <io, proc, clock>
669{
670 if enabled ()
671 {
672 let opts = Options(..local (), policy: PublicOnly)
673 assert_equal
674 (fetch.get (at "http://127.0.0.1:9/") [] opts)
675 Error(Refused("127.0.0.1", "127.0.0.1"))
676 assert_equal
677 (fetch.get (at "http://[::1]:9/") [] opts)
678 Error(Refused("::1", "::1"))
679 match fetch.get (at "http://localhost:9/") [] opts
680 { Error(Refused("localhost", _)) -> ()
681 , other -> panic "localhost: {show other}"
682 }
683 }
684}
685
686@test
687fn a_stalling_server_times_out :: -> () / <io, proc, clock>
688{
689 if enabled ()
690 {
691 let port = stalling_server ()
692 let start = now_ms ()
693 let opts = Options(..local (), deadline: fetch.deadline_in 300)
694 assert_equal
695 (fetch.get (at "http://127.0.0.1:{port}/") [] opts)
696 Error(TimedOut)
697 let took = now_ms () - start
698 assert (took >= 250 && took < 2000) "took >= 250 && took < 2000"
699 }
700}
701
702@test
703fn refused_before_any_connection :: -> () / <io, proc, clock>
704{
705 if enabled ()
706 {
707 let opts = local ()
708 assert
709 (is_bad_url (fetch.get (at "ftp://127.0.0.1/") [] opts))
710 "is_bad_url (fetch.get (at ftp://127.0.0.1/) [] opts)"
711 assert
712 ( is_bad_url
713 (fetch.get (Url("http", "a\r\nb", None, "/", None, None)) [] opts)
714 )
715 "is_bad_url (fetch.get (Url(http, arnb, None, /, None, None)) [] opts)"
716 assert
717 ( is_bad_url (fetch.get (Url("http", "a", None, "/", None, None)) [] opts)
718 == False
719 )
720 "is_bad_url (fetch.get (Url(http, a, None, /, None, None)) [] opts) ..."
721 assert_equal
722 (fetch.get (at "http://127.0.0.1:9/") [("X\r\nY", "1")] opts)
723 Error(BadHeader("X\r\nY"))
724 assert_equal
725 (fetch.get (at "http://127.0.0.1:9/") [("X", "1\r\nY: 2")] opts)
726 Error(BadHeader("X"))
727 assert_equal
728 (fetch.get (at "http://127.0.0.1:9/") [("Bad Name", "1")] opts)
729 Error(BadHeader("Bad Name"))
730 assert_equal
731 ( fetch.get
732 (at "http://127.0.0.1:9/")
733 []
734 Options(..opts, deadline: fetch.deadline_in (-1))
735 )
736 Error(TimedOut)
737 }
738}
739
740fn is_bad_url :: answer: Result<Response, fetch.Error> -> Bool
741{
742 match answer { Error(BadUrl(_)) -> True, _ -> False }
743}
744
745@test
746fn nothing_listening :: -> () / <io, proc, clock>
747{
748 if enabled ()
749 {
750 let listener = result.expect (net.listen "127.0.0.1" 0) "listen"
751 let port = net.port listener
752 net.close_listener listener
753 match fetch.get (at "http://127.0.0.1:{port}/") [] (local ())
754 { Error(Connect(_)) -> (), other -> panic (show other) }
755 }
756}
757
758@test
759fn a_name_that_does_not_resolve :: -> () / <io, proc, clock>
760{
761 if enabled ()
762 {
763 match fetch.get (at "http://louise-fetch-test.invalid/") [] (local ())
764 { Error(NoAddress("louise-fetch-test.invalid")) -> ()
765 , Error(TimedOut) -> ()
766 , other -> panic (show other)
767 }
768 }
769}
770
771/// A kill can only land between two steps of the worker: one waiting in
772/// `net.resolve` (on the `io` blocking pool) is killed when the lookup
773/// returns (`runtime/louise_rt/src/blocking.rs`). `get` does not wait
774/// for that: it answers `TimedOut` at the deadline, and the worker's late
775/// reply, if any, is dropped. Whether a 1 ms deadline lands inside the
776/// lookup depends on the resolver, so this checks the outcome, not where
777/// the kill landed.
778@test
779fn a_deadline_during_the_lookup :: -> () / <io, proc, clock>
780{
781 if enabled ()
782 {
783 list.each
784 (list.range 1 10)
785 fn ms
786 {
787 let start = now_ms ()
788 let opts = Options(..local (), deadline: fetch.deadline_in ms)
789 match fetch.get (at "http://louise-fetch-test-{ms}.invalid/") [] opts
790 { Error(TimedOut) | Error(NoAddress(_)) -> ()
791 , other -> panic (show other)
792 }
793 assert (now_ms () - start < ms + 1000) "now_ms () - start < ms + 1000"
794 }
795 let port = http_server 1
796 assert_equal
797 (body_text (fetch.get (at "http://127.0.0.1:{port}/hello") [] (local ())))
798 Ok((200, "hello", False))
799 }
800}
801
802// ---- cancellable collected requests ----------------------------------------------
803
804@test
805fn pending_success_and_late_cancellation_do_not_touch_a_new_request ::
806 -> () / <io, proc, clock>
807{
808 if enabled ()
809 {
810 let answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"
811 let first = pending_get "http" (answering answer) (local ())
812 assert_equal
813 (completed_body (fetch.await_request first))
814 Ok((200, "ok", False))
815
816 // Start the next exchange before repeatedly stopping the retired handle.
817 // A confused or reused identity would kill this request too.
818 let second = pending_get "http" (answering answer) (local ())
819 fetch.cancel_request first
820 fetch.cancel_request first
821 assert_equal
822 (completed_body (fetch.await_request second))
823 Ok((200, "ok", False))
824 }
825}
826
827@test
828fn cancellation_before_the_response_releases_every_exchange ::
829 -> () / <io, proc, clock>
830{
831 if enabled ()
832 {
833 list.each (list.range 1 20) fn _ { expect_cancelled BeforeResponse "http" }
834 }
835}
836
837@test
838fn cancellation_during_body_collection_closes_the_connection ::
839 -> () / <io, proc, clock>
840{
841 if enabled ()
842 {
843 expect_cancelled DuringBody "http"
844 }
845}
846
847@test
848fn cancellation_during_a_tls_handshake_closes_its_socket ::
849 -> () / <io, proc, clock>
850{
851 if enabled ()
852 {
853 expect_cancelled TlsHandshake "https"
854 }
855}
856
857@test
858fn a_response_written_after_cancellation_is_not_a_success ::
859 -> () / <io, proc, clock>
860{
861 if enabled ()
862 {
863 list.each (list.range 1 20) fn _ { expect_cancelled LateResponse "http" }
864 }
865}
866
867@test
868fn a_pending_request_keeps_the_deadline_behavior :: -> () / <io, proc, clock>
869{
870 if enabled ()
871 {
872 let opts = Options(..local (), deadline: fetch.deadline_in 200)
873 let pending = pending_get "http" (stalling_server ()) opts
874 assert_equal (fetch.await_request pending) Completed(Error(TimedOut))
875 fetch.cancel_request pending
876
877 // Time spent between start and await must not turn an elapsed deadline
878 // into the negative timeout that means "wait forever" in std/process.
879 let opts = Options(..local (), deadline: fetch.deadline_in 50)
880 let pending = pending_get "http" (stalling_server ()) opts
881 process.sleep 100
882 assert_equal (fetch.await_request pending) Completed(Error(TimedOut))
883 fetch.cancel_request pending
884 }
885}
886
887// ---- TLS -----------------------------------------------------------------------
888
889@test
890fn https_with_a_private_authority :: -> () / <io, proc, clock>
891{
892 if enabled ()
893 {
894 let port =
895 tls_server
896 "localhost"
897 "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok"
898 True
899 assert_equal
900 (body_text (fetch.get (at "https://localhost:{port}/") [] (local ())))
901 Ok((200, "ok", False))
902 }
903}
904
905@test
906fn a_tls_close_without_close_notify_ends_the_body :: -> () / <io, proc, clock>
907{
908 if enabled ()
909 {
910 let port =
911 tls_server "localhost" "HTTP/1.1 200 OK\r\n\r\nuntil the end" False
912 assert_equal
913 (body_text (fetch.get (at "https://127.0.0.1:{port}/") [] (local ())))
914 Ok((200, "until the end", False))
915 }
916}
917
918@test
919fn a_certificate_for_another_name_is_refused :: -> () / <io, proc, clock>
920{
921 if enabled ()
922 {
923 let port = tls_server "other-host" "HTTP/1.1 200 OK\r\n\r\nno" True
924 match fetch.get (at "https://localhost:{port}/") [] (local ())
925 { Error(Tls(_)) -> (), other -> panic (show other) }
926 }
927}
928
929@test
930fn an_unknown_authority_is_refused :: -> () / <io, proc, clock>
931{
932 if enabled ()
933 {
934 let port = tls_server "localhost" "HTTP/1.1 200 OK\r\n\r\nno" True
935 let opts =
936 Options( ..local ()
937 , tls: result.expect (tls.config (tls.defaults ())) "Mozilla's roots"
938 )
939 match fetch.get (at "https://localhost:{port}/") [] opts
940 { Error(Tls(_)) -> (), other -> panic (show other) }
941 }
942}