Update TLS examples to use better HTTP->HTTPS redirect #2792
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I tried to implement the redirect from the TLS examples in my project, and it didn't work - I like to use port 6789 when I'm testing things locally and this caused big problems. So I thought I'd try fixing it and filing a PR.
tl;dr: The redirect showcased in the TLS examples is very fragile, I am proposing a more robust alternative.
Motivation:
The HTTP->HTTPS redirect showcased in these examples changes the port with a simple find-and-replace over the entire authority, including the hostname. This works well in the median case but:
Custom HTTPS ports with default HTTP ports fail to redirect properly, as the HTTP port is not present in the string:
http://example.com
->https://example.com
(nothttps://example.com:4443
or whatever port you're using.) This is the one that bit me!IP addresses can be mangled:
http://80.80.80.80
->https://443.443.443.443
,http://[::80]
->https://[::443]
As, I think worst of all, can hostnames, like this real and very cool website:
http://io808.com
->https://io4438.com
!Solution:
I've written an alternative based on parsing into an Authority; this type's
.port()
should guarantee with aNone
return that the authority string is a bare hostname/IP, or withSome(port)
that the string ends with:{port}
and so we can safely strip that suffix. Adding new port only conditionally would be easy, but browsers tend to be smart about eliding unnecessary:443
s, so it seemed an overcomplication?I also changed the args, since this redirect solution doesn't actually need to know the HTTP port, and since clippy's suggestion to use an
&str
seemed reasonable.I'm not very expert at Rust, so hopefully my solution doesn't have any glaring problems! It may be better to simply use the
url
crate, as was proposed (and rejected) previously, but it was more fun for me to write this.