Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions OPERATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,9 @@ A request crosses the proxy before it reaches the site, so no single log answers

**The one routerless https `404` that is not a routing fault is the edge restarting.** It arrives on a hostname the proxy does serve, in a minute that also carries `502`s. The host side restarts the edge nightly and when it pushes a change during the day, and its documentation holds that schedule. The routes return within a minute. Such a window is an intentional update blip, so leave it alone. Investigate only a window that does not look like one, such as one that outlasts a restart or recurs with no `502` beside it.

Two properties of the Caddy side are worth knowing before parsing it. Its access log is `format console`, so each line is a timestamp, a level, and a logger name followed by a JSON object rather than being JSON itself, and a parser that assumes one object per line reads nothing. And `trusted_proxies` is what makes `client_ip` the reader rather than the proxy, which is the same setting "Serving" describes as a security boundary. Without it every request in the log appears to come from one internal address, and the inward pass cannot distinguish a reader from a health check.
**A hostname Cloudflare proxies adds a tier above Traefik, and that tier keeps no record you can read.** The free plan shows aggregates and a sample, never a line per request. A request its rules block or its cache answers therefore reaches no tier below. Cloudflare caches no HTML or JSON by default, and XML and text are not among its cached extensions. Every real-content `404` therefore still reaches Traefik. `robots.txt` is the one exception Cloudflare caches by default, and its `no-cache` answer has any copy revalidated before use. A file type it does cache is answered from Cloudflare for as long as the bundle's `Cache-Control` allows, which [`deploy/README.md`](./deploy/README.md#cache-lifetimes) sets. A count for `/media/` is then a floor, and a first sighting is still logged, which is all the inward pass needs. `ClientHost` on a proxied request is the forwarded chain rather than one address, where Traefik trusts Cloudflare's ranges. Without that trust Traefik strips the header, and the field is Cloudflare's own address, which a pass would read as a reader. That trust is the host side's setting. A client may send a chain of its own, and Cloudflare appends the address it saw. [`checks/log-review.jq`](./checks/log-review.jq) keeps the last element for that reason, and the `403` cross-check below does the same.

Two properties of the Caddy side are worth knowing before parsing it. Its access log is `format console`, so each line is a timestamp, a level, and a logger name followed by a JSON object. The line is not JSON itself, and a parser that assumes one object per line reads nothing. And `trusted_proxies` is what makes `client_ip` the reader rather than the proxy, which is the same setting "Serving" describes as a security boundary. Without it every request in the log appears to come from one internal address. The inward pass then cannot distinguish a reader from a health check. That holds only where Cloudflare does not proxy the hostname. Behind Cloudflare the forwarded chain can start with an address the client wrote. Caddy reads the chain from the left, so `client_ip` is then whatever the client chose. Nothing in the Caddyfile matches on it, so nothing is exposed. On a proxied hostname, read the reader from the last element of `ClientHost` in the edge log instead.

### Reading a 404 list without being fooled by it

Expand Down Expand Up @@ -362,7 +364,7 @@ set -euo pipefail
since="$(( ($(date -u +%s) - $(date -u -d "$start" +%s)) / 3600 + 1 ))h"
jq -r 'select(.DownstreamStatus == 403)
| select(.RequestHost == "blog.insanegenius.com" or .RequestHost == "viljoen.family")
| .ClientHost' window.jsonl | sort -u > blocked.txt
| .ClientHost | split(",") | last | ltrimstr(" ")' window.jsonl | sort -u > blocked.txt
ssh "$VPS_SSH_HOST" "docker exec crowdsec cscli alerts list --since $since -l 0 -o raw" |
cut -d, -f3 | sort -u > alerted.txt
ssh "$VPS_SSH_HOST" 'docker exec crowdsec cscli decisions list -a -l 0 -o raw' |
Expand Down
10 changes: 8 additions & 2 deletions checks/check-live-urls.sh
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,10 @@ check_render() {
[ "$code" = "200" ] || echo "render $url expected 200, got $code" >>"$FAILED"
}

# A caching proxy may answer a media URL from its copy for the file's lifetime, so a file a release lost would still pass.
# The edge's cache key includes the query string and the file server ignores it, so a query no earlier run sent reaches the origin.
CACHE_BUST="live-check=$(date +%s)-$$"

# Invoked indirectly, the same way as check_render above.
# shellcheck disable=SC2329
# The build gate proves the media SET against files on disk.
Expand All @@ -419,7 +423,7 @@ check_media() {
# The redirect URL gets a line of its own, because an empty one would let read shift the type into its place.
local format='%{http_code} %{size_download}\n%{redirect_url}\n%{content_type}\n'
# Command substitution rather than `read < <(...)`, because process substitution discards curl's exit status.
out=$(curl_retry -q -s -o /dev/null -w "$format" --max-time 30 "${auth[@]}" "$BASE$url") || rc=$?
out=$(curl_retry -q -s -o /dev/null -w "$format" --max-time 30 "${auth[@]}" "$BASE$url?$CACHE_BUST") || rc=$?
{
read -r code len
read -r target
Expand All @@ -446,6 +450,8 @@ check_media() {
esac
fi
what="media $url -> $target"
# The rule drops the query, so the hop needs its own.
target="$target?$CACHE_BUST"
rc=0
out=$(curl_retry -q -s -o /dev/null -w "$format" --max-time 30 "${target_auth[@]}" "$target") || rc=$?
{
Expand Down Expand Up @@ -524,7 +530,7 @@ check_redirect() {
}

export -f curl_retry transfer_failure check_render check_redirect check_media
export BASE FAILED CURLRC CHECKRC SAMPLE
export BASE FAILED CURLRC CHECKRC SAMPLE CACHE_BUST

echo "==> $BASE"

Expand Down
2 changes: 2 additions & 0 deletions checks/log-review.jq
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,5 @@ select(.["request_X-Blog-Check"] == null)
| select(.RequestHost == $blog or .RequestHost == $family)
| select(.DownstreamStatus == 404)
| select(scanner | not)
# Behind a proxy ClientHost is the forwarded chain, and its last element is the address Cloudflare saw.
| .ClientHost |= (split(",") | last | ltrimstr(" "))
20 changes: 19 additions & 1 deletion checks/tests/test_check_live_urls_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,9 @@ class Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self) -> None:
self.requested.append(self.path)
if self.path.startswith("/wp-content/uploads/"):
self.answer(301, location="/media/" + self.path.split("/uploads/", 1)[1])
# Caddy's rule drops the query, as here.
path = self.path.split("?", 1)[0]
self.answer(301, location="/media/" + path.split("/uploads/", 1)[1])
elif self.path.startswith(("/media/", "/external/")):
self.answer(200, body=b"\x89PNG", content_type="image/png")
elif self.path in self.redirects:
Expand Down Expand Up @@ -297,6 +299,22 @@ def test_full_run_is_the_default_and_follows_every_redirect(self) -> None:
self.assertIn(DESTINATION, requested)
self.assertEqual(non_static(requested), listed | {"/", DESTINATION})

def test_media_requests_carry_a_query_no_earlier_run_sent(self) -> None:
tokens = []
for _ in range(2):
with MockSite() as site:
result = run(SCRIPT, site.base)
requested = list(site.requested)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
media = [p for p in requested if p not in non_static(requested)]
self.assertTrue(any(p.startswith("/wp-content/") for p in media))
for p in media:
self.assertRegex(p, r"live-check=", p)
found = {re.findall(r"live-check=([^&]+)", p)[-1] for p in media}
self.assertEqual(len(found), 1, media)
tokens.append(found.pop())
self.assertNotEqual(tokens[0], tokens[1])


if __name__ == "__main__":
unittest.main()
19 changes: 18 additions & 1 deletion deploy/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,10 @@
}

route {
# Explicit lifetimes replace whatever heuristic a browser or an edge cache would apply, so a deploy shows at once.
# The baseline runs first so a redirect carries it too, and the file classes below override it.
header Cache-Control "no-cache"

redir @post_id {by_id} 301

# WordPress served every feed under a type suffix too, so dropping it hands the address to the bare feed's rule.
Expand Down Expand Up @@ -130,6 +134,12 @@
redir @mapped {mapped} 301
redir @mapped_slash {mapped_slash} 301

@fingerprinted path /assets/*
header @fingerprinted Cache-Control "public, max-age=31536000, immutable"
# An hour bounds how long a replaced image is still served from any copy.
@media path /media/* /*.png /*.ico
header @media Cache-Control "public, max-age=3600"

# The proxy forwards Accept-Encoding unchanged and adds no compression of its own.
# Serving the precompressed siblings here is what reaches the client.
file_server {
Expand All @@ -138,8 +148,12 @@
}

handle_errors {
# A missing file in a cached class would otherwise keep that class's lifetime.
header Cache-Control "no-cache"
rewrite * /404.html
file_server
file_server {
precompressed br gzip
}
}

log {
Expand Down Expand Up @@ -168,6 +182,8 @@ http://viljoen.family:8080, http://viljoen.vps.insanegenius.net:8080 {$FAMILY_SI
header @svg Cache-Control "public, max-age=604800"
@code path *.css *.js
header @code Cache-Control "no-cache"
@page not path *.svg *.css *.js
header @page Cache-Control "no-cache"

# The root follows the browser's first language, and /en/ and /af/ never redirect, so the language switch always holds.
@af_first {
Expand All @@ -186,6 +202,7 @@ http://viljoen.family:8080, http://viljoen.vps.insanegenius.net:8080 {$FAMILY_SI

# A single-page site has nowhere better to send a stray path than the page itself.
handle_errors {
header Cache-Control "no-cache"
@af_page path /af/*
handle @af_page {
rewrite * /af/index.html
Expand Down
Loading
Loading