carlos / platform Public

console: bound sign-in codes, SES events and log shipping

Fixes from the 11-16 hunt follow-ups (console availability), with
Paul's rulings:
- Sign-in and step-up codes: one rule per sign-in flow for replacing a
  challenge, suppressing repeats and resetting attempts; wrong guesses
  are capped per client network across challenges, never per address;
  held and sent flows look the same.
- SES events can move to a secret path (CARLOS_SES_EVENTS_TOKEN): any
  other path gets 404 before the body is read; a certificate the console
  cannot fetch right now gets 503 so SNS retries.
- Log and error shipping confirm stored bytes before advancing, so a
  lost acknowledgement no longer strands later chunks.

Rollout: the SES subscription switch is a window step (README).
Reviews: Astra, three rounds; census approved (Astra). Copy approved.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from sec-console-dos into main.
claude agent, operated by paul@keymail.dev 60f0dc350447c30aa154984449f9411d1c1077eb parent 7dbd8e1
48 files changed, +2,570 −315
  • .amadan/code-health.tsv +3 −6
  • README.md +19 −0
  • cmd/console/main.go +18 −9
  • docs/parity.md +1 −1
  • docs/superpowers/notes/census-proposal-sec-console-dos.md +11 −0
  • docs/superpowers/specs/2026-10-21-console-email-signin-copy-approved.json +2 −2
  • internal/apperr/read.go +6 −0
  • internal/applog/chunk.go +92 −1
  • internal/applog/chunk_test.go +65 −0
  • internal/applog/read.go +17 −4
  • internal/applog/read_test.go +29 −0
  • internal/console/claim_invariant_fixtures_test.go +24 −0
  • internal/console/claim_invariant_probes_nonapp_test.go +1 −1
  • internal/console/demo_claim_auth.go +3 −6
  • internal/console/demo_claim_auth_test.go +3 −11
  • internal/console/demo_claim_page.go +3 −6
  • internal/console/emailsignin.go +48 −11
  • internal/console/emailsignin_limits.go +93 −23
  • internal/console/emailsignin_limits_test.go +101 −46
  • internal/console/emailsignin_lockout_test.go +197 −0
  • internal/console/emailsignin_oracle_test.go +199 −0
  • internal/console/emailsignin_store.go +104 −66
  • internal/console/emailsignin_store_test.go +145 −30
  • internal/console/emailsignin_test.go +10 −8
  • internal/console/hunt_H4-M5_test.go +57 −0
  • internal/console/hunt_H4-M6_test.go +108 −0
  • internal/console/hunt_H4-M8_test.go +60 −0
  • internal/console/hunt_H5-M12_test.go +88 −0
  • internal/console/hunt_H5-M7_test.go +59 −0
  • internal/console/instances.go +10 −0
  • internal/console/lifetimes_cutover.go +2 −0
  • internal/console/newperson_test.go +5 −1
  • internal/console/perfwalk_test.go +2 −2
  • internal/console/routedecls.go +3 −0
  • internal/console/server.go +12 −34
  • internal/console/sesevents.go +277 −13
  • internal/console/sesevents_test.go +362 −2
  • internal/console/signincopy.go +1 −1
  • internal/console/testdata/claim-routes.txt +1 −0
  • internal/host/errship.go +22 −13
  • internal/host/errship_test.go +37 −0
  • internal/host/logship.go +48 −16
  • internal/host/logship_test.go +177 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/sec_console_dos_census_test.go +37 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv +5 −0
  • parity/parity.tsv +1 −1

CI passed — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-vfR8ie
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2/service/s3 v1.105.0
go: downloading github.com/aws/smithy-go v1.28.1
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading github.com/aws/aws-sdk-go-v2/service/iam v1.58.2
go: downloading github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1
go: downloading golang.org/x/crypto v0.58.0
go: downloading golang.org/x/sys v0.49.0
go: downloading github.com/pion/logging v0.2.4
go: downloading github.com/pion/stun/v3 v3.1.5
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.14
go: downloading github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.23
go: downloading github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading golang.org/x/text v0.43.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/mathutil v1.7.1
=== launchctx (5 s, from +0 s)
ok  	amadan.net/carlos/platform.git/launchctx	0.016s
?   	amadan.net/carlos/platform.git/launchctx/controlname	[no test files]
?   	amadan.net/carlos/platform.git/launchctx/wireid	[no test files]
=== vet (178 s, from +0 s)
go: downloading github.com/klauspost/compress v1.20.2
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/google/uuid v1.6.0
=== vet-tags (197 s, from +0 s)
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
=== gofmt (2 s, from +0 s)
gofmt -l .: clean
=== rest (405 s, from +15 s)
ok  	github.com/carlosframework/platform/cmd/carlos-media	135.000s
?   	github.com/carlosframework/platform/cmd/changelog	[no test files]
ok  	github.com/carlosframework/platform/cmd/console	221.434s
ok  	github.com/carlosframework/platform/cmd/mediaimage	43.078s
ok  	github.com/carlosframework/platform/cmd/moveprobe	14.673s
ok  	github.com/carlosframework/platform/cmd/pricebook-export	0.047s
ok  	github.com/carlosframework/platform/cmd/rootfswitness	0.149s
ok  	github.com/carlosframework/platform/cmd/runsc-assets	0.134s
ok  	github.com/carlosframework/platform/cmd/zddprobe	1.130s
ok  	github.com/carlosframework/platform/internal/agentsock	0.063s
ok  	github.com/carlosframework/platform/internal/alerting	0.021s
ok  	github.com/carlosframework/platform/internal/analytics	0.293s
ok  	github.com/carlosframework/platform/internal/appconfig	43.267s
ok  	github.com/carlosframework/platform/internal/apperr	0.346s
ok  	github.com/carlosframework/platform/internal/applog	3.765s
ok  	github.com/carlosframework/platform/internal/apppolicy	2.555s
ok  	github.com/carlosframework/platform/internal/assetcache	0.499s
ok  	github.com/carlosframework/platform/internal/awsinv	0.018s
ok  	github.com/carlosframework/platform/internal/awsmanaged	6.609s
ok  	github.com/carlosframework/platform/internal/awsregiongroup	0.152s
ok  	github.com/carlosframework/platform/internal/awsterminations	0.015s
ok  	github.com/carlosframework/platform/internal/backupswords	0.018s
ok  	github.com/carlosframework/platform/internal/billing	0.109s
ok  	github.com/carlosframework/platform/internal/billing/billingtest	0.060s
ok  	github.com/carlosframework/platform/internal/billingstripe	1.871s
ok  	github.com/carlosframework/platform/internal/boxchoice	0.027s
ok  	github.com/carlosframework/platform/internal/boxid	2.446s
?   	github.com/carlosframework/platform/internal/boxid/boxidtest	[no test files]
?   	github.com/carlosframework/platform/internal/boxid/internal/signtest	[no test files]
ok  	github.com/carlosframework/platform/internal/boxroles	0.016s
ok  	github.com/carlosframework/platform/internal/boxself	0.138s
ok  	github.com/carlosframework/platform/internal/boxvolumes	0.079s
ok  	github.com/carlosframework/platform/internal/caps	3.862s
ok  	github.com/carlosframework/platform/internal/certwarm	0.007s
ok  	github.com/carlosframework/platform/internal/cgroup	1.460s
ok  	github.com/carlosframework/platform/internal/changelog	4.730s
ok  	github.com/carlosframework/platform/internal/clamd	0.063s
?   	github.com/carlosframework/platform/internal/cliflag	[no test files]
ok  	github.com/carlosframework/platform/internal/clireg	0.011s
ok  	github.com/carlosframework/platform/internal/codehealth	16.273s
ok  	github.com/carlosframework/platform/internal/compute	0.014s
ok  	github.com/carlosframework/platform/internal/consolefleet	0.005s
?   	github.com/carlosframework/platform/internal/controlname	[no test files]
?   	github.com/carlosframework/platform/internal/controlsock	[no test files]
ok  	github.com/carlosframework/platform/internal/dbdoor	10.877s
ok  	github.com/carlosframework/platform/internal/dbdoor/dbdoortest	0.060s
ok  	github.com/carlosframework/platform/internal/dbquery	0.022s
ok  	github.com/carlosframework/platform/internal/dbreads	3.043s
?   	github.com/carlosframework/platform/internal/dbreads/dbreadstest	[no test files]
ok  	github.com/carlosframework/platform/internal/dbverify	0.031s
ok  	github.com/carlosframework/platform/internal/demo	0.014s
ok  	github.com/carlosframework/platform/internal/demobuild	4.744s
ok  	github.com/carlosframework/platform/internal/democlaim	0.322s
ok  	github.com/carlosframework/platform/internal/devbox	13.595s
ok  	github.com/carlosframework/platform/internal/dnsrec	0.006s
ok  	github.com/carlosframework/platform/internal/docsite	0.148s
ok  	github.com/carlosframework/platform/internal/domainreg	0.025s
ok  	github.com/carlosframework/platform/internal/domains	72.916s
ok  	github.com/carlosframework/platform/internal/doorkey	0.039s
ok  	github.com/carlosframework/platform/internal/economics	0.024s
ok  	github.com/carlosframework/platform/internal/edgefence	0.090s
ok  	github.com/carlosframework/platform/internal/edgeguard	0.199s
?   	github.com/carlosframework/platform/internal/edgeproof	[no test files]
ok  	github.com/carlosframework/platform/internal/edgesfile	0.141s
ok  	github.com/carlosframework/platform/internal/egressaddr	0.007s
ok  	github.com/carlosframework/platform/internal/execsandbox	99.802s
ok  	github.com/carlosframework/platform/internal/fileacl	0.007s
ok  	github.com/carlosframework/platform/internal/fleetapi	2.141s
ok  	github.com/carlosframework/platform/internal/fleetstore	0.042s
ok  	github.com/carlosframework/platform/internal/fxrate	0.025s
ok  	github.com/carlosframework/platform/internal/gate	4.138s
ok  	github.com/carlosframework/platform/internal/genselect	0.116s
ok  	github.com/carlosframework/platform/internal/geo	0.052s
ok  	github.com/carlosframework/platform/internal/geoip	0.087s
ok  	github.com/carlosframework/platform/internal/groupadmission	0.010s
ok  	github.com/carlosframework/platform/internal/grouprollaws	17.404s
ok  	github.com/carlosframework/platform/internal/hadeparture	0.019s
ok  	github.com/carlosframework/platform/internal/hafresh	0.009s
ok  	github.com/carlosframework/platform/internal/hairpin	0.222s
ok  	github.com/carlosframework/platform/internal/historyreadback	1.022s
ok  	github.com/carlosframework/platform/internal/hostactors	24.283s
ok  	github.com/carlosframework/platform/internal/hostbox	24.797s
ok  	github.com/carlosframework/platform/internal/hostclaim	2.918s
ok  	github.com/carlosframework/platform/internal/hostenv	0.045s
ok  	github.com/carlosframework/platform/internal/hostevidence	0.050s
ok  	github.com/carlosframework/platform/internal/hostexec	25.605s
ok  	github.com/carlosframework/platform/internal/hostfence	0.235s
ok  	github.com/carlosframework/platform/internal/hostfiles	24.476s
ok  	github.com/carlosframework/platform/internal/hostfloor	0.122s
ok  	github.com/carlosframework/platform/internal/hostguard	1.797s
ok  	github.com/carlosframework/platform/internal/hostops	6.663s
?   	github.com/carlosframework/platform/internal/hostops/fencerelease	[no test files]
ok  	github.com/carlosframework/platform/internal/hostops/internal/fencerelease	0.012s
ok  	github.com/carlosframework/platform/internal/hostquarantine	0.015s
ok  	github.com/carlosframework/platform/internal/hostrelocate	1.810s
ok  	github.com/carlosframework/platform/internal/hostresolve	0.525s
ok  	github.com/carlosframework/platform/internal/hostwrite	0.010s
ok  	github.com/carlosframework/platform/internal/infraview	0.011s
ok  	github.com/carlosframework/platform/internal/ingresshealth	0.010s
ok  	github.com/carlosframework/platform/internal/ingresshealth/awstg	0.023s
ok  	github.com/carlosframework/platform/internal/instancectl	67.897s
ok  	github.com/carlosframework/platform/internal/instanceexec	9.639s
ok  	github.com/carlosframework/platform/internal/instancefs	13.996s
ok  	github.com/carlosframework/platform/internal/instancekey	0.010s
ok  	github.com/carlosframework/platform/internal/instanceupdates	0.021s
ok  	github.com/carlosframework/platform/internal/interactive	0.740s
ok  	github.com/carlosframework/platform/internal/launchd	0.006s
ok  	github.com/carlosframework/platform/internal/layout	23.515s
ok  	github.com/carlosframework/platform/internal/layout/pubclass	101.571s
ok  	github.com/carlosframework/platform/internal/lbhealth	0.004s
ok  	github.com/carlosframework/platform/internal/lease	150.003s
ok  	github.com/carlosframework/platform/internal/lease/leasetest	1.421s
ok  	github.com/carlosframework/platform/internal/lease/locktest	0.014s
ok  	github.com/carlosframework/platform/internal/ledger	0.052s
ok  	github.com/carlosframework/platform/internal/mail	1.603s
ok  	github.com/carlosframework/platform/internal/mailer	0.851s
ok  	github.com/carlosframework/platform/internal/mailsubmit	1.482s
ok  	github.com/carlosframework/platform/internal/mailwire	0.015s
ok  	github.com/carlosframework/platform/internal/maintenance	0.191s
ok  	github.com/carlosframework/platform/internal/maintenanceexec	8.552s
ok  	github.com/carlosframework/platform/internal/maintenanceguard	0.348s
ok  	github.com/carlosframework/platform/internal/managedboot	3.816s
?   	github.com/carlosframework/platform/internal/managedboot/boottest	[no test files]
?   	github.com/carlosframework/platform/internal/managedboot/roottest	[no test files]
ok  	github.com/carlosframework/platform/internal/media	1.888s
ok  	github.com/carlosframework/platform/internal/media/mediatest	0.012s
ok  	github.com/carlosframework/platform/internal/mediaaws	65.774s
ok  	github.com/carlosframework/platform/internal/mediahandler	43.595s
ok  	github.com/carlosframework/platform/internal/mediajobs	0.946s
ok  	github.com/carlosframework/platform/internal/medialocal	10.139s
ok  	github.com/carlosframework/platform/internal/metrics	0.117s
ok  	github.com/carlosframework/platform/internal/minorunits	0.011s
ok  	github.com/carlosframework/platform/internal/moves	56.955s
ok  	github.com/carlosframework/platform/internal/moves/archive	2.596s
ok  	github.com/carlosframework/platform/internal/moves/offlinerun	0.099s
ok  	github.com/carlosframework/platform/internal/namedunits	0.046s
ok  	github.com/carlosframework/platform/internal/objstore	2.410s
ok  	github.com/carlosframework/platform/internal/ops	17.212s
ok  	github.com/carlosframework/platform/internal/pageindex	3.881s
ok  	github.com/carlosframework/platform/internal/parity	0.101s
?   	github.com/carlosframework/platform/internal/parity/cmd/parity-doc	[no test files]
ok  	github.com/carlosframework/platform/internal/park	0.724s
ok  	github.com/carlosframework/platform/internal/perf	0.181s
ok  	github.com/carlosframework/platform/internal/plans	0.113s
ok  	github.com/carlosframework/platform/internal/privatefile	0.008s
ok  	github.com/carlosframework/platform/internal/provision	251.815s
ok  	github.com/carlosframework/platform/internal/proxyproto	0.943s
ok  	github.com/carlosframework/platform/internal/publicrelease	0.048s
ok  	github.com/carlosframework/platform/internal/ratelimit	0.238s
ok  	github.com/carlosframework/platform/internal/regionlabel	0.069s
ok  	github.com/carlosframework/platform/internal/regionname	0.025s
ok  	github.com/carlosframework/platform/internal/registrar	0.015s
ok  	github.com/carlosframework/platform/internal/registrar/openprovider	0.664s
?   	github.com/carlosframework/platform/internal/registrar/registrartest	[no test files]
ok  	github.com/carlosframework/platform/internal/registry	86.082s
ok  	github.com/carlosframework/platform/internal/relay	7.634s
ok  	github.com/carlosframework/platform/internal/release	103.668s
?   	github.com/carlosframework/platform/internal/release/requestwitness	[no test files]
ok  	github.com/carlosframework/platform/internal/replicagen	0.036s
ok  	github.com/carlosframework/platform/internal/replicas	0.040s
ok  	github.com/carlosframework/platform/internal/reqrec	9.264s
ok  	github.com/carlosframework/platform/internal/rollout	11.396s
ok  	github.com/carlosframework/platform/internal/rolloutwords	0.017s
ok  	github.com/carlosframework/platform/internal/rootaws	101.988s
ok  	github.com/carlosframework/platform/internal/rootfsimage	1.164s
ok  	github.com/carlosframework/platform/internal/rootparticipation	0.133s
ok  	github.com/carlosframework/platform/internal/rootstate	0.064s
ok  	github.com/carlosframework/platform/internal/runs	0.818s
ok  	github.com/carlosframework/platform/internal/s3compat	0.025s
ok  	github.com/carlosframework/platform/internal/s3fake	1.548s
ok  	github.com/carlosframework/platform/internal/s3meter	0.425s
ok  	github.com/carlosframework/platform/internal/safefile	0.047s
ok  	github.com/carlosframework/platform/internal/schedule	23.908s
ok  	github.com/carlosframework/platform/internal/seeds	0.070s
ok  	github.com/carlosframework/platform/internal/sim/litestreamfacts	4.319s
ok  	github.com/carlosframework/platform/internal/sim/mediajobs	54.405s
ok  	github.com/carlosframework/platform/internal/sim/regionha	23.602s
ok  	github.com/carlosframework/platform/internal/status	0.545s
ok  	github.com/carlosframework/platform/internal/steering	0.213s
ok  	github.com/carlosframework/platform/internal/stopevidence	0.566s
ok  	github.com/carlosframework/platform/internal/storecfg	0.496s
ok  	github.com/carlosframework/platform/internal/svcrole	0.008s
ok  	github.com/carlosframework/platform/internal/systemd	6.998s
?   	github.com/carlosframework/platform/internal/systemdshow	[no test files]
ok  	github.com/carlosframework/platform/internal/team	4.130s
ok  	github.com/carlosframework/platform/internal/teamcontract	0.175s
ok  	github.com/carlosframework/platform/internal/telemetry	0.020s
ok  	github.com/carlosframework/platform/internal/termfence	3.510s
ok  	github.com/carlosframework/platform/internal/timerspec	0.015s
ok  	github.com/carlosframework/platform/internal/tsidentity	4.212s
ok  	github.com/carlosframework/platform/internal/tunnelclient	0.414s
ok  	github.com/carlosframework/platform/internal/unixdial	0.008s
ok  	github.com/carlosframework/platform/internal/updatewords	0.063s
ok  	github.com/carlosframework/platform/internal/upstreamguard	0.009s
?   	github.com/carlosframework/platform/internal/upstreamguard/guardtest	[no test files]
ok  	github.com/carlosframework/platform/internal/usage	0.035s
ok  	github.com/carlosframework/platform/internal/version	0.015s
ok  	github.com/carlosframework/platform/internal/vet	3.410s
ok  	github.com/carlosframework/platform/internal/zonehost	0.036s
ok  	github.com/carlosframework/platform/internal/zonehost/route53zones	0.163s
?   	github.com/carlosframework/platform/internal/zonehost/zonehosttest	[no test files]
?   	github.com/carlosframework/platform/scripts/gitleaks-gate	[no test files]
ok  	github.com/carlosframework/platform/scripts/govulncheck-gate	0.056s
ok  	github.com/carlosframework/platform/scripts/pathmapcheck	0.144s
ok  	github.com/carlosframework/platform/scripts/region-ha-g2/fixture	5.265s
ok  	github.com/carlosframework/platform/scripts/stateless-replicas-drill	1.258s
ok  	github.com/carlosframework/platform/scripts/witness-pointer	0.047s
=== cutover-witness (165 s, from +15 s)
ok  	github.com/carlosframework/platform	2.545s
=== internal_grouproll@0 (280 s, from +75 s)
ok  	github.com/carlosframework/platform/internal/grouproll	278.423s
=== internal_grouproll@1 (287 s, from +75 s)
ok  	github.com/carlosframework/platform/internal/grouproll	284.914s
=== internal_activator@0 (158 s, from +148 s)
ok  	github.com/carlosframework/platform/internal/activator	152.717s
=== internal_activator@1 (134 s, from +148 s)
ok  	github.com/carlosframework/platform/internal/activator	129.247s
=== internal_activator@2 (138 s, from +148 s)
ok  	github.com/carlosframework/platform/internal/activator	133.343s
=== internal_activator@3 (170 s, from +148 s)
ok  	github.com/carlosframework/platform/internal/activator	164.929s
=== internal_edge@0 (270 s, from +177 s)
ok  	github.com/carlosframework/platform/internal/edge	260.101s
=== internal_edge@1 (135 s, from +177 s)
ok  	github.com/carlosframework/platform/internal/edge	126.317s
=== internal_edge@2 (163 s, from +177 s)
ok  	github.com/carlosframework/platform/internal/edge	153.454s
=== internal_edge@3 (153 s, from +177 s)
ok  	github.com/carlosframework/platform/internal/edge	143.885s
=== root@0 (133 s, from +181 s)
ok  	github.com/carlosframework/platform	123.262s
=== root@1 (112 s, from +181 s)
ok  	github.com/carlosframework/platform	102.072s
=== root@2 (123 s, from +181 s)
ok  	github.com/carlosframework/platform	114.322s
=== root@3 (123 s, from +181 s)
ok  	github.com/carlosframework/platform	113.940s
=== root@4 (103 s, from +181 s)
ok  	github.com/carlosframework/platform	93.802s
=== internal_host@0 (153 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	147.736s
=== internal_host@1 (248 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	243.754s
=== internal_host@2 (215 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	209.967s
=== internal_host@3 (281 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	276.039s
=== internal_host@4 (143 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	138.334s
=== internal_host@5 (204 s, from +229 s)
ok  	github.com/carlosframework/platform/internal/host	199.256s
=== internal_console@0 (205 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	199.337s
=== internal_console@1 (176 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	168.504s
=== internal_console@2 (207 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	200.651s
=== internal_console@3 (260 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	252.530s
=== internal_console@4 (202 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	195.064s
=== internal_console@5 (213 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	207.282s
=== internal_console@6 (218 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	209.325s
=== internal_console@7 (217 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	210.582s
=== internal_console@8 (262 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	254.316s
=== internal_console@9 (230 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	223.609s
=== internal_console@10 (230 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	223.273s
=== internal_console@11 (250 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	244.342s
=== internal_console@12 (304 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	297.241s
=== internal_console@13 (242 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	235.519s
=== internal_console@14 (205 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	197.301s
=== internal_console@15 (255 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	248.379s
=== internal_console@16 (217 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	209.674s
=== internal_console@17 (215 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	206.852s
=== internal_console@18 (212 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	204.592s
=== internal_console@19 (207 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	199.031s
=== internal_console@20 (217 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	209.205s
=== internal_console@21 (232 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	224.569s
=== internal_console@22 (234 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	226.015s
=== internal_console@23 (238 s, from +239 s)
ok  	github.com/carlosframework/platform/internal/console	231.843s
=== lists: internal_console 238 s, internal_edge 176 s, internal_activator 147 s, internal_host 228 s, root 180 s, internal_grouproll 75 s
=== cpu: the gate used 13483 cpu-seconds in 543 s, about 24.8 of 32 cores; the machine as a whole was 83% busy
=== opentofu ===
opentofu: 39 test files in 11 suites, OpenTofu v1.13.9
  initialised in 14 s
  ok      20 s  infra/modules/box-fence-writer/tests/writer.tftest.hcl  Success! 1 passed, 0 failed.
  ok      22 s  infra/modules/deployment-buckets/tests/console_floors.tftest.hcl  Success! 1 passed, 0 failed.
  ok      31 s  infra/modules/deployment-buckets/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      23 s  infra/modules/deployment-buckets/tests/db_reads.tftest.hcl  Success! 1 passed, 0 failed.
  ok      17 s  infra/modules/deployment-buckets/tests/evidence.tftest.hcl  Success! 1 passed, 0 failed.
  ok      31 s  infra/modules/deployment-buckets/tests/fence_writers.tftest.hcl  Success! 3 passed, 0 failed.
  ok      27 s  infra/modules/deployment-buckets/tests/media_results.tftest.hcl  Success! 2 passed, 0 failed.
  ok      89 s  infra/modules/media-engine/tests/media_engine.tftest.hcl  Success! 24 passed, 0 failed.
  ok      27 s  infra/modules/pdf-host/tests/computed.tftest.hcl  Success! 2 passed, 0 failed.
  ok      59 s  infra/modules/pdf-host/tests/pdf_host.tftest.hcl  Success! 24 passed, 0 failed.
  ok      41 s  infra/modules/region-group-operator-document/tests/document.tftest.hcl  Success! 12 passed, 0 failed.
  ok      19 s  infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl  Success! 2 passed, 0 failed.
  ok      71 s  infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl  Success! 30 passed, 0 failed.
  ok      46 s  infra/modules/region-host/tests/alert_publish.tftest.hcl  Success! 18 passed, 0 failed.
  ok      44 s  infra/modules/region-host/tests/alerts_topic.tftest.hcl  Success! 16 passed, 0 failed.
  ok      12 s  infra/modules/region-host/tests/analytics_prune.tftest.hcl  Success! 2 passed, 0 failed.
  ok      16 s  infra/modules/region-host/tests/console_mail.tftest.hcl  Success! 4 passed, 0 failed.
  ok       7 s  infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl  Success! 1 passed, 0 failed.
  ok      72 s  infra/modules/region-host/tests/group.tftest.hcl  Success! 32 passed, 0 failed.
  ok      11 s  infra/modules/region-host/tests/group_alarms.tftest.hcl  Success! 4 passed, 0 failed.
  ok      11 s  infra/modules/region-host/tests/group_iam.tftest.hcl  Success! 4 passed, 0 failed.
  ok       6 s  infra/modules/region-host/tests/group_isolation.tftest.hcl  Success! 1 passed, 0 failed.
  ok      38 s  infra/modules/region-host/tests/group_operator.tftest.hcl  Success! 13 passed, 0 failed.
  ok       9 s  infra/modules/region-host/tests/group_user_data.tftest.hcl  Success! 3 passed, 0 failed.
  ok      29 s  infra/modules/region-host/tests/health_alarms.tftest.hcl  Success! 10 passed, 0 failed.
  ok      14 s  infra/modules/region-host/tests/ingress_drain_read.tftest.hcl  Success! 4 passed, 0 failed.
  ok       6 s  infra/modules/region-host/tests/instance_metadata.tftest.hcl  Success! 1 passed, 0 failed.
  ok      25 s  infra/modules/region-host/tests/mailer.tftest.hcl  Success! 6 passed, 0 failed.
  ok      14 s  infra/modules/region-host/tests/mailer_group.tftest.hcl  Success! 2 passed, 0 failed.
  ok      14 s  infra/modules/region-host/tests/managed_fleets/group_refusal.tftest.hcl  Success! 2 passed, 0 failed.
  ok     108 s  infra/modules/region-host/tests/managed_fleets/managed_fleets.tftest.hcl  Success! 46 passed, 0 failed.
  ok      71 s  infra/modules/region-host/tests/store_conversion.tftest.hcl  Success! 27 passed, 0 failed.
  ok      17 s  infra/modules/region-host/tests/store_scanning.tftest.hcl  Success! 4 passed, 0 failed.
  ok      31 s  infra/modules/region-host/tests/store_versioning.tftest.hcl  Success! 11 passed, 0 failed.
  ok      16 s  infra/modules/region-host/tests/store_write_credentials.tftest.hcl  Success! 4 passed, 0 failed.
  ok      17 s  infra/modules/region-host/tests/user_data_ignored.tftest.hcl  Success! 3 passed, 0 failed.
  ok      12 s  infra/modules/region-remote-host/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      14 s  infra/modules/region-remote-host/tests/no_deployment_bucket.tftest.hcl  Success! 5 passed, 0 failed.
  ok      29 s  infra/modules/scanner-host/tests/scanner_host.tftest.hcl  Success! 14 passed, 0 failed.
opentofu: 39 files in 214 s
opentofu: PASS
=== cross ===
--- shard 0 of 5 ---
go version go1.26.10 linux/arm64
cross-compiling darwin/arm64
--- shard 1 of 5 ---
go version go1.26.10 linux/arm64
cross-compiling darwin/amd64
--- shard 2 of 5 ---
go version go1.26.10 linux/arm64
cross-compiling linux/arm64
linux/arm64 carlos binary: 66519202 bytes (ceiling 70000000)
--- shard 3 of 5 ---
go version go1.26.10 linux/arm64
cross-compiling windows/amd64
--- shard 4 of 5 ---
go version go1.26.10 linux/arm64
cross-compiling windows/arm64
=== minio-contract ===
go version go1.26.10 linux/arm64
minio contract: arm64, minio RELEASE.2025-09-07T16-13-09Z, mc RELEASE.2025-08-13T08-35-41Z
  minio: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/minio/minio.linux-arm64.RELEASE.2025-09-07T16-13-09Z
  minio: downloaded, digest verified
  mc: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/minio/mc.linux-arm64.RELEASE.2025-08-13T08-35-41Z
  mc: downloaded, digest verified
  minio healthy on 127.0.0.1:38379
Added `local` successfully.
Bucket created successfully `local/contract-bucket`.
Bucket created successfully `local/denied-bucket`.
Created policy `contract-only` successfully.
Added user `scopeduser` successfully.
Attached Policies: [contract-only]
To User: scopeduser
  buckets and scoped user ready
=== RUN   TestDeliveredContractMinio
=== RUN   TestDeliveredContractMinio/put
=== RUN   TestDeliveredContractMinio/get_round-trips_the_body
=== RUN   TestDeliveredContractMinio/list_shows_the_key
=== RUN   TestDeliveredContractMinio/head_and_list_agree_on_the_version
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_its_own_object
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_its_own_object/not_by_PutObjectTagging
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_its_own_object/and_not_by_x-amz-tagging_on_upload
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/not_by_CreateMultipartUpload
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/not_by_CopyObject_with_a_REPLACE_tagging_directive
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/but_multipart_itself_is_allowed
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/and_copy_itself_is_allowed
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/a_POST-policy_forged_tag_with_a_matching_version_is_still_not_a_verdict
=== RUN   TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/and_an_ordinary_tagged-with-something-else_upload_is_allowed
=== RUN   TestDeliveredContractMinio/delete_removes_it
=== RUN   TestDeliveredContractMinio/cross-bucket_denial
--- PASS: TestDeliveredContractMinio (0.03s)
    --- PASS: TestDeliveredContractMinio/put (0.00s)
    --- PASS: TestDeliveredContractMinio/get_round-trips_the_body (0.00s)
    --- PASS: TestDeliveredContractMinio/list_shows_the_key (0.00s)
    --- PASS: TestDeliveredContractMinio/head_and_list_agree_on_the_version (0.00s)
    --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_its_own_object (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_its_own_object/not_by_PutObjectTagging (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_its_own_object/and_not_by_x-amz-tagging_on_upload (0.00s)
    --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route (0.02s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/not_by_CreateMultipartUpload (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/not_by_CopyObject_with_a_REPLACE_tagging_directive (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/but_multipart_itself_is_allowed (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/and_copy_itself_is_allowed (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/a_POST-policy_forged_tag_with_a_matching_version_is_still_not_a_verdict (0.00s)
        --- PASS: TestDeliveredContractMinio/the_app_cannot_tag_by_any_other_route/and_an_ordinary_tagged-with-something-else_upload_is_allowed (0.00s)
    --- PASS: TestDeliveredContractMinio/delete_removes_it (0.00s)
    --- PASS: TestDeliveredContractMinio/cross-bucket_denial (0.00s)
PASS
ok  	github.com/carlosframework/platform/internal/objstore	0.042s
=== RUN   TestT4StorageProbeMinio
2026/11/28 19:08:31 moves: T4: STORE: list: operation error S3: ListObjectsV2, https response error StatusCode: 403, RequestID: 18EC4B1677C3AA97, HostID: ab3c482297edce6052f41f6a0d0b60d099aea9ffb1bbf2a92b2702bd62b3cce4, api error SignatureDoesNotMatch: The request signature we calculated does not match the signature you provided. Check your key and signing method.
--- PASS: TestT4StorageProbeMinio (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/host	0.051s
=== RUN   TestS3StoreMinioContract
=== RUN   TestS3StoreMinioContract/conditional_get_and_etag_listing
=== RUN   TestS3StoreMinioContract/bump_through_every_mutation_path
--- PASS: TestS3StoreMinioContract (0.04s)
    --- PASS: TestS3StoreMinioContract/conditional_get_and_etag_listing (0.01s)
    --- PASS: TestS3StoreMinioContract/bump_through_every_mutation_path (0.02s)
PASS
ok  	github.com/carlosframework/platform/internal/release	0.045s
Bucket created successfully `local/analytics-versions`.
local/analytics-versions versioning is enabled
Created policy `analytics-versions` successfully.
Added user `analyticsversions` successfully.
Attached Policies: [analytics-versions]
To User: analyticsversions
=== RUN   TestS3StoreMinioVersions
--- PASS: TestS3StoreMinioVersions (0.04s)
PASS
ok  	github.com/carlosframework/platform/internal/release	0.048s
Bucket created successfully `local/store-versioned`.
local/store-versioned versioning is enabled
Created policy `store-versioned` successfully.
Added user `storeversioned` successfully.
Attached Policies: [store-versioned]
To User: storeversioned
=== RUN   TestVersionedContractMinio
--- PASS: TestVersionedContractMinio (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/objstore	0.023s
Bucket created successfully `local/wc-bucket`.
Created policy `writer` successfully.
Added user `wcwriter` successfully.
Attached Policies: [writer]
To User: wcwriter
=== RUN   TestWriteCredentialContractMinio
=== RUN   TestWriteCredentialContractMinio/put_under_the_prefix
=== RUN   TestWriteCredentialContractMinio/multipart_under_the_prefix
=== RUN   TestWriteCredentialContractMinio/refused:_tag
=== RUN   TestWriteCredentialContractMinio/refused:_put_outside_the_prefix
=== RUN   TestWriteCredentialContractMinio/refused:_put_to_another_bucket
=== RUN   TestWriteCredentialContractMinio/refused:_copy_from_the_store
=== RUN   TestWriteCredentialContractMinio/refused:_bucket_settings
=== RUN   TestWriteCredentialContractMinio/refused:_read_under_the_prefix
=== RUN   TestWriteCredentialContractMinio/refused:_head
=== RUN   TestWriteCredentialContractMinio/refused:_delete
=== RUN   TestWriteCredentialContractMinio/refused:_put_tagged
=== RUN   TestWriteCredentialContractMinio/refused:_put_with_a_platform_tag
=== RUN   TestWriteCredentialContractMinio/refused:_put_beside_the_prefix
=== RUN   TestWriteCredentialContractMinio/refused:_read_elsewhere
=== RUN   TestWriteCredentialContractMinio/refused:_list
=== RUN   TestWriteCredentialContractMinio/refused:_list_uploads
--- PASS: TestWriteCredentialContractMinio (0.04s)
    --- PASS: TestWriteCredentialContractMinio/put_under_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/multipart_under_the_prefix (0.01s)
    --- PASS: TestWriteCredentialContractMinio/refused:_tag (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_outside_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_to_another_bucket (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_copy_from_the_store (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_bucket_settings (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_read_under_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_head (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_delete (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_tagged (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_with_a_platform_tag (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_beside_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_read_elsewhere (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_list (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_list_uploads (0.00s)
PASS
ok  	github.com/carlosframework/platform/internal/objstore	0.055s
=== RUN   TestEndToEndMinio
=== RUN   TestEndToEndMinio/plan
=== RUN   TestEndToEndMinio/roll
=== RUN   TestEndToEndMinio/replace
=== RUN   TestEndToEndMinio/remove
--- PASS: TestEndToEndMinio (0.52s)
    --- PASS: TestEndToEndMinio/plan (0.01s)
    --- PASS: TestEndToEndMinio/roll (0.14s)
    --- PASS: TestEndToEndMinio/replace (0.17s)
    --- PASS: TestEndToEndMinio/remove (0.17s)
PASS
ok  	github.com/carlosframework/platform/internal/grouproll	0.531s
Bucket created successfully `local/dbf-deploy`.
Bucket created successfully `local/dbf-data-ie`.
Bucket created successfully `local/dbf-data-uk`.
local/dbf-deploy versioning is enabled
Created policy `dbf-console` successfully.
Created policy `dbf-ukbox` successfully.
Added user `dbfconsole` successfully.
Added user `dbfukbox` successfully.
Attached Policies: [dbf-console]
To User: dbfconsole
Attached Policies: [dbf-ukbox]
To User: dbfukbox
=== RUN   TestDBForwardMinio
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/28 19:08:40 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=720
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000001
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/28 19:08:40 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=370
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000002
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/28 19:08:40 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=454
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/28 19:08:40 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=720
2026/11/28 19:08:40 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000001
2026/11/28 19:08:40 console: CARLOS_SECRETS_PUBKEY is unset, so no region outside the home can be chosen automatically
2026/11/28 19:08:40 console: could not notify member@example.com of a CLI token issue: keymail: lookup member@example.com: keymail: GET /api/federation/lookup?addr=member%40example.com&from=console%40127.0.0.1%3A38123: could not determine target mailbox
    agent.go:136: dbreads: dbr_cap6o4hw2ebzwb4avu7edhgij4: planned 3 files (1544 bytes) and restored to 3 in 18ms
    agent.go:136: dbreads: dbr_cap6o4hw2ebzwb4avu7edhgij4: output 5 bytes in 1 confirmed chunks in 2ms
2026/11/28 19:08:41 console: db read dbr_cap6o4hw2ebzwb4avu7edhgij4: relayed 1 chunks (102 bytes) in 1.006s, ended done
    agent.go:136: dbreads: dbr_x35cykwmzpqt3gtvu465c7ymem: planned 1 files (720 bytes) and restored to 1 in 14ms
    agent.go:136: dbreads: dbr_x35cykwmzpqt3gtvu465c7ymem: output 5 bytes in 1 confirmed chunks in 2ms
2026/11/28 19:08:42 console: db read dbr_x35cykwmzpqt3gtvu465c7ymem: relayed 1 chunks (102 bytes) in 1.005s, ended done
    agent.go:136: dbreads: dbr_g3fa6t7fuxutwcvsu6vytbg2zi: planned 3 files (1544 bytes) and held through 3 in 14ms
    agent.go:136: dbreads: dbr_g3fa6t7fuxutwcvsu6vytbg2zi: output 1544 bytes in 1 confirmed chunks in 2ms
2026/11/28 19:08:43 console: db read dbr_g3fa6t7fuxutwcvsu6vytbg2zi: relayed 1 chunks (1641 bytes) in 1.006s, ended done
=== RUN   TestDBForwardMinio/by_disconnect
=== NAME  TestDBForwardMinio
    agent.go:136: dbreads: dbr_kjh3bmkwsaluplohz5xtffrv5i: planned 3 files (1544 bytes) and restored to 3 in 15ms
2026/11/28 19:08:43 console: db read dbr_kjh3bmkwsaluplohz5xtffrv5i: relayed 0 chunks (0 bytes) in 24ms, ended client gone
    agent.go:136: dbreads: dbr_kjh3bmkwsaluplohz5xtffrv5i: output 5 bytes in 1 confirmed chunks in 105ms
=== RUN   TestDBForwardMinio/by_timeout
=== NAME  TestDBForwardMinio
    agent.go:136: dbreads: dbr_gc6badfbs4pyyb7vldgdns7sue: planned 3 files (1544 bytes) and restored to 3 in 15ms
2026/11/28 19:09:04 console: db read dbr_gc6badfbs4pyyb7vldgdns7sue: relayed 0 chunks (0 bytes) in 19.884s, ended no-result
    agent.go:136: dbreads: dbr_gc6badfbs4pyyb7vldgdns7sue: output 5 bytes in 1 confirmed chunks in 19.855s
--- PASS: TestDBForwardMinio (23.57s)
    --- PASS: TestDBForwardMinio/by_disconnect (0.24s)
    --- PASS: TestDBForwardMinio/by_timeout (20.00s)
PASS
ok  	github.com/carlosframework/platform/internal/console	23.622s
Bucket created successfully `local/media-transfers`.
Bucket created successfully `local/media-transfer-results`.
local/media-transfer-results versioning is enabled
Created policy `media-transfers` successfully.
Added user `mediatransfers` successfully.
Attached Policies: [media-transfers]
To User: mediatransfers
=== RUN   TestMediaTransfersMinio
    upload.go:117: codec: the store already holds video.mp4
    upload.go:117: codec: the store already holds video.m3u8
    upload.go:117: codec: the store already holds poster.jpg
--- PASS: TestMediaTransfersMinio (0.08s)
PASS
ok  	github.com/carlosframework/platform/internal/mediaaws	0.086s
Bucket created successfully `local/media-local-store`.
Bucket created successfully `local/media-local-results`.
Created policy `media-local` successfully.
Added user `medialocal` successfully.
Attached Policies: [media-local]
To User: medialocal
=== RUN   TestLocalEndToEndMinio
--- PASS: TestLocalEndToEndMinio (0.61s)
PASS
ok  	github.com/carlosframework/platform/internal/medialocal	0.612s
=== RUN   TestHeldHandoverTwoBoxMinio
2026/11/28 19:09:09 edge: mesh key: minted
2026/11/28 19:09:09 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 19:09:09 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 19:09:09 tenant admission is open. accepting tenant work
2026/11/28 19:09:09 activator: HA placement host=shop-2f6a97ba.example.test kind=Place ref=annie reason=roomiest generation=2026-11-28T19:09:09Z lock_generation=0
2026/11/28 19:09:09 lease: t8-2f6a97ba/shop-2f6a97ba.example.test: HA lease acquired in 4ms (first wake)
2026/11/28 19:09:09 activator: shop-2f6a97ba.example.test: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 19:09:09 activator: shop-2f6a97ba.example.test: started carlos-instance@shop\x2d2f6a97ba.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 0s, instance key 0s, env 6ms, control socket 0s, key gate 0s, logs 0s) 7ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 19:09:09 activator: shop-2f6a97ba.example.test: carlos-instance@shop\x2d2f6a97ba.example.test.service launched in 8ms, healthy 0s later
2026/11/28 19:09:09 activator: shop-2f6a97ba.example.test: woke in 23ms: checks 0s, lease 5ms, restore 0s, identity 0s, protect 0s, spawn 8ms, replicate 10ms
2026/11/28 19:09:09 lease: t8-2f6a97ba/plain-2f6a97ba.example.test: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/28 19:09:09 activator: no replica for plain-2f6a97ba.example.test in s3://contract-bucket/t8-2f6a97ba/plain-2f6a97ba.example.test — booting fresh
2026/11/28 19:09:09 activator: plain-2f6a97ba.example.test: started carlos-instance@plain\x2d2f6a97ba.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 1ms, instance key 0s, env 5ms, control socket 0s, key gate 0s, logs 0s) 6ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 19:09:09 activator: plain-2f6a97ba.example.test: carlos-instance@plain\x2d2f6a97ba.example.test.service launched in 8ms, healthy 0s later
2026/11/28 19:09:09 activator: plain-2f6a97ba.example.test: woke in 90ms: checks 0s, lease 2ms, restore 21ms, identity 0s, protect 0s, spawn 8ms, replicate 59ms
2026/11/28 19:09:09 lease: t8-2f6a97ba/bot0.shop.bac.sidecar.internal: HA lease acquired in 4ms (first wake)
2026/11/28 19:09:09 activator: bot0.shop.bac.sidecar.internal: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 19:09:09 activator: bot0.shop.bac.sidecar.internal: woke in 72ms: checks 0s, lease 5ms, restore 0s, identity 0s, protect 0s, spawn 8ms, settle 0s, replicate 57ms
2026/11/28 19:09:09 activator: next-due probe plain-2f6a97ba.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 19:09:09 activator: next-due probe shop-2f6a97ba.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 19:09:09 activator: plain-2f6a97ba.example.test hibernated
2026/11/28 19:09:09 activator: bot0.shop.bac.sidecar.internal: released with a marker (clean true, txid 1, files 3:9cd46c0feaa22faf416b711f570e19f05e09496292c6904ee717f0dcfb8a63fa) in 8ms: files 1ms, sync 4ms, record 1ms, marker 2ms
2026/11/28 19:09:09 activator: bot0.shop.bac.sidecar.internal hibernated
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: released with a marker (clean true, txid 1, files 3:9367255f29fb0ba5b27f40f1ba0a1e9aade3e7b65de60449a4521951978d38be) in 8ms: files 1ms, sync 5ms, record 1ms, marker 2ms
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test hibernated
2026/11/28 19:09:10 lease: t8-2f6a97ba/shop-2f6a97ba.example.test: HA lease acquired in 3ms (clean marker)
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: restored (other-box)
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: started carlos-instance@shop\x2d2f6a97ba.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 0s, instance key 0s, env 0s, control socket 0s, key gate 0s, logs 0s) 1ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: carlos-instance@shop\x2d2f6a97ba.example.test.service launched in 2ms, healthy 0s later
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: woke in 90ms: checks 0s, lease 4ms, restore 27ms, identity 0s, protect 0s, spawn 2ms, replicate 57ms
2026/11/28 19:09:10 edge: ha-take shop-2f6a97ba.example.test from annie (txn t8-witness, marker generation 1): holder betty, generation 2
2026/11/28 19:09:10 edge: forward shop-2f6a97ba.example.test: annie handed the request over to betty; sending it there (occurrence #1)
    hadrain_twobox_minio_linux_test.go:1238: drain report: {V:1 Transaction:t8-witness Incarnation:0b9698841c5e62c41aa21deb4f3ffba5 Step:move Result:ok Reasons:[] Fence:t8-witness StartedAt:2026-11-28 19:09:09.961452615 +0000 UTC FinishedAt:2026-11-28 19:09:10.110054341 +0000 UTC Acked:[betty carol] Departed:[] Moved:[{Host:shop-2f6a97ba.example.test Holder:betty Gen:2 Confirmed:take}] Released:[{Host:plain-2f6a97ba.example.test Kind:other Marker:true Clean:true Reason:} {Host:bot0.shop.bac.sidecar.internal Kind:worker Marker:true Clean:true Reason:}] Unclean:[] Left:[] Holds:{LongestMS:136 Todays:0 RefusedAtOnce:1} Closed:0 Quiet:{DrainQuiet:{Waking:0 Stopping:0 Recovering:0 Owed:0} Held:[]}}
    hadrain_twobox_minio_linux_test.go:1239: driver calls: [begin shop-2f6a97ba.example.test <nil> releasing shop-2f6a97ba.example.test <nil> stop plain-2f6a97ba.example.test marker=true clean=true <nil> stop bot0.shop.bac.sidecar.internal marker=true clean=true <nil> stop shop-2f6a97ba.example.test marker=true clean=true <nil> taken shop-2f6a97ba.example.test betty <nil> end-moves]
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/bot0.shop.bac.sidecar.internal/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: DELETE /contract-bucket/t8-2f6a97ba/plain-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/bot0.shop.bac.sidecar.internal/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/head.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/generations/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0008/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0007/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0006/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0005/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0004/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0008/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0007/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0006/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0005/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0004/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/files/0/manifest.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/files/0/objects/0000000000000001-b38340fa0fab94aa28f5f9e6bd7659ef0b88c1e8e01af795ad3d3d9ba93d9a77
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/files/0/objects/0000000000000003-6abd841dc0baacfbfb6dc574f48ffbea327e670015ea9d8ef21a4cf7e4000b04
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/0000/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-2f6a97ba/shop-2f6a97ba.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/0000/0000000000000002-0000000000000002.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-2f6a97ba/shop-2f6a97ba.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1243: drain took 192ms; S3 calls 45 (DELETE lock=1 GET files=3 GET head=1 GET lock=3 GET replica=2 LIST replica=29 PUT lock=3 PUT replica=3); deployment store calls 20 (GET edges=14 LIST edges=4 PUT edges=2)
    hadrain_twobox_minio_linux_test.go:1367: the fenced A's start gate answers 503 "This service is unavailable. Try again later.\n" (Retry-After "10")
2026/11/28 19:09:10 lease: t8-2f6a97ba/plain-2f6a97ba.example.test: acquired in 2ms (client 0s, lock read and write 2ms)
2026/11/28 19:09:10 activator: plain-2f6a97ba.example.test: started carlos-instance@plain\x2d2f6a97ba.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 0s, instance key 0s, env 0s, control socket 0s, key gate 0s, logs 0s) 0s, launch file 0s, gate 0s, root start 1ms)
2026/11/28 19:09:10 activator: plain-2f6a97ba.example.test: carlos-instance@plain\x2d2f6a97ba.example.test.service launched in 1ms, healthy 0s later
2026/11/28 19:09:10 lease: /tmp/carlos-minio-contract-zCyR0y/g/dw539716511/data/instances/plain-2f6a97ba.example.test/plain-2f6a97ba.example.test.db: continuity with the last clean close not proven; snapshot 1-0000000000000001 written before serving
2026/11/28 19:09:10 activator: plain-2f6a97ba.example.test: woke in 11ms: checks 0s, lease 2ms, restore 0s, identity 0s, protect 1ms, spawn 2ms, replicate 7ms
2026/11/28 19:09:10 activator: next-due probe shop-2f6a97ba.example.test: decode /api/next-due: invalid character 'b' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test: released with a marker (clean true, txid 2, files 3:9367255f29fb0ba5b27f40f1ba0a1e9aade3e7b65de60449a4521951978d38be) in 4ms: files 1ms, sync 1ms, record 1ms, marker 3ms
2026/11/28 19:09:10 activator: shop-2f6a97ba.example.test hibernated
2026/11/28 19:09:10 tenant admission is closed for shutdown
2026/11/28 19:09:10 activator: next-due probe plain-2f6a97ba.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 19:09:10 activator: plain-2f6a97ba.example.test hibernated
--- PASS: TestHeldHandoverTwoBoxMinio (0.63s)
=== RUN   TestHeldHandoverLostLeaseMinio
2026/11/28 19:09:10 edge: mesh key: minted
2026/11/28 19:09:10 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 19:09:10 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 19:09:10 tenant admission is open. accepting tenant work
2026/11/28 19:09:10 activator: HA placement host=shop-060cb393.example.test kind=Place ref=annie reason=roomiest generation=2026-11-28T19:09:10Z lock_generation=0
2026/11/28 19:09:10 lease: t8-060cb393/shop-060cb393.example.test: HA lease acquired in 4ms (first wake)
2026/11/28 19:09:10 activator: shop-060cb393.example.test: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 19:09:10 activator: shop-060cb393.example.test: started carlos-instance@shop\x2d060cb393.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 0s, instance key 0s, env 7ms, control socket 0s, key gate 0s, logs 0s) 7ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 19:09:10 activator: shop-060cb393.example.test: carlos-instance@shop\x2d060cb393.example.test.service launched in 9ms, healthy 0s later
2026/11/28 19:09:10 activator: shop-060cb393.example.test: woke in 68ms: checks 0s, lease 5ms, restore 0s, identity 0s, protect 0s, spawn 9ms, replicate 54ms
2026/11/28 19:09:10 activator: next-due probe shop-060cb393.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 19:09:10 activator: final checkpoint shop-060cb393.example.test: lease: release marker owed for s3://contract-bucket/t8-060cb393/shop-060cb393.example.test/lock.json (If-Match "d1746e0d20b51363ac3c9c732b42c87a"): lease: write release marker: operation error S3: PutObject, https response error StatusCode: 503, RequestID: , HostID: , api error ServiceUnavailable: witness: refused
2026/11/28 19:09:10 activator: shop-060cb393.example.test hibernated
2026/11/28 19:09:10 activator: handover of shop-060cb393.example.test left: released without a marker; its held requests get today's answer
    hadrain_twobox_minio_linux_test.go:1469: the held request's hold ended "shop-060cb393.example.test client 4 "
    hadrain_twobox_minio_linux_test.go:1486: driver calls: [begin shop-060cb393.example.test <nil> releasing shop-060cb393.example.test <nil> stop shop-060cb393.example.test marker=false clean=false <nil> left shop-060cb393.example.test released without a marker]
    hadrain_twobox_minio_linux_test.go:1487: a request after the loss: 503 "This instance cannot wake right now. Please try again shortly.\n" (Retry-After "10", holder "none", 0s, err <nil>)
2026/11/28 19:09:10 tenant admission is closed for shutdown
2026/11/28 19:09:10 http: proxy error: context canceled
--- PASS: TestHeldHandoverLostLeaseMinio (0.33s)
PASS
ok  	github.com/carlosframework/platform/internal/host	1.000s
Bucket created successfully `local/gen-take`.
local/gen-take versioning is enabled
Created policy `gen-take` successfully.
Added user `gentake` successfully.
Attached Policies: [gen-take]
To User: gentake
=== RUN   TestGenerationTakeMinio
=== RUN   TestGenerationTakeMinio/take
2026/11/28 19:09:11 lease: instances/gen-1795892951803270484.shop.example.com: HA lease acquired in 5ms (first wake)
2026/11/28 19:09:11 lease: instances/gen-1795892951803270484.shop.example.com: HA lease acquired in 3ms (holder terminated)
    gentake_minio_test.go:308: a second create-only copy onto instances/gen-1795892951803270484.shop.example.com/g-00000000000000000002/0000/0000000000000001-0000000000000001.ltx: <nil> (destination condition honoured: false)
2026/11/28 19:09:11 ERROR retention enforcement failed system=store db=w.example.com.db error="enforce snapshot retention: remove ltx files: lease: invalid or changed generation binding"
2026/11/28 19:09:11 ERROR enforce L0 time retention system=store db=w.example.com.db error="fetch l1 files: lease handle is spent"
2026/11/28 19:09:11 http: proxy error: context canceled
2026/11/28 19:09:11 ERROR retention enforcement failed system=store db=w.example.com.db error="enforce snapshot retention: remove ltx files: lease: a write has waited too long to reach storage (write fence)"
=== RUN   TestGenerationTakeMinio/switch-412
2026/11/28 19:09:11 lease: instances/gen-1795892951994614024.shop.example.com: HA lease acquired in 4ms (first wake)
2026/11/28 19:09:12 ERROR retention enforcement failed system=store db=seed.db error="enforce snapshot retention: remove ltx files: lease: invalid or changed generation binding"
2026/11/28 19:09:12 lease: instances/gen-1795892951994614024.shop.example.com: HA lease acquired in 3ms (clean marker)
=== RUN   TestGenerationTakeMinio/copy-version
=== RUN   TestGenerationTakeMinio/store-time
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 4ms (first wake)
2026/11/28 19:09:12 ERROR retention enforcement failed system=store db=seed.db error="enforce snapshot retention: remove ltx files: lease: invalid or changed generation binding"
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 3ms (clean marker)
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 3ms (unclean marker)
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 3ms (unclean marker)
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 3ms (unclean marker)
2026/11/28 19:09:12 lease: instances/gen-1795892952109405314.shop.example.com: HA lease acquired in 3ms (unclean marker)
=== RUN   TestGenerationTakeMinio/skew
--- PASS: TestGenerationTakeMinio (0.49s)
    --- PASS: TestGenerationTakeMinio/take (0.19s)
    --- PASS: TestGenerationTakeMinio/switch-412 (0.10s)
    --- PASS: TestGenerationTakeMinio/copy-version (0.01s)
    --- PASS: TestGenerationTakeMinio/store-time (0.18s)
    --- PASS: TestGenerationTakeMinio/skew (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/lease	0.510s
minio contract: PASS
=== staticcheck ===
go version go1.26.10 linux/arm64
go: downloading honnef.co/go/tools v0.8.2
go: downloading golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678
go: downloading github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c
go: downloading golang.org/x/sync v0.23.0
go: downloading golang.org/x/exp v0.0.0-20231110203233-9a3e6036ecaa
staticcheck: clean
=== govulncheck ===
go version go1.26.10 linux/arm64
go: downloading golang.org/x/vuln v1.8.0
go: downloading golang.org/x/telemetry v0.0.0-20260908163034-4bcc4b2ee518
go: downloading golang.org/x/tools v0.50.0
govulncheck: scanned github.com/carlosframework/platform, amadan.net/carlos/platform.git/launchctx, carlos-vulnscan
GO-2026-6859  called  stdlib@v1.26.10, fixed in v1.26.11
    HTTP/1 server crash due to MaxBytesReader header race in net/http
    excepted until 2027-01-31 (.amadan/govulncheck-exceptions.tsv:9): net/http MaxBytesReader header race, fixed in go1.26.11. CI and releases stay on go1.26.10 because 1.26.11 deadlocks the edge's Expect: 100-continue path (#897, .amadan/go-toolchain.sh); #904 checked every production MaxBytesReader site and found it unreachable.
GO-2026-5932  required  golang.org/x/crypto@v0.58.0, fixed in v0.58.1-0.20261009181718-2f1f834330b2
    The golang.org/x/crypto/openpgp package is unmaintained, unsafe by design, and has known security issues
    not fatal: no call path to the vulnerable code
govulncheck: clean (2 finding(s), none called outside .amadan/govulncheck-exceptions.tsv)
=== code-health ===
go version go1.26.10 linux/arm64
    codehealth_test.go:42: scanned in 1m58.987s
    codehealth_test.go:107: line metrics (code lines, then physical):
          file-lines  5471  7324  internal/activator activator_test.go
          file-lines  4190  7040  internal/console server.go
          file-lines  4150  6312  . apimode.go
          file-lines  3785  7224  internal/activator activator.go
          file-lines  3530  4459  . apimode_test.go
          file-lines  3261  3864  internal/registry registry_test.go
          file-lines  3204  6398  internal/host agent.go
          file-lines  3094  3992  internal/provision reconcile_test.go
          func-lines   870   891  internal/host plan14InstalledClaimLaunch
          func-lines   810  1277  internal/provision Reconcile
          func-lines   769  1242  internal/console (*Server).handleAPIInstanceCreate
          func-lines   683  1238  internal/host runAgent
          func-lines   571   908  internal/activator (*Service).doWakeOnce
          func-lines   538   546  internal/host runServingParkPeerNamespace
          func-lines   519   712  . runRoute
          func-lines   509   569  internal/host TestPagingIsRateLimited
          func-lines   494   815  internal/release adoptHost
          func-lines   441   500  internal/host TestRootInstanceStopExecStop
          func-lines   421   436  internal/host (*ClaimWakeAssembly).Build
          func-lines   421   437  internal/team TestFixture
          func-lines   412   414  internal/console TestDemoProtectionsSourceToLimitAndTakedown
          func-lines   408   485  . TestFleetAppServesThroughTheHub
          func-lines   402   406  internal/registry (*Registry).haJournal
          func-lines   400   868  internal/provision rootReadArchivedChain
          func-lines   399   732  internal/release PassFilter
          func-lines   390   398  internal/host runFilesSeedPreparationWithLive
          func-lines   383   406  internal/console TestDemoSourceToLiveAndUpdate
          func-lines   374   377  internal/host plan14RequiredArtifactsRootRunner
          func-lines   371   417  internal/host TestRootEgressKernelProof
          func-lines   369   883  internal/edge (*Edge).ServeHTTP
          func-lines   367   584  internal/console (*Server).handleAPIShip
          func-lines   364   371  internal/host testRootMigrationBootstrap
          func-lines   361   630  cmd/console serve
          func-lines   360   362  internal/edge TestDemoAPIAliasBoundary
          func-lines   357   358  internal/registry (*Registry).dispatchRemote
          func-lines   355   372  internal/host TestRootSandboxUpdateFromOldBox
          func-lines   343   354  internal/analytics Prune
          func-lines   340   353  internal/host newColdRootHarness
          func-lines   335   557  internal/console (*Store).migrate
          func-lines   334   334  internal/host TestPlan12RecoveryRestoreSourceDatabase
          func-lines   330   371  internal/edge TestRegionalNameNeverLeavesItsRegion
          func-lines   329   471  . runDeploy
          func-lines   329   329  internal/host TestPlan12RecoveryRestoreSourceDatabase.func1
          func-lines   327   369  internal/edge TestTunnelWebSocketEndToEnd
          func-lines   325   455  internal/objstore TestDeliveredContractMinio
          func-lines   320   654  internal/appconfig SyncExecWithCallbacks
          func-lines   315   318  internal/host plan14TimerIntention
          func-lines   311   314  internal/host plan14TimerIntention.func1
          func-lines   310   315  internal/hostbox ColdHandover.Run
          func-lines   308   309  internal/host rootFilesSeedIsolatedWitness
          func-lines   305   323  internal/host hairpinKernelWitness
          func-lines   304   308  internal/console TestHAP2ProductionDoors
          func-lines   302   329  internal/host TestRootG2PoolIngress
        release-importers: . cmd/console internal/activator internal/analytics internal/appconfig internal/apperr internal/applog internal/apppolicy internal/boxid internal/boxvolumes internal/console internal/dbreads internal/dbreads/dbreadstest internal/dbverify internal/demobuild internal/domains internal/doorkey internal/edge internal/edgeproof internal/edgesfile internal/fleetapi internal/grouproll internal/grouprollaws internal/historyreadback internal/host internal/hostactors internal/hostbox internal/hostclaim internal/hostevidence internal/hostexec internal/hostfence internal/hostfiles internal/hostfloor internal/hostguard internal/hostops internal/hostrelocate internal/hostresolve internal/instancectl internal/instanceupdates internal/interactive internal/layout internal/lease internal/ledger internal/mail internal/mailer internal/mailsubmit internal/metrics internal/moves internal/objstore internal/ops internal/park internal/plans internal/provision internal/relay internal/rollout internal/rootfsimage internal/runs internal/s3fake internal/schedule internal/seeds internal/status internal/telemetry internal/usage internal/vet scripts/pathmapcheck scripts/witness-pointer
        not scanned (216 files):
          cmd/carlos-media/drill_other.go: built only for other systems or tags
          cmd/carlos-media/harden_other.go: built only for other systems or tags
          cmd/console/fleetsocket_other.go: built only for other systems or tags
          cmd/console/servelock_windows.go: built only for other systems or tags
          cmd/moveprobe/detach_windows.go: built only for other systems or tags
          cmd/rootfswitness/mmap_other.go: built only for other systems or tags
          devbox_acl_other.go: built only for other systems or tags
          devbox_envfile_darwin_test.go: built only for other systems or tags
          devbox_envfile_other.go: built only for other systems or tags
          domains_transfer_signals_other.go: built only for other systems or tags
          interactive_term_darwin.go: built only for other systems or tags
          interactive_term_other.go: built only for other systems or tags
          internal/activator/claimprocess_root_other.go: built only for other systems or tags
          internal/activator/escrow_stamp_other.go: built only for other systems or tags
          internal/activator/fleetreserve_other.go: built only for other systems or tags
          internal/activator/harecord_other.go: built only for other systems or tags
          internal/activator/ownenv_other.go: built only for other systems or tags
          internal/activator/pty_other.go: built only for other systems or tags
          internal/activator/race_on_test.go: built only for other systems or tags
          internal/activator/rolelaunch_other.go: built only for other systems or tags
          internal/assetcache/statfs_other.go: built only for other systems or tags
          internal/boxself/io_other.go: built only for other systems or tags
          internal/cgroup/cleanup_other.go: built only for other systems or tags
          internal/cgroup/cleanup_other_test.go: built only for other systems or tags
          internal/cgroup/hostprocs_other.go: built only for other systems or tags
          internal/cgroup/recreate_other.go: built only for other systems or tags
          internal/cgroup/role_other.go: built only for other systems or tags
          internal/cgroup/shim_other.go: built only for other systems or tags
          internal/cgroup/strict_other.go: built only for other systems or tags
          internal/cgroup/verify_other.go: built only for other systems or tags
          internal/console/claim_sql_identity_other.go: built only for other systems or tags
          internal/console/geoipverify_other.go: built only for other systems or tags
          internal/console/hostreports_process_other.go: built only for other systems or tags
          internal/console/replicaview_other.go: built only for other systems or tags
          internal/console/restore_sim_nice_other_test.go: built only for other systems or tags
          internal/console/scalecost_other_test.go: built only for other systems or tags
          internal/console/seedscratch_windows.go: built only for other systems or tags
          internal/dbreads/worker_other.go: built only for other systems or tags
          internal/demobuild/security_other.go: built only for other systems or tags
          internal/democlaim/source_other.go: built only for other systems or tags
          internal/devbox/peer_darwin.go: built only for other systems or tags
          internal/devbox/peer_darwin_test.go: built only for other systems or tags
          internal/devbox/peer_other.go: built only for other systems or tags
          internal/devbox/socketcheck_other.go: built only for other systems or tags
          internal/domains/certimport_read_portable.go: built only for other systems or tags
          internal/edge/devboxpeer_other.go: built only for other systems or tags
          internal/edge/hairpin_other.go: built only for other systems or tags
          internal/edge/heldbudget_other.go: built only for other systems or tags
          internal/edge/purge_listen_unix.go: built only for other systems or tags
          internal/edge/purge_listen_windows.go: built only for other systems or tags
          internal/edge/race_on_test.go: built only for other systems or tags
          internal/edge/replicaconsole_owner_other.go: built only for other systems or tags
          internal/edge/replicaconsole_peer_other.go: built only for other systems or tags
          internal/edge/replicaconsole_socket_other_test.go: built only for other systems or tags
          internal/edge/static_artifact_other.go: built only for other systems or tags
          internal/edge/static_recordlock_other.go: built only for other systems or tags
          internal/edge/static_sweep_other.go: built only for other systems or tags
          internal/execsandbox/cleanup_other.go: built only for other systems or tags
          internal/execsandbox/file_other.go: built only for other systems or tags
          internal/execsandbox/oci_other.go: built only for other systems or tags
          internal/fileacl/fileacl_darwin.go: built only for other systems or tags
          internal/fileacl/fileacl_darwin_amd64.s: built only for other systems or tags
          internal/fileacl/fileacl_darwin_arm64.s: built only for other systems or tags
          internal/fileacl/fileacl_darwin_test.go: built only for other systems or tags
          internal/grouproll/state_other.go: built only for other systems or tags
          internal/grouprollaws/pty_darwin.go: built only for other systems or tags
          internal/grouprollaws/pty_other.go: built only for other systems or tags
          internal/hairpin/native_other.go: built only for other systems or tags
          internal/host/applylock_other_test.go: built only for other systems or tags
          internal/host/bootstrapfs_other.go: built only for other systems or tags
          internal/host/boxroles_config_other.go: built only for other systems or tags
          internal/host/claimfilesseed_delegation_other.go: built only for other systems or tags
          internal/host/claimfilesseed_transport_other.go: built only for other systems or tags
          internal/host/claimjournal_containment_other.go: built only for other systems or tags
          internal/host/claimjournal_migration_other.go: built only for other systems or tags
          internal/host/claimlaunch_kernel_other.go: built only for other systems or tags
          internal/host/claimlaunch_rev2_other_test.go: built only for other systems or tags
          internal/host/claimproduction_other.go: built only for other systems or tags
          internal/host/claimready_other.go: built only for other systems or tags
          internal/host/claimroleassembly_other.go: built only for other systems or tags
          internal/host/claimservingartifact_other.go: built only for other systems or tags
          internal/host/claimservinghandover_reboot_other.go: built only for other systems or tags
          internal/host/claimservinghandover_reboot_other_test.go: built only for other systems or tags
          internal/host/claimservingpark_other.go: built only for other systems or tags
          internal/host/claimstate_other.go: built only for other systems or tags
          internal/host/claimstop_kernel_other.go: built only for other systems or tags
          internal/host/claimtoken_inventory_other.go: built only for other systems or tags
          internal/host/claimunit_dropin_other.go: built only for other systems or tags
          internal/host/claimunit_files_other.go: built only for other systems or tags
          internal/host/claimunit_migrate_other.go: built only for other systems or tags
          internal/host/claimunit_ready_other.go: built only for other systems or tags
          internal/host/claimunit_socket_migration_other.go: built only for other systems or tags
          internal/host/consolefleet_owner_other.go: built only for other systems or tags
          internal/host/dbreads_other.go: built only for other systems or tags
          internal/host/egress_rail_other.go: built only for other systems or tags
          internal/host/fileowner_other.go: built only for other systems or tags
          internal/host/flock_windows.go: built only for other systems or tags
          internal/host/group_config_other.go: built only for other systems or tags
          internal/host/group_maintenance_other.go: built only for other systems or tags
          internal/host/group_maintenance_verbs_other.go: built only for other systems or tags
          internal/host/group_receipt_other.go: built only for other systems or tags
          internal/host/hadrain_call_other.go: built only for other systems or tags
          internal/host/hadrain_socket_other.go: built only for other systems or tags
          internal/host/hadrainfence_other.go: built only for other systems or tags
          internal/host/headroom_other.go: built only for other systems or tags
          internal/host/installchannel_other.go: built only for other systems or tags
          internal/host/managedboot_other.go: built only for other systems or tags
          internal/host/metrics_nested_other.go: built only for other systems or tags
          internal/host/movesfloor_other.go: built only for other systems or tags
          internal/host/movesfloorgate_other.go: built only for other systems or tags
          internal/host/movesheldrelease_other.go: built only for other systems or tags
          internal/host/movesmeasure_other.go: built only for other systems or tags
          internal/host/offcloudcredentials_other.go: built only for other systems or tags
          internal/host/registrychild_exec_other.go: built only for other systems or tags
          internal/host/registrychild_other.go: built only for other systems or tags
          internal/host/registryowner_chown_other.go: built only for other systems or tags
          internal/host/registryowner_descriptor_unix.go: built only for other systems or tags
          internal/host/replicahealth_other.go: built only for other systems or tags
          internal/host/rootgeneration_census_other.go: built only for other systems or tags
          internal/host/rootgeneration_kernel_other.go: built only for other systems or tags
          internal/host/rootgeneration_payload_other.go: built only for other systems or tags
          internal/host/rootgeneration_retired_other.go: built only for other systems or tags
          internal/host/rootmigration_production_other.go: built only for other systems or tags
          internal/host/runscset_other.go: built only for other systems or tags
          internal/host/sandboxenv_other.go: built only for other systems or tags
          internal/host/statfs_windows.go: built only for other systems or tags
          internal/host/systemapply_other.go: built only for other systems or tags
          internal/hostbox/census_vendor_other.go: built only for other systems or tags
          internal/hostbox/inventory_identity_other.go: built only for other systems or tags
          internal/hostbox/journalmigration_other.go: built only for other systems or tags
          internal/hostbox/journalnamespace_other.go: built only for other systems or tags
          internal/hostbox/journaltrust_other.go: built only for other systems or tags
          internal/hostbox/migration_census_other.go: built only for other systems or tags
          internal/hostbox/typedpark_other.go: built only for other systems or tags
          internal/hostenv/group_other.go: built only for other systems or tags
          internal/hostenv/write_other.go: built only for other systems or tags
          internal/hostenv/write_other_test.go: built only for other systems or tags
          internal/hostexec/clock_other.go: built only for other systems or tags
          internal/hostexec/clock_other_test.go: built only for other systems or tags
          internal/hostexec/local_other.go: built only for other systems or tags
          internal/hostexec/pending_other.go: built only for other systems or tags
          internal/hostexec/probe_other.go: built only for other systems or tags
          internal/hostexec/rootprocess_other.go: built only for other systems or tags
          internal/hostfiles/dir_other.go: built only for other systems or tags
          internal/hostfiles/refuse_other.go: built only for other systems or tags
          internal/hostfiles/watch_other.go: built only for other systems or tags
          internal/hostfloor/controllers_other.go: built only for other systems or tags
          internal/hostfloor/image_other.go: built only for other systems or tags
          internal/hostguard/flock_other.go: built only for other systems or tags
          internal/hostguard/flock_other_test.go: built only for other systems or tags
          internal/hostguard/record_other.go: built only for other systems or tags
          internal/instancectl/claimexec_other.go: built only for other systems or tags
          internal/instancectl/claimexec_socket_other.go: built only for other systems or tags
          internal/instancectl/claimlaunch_snapshot_other.go: built only for other systems or tags
          internal/instancectl/claimnetwork_other.go: built only for other systems or tags
          internal/instancectl/demo_snapshot_other.go: built only for other systems or tags
          internal/instancectl/egress_cgroup_other.go: built only for other systems or tags
          internal/instancectl/egress_dropin_other.go: built only for other systems or tags
          internal/instancectl/fleetsize_other.go: built only for other systems or tags
          internal/instancectl/gvisorprobe_other.go: built only for other systems or tags
          internal/instancectl/peer_other.go: built only for other systems or tags
          internal/instancectl/peer_tuple_other.go: built only for other systems or tags
          internal/instancectl/rootfs_identity_other.go: built only for other systems or tags
          internal/instanceexec/claimexec_other.go: built only for other systems or tags
          internal/instanceexec/exec_rootfs_other.go: built only for other systems or tags
          internal/instanceexec/netlink_route_other.go: built only for other systems or tags
          internal/instanceexec/probe_gvisor_other.go: built only for other systems or tags
          internal/instanceexec/probe_hardening_other.go: built only for other systems or tags
          internal/instanceexec/probe_other.go: built only for other systems or tags
          internal/instanceexec/probe_rootfs_other.go: built only for other systems or tags
          internal/instanceexec/sandbox_other.go: built only for other systems or tags
          internal/instanceexec/scope_other.go: built only for other systems or tags
          internal/instanceexec/stop_other.go: built only for other systems or tags
          internal/instanceexec/tty_other.go: built only for other systems or tags
          internal/instancefs/instancefs_other.go: built only for other systems or tags
          internal/launchd/activate_darwin.go: built only for other systems or tags
          internal/launchd/activate_darwin_amd64.s: built only for other systems or tags
          internal/launchd/activate_darwin_arm64.s: built only for other systems or tags
          internal/launchd/activate_darwin_test.go: built only for other systems or tags
          internal/layout/journal_other.go: built only for other systems or tags
          internal/layout/links_other.go: built only for other systems or tags
          internal/mailer/keys_other.go: built only for other systems or tags
          internal/maintenanceexec/run_other.go: built only for other systems or tags
          internal/managedboot/admission_other.go: built only for other systems or tags
          internal/managedboot/identity_other.go: built only for other systems or tags
          internal/mediahandler/collect_other.go: built only for other systems or tags
          internal/mediahandler/procs_other.go: built only for other systems or tags
          internal/medialocal/runner_other.go: built only for other systems or tags
          internal/moves/archive/open_other.go: built only for other systems or tags
          internal/moves/archive/sync_other.go: built only for other systems or tags
          internal/ops/flock_windows.go: built only for other systems or tags
          internal/park/local_other.go: built only for other systems or tags
          internal/privatefile/io_other.go: built only for other systems or tags
          internal/proxyproto/peek_other.go: built only for other systems or tags
          internal/relay/race_on_test.go: built only for other systems or tags
          internal/release/consumedfence_other.go: built only for other systems or tags
          internal/release/digestcache_other.go: built only for other systems or tags
          internal/rootaws/credentials_other.go: built only for other systems or tags
          internal/rootaws/open_darwin.go: built only for other systems or tags
          internal/rootfsimage/dir_other.go: built only for other systems or tags
          internal/rootstate/authoritydir_other.go: built only for other systems or tags
          internal/rootstate/authorityfile_other.go: built only for other systems or tags
          internal/rootstate/file_other.go: built only for other systems or tags
          internal/rootstate/link_other.go: built only for other systems or tags
          internal/rootstate/persistent_other.go: built only for other systems or tags
          internal/rootstate/state_other.go: built only for other systems or tags
          internal/safefile/file_other.go: built only for other systems or tags
          internal/safefile/reap_other.go: built only for other systems or tags
          internal/stopevidence/fds_other.go: built only for other systems or tags
          internal/stopevidence/fds_other_test.go: built only for other systems or tags
          internal/stopevidence/holders_other.go: built only for other systems or tags
          internal/stopevidence/reconstruct_other.go: built only for other systems or tags
          internal/team/storelock_other.go: built only for other systems or tags
          internal/team/storelock_windows.go: built only for other systems or tags
          move_offline_run_other.go: built only for other systems or tags
          system_group_other.go: built only for other systems or tags
        
    codehealth_test.go:115: fatal               1094 at  474 sites  log.Fatal*, (*log.Logger).Fatal* and os.Exit in the root package's production files
    codehealth_test.go:115: sleep               1005 at  811 sites  time.Sleep in test files
    codehealth_test.go:115: db-no-context        874 at  697 sites  database calls with no context (dbOpWithoutContext) in production files
    codehealth_test.go:115: host-context         188 at  142 sites  context.Background and context.TODO in internal/host production files
    codehealth_test.go:115: func-lines         18585 at   45 sites  functions over 300 code lines (blank and comment-only lines not counted)
    codehealth_test.go:115: file-lines         30685 at    8 sites  files over 3,000 code lines, counted the same way
    codehealth_test.go:115: release-importers     66 at    1 sites  packages whose production files import internal/release
--- PASS: TestCodeHealth (118.99s)
PASS
ok  	github.com/carlosframework/platform/internal/codehealth	120.130s
=== code-health-record ===
go version go1.26.10 linux/arm64
code-health record: HEAD is on main; comparing with its parent 7dbd8e1752550619b2dbeab1678d874093183e80
=== RUN   TestRecordAgainstBase
--- PASS: TestRecordAgainstBase (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/codehealth	0.009s
code-health record: no line went up without a reason
=== race ===
go version go1.26.10 linux/arm64
GATE_RACE=1 .amadan/test-gate.sh
=== internal_systemd@0 (14 s, from +14 s)
ok  	github.com/carlosframework/platform/internal/systemd	13.810s
=== internal_rootaws@0 (27 s, from +35 s)
ok  	github.com/carlosframework/platform/internal/rootaws	25.823s
=== internal_activator@0 (273 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	270.816s
=== internal_activator@1 (270 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	267.644s
=== internal_activator@2 (284 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	281.785s
=== internal_activator@3 (424 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	421.392s
=== internal_activator@4 (282 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	279.448s
=== internal_activator@5 (319 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	316.898s
=== internal_activator@6 (327 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	324.750s
=== internal_activator@7 (418 s, from +118 s)
ok  	github.com/carlosframework/platform/internal/activator	415.866s
=== internal_edge@0 (87 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	84.202s
=== internal_edge@1 (79 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	76.221s
=== internal_edge@2 (210 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	206.942s
=== internal_edge@3 (190 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	187.191s
=== internal_edge@4 (185 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	181.633s
=== internal_edge@5 (229 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	226.429s
=== internal_edge@6 (211 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	208.201s
=== internal_edge@7 (231 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	227.580s
=== internal_edge@8 (230 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	227.355s
=== internal_edge@9 (349 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	345.838s
=== internal_edge@10 (244 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	240.642s
=== internal_edge@11 (216 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	213.118s
=== internal_edge@12 (252 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	248.743s
=== internal_edge@13 (270 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	266.676s
=== internal_edge@14 (179 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	175.562s
=== internal_edge@15 (254 s, from +142 s)
ok  	github.com/carlosframework/platform/internal/edge	250.676s
=== internal_host@0 (9 s, from +206 s)
ok  	github.com/carlosframework/platform/internal/host	4.830s
=== internal_host@1 (18 s, from +206 s)
ok  	github.com/carlosframework/platform/internal/host	13.690s
=== lists: internal_edge 141 s, internal_activator 117 s, internal_host 206 s, internal_rootaws 35 s, internal_systemd 14 s
=== cpu: the gate used 7913 cpu-seconds in 542 s, about 14.6 of 32 cores; the machine as a whole was 45% busy
=== gitleaks ===
go version go1.26.10 linux/arm64
go: downloading github.com/zricethezav/gitleaks/v8 v8.30.1
go: downloading github.com/rs/zerolog v1.33.0
go: downloading github.com/spf13/viper v1.19.0
go: downloading github.com/spf13/cobra v1.9.1
go: downloading github.com/fatih/semgroup v1.2.0
go: downloading golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa
go: downloading github.com/hashicorp/go-version v1.7.0
go: downloading github.com/gitleaks/go-gitdiff v0.9.1
go: downloading github.com/BobuSumisu/aho-corasick v1.0.3
go: downloading github.com/h2non/filetype v1.1.3
go: downloading github.com/charmbracelet/lipgloss v0.5.0
go: downloading github.com/Masterminds/sprig/v3 v3.3.0
go: downloading github.com/mholt/archives v0.1.2
go: downloading github.com/muesli/termenv v0.15.1
go: downloading github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68
go: downloading github.com/mattn/go-runewidth v0.0.14
go: downloading github.com/lucasb-eyer/go-colorful v1.2.0
go: downloading golang.org/x/sync v0.11.0
go: downloading github.com/mitchellh/mapstructure v1.5.0
go: downloading github.com/fsnotify/fsnotify v1.8.0
go: downloading github.com/spf13/afero v1.12.0
go: downloading github.com/spf13/cast v1.7.1
go: downloading gopkg.in/yaml.v3 v3.0.1
go: downloading github.com/pelletier/go-toml/v2 v2.2.3
go: downloading github.com/subosito/gotenv v1.6.0
go: downloading github.com/hashicorp/hcl v1.0.0
go: downloading gopkg.in/ini.v1 v1.67.0
go: downloading github.com/magiconair/properties v1.8.9
go: downloading github.com/spf13/pflag v1.0.6
go: downloading github.com/sagikazarmark/slog-shim v0.1.0
go: downloading dario.cat/mergo v1.0.1
go: downloading github.com/Masterminds/semver/v3 v3.3.0
go: downloading github.com/Masterminds/goutils v1.1.1
go: downloading github.com/mitchellh/copystructure v1.2.0
go: downloading github.com/shopspring/decimal v1.4.0
go: downloading github.com/huandu/xstrings v1.5.0
go: downloading golang.org/x/crypto v0.35.0
go: downloading github.com/mattn/go-colorable v0.1.14
go: downloading golang.org/x/text v0.22.0
go: downloading github.com/mitchellh/reflectwalk v1.0.2
go: downloading golang.org/x/sys v0.30.0
go: downloading github.com/klauspost/compress v1.17.11
go: downloading github.com/minio/minlz v1.0.0
go: downloading github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707
go: downloading github.com/sorairolake/lzip-go v0.3.5
go: downloading github.com/pierrec/lz4/v4 v4.1.21
go: downloading github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3
go: downloading github.com/klauspost/pgzip v1.2.6
go: downloading github.com/nwaples/rardecode/v2 v2.1.0
go: downloading github.com/ulikunitz/xz v0.5.12
go: downloading github.com/therootcompany/xz v1.0.1
go: downloading github.com/STARRY-S/zip v0.2.1
go: downloading github.com/bodgit/sevenzip v1.6.0
go: downloading github.com/rivo/uniseg v0.2.0
go: downloading github.com/aymanbagabas/go-osc52/v2 v2.0.1
go: downloading github.com/bodgit/windows v1.0.1
go: downloading github.com/hashicorp/go-multierror v1.1.1
go: downloading github.com/hashicorp/golang-lru/v2 v2.0.7
go: downloading github.com/bodgit/plumbing v1.3.0
go: downloading go4.org v0.0.0-20230225012048-214862532bf5
go: downloading github.com/hashicorp/errwrap v1.1.0
self-test: reported source file: a key
self-test: reported source file: a 64-hex key
self-test: reported source file: a census-shaped entry
self-test: reported source file: a key marked gitleaks:allow
self-test: reported source file: a test's fake value outside tests
self-test: reported allowed file: another key beside its allowed value
self-test: reported a tracked file named gitleaks-gate-sentinel.env
self-test: reported 100 near misses of the names notscanned.go lists
self-test: skipped  the 33 files notscanned.go lists
self-test: refused  a notscanned.go entry git does not track
self-test: refused  a config that does not parse
self-test: refused  a config that does not exist
self-test: refused  a missing gitleaks binary
self-test: 6 planted keys reported, 134 tracked files judged, 3 broken setups refused
gitleaks: scanned 11886 tracked files; 33 not scanned, by exact path (scripts/gitleaks-gate/notscanned.go)
gitleaks: clean

landed from sec-console-dos

diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index 15515c446..b5da24a0c 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -1421,7 +1421,6 @@ db-no-context internal/console (*Store).CreateAccount (*sql.Tx).Exec 2
db-no-context internal/console (*Store).CreateAccount console.sqlHandle.Begin 1
db-no-context internal/console (*Store).CreateConfirmation console.sqlHandle.Exec 1
db-no-context internal/console (*Store).CreateDomainPurchase console.sqlHandle.Exec 1
-db-no-context internal/console (*Store).CreateEmailChallenge console.sqlHandle.Begin 1
db-no-context internal/console (*Store).CreateInvite console.sqlHandle.Exec 1
db-no-context internal/console (*Store).CreateSessionVia console.sqlHandle.Exec 1
db-no-context internal/console (*Store).DeferConnectorOutbox console.sqlHandle.Exec 1
@@ -1466,8 +1465,6 @@ db-no-context internal/console (*Store).HasApp console.sqlHandle.QueryRow 1
db-no-context internal/console (*Store).HasOwners console.sqlHandle.QueryRow 1
db-no-context internal/console (*Store).HasPayment console.sqlHandle.QueryRow 1
db-no-context internal/console (*Store).HoldConnectorOutbox console.sqlHandle.Exec 1
-db-no-context internal/console (*Store).HoldEmailChallenge (*sql.Tx).QueryRow 1
-db-no-context internal/console (*Store).HoldEmailChallenge console.sqlHandle.Begin 1
db-no-context internal/console (*Store).HoldMoveLog console.sqlHandle.Exec 1
db-no-context internal/console (*Store).InteractiveEndRecorded console.sqlHandle.QueryRow 1
db-no-context internal/console (*Store).IsOperator console.sqlHandle.QueryRow 1
@@ -1718,7 +1715,7 @@ db-no-context internal/console (*Store).migrateDemoReports console.sqlHandle.Exe
db-no-context internal/console (*Store).migrateDemoServing console.sqlHandle.Exec 2
db-no-context internal/console (*Store).migrateDemoServing console.sqlHandle.QueryRow 1
db-no-context internal/console (*Store).migrateDomains console.sqlHandle.Exec 2
-db-no-context internal/console (*Store).migrateEmailSignin console.sqlHandle.Exec 2
+db-no-context internal/console (*Store).migrateEmailSignin console.sqlHandle.Exec 1
db-no-context internal/console (*Store).migrateGettingStarted console.sqlHandle.Exec 1
db-no-context internal/console (*Store).migrateLinks console.sqlHandle.Exec 2
db-no-context internal/console (*Store).migrateManaged console.sqlHandle.Exec 4
@@ -2173,7 +2170,7 @@ host-context internal/host withEffectiveMovesFloorLock context.Background 2
func-lines . TestFleetAppServesThroughTheHub - 408
func-lines . runDeploy - 329
func-lines . runRoute - 519
-func-lines cmd/console serve - 366
+func-lines cmd/console serve - 361
func-lines internal/activator (*Service).doWakeOnce - 571 # raised: step 0.69, the one call that delivers an instance's config before its wake is planned (body in configbeforewake.go); before it, #1290 step 2c
func-lines internal/analytics Prune - 343
func-lines internal/appconfig SyncExecWithCallbacks - 320
@@ -2219,7 +2216,7 @@ file-lines . apimode.go - 4150
file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals
file-lines internal/activator activator.go - 3785 # raised: the Service.ConfigBeforeWake field and doWakeOnce's one call to it (the body lives in configbeforewake.go); before it, #1290 step 2c
file-lines internal/activator activator_test.go - 5471
-file-lines internal/console server.go - 4207 # raised: domain transfers Task 6, Config.LookupNS, LookupDS and DNSServer (the brief puts them on Config) and the transfer engine clock seam on Server
+file-lines internal/console server.go - 4190 # raised: domain transfers Task 6, Config.LookupNS, LookupDS and DNSServer (the brief puts them on Config) and the transfer engine clock seam on Server
file-lines internal/host agent.go - 3204
file-lines internal/provision reconcile_test.go - 3094
file-lines internal/registry registry_test.go - 3261
diff --git a/README.md b/README.md
index e7add6652..4b45833b9 100644
--- a/README.md
+++ b/README.md
@@ -609,6 +609,25 @@ Roll it in this order:
6. apply IAM step 2. condition the role's `iam:CreateUser` and `iam:PutUserPolicy` on `iam:PermissionsBoundary` equal to the boundary ARN. do this only after every console runs this release, because an older console creates users without the boundary and step 2 refuses them.
7. wait a few minutes for IAM to propagate, then run the check in step 5 again with your own operator credentials, not the console role. `iam:CreateAccessKey` cannot be conditioned on the boundary, so anyone holding the console role could have made an unbounded user between step 5 and step 2. delete any user without the boundary, or set the boundary on it. the gap is closed only when this second check is clean.
+### SES events on a secret path (2026-11-16)
+
+SES reports sends, bounces and complaints to the console through an SNS subscription to `POST /api/ses/events`. Anyone can post to that path, and a post naming a signing certificate the console has not seen makes it fetch one. Enough of those can use up the fetches a real notification needs after a restart or a certificate change. This release lets the path carry a secret, so only the SNS subscription can reach the code that reads the body or fetches anything.
+
+- `CARLOS_SES_EVENTS_TOKEN` is optional. Unset, nothing changes: SNS keeps posting to `/api/ses/events`.
+- Set, the console takes notifications only at `/api/ses/events/<token>`. The old path, and any other token, get the same 404 as a path that does not exist, before the console reads the body.
+- The token is a secret. Keep it where the console's other secrets live, never in a repo, a ticket or a log. The console never logs it.
+- A notification whose signing certificate the console cannot fetch right now gets a 503, which SNS retries. Before this release it got a 403, and SNS gives up on a 403.
+
+Switch over in a window, one console at a time:
+
+1. Roll the console to this release. Nothing changes yet.
+2. Make a token: `openssl rand -hex 32`.
+3. Set `CARLOS_SES_EVENTS_TOKEN` to it in the console's environment and restart the console. From now on it answers only the new path, so do steps 4 and 5 straight away. A notification sent in between gets a 404, and SNS does not retry a 404.
+4. Subscribe the SES events topic (`CARLOS_MAIL_SNS_TOPIC_ARN`) to `https://<console origin>/api/ses/events/<token>` over HTTPS. The console confirms the subscription itself. Check that `aws sns list-subscriptions-by-topic --topic-arn <arn>` shows the new endpoint with a subscription ARN, not `PendingConfirmation`.
+5. Delete the old subscription to `/api/ses/events` with `aws sns unsubscribe --subscription-arn <old arn>`.
+
+The subscription is not in this repo's `infra/`. Make the change wherever the deployment's SES events topic and its subscription are managed. If that is Terraform, change the endpoint there instead of by hand, or the next apply puts the old one back.
+
### App policies: egress allows and sizes (2026-10-25)
This release adds the app policy (#328, #329). A system operator can let an app's instances reach named private addresses with `carlos apps set --egress-allow`, and choose the size they run at with `carlos apps set --size` and `carlos instances set --size`. `carlos apps show` reads it back. Each app's policy is one signed object in the deployment bucket, under `control/app-policy/`.
diff --git a/cmd/console/main.go b/cmd/console/main.go
index 47f31ecc9..e6e615609 100644
--- a/cmd/console/main.go
+++ b/cmd/console/main.go
@@ -381,6 +381,20 @@ func startStoreObjectPasses(startClaimWorker func(name string)) {
startClaimWorker("StartMediaPass")
}
+// scanCallbackSigner is the scan webhook's signer from
+// CARLOS_SCAN_WEBHOOK_KEY (and _PREVIOUS while a key rolls), nil when no key
+// is set. A previous key with no current one is a misconfiguration.
+func scanCallbackSigner(getenv func(string) string) (*console.CallbackSigner, error) {
+ key, previous := getenv("CARLOS_SCAN_WEBHOOK_KEY"), getenv("CARLOS_SCAN_WEBHOOK_KEY_PREVIOUS")
+ if key == "" && previous != "" {
+ return nil, errors.New("console: CARLOS_SCAN_WEBHOOK_KEY_PREVIOUS is set without CARLOS_SCAN_WEBHOOK_KEY")
+ }
+ if key == "" {
+ return nil, nil
+ }
+ return console.NewCallbackSigner(key, previous)
+}
+
func serve() {
// The serve lock (servelock_*.go), held for the life of the process:
// the offline hosts-used verbs need the console stopped, and refuse
@@ -483,15 +497,9 @@ func serve() {
log.Fatalf("console: recording price book %s: %v", billingCfg.Book.Version, err)
}
}
- var callbackSigner *console.CallbackSigner
- if os.Getenv("CARLOS_SCAN_WEBHOOK_KEY") == "" && os.Getenv("CARLOS_SCAN_WEBHOOK_KEY_PREVIOUS") != "" {
- log.Fatal("console: CARLOS_SCAN_WEBHOOK_KEY_PREVIOUS is set without CARLOS_SCAN_WEBHOOK_KEY")
- }
- if os.Getenv("CARLOS_SCAN_WEBHOOK_KEY") != "" {
- callbackSigner, err = console.NewCallbackSigner(os.Getenv("CARLOS_SCAN_WEBHOOK_KEY"), os.Getenv("CARLOS_SCAN_WEBHOOK_KEY_PREVIOUS"))
- if err != nil {
- log.Fatal(err)
- }
+ callbackSigner, err := scanCallbackSigner(os.Getenv)
+ if err != nil {
+ log.Fatal(err)
}
mailDep := mailDeployment()
mailBoundary, err := mailUserBoundary(mailDep.Region, os.Getenv("CARLOS_MAIL_USER_BOUNDARY"))
@@ -572,6 +580,7 @@ func serve() {
DemoAbuseAddress: demoAbuseAddress,
Origin: origin,
Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"),
+ SESEventsToken: strings.TrimSpace(os.Getenv("CARLOS_SES_EVENTS_TOKEN")),
Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"),
Releases: rel,
AnalyticsRetentionDays: os.Getenv("CARLOS_ANALYTICS_RETENTION_DAYS"),
diff --git a/docs/parity.md b/docs/parity.md
index 6abeafb57..4b2e37f8a 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -509,6 +509,6 @@ Discussion #1289.
| alert-signing-key | platform | | `GET /alerts/signing-key` | The public key alert webhook receivers fetch. |
| legacy-apps | platform | | `GET /apps`<br>`GET /apps/{app}` | Old URLs kept as redirects into the account. |
| billing-webhook | platform | | `POST /billing/webhook` | Stripe calls it. |
-| ses-events | platform | | `POST /api/ses/events` | Amazon SES delivery events. |
+| ses-events | platform | | `POST /api/ses/events`<br>`POST /api/ses/events/{token}` | Amazon SES delivery events. |
| box-doors | platform | | `POST /api/fleet/enrol`<br>`POST /api/fleet/enrol/seed`<br>`POST /api/fleet/managed/secrets-key`<br>`GET /api/box/interactive/{id}`<br>`GET /api/box/runs/{id}`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/coordinator`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/release`<br>`POST /api/fleet/replicas/{account}/{app}/{host}/deploy`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/placed`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/failed`<br>`POST /api/fleet/seeds/{account}/{app}/{host}/rolledback` | Doors boxes and managed fleets call, not people. |
| plumbing | platform | `__demo-snapshot`<br>`__registry-child`<br>`__rootfs-check-probe`<br>`__rootfs-check-prepare`<br>`__cgexec`<br>`__cgprobe` | | Words the binary runs itself as, dispatched before the command switch. |
diff --git a/docs/superpowers/notes/census-proposal-sec-console-dos.md b/docs/superpowers/notes/census-proposal-sec-console-dos.md
new file mode 100644
index 000000000..bf984cefd
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-sec-console-dos.md
@@ -0,0 +1,11 @@
+# Census approval: sec-console-dos
+
+Ruling `census-ruling-sec-console-dos`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/apperr`, `internal/applog`, `internal/host`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `5933c519749247288b20f5d6e2398879ac7209d1bfeff2fb0d93d14b426f9e2f` → `5933c519749247288b20f5d6e2398879ac7209d1bfeff2fb0d93d14b426f9e2f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/2026-10-21-console-email-signin-copy-approved.json b/docs/superpowers/specs/2026-10-21-console-email-signin-copy-approved.json
index dee476dca..7cae27428 100644
--- a/docs/superpowers/specs/2026-10-21-console-email-signin-copy-approved.json
+++ b/docs/superpowers/specs/2026-10-21-console-email-signin-copy-approved.json
@@ -130,9 +130,9 @@
},
{
"id": "check.code_throttled",
- "text": "Too many wrong codes for this address. Use the link in the email, or try again later.",
+ "text": "Too many wrong codes. Use the link in the email, or try again later.",
"original": "Too many wrong codes for this address. Use the link in the email, or try again later.",
- "edited": false,
+ "edited": true,
"rerolled": false,
"rerolls": [],
"done": false
diff --git a/internal/apperr/read.go b/internal/apperr/read.go
index 96aac7cfc..c99760d22 100644
--- a/internal/apperr/read.go
+++ b/internal/apperr/read.go
@@ -32,6 +32,12 @@ func HourOf(t time.Time) string { return applog.HourOf(t) }
// EncodeChunk renders records as gzipped JSONL.
func EncodeChunk(recs []Record) ([]byte, error) { return applog.EncodeJSONL(recs) }
+// EncodeChunks renders records as the chunks a shipper writes, cut where
+// applog.EncodeJSONLChunks cuts.
+func EncodeChunks(recs []Record) ([][]Record, [][]byte, error) {
+ return applog.EncodeJSONLChunks(recs)
+}
+
// DecodeChunk parses a chunk, skipping malformed lines.
func DecodeChunk(b []byte) ([]Record, error) { return applog.DecodeJSONL[Record](b) }
diff --git a/internal/applog/chunk.go b/internal/applog/chunk.go
index b7935d7fa..350826325 100644
--- a/internal/applog/chunk.go
+++ b/internal/applog/chunk.go
@@ -184,25 +184,112 @@ func EncodeJSONL[T any](recs []T) ([]byte, error) {
return buf.Bytes(), nil
}
+// WriteChunkBytes and WriteChunkLines are where a writer cuts a chunk
+// (EncodeJSONLChunks): its serialised JSONL, before gzip, stays at or under
+// WriteChunkBytes (one record over it alone excepted) and its lines at or
+// under WriteChunkLines, a quarter and a half of what DecodeJSONL will read.
+// The size is measured after JSON escaping, which is what the reader sees:
+// a raw byte can become six (a NUL is \u0000), so 4096 pending 8 KiB lines
+// can serialise to over 192 MiB, and only cutting on the encoded size keeps
+// every chunk a writer makes readable (H5-M7 review 1).
+const (
+ WriteChunkBytes = 16 << 20
+ WriteChunkLines = MaxChunkLines / 2
+)
+
+// EncodeJSONLChunks renders recs, in order, as one or more gzipped JSONL
+// chunks cut at WriteChunkBytes and WriteChunkLines, returning each chunk's
+// records with its body. A shipper writes each as its own chunk, keyed by
+// its first record.
+func EncodeJSONLChunks[T any](recs []T) (runs [][]T, bodies [][]byte, err error) {
+ var line, run bytes.Buffer
+ enc := json.NewEncoder(&line)
+ start, n := 0, 0
+ cut := func(end int) error {
+ var buf bytes.Buffer
+ zw := gzip.NewWriter(&buf)
+ if _, err := zw.Write(run.Bytes()); err != nil {
+ return err
+ }
+ if err := zw.Close(); err != nil {
+ return err
+ }
+ runs, bodies = append(runs, recs[start:end:end]), append(bodies, buf.Bytes())
+ run.Reset()
+ start, n = end, 0
+ return nil
+ }
+ for i, r := range recs {
+ line.Reset()
+ if err := enc.Encode(r); err != nil {
+ return nil, nil, err
+ }
+ if n > 0 && (run.Len()+line.Len() > WriteChunkBytes || n >= WriteChunkLines) {
+ if err := cut(i); err != nil {
+ return nil, nil, err
+ }
+ }
+ run.Write(line.Bytes())
+ n++
+ }
+ if n > 0 {
+ if err := cut(len(recs)); err != nil {
+ return nil, nil, err
+ }
+ }
+ return runs, bodies, nil
+}
+
+// MaxChunkLines and MaxChunkBytes bound what DecodeJSONL will decode from
+// one chunk (H5-M7). A chunk is written by a box, so the reader cannot
+// trust its size: a few KiB of gzip can expand to hundreds of thousands of
+// records, all decoded before any filter or collect cap could drop them.
+// The bounds sit well above anything a shipper writes: host's logship and
+// errship cut their chunks at WriteChunkBytes and WriteChunkLines
+// (EncodeJSONLChunks). A chunk written before that cut could serialise
+// past MaxChunkBytes only through pathological escaping (thousands of
+// pending lines of control characters, each byte six on the wire); such a
+// chunk is refused here and its read reports itself truncated (ReadChunks).
+const (
+ MaxChunkLines = 8192
+ MaxChunkBytes = 64 << 20
+)
+
+// ErrChunkTooLarge is DecodeJSONL refusing a chunk past MaxChunkLines or
+// MaxChunkBytes. No current shipper writes one, so it is not a log to show.
+var ErrChunkTooLarge = errors.New("applog: chunk decodes past its bound")
+
// DecodeJSONL parses a chunk, skipping malformed lines rather than failing
// the whole object — one corrupt line must not cost the member the rest of
// the hour. Corrupt gzip is an error: that is a broken object, not a line.
+// A chunk that decodes past MaxChunkLines lines or MaxChunkBytes bytes is
+// refused whole with ErrChunkTooLarge, and decoding stops at the bound: the
+// gzip stream is read through a limit one byte over MaxChunkBytes, which is
+// how an over-long stream shows itself.
func DecodeJSONL[T any](b []byte) ([]T, error) {
zr, err := gzip.NewReader(bytes.NewReader(b))
if err != nil {
return nil, err
}
defer zr.Close()
+ lr := &io.LimitedReader{R: zr, N: MaxChunkBytes + 1}
var out []T
- sc := bufio.NewScanner(zr)
+ sc := bufio.NewScanner(lr)
sc.Buffer(nil, 1<<20) // lines are capped well below this at the tee
+ lines := 0
for sc.Scan() {
+ if lines++; lines > MaxChunkLines {
+ return nil, ErrChunkTooLarge
+ }
var r T
if json.Unmarshal(sc.Bytes(), &r) != nil {
continue
}
out = append(out, r)
}
+ if lr.N <= 0 {
+ return nil, ErrChunkTooLarge
+ }
if err := sc.Err(); err != nil && err != io.EOF {
return out, err
}
@@ -212,5 +299,9 @@ func DecodeJSONL[T any](b []byte) ([]T, error) {
// EncodeChunk renders log records: EncodeJSONL over Record.
func EncodeChunk(recs []Record) ([]byte, error) { return EncodeJSONL(recs) }
+// EncodeChunks renders log records as the chunks a shipper writes:
+// EncodeJSONLChunks over Record.
+func EncodeChunks(recs []Record) ([][]Record, [][]byte, error) { return EncodeJSONLChunks(recs) }
+
// DecodeChunk parses a log chunk: DecodeJSONL over Record.
func DecodeChunk(b []byte) ([]Record, error) { return DecodeJSONL[Record](b) }
diff --git a/internal/applog/chunk_test.go b/internal/applog/chunk_test.go
index fb9d00c32..8097cec5f 100644
--- a/internal/applog/chunk_test.go
+++ b/internal/applog/chunk_test.go
@@ -3,7 +3,9 @@ package applog
import (
"bytes"
"compress/gzip"
+ "errors"
"io"
+ "strings"
"testing"
"time"
)
@@ -188,3 +190,66 @@ func must(t testing.TB) func(string, error) string {
return k
}
}
+
+// A chunk is box-written, so its decoded size is not trusted (H5-M7):
+// past MaxChunkLines lines or MaxChunkBytes bytes it is refused whole,
+// and a chunk at the bounds still decodes.
+func TestDecodeJSONLRefusesPastItsBounds(t *testing.T) {
+ line := `{"msg":"x"}` + "\n"
+ atLines := mustGzip(t, bytes.Repeat([]byte(line), MaxChunkLines))
+ if recs, err := DecodeChunk(atLines); err != nil || len(recs) != MaxChunkLines {
+ t.Fatalf("chunk of exactly MaxChunkLines: %d records, %v", len(recs), err)
+ }
+ overLines := mustGzip(t, bytes.Repeat([]byte(line), MaxChunkLines+1))
+ if recs, err := DecodeChunk(overLines); !errors.Is(err, ErrChunkTooLarge) || recs != nil {
+ t.Fatalf("chunk of MaxChunkLines+1: %d records, %v; want ErrChunkTooLarge", len(recs), err)
+ }
+ // Few lines, many bytes: whitespace padding carries the size.
+ pad := bytes.Repeat([]byte(" "), 1<<20-1)
+ var big []byte
+ for len(big) <= MaxChunkBytes {
+ big = append(big, pad...)
+ big = append(big, '\n')
+ }
+ if recs, err := DecodeChunk(mustGzip(t, big)); !errors.Is(err, ErrChunkTooLarge) || recs != nil {
+ t.Fatalf("chunk over MaxChunkBytes: %d records, %v; want ErrChunkTooLarge", len(recs), err)
+ }
+}
+
+// EncodeJSONLChunks cuts on the serialised size the reader will see, escaping
+// included (H5-M7 review 1): every chunk decodes within WriteChunkBytes and
+// WriteChunkLines, and the runs are recs in order.
+func TestEncodeJSONLChunksCutsAtTheWriteBound(t *testing.T) {
+ msg := strings.Repeat("\x00", 8<<10) // 8 KiB on the tee, 48 KiB as JSON
+ var recs []Record
+ for i := 0; i < 1000; i++ {
+ recs = append(recs, Record{Seq: uint64(i), Msg: msg})
+ }
+ for i := 0; i < 2*WriteChunkLines; i++ { // tiny lines: the line cut
+ recs = append(recs, Record{Seq: uint64(1000 + i)})
+ }
+ runs, bodies, err := EncodeJSONLChunks(recs)
+ if err != nil || len(runs) != len(bodies) || len(runs) < 4 {
+ t.Fatalf("%d runs, %d bodies, %v", len(runs), len(bodies), err)
+ }
+ next := 0
+ for i, run := range runs {
+ raw := mustGunzip(t, bodies[i])
+ if len(raw) > WriteChunkBytes || len(run) > WriteChunkLines {
+ t.Fatalf("chunk %d: %d bytes, %d lines; want at most %d and %d", i, len(raw), len(run), WriteChunkBytes, WriteChunkLines)
+ }
+ got, err := DecodeChunk(bodies[i])
+ if err != nil || len(got) != len(run) {
+ t.Fatalf("chunk %d decodes to %d records, %v; want %d", i, len(got), err, len(run))
+ }
+ for _, r := range run {
+ if r.Seq != uint64(next) {
+ t.Fatalf("chunk %d holds seq %d, want %d", i, r.Seq, next)
+ }
+ next++
+ }
+ }
+ if next != len(recs) {
+ t.Fatalf("runs hold %d records, want %d", next, len(recs))
+ }
+}
diff --git a/internal/applog/read.go b/internal/applog/read.go
index 207a4946c..16067faa0 100644
--- a/internal/applog/read.go
+++ b/internal/applog/read.go
@@ -2,6 +2,7 @@ package applog
import (
"context"
+ "errors"
"strings"
"sync"
"time"
@@ -23,8 +24,10 @@ const readConcurrency = 16
// order. Hour pruning happens at the PREFIX level — an hour outside the
// window is never listed, which is what makes a 1h read over 7d of history
// cheap (spec §3). collectCap bounds memory per box: past it the OLDEST
-// records go and trimmed says so. Store errors fail the read — a partial
-// answer that looks whole is the one thing this must never produce.
+// records go and trimmed says so. A chunk DecodeJSONL refuses as too large
+// (ErrChunkTooLarge) is left out, and trimmed says that too. Store errors
+// fail the read — a partial answer that looks whole is the one thing this
+// must never produce.
//
// Listings and GETs run readConcurrency at a time, but the answer is
// assembled strictly in listing order, so it is exactly what a serial walk
@@ -87,8 +90,9 @@ func ReadChunks[T any](ctx context.Context, s release.Store, prefix string, sinc
// fetch whose result is never read (the read failed first) still ends;
// the feeder stops at cancel.
type fetched struct {
- recs []T
- err error
+ recs []T
+ refused bool // DecodeJSONL refused the chunk as too large
+ err error
}
slots := make([]chan fetched, len(chunks))
for i := range slots {
@@ -109,6 +113,12 @@ func ReadChunks[T any](ctx context.Context, s release.Store, prefix string, sinc
return
}
all, err := DecodeJSONL[T](body)
+ if errors.Is(err, ErrChunkTooLarge) {
+ // Not a chunk any shipper writes: leave it out and
+ // say the answer is not the whole window.
+ slots[i] <- fetched{refused: true}
+ return
+ }
if err != nil {
slots[i] <- fetched{err: err}
return
@@ -136,6 +146,9 @@ func ReadChunks[T any](ctx context.Context, s release.Store, prefix string, sinc
if f.err != nil {
return nil, false, f.err
}
+ if f.refused {
+ trimmed = true
+ }
recs := append(perBox[c.box], f.recs...)
if over := len(recs) - collectCap; over > 0 {
recs = recs[over:]
diff --git a/internal/applog/read_test.go b/internal/applog/read_test.go
index 316484154..ba3aae73a 100644
--- a/internal/applog/read_test.go
+++ b/internal/applog/read_test.go
@@ -223,3 +223,32 @@ func TestReadChunksConcurrentIsSerialOrder(t *testing.T) {
t.Fatal("a failed chunk must fail the read, never return a partial answer")
}
}
+
+// A chunk DecodeJSONL refuses as too large (H5-M7) is left out of the
+// answer, which says it is not the whole window; the other chunks read.
+func TestReadChunksSkipsARefusedChunk(t *testing.T) {
+ ctx := context.Background()
+ s := release.NewDirStore(t.TempDir())
+ now := time.Date(2026, 9, 7, 10, 30, 0, 0, time.UTC)
+ good, _ := EncodeChunk([]Record{{TS: now, Box: "box1", Seq: 1, Stream: StreamApp, Msg: "kept"}})
+ var lines []Record
+ for i := 0; i <= MaxChunkLines; i++ {
+ lines = append(lines, Record{TS: now, Box: "box1", Seq: uint64(2 + i), Stream: StreamApp})
+ }
+ bad, _ := EncodeChunk(lines)
+ for seq, body := range map[uint64][]byte{1: good, 2: bad} {
+ if _, err := s.Put(ctx, must(t)(ChunkKey("bde", "ledgerpay", "box1", HourOf(now), seq, len(body))), body, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ perBox, trimmed, err := ReadChunks[Record](ctx, s, must(t)(Prefix("bde", "ledgerpay")), time.Time{}, time.Time{}, func(Record) bool { return true }, 1000)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !trimmed {
+ t.Error("trimmed = false; a refused chunk must mark the answer partial")
+ }
+ if len(perBox) != 1 || len(perBox[0]) != 1 || perBox[0][0].Msg != "kept" {
+ t.Fatalf("perBox = %+v; want only the good chunk's record", perBox)
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index bc5f48699..219de8dc5 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -1551,6 +1551,30 @@ var claimFixtures = map[string]claimFixture{
},
}},
+ "route POST /api/ses/events/{token}": {door: &claimDoor{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) {
+ cx.srv.cfg.SESEventsToken = "claim-fixture-ses-token" // the secret door (H5-M12 review 2)
+ cx.srv.snsVerify = func(snsEnvelope) error { return nil } // the signature check's own seam
+ cx.emailProvisioned(t)
+ },
+ // The same Send through the token door, which runs the same ingest.
+ // A Send named by the app's own IAM user: the named path writes the
+ // app's log rows (mail_events), its per-sender count
+ // (mail_sender_counts) and its caller-class count
+ // (mail_caller_sends, platform mail submission Task 2), all under
+ // bab/titogo's permit.
+ do: func(t *testing.T, cx *claimCase) int {
+ resp := sesPostPath(t, cx.consoleFixture, "/api/ses/events/claim-fixture-ses-token", `{"Type":"Notification","TopicArn":"arn:aws:sns:eu-west-1:1:carlos-mail",`+
+ `"Message":"{\"eventType\":\"Send\",\"mail\":{\"source\":\"hello@`+claimMailDomain+`\",`+
+ `\"messageId\":\"claim-fixture-message\",\"destination\":[\"claim@example.com\"],`+
+ `\"tags\":{\"ses:caller-identity\":[\"carlos-mail-bab-titogo\"]}}}",`+
+ `"SigningCertURL":"https://sns.eu-west-1.amazonaws.com/x.pem","Signature":"x"}`)
+ resp.Body.Close()
+ return resp.StatusCode
+ },
+ }},
+
// The billing webhook re-reads a subscription and writes the account's
// plan row and billing state (plans 6a).
"route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"),
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go
index d809e95ec..4c1538820 100644
--- a/internal/console/claim_invariant_probes_nonapp_test.go
+++ b/internal/console/claim_invariant_probes_nonapp_test.go
@@ -160,7 +160,7 @@ func claimEmailChallengeWorld(t *testing.T, cx *claimCase) {
if err != nil {
t.Fatal(err)
}
- link, code, err := cx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner, FlowHash: hashToken(flow)}, time.Now())
+ link, code, _, err := cx.st.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: ChallengeSignIn, Address: claimFxOwner, FlowHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_claim_auth.go b/internal/console/demo_claim_auth.go
index 7fabb692c..d261c0250 100644
--- a/internal/console/demo_claim_auth.go
+++ b/internal/console/demo_claim_auth.go
@@ -217,11 +217,8 @@ func (s *Server) handleDemoClaimStart(w http.ResponseWriter, r *http.Request) {
return nil
}
c := EmailChallenge{Purpose: ChallengeDemoClaim, FlowHash: flow.Hash, Address: flow.Address, ExpiresAt: flow.ExpiresAt}
- if !s.limits.signinSend(address, ip) {
- return s.store.HoldEmailChallenge(c, now)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- sent = err == nil
+ // The send limits' clock decides the repeat rule, as for sign-in.
+ link, code, sent, err = s.store.CreateEmailChallenge(r.Context(), c, s.limits.clock(), func() bool { return s.limits.signinSend(address, ip) })
return err
})
if err != nil {
@@ -264,7 +261,7 @@ func (s *Server) handleDemoClaimVerify(w http.ResponseWriter, r *http.Request) {
if s.cfg.DemoAPIOrigin == "" {
ip = s.clientIP(r)
}
- done, ok := s.limits.reserveGuess(c.Address, ip)
+ done, ok := s.limits.reserveCodeGuess(c, ip)
if !ok {
jsonError(w, 401, demoClaimBadProof)
return
diff --git a/internal/console/demo_claim_auth_test.go b/internal/console/demo_claim_auth_test.go
index df6b70d6d..52af7392a 100644
--- a/internal/console/demo_claim_auth_test.go
+++ b/internal/console/demo_claim_auth_test.go
@@ -130,7 +130,7 @@ func TestDemoClaimProofBinding(t *testing.T) {
purpose = ChallengeStepUp
}
var err error
- _, code, err = s.store.CreateEmailChallenge(EmailChallenge{Purpose: purpose, Address: "shop@example.com", FlowHash: hashToken(flow), SessionHash: hashToken(flow)}, time.Now())
+ _, code, _, err = s.store.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: purpose, Address: "shop@example.com", FlowHash: hashToken(flow), SessionHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
@@ -338,7 +338,7 @@ func TestDemoClaimSharedLimits(t *testing.T) {
}
})
}
- for _, cap := range []string{"challenge", "address", "ip"} {
+ for _, cap := range []string{"challenge", "ip"} {
t.Run("guess_"+cap, func(t *testing.T) {
s, m, token := claimTestServer(t)
flow, _ := claimStart(t, s, token, "shop@example.com", "")
@@ -350,17 +350,9 @@ func TestDemoClaimSharedLimits(t *testing.T) {
t.Fatal("bad code worked")
}
}
- case "address":
- for i := 0; i < 10; i++ {
- done, ok := s.limits.reserveGuess("shop@example.com", "other-ip")
- if !ok {
- t.Fatal("early guess refusal")
- }
- done(false)
- }
case "ip":
for i := 0; i < 30; i++ {
- done, ok := s.limits.reserveGuess(fmt.Sprintf("shop%d@example.com", i), "192.0.2.10")
+ done, ok := s.limits.reserveCodeGuess(&EmailChallenge{Purpose: ChallengeDemoClaim, Address: fmt.Sprintf("shop%d@example.com", i)}, "192.0.2.10")
if !ok {
t.Fatal("early IP guess refusal")
}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 089a65c08..a267ee6a0 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -434,7 +434,7 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
}
- done, ok := s.limits.reserveGuess(c.Address, ip)
+ done, ok := s.limits.reserveCodeGuess(c, ip)
if !ok {
s.demoClaimBrowserError(w, 401, demoClaimBadProof)
return
@@ -504,11 +504,8 @@ func (s *Server) handleDemoClaimBrowserProof(w http.ResponseWriter, r *http.Requ
return nil
}
c := EmailChallenge{Purpose: ChallengeDemoClaim, FlowHash: f.Hash, Address: address, ExpiresAt: f.ExpiresAt}
- if !s.limits.signinSend(address, ip) {
- return s.store.HoldEmailChallenge(c, now)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- sent = err == nil
+ // The send limits' clock decides the repeat rule, as for sign-in.
+ link, code, sent, err = s.store.CreateEmailChallenge(r.Context(), c, s.limits.clock(), func() bool { return s.limits.signinSend(address, ip) })
return err
})
mu.Unlock()
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
index aa6d04f93..a0834c56c 100644
--- a/internal/console/emailsignin.go
+++ b/internal/console/emailsignin.go
@@ -435,16 +435,17 @@ func (s *Server) handleEmailLink(w http.ResponseWriter, r *http.Request) {
// handleEmailCode is POST /auth/email/code (spec 5.2): the typed code is
// checked only against the newest live sign-in challenge of this browser's
// flow. A challenge that was sent and one a refused request recorded unsent
-// answer alike, so the code box says nothing about throttling. Wrong codes
-// count against the challenge's address and the client IP across every
-// challenge (spec 5); past either cap the code is refused unchecked and
-// nothing is burned, so the emailed link still works.
+// answer alike, so the code box says nothing about throttling or about the
+// address. Five wrong codes burn the challenge; wrong codes also count
+// against the client IP across every challenge, and past that cap the code
+// is refused unchecked and nothing is burned, so the emailed link still
+// works. Nothing counts per address: see reserveCodeGuess for the bound.
func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
if !s.sameOrigin(r) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
- now := time.Now()
+ now := s.limits.clock() // handleContinue's clock
flow := s.requestFlow(r)
// The page shows the address and next the form carried, never the stored
// challenge's: shown only, never used as a key.
@@ -459,7 +460,7 @@ func (s *Server) handleEmailCode(w http.ResponseWriter, r *http.Request) {
// One guess is reserved before the check, so concurrent guesses cannot all
// pass on the same count; only a right code takes it back.
ip := s.clientIP(r)
- done, allowed := s.limits.reserveGuess(c.Address, ip)
+ done, allowed := s.limits.reserveCodeGuess(c, ip)
if !allowed {
log.Printf("console: code for %s from %s refused: too many wrong codes", c.Address, ip)
s.renderCheckError(w, flow, addr, next, copyText("check.code_throttled"))
@@ -515,13 +516,13 @@ func (s *Server) emailStepUp(w http.ResponseWriter, r *http.Request, addr, raw s
return false
}
// It replaces this session's earlier step-up challenge, if any.
- link, code, err := s.store.CreateEmailChallenge(EmailChallenge{
+ link, code, _, err := s.store.CreateEmailChallenge(r.Context(), EmailChallenge{
Purpose: ChallengeStepUp,
Address: addr,
SessionHash: hashToken(raw),
PendingHash: hashToken(pending),
ExpiresAt: now.Add(stepUpFlowTTL),
- }, now)
+ }, now, nil)
if err != nil {
log.Printf("console: step-up challenge for %s: %v", addr, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the confirmation. Please try again.")
@@ -617,8 +618,9 @@ func (s *Server) stepUpLink(w http.ResponseWriter, r *http.Request, link string,
// handleStepUpEmailCode is POST /auth/email/stepup/code: the typed code is
// checked only against the newest live step-up challenge made for this
-// browser's session. Wrong codes count against the
-// challenge's address and the client IP, as for sign-in codes.
+// browser's session. Wrong codes count against the client IP, as for
+// sign-in codes, and against this session's own step-up budget, which no
+// other browser can spend (reserveCodeGuess).
func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) {
addr, raw, ok := s.session(r)
if !ok {
@@ -636,7 +638,7 @@ func (s *Server) handleStepUpEmailCode(w http.ResponseWriter, r *http.Request) {
return
}
ip := s.clientIP(r)
- done, allowed := s.limits.reserveGuess(c.Address, ip)
+ done, allowed := s.limits.reserveCodeGuess(c, ip)
if !allowed {
log.Printf("console: step-up code for %s from %s refused: too many wrong codes", c.Address, ip)
s.renderStepUp(w, r, c.Address, copyText("check.code_throttled"))
@@ -676,3 +678,38 @@ func (s *Server) finishStepUp(w http.ResponseWriter, r *http.Request, addr, raw
}
s.resume(w, r, pending)
}
+
+// signinChallenge is the front door's limits and challenge write for one
+// flow, under that flow's lock, so overlapping submissions from one browser
+// take turns. Accepted (under the submission cap and every send limit), it
+// records a new sign-in challenge for the flow, replacing the flow's earlier
+// ones, and returns its link and code to send. Refused, it sends nothing and
+// leaves the flow's live challenge, if any, untouched, so the email already
+// sent keeps working. Over the submission cap it writes nothing at all: that
+// throttle is the requester's own IP and says nothing about anyone else, so
+// the code box may answer "used up" there. Refused by the send limits (which
+// the submission cap bounds to 30 an hour per IP), a flow with no live
+// challenge gets one nobody is ever told the link or code of, so a code
+// typed next answers exactly as it would against a sent one.
+func (s *Server) signinChallenge(ctx context.Context, flow, addr, next, ip string, underCap bool, now time.Time) (link, code string, sent bool, err error) {
+ mu := s.flowLock(flow)
+ mu.Lock()
+ defer mu.Unlock()
+ if !underCap {
+ return "", "", false, nil
+ }
+ c := EmailChallenge{Purpose: ChallengeSignIn, Address: addr, Next: next, FlowHash: hashToken(flow)}
+ known, err := s.store.KnownAddress(ctx, addr, now)
+ if err != nil {
+ return "", "", false, err
+ }
+ asked, allowed := false, false
+ link, code, sent, err = s.store.CreateEmailChallenge(ctx, c, now, func() bool {
+ asked, allowed = true, s.limits.signinSendTo(addr, ip, known)
+ return allowed
+ })
+ if asked && !allowed {
+ log.Printf("console: sign-in email to %s from %s refused by its limits; not sent", addr, ip)
+ }
+ return link, code, sent, err
+}
diff --git a/internal/console/emailsignin_limits.go b/internal/console/emailsignin_limits.go
index c7c297cad..56406a679 100644
--- a/internal/console/emailsignin_limits.go
+++ b/internal/console/emailsignin_limits.go
@@ -20,11 +20,13 @@ const (
signinPerAddrHour = 5 // sign-in emails per address
signinPerAddrDay = 20 // sign-in emails per address
signinPerIPHour = 10 // sign-in emails per IP
- signinGlobalHour = 200 // sign-in emails console-wide
+ signinGlobalHour = 200 // sign-in emails console-wide (see signinSendTo)
+ knownPastCapHour = 5 // sign-in emails per known address past the console-wide cap
+ knownPastCapDay = 10 // sign-in emails per known address past the console-wide cap
newPersonPerIPHour = 10 // new people per IP
newPersonGlobalHour = 200 // new people console-wide
stepUpPerAddrHour = 10 // step-up emails per address
- wrongCodesPerAddrDay = 10 // wrong codes per address
+ wrongCodesPerSessDay = 10 // wrong step-up codes per session
wrongCodesPerIPHour = 30 // wrong codes per IP
// Alert confirmations (fleet alerts spec §5.3): every verify row that
@@ -138,8 +140,9 @@ type emailLimits struct {
addrSends keyedWindow // sign-in emails, by address
ipSends keyedWindow // sign-in emails, by IP
globalSend []time.Time // sign-in emails, console-wide
+ pastCap keyedWindow // known addresses' sign-in emails past the console-wide cap, by address
stepUps keyedWindow // step-up emails, by address
- addrWrong keyedWindow // wrong codes, by address
+ stepWrong keyedWindow // wrong step-up codes, by session hash
ipWrong keyedWindow // wrong codes, by IP
alertConfirms keyedWindow // alert confirmation sends, by alert scope
@@ -174,7 +177,7 @@ func (l *emailLimits) submit(ip string) bool {
}
func (l *emailLimits) sweepWindows() []*keyedWindow {
- return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.addrWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
+ return []*keyedWindow{&l.submits, &l.addrSends, &l.ipSends, &l.stepUps, &l.pastCap, &l.stepWrong, &l.ipWrong, &l.alertConfirms, &l.ipNewPeople}
}
// newPerson reserves one new-person slot across all sign-in paths (social
@@ -223,11 +226,29 @@ func (l *emailLimits) sweep(now time.Time) int {
return limitSweepBudget - budget
}
-// signinSend reports whether a sign-in email may go to addr from ip, and if so
-// records it in every window. All or nothing: a refusal by any one limit
-// charges none of them, so a refused call does not push any window forward.
-// Callers pass addr canonical (trimmed, lower-cased).
+// signinSend is signinSendTo for an address the console does not know: every
+// limit applies, the console-wide one included.
func (l *emailLimits) signinSend(addr, ip string) bool {
+ return l.signinSendTo(addr, ip, false)
+}
+
+// signinSendTo reports whether a sign-in email may go to addr from ip, and
+// records it. Callers pass addr canonical (trimmed, lower-cased).
+//
+// Every shared window (the address's, the IP's, the console-wide one) is
+// decided and charged exactly as for an unknown address, all or nothing: a
+// refusal by any one limit charges none of them. So their state never
+// depends on whether the console knows addr, and nothing a requester can
+// see later (its own sends, another address's) can tell (H4-M5/M6 review 2).
+//
+// The console-wide cap is a backstop against spraying mail at strangers. A
+// few dozen client addresses (one IPv6 /64 holds plenty) can fill it, which
+// must not stop existing people signing in by email (H4-M5). So when the
+// console-wide cap is the ONLY refusal and addr is known (Store.KnownAddress),
+// the email still goes, charged to pastCap alone: its own budget of
+// knownPastCapHour and knownPastCapDay per address with the usual 60-second
+// gap, which nothing but this decision reads.
+func (l *emailLimits) signinSendTo(addr, ip string, known bool) bool {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clock()
@@ -255,7 +276,16 @@ func (l *emailLimits) signinSend(addr, ip string) bool {
}
l.globalSend = kept
if len(kept) >= signinGlobalHour {
- return false
+ if !known {
+ return false
+ }
+ l.pastCap.trim(addr, now)
+ if _, ok := l.pastCap.last(addr, now.Add(-emailResendGap)); ok ||
+ l.pastCap.count(addr, hour) >= knownPastCapHour || l.pastCap.count(addr, day) >= knownPastCapDay {
+ return false
+ }
+ l.pastCap.add(addr, now)
+ return true
}
l.addrSends.add(addr, now)
@@ -302,25 +332,63 @@ func (l *emailLimits) stepUpSend(addr string) bool {
return true
}
-// reserveGuess is the guessing cap as one step, so concurrent guesses cannot
-// all pass on the same count. Under the lock it refuses (allowed false) once
-// addr has 10 guesses in 24 hours or ip has 30 in an hour; otherwise it
-// records one guess against both at once and returns done, through which the
-// caller reports the verdict: done(true), a right code, takes the reservation
-// back; done(false), any other outcome, keeps it as a wrong code. done acts
-// once; later calls do nothing. Refused, done is a no-op.
-// Callers pass addr canonical (trimmed, lower-cased).
-func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed bool) {
+// reserveCodeGuess is the guessing cap for a code typed against c, as one
+// step, so concurrent guesses cannot all pass on the same count. Under the
+// lock it refuses (allowed false) once ip has 30 wrong codes in an hour or,
+// for a step-up, c's session has 10 in 24 hours; otherwise it records one
+// guess and returns done, through which the caller reports the verdict:
+// done(true), a right code, takes the reservation back; done(false), any
+// other outcome, keeps it as a wrong code. done acts once; later calls do
+// nothing. Refused, done is a no-op.
+//
+// There is no per-address budget (H4-M6). Anyone who knows an address can
+// open sign-in flows for it, so a budget keyed by the address was one a
+// stranger could spend, locking the owner's own right code out for a day;
+// and since a held challenge and a sent one had to be charged alike or tell
+// the requester which it was, keeping it meant also keeping that lockout.
+// Guessing is bounded instead by what a guess can reach:
+// - A code is checked only against the newest challenge of the guessing
+// browser's own flow, and the fifth wrong code burns it
+// (emailCodeAttempts, counted in the row).
+// - A held challenge (one Store.CreateEmailChallenge made unsent) never redeems a code: its
+// code was never sent. Guessing it is worthless, so its number is
+// unbounded without harm.
+// - A sent challenge exists only when signinSendTo lets an email go to
+// the address: at most signinPerAddrDay (20) a day, demo claims
+// included, plus, for a known address while the console-wide cap is
+// full, knownPastCapDay (10) more.
+//
+// So an address faces at most 30 x 5 = 150 guesses a day at codes that
+// redeem, each right with probability 1 in 10^6: at most 1.5e-4 a day, about
+// 5.3% over a year of continuous attack on one address. A restart resets the
+// send windows (see the top of this file) and buys a fresh day; the IP
+// budget below caps how fast any one client gets there. Step-up codes go to
+// a budget keyed by the session that asked (only that session can type
+// them), so no one else can spend it.
+func (l *emailLimits) reserveCodeGuess(c *EmailChallenge, ip string) (done func(ok bool), allowed bool) {
+ if c.Purpose == ChallengeStepUp {
+ return l.reserveGuessIn(&l.stepWrong, c.SessionHash, ip)
+ }
+ return l.reserveGuessIn(nil, "", ip)
+}
+
+// reserveGuessIn is reserveCodeGuess over the IP window and, when w is not
+// nil, w's key, capped at wrongCodesPerSessDay a day.
+func (l *emailLimits) reserveGuessIn(w *keyedWindow, key, ip string) (done func(ok bool), allowed bool) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.clock()
- l.addrWrong.trim(addr, now)
l.ipWrong.trim(ip, now)
- if l.addrWrong.count(addr, now.Add(-24*time.Hour)) >= wrongCodesPerAddrDay ||
- l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
+ if l.ipWrong.count(ip, now.Add(-time.Hour)) >= wrongCodesPerIPHour {
return func(bool) {}, false
}
- l.addrWrong.add(addr, now)
+ if w != nil {
+ w.trim(key, now)
+ if w.count(key, now.Add(-24*time.Hour)) >= wrongCodesPerSessDay {
+ return func(bool) {}, false
+ }
+ w.add(key, now)
+ }
l.ipWrong.add(ip, now)
var once sync.Once
return func(ok bool) {
@@ -330,7 +398,9 @@ func (l *emailLimits) reserveGuess(addr, ip string) (done func(ok bool), allowed
}
l.mu.Lock()
defer l.mu.Unlock()
- l.addrWrong.remove(addr, now)
+ if w != nil {
+ w.remove(key, now)
+ }
l.ipWrong.remove(ip, now)
})
}, true
diff --git a/internal/console/emailsignin_limits_test.go b/internal/console/emailsignin_limits_test.go
index 74d7994cd..b8aa5de08 100644
--- a/internal/console/emailsignin_limits_test.go
+++ b/internal/console/emailsignin_limits_test.go
@@ -220,6 +220,31 @@ func TestSigninSendIPAndGlobal(t *testing.T) {
}
}
+// The console-wide cap counts and refuses only unknown addresses (H4-M5): a
+// known address still gets its email when strangers have spent the hour, its
+// own limits still apply, and its sends leave the strangers' budget alone.
+func TestSigninSendKnownAddressSkipsTheGlobalCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ for i := 0; i < signinGlobalHour; i++ {
+ if !l.signinSend(fmt.Sprintf("g%d@example.com", i), fmt.Sprintf("10.0.%d.%d", i/250, i%250)) {
+ t.Fatalf("stranger send %d refused", i+1)
+ }
+ }
+ if l.signinSendTo("stranger@example.com", "10.9.9.9", false) {
+ t.Fatal("a stranger was sent past the console-wide cap")
+ }
+ if !l.signinSendTo("member@example.com", "10.9.9.9", true) {
+ t.Fatal("a known address was refused by the console-wide cap")
+ }
+ if l.signinSendTo("member@example.com", "10.9.9.8", true) {
+ t.Fatal("a known address skipped its own 60-second gap")
+ }
+ if len(l.globalSend) != signinGlobalHour {
+ t.Fatalf("console-wide window holds %d, want %d: a known send was charged to it", len(l.globalSend), signinGlobalHour)
+ }
+}
+
func TestSigninSendRefusalByIPDoesNotChargeGlobal(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
@@ -282,50 +307,79 @@ func TestStepUpSendSeparate(t *testing.T) {
}
}
+// signinCode and stepUpCode are challenges a code can be typed against.
+func signinCode(addr string) *EmailChallenge {
+ return &EmailChallenge{Purpose: ChallengeSignIn, Address: addr}
+}
+
+func stepUpCode(addr, session string) *EmailChallenge {
+ return &EmailChallenge{Purpose: ChallengeStepUp, Address: addr, SessionHash: session}
+}
+
// wrongGuess reserves one guess and keeps it, as a wrong code does.
-func wrongGuess(t *testing.T, l *emailLimits, addr, ip string) {
+func wrongGuess(t *testing.T, l *emailLimits, c *EmailChallenge, ip string) {
t.Helper()
- done, ok := l.reserveGuess(addr, ip)
+ done, ok := l.reserveCodeGuess(c, ip)
if !ok {
- t.Fatalf("guess for %s from %s refused", addr, ip)
+ t.Fatalf("guess for %s from %s refused", c.Address, ip)
}
done(false)
}
// guessAllowed reports whether a guess would be allowed now, taking the
// reservation straight back as a right code does.
-func guessAllowed(l *emailLimits, addr, ip string) bool {
- done, ok := l.reserveGuess(addr, ip)
+func guessAllowed(l *emailLimits, c *EmailChallenge, ip string) bool {
+ done, ok := l.reserveCodeGuess(c, ip)
done(true)
return ok
}
-func TestCodeGuessCaps(t *testing.T) {
+// No per-address budget (H4-M6): any number of wrong codes against an
+// address, from IPs under their own cap, leave its next code checkable, sent
+// or held, sign-in or step-up.
+func TestCodeGuessNoAddressBudget(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
const addr = "bob@example.com"
+ held := &EmailChallenge{Purpose: ChallengeSignIn, Address: addr, held: true}
+ for i := 0; i < 100; i++ {
+ wrongGuess(t, l, signinCode(addr), fmt.Sprintf("9.9.%d.1", i))
+ wrongGuess(t, l, held, fmt.Sprintf("9.9.%d.2", i))
+ wrongGuess(t, l, &EmailChallenge{Purpose: ChallengeDemoClaim, Address: addr}, fmt.Sprintf("9.9.%d.3", i))
+ }
+ if !guessAllowed(l, signinCode(addr), "1.1.1.1") || !guessAllowed(l, held, "1.1.1.1") {
+ t.Fatal("wrong codes from other IPs locked the address's sign-in")
+ }
+ if !guessAllowed(l, stepUpCode(addr, "bob-session"), "1.1.1.1") {
+ t.Fatal("sign-in wrong codes locked the address's step-up")
+ }
+}
- if !guessAllowed(l, addr, "1.1.1.1") {
- t.Fatal("fresh address not allowed")
+// A step-up's budget is its session's: ten wrong codes in a day lock that
+// session's step-up from any IP, and nothing else.
+func TestCodeGuessStepUpSessionCap(t *testing.T) {
+ c := newLimitClock()
+ l := newTestLimits(c)
+ const addr = "bob@example.com"
+ for i := 0; i < wrongCodesPerSessDay-1; i++ {
+ wrongGuess(t, l, stepUpCode(addr, "s1"), fmt.Sprintf("9.9.9.%d", i))
}
- for i := 0; i < 9; i++ {
- wrongGuess(t, l, addr, fmt.Sprintf("9.9.9.%d", i))
+ if !guessAllowed(l, stepUpCode(addr, "s1"), "1.1.1.1") {
+ t.Fatal("session blocked after 9 wrong codes")
}
- if !guessAllowed(l, addr, "1.1.1.1") {
- t.Fatal("blocked after 9 wrong codes")
+ wrongGuess(t, l, stepUpCode(addr, "s1"), "9.9.9.99")
+ if guessAllowed(l, stepUpCode(addr, "s1"), "1.1.1.1") || guessAllowed(l, stepUpCode(addr, "s1"), "4.4.4.4") {
+ t.Fatal("session allowed after 10 wrong codes")
}
- wrongGuess(t, l, addr, "9.9.9.99")
- // Ten wrong codes against one address block it from any IP.
- if guessAllowed(l, addr, "1.1.1.1") || guessAllowed(l, addr, "4.4.4.4") {
- t.Fatal("address allowed after 10 wrong codes")
+ if !guessAllowed(l, stepUpCode(addr, "s2"), "1.1.1.1") {
+ t.Fatal("another session of the same address blocked")
}
- // Another address from a fresh IP is unaffected.
- if !guessAllowed(l, "other@example.com", "1.1.1.1") {
- t.Fatal("other address blocked")
+ if !guessAllowed(l, signinCode(addr), "1.1.1.1") {
+ t.Fatal("a step-up lockout locked sign-in")
}
c.advance(24*time.Hour + time.Second)
- if !guessAllowed(l, addr, "1.1.1.1") {
- t.Fatal("address still blocked after 24h")
+ if !guessAllowed(l, stepUpCode(addr, "s1"), "1.1.1.1") {
+ t.Fatal("session still blocked after 24h")
}
}
@@ -333,72 +387,73 @@ func TestCodeGuessIPCap(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
for i := 0; i < 29; i++ {
- wrongGuess(t, l, fmt.Sprintf("a%d@example.com", i), "5.5.5.5")
+ wrongGuess(t, l, signinCode(fmt.Sprintf("a%d@example.com", i)), "5.5.5.5")
}
- if !guessAllowed(l, "fresh@example.com", "5.5.5.5") {
+ if !guessAllowed(l, signinCode("fresh@example.com"), "5.5.5.5") {
t.Fatal("IP blocked after 29 wrong codes")
}
- wrongGuess(t, l, "a29@example.com", "5.5.5.5")
- // 30 wrong codes from one IP block that IP for any address.
- if guessAllowed(l, "fresh@example.com", "5.5.5.5") {
+ wrongGuess(t, l, stepUpCode("a29@example.com", "s"), "5.5.5.5")
+ // 30 wrong codes from one IP, of any kind, block that IP for any code.
+ if guessAllowed(l, signinCode("fresh@example.com"), "5.5.5.5") || guessAllowed(l, stepUpCode("x@example.com", "t"), "5.5.5.5") {
t.Fatal("IP allowed after 30 wrong codes")
}
- if !guessAllowed(l, "fresh@example.com", "6.6.6.6") {
+ if !guessAllowed(l, signinCode("fresh@example.com"), "6.6.6.6") {
t.Fatal("another IP blocked")
}
c.advance(time.Hour + time.Second)
- if !guessAllowed(l, "fresh@example.com", "5.5.5.5") {
+ if !guessAllowed(l, signinCode("fresh@example.com"), "5.5.5.5") {
t.Fatal("IP still blocked after an hour")
}
}
-// A right code takes its reservation back, against both keys, once.
+// A right code takes its reservation back, against every key, once.
func TestCodeGuessRightCodeRefunds(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
- const addr = "bob@example.com"
+ step := stepUpCode("bob@example.com", "s1")
for i := 0; i < 9; i++ {
- wrongGuess(t, l, addr, "1.1.1.1")
+ wrongGuess(t, l, step, "1.1.1.1")
}
for i := 0; i < 5; i++ {
- done, ok := l.reserveGuess(addr, "1.1.1.1")
+ done, ok := l.reserveCodeGuess(step, "1.1.1.1")
if !ok {
t.Fatalf("right code %d refused after 9 wrong", i+1)
}
done(true)
done(true) // a second report changes nothing
}
- if n := l.addrWrong.count(addr, c.now().Add(-24*time.Hour)); n != 9 {
- t.Fatalf("address holds %d guesses, want the 9 wrong", n)
+ if n := l.stepWrong.count("s1", c.now().Add(-24*time.Hour)); n != 9 {
+ t.Fatalf("session holds %d guesses, want the 9 wrong", n)
}
if n := l.ipWrong.count("1.1.1.1", c.now().Add(-time.Hour)); n != 9 {
t.Fatalf("IP holds %d guesses, want the 9 wrong", n)
}
// A kept reservation is the tenth wrong code.
- done, _ := l.reserveGuess(addr, "1.1.1.1")
+ done, _ := l.reserveCodeGuess(step, "1.1.1.1")
done(false)
done(true) // too late: done acts once
- if guessAllowed(l, addr, "1.1.1.1") {
- t.Fatal("address allowed after 10 kept guesses")
+ if guessAllowed(l, step, "1.1.1.1") {
+ t.Fatal("session allowed after 10 kept guesses")
}
}
-// The cap is one step: with nine wrong codes recorded, any number of guesses
-// arriving together let exactly one through.
+// The cap is one step: one short of a cap, any number of guesses arriving
+// together let exactly one through.
func TestCodeGuessConcurrentBoundary(t *testing.T) {
for _, tc := range []struct {
- name string
- addr, ip func(i int) string
- have int
+ name string
+ code func(i int) *EmailChallenge
+ ip func(i int) string
+ have int
}{
- {"address", func(int) string { return "bob@example.com" }, func(i int) string { return fmt.Sprintf("10.0.0.%d", i) }, wrongCodesPerAddrDay - 1},
- {"ip", func(i int) string { return fmt.Sprintf("u%d@example.com", i) }, func(int) string { return "5.5.5.5" }, wrongCodesPerIPHour - 1},
+ {"session", func(int) *EmailChallenge { return stepUpCode("bob@example.com", "s1") }, func(i int) string { return fmt.Sprintf("10.0.0.%d", i) }, wrongCodesPerSessDay - 1},
+ {"ip", func(i int) *EmailChallenge { return signinCode(fmt.Sprintf("u%d@example.com", i)) }, func(int) string { return "5.5.5.5" }, wrongCodesPerIPHour - 1},
} {
t.Run(tc.name, func(t *testing.T) {
c := newLimitClock()
l := newTestLimits(c)
for i := 0; i < tc.have; i++ {
- wrongGuess(t, l, tc.addr(1000+i), tc.ip(1000+i))
+ wrongGuess(t, l, tc.code(1000+i), tc.ip(1000+i))
}
const n = 32
var (
@@ -411,7 +466,7 @@ func TestCodeGuessConcurrentBoundary(t *testing.T) {
go func() {
defer wg.Done()
<-start
- if done, ok := l.reserveGuess(tc.addr(i), tc.ip(i)); ok {
+ if done, ok := l.reserveCodeGuess(tc.code(i), tc.ip(i)); ok {
allowed.Add(1)
done(false)
}
diff --git a/internal/console/emailsignin_lockout_test.go b/internal/console/emailsignin_lockout_test.go
new file mode 100644
index 000000000..6d5b9fca6
--- /dev/null
+++ b/internal/console/emailsignin_lockout_test.go
@@ -0,0 +1,197 @@
+package console
+
+// Review round 1 on H4-M5/H4-M6 (Astra): an unauthenticated requester must
+// not exhaust another browser's authentication budget, nor learn whether the
+// console knows an address.
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// skewLimits moves fx's limit clock (only) forward on demand, so a test can
+// step past the 60-second resend gap without sleeping. Challenges keep real
+// time, so nothing expires.
+func skewLimits(fx *consoleFixture) (advance func(time.Duration)) {
+ var off atomic.Int64
+ fx.srv.limits.now = func() time.Time { return time.Now().Add(time.Duration(off.Load())) }
+ return func(d time.Duration) { off.Add(int64(d)) }
+}
+
+// postAs posts form to path through the production router from ip, holding
+// only its own flow cookie, as a script would.
+func postAs(t *testing.T, fx *consoleFixture, ip, flow, path string, form url.Values) (int, string) {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+ r.RemoteAddr = ip
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.AddCookie(&http.Cookie{Name: flowCookie, Value: flow})
+ w := httptest.NewRecorder()
+ fx.srv.ServeHTTP(w, r)
+ return w.Code, w.Body.String()
+}
+
+// Astra's scenario: the attacker waits out the resend gap twice, so both of
+// its flows get SENT challenges (two real emails to the victim), and spends
+// five wrong codes on each. The victim's own code, in its own flow, still
+// signs in.
+func TestSentFlowsCannotLockTheOwnersCode(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ advance := skewLimits(fx)
+ const addr = "victim@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ victim := newBrowser(t)
+ code, _ := askSignin(t, fx, m, victim, addr, "")
+
+ for i, flow := range []string{
+ "attacker-sent-flow-one-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "attacker-sent-flow-two-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ } {
+ advance(emailResendGap + time.Second)
+ before := len(m.sentCopy())
+ if status, _ := postAs(t, fx, huntM6AttackerAddr, flow, "/auth/continue", url.Values{"address": {addr}}); status != http.StatusOK {
+ t.Fatalf("attacker continue %d = %d", i+1, status)
+ }
+ waitChallengeSent(t, fx, 1)
+ if len(m.sentCopy()) != before+1 {
+ t.Fatalf("attacker flow %d was not sent an email; the scenario needs sent challenges", i+1)
+ }
+ for j := 1; j <= emailCodeAttempts; j++ {
+ want := "check.code_wrong"
+ if j == emailCodeAttempts {
+ want = "check.code_used_up"
+ }
+ status, body := postAs(t, fx, huntM6AttackerAddr, flow, "/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText(want))) {
+ t.Fatalf("attacker junk code %d in flow %d = %d, want %s", j, i+1, status, want)
+ }
+ }
+ }
+ status, loc, body := postCode(t, fx, victim, code)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Fatalf("victim's right code after ten wrong codes on two sent attacker flows = %d -> %q (throttled: %v); want 303 into an account",
+ status, loc, strings.Contains(body, esc(copyText("check.code_throttled"))))
+ }
+}
+
+// Astra's oracle: with the console-wide stranger budget full and the
+// attacker's IP out of sends, a third flow from a fresh IP is SENT for a
+// known address and HELD for an unknown one. Every response the attacker
+// sees, at every step, must be byte-identical either way.
+func TestKnownAndUnknownAddressAnswerAlike(t *testing.T) {
+ const target = "target@example.com"
+ run := func(known bool) []string {
+ fx, _ := newEmailFixture(t, true)
+ lookupAnswers(fx, target, http.StatusNotFound)
+ if known {
+ if err := fx.st.CreateAccount(42, "cdef", "target", target, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ const attackerIP, freshIP = "203.0.113.66:40000", "198.51.100.7:40000"
+ // Spend the attacker IP's sends, then the rest of the stranger budget.
+ for i := 0; i < signinPerIPHour; i++ {
+ if !fx.srv.limits.signinSend(fmt.Sprintf("a%d@example.org", i), "203.0.113.66") {
+ t.Fatal("setup: attacker send refused")
+ }
+ }
+ for i := signinPerIPHour; i < signinGlobalHour; i++ {
+ if !fx.srv.limits.signinSend(fmt.Sprintf("g%d@example.org", i), fmt.Sprintf("10.1.%d.%d", i/250, i%250)) {
+ t.Fatal("setup: filler send refused")
+ }
+ }
+ var seen []string
+ step := func(ip, flow, path string, form url.Values) {
+ status, body := postAs(t, fx, ip, flow, path, form)
+ seen = append(seen, fmt.Sprintf("%s %s %d\n%s", ip, path, status, strings.ReplaceAll(body, fx.ts.URL, "ORIGIN")))
+ }
+ flows := []struct{ ip, flow string }{
+ {attackerIP, "oracle-flow-one-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},
+ {attackerIP, "oracle-flow-two-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"},
+ {freshIP, "oracle-flow-three-ccccccccccccccccccccccccccccccccccc"},
+ }
+ for _, f := range flows {
+ step(f.ip, f.flow, "/auth/continue", url.Values{"address": {target}})
+ for j := 0; j <= emailCodeAttempts; j++ { // one past the burn
+ step(f.ip, f.flow, "/auth/email/code", url.Values{"code": {"zzzzzz"}, "address": {target}})
+ }
+ }
+ if known {
+ waitChallengeSent(t, fx, 1) // flow three's email to the known address
+ }
+ return seen
+ }
+ known, unknown := run(true), run(false)
+ if len(known) != len(unknown) {
+ t.Fatalf("%d steps known, %d unknown", len(known), len(unknown))
+ }
+ for i := range known {
+ if known[i] != unknown[i] {
+ t.Errorf("step %d differs between a known and an unknown address:\nknown:\n%s\nunknown:\n%s", i+1, known[i], unknown[i])
+ }
+ }
+}
+
+// fillStrangerCap spends the console-wide send budget on strangers from
+// filler IPs, as a flood of unrelated requests would.
+func fillStrangerCap(t *testing.T, fx *consoleFixture, tag string) {
+ t.Helper()
+ for i := 0; ; i++ {
+ if !fx.srv.limits.signinSend(fmt.Sprintf("fill-%s-%d@example.net", tag, i), fmt.Sprintf("10.%d.%d.%d", 100+i/65000, i/250%250, i%250)) {
+ return
+ }
+ if i > 10*signinGlobalHour {
+ t.Fatal("console-wide cap never filled")
+ }
+ }
+}
+
+// Astra's review-2 sequence: with the stranger budget full, one flow asks
+// for an unknown seed address, spends four wrong codes, then asks for the
+// target, and types one more wrong code. Known or not, the last answer is
+// the same (both replace the challenge and reset its attempts).
+func TestR2ReplacementDoesNotRevealAKnownAddress(t *testing.T) {
+ const target, seedAddr = "target@example.com", "seed@example.org"
+ run := func(known bool) []string {
+ fx, _ := newEmailFixture(t, true)
+ lookupAnswers(fx, target, http.StatusNotFound)
+ lookupAnswers(fx, seedAddr, http.StatusNotFound)
+ if known {
+ if err := fx.st.CreateAccount(42, "cdef", "target", target, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fillStrangerCap(t, fx, "r2")
+ const ip, flow = "198.51.100.9:40000", "r2-flow-dddddddddddddddddddddddddddddddddddddddd"
+ var seen []string
+ step := func(path string, form url.Values) {
+ status, body := postAs(t, fx, ip, flow, path, form)
+ seen = append(seen, fmt.Sprintf("%s %d\n%s", path, status, strings.ReplaceAll(body, fx.ts.URL, "ORIGIN")))
+ }
+ step("/auth/continue", url.Values{"address": {seedAddr}})
+ for i := 0; i < emailCodeAttempts-1; i++ {
+ step("/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ }
+ step("/auth/continue", url.Values{"address": {target}})
+ step("/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ if known {
+ waitChallengeSent(t, fx, 1)
+ }
+ return seen
+ }
+ known, unknown := run(true), run(false)
+ for i := range known {
+ if known[i] != unknown[i] {
+ t.Errorf("step %d differs between a known and an unknown target:\nknown:\n%s\nunknown:\n%s", i+1, known[i], unknown[i])
+ }
+ }
+ if last := known[len(known)-1]; !strings.Contains(last, esc(copyText("check.code_wrong"))) {
+ t.Errorf("the code after asking for the target = %s; want a wrong code on a fresh challenge", last)
+ }
+}
diff --git a/internal/console/emailsignin_oracle_test.go b/internal/console/emailsignin_oracle_test.go
new file mode 100644
index 000000000..f8f3a399b
--- /dev/null
+++ b/internal/console/emailsignin_oracle_test.go
@@ -0,0 +1,199 @@
+package console
+
+// "One flow, one rule" (H4-M5/M6 review 2, Paul's ruling): a requester who
+// does not hold the target's mailbox must see exactly the same thing whether
+// the console knows the target or not. Random sequences of what such a
+// requester can do run twice, once with the target a known person and once
+// not; every response (status, headers, body), and every email that goes to
+// an address other than the target (one the requester might own), must be
+// the same both times. Only the target's own mail may differ.
+
+import (
+ "flag"
+ "fmt"
+ "math/rand/v2"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "regexp"
+ "sort"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+var oracleSeed = flag.Uint64("oracle.seed", 0, "seed for TestKnownAddressOracleInvariant (0: time-based)")
+
+const (
+ oracleTarget = "target@example.com"
+ oracleSequences = 500
+)
+
+var serverTimingDur = regexp.MustCompile(`dur=[0-9.]+`)
+
+var oracleSeeds = []string{"seed-a@example.org", "seed-b@example.org"}
+
+// oracleOp is one requester action.
+type oracleOp struct {
+ kind string // continue, wrong, flow, ip, advance, fill
+ addr string
+ d time.Duration
+}
+
+func (o oracleOp) String() string {
+ switch o.kind {
+ case "continue":
+ return "continue " + o.addr
+ case "advance":
+ return "advance " + o.d.String()
+ }
+ return o.kind
+}
+
+func oracleSequence(r *rand.Rand) []oracleOp {
+ ops := []oracleOp{}
+ if r.IntN(2) == 0 {
+ ops = append(ops, oracleOp{kind: "fill"})
+ }
+ addrs := append([]string{oracleTarget, oracleTarget}, oracleSeeds...)
+ for n := 3 + r.IntN(12); n > 0; n-- {
+ switch k := r.IntN(10); {
+ case k < 4:
+ ops = append(ops, oracleOp{kind: "continue", addr: addrs[r.IntN(len(addrs))]})
+ case k < 7:
+ ops = append(ops, oracleOp{kind: "wrong"})
+ case k == 7:
+ ops = append(ops, oracleOp{kind: []string{"flow", "ip"}[r.IntN(2)]})
+ case k == 8:
+ ops = append(ops, oracleOp{kind: "advance", d: []time.Duration{20 * time.Second, emailResendGap + time.Second, 16 * time.Minute, time.Hour + time.Second}[r.IntN(4)]})
+ default:
+ ops = append(ops, oracleOp{kind: "fill"})
+ }
+ }
+ return ops
+}
+
+// oracleWorld is one fixture, known or not, reused across sequences.
+type oracleWorld struct {
+ fx *consoleFixture
+ mail *fakeConsoleMail
+ off atomic.Int64
+}
+
+func newOracleWorld(t *testing.T, known bool) *oracleWorld {
+ fx, m := newEmailFixture(t, true)
+ fx.srv.challengeSent = make(chan struct{}, 64)
+ for _, a := range append([]string{oracleTarget}, oracleSeeds...) {
+ lookupAnswers(fx, a, http.StatusNotFound)
+ }
+ if known {
+ if err := fx.st.CreateAccount(42, "cdef", "target", oracleTarget, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ }
+ w := &oracleWorld{fx: fx, mail: m}
+ return w
+}
+
+// newest is the flow's newest challenge row and whether it is held.
+func (w *oracleWorld) newest(flow string) (id string, held bool) {
+ w.fx.st.db.QueryRow(`SELECT id_hash, held FROM email_challenges WHERE flow_hash = ? ORDER BY created_at DESC, rowid DESC LIMIT 1`,
+ hashToken(flow)).Scan(&id, &held)
+ return id, held
+}
+
+// run plays ops from a clean slate and returns the transcript.
+func (w *oracleWorld) run(t *testing.T, seq int, ops []oracleOp) []string {
+ fx := w.fx
+ base := time.Now().Add(time.Duration(w.off.Load()))
+ w.off.Store(0)
+ var off atomic.Int64
+ fx.srv.limits = emailLimits{now: func() time.Time { return base.Add(time.Duration(off.Load())) }}
+ if _, err := fx.st.db.Exec(`DELETE FROM email_challenges`); err != nil {
+ t.Fatal(err)
+ }
+ flowN, ipN := 0, 0
+ flow := func() string {
+ return fmt.Sprintf("oracle-%04d-flow-%02d-eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", seq, flowN)
+ }
+ ip := func() string { return fmt.Sprintf("203.0.%d.%d:40000", 1+ipN, 1+seq%250) }
+ var out []string
+ for i, op := range ops {
+ var line string
+ switch op.kind {
+ case "fill":
+ fillStrangerCap(t, fx, fmt.Sprintf("%d-%d", seq, i))
+ line = "filled"
+ case "flow":
+ flowN++
+ line = "new flow"
+ case "ip":
+ ipN++
+ line = "new ip"
+ case "advance":
+ off.Add(int64(op.d))
+ line = "advanced"
+ case "continue", "wrong":
+ path, form := "/auth/email/code", url.Values{"code": {"zzzzzz"}}
+ if op.kind == "continue" {
+ path, form = "/auth/continue", url.Values{"address": {op.addr}}
+ }
+ before, _ := w.newest(flow())
+ sentBefore := len(w.mail.sentCopy())
+ r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+ r.RemoteAddr = ip()
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.AddCookie(&http.Cookie{Name: flowCookie, Value: flow()})
+ rec := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rec, r)
+ if after, held := w.newest(flow()); op.kind == "continue" && after != "" && after != before && !held {
+ select { // a send was scheduled: let it land
+ case <-fx.srv.challengeSent:
+ case <-time.After(5 * time.Second):
+ t.Fatal("a scheduled send never finished")
+ }
+ }
+ var others []string
+ for _, m := range w.mail.sentCopy()[sentBefore:] {
+ if to, _, _ := strings.Cut(m, "|"); to != oracleTarget {
+ others = append(others, to)
+ }
+ }
+ var hdr []string
+ for k, vs := range rec.Result().Header {
+ v := strings.Join(vs, ", ")
+ if k == "Server-Timing" { // measured durations: noise, not state
+ v = serverTimingDur.ReplaceAllString(v, "dur=N")
+ }
+ hdr = append(hdr, k+": "+v)
+ }
+ sort.Strings(hdr)
+ line = fmt.Sprintf("%d\n%s\n%s\nmail to others: %v", rec.Code, strings.Join(hdr, "\n"), rec.Body.String(), others)
+ line = strings.ReplaceAll(line, fx.ts.URL, "ORIGIN")
+ }
+ out = append(out, op.String()+" -> "+line)
+ }
+ w.off.Store(off.Load())
+ return out
+}
+
+func TestKnownAddressOracleInvariant(t *testing.T) {
+ seed := *oracleSeed
+ if seed == 0 {
+ seed = uint64(time.Now().UnixNano())
+ }
+ known, unknown := newOracleWorld(t, true), newOracleWorld(t, false)
+ start := time.Now()
+ for seq := 0; seq < oracleSequences; seq++ {
+ ops := oracleSequence(rand.New(rand.NewPCG(seed, uint64(seq))))
+ a, b := known.run(t, seq, ops), unknown.run(t, seq, ops)
+ for i := range a {
+ if a[i] != b[i] {
+ t.Fatalf("seed %d (rerun with -oracle.seed=%d), sequence %d, step %d of %v differs between a known and an unknown target:\nknown:\n%s\n\nunknown:\n%s",
+ seed, seed, seq, i+1, ops, a[i], b[i])
+ }
+ }
+ }
+ t.Logf("seed %d: %d sequences alike in %v", seed, oracleSequences, time.Since(start).Round(time.Millisecond))
+}
diff --git a/internal/console/emailsignin_store.go b/internal/console/emailsignin_store.go
index 1cc647364..d81b2338e 100644
--- a/internal/console/emailsignin_store.go
+++ b/internal/console/emailsignin_store.go
@@ -15,6 +15,7 @@ package console
// again sends a fresh code.
import (
+ "context"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
@@ -49,6 +50,10 @@ type EmailChallenge struct {
// row is the challenge's row key (id_hash), set by LiveEmailChallenge, so
// TakeEmailCode checks the very challenge that was read.
row string
+ // held, set by LiveEmailChallenge, is a challenge CreateEmailChallenge
+ // stored for a refused request: its code was never sent, and no code
+ // redeems it.
+ held bool
}
// CodeResult is the verdict of TakeEmailCode.
@@ -68,7 +73,8 @@ const (
)
func (s *Store) migrateEmailSignin() error {
- _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS email_challenges (
+ for _, stmt := range []string{
+ `CREATE TABLE IF NOT EXISTS email_challenges (
id_hash TEXT PRIMARY KEY,
link_hash TEXT UNIQUE,
code_mac TEXT NOT NULL,
@@ -80,17 +86,25 @@ func (s *Store) migrateEmailSignin() error {
attempts INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
expires_at INTEGER NOT NULL,
- flow_hash TEXT NOT NULL DEFAULT ''
-);`)
- if err != nil {
- return err
- }
- // Additive: the sign-in flow a challenge belongs to. Forgiving "duplicate
- // column", so re-running is always safe. (An earlier build's alias_hashes
- // column, where one exists, is no longer read or written.)
- if _, err := s.db.Exec(`ALTER TABLE email_challenges ADD COLUMN flow_hash TEXT NOT NULL DEFAULT ''`); err != nil &&
- !strings.Contains(err.Error(), "duplicate column") {
- return err
+ flow_hash TEXT NOT NULL DEFAULT '',
+ held INTEGER NOT NULL DEFAULT 0
+);`,
+ // KnownAddress asks, on the public sign-in path, whether an address
+ // has a live invite; without this that is a table scan. (migrate
+ // creates invites before this runs.)
+ `CREATE INDEX IF NOT EXISTS invites_by_address ON invites (address, accepted_at, expires_at);`,
+ // Additive columns from here, forgiving "duplicate column", so
+ // re-running is always safe. First, the sign-in flow a challenge
+ // belongs to. (An earlier build's alias_hashes column, where one
+ // exists, is no longer read or written.)
+ `ALTER TABLE email_challenges ADD COLUMN flow_hash TEXT NOT NULL DEFAULT ''`,
+ // 1 marks a held challenge (CreateEmailChallenge), whose code was
+ // never sent and never redeems. Rows from before it read 0, as they did.
+ `ALTER TABLE email_challenges ADD COLUMN held INTEGER NOT NULL DEFAULT 0`,
+ } {
+ if _, err := s.db.Exec(stmt); err != nil && !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
}
return nil
}
@@ -125,59 +139,64 @@ func (s *Store) codeMAC(linkHash, code string) string {
return s.codeEpoch + ":" + hex.EncodeToString(m.Sum(nil))
}
-// CreateEmailChallenge stores a challenge and returns the emailed link token
-// and the six-digit code. A zero ExpiresAt means ConfirmationTTL from now. In
-// the same transaction it deletes every earlier challenge of the same purpose
-// and binding (the flow's sign-ins, or the session's step-ups), so only the
-// newest email's link and code work. An empty binding replaces nothing.
-func (s *Store) CreateEmailChallenge(c EmailChallenge, now time.Time) (link, code string, err error) {
- tx, err := s.db.Begin()
+// CreateEmailChallenge is the one way a challenge comes to be, sent or not
+// (H4-M5/M6 review 2, "one flow, one rule"). It returns the link token and
+// six-digit code to email, and whether to email them. A zero ExpiresAt means
+// ConfirmationTTL from now. In one transaction:
+//
+// - A requester's repeat is kept as it is: when send is not nil and the
+// binding's newest live challenge is for c.Address and less than
+// emailResendGap old, nothing changes, send is not asked, and sent is
+// false. A double-click or an impatient resubmission so leaves the email
+// already on its way working, and resets no attempts.
+// - Otherwise send is asked (nil means yes); every earlier challenge of
+// the same purpose and binding (the flow's sign-ins, or the session's
+// step-ups) is deleted; and a new one is stored with no attempts, so
+// only the newest email's link and code work. When send said no, the
+// new row is held: its link and code are told to nobody, and no code
+// ever redeems it (TakeEmailCode), so guessing it is worthless.
+//
+// Whether a code goes out is the only difference between the two, and it
+// shows to nobody but the mailbox: the requester sees the same challenge
+// replaced, the same attempts and the same expiry either way, so nothing it
+// can do tells a known address from an unknown one, or a sent challenge from
+// a held one. An empty binding replaces nothing. send runs inside the
+// transaction and must not use the store. ctx is the request's.
+func (s *Store) CreateEmailChallenge(ctx context.Context, c EmailChallenge, now time.Time, send func() bool) (link, code string, sent bool, err error) {
+ tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
- return "", "", err
+ return "", "", false, err
}
defer tx.Rollback()
+ if send != nil {
+ if col, ok := challengeBinding(c.Purpose); ok && bindingOf(c) != "" {
+ var addr string
+ var created int64
+ err := tx.QueryRowContext(ctx, `SELECT address, created_at FROM email_challenges
+WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?
+ORDER BY created_at DESC, rowid DESC LIMIT 1`, c.Purpose, bindingOf(c), now.Unix()).Scan(&addr, &created)
+ if err == nil && addr == c.Address && created > now.Add(-emailResendGap).Unix() {
+ return "", "", false, nil
+ }
+ if err != nil && err != sql.ErrNoRows {
+ return "", "", false, err
+ }
+ }
+ }
+ sent = send == nil || send()
if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
- return "", "", err
+ return "", "", false, err
}
- if link, code, err = s.insertEmailChallenge(tx, c, now); err != nil {
- return "", "", err
+ if link, code, err = s.insertEmailChallenge(tx, c, !sent, now); err != nil {
+ return "", "", false, err
}
if err := tx.Commit(); err != nil {
- return "", "", err
- }
- return link, code, nil
-}
-
-// HoldEmailChallenge is a refused request's challenge (spec §15, rev 6): when
-// c's binding already has a live challenge of c's purpose it changes nothing,
-// so the email already sent keeps working; otherwise it stores c with a link
-// and code nobody is ever told, so a typed code reads exactly as it would
-// against a sent one, and nothing the mailbox could redeem exists.
-func (s *Store) HoldEmailChallenge(c EmailChallenge, now time.Time) error {
- col, ok := challengeBinding(c.Purpose)
- if !ok {
- return fmt.Errorf("console: no binding for challenge purpose %q", c.Purpose)
- }
- tx, err := s.db.Begin()
- if err != nil {
- return err
- }
- defer tx.Rollback()
- var live int
- if err := tx.QueryRow(`SELECT COUNT(*) FROM email_challenges WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?`,
- c.Purpose, bindingOf(c), now.Unix()).Scan(&live); err != nil {
- return err
- }
- if live > 0 {
- return nil
+ return "", "", false, err
}
- if err := deleteBound(tx, c.Purpose, bindingOf(c)); err != nil {
- return err
+ if !sent {
+ return "", "", false, nil
}
- if _, _, err := s.insertEmailChallenge(tx, c, now); err != nil {
- return err
- }
- return tx.Commit()
+ return link, code, true, nil
}
// deleteBound deletes every challenge of purpose bound to bind; an empty bind
@@ -192,8 +211,9 @@ func deleteBound(tx *sql.Tx, purpose, bind string) error {
}
// insertEmailChallenge mints a challenge's row key, link and code and stores
-// c under them. The row key is internal: no browser is given it.
-func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, now time.Time) (link, code string, err error) {
+// c under them, marked held when its code is not sent. The row key is
+// internal: no browser is given it.
+func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, held bool, now time.Time) (link, code string, err error) {
row, err := randomToken()
if err != nil {
return "", "", err
@@ -211,10 +231,10 @@ func (s *Store) insertEmailChallenge(tx *sql.Tx, c EmailChallenge, now time.Time
exp = now.Add(ConfirmationTTL)
}
if _, err := tx.Exec(`INSERT INTO email_challenges
-(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, flow_hash, attempts, created_at, expires_at)
-VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?)`,
+(id_hash, link_hash, code_mac, purpose, address, session_hash, pending, next, flow_hash, attempts, created_at, expires_at, held)
+VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?)`,
hashToken(row), hashToken(link), s.codeMAC(hashToken(link), code), c.Purpose, c.Address,
- c.SessionHash, c.PendingHash, c.Next, c.FlowHash, now.Unix(), exp.Unix()); err != nil {
+ c.SessionHash, c.PendingHash, c.Next, c.FlowHash, now.Unix(), exp.Unix(), held); err != nil {
return "", "", err
}
return link, code, nil
@@ -246,10 +266,10 @@ func (s *Store) LiveEmailChallenge(purpose, bind string, now time.Time) (*EmailC
var row string
var c EmailChallenge
var exp int64
- err := s.db.QueryRow(`SELECT id_hash, `+challengeColumns+` FROM email_challenges
+ err := s.db.QueryRow(`SELECT id_hash, `+challengeColumns+`, held FROM email_challenges
WHERE purpose = ? AND `+col+` = ? AND expires_at >= ?
ORDER BY created_at DESC, rowid DESC LIMIT 1`, purpose, bind, now.Unix()).
- Scan(&row, &c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp)
+ Scan(&row, &c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &c.held)
if err != nil {
return nil, false
}
@@ -296,6 +316,7 @@ FROM email_challenges WHERE link_hash = ?`, hashToken(link)))
// meanwhile is reported CodeGone (an expired one is deleted); a wrong code
// adds an attempt, and the fifth burns the challenge (CodeBurned); a right
// code deletes it, with its binding's other challenges, and reports CodeOK.
+// On a held challenge every code is a wrong one: its code was never sent.
func (s *Store) TakeEmailCode(read *EmailChallenge, code string, now time.Time) (*EmailChallenge, CodeResult) {
if read == nil || read.row == "" {
return nil, CodeGone
@@ -307,11 +328,12 @@ func (s *Store) TakeEmailCode(read *EmailChallenge, code string, now time.Time)
defer tx.Rollback()
var mac, linkHash string
var attempts int
+ var held bool
var c EmailChallenge
var exp int64
- if err := tx.QueryRow(`SELECT `+challengeColumns+`, code_mac, link_hash, attempts
+ if err := tx.QueryRow(`SELECT `+challengeColumns+`, code_mac, link_hash, attempts, held
FROM email_challenges WHERE id_hash = ?`, read.row).
- Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &mac, &linkHash, &attempts); err != nil {
+ Scan(&c.Purpose, &c.Address, &c.SessionHash, &c.PendingHash, &c.Next, &c.FlowHash, &exp, &mac, &linkHash, &attempts, &held); err != nil {
return nil, CodeGone
}
c.ExpiresAt = time.Unix(exp, 0)
@@ -329,7 +351,7 @@ FROM email_challenges WHERE id_hash = ?`, read.row).
if !strings.HasPrefix(mac, s.codeEpoch+":") {
return nil, CodeGone
}
- if !hmac.Equal([]byte(mac), []byte(s.codeMAC(linkHash, code))) {
+ if held || !hmac.Equal([]byte(mac), []byte(s.codeMAC(linkHash, code))) {
attempts++
res := CodeWrong
if attempts >= emailCodeAttempts {
@@ -367,3 +389,19 @@ func scanEmailChallenge(row *sql.Row) (*EmailChallenge, int64, error) {
c.ExpiresAt = time.Unix(exp, 0)
return &c, exp, nil
}
+
+// KnownAddress reports whether the console already knows addr as a person:
+// a user, an email sign-in method, a membership, or an unaccepted, unexpired
+// invite. Sign-in mail to a known address is bounded by that address's own
+// limits, not the console-wide cap (emailsignin_limits.go), so strangers'
+// sends cannot use up the people who already have a way in. Callers pass
+// addr canonical (trimmed, lower-cased).
+func (s *Store) KnownAddress(ctx context.Context, addr string, now time.Time) (bool, error) {
+ var known bool
+ err := s.db.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM users WHERE address = ?)
+OR EXISTS (SELECT 1 FROM sign_in_methods WHERE kind = ? AND subject = ?)
+OR EXISTS (SELECT 1 FROM memberships WHERE address = ?)
+OR EXISTS (SELECT 1 FROM invites WHERE address = ? AND accepted_at = 0 AND expires_at >= ?)`,
+ addr, MethodEmail, addr, addr, addr, now.Unix()).Scan(&known)
+ return known, err
+}
diff --git a/internal/console/emailsignin_store_test.go b/internal/console/emailsignin_store_test.go
index ae85bd099..27601bf86 100644
--- a/internal/console/emailsignin_store_test.go
+++ b/internal/console/emailsignin_store_test.go
@@ -6,6 +6,7 @@ import (
"database/sql"
"encoding/hex"
"path/filepath"
+ "strings"
"testing"
"time"
)
@@ -15,10 +16,10 @@ var testFlow = hashToken("a-test-flow-token-of-some-length-000000")
func newSignInChallenge(t *testing.T, s *Store, now time.Time, flowHash string) (link, code string) {
t.Helper()
- link, code, err := s.CreateEmailChallenge(EmailChallenge{
+ link, code, _, err := s.CreateEmailChallenge(t.Context(), EmailChallenge{
Purpose: ChallengeSignIn, Address: "bob@example.com", Next: "/auth/cli", FlowHash: flowHash,
ExpiresAt: now.Add(ConfirmationTTL),
- }, now)
+ }, now, nil)
if err != nil {
t.Fatal(err)
}
@@ -95,9 +96,9 @@ func TestEmailChallengeLiveByFlow(t *testing.T) {
t.Fatal("a taken challenge is still live")
}
// A step-up is found by its session's hash.
- if _, _, err := s.CreateEmailChallenge(EmailChallenge{
+ if _, _, _, err := s.CreateEmailChallenge(t.Context(), EmailChallenge{
Purpose: ChallengeStepUp, Address: "bob@example.com", SessionHash: "sh", PendingHash: "ph",
- }, now); err != nil {
+ }, now, nil); err != nil {
t.Fatal(err)
}
if c, ok := s.LiveEmailChallenge(ChallengeStepUp, "sh", now); !ok || c.PendingHash != "ph" {
@@ -281,45 +282,64 @@ func TestEmailChallengeReplace(t *testing.T) {
}
}
-// A refused request's challenge is recorded only when the flow has no live
-// one, and never displaces the email already sent.
-func TestEmailChallengeHold(t *testing.T) {
+// One rule for sent and unsent (H4-M5/M6 review 2): a requester's request
+// replaces the flow's challenge and resets attempts whether or not its code
+// goes out; an unsent one is held and redeems nothing; a same-address repeat
+// inside the resend gap changes nothing and asks nothing.
+func TestEmailChallengeOneRule(t *testing.T) {
s := openTestStore(t)
now := time.Now()
- link, code := newSignInChallenge(t, s, now, testFlow)
- held := EmailChallenge{Purpose: ChallengeSignIn, Address: "carol@example.com", FlowHash: testFlow}
- if err := s.HoldEmailChallenge(held, now); err != nil {
- t.Fatal(err)
- }
- if n := countChallenges(t, s); n != 1 {
- t.Fatalf("%d challenges after a hold beside a live one, want 1", n)
+ asks := 0
+ send := func(ok bool) func() bool { return func() bool { asks++; return ok } }
+ bob := EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: testFlow}
+ carol := EmailChallenge{Purpose: ChallengeSignIn, Address: "carol@example.com", FlowHash: testFlow}
+
+ link, code, sent, err := s.CreateEmailChallenge(t.Context(), bob, now, send(true))
+ if err != nil || !sent || link == "" || code == "" {
+ t.Fatalf("sent create = %q %q %v %v", link, code, sent, err)
}
- if c := live(t, s, testFlow, now); c.Address != "bob@example.com" {
- t.Fatalf("the hold displaced the sent challenge: %+v", c)
+ // A repeat inside the gap: nothing changes, send not asked.
+ if _, _, sent, err := s.CreateEmailChallenge(t.Context(), bob, now.Add(emailResendGap-2*time.Second), send(false)); err != nil || sent || asks != 1 {
+ t.Fatalf("repeat = sent %v, %v, asks %d; want a no-op", sent, err, asks)
}
if _, ok := s.PeekEmailLink(link, now); !ok {
- t.Fatal("the hold ended the sent link")
+ t.Fatal("a repeat ended the email already sent")
}
- if _, res := s.TakeEmailCode(live(t, s, testFlow, now), code, now); res != CodeOK {
- t.Fatalf("the sent code after a hold = %v", res)
+ // Spend four attempts, then ask for another address, unsent: replaced,
+ // held, attempts reset to five fresh ones.
+ for i := 0; i < emailCodeAttempts-1; i++ {
+ if _, res := s.TakeEmailCode(live(t, s, testFlow, now), wrongCode(code), now); res != CodeWrong {
+ t.Fatalf("wrong code %d = %v", i+1, res)
+ }
}
- // A flow with none gets an unsent challenge for the refused address.
- if err := s.HoldEmailChallenge(held, now); err != nil {
- t.Fatal(err)
+ if _, _, sent, err := s.CreateEmailChallenge(t.Context(), carol, now, send(false)); err != nil || sent {
+ t.Fatalf("unsent create = %v %v", sent, err)
}
c := live(t, s, testFlow, now)
- if c.Address != "carol@example.com" {
- t.Fatalf("held challenge = %+v", c)
+ if c.Address != "carol@example.com" || !c.held || countChallenges(t, s) != 1 {
+ t.Fatalf("after an unsent create: %+v, %d rows", c, countChallenges(t, s))
}
- if _, res := s.TakeEmailCode(c, "000000", now); res == CodeGone {
- t.Fatal("a code against the held challenge found nothing, unlike a sent one")
+ if _, ok := s.PeekEmailLink(link, now); ok {
+ t.Fatal("the replaced challenge's link still works")
+ }
+ for i := 1; i <= emailCodeAttempts; i++ {
+ want := CodeWrong
+ if i == emailCodeAttempts {
+ want = CodeBurned
+ }
+ if _, res := s.TakeEmailCode(live(t, s, testFlow, now), "000000", now); res != want {
+ t.Fatalf("held attempt %d = %v, want %v", i, res, want)
+ }
}
- // An expired one counts as none.
- if err := s.HoldEmailChallenge(held, now.Add(ConfirmationTTL+time.Second)); err != nil {
+ // Past the gap, the same address is a new request again.
+ if _, _, sent, err := s.CreateEmailChallenge(t.Context(), carol, now, send(false)); err != nil || sent {
t.Fatal(err)
}
- if n := countChallenges(t, s); n != 1 {
- t.Fatalf("%d challenges after holding past an expired one, want 1", n)
+ if _, _, _, err := s.CreateEmailChallenge(t.Context(), carol, now.Add(emailResendGap+time.Second), send(true)); err != nil {
+ t.Fatal(err)
+ }
+ if c := live(t, s, testFlow, now.Add(emailResendGap+time.Second)); c.held || countChallenges(t, s) != 1 {
+ t.Fatalf("a sent create past the gap = %+v, %d rows", c, countChallenges(t, s))
}
}
@@ -431,3 +451,98 @@ func TestSessionMethodPreMigrationRowReadsKeymail(t *testing.T) {
t.Fatalf("pre-migration session = %q %q %v, want keymail", a, m, ok)
}
}
+
+// KnownAddress is what lets a sign-in email skip the console-wide cap
+// (H4-M5): a user, a member, or a live invite is known; a stranger, or an
+// address whose only invite has expired, is not.
+func TestKnownAddress(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ if err := st.CreateAccount(42, "cdef", "shop", "owner@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.EnsureUser("user@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateInvite(42, "invitee@example.com", "owner@example.com", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateInvite(42, "lapsed@example.com", "owner@example.com", now.Add(-2*InviteTTL)); err != nil {
+ t.Fatal(err)
+ }
+ for addr, want := range map[string]bool{
+ "owner@example.com": true,
+ "user@example.com": true,
+ "invitee@example.com": true,
+ "lapsed@example.com": false,
+ "stranger@example.com": false,
+ } {
+ got, err := st.KnownAddress(t.Context(), addr, now)
+ if err != nil || got != want {
+ t.Errorf("KnownAddress(%s) = %v, %v; want %v", addr, got, err, want)
+ }
+ }
+}
+
+// A held challenge (HoldEmailChallenge) never redeems a code, not even its
+// own (H4-M6): nobody was sent it, so a right guess must not sign anyone in.
+func TestHeldChallengeNeverRedeemsACode(t *testing.T) {
+ st := openTestStore(t)
+ now := time.Now()
+ c := EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("flow")}
+ tx, err := st.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, code, err := st.insertEmailChallenge(tx, c, true, now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ live, ok := st.LiveEmailChallenge(ChallengeSignIn, c.FlowHash, now)
+ if !ok || !live.held {
+ t.Fatalf("live held challenge = %+v, %v; want held", live, ok)
+ }
+ if got, res := st.TakeEmailCode(live, code, now); res != CodeWrong || got != nil {
+ t.Fatalf("held challenge's own code = %v, %v; want CodeWrong", got, res)
+ }
+
+ // An unsent create marks its row held; a sent one is not.
+ if _, _, _, err := st.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("other")}, now, func() bool { return false }); err != nil {
+ t.Fatal(err)
+ }
+ if h, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("other"), now); !ok || !h.held {
+ t.Fatalf("unsent row = %+v, %v; want held", h, ok)
+ }
+ if _, _, _, err := st.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: ChallengeSignIn, Address: "bob@example.com", FlowHash: hashToken("sent")}, now, nil); err != nil {
+ t.Fatal(err)
+ }
+ if s, ok := st.LiveEmailChallenge(ChallengeSignIn, hashToken("sent"), now); !ok || s.held {
+ t.Fatalf("CreateEmailChallenge row = %+v, %v; want not held", s, ok)
+ }
+}
+
+// KnownAddress's invite lookup is indexed (H4-M5 review 1): it runs for every
+// public sign-in request.
+func TestKnownAddressInviteLookupIsIndexed(t *testing.T) {
+ st := openTestStore(t)
+ rows, err := st.db.Query(`EXPLAIN QUERY PLAN SELECT 1 FROM invites WHERE address = ? AND accepted_at = 0 AND expires_at >= ?`, "a@example.com", 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var plan []string
+ for rows.Next() {
+ var id, parent, unused int
+ var detail string
+ if err := rows.Scan(&id, &parent, &unused, &detail); err != nil {
+ t.Fatal(err)
+ }
+ plan = append(plan, detail)
+ }
+ if got := strings.Join(plan, "; "); !strings.Contains(got, "invites_by_address") {
+ t.Fatalf("invite lookup plan = %q, want it to use invites_by_address", got)
+ }
+}
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
index 4f4cf34cf..2468b9639 100644
--- a/internal/console/emailsignin_test.go
+++ b/internal/console/emailsignin_test.go
@@ -923,8 +923,10 @@ func TestEmailCodeCrossDevice(t *testing.T) {
}
}
-// Spec r2-2: wrong codes count per address across fresh challenges. Past the
-// cap the code box refuses without checking, while a link still signs in.
+// Five wrong codes burn a challenge, and a fresh one (which costs an email to
+// the address, under its send limits) has its own five. Wrong codes count per
+// client IP across challenges, never per address (H4-M6); past the IP cap
+// the code box refuses without checking, while a link still signs in.
func TestEmailCodeGuessCap(t *testing.T) {
fx := newConsoleFixture(t)
const addr = "bob@example.com"
@@ -934,7 +936,7 @@ func TestEmailCodeGuessCap(t *testing.T) {
c.Jar.SetCookies(u, []*http.Cookie{{Name: flowCookie, Value: flow, Path: "/"}})
// Each new challenge in the flow replaces the one before.
fresh := func() (link, code string) {
- link, code, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: addr, FlowHash: hashToken(flow)}, time.Now())
+ link, code, _, err := fx.st.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: ChallengeSignIn, Address: addr, FlowHash: hashToken(flow)}, time.Now(), nil)
if err != nil {
t.Fatal(err)
}
@@ -953,13 +955,13 @@ func TestEmailCodeGuessCap(t *testing.T) {
}
}
}
- _, code := fresh()
- wrong(5, code)
- _, code = fresh()
- wrong(5, code)
+ for i := 0; i < wrongCodesPerIPHour/emailCodeAttempts; i++ {
+ _, code := fresh()
+ wrong(emailCodeAttempts, code)
+ }
link, code := fresh()
- // The eleventh wrong code, and even the right one, is throttled unchecked.
+ // The IP's next wrong code, and even the right one, is throttled unchecked.
for _, try := range []string{wrongCode(code), code} {
status, _, body := postCode(t, fx, c, try)
if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.code_throttled"))) {
diff --git a/internal/console/hunt_H4-M5_test.go b/internal/console/hunt_H4-M5_test.go
new file mode 100644
index 000000000..874310ffe
--- /dev/null
+++ b/internal/console/hunt_H4-M5_test.go
@@ -0,0 +1,57 @@
+package console
+
+import (
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestHunt_H4_M5_GlobalBudgetCannotBlockUnrelatedSignin(t *testing.T) {
+ fx, mail := newEmailFixture(t, true)
+ submit := func(address, ip string) {
+ t.Helper()
+ lookupAnswers(fx, address, http.StatusNotFound)
+ req := httptest.NewRequest(http.MethodPost, fx.ts.URL+"/auth/continue", strings.NewReader(url.Values{"address": {address}}.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", fx.ts.URL)
+ req.RemoteAddr = ip
+ w := httptest.NewRecorder()
+ fx.srv.ServeHTTP(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("continue: status=%d", w.Code)
+ }
+ }
+ victim := "victim@example.com"
+ if err := fx.st.CreateAccount(42, "cdef", "victim", victim, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for ip := 1; ip <= 20; ip++ {
+ for n := 0; n < 10; n++ {
+ submit(fmt.Sprintf("attacker-%d-%d@example.com", ip, n), fmt.Sprintf("[2001:db8:1::%x]:12345", ip))
+ waitChallengeSent(t, fx, 1)
+ }
+ }
+ if sent := len(mail.sentCopy()); sent != 200 {
+ t.Fatalf("setup sent=%d; want 200", sent)
+ }
+ submit(victim, "[2001:db8:2::1]:12345")
+ // Give the asynchronous sender its normal completion hook; no hook means
+ // the production send gate never scheduled a message.
+ select {
+ case <-fx.srv.challengeSent:
+ case <-time.After(250 * time.Millisecond):
+ }
+ victimSent := false
+ for _, msg := range mail.sentCopy() {
+ if strings.HasPrefix(msg, victim+"|") {
+ victimSent = true
+ }
+ }
+ if !victimSent {
+ t.Errorf("unrelated existing user's sign-in email suppressed after 200 unauthenticated sends from 20 IPv6 addresses in one /64: victim_delivered=false total_sent=%d; want victim delivery", len(mail.sentCopy()))
+ }
+}
diff --git a/internal/console/hunt_H4-M6_test.go b/internal/console/hunt_H4-M6_test.go
new file mode 100644
index 000000000..ed7f3eda3
--- /dev/null
+++ b/internal/console/hunt_H4-M6_test.go
@@ -0,0 +1,108 @@
+package console
+
+// Hunt H4-M6 (verifier, opus): an unauthenticated client that knows only a
+// victim's address opens its own sign-in flows for that address and spends
+// the address-wide wrong-code budget (10 a day) with junk codes. The victim's
+// own correct code, in its own flow from another IP, is then refused.
+//
+// The assertions are the SECURE behaviour (the victim's right code still signs
+// in / still confirms the step-up). They fail on current code.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+const huntM6AttackerAddr = "203.0.113.66:40000"
+
+// huntM6Attacker posts form to path through the production router from a
+// non-loopback client holding only its own flow cookie. It sends neither
+// Origin nor Sec-Fetch-Site, as a script would (sameOrigin lets that pass).
+func huntM6Attacker(t *testing.T, fx *consoleFixture, flow, path string, form url.Values) (int, string) {
+ t.Helper()
+ r := httptest.NewRequest(http.MethodPost, path, strings.NewReader(form.Encode()))
+ r.RemoteAddr = huntM6AttackerAddr
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ r.AddCookie(&http.Cookie{Name: flowCookie, Value: flow})
+ w := httptest.NewRecorder()
+ fx.srv.ServeHTTP(w, r)
+ return w.Code, w.Body.String()
+}
+
+// huntM6Burn is the attack: two attacker flows for addr, five junk codes in
+// each. Twelve requests from one IP.
+func huntM6Burn(t *testing.T, fx *consoleFixture, addr string) {
+ t.Helper()
+ for _, flow := range []string{
+ "attacker-flow-one-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+ "attacker-flow-two-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+ } {
+ status, body := huntM6Attacker(t, fx, flow, "/auth/continue", url.Values{"address": {addr}})
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText("check.sent", "address", addr))) {
+ t.Fatalf("attacker continue = %d:\n%s", status, body)
+ }
+ for i := 1; i <= emailCodeAttempts; i++ {
+ status, body := huntM6Attacker(t, fx, flow, "/auth/email/code", url.Values{"code": {"zzzzzz"}})
+ want := "check.code_wrong"
+ if i == emailCodeAttempts {
+ want = "check.code_used_up"
+ }
+ if status != http.StatusOK || !strings.Contains(body, esc(copyText(want))) {
+ t.Fatalf("attacker junk code %d = %d, want %s:\n%s", i, status, want, body)
+ }
+ }
+ }
+}
+
+func TestHunt_H4_M6_SigninCodeLockout(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ const addr = "victim@example.com"
+ lookupAnswers(fx, addr, http.StatusNotFound)
+ victim := newBrowser(t)
+ code, link := askSignin(t, fx, m, victim, addr, "")
+
+ huntM6Burn(t, fx, addr)
+ if n := len(m.sentCopy()); n != 1 {
+ t.Logf("console mailer sent %d messages (the attacker's flows were held, not sent)", n)
+ }
+
+ // SECURE: the victim's own right code, in the victim's own flow and from
+ // the victim's own IP, signs the victim in.
+ status, loc, body := postCode(t, fx, victim, code)
+ if status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ throttled := strings.Contains(body, esc(copyText("check.code_throttled")))
+ t.Errorf("H4-M6: victim's correct sign-in code after an attacker's 10 junk codes from %s = %d -> %q (throttled page: %v); want 303 into an account",
+ huntM6AttackerAddr, status, loc, throttled)
+ }
+
+ // Residual (not the assertion under test): the emailed link still works.
+ if signedOut(t, fx, victim) {
+ other := newBrowser(t)
+ _, _, nonce := openLink(t, fx, other, link)
+ if status, loc, _ := postLink(t, fx, other, link, nonce); status != http.StatusSeeOther || !strings.HasPrefix(loc, "/a/") {
+ t.Errorf("link after lockout = %d -> %q", status, loc)
+ } else {
+ t.Log("the emailed link still signs in after the lockout")
+ }
+ }
+}
+
+func TestHunt_H4_M6_StepUpCodeLockout(t *testing.T) {
+ fx, m := newEmailFixture(t, true)
+ c := newBrowser(t)
+ raw, base := emailOwnerWorld(t, fx, m, c)
+ code, _ := askStepUp(t, fx, m, c, raw, base)
+
+ huntM6Burn(t, fx, "bob@example.com")
+
+ // SECURE: bob's right step-up code confirms the held removal.
+ status, loc, body := postStepUpCode(t, fx, c, code)
+ if status != http.StatusSeeOther || loc != base+"/team" {
+ throttled := strings.Contains(body, esc(copyText("check.code_throttled")))
+ t.Errorf("H4-M6: victim's correct step-up code after an attacker's 10 junk sign-in codes = %d -> %q (throttled page: %v); want 303 -> %s/team",
+ status, loc, throttled, base)
+ }
+}
diff --git a/internal/console/hunt_H4-M8_test.go b/internal/console/hunt_H4-M8_test.go
new file mode 100644
index 000000000..5b174770e
--- /dev/null
+++ b/internal/console/hunt_H4-M8_test.go
@@ -0,0 +1,60 @@
+package console
+
+// Hunt H4-M8 (verifier, opus): the app's /.carlos/instances answer is a
+// redirect, and the console's instance fetcher (production wiring: cmd never
+// sets Config.AppClient, so newInstanceFetcher's default http.Client is used)
+// follows it to a host the tenant chose. Here the target is a second loopback
+// server standing in for a service on the console host's own network.
+//
+// The assertion is the SECURE behaviour: the internal service is never hit.
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+func TestHunt_H4_M8_InstanceReportFollowsRedirect(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := signInPaul(t, fx)
+
+ // The "internal" service: it records every hit, and answers in the one
+ // shape the fetcher reflects onto the page.
+ var internalHits atomic.Int64
+ var internalPath atomic.Value
+ internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ internalHits.Add(1)
+ internalPath.Store(r.URL.RequestURI())
+ w.Write([]byte(`[{"slug":"internal-secret-row","detail":"served by the internal service"}]`))
+ }))
+ t.Cleanup(internal.Close)
+
+ // The tenant's app: its report endpoint redirects into the internal one.
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != InstancesPath {
+ http.NotFound(w, r)
+ return
+ }
+ http.Redirect(w, r, internal.URL+"/admin/anything?probe=1", http.StatusFound)
+ }))
+ t.Cleanup(app.Close)
+ host := strings.TrimPrefix(app.URL, "http://")
+ fx.addRoute(t, registry.Route{Host: host, Kind: "instance", Status: "ready", App: "kass"})
+
+ status, _, body := get(t, c, fx.u("/apps/kass/instances"))
+ if status != http.StatusOK {
+ t.Fatalf("instances page = %d", status)
+ }
+ if n := internalHits.Load(); n != 0 {
+ p, _ := internalPath.Load().(string)
+ t.Errorf("H4-M8: the console followed the app's redirect and hit the internal service %d time(s) (GET %s); want 0",
+ n, p)
+ }
+ if strings.Contains(body, "internal-secret-row") {
+ t.Errorf("H4-M8: the internal service's slug-shaped answer was rendered on the tenant's instances page")
+ }
+}
diff --git a/internal/console/hunt_H5-M12_test.go b/internal/console/hunt_H5-M12_test.go
new file mode 100644
index 000000000..a694e8453
--- /dev/null
+++ b/internal/console/hunt_H5-M12_test.go
@@ -0,0 +1,88 @@
+package console
+
+// Hunt H5-M12 (verifier: opus). POST /api/ses/events is unauthenticated. With
+// the deployment's (non-secret) TopicArn and a SigningCertURL on the pinned
+// regional SNS host, validSigningCertURL accepts any fragment (and any query),
+// verifiedCertKey caches by the WHOLE URL string, and the entry is stored
+// before the signature is checked. So each distinct fragment is a fresh
+// outbound fetch and a new map entry that lives forever, with the URL string
+// itself (up to the 256 KiB body ceiling) as the retained key.
+//
+// Production wiring: the real registered route, snsVerify left nil so the
+// real verifySNSSignature -> verifiedCertKey -> fetchVerifiedCertKey path
+// runs. Only the network under snsFetchClient is pointed at a local TLS
+// listener (hijackFetchClient, the existing seam), and TLS hostname
+// verification still runs against sns.eu-west-1.amazonaws.com.
+
+import (
+ "crypto/tls"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync/atomic"
+ "testing"
+)
+
+func TestHunt_H5_M12_FragmentsGrowCertCache(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.MailDeployment.SNSTopicARN = "arn:aws:sns:eu-west-1:1:carlos-mail"
+ fx.srv.cfg.MailDeployment.Region = "eu-west-1"
+ if fx.srv.snsVerify != nil {
+ t.Fatal("test bug: the real signature path must run")
+ }
+
+ const regional = "sns.eu-west-1.amazonaws.com"
+ tlsDER, tlsLeaf, tlsKey := genLeafCert(t, regional)
+ pemDER, _, _ := genLeafCert(t, snsCertDNSName)
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pemDER})
+ var fetches atomic.Int64
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fetches.Add(1)
+ w.Write(certPEM)
+ }))
+ ts.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{tlsDER}, PrivateKey: tlsKey}}}
+ ts.StartTLS()
+ t.Cleanup(ts.Close)
+ hijackFetchClient(t, ts.Listener.Addr().String(), tlsLeaf)
+
+ post := func(certURL string) int {
+ env := map[string]string{
+ "Type": "Notification", "MessageId": "m", "TopicArn": fx.srv.cfg.MailDeployment.SNSTopicARN,
+ "Message": "{}", "Timestamp": "2026-10-25T00:00:00Z", "SignatureVersion": "1",
+ "Signature": "Ym9ndXM=", "SigningCertURL": certURL,
+ }
+ b, _ := json.Marshal(env)
+ resp := sesPost(t, fx, string(b))
+ resp.Body.Close()
+ return resp.StatusCode
+ }
+
+ const n = 25
+ base := "https://" + regional + "/SimpleNotificationService-0123456789abcdef.pem"
+ for i := 0; i < n; i++ {
+ if code := post(fmt.Sprintf("%s#%d", base, i)); code != http.StatusForbidden {
+ t.Fatalf("request %d = %d, want 403 (bogus signature)", i, code)
+ }
+ }
+ // One long fragment: the retained key is the attacker's string.
+ long := base + "#" + strings.Repeat("A", 200<<10)
+ if code := post(long); code != http.StatusForbidden {
+ t.Fatalf("long-fragment request = %d, want 403", code)
+ }
+
+ fx.srv.snsCerts.mu.Lock()
+ entries, keyBytes := len(fx.srv.snsCerts.keys), 0
+ for k := range fx.srv.snsCerts.keys {
+ keyBytes += len(k)
+ }
+ fx.srv.snsCerts.mu.Unlock()
+
+ if entries > 1 || fetches.Load() > 1 {
+ t.Fatalf("H5-M12: %d unauthenticated requests with invalid signatures, differing only in the URL fragment, "+
+ "caused %d outbound certificate fetches and left %d cache entries retaining %d bytes of attacker-chosen keys "+
+ "(want one canonical entry and one fetch)", n+1, fetches.Load(), entries, keyBytes)
+ }
+}
diff --git a/internal/console/hunt_H5-M7_test.go b/internal/console/hunt_H5-M7_test.go
new file mode 100644
index 000000000..e86c330ff
--- /dev/null
+++ b/internal/console/hunt_H5-M7_test.go
@@ -0,0 +1,59 @@
+package console
+
+// Hunt H5-M7 (verifier: opus). A fleet box may PUT any body up to 32 MiB
+// under apps/<own sqid>/<app>/logs/** through the edge store door
+// (storedoor.go aclWriteAppFamily + io.ReadAll(MaxBytesReader(32 MiB)) ->
+// store.Put, no content check). The console's logs door then hands every
+// chunk in the window to applog.ReadChunks, whose DecodeJSONL decodes the
+// whole gzip stream into one []T before the filter or collectCap run.
+//
+// This test writes the chunk straight into the deployment store (the bytes
+// the store door would have stored verbatim) and drives the REAL CLI logs
+// route with limit=1. It asserts the secure behaviour: a chunk a few KiB
+// compressed must not cost the console tens of MiB of heap.
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "net/http"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/applog"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestHunt_H5_M7_GzipChunkFullyDecoded(t *testing.T) {
+ fx, token := instanceFixture(t, "code-h5m7")
+ now := time.Now().UTC()
+
+ const lines = 400_000
+ var buf bytes.Buffer
+ zw, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
+ zw.Write([]byte(strings.Repeat("{}\n", lines)))
+ zw.Close()
+ body := buf.Bytes()
+ key := mustKey(t)(applog.ChunkKey(release.OpsAccount, "titogo", "box1", applog.HourOf(now), 1, len(body)))
+ if _, err := fx.rel.Put(context.Background(), key, body, ""); err != nil {
+ t.Fatal(err)
+ }
+
+ runtime.GC()
+ var before, after runtime.MemStats
+ runtime.ReadMemStats(&before)
+ status, _, out := rawReq(t, http.MethodGet, logsURL(fx, fx.sqid, "titogo", "limit=1"), token, "")
+ runtime.ReadMemStats(&after)
+ if status != http.StatusOK {
+ t.Fatalf("GET logs = %d %s", status, out)
+ }
+ alloc := after.TotalAlloc - before.TotalAlloc
+ const budget = 32 << 20
+ if alloc > budget {
+ t.Fatalf("H5-M7: one logs read (limit=1) of a %d-byte gzip chunk allocated %d MiB in the console "+
+ "(%d records decoded before any filter or cap; ratio %dx). A 32 MiB chunk at this ratio is ~%d GiB of records. Want <= %d MiB.",
+ len(body), alloc>>20, lines, alloc/uint64(len(body)), (alloc*uint64(32<<20)/uint64(len(body)))>>30, budget>>20)
+ }
+}
diff --git a/internal/console/instances.go b/internal/console/instances.go
index 876ceac06..c8b352a0b 100644
--- a/internal/console/instances.go
+++ b/internal/console/instances.go
@@ -72,10 +72,20 @@ type instanceCacheEntry struct {
// newInstanceFetcher builds the fetcher over client (nil is a plain client
// with the fetch timeout). It reads s.perf, so NewServer calls it once that
// is set.
+//
+// The fetcher never follows a redirect: the app chooses the answer, so a
+// followed Location would let a tenant point the console's GET at any host
+// the console can reach (its own loopback, another tenant's backend). A 3xx
+// is a non-200 like any other and folds to "not reporting". A given client
+// is copied, not changed, to set that.
func (s *Server) newInstanceFetcher(client *http.Client, scheme string) *instanceFetcher {
if client == nil {
client = &http.Client{Timeout: instancesTimeout}
+ } else {
+ c := *client
+ client = &c
}
+ client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
if scheme == "" {
scheme = "https"
}
diff --git a/internal/console/lifetimes_cutover.go b/internal/console/lifetimes_cutover.go
index b81ca8b36..452045a33 100644
--- a/internal/console/lifetimes_cutover.go
+++ b/internal/console/lifetimes_cutover.go
@@ -380,6 +380,8 @@ func lifetimesExempt(path string) bool {
switch {
case path == "/healthz", path == "/api/ses/events", path == lifetimesCutoverPath:
return true
+ case strings.HasPrefix(path, "/api/ses/events/"):
+ return true
case strings.HasPrefix(path, "/auth/"), strings.HasPrefix(path, "/static/"):
return true
case path == demoBuildStreamPath, strings.HasPrefix(path, interactive.AttachPathPrefix), strings.HasPrefix(path, interactive.RunAttachPathPrefix):
diff --git a/internal/console/newperson_test.go b/internal/console/newperson_test.go
index f2efaf10c..a92e7fdb9 100644
--- a/internal/console/newperson_test.go
+++ b/internal/console/newperson_test.go
@@ -11,7 +11,11 @@ import (
func exhaustNewPersonBudget(t *testing.T, fx *consoleFixture, global bool) {
t.Helper()
- c := newLimitClock()
+ // Frozen at the wall clock, as production's limits clock is: handleContinue
+ // mints challenges on this clock while the link page checks expiry on
+ // the wall clock, so a clock frozen in the past would hand the test an
+ // already-expired link.
+ c := &limitClock{t: time.Now()}
fx.srv.limits.mu.Lock()
fx.srv.limits.now = c.now
fx.srv.limits.mu.Unlock()
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index f534bc9a2..00f8ea2e5 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -203,8 +203,8 @@ func perfSeed(t *testing.T, fx *consoleFixture, seeds *perfSeeds) {
}
seeds.invite = tok
// /auth/email/link?t=: a live sign-in link; its GET never spends it.
- link, _, err := fx.st.CreateEmailChallenge(EmailChallenge{Purpose: ChallengeSignIn, Address: "paul@keymail.dev",
- FlowHash: hashToken("perf-walk-flow")}, now)
+ link, _, _, err := fx.st.CreateEmailChallenge(t.Context(), EmailChallenge{Purpose: ChallengeSignIn, Address: "paul@keymail.dev",
+ FlowHash: hashToken("perf-walk-flow")}, now, nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 61e78105e..a3926687f 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -446,6 +446,9 @@ var routeDecls = []routeDecl{
// label-aware SigningCertURL host check, and a verified signature,
// all run before any field of the message is trusted.
{Pattern: "POST /api/ses/events", Handler: (*Server).handleSESEvents},
+ // The same ingest behind a secret path (Config.SESEventsToken): when
+ // one is set, it is the only door that reads anything.
+ {Pattern: "POST /api/ses/events/{token}", Handler: (*Server).handleSESEventsWithToken},
{Pattern: "POST /api/fleet/enrol", Handler: (*Server).handleManagedEnrol},
// The seed door (managedseed.go): the same public, token-bound shape as
// enrolment, read-only, and it never consumes the token.
diff --git a/internal/console/server.go b/internal/console/server.go
index 2e87bd355..ad094c9dd 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -942,6 +942,12 @@ type Config struct {
// MailDeployment carries the region, the platform suffix, the DMARC rua
// and the SNS topic.
MailDeployment mail.Deployment
+ // SESEventsToken (CARLOS_SES_EVENTS_TOKEN), when set, is the secret the
+ // SES event ingest's path must carry: SNS posts to
+ // /api/ses/events/<token>, and the bare /api/ses/events, or a wrong
+ // token, is a 404 before anything is read (sesevents.go). Empty keeps
+ // the bare path, as before.
+ SESEventsToken string
// MailOperators are the addresses allowed to drive the email pause/cap
// door (CARLOS_MAIL_OPERATORS, apimail.go): pausing or resuming a
// tenant's sending, and raising its daily cap above what its tier
@@ -1564,7 +1570,8 @@ type Server struct {
// only place production ever sends. A test points it at an httptest
// server instead. The path still goes through the same validation.
mailPushTarget func(acct, app, path string) string
- // snsCerts caches a verified signing certificate's RSA public key by URL
+ // snsCerts caches a verified signing certificate's RSA public key by its
+ // canonical URL, a few entries at most
// (sesevents.go) — otherwise every request bearing the deployment's
// TopicArn, which is not a secret, triggers a fresh outbound HTTPS fetch
// and full chain verification. Zero value is ready to use.
@@ -3767,7 +3774,9 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
- now := time.Now()
+ // The send limits' clock, so one clock decides both the sends and the
+ // challenge's age (CreateEmailChallenge's repeat rule) and expiry.
+ now := s.limits.clock()
s.store.PurgeExpired(now) // housekeeping on the write path
flow := s.requestFlow(r)
if flow == "" {
@@ -3794,7 +3803,7 @@ func (s *Server) handleContinue(w http.ResponseWriter, r *http.Request) {
s.renderHome(w, r, homeForm{Prefill: addr, Next: next, NoMail: true, flow: flow})
return
}
- link, code, sent, err := s.signinChallenge(flow, addr, next, ip, underCap, now)
+ link, code, sent, err := s.signinChallenge(r.Context(), flow, addr, next, ip, underCap, now)
if err != nil {
log.Printf("console: sign-in challenge for %s: %v", addr, err)
s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not start the sign-in flow. Please try again.")
@@ -3825,37 +3834,6 @@ func (s *Server) continueKeymailSignin(w http.ResponseWriter, r *http.Request, f
http.Redirect(w, r, target, http.StatusSeeOther)
}
-// signinChallenge is the front door's limits and challenge write for one
-// flow, under that flow's lock, so overlapping submissions from one browser
-// take turns. Accepted (under the submission cap and every send limit), it
-// records a new sign-in challenge for the flow, replacing the flow's earlier
-// ones, and returns its link and code to send. Refused, it sends nothing and
-// leaves the flow's live challenge, if any, untouched, so the email already
-// sent keeps working. Over the submission cap it writes nothing at all: that
-// throttle is the requester's own IP and says nothing about anyone else, so
-// the code box may answer "used up" there. Refused by the send limits (which
-// the submission cap bounds to 30 an hour per IP), a flow with no live
-// challenge gets one nobody is ever told the link or code of, so a code
-// typed next answers exactly as it would against a sent one.
-func (s *Server) signinChallenge(flow, addr, next, ip string, underCap bool, now time.Time) (link, code string, sent bool, err error) {
- mu := s.flowLock(flow)
- mu.Lock()
- defer mu.Unlock()
- if !underCap {
- return "", "", false, nil
- }
- c := EmailChallenge{Purpose: ChallengeSignIn, Address: addr, Next: next, FlowHash: hashToken(flow)}
- if !s.limits.signinSend(addr, ip) {
- log.Printf("console: sign-in email to %s from %s refused by its limits; not sent", addr, ip)
- return "", "", false, s.store.HoldEmailChallenge(c, now)
- }
- link, code, err = s.store.CreateEmailChallenge(c, now)
- if err != nil {
- return "", "", false, err
- }
- return link, code, true, nil
-}
-
// ValidAddress is the console's one shape check on a keymail address:
// <local>@<host>, no whitespace. Exported because the box-side verbs
// (`console member`) must reject a typo with the SAME rule the web surface
diff --git a/internal/console/sesevents.go b/internal/console/sesevents.go
index b81294d64..96c765853 100644
--- a/internal/console/sesevents.go
+++ b/internal/console/sesevents.go
@@ -102,6 +102,7 @@ import (
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
+ "crypto/subtle"
"crypto/x509"
"encoding/base64"
"encoding/json"
@@ -308,7 +309,39 @@ func (e snsEnvelope) canonicalString() string {
// 200 — SNS retries non-2xx, so refusing an unknown case with a
// failure status would turn one unrecognised field into an unbounded
// retry flood against the console.
+//
+// With Config.SESEventsToken set, this bare path is a 404 before anything
+// is read, and SNS posts to handleSESEventsWithToken instead.
func (s *Server) handleSESEvents(w http.ResponseWriter, r *http.Request) {
+ if s.cfg.SESEventsToken != "" {
+ http.NotFound(w, r)
+ return
+ }
+ s.ingestSESEvents(w, r)
+}
+
+// handleSESEventsWithToken is POST /api/ses/events/{token}: the ingest
+// behind a secret only SNS's subscription knows (H5-M12 review 2). The
+// signature check alone cannot keep anonymous requests from spending the
+// certificate-fetch budget a genuine delivery needs after a restart or a
+// rotation; a path nobody else can name can. No token configured, or a
+// wrong one, is the unknown route's 404 before the body, the envelope or
+// any certificate is touched. The token is compared in constant time, as
+// fixed-length digests so its length does not show either, and never
+// logged.
+func (s *Server) handleSESEventsWithToken(w http.ResponseWriter, r *http.Request) {
+ want := s.cfg.SESEventsToken
+ got := sha256.Sum256([]byte(r.PathValue("token")))
+ exp := sha256.Sum256([]byte(want))
+ if want == "" || subtle.ConstantTimeCompare(got[:], exp[:]) != 1 {
+ http.NotFound(w, r)
+ return
+ }
+ s.ingestSESEvents(w, r)
+}
+
+// ingestSESEvents is the ingest itself, behind whichever door is open.
+func (s *Server) ingestSESEvents(w http.ResponseWriter, r *http.Request) {
// 1. Bound the body first.
r.Body = http.MaxBytesReader(w, r.Body, sesEventMaxBody)
body, err := io.ReadAll(r.Body)
@@ -361,6 +394,14 @@ func (s *Server) handleSESEvents(w http.ResponseWriter, r *http.Request) {
verify = func(e snsEnvelope) error { return s.verifySNSSignature(r.Context(), e) }
}
if err := verify(env); err != nil {
+ // A certificate not to be had right now is a retry, not a verdict:
+ // SNS retries only 429 and 5xx, and treats any other 4xx as final,
+ // so a 403 here would lose a genuine bounce or complaint for good.
+ if errors.Is(err, errSNSCertUnavailable) {
+ log.Printf("console: ses events: signing certificate unavailable: %v", err)
+ jsonError(w, http.StatusServiceUnavailable, "signing certificate unavailable; retry later")
+ return
+ }
log.Printf("console: ses events: signature verification failed: %v", err)
jsonError(w, http.StatusForbidden, "signature verification failed")
return
@@ -733,12 +774,92 @@ func (s *Server) confirmSNSSubscription(ctx context.Context, subscribeURL string
// outbound amplification, one connection out per request in. The AWS SDKs
// cache verification certs by URL for the same reason.
//
+// The key is the CANONICAL URL (canonicalSigningCertURL), and the map holds
+// at most snsCertCacheMax entries (H5-M12). The door is unauthenticated and
+// the entry is stored before the message signature is checked, so keying on
+// the raw string let any caller with the TopicArn mint a fresh fetch and a
+// map entry that lived forever per fragment or query variant, the URL itself
+// (up to the body ceiling) retained as the key. SNS signs with one
+// certificate at a time and rotates rarely; a handful of slots is plenty,
+// and the oldest entry makes room when they are full.
+//
+// A cache only bounds hits; a miss is outbound work an unsigned request can
+// ask for (H5-M12 review 1). So, before any fetch: the path must have the
+// shape of an SNS signing certificate (validSigningCertPath); identical
+// misses in flight share one fetch; a failed URL is not fetched again until
+// its backoff (snsCertBackoff, doubling per failure to a ceiling) runs out,
+// and the failures remembered are bounded too; and the door as a whole
+// starts at most snsCertFetchesPerMinute fetches a minute and holds at most
+// snsCertFetchesInFlight at once, refusing past either without fetching.
+// A genuine message whose certificate is cached never fetches. One that
+// needs a fetch it cannot have right now answers 503 (errSNSCertUnavailable),
+// which SNS retries; it treats 403 and every other 4xx but 429 as final. And
+// with Config.SESEventsToken set, an anonymous request never reaches here,
+// so these windows are SNS's own.
+//
// A value type with a nil-safe zero value on purpose: Server embeds one
// directly (no constructor call needed), the same way ceClientOnce
// (server.go) needs no init.
type snsCertCache struct {
- mu sync.Mutex
- keys map[string]*rsa.PublicKey
+ mu sync.Mutex
+ now func() time.Time // nil: time.Now
+ keys map[string]*rsa.PublicKey
+ order []string // insertion order of keys, oldest first
+
+ fails map[string]snsCertFailure // failed fetches, by canonical URL
+ failOrder []string // insertion order of fails, oldest first
+ inflight map[string]*snsCertCall // fetches in flight, by canonical URL
+ started []time.Time // fetch starts in the last minute
+
+ // joined, nil but in tests, is told each time a caller starts waiting
+ // on a fetch already in flight: the seam a test waits on instead of
+ // sleeping.
+ joined func()
+}
+
+// snsCertFailure is a URL's failed fetches: how many in a row, the last
+// error, and when it may be fetched again.
+type snsCertFailure struct {
+ n int
+ err error
+ until time.Time
+}
+
+// snsCertCall is one fetch in flight; done closes when pub and err are set.
+type snsCertCall struct {
+ done chan struct{}
+ pub *rsa.PublicKey
+ err error
+}
+
+const (
+ // snsCertCacheMax bounds the verified keys, and snsCertFailMax the
+ // failures, snsCertCache remembers.
+ snsCertCacheMax = 8
+ snsCertFailMax = 64
+ // snsCertFetchesInFlight and snsCertFetchesPerMinute bound the
+ // certificate fetches the whole door makes.
+ snsCertFetchesInFlight = 2
+ snsCertFetchesPerMinute = 10
+ // A failed URL waits snsCertBackoffBase, doubling per failure in a row,
+ // up to snsCertBackoffMax, before it is fetched again.
+ snsCertBackoffBase = 30 * time.Second
+ snsCertBackoffMax = 15 * time.Minute
+)
+
+// errSNSCertUnavailable marks a signing certificate that cannot be had right
+// now (a refusal past the fetch limits, a failed or refused fetch): the
+// delivery is answered 503, so SNS tries again later, never 403.
+var errSNSCertUnavailable = errors.New("sns: signing cert unavailable")
+
+// errSNSCertBusy refuses a miss past the door's fetch limits, unfetched.
+var errSNSCertBusy = fmt.Errorf("%w: fetches over their limit; not fetched", errSNSCertUnavailable)
+
+func (c *snsCertCache) clock() time.Time {
+ if c.now != nil {
+ return c.now()
+ }
+ return time.Now()
}
func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) {
@@ -751,26 +872,169 @@ func (c *snsCertCache) get(certURL string) (*rsa.PublicKey, bool) {
func (c *snsCertCache) put(certURL string, pub *rsa.PublicKey) {
c.mu.Lock()
defer c.mu.Unlock()
+ c.putLocked(certURL, pub)
+}
+
+func (c *snsCertCache) putLocked(certURL string, pub *rsa.PublicKey) {
if c.keys == nil {
c.keys = map[string]*rsa.PublicKey{}
}
+ if _, ok := c.keys[certURL]; !ok {
+ for len(c.order) >= snsCertCacheMax {
+ delete(c.keys, c.order[0])
+ c.order = c.order[1:]
+ }
+ c.order = append(c.order, certURL)
+ }
c.keys[certURL] = pub
}
+// snsCertBackoff is how long a URL waits after its nth failure in a row.
+func snsCertBackoff(n int) time.Duration {
+ d := snsCertBackoffBase
+ for i := 1; i < n && d < snsCertBackoffMax; i++ {
+ d *= 2
+ }
+ return min(d, snsCertBackoffMax)
+}
+
+// failLocked records a failed fetch of certURL.
+func (c *snsCertCache) failLocked(certURL string, err error, now time.Time) {
+ if c.fails == nil {
+ c.fails = map[string]snsCertFailure{}
+ }
+ f, ok := c.fails[certURL]
+ if !ok {
+ for len(c.failOrder) >= snsCertFailMax {
+ delete(c.fails, c.failOrder[0])
+ c.failOrder = c.failOrder[1:]
+ }
+ c.failOrder = append(c.failOrder, certURL)
+ }
+ f.n++
+ f.err = err
+ f.until = now.Add(snsCertBackoff(f.n))
+ c.fails[certURL] = f
+}
+
+// key returns certURL's verified key: cached, the answer of a fetch already
+// in flight for it, a remembered failure still in its backoff, a refusal
+// past the door's fetch limits, or else the result of fetching it now with
+// fetch. certURL is canonical and shape-checked.
+func (c *snsCertCache) key(ctx context.Context, certURL string, fetch func(context.Context, string) (*rsa.PublicKey, error)) (*rsa.PublicKey, error) {
+ c.mu.Lock()
+ if pub, ok := c.keys[certURL]; ok {
+ c.mu.Unlock()
+ return pub, nil
+ }
+ now := c.clock()
+ if f, ok := c.fails[certURL]; ok && now.Before(f.until) {
+ c.mu.Unlock()
+ return nil, f.err
+ }
+ if call, ok := c.inflight[certURL]; ok {
+ c.mu.Unlock()
+ if c.joined != nil {
+ c.joined()
+ }
+ select {
+ case <-call.done:
+ return call.pub, call.err
+ case <-ctx.Done():
+ return nil, fmt.Errorf("%w: %v", errSNSCertUnavailable, ctx.Err())
+ }
+ }
+ kept := c.started[:0]
+ for _, t := range c.started {
+ if t.After(now.Add(-time.Minute)) {
+ kept = append(kept, t)
+ }
+ }
+ c.started = kept
+ if len(c.inflight) >= snsCertFetchesInFlight || len(c.started) >= snsCertFetchesPerMinute {
+ c.mu.Unlock()
+ return nil, errSNSCertBusy
+ }
+ if c.inflight == nil {
+ c.inflight = map[string]*snsCertCall{}
+ }
+ call := &snsCertCall{done: make(chan struct{})}
+ c.inflight[certURL] = call
+ c.started = append(c.started, now)
+ c.mu.Unlock()
+
+ // The fetch is the door's, not this request's: a caller that gives up
+ // must not fail the others waiting on it.
+ call.pub, call.err = fetch(context.WithoutCancel(ctx), certURL)
+
+ c.mu.Lock()
+ delete(c.inflight, certURL)
+ if call.err != nil {
+ c.failLocked(certURL, call.err, c.clock())
+ } else {
+ c.putLocked(certURL, call.pub)
+ delete(c.fails, certURL) // its failOrder slot ages out
+ }
+ c.mu.Unlock()
+ close(call.done)
+ return call.pub, call.err
+}
+
+// snsCertPathPattern is the path of an SNS signing certificate:
+// /SimpleNotificationService-<hex>.pem, as every SigningCertURL AWS
+// documents and sends (the hex is 32 digits today; any length up to 64 is
+// let through so a change of digest does not stop mail).
+var snsCertPathPattern = regexp.MustCompile(`^/SimpleNotificationService-[0-9a-fA-F]{1,64}\.pem$`)
+
+// validSigningCertPath refuses a canonical SigningCertURL whose path is not
+// an SNS signing certificate's, or that names a port other than https's:
+// nothing else on the pinned host is worth a fetch (H5-M12 review 1). It is
+// for SigningCertURL only; SubscribeURL is a query on "/".
+func validSigningCertPath(certURL string) error {
+ u, err := url.Parse(certURL)
+ if err != nil {
+ return fmt.Errorf("sns: unparseable SigningCertURL")
+ }
+ if u.Port() != "" {
+ return fmt.Errorf("sns: SigningCertURL names a port")
+ }
+ if !snsCertPathPattern.MatchString(u.EscapedPath()) {
+ return fmt.Errorf("sns: SigningCertURL path %q is not an SNS signing certificate", u.EscapedPath())
+ }
+ return nil
+}
+
+// canonicalSigningCertURL is the one URL a SigningCertURL names, for both
+// the cache key and the fetch: https, the lowercased host (default port
+// dropped), the path as given, and nothing else. A fragment never reaches
+// the wire and a query is not part of an SNS certificate's address, so
+// neither may make a second fetch or a second cache entry (H5-M12).
+// Userinfo goes too. raw has already passed validSigningCertURL.
+func canonicalSigningCertURL(raw string) (string, error) {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return "", fmt.Errorf("sns: unparseable SigningCertURL")
+ }
+ host := strings.ToLower(u.Host)
+ host = strings.TrimSuffix(host, ":443")
+ c := url.URL{Scheme: "https", Host: host, Path: u.Path, RawPath: u.RawPath}
+ return c.String(), nil
+}
+
// verifiedCertKey returns the RSA public key for a signing certificate URL
// — already pinned to an SNS host by the caller (validSigningCertURL) —
-// using the cache on a hit, and fetching plus fully verifying the
-// certificate on a miss.
+// canonical and shape-checked first, then through snsCertCache.key: the
+// cache on a hit, and on a miss, within the door's fetch limits, fetching
+// plus fully verifying the certificate.
func (s *Server) verifiedCertKey(ctx context.Context, certURL string) (*rsa.PublicKey, error) {
- if pub, ok := s.snsCerts.get(certURL); ok {
- return pub, nil
- }
- pub, err := fetchVerifiedCertKey(ctx, certURL)
+ certURL, err := canonicalSigningCertURL(certURL)
if err != nil {
return nil, err
}
- s.snsCerts.put(certURL, pub)
- return pub, nil
+ if err := validSigningCertPath(certURL); err != nil {
+ return nil, err
+ }
+ return s.snsCerts.key(ctx, certURL, fetchVerifiedCertKey)
}
// snsCertDNSName is the hostname a genuine SNS message-signing certificate
@@ -829,15 +1093,15 @@ func fetchVerifiedCertKey(ctx context.Context, certURL string) (*rsa.PublicKey,
}
resp, err := snsFetchClient.Do(req)
if err != nil {
- return nil, fmt.Errorf("sns: fetching signing cert: %w", err)
+ return nil, fmt.Errorf("%w: fetching: %v", errSNSCertUnavailable, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("sns: signing cert fetch status %d", resp.StatusCode)
+ return nil, fmt.Errorf("%w: fetch status %d", errSNSCertUnavailable, resp.StatusCode)
}
certPEM, err := io.ReadAll(io.LimitReader(resp.Body, sesCertMaxBody))
if err != nil {
- return nil, fmt.Errorf("sns: reading signing cert: %w", err)
+ return nil, fmt.Errorf("%w: reading: %v", errSNSCertUnavailable, err)
}
block, _ := pem.Decode(certPEM)
if block == nil {
diff --git a/internal/console/sesevents_test.go b/internal/console/sesevents_test.go
index db8657956..7a07f0f76 100644
--- a/internal/console/sesevents_test.go
+++ b/internal/console/sesevents_test.go
@@ -23,8 +23,11 @@ import (
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
+ "encoding/json"
"encoding/pem"
"errors"
+ "fmt"
+ "io"
"log"
"math/big"
"net"
@@ -33,6 +36,8 @@ import (
"os"
"reflect"
"strings"
+ "sync"
+ "sync/atomic"
"testing"
"time"
@@ -154,7 +159,13 @@ func TestSigningCertURLPinsToConfiguredRegionExactly(t *testing.T) {
// sesPost drives the ingest endpoint the way SNS would.
func sesPost(t *testing.T, fx *consoleFixture, body string) *http.Response {
t.Helper()
- req, err := http.NewRequest(http.MethodPost, fx.ts.URL+"/api/ses/events", strings.NewReader(body))
+ return sesPostPath(t, fx, "/api/ses/events", body)
+}
+
+// sesPostPath is sesPost to path (the token door, say).
+func sesPostPath(t *testing.T, fx *consoleFixture, path, body string) *http.Response {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, fx.ts.URL+path, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
@@ -722,7 +733,7 @@ func TestVerifiedCertKeyServesFromCache(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- const certURL = "https://sns.eu-west-1.amazonaws.com/nothing-listens-here.pem"
+ const certURL = "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-0badc0de.pem" // nothing listens
fx.srv.snsCerts.put(certURL, &key.PublicKey)
pub, err := fx.srv.verifiedCertKey(context.Background(), certURL)
@@ -734,6 +745,355 @@ func TestVerifiedCertKeyServesFromCache(t *testing.T) {
}
}
+// The cache holds at most snsCertCacheMax keys (H5-M12): the oldest makes
+// room, and the newest is always kept.
+func TestSNSCertCacheIsBounded(t *testing.T) {
+ var c snsCertCache
+ key, err := rsa.GenerateKey(rand.Reader, 1024)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for i := 0; i < 3*snsCertCacheMax; i++ {
+ c.put(fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/%d.pem", i), &key.PublicKey)
+ }
+ if len(c.keys) != snsCertCacheMax || len(c.order) != snsCertCacheMax {
+ t.Fatalf("cache holds %d keys (%d ordered), want %d", len(c.keys), len(c.order), snsCertCacheMax)
+ }
+ if _, ok := c.get(fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/%d.pem", 3*snsCertCacheMax-1)); !ok {
+ t.Fatal("the newest key was evicted")
+ }
+ if _, ok := c.get("https://sns.eu-west-1.amazonaws.com/0.pem"); ok {
+ t.Fatal("the oldest key survived past the bound")
+ }
+}
+
+// Fragment, query, userinfo, host case and the default port do not change
+// the certificate a SigningCertURL names, so none may change the cache key.
+func TestCanonicalSigningCertURL(t *testing.T) {
+ const want = "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-abc.pem"
+ for _, raw := range []string{
+ want,
+ want + "#x",
+ want + "?a=b",
+ want + "?a=b#x",
+ "https://u:p@SNS.eu-west-1.amazonaws.com:443/SimpleNotificationService-abc.pem",
+ } {
+ got, err := canonicalSigningCertURL(raw)
+ if err != nil || got != want {
+ t.Errorf("canonicalSigningCertURL(%q) = %q, %v; want %q", raw, got, err, want)
+ }
+ }
+}
+
+// snsCertServer is a local TLS stand-in for the pinned regional SNS host,
+// hijacked under snsFetchClient. Each fetch is counted; status answers it
+// (200 serves a valid signing cert), and gate, when not nil, holds every
+// fetch until it closes.
+func snsCertServer(t *testing.T, status int, gate chan struct{}) *atomic.Int64 {
+ t.Helper()
+ tlsDER, tlsLeaf, tlsKey := genLeafCert(t, "sns.eu-west-1.amazonaws.com")
+ pemDER, _, _ := genLeafCert(t, snsCertDNSName)
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pemDER})
+ var fetches atomic.Int64
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fetches.Add(1)
+ if gate != nil {
+ <-gate
+ }
+ w.WriteHeader(status)
+ if status == http.StatusOK {
+ w.Write(certPEM)
+ }
+ }))
+ ts.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{tlsDER}, PrivateKey: tlsKey}}}
+ ts.StartTLS()
+ t.Cleanup(ts.Close)
+ hijackFetchClient(t, ts.Listener.Addr().String(), tlsLeaf)
+ return &fetches
+}
+
+func snsCertPath(i int) string {
+ return fmt.Sprintf("https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-%032x.pem", i)
+}
+
+// H5-M12 review 1: N unsigned requests, each naming a distinct valid-shaped
+// certificate path on the pinned host, cost at most the door's per-minute
+// fetches, through the real route.
+func TestSNSCertFetchesAreCapped(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.MailDeployment.SNSTopicARN = "arn:aws:sns:eu-west-1:1:carlos-mail"
+ fx.srv.cfg.MailDeployment.Region = "eu-west-1"
+ fetches := snsCertServer(t, http.StatusOK, nil)
+ const n = 50
+ for i := 0; i < n; i++ {
+ env, _ := json.Marshal(map[string]string{
+ "Type": "Notification", "MessageId": "m", "TopicArn": fx.srv.cfg.MailDeployment.SNSTopicARN,
+ "Message": "{}", "Timestamp": "2026-10-25T00:00:00Z", "SignatureVersion": "1",
+ "Signature": "Ym9ndXM=", "SigningCertURL": snsCertPath(i),
+ })
+ resp := sesPost(t, fx, string(env))
+ resp.Body.Close()
+ // 403 for a fetched certificate the bogus signature fails; 503,
+ // which SNS retries, past the fetch limits.
+ if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusServiceUnavailable {
+ t.Fatalf("request %d = %d, want 403 or 503", i, resp.StatusCode)
+ }
+ }
+ if got := fetches.Load(); got > snsCertFetchesPerMinute {
+ t.Fatalf("%d unsigned requests with distinct certificate paths made %d fetches; want at most %d", n, got, snsCertFetchesPerMinute)
+ }
+}
+
+// A path that is not an SNS signing certificate's, or a port, is refused
+// before any fetch.
+func TestSNSCertPathShapeRefusedUnfetched(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fetches := snsCertServer(t, http.StatusOK, nil)
+ for _, u := range []string{
+ "https://sns.eu-west-1.amazonaws.com/x.pem",
+ "https://sns.eu-west-1.amazonaws.com/",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-abc.pem/x",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-.pem",
+ "https://sns.eu-west-1.amazonaws.com/SimpleNotificationService-%61bc.pem",
+ "https://sns.eu-west-1.amazonaws.com:8443/SimpleNotificationService-abc.pem",
+ } {
+ if _, err := fx.srv.verifiedCertKey(context.Background(), u); err == nil {
+ t.Errorf("verifiedCertKey(%q) accepted", u)
+ }
+ }
+ if got := fetches.Load(); got != 0 {
+ t.Fatalf("%d fetches for refused shapes, want 0", got)
+ }
+ if _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(1)+"#frag"); err != nil {
+ t.Fatalf("a genuine shape was refused: %v", err)
+ }
+}
+
+// A failed URL is not fetched again until its backoff runs out, and the
+// backoff doubles to a ceiling.
+func TestSNSCertFailureIsBackedOff(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fetches := snsCertServer(t, http.StatusNotFound, nil)
+ var off atomic.Int64
+ fx.srv.snsCerts.now = func() time.Time { return time.Now().Add(time.Duration(off.Load())) }
+ for i := 0; i < 5; i++ {
+ if _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(7)); err == nil {
+ t.Fatal("a 404 certificate was accepted")
+ }
+ }
+ if got := fetches.Load(); got != 1 {
+ t.Fatalf("five tries of one failing URL made %d fetches, want 1", got)
+ }
+ off.Add(int64(snsCertBackoffBase + time.Second))
+ fx.srv.verifiedCertKey(context.Background(), snsCertPath(7))
+ if got := fetches.Load(); got != 2 {
+ t.Fatalf("after the backoff, %d fetches, want 2", got)
+ }
+ off.Add(int64(snsCertBackoffBase + time.Second)) // the second backoff is twice the first
+ fx.srv.verifiedCertKey(context.Background(), snsCertPath(7))
+ if got := fetches.Load(); got != 2 {
+ t.Fatalf("inside the doubled backoff, %d fetches, want 2", got)
+ }
+ if d := snsCertBackoff(100); d != snsCertBackoffMax {
+ t.Fatalf("backoff after 100 failures = %v, want the ceiling %v", d, snsCertBackoffMax)
+ }
+}
+
+// Identical misses in flight share one fetch, and every caller gets its key.
+func TestSNSCertMissesCoalesce(t *testing.T) {
+ fx := newConsoleFixture(t)
+ gate := make(chan struct{})
+ fetches := snsCertServer(t, http.StatusOK, gate)
+ const n = 8
+ joined := make(chan struct{}, n)
+ fx.srv.snsCerts.joined = func() { joined <- struct{}{} }
+ var wg sync.WaitGroup
+ errs := make(chan error, n)
+ for i := 0; i < n; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ _, err := fx.srv.verifiedCertKey(context.Background(), snsCertPath(3))
+ errs <- err
+ }()
+ }
+ // The fetch is held at the gate until every other caller is waiting on
+ // it; a caller that fetched for itself instead never joins.
+ for i := 0; i < n-1; i++ {
+ select {
+ case <-joined:
+ case <-time.After(10 * time.Second):
+ close(gate)
+ t.Fatalf("only %d of %d callers joined the fetch in flight", i, n-1)
+ }
+ }
+ close(gate)
+ wg.Wait()
+ close(errs)
+ for err := range errs {
+ if err != nil {
+ t.Fatalf("a coalesced caller failed: %v", err)
+ }
+ }
+ if got := fetches.Load(); got != 1 {
+ t.Fatalf("%d identical concurrent misses made %d fetches, want 1", n, got)
+ }
+}
+
+// ---- the secret ingest door (H5-M12 review 2) -----------------------------
+
+const sesTestToken = "a-test-ses-events-token-0123456789abcdef"
+
+// signedSNS is a Notification on fx's topic, signed with key for certURL.
+func signedSNS(t *testing.T, fx *consoleFixture, key *rsa.PrivateKey, certURL string) string {
+ t.Helper()
+ env := snsEnvelope{
+ Type: "Notification", MessageID: "legit-1", TopicArn: fx.srv.cfg.MailDeployment.SNSTopicARN,
+ Message: "{}", Timestamp: "2026-11-16T00:00:00Z", SignatureVersion: "1", SigningCertURL: certURL,
+ }
+ sum := sha1.Sum([]byte(env.canonicalString()))
+ sig, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA1, sum[:])
+ if err != nil {
+ t.Fatal(err)
+ }
+ env.Signature = base64.StdEncoding.EncodeToString(sig)
+ b, _ := json.Marshal(env)
+ return string(b)
+}
+
+// sesTokenFixture is a console on topic carlos-mail in eu-west-1 with the
+// ingest token set (or not), and a hijacked SNS host serving a signing
+// certificate whose key it returns. Fetches are counted.
+func sesTokenFixture(t *testing.T, token string) (*consoleFixture, *rsa.PrivateKey, *atomic.Int64) {
+ t.Helper()
+ fx := newConsoleFixture(t)
+ fx.srv.cfg.MailDeployment.SNSTopicARN = "arn:aws:sns:eu-west-1:1:carlos-mail"
+ fx.srv.cfg.MailDeployment.Region = "eu-west-1"
+ fx.srv.cfg.SESEventsToken = token
+ tlsDER, tlsLeaf, tlsKey := genLeafCert(t, "sns.eu-west-1.amazonaws.com")
+ pemDER, _, signKey := genLeafCert(t, snsCertDNSName)
+ certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: pemDER})
+ var fetches atomic.Int64
+ ts := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ fetches.Add(1)
+ w.Write(certPEM)
+ }))
+ ts.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{tlsDER}, PrivateKey: tlsKey}}}
+ ts.StartTLS()
+ t.Cleanup(ts.Close)
+ hijackFetchClient(t, ts.Listener.Addr().String(), tlsLeaf)
+ return fx, signKey, &fetches
+}
+
+// No token configured: the bare path ingests as before, and a token path is
+// the unknown route's 404.
+func TestSESEventsWithoutATokenKeepsTheBarePath(t *testing.T) {
+ fx, key, fetches := sesTokenFixture(t, "")
+ resp := sesPost(t, fx, signedSNS(t, fx, key, snsCertPath(1)))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK || fetches.Load() != 1 {
+ t.Fatalf("bare path, no token = %d after %d fetches; want 200 after 1", resp.StatusCode, fetches.Load())
+ }
+ resp = sesPostPath(t, fx, "/api/ses/events/anything", signedSNS(t, fx, key, snsCertPath(1)))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("token path with no token configured = %d, want 404", resp.StatusCode)
+ }
+}
+
+// With a token: the bare path and a wrong token are 404 before anything is
+// read (a malformed body would otherwise be a 400) and fetch nothing; the
+// right token ingests.
+func TestSESEventsTokenDoorRefusesUnreadAndUnfetched(t *testing.T) {
+ fx, key, fetches := sesTokenFixture(t, sesTestToken)
+ unknown := sesPostPath(t, fx, "/no/such/route", "x")
+ want, _ := io.ReadAll(unknown.Body)
+ unknown.Body.Close()
+ for _, path := range []string{
+ "/api/ses/events",
+ "/api/ses/events/" + sesTestToken[:len(sesTestToken)-1],
+ "/api/ses/events/" + sesTestToken + "x",
+ "/api/ses/events/x",
+ } {
+ for _, body := range []string{"{not json", signedSNS(t, fx, key, snsCertPath(2))} {
+ resp := sesPostPath(t, fx, path, body)
+ got, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusNotFound || string(got) != string(want) {
+ t.Fatalf("POST %s = %d %q; want the unknown route's 404 %q", path, resp.StatusCode, got, want)
+ }
+ }
+ }
+ if n := fetches.Load(); n != 0 {
+ t.Fatalf("refused requests made %d certificate fetches, want 0", n)
+ }
+ resp := sesPostPath(t, fx, "/api/ses/events/"+sesTestToken, signedSNS(t, fx, key, snsCertPath(2)))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("the right token = %d, want 200", resp.StatusCode)
+ }
+}
+
+// A genuine delivery that needs a certificate the console has never fetched
+// gets through while anonymous requests flood the door's other paths.
+func TestSESEventsColdCacheDeliveryUnderAFlood(t *testing.T) {
+ fx, key, fetches := sesTokenFixture(t, sesTestToken)
+ stop := make(chan struct{})
+ var wg, flooding sync.WaitGroup
+ for g := 0; g < 8; g++ {
+ wg.Add(1)
+ flooding.Add(1)
+ go func() {
+ defer wg.Done()
+ for i := 0; ; i++ {
+ if i == 1 {
+ flooding.Done() // one round answered: this flooder is at the door
+ }
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ body := `{"Type":"Notification","TopicArn":"arn:aws:sns:eu-west-1:1:carlos-mail","Message":"{}","Signature":"Ym9ndXM=","SigningCertURL":"` + snsCertPath(1000*g+i) + `"}`
+ for _, path := range []string{"/api/ses/events", "/api/ses/events/guess-" + fmt.Sprint(i)} {
+ req, _ := http.NewRequest(http.MethodPost, fx.ts.URL+path, strings.NewReader(body))
+ if resp, err := fx.ts.Client().Do(req); err == nil {
+ io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ }
+ }
+ }
+ }()
+ }
+ flooding.Wait()
+ resp := sesPostPath(t, fx, "/api/ses/events/"+sesTestToken, signedSNS(t, fx, key, snsCertPath(7)))
+ resp.Body.Close()
+ close(stop)
+ wg.Wait()
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("genuine cold-cache delivery under a flood = %d, want 200", resp.StatusCode)
+ }
+ if n := fetches.Load(); n != 1 {
+ t.Fatalf("%d certificate fetches, want the genuine delivery's 1", n)
+ }
+}
+
+// A certificate the door cannot fetch right now is a 503, which SNS
+// retries, never a 403, which it does not.
+func TestSESEventsBusyIsRetryable(t *testing.T) {
+ fx, key, fetches := sesTokenFixture(t, sesTestToken)
+ fx.srv.snsCerts.mu.Lock()
+ for i := 0; i < snsCertFetchesPerMinute; i++ {
+ fx.srv.snsCerts.started = append(fx.srv.snsCerts.started, time.Now())
+ }
+ fx.srv.snsCerts.mu.Unlock()
+ resp := sesPostPath(t, fx, "/api/ses/events/"+sesTestToken, signedSNS(t, fx, key, snsCertPath(9)))
+ resp.Body.Close()
+ if resp.StatusCode != http.StatusServiceUnavailable || fetches.Load() != 0 {
+ t.Fatalf("delivery past the fetch limit = %d after %d fetches; want 503 after 0", resp.StatusCode, fetches.Load())
+ }
+}
+
// ---- event-to-domain attribution (I6, review follow-up) --------------------
//
// ParseEvent attributes an event by the domain of mail.source. If SES
diff --git a/internal/console/signincopy.go b/internal/console/signincopy.go
index 36a4634a4..50a265f70 100644
--- a/internal/console/signincopy.go
+++ b/internal/console/signincopy.go
@@ -21,7 +21,7 @@ var signinCopy = map[string]string{
"check.code_button": "Sign in",
"check.code_wrong": "That code doesn't match. Check the email and try again.",
"check.code_used_up": "That code has expired or had too many wrong tries. Ask for a new link below.",
- "check.code_throttled": "Too many wrong codes for this address. Use the link in the email, or try again later.",
+ "check.code_throttled": "Too many wrong codes. Use the link in the email, or try again later.",
"check.nothing": "Nothing arriving? Check your spam folder, or ask for a new link. You can ask once a minute.",
"check.again_button": "Send a new link",
"link.title": "Sign in as {address}?",
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index 734603328..00c76c3d5 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -412,6 +412,7 @@ route POST /api/fleet/seeds/{account}/{app}/{host}/rolledback
route POST /api/link/publications
route POST /api/link/rotate
route POST /api/ses/events
+route POST /api/ses/events/{token}
route POST /auth/cli/accounts
route POST /auth/cli/approve
route POST /auth/cli/poll
diff --git a/internal/host/errship.go b/internal/host/errship.go
index d5adde012..247ec258e 100644
--- a/internal/host/errship.go
+++ b/internal/host/errship.go
@@ -70,32 +70,41 @@ func errshipGather(sink *apperr.Sink, pending map[applog.AppKey][]apperr.Record)
}
}
-// errshipFlush writes one create-only chunk per pending app and forgets
-// what landed; a failed app keeps its records for the next round.
+// errshipFlush writes each pending app's records as create-only chunks, cut
+// as logshipFlush cuts them, and forgets what landed; a failed app keeps
+// the records from its first unwritten chunk on for the next round.
func errshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]apperr.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
continue
}
- body, err := apperr.EncodeChunk(recs)
+ runs, bodies, err := apperr.EncodeChunks(recs)
if err != nil {
log.Printf("agent: errship encode %s/%s: %v (dropping %d records)", k.Acct, k.App, err, len(recs))
delete(pending, k)
continue
}
- key, err := apperr.ChunkKey(k.Acct, k.App, recs[0].Box, apperr.HourOf(recs[0].TS), recs[0].Seq, len(body))
- if err != nil {
- unshippable(applog.FamilyErrors, k, err)
- delete(pending, k)
- continue
+ done := 0
+ for i, run := range runs {
+ key, err := apperr.ChunkKey(k.Acct, k.App, run[0].Box, apperr.HourOf(run[0].TS), run[0].Seq, len(bodies[i]))
+ if err != nil {
+ unshippable(applog.FamilyErrors, k, err)
+ done = len(recs)
+ break
+ }
+ if err := shipChunk(ctx, s, "errship", key, bodies[i]); err != nil {
+ log.Printf("agent: errship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs)-done)
+ break
+ }
+ ledger.wrote(k, key, len(bodies[i]))
+ done += len(run)
}
- if _, err := s.Put(ctx, key, body, ""); err != nil {
- log.Printf("agent: errship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
- continue
+ if done == len(recs) {
+ delete(pending, k)
+ } else {
+ pending[k] = recs[done:]
}
- ledger.wrote(k, key, len(body))
- delete(pending, k)
}
}
diff --git a/internal/host/errship_test.go b/internal/host/errship_test.go
index 1808b48f4..6fead1c45 100644
--- a/internal/host/errship_test.go
+++ b/internal/host/errship_test.go
@@ -58,3 +58,40 @@ func TestErrshipFlushHoldsOnFailure(t *testing.T) {
t.Fatal("a failed flush must keep its records for the next round")
}
}
+
+// H5-M7 review 2, errship: storage commits chunk A but the flush sees a
+// timeout; the retry counts A delivered and delivers B, nothing twice.
+func TestErrshipLostAckDoesNotStrandLaterChunks(t *testing.T) {
+ dir := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bab", App: "web"}
+ ts := time.Date(2026, 9, 7, 10, 0, 0, 0, time.UTC)
+ recs := make([]apperr.Record, applog.WriteChunkLines+100) // two chunks by line count
+ for i := range recs {
+ recs[i] = apperr.Record{TS: ts, Box: "box1", Seq: uint64(1 + i), Source: apperr.SourceEdge, Name: "500 GET /x", FP: "f"}
+ }
+ runs, _, err := apperr.EncodeChunks(recs)
+ if err != nil || len(runs) != 2 {
+ t.Fatalf("EncodeChunks: %d runs, %v", len(runs), err)
+ }
+ s := &lostAckStore{Store: dir, lost: 1}
+ pending := map[applog.AppKey][]apperr.Record{app: recs}
+ errshipFlush(context.Background(), s, pending, nil)
+ if len(pending[app]) != len(recs) {
+ t.Fatalf("after the lost acknowledgement %d records held, want all %d", len(pending[app]), len(recs))
+ }
+ errshipFlush(context.Background(), s, pending, nil)
+ if len(pending) != 0 {
+ t.Fatalf("%d records still held after the retry; later chunks stranded", len(pending[app]))
+ }
+ prefix := mustKey(t)(applog.FamilyPrefix(applog.FamilyErrors, app.Acct, app.App))
+ perBox, trimmed, err := applog.ReadChunks[apperr.Record](context.Background(), dir, prefix,
+ time.Time{}, time.Time{}, func(apperr.Record) bool { return true }, 2*len(recs))
+ if err != nil || trimmed || len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back: %v trimmed=%v; want %d records once each", err, trimmed, len(recs))
+ }
+ for i, r := range perBox[0] {
+ if r.Seq != recs[i].Seq {
+ t.Fatalf("record %d has seq %d, want %d", i, r.Seq, recs[i].Seq)
+ }
+ }
+}
diff --git a/internal/host/logship.go b/internal/host/logship.go
index 4023cac68..a9b873e26 100644
--- a/internal/host/logship.go
+++ b/internal/host/logship.go
@@ -14,6 +14,7 @@
package host
import (
+ "bytes"
"context"
"errors"
"log"
@@ -112,38 +113,69 @@ func logshipGather(sink *applog.Sink, pending map[applog.AppKey][]applog.Record)
}
}
-// logshipFlush writes one chunk per pending app — create-only, keyed by the
-// batch's first seq, so a retried batch can never overwrite a delivered one
-// — and forgets what landed, telling ledger what it wrote. A failed app
-// keeps its records for the next round; other apps' flushes proceed
-// regardless.
+// logshipFlush writes each pending app's records as chunks — create-only,
+// each keyed by its batch's first seq, so a retried batch can never
+// overwrite a delivered one — and forgets what landed, telling ledger what
+// it wrote. The batch is cut where applog.EncodeChunks cuts (16 MiB of
+// serialised JSONL), so every chunk stays readable by the console's
+// decoder (H5-M7). A failed app keeps the records from its first unwritten
+// chunk on for the next round; other apps' flushes proceed regardless.
func logshipFlush(ctx context.Context, s release.Store, pending map[applog.AppKey][]applog.Record, ledger *pruneLedger) {
for k, recs := range pending {
if len(recs) == 0 || strings.HasPrefix(k.App, demo.AppPrefix) {
delete(pending, k)
continue
}
- body, err := applog.EncodeChunk(recs)
+ runs, bodies, err := applog.EncodeChunks(recs)
if err != nil { // marshal of our own records — a bug, not a retry case
log.Printf("agent: logship encode %s/%s: %v (dropping %d records)", k.Acct, k.App, err, len(recs))
delete(pending, k)
continue
}
- key, err := applog.ChunkKey(k.Acct, k.App, recs[0].Box, applog.HourOf(recs[0].TS), recs[0].Seq, len(body))
- if err != nil {
- unshippable(applog.FamilyLogs, k, err)
- delete(pending, k)
- continue
+ done := 0
+ for i, run := range runs {
+ key, err := applog.ChunkKey(k.Acct, k.App, run[0].Box, applog.HourOf(run[0].TS), run[0].Seq, len(bodies[i]))
+ if err != nil {
+ unshippable(applog.FamilyLogs, k, err)
+ done = len(recs)
+ break
+ }
+ if err := shipChunk(ctx, s, "logship", key, bodies[i]); err != nil {
+ log.Printf("agent: logship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs)-done)
+ break
+ }
+ ledger.wrote(k, key, len(bodies[i]))
+ done += len(run)
}
- if _, err := s.Put(ctx, key, body, ""); err != nil {
- log.Printf("agent: logship flush %s/%s: %v (%d records held)", k.Acct, k.App, err, len(recs))
- continue
+ if done == len(recs) {
+ delete(pending, k)
+ } else {
+ pending[k] = recs[done:]
}
- ledger.wrote(k, key, len(body))
- delete(pending, k)
}
}
+// shipChunk writes body at key, create-only. A conflict is a chunk already
+// there: when the existing object is this very body, it is one an earlier
+// flush delivered and lost the acknowledgement of (encoding is
+// deterministic, and the key carries the first seq and the size), so it
+// counts as delivered and the caller moves on to the next chunk; otherwise
+// the conflict stands and the records stay held. Without this a lost
+// acknowledgement on one chunk of a split batch stranded every later chunk
+// behind it for good (H5-M7 review 2).
+func shipChunk(ctx context.Context, s release.Store, family, key string, body []byte) error {
+ _, err := s.Put(ctx, key, body, "")
+ if !errors.Is(err, release.ErrCASConflict) {
+ return err
+ }
+ got, _, gerr := s.Get(ctx, key)
+ if gerr == nil && bytes.Equal(got, body) {
+ return nil
+ }
+ log.Printf("agent: %s chunk %s already exists with other content; not overwritten", family, key)
+ return err
+}
+
// logshipKnownApps is the union of apps with pending records and apps the
// sink has ever buffered for — the prune worklist. A demo app is left off:
// its chunks are never shipped, so listing them would cost requests for nothing.
diff --git a/internal/host/logship_test.go b/internal/host/logship_test.go
index 2450259e4..2f9e2f83b 100644
--- a/internal/host/logship_test.go
+++ b/internal/host/logship_test.go
@@ -1,6 +1,7 @@
package host
import (
+ "bytes"
"context"
"strings"
"testing"
@@ -167,3 +168,179 @@ func mustKey(t testing.TB) func(string, error) string {
return k
}
}
+
+// worstCaseRecords is logshipMaxPending records of 8 KiB app lines made of
+// NULs, each byte six on the wire (\u0000): about 192 MiB of JSONL.
+func worstCaseRecords() []applog.Record {
+ ts := time.Date(2026, 8, 10, 12, 0, 0, 0, time.UTC)
+ msg := strings.Repeat("\x00", 8<<10)
+ recs := make([]applog.Record, logshipMaxPending)
+ for i := range recs {
+ recs[i] = applog.Record{TS: ts, Box: "box1", Seq: uint64(1 + i), Stream: applog.StreamApp, Host: "h", Msg: msg}
+ }
+ return recs
+}
+
+// H5-M7 review 1: whatever the writer legitimately holds, every chunk it
+// writes is one the console's bounded decoder reads in full. A full pending
+// buffer of worst-case escaping goes out as several chunks, and the reader
+// gets every record back with nothing trimmed.
+func TestLogshipWorstCaseEscapingReadsBackWhole(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), s, pending, nil)
+ if len(pending) != 0 {
+ t.Fatalf("%d records still pending after a flush to a working bucket", len(pending[app]))
+ }
+ keys, err := s.List(context.Background(), mustKey(t)(applog.Prefix(app.Acct, app.App)))
+ if err != nil || len(keys) < 2 {
+ t.Fatalf("chunks %v (%v); want the batch cut into several", keys, err)
+ }
+ perBox, trimmed, err := applog.ReadChunks[applog.Record](context.Background(), s, mustKey(t)(applog.Prefix(app.Acct, app.App)),
+ time.Time{}, time.Time{}, func(applog.Record) bool { return true }, 2*logshipMaxPending)
+ if err != nil || trimmed {
+ t.Fatalf("read back: %v trimmed=%v; want every chunk readable", err, trimmed)
+ }
+ if len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back %d boxes, %d records; want 1 box, %d", len(perBox), len(perBox[0]), len(recs))
+ }
+ for i, r := range perBox[0] {
+ if r.Seq != recs[i].Seq || r.Msg != recs[i].Msg {
+ t.Fatalf("record %d came back as seq %d with a %d-byte message", i, r.Seq, len(r.Msg))
+ }
+ }
+}
+
+// putOnce lets the first n Puts through and refuses the rest.
+type putOnce struct {
+ release.Store
+ n int
+}
+
+func (p *putOnce) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ if p.n == 0 {
+ return "", context.DeadlineExceeded
+ }
+ p.n--
+ return p.Store.Put(ctx, key, body, ifMatch)
+}
+
+// A flush that fails part-way keeps exactly the records from the first
+// unwritten chunk on; the next flush writes them under their own first seq.
+func TestLogshipFlushHoldsFromTheFirstUnwrittenChunk(t *testing.T) {
+ dir := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ runs, _, err := applog.EncodeChunks(recs)
+ if err != nil || len(runs) < 2 {
+ t.Fatalf("EncodeChunks: %d runs, %v", len(runs), err)
+ }
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), &putOnce{Store: dir, n: 1}, pending, nil)
+ held := pending[app]
+ if len(held) != len(recs)-len(runs[0]) || held[0].Seq != runs[1][0].Seq {
+ t.Fatalf("held %d records from seq %d; want %d from seq %d", len(held), held[0].Seq, len(recs)-len(runs[0]), runs[1][0].Seq)
+ }
+ logshipFlush(context.Background(), dir, pending, nil)
+ if len(pending) != 0 {
+ t.Fatal("records still pending after the retry")
+ }
+ perBox, trimmed, err := applog.ReadChunks[applog.Record](context.Background(), dir, mustKey(t)(applog.Prefix(app.Acct, app.App)),
+ time.Time{}, time.Time{}, func(applog.Record) bool { return true }, 2*logshipMaxPending)
+ if err != nil || trimmed || len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back after retry: %v trimmed=%v", err, trimmed)
+ }
+}
+
+// lostAckStore commits each of the first lost Puts and then reports a
+// timeout, as a store whose acknowledgement was lost does.
+type lostAckStore struct {
+ release.Store
+ lost int
+}
+
+func (l *lostAckStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) {
+ etag, err := l.Store.Put(ctx, key, body, ifMatch)
+ if err == nil && l.lost > 0 {
+ l.lost--
+ return "", context.DeadlineExceeded
+ }
+ return etag, err
+}
+
+// H5-M7 review 2: storage commits chunk A but the flush sees a timeout, so
+// the whole batch stays held. The retry finds A already there, byte for
+// byte, counts it delivered and goes on to B. Nothing is lost or written
+// twice.
+func TestLogshipLostAckDoesNotStrandLaterChunks(t *testing.T) {
+ dir := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ runs, _, err := applog.EncodeChunks(recs)
+ if err != nil || len(runs) < 2 {
+ t.Fatalf("EncodeChunks: %d runs, %v", len(runs), err)
+ }
+ s := &lostAckStore{Store: dir, lost: 1}
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), s, pending, nil)
+ if len(pending[app]) != len(recs) {
+ t.Fatalf("after the lost acknowledgement %d records held, want all %d", len(pending[app]), len(recs))
+ }
+ logshipFlush(context.Background(), s, pending, nil)
+ if len(pending) != 0 {
+ t.Fatalf("%d records still held after the retry; later chunks stranded", len(pending[app]))
+ }
+ prefix := mustKey(t)(applog.Prefix(app.Acct, app.App))
+ keys, err := dir.List(context.Background(), prefix)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var n int
+ for _, k := range keys {
+ if strings.HasSuffix(k, ".jsonl.gz") {
+ n++
+ }
+ }
+ if n != len(runs) {
+ t.Fatalf("%d chunks written, want %d", n, len(runs))
+ }
+ perBox, trimmed, err := applog.ReadChunks[applog.Record](context.Background(), dir, prefix,
+ time.Time{}, time.Time{}, func(applog.Record) bool { return true }, 2*logshipMaxPending)
+ if err != nil || trimmed || len(perBox) != 1 || len(perBox[0]) != len(recs) {
+ t.Fatalf("read back: %v trimmed=%v, %d records; want %d once each", err, trimmed, len(perBox[0]), len(recs))
+ }
+ for i, r := range perBox[0] {
+ if r.Seq != recs[i].Seq {
+ t.Fatalf("record %d has seq %d, want %d", i, r.Seq, recs[i].Seq)
+ }
+ }
+}
+
+// A conflict on a chunk whose existing body differs is still a refusal: the
+// records stay held and the other object is not overwritten.
+func TestLogshipConflictWithOtherContentHolds(t *testing.T) {
+ dir := release.NewDirStore(t.TempDir())
+ app := applog.AppKey{Acct: "bde", App: "ledgerpay"}
+ recs := worstCaseRecords()
+ runs, bodies, err := applog.EncodeChunks(recs)
+ if err != nil || len(runs) < 2 {
+ t.Fatalf("EncodeChunks: %d runs, %v", len(runs), err)
+ }
+ r := runs[0]
+ key := mustKey(t)(applog.ChunkKey(app.Acct, app.App, r[0].Box, applog.HourOf(r[0].TS), r[0].Seq, len(bodies[0])))
+ other := append([]byte(nil), bodies[0]...)
+ other[len(other)-1] ^= 0xff
+ if _, err := dir.Put(context.Background(), key, other, ""); err != nil {
+ t.Fatal(err)
+ }
+ pending := map[applog.AppKey][]applog.Record{app: recs}
+ logshipFlush(context.Background(), dir, pending, nil)
+ if len(pending[app]) != len(recs) {
+ t.Fatalf("%d records held after a conflict with other content, want all %d", len(pending[app]), len(recs))
+ }
+ if got, _, _ := dir.Get(context.Background(), key); !bytes.Equal(got, other) {
+ t.Fatal("the existing object was overwritten")
+ }
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index c9acabb5b..1dca4771b 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := secH4MemberDoorsWriteCensusInventory()
+ inventory := secConsoleDosWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/sec_console_dos_census_test.go b/internal/provision/sec_console_dos_census_test.go
new file mode 100644
index 000000000..97f081cbb
--- /dev/null
+++ b/internal/provision/sec_console_dos_census_test.go
@@ -0,0 +1,37 @@
+package provision
+
+// secConsoleDosWriteCensusInventory is the record-write census for branch
+// sec-console-dos, layered on fleetUpdateHoldWriteCensusInventory (the inventory
+// TestPlan9B8RecordWriteCensus used before this branch). No record write is
+// added, moved or reclassified:
+//
+// - var routeDecls (console, re-pinned on fleetUpdateHold's digest): one new declaration, POST
+// /api/ses/events/{token} (the SES events door behind a secret path).
+// It records bounce and complaint suppressions in the console database;
+// it writes no app records, sidecars or bucket objects. The instances
+// and sidecars literals are unchanged: still key-site.
+// - internal/host errshipFlush and logshipFlush: the batch is cut into
+// chunks (applog.EncodeChunks) and each chunk's single create-only Put
+// moved into the shared shipChunk, which on a conflict reads the
+// existing object and treats an identical body as delivered. The Put is
+// still of one log or error chunk under the app's logs or errors
+// prefix; no record key. The two flush units no longer hold a write
+// site; shipChunk is the one nonrecord Put site for both.
+func secConsoleDosWriteCensusInventory() []censusEntry {
+ base := secH4MemberDoorsWriteCensusInventory()
+ entries := make([]censusEntry, 0, len(base)+1)
+ for _, e := range base {
+ switch {
+ case e.File == "internal/host/errship.go" && e.Unit == "errshipFlush",
+ e.File == "internal/host/logship.go" && e.Unit == "logshipFlush":
+ continue
+ case e.File == "internal/console/routedecls.go" && e.Unit == "var routeDecls":
+ if e.Class != "key-site" || e.Kinds != "lit:instances,lit:sidecars" {
+ panic("sec-console-dos re-pin changes the class or kinds of var routeDecls")
+ }
+ e.Digest = "3e9ed52ed0a7048c8f9f1df49e48c2090d959bfa2b886df346532a250e202eab"
+ }
+ entries = append(entries, e)
+ }
+ return append(entries, censusEntry{"internal/host/logship.go", "shipChunk", "nonrecord", "sel:Put", "f65e1bbd868803a1759e9ebe12235ac7f776c2fe33583817c1806a37eba0c70c"})
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index b4ca838fc..dc4ac692d 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -306,3 +306,4 @@ plan14-root-reads-gvisor-slice1-control-purge.tsv a3f8ba38714f1cdeea10b3e5ed4402
plan14-root-reads-sec-h5-edge-availability.tsv 96487fabb7fdc93cd86b17188c145350d7248d67cd5928c10142f997b5a19c61
plan14-root-reads-fleet-update-hold.tsv 96487fabb7fdc93cd86b17188c145350d7248d67cd5928c10142f997b5a19c61
plan14-root-reads-s3-polling-3.tsv 5933c519749247288b20f5d6e2398879ac7209d1bfeff2fb0d93d14b426f9e2f
+plan14-root-reads-sec-console-dos.tsv 5933c519749247288b20f5d6e2398879ac7209d1bfeff2fb0d93d14b426f9e2f
diff --git a/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv b/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv
new file mode 100644
index 000000000..9c35eb8e4
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-sec-console-dos.tsv
@@ -0,0 +1,5 @@
+# Census overlay sec-console-dos, written by census-propose (#369). census-ruling-sec-console-dos, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-sec-console-dos.md.
+# 0 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/apperr eeed6e99fe5b8d2be14e07d3d4a96d4a3dd9995f9b99c80c09349f1b123d3ffa
+@coverage internal/applog bf04191fc816519559492f0d598d9d64ec5edd96660c95342e980429bcc43300
+@coverage internal/host 417904b727c82aab1030dae386c1f63ee6a8d6bcafe7b2d140b56438d9283bab
diff --git a/parity/parity.tsv b/parity/parity.tsv
index b5ac5d2f1..7c3a31082 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -274,6 +274,6 @@ healthz platform internal GET /healthz Health check for the load balancer.
alert-signing-key platform internal GET /alerts/signing-key The public key alert webhook receivers fetch.
legacy-apps platform internal GET /apps ; GET /apps/{app} Old URLs kept as redirects into the account.
billing-webhook platform internal POST /billing/webhook Stripe calls it.
-ses-events platform internal POST /api/ses/events Amazon SES delivery events.
+ses-events platform internal POST /api/ses/events ; POST /api/ses/events/{token} Amazon SES delivery events.
box-doors platform internal POST /api/fleet/enrol ; POST /api/fleet/enrol/seed ; POST /api/fleet/managed/secrets-key ; GET /api/box/interactive/{id} ; GET /api/box/runs/{id} ; POST /api/fleet/replicas/{account}/{app}/{host}/coordinator ; POST /api/fleet/replicas/{account}/{app}/{host}/release ; POST /api/fleet/replicas/{account}/{app}/{host}/deploy ; POST /api/fleet/seeds/{account}/{app}/{host}/placed ; POST /api/fleet/seeds/{account}/{app}/{host}/failed ; POST /api/fleet/seeds/{account}/{app}/{host}/rolledback Doors boxes and managed fleets call, not people.
plumbing platform internal __demo-snapshot ; __registry-child ; __rootfs-check-probe ; __rootfs-check-prepare ; __cgexec ; __cgprobe Words the binary runs itself as, dispatched before the command switch.