carlos / platform Public

console: owner-only doors for members; removal ends their credentials

Fixes from the October hunt (H4, H5-M1), with Paul's rulings:
- Members can no longer delete or place apps, change pipelines, attach
  or detach domains, change a temporary app's expiry or turn off an
  instance's password; those doors are owner-only, and password-off,
  app delete and TTL also need a step-up.
- Removing or demoting a member revokes the credentials they minted,
  including platform per-customer credentials and those derived from
  platform service credentials; a durable queue retries per app.
- Named-service and platform mints re-check the minter's current role.
- A platform's live per-customer Publish credential counts as owner on
  its customer account (step-up doors excepted).
- A catch-all over another account's name is refused unless the parent
  is proven by its DNS challenge; existing names keep working.

Reviews: Astra and Fable, three rounds plus a Paul-approved scoped
round; census approved (Astra). Copy approved by Paul.

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

Squashed from sec-h4-member-doors into main.
claude agent, operated by paul@keymail.dev 7dbd8e1752550619b2dbeab1678d874093183e80 parent e210550
87 files changed, +3,092 −202
  • .amadan/code-health.tsv +1 −4
  • cmd/console/member.go +1 −1
  • cmd/console/member_demo_test.go +31 −1
  • internal/console/apibackups_test.go +1 −0
  • internal/console/apicli.go +7 −0
  • internal/console/apicli_test.go +6 −5
  • internal/console/apidomainpaths_test.go +10 −10
  • internal/console/apidomains.go +22 −0
  • internal/console/apidomains_firstroute_test.go +2 −2
  • internal/console/apidomains_test.go +55 −32
  • internal/console/apidoorkeys.go +5 −1
  • internal/console/apidoorkeys_test.go +1 −1
  • internal/console/apifeatures_test.go +1 −1
  • internal/console/apiinstances.go +11 −0
  • internal/console/apiinstances_test.go +12 −4
  • internal/console/apipipeline.go +8 −0
  • internal/console/apipipeline_test.go +1 −0
  • internal/console/apiplacements.go +9 −0
  • internal/console/apiplacements_put_test.go +27 −0
  • internal/console/apiplatformcustomers.go +12 −1
  • internal/console/apiplatformcustomers_test.go +20 −2
  • internal/console/apirestart_test.go +2 −1
  • internal/console/apiservices.go +94 −0
  • internal/console/apiservices_test.go +2 −1
  • internal/console/apisidecars_test.go +2 −1
  • internal/console/apitemporary.go +7 −0
  • internal/console/apitemporary_test.go +20 −0
  • internal/console/appsettings.go +14 −6
  • internal/console/appsettings_gate_test.go +10 −0
  • internal/console/authstore.go +18 −3
  • internal/console/authstore_test.go +5 −0
  • internal/console/catchallchild_test.go +227 −0
  • internal/console/claim_alias.go +5 −0
  • internal/console/controlplane_test.go +1 −0
  • internal/console/deletion_evidence_test.go +2 −2
  • internal/console/deletion_test.go +1 −1
  • internal/console/demo_api_origin_test.go +3 −1
  • internal/console/demo_members.go +12 −10
  • internal/console/deploycred_test.go +3 −0
  • internal/console/domainattach.go +3 −0
  • internal/console/domaincatchall.go +145 −6
  • internal/console/domaincatchall_test.go +1 −1
  • internal/console/domainplatform_test.go +8 −5
  • internal/console/domainpolicy.go +20 −10
  • internal/console/domainpolicy_test.go +5 −5
  • internal/console/domainproof_test.go +4 −4
  • internal/console/doorkeys_store.go +50 −8
  • internal/console/fleets.go +26 −4
  • internal/console/hap2_wiring_test.go +1 −1
  • internal/console/hostsused_writers_test.go +1 −1
  • internal/console/hunt_H4-M10_test.go +39 −0
  • internal/console/hunt_H4-M12_test.go +52 −0
  • internal/console/hunt_H4-M1_test.go +180 −0
  • internal/console/hunt_H4-M2_test.go +26 −0
  • internal/console/hunt_H4-M3_test.go +72 −0
  • internal/console/hunt_H4-M4_test.go +53 −0
  • internal/console/hunt_H4-M7_test.go +27 −0
  • internal/console/hunt_H5-M1_test.go +106 −0
  • internal/console/lifetimes_create_test.go +6 −6
  • internal/console/lifetimes_retire_test.go +2 −2
  • internal/console/links_sync.go +5 −0
  • internal/console/member_demo_test.go +3 −3
  • internal/console/memberrevoke.go +466 −0
  • internal/console/memberrevoke_claim_test.go +121 −0
  • internal/console/memberrevoke_test.go +597 −0
  • internal/console/ownership.go +19 −6
  • internal/console/plancaps_doors_test.go +3 −3
  • internal/console/planmembers_test.go +2 −2
  • internal/console/platform_credentials.go +10 −6
  • internal/console/platform_credentials_test.go +132 −3
  • internal/console/regional_writers_test.go +6 −3
  • internal/console/seedholdreview_test.go +2 −0
  • internal/console/seedslice3review_test.go +2 −0
  • internal/console/store.go +40 −12
  • internal/console/store_gate.go +1 −0
  • internal/console/subdomains_test.go +31 −15
  • internal/console/svcfixture_test.go +47 −0
  • internal/console/svcpage.go +6 −0
  • internal/console/svcpage_test.go +5 −1
  • internal/console/svcprincipal.go +29 −0
  • internal/console/svcprincipal_run_test.go +1 −0
  • internal/console/svcprincipal_test.go +8 −0
  • internal/console/svcscope_test.go +9 −1
  • internal/console/teamdoors_test.go +3 −1
  • internal/provision/ffr_census_test.go +11 −1
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/sec_h4_member_doors_census_test.go +34 −0

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-i5c0M5
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2 v1.44.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
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 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/prometheus/client_golang v1.17.0
go: downloading github.com/aws/aws-sdk-go-v2/service/acm v1.45.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/resourcegroupstaggingapi v1.37.0
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/pierrec/lz4/v4 v4.1.22
go: downloading github.com/pion/turn/v4 v4.1.4
go: downloading github.com/lmittmann/tint v1.1.3
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/pion/transport/v4 v4.0.2
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading golang.org/x/text v0.43.0
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
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/libc v1.74.1
go: downloading modernc.org/memory v1.11.0
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
=== launchctx (4 s, from +0 s)
ok  	amadan.net/carlos/platform.git/launchctx	0.015s
?   	amadan.net/carlos/platform.git/launchctx/controlname	[no test files]
?   	amadan.net/carlos/platform.git/launchctx/wireid	[no test files]
=== vet (167 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/pierrec/lz4/v4 v4.1.22
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading modernc.org/libc v1.74.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec
=== vet-tags (165 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
=== gofmt (2 s, from +0 s)
gofmt -l .: clean
=== rest (387 s, from +15 s)
ok  	github.com/carlosframework/platform/cmd/carlos-media	122.706s
?   	github.com/carlosframework/platform/cmd/changelog	[no test files]
ok  	github.com/carlosframework/platform/cmd/console	213.664s
ok  	github.com/carlosframework/platform/cmd/mediaimage	36.595s
ok  	github.com/carlosframework/platform/cmd/moveprobe	14.576s
ok  	github.com/carlosframework/platform/cmd/pricebook-export	0.031s
ok  	github.com/carlosframework/platform/cmd/rootfswitness	0.181s
ok  	github.com/carlosframework/platform/cmd/runsc-assets	0.133s
ok  	github.com/carlosframework/platform/cmd/zddprobe	0.871s
ok  	github.com/carlosframework/platform/internal/agentsock	0.118s
ok  	github.com/carlosframework/platform/internal/alerting	0.014s
ok  	github.com/carlosframework/platform/internal/analytics	0.161s
ok  	github.com/carlosframework/platform/internal/appconfig	37.800s
ok  	github.com/carlosframework/platform/internal/apperr	0.309s
ok  	github.com/carlosframework/platform/internal/applog	0.500s
ok  	github.com/carlosframework/platform/internal/apppolicy	1.842s
ok  	github.com/carlosframework/platform/internal/assetcache	0.564s
ok  	github.com/carlosframework/platform/internal/awsinv	0.012s
ok  	github.com/carlosframework/platform/internal/awsmanaged	14.206s
ok  	github.com/carlosframework/platform/internal/awsregiongroup	0.092s
ok  	github.com/carlosframework/platform/internal/awsterminations	0.014s
ok  	github.com/carlosframework/platform/internal/backupswords	0.014s
ok  	github.com/carlosframework/platform/internal/billing	0.060s
ok  	github.com/carlosframework/platform/internal/billing/billingtest	0.053s
ok  	github.com/carlosframework/platform/internal/billingstripe	1.686s
ok  	github.com/carlosframework/platform/internal/boxchoice	0.016s
ok  	github.com/carlosframework/platform/internal/boxid	1.902s
?   	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.011s
ok  	github.com/carlosframework/platform/internal/boxself	0.099s
ok  	github.com/carlosframework/platform/internal/boxvolumes	0.036s
ok  	github.com/carlosframework/platform/internal/caps	2.718s
ok  	github.com/carlosframework/platform/internal/certwarm	0.012s
ok  	github.com/carlosframework/platform/internal/cgroup	1.287s
ok  	github.com/carlosframework/platform/internal/changelog	3.093s
ok  	github.com/carlosframework/platform/internal/clamd	0.067s
?   	github.com/carlosframework/platform/internal/cliflag	[no test files]
ok  	github.com/carlosframework/platform/internal/clireg	0.009s
ok  	github.com/carlosframework/platform/internal/codehealth	12.048s
ok  	github.com/carlosframework/platform/internal/compute	0.017s
ok  	github.com/carlosframework/platform/internal/consolefleet	0.007s
?   	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.196s
ok  	github.com/carlosframework/platform/internal/dbdoor/dbdoortest	0.024s
ok  	github.com/carlosframework/platform/internal/dbquery	0.013s
ok  	github.com/carlosframework/platform/internal/dbreads	2.951s
?   	github.com/carlosframework/platform/internal/dbreads/dbreadstest	[no test files]
ok  	github.com/carlosframework/platform/internal/dbverify	0.026s
ok  	github.com/carlosframework/platform/internal/demo	0.004s
ok  	github.com/carlosframework/platform/internal/demobuild	3.532s
ok  	github.com/carlosframework/platform/internal/democlaim	0.263s
ok  	github.com/carlosframework/platform/internal/devbox	10.985s
ok  	github.com/carlosframework/platform/internal/dnsrec	0.005s
ok  	github.com/carlosframework/platform/internal/docsite	0.060s
ok  	github.com/carlosframework/platform/internal/domainreg	0.019s
ok  	github.com/carlosframework/platform/internal/domains	67.794s
ok  	github.com/carlosframework/platform/internal/doorkey	0.011s
ok  	github.com/carlosframework/platform/internal/economics	0.014s
ok  	github.com/carlosframework/platform/internal/edgefence	0.082s
ok  	github.com/carlosframework/platform/internal/edgeguard	0.121s
?   	github.com/carlosframework/platform/internal/edgeproof	[no test files]
ok  	github.com/carlosframework/platform/internal/edgesfile	0.039s
ok  	github.com/carlosframework/platform/internal/egressaddr	0.004s
ok  	github.com/carlosframework/platform/internal/execsandbox	101.846s
ok  	github.com/carlosframework/platform/internal/fileacl	0.002s
ok  	github.com/carlosframework/platform/internal/fleetapi	1.435s
ok  	github.com/carlosframework/platform/internal/fleetstore	0.006s
ok  	github.com/carlosframework/platform/internal/fxrate	0.013s
ok  	github.com/carlosframework/platform/internal/gate	3.895s
ok  	github.com/carlosframework/platform/internal/genselect	0.045s
ok  	github.com/carlosframework/platform/internal/geo	0.022s
ok  	github.com/carlosframework/platform/internal/geoip	0.039s
ok  	github.com/carlosframework/platform/internal/groupadmission	0.009s
ok  	github.com/carlosframework/platform/internal/grouprollaws	16.541s
ok  	github.com/carlosframework/platform/internal/hadeparture	0.013s
ok  	github.com/carlosframework/platform/internal/hafresh	0.004s
ok  	github.com/carlosframework/platform/internal/hairpin	0.112s
ok  	github.com/carlosframework/platform/internal/historyreadback	0.610s
ok  	github.com/carlosframework/platform/internal/hostactors	20.821s
ok  	github.com/carlosframework/platform/internal/hostbox	17.155s
ok  	github.com/carlosframework/platform/internal/hostclaim	2.056s
ok  	github.com/carlosframework/platform/internal/hostenv	0.034s
ok  	github.com/carlosframework/platform/internal/hostevidence	0.023s
ok  	github.com/carlosframework/platform/internal/hostexec	17.752s
ok  	github.com/carlosframework/platform/internal/hostfence	0.139s
ok  	github.com/carlosframework/platform/internal/hostfiles	22.495s
ok  	github.com/carlosframework/platform/internal/hostfloor	0.036s
ok  	github.com/carlosframework/platform/internal/hostguard	1.348s
ok  	github.com/carlosframework/platform/internal/hostops	5.443s
?   	github.com/carlosframework/platform/internal/hostops/fencerelease	[no test files]
ok  	github.com/carlosframework/platform/internal/hostops/internal/fencerelease	0.016s
ok  	github.com/carlosframework/platform/internal/hostquarantine	0.012s
ok  	github.com/carlosframework/platform/internal/hostrelocate	1.342s
ok  	github.com/carlosframework/platform/internal/hostresolve	0.550s
ok  	github.com/carlosframework/platform/internal/hostwrite	0.006s
ok  	github.com/carlosframework/platform/internal/infraview	0.011s
ok  	github.com/carlosframework/platform/internal/ingresshealth	0.014s
ok  	github.com/carlosframework/platform/internal/ingresshealth/awstg	0.008s
ok  	github.com/carlosframework/platform/internal/instancectl	64.237s
ok  	github.com/carlosframework/platform/internal/instanceexec	8.446s
ok  	github.com/carlosframework/platform/internal/instancefs	12.389s
ok  	github.com/carlosframework/platform/internal/instancekey	0.008s
ok  	github.com/carlosframework/platform/internal/instanceupdates	0.043s
ok  	github.com/carlosframework/platform/internal/interactive	0.626s
ok  	github.com/carlosframework/platform/internal/launchd	0.009s
ok  	github.com/carlosframework/platform/internal/layout	19.605s
ok  	github.com/carlosframework/platform/internal/layout/pubclass	102.023s
ok  	github.com/carlosframework/platform/internal/lbhealth	0.012s
ok  	github.com/carlosframework/platform/internal/lease	144.425s
ok  	github.com/carlosframework/platform/internal/lease/leasetest	1.096s
ok  	github.com/carlosframework/platform/internal/lease/locktest	0.019s
ok  	github.com/carlosframework/platform/internal/ledger	0.058s
ok  	github.com/carlosframework/platform/internal/mail	0.811s
ok  	github.com/carlosframework/platform/internal/mailer	0.754s
ok  	github.com/carlosframework/platform/internal/mailsubmit	1.437s
ok  	github.com/carlosframework/platform/internal/mailwire	0.010s
ok  	github.com/carlosframework/platform/internal/maintenance	0.143s
ok  	github.com/carlosframework/platform/internal/maintenanceexec	8.403s
ok  	github.com/carlosframework/platform/internal/maintenanceguard	0.230s
ok  	github.com/carlosframework/platform/internal/managedboot	2.878s
?   	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.474s
ok  	github.com/carlosframework/platform/internal/media/mediatest	0.016s
ok  	github.com/carlosframework/platform/internal/mediaaws	56.672s
ok  	github.com/carlosframework/platform/internal/mediahandler	39.166s
ok  	github.com/carlosframework/platform/internal/mediajobs	0.705s
ok  	github.com/carlosframework/platform/internal/medialocal	9.611s
ok  	github.com/carlosframework/platform/internal/metrics	0.082s
ok  	github.com/carlosframework/platform/internal/minorunits	0.008s
ok  	github.com/carlosframework/platform/internal/moves	49.881s
ok  	github.com/carlosframework/platform/internal/moves/archive	2.191s
ok  	github.com/carlosframework/platform/internal/moves/offlinerun	0.082s
ok  	github.com/carlosframework/platform/internal/namedunits	0.025s
ok  	github.com/carlosframework/platform/internal/objstore	2.035s
ok  	github.com/carlosframework/platform/internal/ops	11.316s
ok  	github.com/carlosframework/platform/internal/pageindex	4.147s
ok  	github.com/carlosframework/platform/internal/parity	0.149s
?   	github.com/carlosframework/platform/internal/parity/cmd/parity-doc	[no test files]
ok  	github.com/carlosframework/platform/internal/park	0.491s
ok  	github.com/carlosframework/platform/internal/perf	0.186s
ok  	github.com/carlosframework/platform/internal/plans	0.058s
ok  	github.com/carlosframework/platform/internal/privatefile	0.007s
ok  	github.com/carlosframework/platform/internal/provision	234.817s
ok  	github.com/carlosframework/platform/internal/proxyproto	0.939s
ok  	github.com/carlosframework/platform/internal/publicrelease	0.036s
ok  	github.com/carlosframework/platform/internal/ratelimit	0.141s
ok  	github.com/carlosframework/platform/internal/regionlabel	0.055s
ok  	github.com/carlosframework/platform/internal/regionname	0.036s
ok  	github.com/carlosframework/platform/internal/registrar	0.014s
ok  	github.com/carlosframework/platform/internal/registrar/openprovider	0.546s
?   	github.com/carlosframework/platform/internal/registrar/registrartest	[no test files]
ok  	github.com/carlosframework/platform/internal/registry	81.844s
ok  	github.com/carlosframework/platform/internal/relay	7.483s
ok  	github.com/carlosframework/platform/internal/release	101.281s
?   	github.com/carlosframework/platform/internal/release/requestwitness	[no test files]
ok  	github.com/carlosframework/platform/internal/replicagen	0.040s
ok  	github.com/carlosframework/platform/internal/replicas	0.103s
ok  	github.com/carlosframework/platform/internal/reqrec	6.507s
ok  	github.com/carlosframework/platform/internal/rollout	10.658s
ok  	github.com/carlosframework/platform/internal/rolloutwords	0.064s
ok  	github.com/carlosframework/platform/internal/rootaws	99.987s
ok  	github.com/carlosframework/platform/internal/rootfsimage	0.770s
ok  	github.com/carlosframework/platform/internal/rootparticipation	0.101s
ok  	github.com/carlosframework/platform/internal/rootstate	0.046s
ok  	github.com/carlosframework/platform/internal/runs	0.670s
ok  	github.com/carlosframework/platform/internal/s3compat	0.021s
ok  	github.com/carlosframework/platform/internal/s3fake	0.891s
ok  	github.com/carlosframework/platform/internal/s3meter	0.442s
ok  	github.com/carlosframework/platform/internal/safefile	0.029s
ok  	github.com/carlosframework/platform/internal/schedule	20.656s
ok  	github.com/carlosframework/platform/internal/seeds	0.032s
ok  	github.com/carlosframework/platform/internal/sim/litestreamfacts	4.665s
ok  	github.com/carlosframework/platform/internal/sim/mediajobs	47.113s
ok  	github.com/carlosframework/platform/internal/sim/regionha	22.368s
ok  	github.com/carlosframework/platform/internal/status	0.283s
ok  	github.com/carlosframework/platform/internal/steering	0.173s
ok  	github.com/carlosframework/platform/internal/stopevidence	0.308s
ok  	github.com/carlosframework/platform/internal/storecfg	0.339s
ok  	github.com/carlosframework/platform/internal/svcrole	0.015s
ok  	github.com/carlosframework/platform/internal/systemd	5.900s
?   	github.com/carlosframework/platform/internal/systemdshow	[no test files]
ok  	github.com/carlosframework/platform/internal/team	2.408s
ok  	github.com/carlosframework/platform/internal/teamcontract	0.159s
ok  	github.com/carlosframework/platform/internal/telemetry	0.024s
ok  	github.com/carlosframework/platform/internal/termfence	2.247s
ok  	github.com/carlosframework/platform/internal/timerspec	0.024s
ok  	github.com/carlosframework/platform/internal/tsidentity	4.209s
ok  	github.com/carlosframework/platform/internal/tunnelclient	0.458s
ok  	github.com/carlosframework/platform/internal/unixdial	0.005s
ok  	github.com/carlosframework/platform/internal/updatewords	0.037s
ok  	github.com/carlosframework/platform/internal/upstreamguard	0.010s
?   	github.com/carlosframework/platform/internal/upstreamguard/guardtest	[no test files]
ok  	github.com/carlosframework/platform/internal/usage	0.027s
ok  	github.com/carlosframework/platform/internal/version	0.009s
ok  	github.com/carlosframework/platform/internal/vet	2.903s
ok  	github.com/carlosframework/platform/internal/zonehost	0.019s
ok  	github.com/carlosframework/platform/internal/zonehost/route53zones	0.049s
?   	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.010s
ok  	github.com/carlosframework/platform/scripts/pathmapcheck	0.088s
ok  	github.com/carlosframework/platform/scripts/region-ha-g2/fixture	5.182s
ok  	github.com/carlosframework/platform/scripts/stateless-replicas-drill	1.217s
ok  	github.com/carlosframework/platform/scripts/witness-pointer	0.031s
=== cutover-witness (155 s, from +15 s)
ok  	github.com/carlosframework/platform	2.195s
=== internal_grouproll@0 (267 s, from +72 s)
ok  	github.com/carlosframework/platform/internal/grouproll	264.982s
=== internal_grouproll@1 (275 s, from +72 s)
ok  	github.com/carlosframework/platform/internal/grouproll	273.102s
=== internal_activator@0 (157 s, from +149 s)
ok  	github.com/carlosframework/platform/internal/activator	151.267s
=== internal_activator@1 (133 s, from +149 s)
ok  	github.com/carlosframework/platform/internal/activator	127.525s
=== internal_activator@2 (134 s, from +149 s)
ok  	github.com/carlosframework/platform/internal/activator	127.742s
=== internal_activator@3 (167 s, from +149 s)
ok  	github.com/carlosframework/platform/internal/activator	161.135s
=== internal_edge@0 (260 s, from +170 s)
ok  	github.com/carlosframework/platform/internal/edge	251.167s
=== internal_edge@1 (138 s, from +170 s)
ok  	github.com/carlosframework/platform/internal/edge	129.481s
=== internal_edge@2 (161 s, from +170 s)
ok  	github.com/carlosframework/platform/internal/edge	152.705s
=== internal_edge@3 (157 s, from +170 s)
ok  	github.com/carlosframework/platform/internal/edge	148.981s
=== root@0 (133 s, from +171 s)
ok  	github.com/carlosframework/platform	125.606s
=== root@1 (110 s, from +171 s)
ok  	github.com/carlosframework/platform	101.939s
=== root@2 (120 s, from +171 s)
ok  	github.com/carlosframework/platform	111.040s
=== root@3 (125 s, from +171 s)
ok  	github.com/carlosframework/platform	115.963s
=== root@4 (106 s, from +171 s)
ok  	github.com/carlosframework/platform	97.431s
=== internal_host@0 (140 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	136.568s
=== internal_host@1 (188 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	184.122s
=== internal_host@2 (262 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	258.275s
=== internal_host@3 (210 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	206.265s
=== internal_host@4 (158 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	154.042s
=== internal_host@5 (228 s, from +217 s)
ok  	github.com/carlosframework/platform/internal/host	224.450s
=== internal_console@0 (204 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	196.181s
=== internal_console@1 (219 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	211.320s
=== internal_console@2 (202 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	194.491s
=== internal_console@3 (256 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	247.887s
=== internal_console@4 (198 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	189.475s
=== internal_console@5 (216 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	207.724s
=== internal_console@6 (232 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	225.859s
=== internal_console@7 (220 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	211.712s
=== internal_console@8 (217 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	209.022s
=== internal_console@9 (218 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	210.763s
=== internal_console@10 (216 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	209.701s
=== internal_console@11 (259 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	250.991s
=== internal_console@12 (302 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	294.235s
=== internal_console@13 (214 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	206.755s
=== internal_console@14 (214 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	205.227s
=== internal_console@15 (254 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	245.236s
=== internal_console@16 (209 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	200.297s
=== internal_console@17 (208 s, from +223 s)
ok  	github.com/carlosframework/platform/internal/console	199.221s
=== internal_console@18 (218 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	211.129s
=== internal_console@19 (207 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	199.842s
=== internal_console@20 (203 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	195.816s
=== internal_console@21 (230 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	223.633s
=== internal_console@22 (228 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	220.140s
=== internal_console@23 (230 s, from +224 s)
ok  	github.com/carlosframework/platform/internal/console	222.166s
=== lists: internal_console 222 s, internal_edge 169 s, internal_activator 148 s, internal_host 216 s, root 169 s, internal_grouproll 71 s
=== cpu: the gate used 12929 cpu-seconds in 526 s, about 24.6 of 32 cores; the machine as a whole was 82% busy
=== opentofu ===
opentofu: 39 test files in 11 suites, OpenTofu v1.13.9
  initialised in 14 s
  ok      21 s  infra/modules/box-fence-writer/tests/writer.tftest.hcl  Success! 1 passed, 0 failed.
  ok      23 s  infra/modules/deployment-buckets/tests/console_floors.tftest.hcl  Success! 1 passed, 0 failed.
  ok      33 s  infra/modules/deployment-buckets/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      21 s  infra/modules/deployment-buckets/tests/db_reads.tftest.hcl  Success! 1 passed, 0 failed.
  ok      18 s  infra/modules/deployment-buckets/tests/evidence.tftest.hcl  Success! 1 passed, 0 failed.
  ok      32 s  infra/modules/deployment-buckets/tests/fence_writers.tftest.hcl  Success! 3 passed, 0 failed.
  ok      26 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      26 s  infra/modules/pdf-host/tests/computed.tftest.hcl  Success! 2 passed, 0 failed.
  ok      54 s  infra/modules/pdf-host/tests/pdf_host.tftest.hcl  Success! 24 passed, 0 failed.
  ok      40 s  infra/modules/region-group-operator-document/tests/document.tftest.hcl  Success! 12 passed, 0 failed.
  ok      17 s  infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl  Success! 2 passed, 0 failed.
  ok      66 s  infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl  Success! 30 passed, 0 failed.
  ok      41 s  infra/modules/region-host/tests/alert_publish.tftest.hcl  Success! 18 passed, 0 failed.
  ok      40 s  infra/modules/region-host/tests/alerts_topic.tftest.hcl  Success! 16 passed, 0 failed.
  ok      13 s  infra/modules/region-host/tests/analytics_prune.tftest.hcl  Success! 2 passed, 0 failed.
  ok      14 s  infra/modules/region-host/tests/console_mail.tftest.hcl  Success! 4 passed, 0 failed.
  ok       6 s  infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl  Success! 1 passed, 0 failed.
  ok      73 s  infra/modules/region-host/tests/group.tftest.hcl  Success! 32 passed, 0 failed.
  ok      10 s  infra/modules/region-host/tests/group_alarms.tftest.hcl  Success! 4 passed, 0 failed.
  ok      10 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      33 s  infra/modules/region-host/tests/health_alarms.tftest.hcl  Success! 10 passed, 0 failed.
  ok      13 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      26 s  infra/modules/region-host/tests/mailer.tftest.hcl  Success! 6 passed, 0 failed.
  ok      16 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     103 s  infra/modules/region-host/tests/managed_fleets/managed_fleets.tftest.hcl  Success! 46 passed, 0 failed.
  ok      66 s  infra/modules/region-host/tests/store_conversion.tftest.hcl  Success! 27 passed, 0 failed.
  ok      14 s  infra/modules/region-host/tests/store_scanning.tftest.hcl  Success! 4 passed, 0 failed.
  ok      29 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      11 s  infra/modules/region-remote-host/tests/data_lifecycle.tftest.hcl  Success! 3 passed, 0 failed.
  ok      15 s  infra/modules/region-remote-host/tests/no_deployment_bucket.tftest.hcl  Success! 5 passed, 0 failed.
  ok      26 s  infra/modules/scanner-host/tests/scanner_host.tftest.hcl  Success! 14 passed, 0 failed.
opentofu: 39 files in 206 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:39155
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.038s
=== RUN   TestT4StorageProbeMinio
2026/11/28 18:25:46 moves: T4: STORE: list: operation error S3: ListObjectsV2, https response error StatusCode: 403, RequestID: 18EC48C140A7C2E8, HostID: f7385e8be4b94c6c6eaf1b4d0a412fd9c94371b5075c12e3631a2fcb24eda74d, 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.049s
=== 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.044s
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.03s)
PASS
ok  	github.com/carlosframework/platform/internal/release	0.041s
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.019s
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:_head
=== RUN   TestWriteCredentialContractMinio/refused:_list
=== RUN   TestWriteCredentialContractMinio/refused:_tag
=== RUN   TestWriteCredentialContractMinio/refused:_put_beside_the_prefix
=== RUN   TestWriteCredentialContractMinio/refused:_bucket_settings
=== RUN   TestWriteCredentialContractMinio/refused:_read_elsewhere
=== RUN   TestWriteCredentialContractMinio/refused:_list_uploads
=== RUN   TestWriteCredentialContractMinio/refused:_delete
=== RUN   TestWriteCredentialContractMinio/refused:_put_tagged
=== RUN   TestWriteCredentialContractMinio/refused:_put_with_a_platform_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:_read_under_the_prefix
--- PASS: TestWriteCredentialContractMinio (0.04s)
    --- PASS: TestWriteCredentialContractMinio/put_under_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/multipart_under_the_prefix (0.01s)
    --- PASS: TestWriteCredentialContractMinio/refused:_head (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_list (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_tag (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_put_beside_the_prefix (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_bucket_settings (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_read_elsewhere (0.00s)
    --- PASS: TestWriteCredentialContractMinio/refused:_list_uploads (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_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:_read_under_the_prefix (0.00s)
PASS
ok  	github.com/carlosframework/platform/internal/objstore	0.048s
=== RUN   TestEndToEndMinio
=== RUN   TestEndToEndMinio/plan
=== RUN   TestEndToEndMinio/roll
=== RUN   TestEndToEndMinio/replace
=== RUN   TestEndToEndMinio/remove
--- PASS: TestEndToEndMinio (0.47s)
    --- PASS: TestEndToEndMinio/plan (0.01s)
    --- PASS: TestEndToEndMinio/roll (0.12s)
    --- PASS: TestEndToEndMinio/replace (0.15s)
    --- PASS: TestEndToEndMinio/remove (0.15s)
PASS
ok  	github.com/carlosframework/platform/internal/grouproll	0.475s
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 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/28 18:25:54 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=720
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000001
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000002
2026/11/28 18:25:54 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000002 maxTXID=0000000000000002 size=370
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000002
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000002 txid.db=0000000000000003
2026/11/28 18:25:54 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000003 maxTXID=0000000000000003 size=454
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000003 txid.db=0000000000000003
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000000 txid.db=0000000000000001
2026/11/28 18:25:54 INFO ltx file uploaded system=store db=source.db replica=file level=0 minTXID=0000000000000001 maxTXID=0000000000000001 size=720
2026/11/28 18:25:54 INFO replica sync system=store db=source.db replica=file txid.replica=0000000000000001 txid.db=0000000000000001
2026/11/28 18:25:55 console: CARLOS_SECRETS_PUBKEY is unset, so no region outside the home can be chosen automatically
2026/11/28 18:25:55 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%3A37817: could not determine target mailbox
    agent.go:136: dbreads: dbr_qanawmjrxj34qwco5bxu2nxaqi: planned 1 files (720 bytes) and restored to 1 in 11ms
    agent.go:136: dbreads: dbr_qanawmjrxj34qwco5bxu2nxaqi: output 5 bytes in 1 confirmed chunks in 1ms
2026/11/28 18:25:56 console: db read dbr_qanawmjrxj34qwco5bxu2nxaqi: relayed 1 chunks (102 bytes) in 1.005s, ended done
    agent.go:136: dbreads: dbr_l3y5z25iwzxumanzl23dhwr25i: planned 3 files (1544 bytes) and restored to 3 in 13ms
    agent.go:136: dbreads: dbr_l3y5z25iwzxumanzl23dhwr25i: output 5 bytes in 1 confirmed chunks in 1ms
2026/11/28 18:25:57 console: db read dbr_l3y5z25iwzxumanzl23dhwr25i: relayed 1 chunks (102 bytes) in 1.004s, ended done
    agent.go:136: dbreads: dbr_qriieofrhjlkk7maq2x7qf3vd4: planned 3 files (1544 bytes) and held through 3 in 13ms
    agent.go:136: dbreads: dbr_qriieofrhjlkk7maq2x7qf3vd4: output 1544 bytes in 1 confirmed chunks in 1ms
2026/11/28 18:25:58 console: db read dbr_qriieofrhjlkk7maq2x7qf3vd4: relayed 1 chunks (1641 bytes) in 1.005s, ended done
=== RUN   TestDBForwardMinio/by_disconnect
=== NAME  TestDBForwardMinio
    agent.go:136: dbreads: dbr_6qkeahhm277ge525w273va6nry: planned 3 files (1544 bytes) and restored to 3 in 15ms
2026/11/28 18:25:58 console: db read dbr_6qkeahhm277ge525w273va6nry: relayed 0 chunks (0 bytes) in 22ms, ended client gone
    agent.go:136: dbreads: dbr_6qkeahhm277ge525w273va6nry: output 5 bytes in 1 confirmed chunks in 104ms
=== RUN   TestDBForwardMinio/by_timeout
=== NAME  TestDBForwardMinio
    agent.go:136: dbreads: dbr_6mwcq3av2ztdtu7sveh72djuxq: planned 3 files (1544 bytes) and restored to 3 in 12ms
2026/11/28 18:26:18 console: db read dbr_6mwcq3av2ztdtu7sveh72djuxq: relayed 0 chunks (0 bytes) in 19.631s, ended no-result
    agent.go:136: dbreads: dbr_6mwcq3av2ztdtu7sveh72djuxq: output 5 bytes in 1 confirmed chunks in 19.606s
--- PASS: TestDBForwardMinio (23.32s)
    --- PASS: TestDBForwardMinio/by_disconnect (0.23s)
    --- PASS: TestDBForwardMinio/by_timeout (19.74s)
PASS
ok  	github.com/carlosframework/platform/internal/console	23.361s
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.07s)
PASS
ok  	github.com/carlosframework/platform/internal/mediaaws	0.075s
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.55s)
PASS
ok  	github.com/carlosframework/platform/internal/medialocal	0.557s
=== RUN   TestHeldHandoverTwoBoxMinio
2026/11/28 18:26:23 edge: mesh key: minted
2026/11/28 18:26:23 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 18:26:23 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 18:26:23 tenant admission is open. accepting tenant work
2026/11/28 18:26:23 activator: HA placement host=shop-78694433.example.test kind=Place ref=annie reason=roomiest generation=2026-11-28T18:26:23Z lock_generation=0
2026/11/28 18:26:23 lease: t8-78694433/shop-78694433.example.test: HA lease acquired in 4ms (first wake)
2026/11/28 18:26:23 activator: shop-78694433.example.test: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 18:26:23 activator: shop-78694433.example.test: started carlos-instance@shop\x2d78694433.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) 6ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 18:26:23 activator: shop-78694433.example.test: carlos-instance@shop\x2d78694433.example.test.service launched in 7ms, healthy 0s later
2026/11/28 18:26:23 activator: shop-78694433.example.test: woke in 19ms: checks 0s, lease 4ms, restore 0s, identity 0s, protect 0s, spawn 7ms, replicate 7ms
2026/11/28 18:26:23 lease: t8-78694433/plain-78694433.example.test: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/28 18:26:23 activator: no replica for plain-78694433.example.test in s3://contract-bucket/t8-78694433/plain-78694433.example.test — booting fresh
2026/11/28 18:26:23 activator: plain-78694433.example.test: started carlos-instance@plain\x2d78694433.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 1ms, instance key 0s, env 4ms, control socket 0s, key gate 0s, logs 0s) 5ms, launch file 0s, gate 0s, root start 1ms)
2026/11/28 18:26:23 activator: plain-78694433.example.test: carlos-instance@plain\x2d78694433.example.test.service launched in 6ms, healthy 0s later
2026/11/28 18:26:23 activator: plain-78694433.example.test: woke in 90ms: checks 0s, lease 1ms, restore 18ms, identity 0s, protect 0s, spawn 6ms, replicate 64ms
2026/11/28 18:26:23 lease: t8-78694433/bot0.shop.bac.sidecar.internal: HA lease acquired in 3ms (first wake)
2026/11/28 18:26:23 activator: bot0.shop.bac.sidecar.internal: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 18:26:23 activator: bot0.shop.bac.sidecar.internal: woke in 68ms: checks 0s, lease 4ms, restore 0s, identity 0s, protect 0s, spawn 7ms, settle 0s, replicate 57ms
2026/11/28 18:26:23 activator: next-due probe plain-78694433.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 18:26:23 activator: plain-78694433.example.test hibernated
2026/11/28 18:26:23 activator: bot0.shop.bac.sidecar.internal: released with a marker (clean true, txid 1, files 3:80826f51d4019bb34ecc3c3a4a832c80655b4592743252cea5029da48a5f0840) in 7ms: files 1ms, sync 4ms, record 1ms, marker 2ms
2026/11/28 18:26:23 activator: bot0.shop.bac.sidecar.internal hibernated
2026/11/28 18:26:23 activator: next-due probe shop-78694433.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 18:26:23 activator: shop-78694433.example.test: released with a marker (clean true, txid 1, files 3:aae207fc82a75b5ceb095efe85b4a519f5286f2361e189e9abb6fb26ea45a7b4) in 5ms: files 1ms, sync 2ms, record 1ms, marker 2ms
2026/11/28 18:26:23 activator: shop-78694433.example.test hibernated
2026/11/28 18:26:23 lease: t8-78694433/shop-78694433.example.test: HA lease acquired in 2ms (clean marker)
2026/11/28 18:26:23 activator: shop-78694433.example.test: restored (other-box)
2026/11/28 18:26:23 activator: shop-78694433.example.test: started carlos-instance@shop\x2d78694433.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 18:26:23 activator: shop-78694433.example.test: carlos-instance@shop\x2d78694433.example.test.service launched in 2ms, healthy 0s later
2026/11/28 18:26:23 activator: shop-78694433.example.test: woke in 85ms: checks 0s, lease 3ms, restore 24ms, identity 0s, protect 0s, spawn 2ms, replicate 56ms
2026/11/28 18:26:23 edge: ha-take shop-78694433.example.test from annie (txn t8-witness, marker generation 1): holder betty, generation 2
2026/11/28 18:26:23 edge: forward shop-78694433.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:d9030b19ab7c5be7fdbf36a0a1142362 Step:move Result:ok Reasons:[] Fence:t8-witness StartedAt:2026-11-28 18:26:23.44161249 +0000 UTC FinishedAt:2026-11-28 18:26:23.59008054 +0000 UTC Acked:[betty carol] Departed:[] Moved:[{Host:shop-78694433.example.test Holder:betty Gen:2 Confirmed:take}] Released:[{Host:plain-78694433.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:125 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-78694433.example.test <nil> stop plain-78694433.example.test marker=true clean=true <nil> stop bot0.shop.bac.sidecar.internal marker=true clean=true <nil> releasing shop-78694433.example.test <nil> stop shop-78694433.example.test marker=true clean=true <nil> taken shop-78694433.example.test betty <nil> end-moves]
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: DELETE /contract-bucket/t8-78694433/plain-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/bot0.shop.bac.sidecar.internal/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/bot0.shop.bac.sidecar.internal/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/shop-78694433.example.test/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/shop-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/shop-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/head.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/generations/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0008/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0007/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0006/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0005/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0004/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0008/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0007/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0006/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0005/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0004/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/0009/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/files/0/manifest.json
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/files/0/objects/0000000000000001-ae47b57a9bd83bb8f534c030ff9b8c08472093b9bab73e6ac31c233fa0f207f7
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/files/0/objects/0000000000000003-279173c2b6054b195f79b2d1821855e5844a0d27cba3100c078836080dfc04b5
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/0000/0000000000000001-0000000000000001.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0000/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0009/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: PUT /contract-bucket/t8-78694433/shop-78694433.example.test/0000/0000000000000002-0000000000000002.ltx
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0001/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0002/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: LIST /contract-bucket?t8-78694433/shop-78694433.example.test/0003/
    hadrain_twobox_minio_linux_test.go:1241: S3 during the drain: GET /contract-bucket/t8-78694433/shop-78694433.example.test/lock.json
    hadrain_twobox_minio_linux_test.go:1243: drain took 201ms; S3 calls 44 (DELETE lock=1 GET files=3 GET head=1 GET lock=3 GET replica=2 LIST replica=28 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 18:26:23 lease: t8-78694433/plain-78694433.example.test: acquired in 1ms (client 0s, lock read and write 1ms)
2026/11/28 18:26:23 activator: plain-78694433.example.test: started carlos-instance@plain\x2d78694433.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 18:26:23 activator: plain-78694433.example.test: carlos-instance@plain\x2d78694433.example.test.service launched in 1ms, healthy 0s later
2026/11/28 18:26:23 lease: /tmp/carlos-minio-contract-3TGE2l/g/dw2889768669/data/instances/plain-78694433.example.test/plain-78694433.example.test.db: continuity with the last clean close not proven; snapshot 1-0000000000000001 written before serving
2026/11/28 18:26:23 activator: plain-78694433.example.test: woke in 9ms: checks 0s, lease 1ms, restore 0s, identity 0s, protect 0s, spawn 1ms, replicate 6ms
2026/11/28 18:26:23 activator: next-due probe shop-78694433.example.test: decode /api/next-due: invalid character 'b' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 18:26:23 activator: shop-78694433.example.test: released with a marker (clean true, txid 2, files 3:aae207fc82a75b5ceb095efe85b4a519f5286f2361e189e9abb6fb26ea45a7b4) in 4ms: files 1ms, sync 0s, record 1ms, marker 2ms
2026/11/28 18:26:23 activator: shop-78694433.example.test hibernated
2026/11/28 18:26:23 tenant admission is closed for shutdown
2026/11/28 18:26:23 activator: next-due probe plain-78694433.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 18:26:23 activator: plain-78694433.example.test hibernated
--- PASS: TestHeldHandoverTwoBoxMinio (0.64s)
=== RUN   TestHeldHandoverLostLeaseMinio
2026/11/28 18:26:23 edge: mesh key: minted
2026/11/28 18:26:23 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 18:26:23 provision: minted sidecar route bot0.shop.bac.sidecar.internal (app "shop" acct "bac" args ["work"])
2026/11/28 18:26:23 tenant admission is open. accepting tenant work
2026/11/28 18:26:23 activator: HA placement host=shop-c3d6693c.example.test kind=Place ref=annie reason=roomiest generation=2026-11-28T18:26:23Z lock_generation=0
2026/11/28 18:26:23 lease: t8-c3d6693c/shop-c3d6693c.example.test: HA lease acquired in 3ms (first wake)
2026/11/28 18:26:23 activator: shop-c3d6693c.example.test: restored (no-marker): first wake, the prefix proven empty, booting fresh
2026/11/28 18:26:23 activator: shop-c3d6693c.example.test: started carlos-instance@shop\x2dc3d6693c.example.test.service memory.max=536870912 (build 0s, prepare (dirs 0s, admin token 0s, 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 18:26:23 activator: shop-c3d6693c.example.test: carlos-instance@shop\x2dc3d6693c.example.test.service launched in 7ms, healthy 0s later
2026/11/28 18:26:23 activator: shop-c3d6693c.example.test: woke in 65ms: checks 0s, lease 4ms, restore 0s, identity 0s, protect 0s, spawn 7ms, replicate 54ms
2026/11/28 18:26:23 activator: next-due probe shop-c3d6693c.example.test: decode /api/next-due: invalid character 'a' looking for beginning of value — recording none (it sleeps until a request)
2026/11/28 18:26:23 activator: final checkpoint shop-c3d6693c.example.test: lease: release marker owed for s3://contract-bucket/t8-c3d6693c/shop-c3d6693c.example.test/lock.json (If-Match "b4b74ef0cdf8b33fc4776910522b8c80"): lease: write release marker: operation error S3: PutObject, https response error StatusCode: 503, RequestID: , HostID: , api error ServiceUnavailable: witness: refused
2026/11/28 18:26:23 activator: shop-c3d6693c.example.test hibernated
2026/11/28 18:26:23 activator: handover of shop-c3d6693c.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-c3d6693c.example.test client 4 "
    hadrain_twobox_minio_linux_test.go:1486: driver calls: [begin shop-c3d6693c.example.test <nil> releasing shop-c3d6693c.example.test <nil> stop shop-c3d6693c.example.test marker=false clean=false <nil> left shop-c3d6693c.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 18:26:23 tenant admission is closed for shutdown
2026/11/28 18:26:23 http: proxy error: context canceled
--- PASS: TestHeldHandoverLostLeaseMinio (0.32s)
PASS
ok  	github.com/carlosframework/platform/internal/host	1.004s
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 18:26:25 lease: instances/gen-1795890385185537615.shop.example.com: HA lease acquired in 5ms (first wake)
2026/11/28 18:26:25 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 18:26:25 lease: instances/gen-1795890385185537615.shop.example.com: HA lease acquired in 3ms (holder terminated)
    gentake_minio_test.go:308: a second create-only copy onto instances/gen-1795890385185537615.shop.example.com/g-00000000000000000002/0000/0000000000000001-0000000000000001.ltx: <nil> (destination condition honoured: false)
2026/11/28 18:26:25 ERROR retention enforcement failed system=store db=w.example.com.db error="enforce snapshot retention: remove ltx files: lease: invalid or changed generation binding"
=== RUN   TestGenerationTakeMinio/switch-412
2026/11/28 18:26:25 lease: instances/gen-1795890385408876697.shop.example.com: HA lease acquired in 3ms (first wake)
2026/11/28 18:26:25 ERROR retention enforcement failed system=store db=seed.db error="enforce snapshot retention: fetch ltx files: lease: a write has waited too long to reach storage (write fence)"
2026/11/28 18:26:25 lease: instances/gen-1795890385408876697.shop.example.com: HA lease acquired in 2ms (clean marker)
=== RUN   TestGenerationTakeMinio/copy-version
=== RUN   TestGenerationTakeMinio/store-time
2026/11/28 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 4ms (first wake)
2026/11/28 18:26:25 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 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 2ms (clean marker)
2026/11/28 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 2ms (unclean marker)
2026/11/28 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 2ms (unclean marker)
2026/11/28 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 2ms (unclean marker)
2026/11/28 18:26:25 lease: instances/gen-1795890385457967206.shop.example.com: HA lease acquired in 2ms (unclean marker)
=== RUN   TestGenerationTakeMinio/skew
--- PASS: TestGenerationTakeMinio (0.44s)
    --- PASS: TestGenerationTakeMinio/take (0.22s)
    --- PASS: TestGenerationTakeMinio/switch-412 (0.04s)
    --- PASS: TestGenerationTakeMinio/copy-version (0.01s)
    --- PASS: TestGenerationTakeMinio/store-time (0.15s)
    --- PASS: TestGenerationTakeMinio/skew (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/lease	0.446s
minio contract: PASS
=== staticcheck ===
go version go1.26.10 linux/arm64
go: downloading honnef.co/go/tools v0.8.2
go: downloading github.com/BurntSushi/toml v1.4.1-0.20240526193622-a339e1f7089c
go: downloading golang.org/x/exp/typeparams v0.0.0-20231108232855-2478ac86f678
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 1m53.138s
    codehealth_test.go:107: line metrics (code lines, then physical):
          file-lines  5471  7324  internal/activator activator_test.go
          file-lines  4207  7062  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   366   635  cmd/console serve
          func-lines   364   371  internal/host testRootMigrationBootstrap
          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        878 at  700 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         18590 at   45 sites  functions over 300 code lines (blank and comment-only lines not counted)
    codehealth_test.go:115: file-lines         30702 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 (113.14s)
PASS
ok  	github.com/carlosframework/platform/internal/codehealth	114.109s
=== code-health-record ===
go version go1.26.10 linux/arm64
code-health record: HEAD is on main; comparing with its parent e210550b1d88f79e5ae71a68cf668c4aaa35756c
=== RUN   TestRecordAgainstBase
--- PASS: TestRecordAgainstBase (0.01s)
PASS
ok  	github.com/carlosframework/platform/internal/codehealth	0.008s
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 +13 s)
ok  	github.com/carlosframework/platform/internal/systemd	13.461s
=== internal_rootaws@0 (25 s, from +35 s)
ok  	github.com/carlosframework/platform/internal/rootaws	25.276s
=== internal_activator@0 (268 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	265.538s
=== internal_activator@1 (268 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	265.928s
=== internal_activator@2 (278 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	275.227s
=== internal_activator@3 (418 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	415.924s
=== internal_activator@4 (275 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	272.785s
=== internal_activator@5 (312 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	309.455s
=== internal_activator@6 (320 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	317.881s
=== internal_activator@7 (411 s, from +111 s)
ok  	github.com/carlosframework/platform/internal/activator	408.342s
=== internal_edge@0 (84 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	81.314s
=== internal_edge@1 (77 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	74.391s
=== internal_edge@2 (206 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	203.393s
=== internal_edge@3 (185 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	182.361s
=== internal_edge@4 (181 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	177.819s
=== internal_edge@5 (224 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	220.816s
=== internal_edge@6 (206 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	203.710s
=== internal_edge@7 (226 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	222.918s
=== internal_edge@8 (225 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	222.201s
=== internal_edge@9 (341 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	338.483s
=== internal_edge@10 (238 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	235.386s
=== internal_edge@11 (211 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	208.426s
=== internal_edge@12 (246 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	243.251s
=== internal_edge@13 (264 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	261.575s
=== internal_edge@14 (174 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	171.463s
=== internal_edge@15 (246 s, from +134 s)
ok  	github.com/carlosframework/platform/internal/edge	243.389s
=== internal_host@0 (9 s, from +193 s)
ok  	github.com/carlosframework/platform/internal/host	4.871s
=== internal_host@1 (17 s, from +193 s)
ok  	github.com/carlosframework/platform/internal/host	13.280s
=== lists: internal_edge 133 s, internal_activator 110 s, internal_host 192 s, internal_rootaws 34 s, internal_systemd 13 s
=== cpu: the gate used 7675 cpu-seconds in 529 s, about 14.5 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/hashicorp/go-version v1.7.0
go: downloading github.com/spf13/viper v1.19.0
go: downloading github.com/charmbracelet/lipgloss v0.5.0
go: downloading golang.org/x/exp v0.0.0-20250218142911-aa4b98e5adaa
go: downloading github.com/spf13/cobra v1.9.1
go: downloading github.com/fatih/semgroup v1.2.0
go: downloading github.com/gitleaks/go-gitdiff v0.9.1
go: downloading github.com/h2non/filetype v1.1.3
go: downloading github.com/mholt/archives v0.1.2
go: downloading github.com/BobuSumisu/aho-corasick v1.0.3
go: downloading github.com/Masterminds/sprig/v3 v3.3.0
go: downloading github.com/lucasb-eyer/go-colorful v1.2.0
go: downloading github.com/muesli/reflow v0.2.1-0.20210115123740-9e1d0d53df68
go: downloading github.com/muesli/termenv v0.15.1
go: downloading github.com/mattn/go-runewidth v0.0.14
go: downloading github.com/andybalholm/brotli v1.1.2-0.20250424173009-453214e765f3
go: downloading github.com/nwaples/rardecode/v2 v2.1.0
go: downloading github.com/pierrec/lz4/v4 v4.1.21
go: downloading github.com/klauspost/compress v1.17.11
go: downloading github.com/klauspost/pgzip v1.2.6
go: downloading github.com/therootcompany/xz v1.0.1
go: downloading github.com/sorairolake/lzip-go v0.3.5
go: downloading github.com/dsnet/compress v0.0.2-0.20230904184137-39efe44ab707
go: downloading github.com/STARRY-S/zip v0.2.1
go: downloading github.com/ulikunitz/xz v0.5.12
go: downloading golang.org/x/sync v0.11.0
go: downloading golang.org/x/text v0.22.0
go: downloading github.com/minio/minlz v1.0.0
go: downloading github.com/bodgit/sevenzip v1.6.0
go: downloading github.com/fsnotify/fsnotify v1.8.0
go: downloading github.com/mitchellh/mapstructure v1.5.0
go: downloading github.com/sagikazarmark/slog-shim v0.1.0
go: downloading github.com/spf13/afero v1.12.0
go: downloading github.com/spf13/cast v1.7.1
go: downloading github.com/spf13/pflag v1.0.6
go: downloading dario.cat/mergo v1.0.1
go: downloading github.com/Masterminds/goutils v1.1.1
go: downloading github.com/Masterminds/semver/v3 v3.3.0
go: downloading github.com/huandu/xstrings v1.5.0
go: downloading github.com/mitchellh/copystructure v1.2.0
go: downloading github.com/shopspring/decimal v1.4.0
go: downloading golang.org/x/crypto v0.35.0
go: downloading github.com/mattn/go-colorable v0.1.14
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/pelletier/go-toml/v2 v2.2.3
go: downloading gopkg.in/yaml.v3 v3.0.1
go: downloading github.com/rivo/uniseg v0.2.0
go: downloading github.com/aymanbagabas/go-osc52/v2 v2.0.1
go: downloading golang.org/x/sys v0.30.0
go: downloading github.com/mitchellh/reflectwalk v1.0.2
go: downloading github.com/bodgit/plumbing v1.3.0
go: downloading go4.org v0.0.0-20230225012048-214862532bf5
go: downloading github.com/hashicorp/go-multierror v1.1.1
go: downloading github.com/bodgit/windows v1.0.1
go: downloading github.com/hashicorp/golang-lru/v2 v2.0.7
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 11876 tracked files; 33 not scanned, by exact path (scripts/gitleaks-gate/notscanned.go)
gitleaks: clean

landed from sec-h4-member-doors

diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index eed61f5e9..15515c446 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -1718,7 +1718,6 @@ 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).migrateDoorKeys console.sqlHandle.Exec 1
db-no-context internal/console (*Store).migrateEmailSignin console.sqlHandle.Exec 2
db-no-context internal/console (*Store).migrateGettingStarted console.sqlHandle.Exec 1
db-no-context internal/console (*Store).migrateLinks console.sqlHandle.Exec 2
@@ -1786,10 +1785,8 @@ db-no-context internal/console mintLinkTx (*sql.Tx).QueryRow 1
db-no-context internal/console openGated (*sql.DB).Exec 1
db-no-context internal/console putBillingState console.sqlExecer.Exec 1
db-no-context internal/console readAlertToken interface.QueryRow 1
-db-no-context internal/console removeDemoHoldingMemberWrite (*sql.Tx).Exec 3
db-no-context internal/console removeDemoHoldingMemberWrite (*sql.Tx).Query 1
db-no-context internal/console removeDemoHoldingMemberWrite (*sql.Tx).QueryRow 4
-db-no-context internal/console removeMemberTx (*sql.Tx).Exec 3
db-no-context internal/console revokeAccountLinksTx (*sql.Tx).Exec 2
db-no-context internal/console revokeAllDoorKeys (*sql.Tx).Exec 1
db-no-context internal/console revokeClaimDoorKeys (*sql.Tx).Exec 2
@@ -2186,7 +2183,7 @@ func-lines internal/console (*Store).migrate - 335
func-lines internal/console TestDemoProtectionsSourceToLimitAndTakedown - 412
func-lines internal/console TestDemoSourceToLiveAndUpdate - 383
func-lines internal/console TestHAP2ProductionDoors - 304
-func-lines internal/edge (*Edge).ServeHTTP - 378
+func-lines internal/edge (*Edge).ServeHTTP - 369
func-lines internal/edge TestDemoAPIAliasBoundary - 360
func-lines internal/edge TestRegionalNameNeverLeavesItsRegion - 330
func-lines internal/edge TestTunnelWebSocketEndToEnd - 327
diff --git a/cmd/console/member.go b/cmd/console/member.go
index 6d29063a4..ffa007fa4 100644
--- a/cmd/console/member.go
+++ b/cmd/console/member.go
@@ -200,7 +200,7 @@ func memberRemove(st *console.Store, acct *console.Account, address string) {
fmt.Printf("%s is not a member of %s (%s) — nothing to do\n", address, acct.Sqid, acct.Name)
return
}
- if err := memberTransition(st, acct, console.RemoveMemberWrite(acct.ID, address)); err != nil {
+ if err := memberTransition(st, acct, st.RemoveMemberWrite(acct.ID, address)); err != nil {
log.Fatal(err)
}
fmt.Printf("removed %s (%s) from %s (%s)\n", address, current, acct.Sqid, acct.Name)
diff --git a/cmd/console/member_demo_test.go b/cmd/console/member_demo_test.go
index 54abfc577..fc15f49c6 100644
--- a/cmd/console/member_demo_test.go
+++ b/cmd/console/member_demo_test.go
@@ -1,6 +1,7 @@
package main_test
import (
+ "database/sql"
"path/filepath"
"strings"
"testing"
@@ -14,7 +15,7 @@ func TestMemberDemoHoldingLastOwner(t *testing.T) {
bin := buildConsole(t)
for _, tc := range []struct {
name, enabled, domain, fleetOwner, target, address, want string
- extraMember, extraOwner, liveTokens bool
+ extraMember, extraOwner, liveTokens, ownToken bool
}{
{name: "prepare before admission", fleetOwner: "shop", want: "has no members"},
{name: "admission enabled", enabled: "1", fleetOwner: "shop", want: "has no members"},
@@ -29,6 +30,9 @@ func TestMemberDemoHoldingLastOwner(t *testing.T) {
{name: "live tokens", fleetOwner: "shop", liveTokens: true, want: "console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):"},
{name: "live tokens with member remaining", fleetOwner: "shop", extraMember: true, liveTokens: true, want: "console: cannot remove the last owner while CLI or service tokens remain unrevoked. revoke them first through the account's service pages (including expired tokens):"},
{name: "another owner can revoke", fleetOwner: "shop", extraOwner: true, liveTokens: true, want: "removed"},
+ // The removed member's own credentials end with the membership
+ // (security hunt H4-M1, review round 2), as on any other account.
+ {name: "removed owner's credentials end", fleetOwner: "shop", extraOwner: true, ownToken: true, want: "removed"},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
@@ -55,10 +59,25 @@ func TestMemberDemoHoldingLastOwner(t *testing.T) {
}
}
// Tokens minted by someone else must be reported too. No implicit revocation.
+ // A mint re-reads its minter's membership (security hunt H4-M1), so the
+ // minter is a member for the mint only.
+ if err := st.AddMember(42, "another@keymail.dev", console.RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
secret, err := st.NewAppToken(42, "example", "another@keymail.dev", "demo credential", now)
if err != nil {
t.Fatal(err)
}
+ // The membership row goes by hand: RemoveMember would revoke the
+ // token, and this case is about tokens that outlive their minter.
+ raw, err := sql.Open("sqlite", dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := raw.Exec(`DELETE FROM memberships WHERE account_id = 42 AND address = 'another@keymail.dev'`); err != nil {
+ t.Fatal(err)
+ }
+ raw.Close()
toks, err := st.CLITokens("another@keymail.dev")
if err != nil || len(toks) != 1 {
t.Fatalf("tokens: %v %v", toks, err)
@@ -68,6 +87,12 @@ func TestMemberDemoHoldingLastOwner(t *testing.T) {
t.Fatal(err)
}
}
+ var own string
+ if tc.ownToken {
+ if own, err = st.NewAppToken(42, "example", "owner@keymail.dev", "owner's credential", now); err != nil {
+ t.Fatal(err)
+ }
+ }
reg, err := registry.Open(regPath)
if err != nil {
t.Fatal(err)
@@ -122,6 +147,11 @@ func TestMemberDemoHoldingLastOwner(t *testing.T) {
if (tc.extraMember || tc.extraOwner || !success) && strings.Contains(out, "has no members") {
t.Fatalf("false empty report: %s", out)
}
+ if tc.ownToken {
+ if _, ok := st.CLIPrincipal(own, time.Now()); ok {
+ t.Fatal("the removed owner's instance token still resolves")
+ }
+ }
after, err := st.CLITokens("another@keymail.dev")
if err != nil || (tc.liveTokens && (len(after) != 1 || after[0].ID != toks[0].ID)) || (!tc.liveTokens && len(after) != 0) {
t.Fatalf("tokens changed: %v %v", after, err)
diff --git a/internal/console/apibackups_test.go b/internal/console/apibackups_test.go
index 2a8966fc1..81b4643d7 100644
--- a/internal/console/apibackups_test.go
+++ b/internal/console/apibackups_test.go
@@ -159,6 +159,7 @@ func backupsToken(t *testing.T, st *Store, accountID int64, name, app string, ro
default:
return serviceToken(t, st, accountID, name, app, role)
}
+ defer mintAsOwner(t, st, accountID, "paul@example.test")()
tok, err := st.NewServicePrincipalScoped(accountID, name, app, role, rungs, commands, "paul@example.test", time.Now())
if err != nil {
t.Fatalf("mint %s %q: %v", role, name, err)
diff --git a/internal/console/apicli.go b/internal/console/apicli.go
index f19c892c9..a920db07e 100644
--- a/internal/console/apicli.go
+++ b/internal/console/apicli.go
@@ -1725,6 +1725,13 @@ func (s *Server) handleAPITrashApp(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's delete is owner plus passkey (handleAppDelete); the CLI
+ // has no step-up yet, so this door holds the owner half (H4-M2), without
+ // a platform's per-customer delegation (review round 4, Paul's ruling:
+ // a step-up door refuses it).
+ if !s.apiStepUpOwnerOnly(w, r, acct, "delete an app") {
+ return
+ }
p, _ := principalFrom(r.Context())
if !s.allowWrite(p, time.Now()) {
jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again")
diff --git a/internal/console/apicli_test.go b/internal/console/apicli_test.go
index e3da6f3c4..1cc52e4c9 100644
--- a/internal/console/apicli_test.go
+++ b/internal/console/apicli_test.go
@@ -2118,9 +2118,10 @@ func TestAPIShipReshipToleratesADifferentLabel(t *testing.T) {
// ---- trash and restore ------------------------------------------------------
-// trashFixture is a console with titogo claimed in the ops account and a
-// MEMBER (not owner) token for it: trashing is a member action on purpose —
-// the 30-day window is what makes the reversible verb cheap.
+// trashFixture is a console with titogo claimed in the ops account, alice a
+// member, and an OWNER token for it: the CLI delete is owner-only, the
+// browser delete's owner half (security hunt H4-M2,
+// TestHunt_H4_M2_MemberCannotTrash).
func trashFixture(t *testing.T, code string) (*consoleFixture, string) {
t.Helper()
fx := newConsoleFixture(t)
@@ -2131,7 +2132,7 @@ func trashFixture(t *testing.T, code string) (*consoleFixture, string) {
if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil {
t.Fatal(err)
}
- return fx, cliToken(t, fx, "alice@keymail.dev", code)
+ return fx, cliToken(t, fx, "paul@keymail.dev", code)
}
// tombstone reads the trash marker straight from the fixture's own bucket —
@@ -2178,7 +2179,7 @@ func TestAPITrashAndRestoreApp(t *testing.T) {
if tomb == nil {
t.Fatal("no trash marker in the bucket after a 200 delete")
}
- if tomb.Actor != "alice@keymail.dev" {
+ if tomb.Actor != "paul@keymail.dev" {
t.Fatalf("marker actor = %q, want the token's own identity", tomb.Actor)
}
if has, err := fx.st.HasAppIn(OpsAccountID, "titogo"); err != nil || has {
diff --git a/internal/console/apidomainpaths_test.go b/internal/console/apidomainpaths_test.go
index 65ca4d4ec..d836e9049 100644
--- a/internal/console/apidomainpaths_test.go
+++ b/internal/console/apidomainpaths_test.go
@@ -76,7 +76,7 @@ func claimedHost(t *testing.T, fx *consoleFixture, member, host string) {
// TestAPIDomainPathsPublishes: the door writes the map onto the claim, and
// the answer names the normalized host it wrote to.
func TestAPIDomainPathsPublishes(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-publish")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-publish")
claimedHost(t, fx, member, "ti.to")
got := publishPaths(t, fx, member, "ti.to", map[string]string{"paulca": "go.tito.io"})
if got != (domainPathsResp{Host: "ti.to", Prefixes: 1, Changed: true}) {
@@ -98,7 +98,7 @@ func TestAPIDomainPathsPublishes(t *testing.T) {
// regenerates its whole map and publishes it, so an entry it no longer lists
// must be GONE. Merging would make a rollback impossible to express.
func TestAPIDomainPathsReplaces(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-replace")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-replace")
claimedHost(t, fx, member, "ti.to")
publishPaths(t, fx, member, "ti.to", map[string]string{"paulca": "go.tito.io"})
publishPaths(t, fx, member, "ti.to", map[string]string{"bigcorp": "go.tito.io"})
@@ -115,7 +115,7 @@ func TestAPIDomainPathsReplaces(t *testing.T) {
// state — every account back on the origin — and is how a whole migration is
// rolled back in one call.
func TestAPIDomainPathsEmptyBodyClears(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-clear")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-clear")
claimedHost(t, fx, member, "ti.to")
publishPaths(t, fx, member, "ti.to", map[string]string{"paulca": "go.tito.io"})
got := publishPaths(t, fx, member, "ti.to", map[string]string{})
@@ -132,7 +132,7 @@ func TestAPIDomainPathsEmptyBodyClears(t *testing.T) {
// field would otherwise clear every prefix on the hostname and answer 200.
// An empty map still means "clear it"; it just has to be said.
func TestAPIDomainPathsRequiresThePathsField(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-nofield")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-nofield")
claimedHost(t, fx, member, "ti.to")
publishPaths(t, fx, member, "ti.to", map[string]string{"paulca": "go.tito.io"})
@@ -155,7 +155,7 @@ func TestAPIDomainPathsRequiresThePathsField(t *testing.T) {
// account and app, so what refuses it is the claim's ownership check rather
// than the membership gate above it.
func TestAPIDomainPathsRejectsOtherAccount(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-other")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-other")
claimedHost(t, fx, member, "ti.to")
// The positive control, and it is not optional: an UNREGISTERED route
// answers the byte-identical 404 too, so without a publish that works
@@ -188,7 +188,7 @@ func TestAPIDomainPathsRejectsOtherAccount(t *testing.T) {
// silently truncated map would route a subset of accounts and still look
// successful, which is the worst failure this feature can have.
func TestAPIDomainPathsRejectsOversize(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-oversize")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-oversize")
claimedHost(t, fx, member, "ti.to")
publishPaths(t, fx, member, "ti.to", map[string]string{"paulca": "go.tito.io"})
@@ -211,7 +211,7 @@ func TestAPIDomainPathsRejectsOversize(t *testing.T) {
// never be stored. "/paulca" is the shape a caller reaches for first, so it
// is the one worth pinning.
func TestAPIDomainPathsRejectsBadPrefix(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-badprefix")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-badprefix")
claimedHost(t, fx, member, "ti.to")
code, _, out := rawReq(t, http.MethodPut, pathsURL(fx, "bab", "titogo", "ti.to"), member,
pathsBody(t, map[string]string{"/paulca": "go.tito.io"}))
@@ -236,7 +236,7 @@ func TestAPIDomainPathsRejectsBadPrefix(t *testing.T) {
// drops it into the wrong branch, and dropping the %w wrap in claims.go is
// enough to move every case in this test from 422 to 502.
func TestAPIDomainPathsRejectsBadTarget(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-badtarget")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-badtarget")
claimedHost(t, fx, member, "ti.to")
for _, target := range []string{"notahostname", "GO.tito.io", "go.tito.io.", "go tito io"} {
code, _, out := rawReq(t, http.MethodPut, pathsURL(fx, "bab", "titogo", "ti.to"), member,
@@ -270,7 +270,7 @@ func TestAPIDomainPathsRejectsBadTarget(t *testing.T) {
// regardless: this door reports what was published, and makes no judgement
// about what a box did with it.
func TestAPIDomainGetAnswersThePublishedMap(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-get-paths")
+ fx, member := domainOwnerFixture(t, "code-dom-get-paths")
claimedHost(t, fx, member, "ti.to")
// Before anything is published: an object, never null, so a client can
@@ -329,7 +329,7 @@ func getPaths(t *testing.T, fx *consoleFixture, token, host string) map[string]s
// Operate is the negative control: widening the door must widen it to a
// named pair, not to every service role.
func TestAPIDomainPathsReachesPublishAndInstance(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-paths-roles")
+ fx, member := domainOwnerFixture(t, "code-dom-paths-roles")
claimedHost(t, fx, member, "ti.to")
body := pathsBody(t, map[string]string{"paulca": "go.tito.io"})
diff --git a/internal/console/apidomains.go b/internal/console/apidomains.go
index f34fb5336..a6344a6bd 100644
--- a/internal/console/apidomains.go
+++ b/internal/console/apidomains.go
@@ -305,6 +305,11 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's attach is owner-only (appdomains.go); so is this
+ // door (H4-M7). A member-minted instance token is held to its minter.
+ if !s.apiOwnerOnly(w, r, acct, "attach a domain") {
+ return
+ }
if s.refuseTemporary(w, acct, app, "attach a domain to it") {
return
}
@@ -619,6 +624,9 @@ func (s *Server) handleAPIDomainAttach(w http.ResponseWriter, r *http.Request) {
// The claim the namespace decision admitted has gone or changed.
jsonError(w, pe.ref.Status, pe.ref.Msg)
return
+ } else if de := (*claimDoorError)(nil); errors.As(err, &de) {
+ jsonError(w, de.ref.Status, de.ref.Msg)
+ return
} else if errors.Is(err, domains.ErrHostUnavailable) {
// Exactly these bytes, whoever holds it: naming the holder — or even
// distinguishing "held by another app of yours" from "held by a
@@ -802,6 +810,15 @@ func (s *Server) setDomainCapabilities(w http.ResponseWriter, r *http.Request, c
return false
}
}
+ // First claim wins (security hunt H5-M1): a catch-all does not take a
+ // name another account already holds one label below. After the
+ // regional scan, whose own answer names its case.
+ if wildcard && catchall && !(cur.Wildcard && cur.Catchall) {
+ if ref := s.foreignChildRefusal(ctx, host, acct.Sqid); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return false
+ }
+ }
// enabling is the false->true TRANSITION only — re-sending wildcard:true
// for a claim that already has it must not re-run the gate. Two reasons:
// the CNAME lookup is a live, sequential, request-path DNS round trip
@@ -1138,6 +1155,11 @@ func (s *Server) handleAPIDomainDetach(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's detach is owner-only (appdomains.go); so is this
+ // door (H4-M7). A member-minted instance token is held to its minter.
+ if !s.apiOwnerOnly(w, r, acct, "detach a domain") {
+ return
+ }
// The NINTH control-plane door, and the same fuse as the instance
// delete: the first-route branch below calls the very
// provision.DeleteRecord that retires a route, on the same app, and this
diff --git a/internal/console/apidomains_firstroute_test.go b/internal/console/apidomains_firstroute_test.go
index 61b5ef7fe..e7482535e 100644
--- a/internal/console/apidomains_firstroute_test.go
+++ b/internal/console/apidomains_firstroute_test.go
@@ -19,7 +19,7 @@ import (
// to the host itself.
func firstRouteFixture(t *testing.T, code string) (*consoleFixture, string) {
t.Helper()
- fx, member := instanceFixture(t, code)
+ fx, member := domainOwnerFixture(t, code) // attach is owner-only (H4-M7)
ctx := context.Background()
if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{
Host: "woodstar.app", Account: "bab", App: "titogo", CreatedAt: time.Now().UTC().Format(time.RFC3339),
@@ -81,7 +81,7 @@ func TestAttachKeepsAFirstRouteClaimFirstRoute(t *testing.T) {
// Another holder's claim does not take the branch: the ordinary path answers
// with its neutral refusal, exactly as before.
func TestAttachFirstRouteBranchIsOwnClaimsOnly(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-fr-other")
+ fx, member := domainOwnerFixture(t, "code-dom-fr-other")
if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{
Host: "woodstar.app", Account: "cdef", App: "widgets", CreatedAt: time.Now().UTC().Format(time.RFC3339),
}); err != nil {
diff --git a/internal/console/apidomains_test.go b/internal/console/apidomains_test.go
index 00296732e..abdc94b73 100644
--- a/internal/console/apidomains_test.go
+++ b/internal/console/apidomains_test.go
@@ -39,6 +39,24 @@ func domainsURL(fx *consoleFixture, acct, app string) string {
return fx.ts.URL + "/api/cli/apps/" + acct + "/" + app + "/domains"
}
+// domainOwnerFixture is instanceFixture with alice an OWNER of the account:
+// the CLI domain attach and detach doors are owner-only, as the browser's
+// are (security hunt H4-M7, TestHunt_H4_M7_MemberCannotDetachDomain).
+func domainOwnerFixture(t *testing.T, code string) (*consoleFixture, string) {
+ t.Helper()
+ fx, token := instanceFixture(t, code)
+ makeOwner(t, fx, "alice@keymail.dev")
+ return fx, token
+}
+
+// makeOwner gives address the owner role in the ops account.
+func makeOwner(t *testing.T, fx *consoleFixture, address string) {
+ t.Helper()
+ if err := fx.st.AddMember(OpsAccountID, address, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
// attachBody is the door's request shape. route is always sent (empty means
// "default it"), because an omitted field and an empty one must behave the
// same and the tests exercise the empty one.
@@ -111,7 +129,7 @@ func claimAbsent(t *testing.T, fx *consoleFixture, host string) {
// named route — 200, created true, and a claim object in the bucket carrying
// the member as its author.
func TestAPIDomainAttachCreates(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-create")
+ fx, member := domainOwnerFixture(t, "code-dom-create")
got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io")
if got != (domainAttachResp{Host: "tickets.example.com", Route: "go.tito.io", Created: true}) {
t.Fatalf("attach answer = %+v, want the host/route echoed with created true", got)
@@ -134,7 +152,7 @@ func TestAPIDomainAttachCreates(t *testing.T) {
}
func TestAPIDomainAttachRecordsDescriptionAndCanonicalRoute(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-message")
+ fx, member := domainOwnerFixture(t, "code-dom-message")
body := `{"host":"tickets.example.com","route":"go.tito.io","message":"attach the ticket checkout"}`
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body)
if code != http.StatusOK {
@@ -152,7 +170,7 @@ func TestAPIDomainAttachRecordsDescriptionAndCanonicalRoute(t *testing.T) {
}
func TestAPIDomainAttachRejectsInvalidDescriptionBeforeWriting(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-message-invalid")
+ fx, member := domainOwnerFixture(t, "code-dom-message-invalid")
body := `{"host":"tickets.example.com","route":"go.tito.io","message":"first\nsecond"}`
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, body)
if code != http.StatusBadRequest {
@@ -169,7 +187,7 @@ func TestAPIDomainAttachRejectsInvalidDescriptionBeforeWriting(t *testing.T) {
// family's byte-identical 404 (apiInstancePrincipal's contract), never a
// hint that the path exists.
func TestAPIDomainAttachAppToken(t *testing.T) {
- fx, _ := instanceFixture(t, "code-dom-apptoken")
+ fx, _ := domainOwnerFixture(t, "code-dom-apptoken")
now := time.Now()
if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil {
t.Fatal(err)
@@ -208,7 +226,7 @@ func TestAPIDomainAttachAppToken(t *testing.T) {
// a second identical attach is 200 with created false, and an attach naming a
// different route converges the claim in place rather than refusing it.
func TestAPIDomainAttachIdempotent(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-idem")
+ fx, member := domainOwnerFixture(t, "code-dom-idem")
if got := attachDomain(t, fx, member, "tickets.example.com", "go.tito.io"); !got.Created {
t.Fatalf("first attach = %+v, want created true", got)
}
@@ -227,7 +245,7 @@ func TestAPIDomainAttachIdempotent(t *testing.T) {
// 409 whose body says exactly one thing — never who holds it, never whether
// the holder is in this deployment at all.
func TestAPIDomainAttachConflictNeutral(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-conflict")
+ fx, member := domainOwnerFixture(t, "code-dom-conflict")
if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{
Host: "tickets.example.com", Account: "cdef", App: "widgets",
Route: "widgets.example.net", CreatedAt: time.Now().UTC().Format(time.RFC3339),
@@ -256,7 +274,7 @@ func TestAPIDomainAttachConflictNeutral(t *testing.T) {
// (CONSOLE_REDIRECT_HOSTS, which this console still answers on and 301s
// away, such as an old console.example.org).
func TestAPIDomainAttachValidation(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-validate")
+ fx, member := domainOwnerFixture(t, "code-dom-validate")
fx.srv.cfg.DenyDomains = []string{"", "denied.test"}
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.RedirectHosts = []string{"", "Carlos.Tito.Test:8443"}
@@ -298,7 +316,7 @@ func TestAPIDomainAttachValidation(t *testing.T) {
// are still refused. The apps domain, and names under the console's
// hostnames, are not.
func TestAPIDomainAttachUnreservedDefault(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-unreserved")
+ fx, member := domainOwnerFixture(t, "code-dom-unreserved")
origin, err := url.Parse(fx.srv.cfg.Origin)
if err != nil {
t.Fatal(err)
@@ -334,7 +352,7 @@ func TestAPIDomainAttachUnreservedDefault(t *testing.T) {
// exactly one thing it could mean. Two instance records make it ambiguous,
// and ambiguity names the flag that resolves it rather than guessing.
func TestAPIDomainAttachRouteDefault(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-route")
+ fx, member := domainOwnerFixture(t, "code-dom-route")
ctx := context.Background()
rec := provision.Record{Schema: 1, Host: "one.go.tito.io", Slug: "one", App: "titogo",
Account: "bab", Channel: "stable", CreatedAt: time.Now().UTC()}
@@ -367,7 +385,7 @@ func TestAPIDomainAttachRouteDefault(t *testing.T) {
// holds — so a caller cannot use detach to discover who owns a hostname.
// Only the first of the three actually removes anything.
func TestAPIDomainDetachQuiet(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-detach")
+ fx, member := domainOwnerFixture(t, "code-dom-detach")
attachDomain(t, fx, member, "tickets.example.com", "go.tito.io")
if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{
Host: "theirs.example.com", Account: "cdef", App: "widgets",
@@ -419,7 +437,7 @@ func TestAPIDomainDetachQuiet(t *testing.T) {
// reads "live"; one no live box reports reads "pending", including one only a
// STALE box still remembers.
func TestAPIDomainList(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-list")
+ fx, member := domainOwnerFixture(t, "code-dom-list")
ctx := context.Background()
now := time.Now()
if _, err := fx.st.CreateAppIn(OpsAccountID, "other", "alice@keymail.dev", now); err != nil {
@@ -499,7 +517,7 @@ func TestAPIDomainList(t *testing.T) {
// our outage. "elsewhere" (a real, wrong answer) still earns guidance, so
// the suppression is specific to "unresolved" and not a blanket regression.
func TestAPIDomainListSuppressesGuidanceForUnresolvedDNS(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-unresolved")
+ fx, member := domainOwnerFixture(t, "code-dom-unresolved")
ctx := context.Background()
now := time.Now()
attachDomain(t, fx, member, "broken.example.com", "go.tito.io")
@@ -566,7 +584,7 @@ func domainEvents(t *testing.T, fx *consoleFixture) int {
// the STEADY STATE — a bump per pass would keep the whole fleet converging
// onto nothing, and an audit row per pass would bury the tenant's log.
func TestAPIDomainSerialBump(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-serial")
+ fx, member := domainOwnerFixture(t, "code-dom-serial")
if got := serial(t, fx); got != 0 {
t.Fatalf("serial before any domain write = %d, want 0", got)
}
@@ -645,7 +663,7 @@ func attachBodyKind(host, route, kind, channel string) string {
// two different instructions), and any kind but "static" (nothing else can
// be minted from a domain attach). Neither writes a claim.
func TestAPIDomainAttachKindValidation(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-kind-400")
+ fx, member := domainOwnerFixture(t, "code-dom-kind-400")
for name, body := range map[string]string{
"route and kind together": attachBodyKind("both.example.com", "go.tito.io", "static", ""),
"kind other than static": attachBodyKind("both.example.com", "", "binary", ""),
@@ -664,7 +682,7 @@ func TestAPIDomainAttachKindValidation(t *testing.T) {
// and the answer's route is the host itself, the primary the record just
// declared. This is `carlos deploy -kind static -host <h>`'s server half.
func TestAPIDomainAttachKindStaticFirstRoute(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-kind-first")
+ fx, member := domainOwnerFixture(t, "code-dom-kind-first")
// The fixture registry holds no titogo routes, so the core has nothing
// to alias; the first-route branch needs something shipped to resolve
// the record's channel from.
@@ -711,7 +729,7 @@ func TestAPIDomainAttachKindStaticFirstRoute(t *testing.T) {
// stores the ready route, the answer reports it, and no provision record
// appears at the host's key.
func TestAPIDomainAttachKindStaticWithReadyRouteAliases(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-kind-alias")
+ fx, member := domainOwnerFixture(t, "code-dom-kind-alias")
fx.srv.cfg.Registry = attachRegistry(t,
registry.Route{Host: "titogo.bab.oncarlos.test", Kind: "static", App: "titogo",
Account: "bab", Channel: "canary/live", Status: "ready"},
@@ -752,7 +770,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
wantCNAME := "_acme-challenge." + host + "." + zone + "."
t.Run("missing CNAME refuses with the record to create", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-missing")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-missing")
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") }
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member,
@@ -779,7 +797,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
})
t.Run("correct CNAME enables wildcard and bumps the serial", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-ok")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-ok")
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
if name == "_acme-challenge."+host {
@@ -806,7 +824,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
// zone's. A customer who typed their CNAME target in mixed case must
// still delegate, not read as a permanently broken/missing record.
t.Run("mixed-case CNAME target still delegates", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-mixedcase")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-mixedcase")
fx.srv.delegationZone = zone
mixedCase := "_ACME-Challenge." + host + "." + strings.ToUpper(zone) + "."
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
@@ -832,7 +850,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
// this would 422 instead of succeeding, and the counter would be
// nonzero.
t.Run("re-sending wildcard true on an already-wildcard claim skips the lookup", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-idempotent")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-idempotent")
fx.srv.delegationZone = zone
calls := 0
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
@@ -873,7 +891,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
// os.ErrNotExist and returns ErrHostUnavailable — which must answer the
// SAME byte-identical 404 every other non-owner refusal does.
t.Run("claim vanishing between attach and capability write answers the byte-identical 404", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-vanish")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-vanish")
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
if _, err := domains.DetachClaim(context.Background(), fx.rel, host, "bab", "titogo"); err != nil {
@@ -889,7 +907,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
})
t.Run("catchall without wildcard refuses and stores nothing", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-catchall")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-catchall")
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(context.Context, string) (string, error) { return "", errors.New("not found") }
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member,
@@ -906,7 +924,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
})
t.Run("wildcard and catchall together with a correct CNAME store both", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-both")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-both")
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
if name == "_acme-challenge."+host {
@@ -952,7 +970,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
// only writer of Wildcard/Catchall is SetClaimCapabilities, called AFTER
// the create, and gated on the zone.
t.Run("zone unset refuses, and smuggled capability fields never reach the claim", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-wc-nozone")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-nozone")
// fx.srv.delegationZone is left at its zero value "" — no
// CARLOS_ACME_DELEGATION_ZONE configured for this fixture.
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member,
@@ -978,7 +996,7 @@ func TestAttachWildcardCNAMEGate(t *testing.T) {
func TestAttachWildcardDisableCascadesCatchallOff(t *testing.T) {
const zone = "acme.oncarlos.com"
const host = "wild.example.com"
- fx, member := instanceFixture(t, "code-dom-wc-disable")
+ fx, member := domainOwnerFixture(t, "code-dom-wc-disable")
fx.srv.delegationZone = zone
wantCNAME := "_acme-challenge." + host + "." + zone + "."
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
@@ -1012,7 +1030,7 @@ func TestAttachWildcardDisableCascadesCatchallOff(t *testing.T) {
// field at all.
func TestDomainsListDelegationStamp(t *testing.T) {
const zone = "acme.oncarlos.com"
- fx, member := instanceFixture(t, "code-dom-list-deleg")
+ fx, member := domainOwnerFixture(t, "code-dom-list-deleg")
fx.srv.delegationZone = zone
const wildHost = "wild.example.com"
const plainHost = "plain.example.com"
@@ -1086,7 +1104,7 @@ func TestDomainsListDelegationStamp(t *testing.T) {
// unset zone or wildcard off — never an error.
func TestDomainsListDelegationStampCapsLookups(t *testing.T) {
const zone = "acme.oncarlos.com"
- fx, member := instanceFixture(t, "code-dom-list-cap")
+ fx, member := domainOwnerFixture(t, "code-dom-list-cap")
fx.srv.delegationZone = zone
var calls int
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
@@ -1212,6 +1230,7 @@ func zoneFixtureWithDelegation(t *testing.T, zone, code string) (*consoleFixture
// call built from an invalid zone.
func TestDelegationZoneInvalidAtConstruction(t *testing.T) {
fx, member := zoneFixtureWithDelegation(t, "*.bad zone", "code-dom-wc-badzone")
+ makeOwner(t, fx, "alice@keymail.dev") // the attach door is owner-only (H4-M7)
fx.srv.lookupCNAME = func(context.Context, string) (string, error) {
t.Fatal("lookupCNAME must not be called when the configured zone is invalid")
return "", nil
@@ -1258,6 +1277,7 @@ func TestWildcardEnableIsNotRateLimited(t *testing.T) {
attempts, cliInstanceBurst, svcWriteBurst, domainsCeilingBurst)
}
fx, _ := instanceFixture(t, "code-wc-exempt")
+ ownerMintsServices(t, fx)
svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish)
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
@@ -1286,6 +1306,7 @@ func TestWildcardEnableIsNotRateLimited(t *testing.T) {
// it — the ceiling applies to the door, not to the wildcard flags.
func TestDomainsCeilingBoundsConvergenceRate(t *testing.T) {
fx, _ := instanceFixture(t, "code-wc-ceiling")
+ ownerMintsServices(t, fx)
svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish)
var saw429 bool
for i := 0; i < domainsCeilingBurst+5; i++ {
@@ -1314,6 +1335,7 @@ func TestDomainsCeilingBoundsConvergenceRate(t *testing.T) {
func TestFailedWildcardEnableIsBounded(t *testing.T) {
const zone = "acme.example"
fx, _ := instanceFixture(t, "code-wc-bounded")
+ ownerMintsServices(t, fx)
svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Publish)
fx.srv.delegationZone = zone
fx.srv.lookupCNAME = func(context.Context, string) (string, error) {
@@ -1344,6 +1366,7 @@ func TestFailedWildcardEnableIsBounded(t *testing.T) {
func TestIdempotentReattachTouchesNeitherBudget(t *testing.T) {
const zone = "acme.example"
fx, _ := instanceFixture(t, "code-wc-idempotent")
+ ownerMintsServices(t, fx)
svc := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Instance)
fx.srv.delegationZone = zone
const host = "one.pages.example"
@@ -1447,7 +1470,7 @@ func TestLegacyAppTokensHaveSeparateWildFailBudgets(t *testing.T) {
// one did) cannot see failure mode 2 at all.
func TestAPIDomainAttachRefusesADeploymentRouteNeutrally(t *testing.T) {
ctx := context.Background()
- fx, member := instanceFixture(t, "code-dom-deproute")
+ fx, member := domainOwnerFixture(t, "code-dom-deproute")
// go.tito.io is a real, NON-ALIAS route published by a live box called
// "annie". Both halves are required: DeploymentRoutes drops any edges
@@ -1571,7 +1594,7 @@ func TestAPIDomainAttachRefusesADeploymentRouteNeutrally(t *testing.T) {
// permanent 409 on hostnames this deployment itself granted.
func TestAPIDomainAttachStillConvergesTheCallersOwnDeploymentRoute(t *testing.T) {
ctx := context.Background()
- fx, member := instanceFixture(t, "code-dom-ownroute")
+ fx, member := domainOwnerFixture(t, "code-dom-ownroute")
if _, err := fx.rel.Put(ctx, edgesfile.Key("annie"),
[]byte(`{"v":1,"box":"annie","eip":"198.51.100.9","hosts":{"mine.example.com":{"role":"home"}}}`), ""); err != nil {
t.Fatal(err)
@@ -1668,7 +1691,7 @@ func domainGetURL(fx *consoleFixture, acct, app, host string) string {
// refreshes one host and compares it against a listed row must not see a
// mirrored status flap for reasons that have nothing to do with the domain.
func TestAPIDomainGetAgreesWithTheListRow(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-get")
+ fx, member := domainOwnerFixture(t, "code-dom-get")
ctx := context.Background()
now := time.Now()
attachDomain(t, fx, member, "live.example.com", "go.tito.io")
@@ -1786,7 +1809,7 @@ func TestAPIDomainGetRefusesATraversalHost(t *testing.T) {
// consumer refreshing a single host and comparing it against a listed row
// must never see them disagree.
func TestAPIDomainFailedStateComesFromTheWarmRecord(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-warm")
+ fx, member := domainOwnerFixture(t, "code-dom-warm")
ctx := context.Background()
now := time.Now()
attachDomain(t, fx, member, "broken.example.com", "go.tito.io")
@@ -1865,7 +1888,7 @@ func TestAPIDomainFailedStateComesFromTheWarmRecord(t *testing.T) {
// writes for every domain it warms), so the join has to be by exact host or
// one tenant's certificate trouble shows up on another tenant's domain.
func TestAPIDomainWarmRecordsJoinByExactHost(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-warm-iso")
+ fx, member := domainOwnerFixture(t, "code-dom-warm-iso")
ctx := context.Background()
now := time.Now()
attachDomain(t, fx, member, "mine.example.com", "go.tito.io")
diff --git a/internal/console/apidoorkeys.go b/internal/console/apidoorkeys.go
index 22d186bab..fcf003638 100644
--- a/internal/console/apidoorkeys.go
+++ b/internal/console/apidoorkeys.go
@@ -228,7 +228,11 @@ func (s *Server) handleAPIDoorKeyMint(w http.ResponseWriter, r *http.Request) {
return
}
entry.Label = cleanLabel(req.Label)
- if _, err := s.store.DoorKeyInsertContext(r.Context(), acct.ID, app, entry); err != nil {
+ if _, err := s.store.DoorKeyInsertContext(r.Context(), acct.ID, app, entry, addr); err != nil {
+ if errors.Is(err, errMinterNotMember) {
+ http.NotFound(w, r) // removed while the request was in flight: the family's 404
+ return
+ }
if errors.Is(err, errDoorKeysFull) {
jsonError(w, http.StatusConflict, fmt.Sprintf(
"this app already has %d door keys. revoke one before you mint another", doorkey.MaxKeys))
diff --git a/internal/console/apidoorkeys_test.go b/internal/console/apidoorkeys_test.go
index 0e224b2fd..b11f799c0 100644
--- a/internal/console/apidoorkeys_test.go
+++ b/internal/console/apidoorkeys_test.go
@@ -439,7 +439,7 @@ func TestDoorKeyResignPassCoversEveryApp(t *testing.T) {
// mintTestDoorKey stores one live door key for (account, app) directly.
func mintTestDoorKey(t *testing.T, s *Store, accountID int64, app, id string) {
t.Helper()
- if _, err := s.DoorKeyInsert(accountID, app, doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}); err != nil {
+ if _, err := s.DoorKeyInsert(accountID, app, doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}, ""); err != nil {
t.Fatalf("DoorKeyInsert(%d, %s): %v", accountID, app, err)
}
}
diff --git a/internal/console/apifeatures_test.go b/internal/console/apifeatures_test.go
index 0b60c91be..e06862e16 100644
--- a/internal/console/apifeatures_test.go
+++ b/internal/console/apifeatures_test.go
@@ -154,7 +154,7 @@ func TestAPIFeaturesBadShapesAre400AndWriteNothing(t *testing.T) {
// deployment block it already fetches with its CARLOS_INSTANCE_TOKEN, beside
// managed_domains — no new call, no new credential, no restart.
func TestAPIFeaturesRideTheDomainsDeploymentBlock(t *testing.T) {
- fx, member := instanceFixture(t, "code-feat-block")
+ fx, member := domainOwnerFixture(t, "code-feat-block")
app := serviceToken(t, fx.st, OpsAccountID, "router", "titogo", svcrole.Instance)
type block struct {
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go
index 45c6d3712..9466c8379 100644
--- a/internal/console/apiinstances.go
+++ b/internal/console/apiinstances.go
@@ -3113,6 +3113,13 @@ func (s *Server) handleAPIInstanceUpdate(w http.ResponseWriter, r *http.Request)
"nothing to update — send addrs, probe, steering, environment, gate, or a combination")
return
}
+ // Turning a password off is the owner's act (H4-M12): the browser asks
+ // an owner and a passkey, and the CLI has no step-up yet, so this door
+ // asks the owner. Setting one stays any member's. A platform's
+ // per-customer credential is no owner here (apiStepUpOwnerOnly).
+ if req.Gate != nil && *req.Gate == "" && !s.apiStepUpOwnerOnly(w, r, acct, "turn off an instance's password") {
+ return
+ }
// A team credential may not repoint a hostname's upstream (§4): addrs
// and steering are refused on shape, before anything is read.
tv, team := teamFrom(r.Context())
@@ -3588,6 +3595,10 @@ func (s *Server) handleAPIInstanceToken(w http.ResponseWriter, r *http.Request)
label = app + " instance token"
}
raw, err := s.store.NewAppTokenContext(r.Context(), acct.ID, app, addr, label, time.Now())
+ if errors.Is(err, errMinterNotMember) {
+ http.NotFound(w, r) // removed while the request was in flight: the family's 404
+ return
+ }
if err != nil {
log.Printf("console: api instance token %s/%s: %v", acct.Sqid, app, err)
jsonError(w, http.StatusInternalServerError, "could not mint the token — try again")
diff --git a/internal/console/apiinstances_test.go b/internal/console/apiinstances_test.go
index 7630a3f66..4e5973063 100644
--- a/internal/console/apiinstances_test.go
+++ b/internal/console/apiinstances_test.go
@@ -403,8 +403,9 @@ func TestAPIInstanceCreateInheritsFleetPlacement(t *testing.T) {
map[string]string{"name": "pi", "bucket": "pi-fleet-data"}, token); status != http.StatusOK {
t.Fatalf("create fleet = %d %v, want 200", status, body)
}
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-inst-placed-owner") // place is owner-only (H4-M4)
if status, body := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/titogo/place",
- map[string]string{"target": "fleet/pi"}, token); status != http.StatusOK {
+ map[string]string{"target": "fleet/pi"}, owner); status != http.StatusOK {
t.Fatalf("place = %d %v, want 200", status, body)
}
@@ -1536,8 +1537,10 @@ func TestAPIInstanceUpdateAuditNamesChangedFields(t *testing.T) {
}
// Combined case: steering, environment and gate together name all
- // three, in request-struct order.
- if status, _, out := rawReq(t, http.MethodPatch, pu, token,
+ // three, in request-struct order. An owner's token: turning a password
+ // off is the owner's (H4-M12).
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-audit-fields-owner")
+ if status, _, out := rawReq(t, http.MethodPatch, pu, owner,
`{"steering":"","environment":"","gate":""}`); status != http.StatusOK {
t.Fatalf("patch steering+environment+gate = %d %s, want 200", status, out)
}
@@ -2580,7 +2583,12 @@ func TestAPIInstanceUpdateGateRoundTrip(t *testing.T) {
}
}
- status, _, out = rawReq(t, http.MethodPatch, pu, token, `{"gate":""}`)
+ // Turning it off is the owner's (H4-M12); the member is refused.
+ if status, _, out := rawReq(t, http.MethodPatch, pu, token, `{"gate":""}`); status != http.StatusForbidden {
+ t.Fatalf("member patch clear = %d %s, want 403", status, out)
+ }
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-gate-roundtrip-owner")
+ status, _, out = rawReq(t, http.MethodPatch, pu, owner, `{"gate":""}`)
if status != http.StatusOK {
t.Fatalf("patch clear = %d %s", status, out)
}
diff --git a/internal/console/apipipeline.go b/internal/console/apipipeline.go
index e22d172c1..8daae31a2 100644
--- a/internal/console/apipipeline.go
+++ b/internal/console/apipipeline.go
@@ -106,6 +106,14 @@ func (s *Server) handleAPIPipelinePut(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's save asks a passkey of every member
+ // (handlePipelineSettingsSave). The CLI has no step-up yet, so this
+ // door holds the owner instead: a pipeline written here can take a
+ // legacy app's stable rung out from under the owner-plus-passkey
+ // promote gate (H4-M10).
+ if !s.apiOwnerOnly(w, r, acct, "change an app's pipeline") {
+ return
+ }
principal, _ := principalFrom(r.Context())
if !s.allowWrite(principal, time.Now()) {
jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again")
diff --git a/internal/console/apipipeline_test.go b/internal/console/apipipeline_test.go
index 36bd5c30a..62e4a11b3 100644
--- a/internal/console/apipipeline_test.go
+++ b/internal/console/apipipeline_test.go
@@ -380,6 +380,7 @@ func TestAPIPipelinePutStoreFailureStatuses(t *testing.T) {
// breaks a test instead of silently locking every service out.
func TestAPIPipelinePutNoServiceRoleReachesIt(t *testing.T) {
fx := newConsoleFixture(t)
+ ownerMintsServices(t, fx)
if _, err := fx.st.CreateAppIn(OpsAccountID, "widget", "paul@keymail.dev", time.Now()); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/apiplacements.go b/internal/console/apiplacements.go
index 0c269395d..a1d7d9c90 100644
--- a/internal/console/apiplacements.go
+++ b/internal/console/apiplacements.go
@@ -639,6 +639,15 @@ func (s *Server) handleAPIDomainPlacementsPut(w http.ResponseWriter, r *http.Req
return
}
}
+ // First claim wins (security hunt H5-M1, review round 2): a claim
+ // created with wildcard and catch-all meets the capability door's
+ // foreign-child refusal. After the regional scan, as there.
+ if create && wantWildcard && wantCatchall {
+ if ref := s.foreignChildRefusal(ctx, host, acct.Sqid); ref != nil {
+ jsonError(w, ref.Status, ref.Msg)
+ return
+ }
+ }
// Step 7.
if ref := regionalReadyRefusal(boxes, now); ref != nil {
diff --git a/internal/console/apiplacements_put_test.go b/internal/console/apiplacements_put_test.go
index 2a96f2329..30fb26348 100644
--- a/internal/console/apiplacements_put_test.go
+++ b/internal/console/apiplacements_put_test.go
@@ -1067,3 +1067,30 @@ func TestPlacementsPutPlanCapComesFirst(t *testing.T) {
w.mustPut(t, rdHost, rdSet("uk="+rdUK))
w.requireNoClaim(t, "free.example.com", "a capped create")
}
+
+// TestPlacementsPutCatchallOverForeignChild (review round 2, Fable N3):
+// the placements PUT that creates a claim with wildcard and catch-all
+// meets the capability door's foreign-child refusal, and writes nothing.
+func TestPlacementsPutCatchallOverForeignChild(t *testing.T) {
+ const zone = "acme.example.org"
+ w := newRegionalWorld(t, "code-rdput-foreign-child")
+ w.fx.srv.delegationZone = zone
+ w.fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
+ return name + "." + zone + ".", nil
+ }
+ noCatchallProof(w.fx)
+ const parent = "fox.example.com"
+ if _, _, err := domains.AttachClaim(context.Background(), w.fx.rel, domains.Claim{Host: "kid." + parent, Account: "zzz",
+ App: "blog", Route: "blog.example.net", CreatedAt: time.Now().UTC().Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ both := rdBoth()
+ both.Wildcard, both.Catchall = boolp(true), boolp(true)
+ code, out := w.put(t, parent, both)
+ if proof := w.fx.srv.domainChallenge(parent, w.fx.sqid); code != http.StatusConflict || !strings.Contains(out, proof.Name) {
+ t.Fatalf("PUT with catch-all over a foreign child = %d %s, want 409 naming %s", code, out, proof.Name)
+ }
+ w.requireNoClaim(t, parent, "a catch-all over a foreign child")
+ // Without the catch-all, the same PUT creates.
+ w.mustPut(t, parent, rdBoth())
+}
diff --git a/internal/console/apiplatformcustomers.go b/internal/console/apiplatformcustomers.go
index 8ba8e4338..15902f032 100644
--- a/internal/console/apiplatformcustomers.go
+++ b/internal/console/apiplatformcustomers.go
@@ -141,7 +141,8 @@ func (s *Server) platformGate(w http.ResponseWriter, r *http.Request, failRow st
//
// - apiPrincipalAccount: the platform credential's own account, or an
// account the person belongs to; anything else is the family's 404;
-// - a person who is not an owner is 403 door.not_owner;
+// - a person who is not an owner, or a platform credential whose minter
+// is not one now, is 403 door.not_owner;
// - no grant is 403 door.not_platform, and a grant whose generation is not
// live is 403 door.revoked. It authorizes on PlatformGenerationLive,
// never on the grant row's state alone: a deleted platform's grant row
@@ -176,6 +177,16 @@ func (s *Server) platformAuthorizeDoor(w http.ResponseWriter, r *http.Request, f
http.NotFound(w, r)
return platformCaller{}, false
}
+ // A platform credential is held to its minter's role now, as a
+ // person is above and as every owner gate holds a service
+ // credential (ownerAuthority): an owner who steps down to member
+ // takes the platform doors from what they minted (review round 3,
+ // Astra P2). The mint re-checks it in its insert transaction
+ // (platformMinterHolds).
+ if !s.ownerAuthority(p, acct) {
+ jsonError(w, http.StatusForbidden, platformCopy["door.not_owner"])
+ return platformCaller{}, false
+ }
gen = p.PlatformGeneration
default:
http.NotFound(w, r)
diff --git a/internal/console/apiplatformcustomers_test.go b/internal/console/apiplatformcustomers_test.go
index ce6bea5e4..feaad5f48 100644
--- a/internal/console/apiplatformcustomers_test.go
+++ b/internal/console/apiplatformcustomers_test.go
@@ -3,6 +3,7 @@ package console
import (
"bytes"
"context"
+ "database/sql"
"encoding/json"
"errors"
"fmt"
@@ -60,10 +61,27 @@ func grantPlatformAccount(t *testing.T, fx *consoleFixture, sqid string, max int
return got
}
-// platformToken mints the platform account's platform credential.
+// platformToken mints the platform account's platform credential, as one of
+// its current owners: a platform credential is held to its minter's
+// current role at the platform doors (review round 3), so a fixture minter
+// that is no member would leave it refused. An account with no owner falls
+// back to serviceToken's passing owner.
func platformToken(t *testing.T, fx *consoleFixture, platformID int64, name string) string {
t.Helper()
- return serviceToken(t, fx.st, platformID, name, "", svcrole.Platform)
+ var owner string
+ err := fx.st.db.QueryRow(`SELECT address FROM memberships WHERE account_id = ? AND role = ? ORDER BY address LIMIT 1`,
+ platformID, RoleOwner).Scan(&owner)
+ if errors.Is(err, sql.ErrNoRows) {
+ return serviceToken(t, fx.st, platformID, name, "", svcrole.Platform)
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, err := fx.st.NewServicePrincipal(platformID, name, "", svcrole.Platform, owner, time.Now())
+ if err != nil {
+ t.Fatalf("NewServicePrincipal(%q): %v", name, err)
+ }
+ return raw
}
// callJSON is one request with no *testing.T, so goroutines can make it.
diff --git a/internal/console/apirestart_test.go b/internal/console/apirestart_test.go
index b099d58ba..dfb581d27 100644
--- a/internal/console/apirestart_test.go
+++ b/internal/console/apirestart_test.go
@@ -155,7 +155,8 @@ func TestAPIRestartIsRateLimited(t *testing.T) {
// somebody's app was deleted.
func TestAPIRestartRefusesATrashedApp(t *testing.T) {
fx, token := restartFixture(t, "code-restart-trashed")
- if status, out := postBody(t, fx.ts.URL+"/api/cli/apps/bab/titogo/delete", token, ""); status != http.StatusOK {
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-restart-trashed-owner") // delete is owner-only (H4-M2)
+ if status, out := postBody(t, fx.ts.URL+"/api/cli/apps/bab/titogo/delete", owner, ""); status != http.StatusOK {
t.Fatalf("trash = %d %s", status, out)
}
if status, body := postBody(t, fx.ts.URL+"/api/cli/apps/bab/titogo/restart", token, ""); status != http.StatusNotFound {
diff --git a/internal/console/apiservices.go b/internal/console/apiservices.go
index 4cfe46d70..5f30d8190 100644
--- a/internal/console/apiservices.go
+++ b/internal/console/apiservices.go
@@ -136,6 +136,90 @@ func (s *Server) apiOwnerAccountFor(w http.ResponseWriter, r *http.Request, purp
return p, acct, true
}
+// apiOwnerOnly is the owner gate of the browser's owner-only app doors
+// (owner(), or accountApp plus role == RoleOwner) for a CLI door that has
+// already resolved acct through the family's 404 (apiAccountApp and kin).
+// It answers apiOwnerAccountFor's 403 in the same words: the caller has
+// proved membership, so the refusal hides nothing (security hunt H4).
+//
+// A person must hold the owner role. A service credential is held to its
+// minter's role NOW, whatever its kind: a legacy instance token, which any
+// member may mint, so that a member cannot reach an owner-only act by
+// minting one; and a named service credential, so that an owner who
+// transfers ownership away (and steps down to member) takes the owner-only
+// reach of what they minted with them (review round 1). The door's role
+// set still limits what the credential may call at all.
+func (s *Server) apiOwnerOnly(w http.ResponseWriter, r *http.Request, acct *Account, purpose string) bool {
+ p, _ := principalFrom(r.Context())
+ if s.ownerAuthority(p, acct) {
+ return true
+ }
+ jsonError(w, http.StatusForbidden, "only an account owner can "+purpose)
+ return false
+}
+
+// apiStepUpOwnerOnly is apiOwnerOnly for a door the browser holds behind
+// an owner and a passkey step-up that Paul's review-round-3 ruling keeps
+// from a platform's delegation (turning an instance's password off,
+// deleting an app, and a temporary app's TTL, which is a delete by another
+// door): the owner rule without the per-customer credential's standing
+// (stepUpOwnerAuthority). Same refusal as apiOwnerOnly.
+func (s *Server) apiStepUpOwnerOnly(w http.ResponseWriter, r *http.Request, acct *Account, purpose string) bool {
+ p, _ := principalFrom(r.Context())
+ if s.stepUpOwnerAuthority(p, acct) {
+ return true
+ }
+ jsonError(w, http.StatusForbidden, "only an account owner can "+purpose)
+ return false
+}
+
+// ownerAuthority is apiOwnerOnly's rule without the answer. A store error
+// is not ownership.
+//
+// A live per-customer Publish credential is an owner of its customer
+// account (review round 3, Paul's ruling): the platform runs that account
+// (platform accounts spec §6.2, §7), and an unclaimed customer has no
+// member to hold it to. Its link and grant were re-checked when it
+// resolved on this request (platformCustomerPrincipal). Everything else is
+// stepUpOwnerAuthority.
+func (s *Server) ownerAuthority(p Principal, acct *Account) bool {
+ if platformCustomerOwner(p, acct) {
+ return true
+ }
+ return s.stepUpOwnerAuthority(p, acct)
+}
+
+// platformCustomerOwner reports whether p is a per-customer credential
+// (kind platform) of role Publish bound to acct: a platform's credential,
+// on a customer account that is not the platform's own, and on no app.
+// The platform credential itself (role Platform, bound to the platform's
+// own account) is not one: it is held to its minter.
+func platformCustomerOwner(p Principal, acct *Account) bool {
+ return p.Kind == PrincipalService && p.Role == svcrole.Publish && p.App == "" &&
+ p.PlatformAccountID != 0 && p.Platform != "" && p.PlatformGeneration != 0 &&
+ p.AccountID == acct.ID && p.PlatformAccountID != acct.ID
+}
+
+// stepUpOwnerAuthority is the owner rule with no platform delegation: a
+// person must hold the owner role, and a service credential is held to its
+// minter's role now (apiOwnerOnly). A per-customer credential never passes
+// here, whoever minted it.
+func (s *Server) stepUpOwnerAuthority(p Principal, acct *Account) bool {
+ switch {
+ case p.Kind == PrincipalService && p.PlatformAccountID != 0 && p.PlatformAccountID != p.AccountID:
+ return false
+ case p.Kind == PrincipalUser:
+ return acct.Role == RoleOwner
+ case p.Kind == PrincipalService:
+ role, err := s.store.Role(acct.ID, p.Address)
+ if err != nil {
+ log.Printf("console: owner gate %s: minter role: %v", acct.Sqid, err)
+ }
+ return err == nil && role == RoleOwner
+ }
+ return false
+}
+
// doorsFor lists the /api/cli/ patterns a role reaches, sorted.
//
// It reads s.cliRoles — the SAME map the gate consults on every request — so
@@ -254,6 +338,16 @@ func (s *Server) handleAPIServiceCreate(w http.ResponseWriter, r *http.Request)
// refused by the grammar rather than quietly repaired (teamscope.go).
secret, err := s.store.NewServicePrincipalWithScopeContext(r.Context(), acct.ID, name, app, role, req.Rungs, req.Commands, req.Scope, actor, time.Now())
if err != nil {
+ // Removed, or stepped down, while the request was in flight: the
+ // family's 404 and the owner gate's 403, as a fresh request gets.
+ if errors.Is(err, errMinterNotMember) {
+ http.NotFound(w, r)
+ return
+ }
+ if errors.Is(err, errMinterNotOwner) {
+ jsonError(w, http.StatusForbidden, "only an account owner can manage service credentials")
+ return
+ }
// The sentinel, not a string match: a name collision is the
// caller's to fix and a busy database is not, and the two must not
// answer alike.
diff --git a/internal/console/apiservices_test.go b/internal/console/apiservices_test.go
index eadb5b618..9896ac361 100644
--- a/internal/console/apiservices_test.go
+++ b/internal/console/apiservices_test.go
@@ -835,7 +835,8 @@ func TestServiceCredentialCannotBeAccountScoped(t *testing.T) {
t.Fatalf("account-scoped Service credential = %v, want ErrAccountScopedService", err)
}
- // Bound to an app, it mints.
+ // Bound to an app, it mints (as an owner: H4-M1 review round 2).
+ defer mintAsOwner(t, fx.st, OpsAccountID, "op@keymail.dev")()
if _, err := fx.st.NewServicePrincipal(OpsAccountID, "svc-app", "kass", svcrole.Service, "op@keymail.dev", now); err != nil {
t.Fatalf("app-scoped Service credential: %v", err)
}
diff --git a/internal/console/apisidecars_test.go b/internal/console/apisidecars_test.go
index 5669ed431..2b0c964b2 100644
--- a/internal/console/apisidecars_test.go
+++ b/internal/console/apisidecars_test.go
@@ -917,8 +917,9 @@ func TestAPISidecarCreateInheritsFleetPlacement(t *testing.T) {
map[string]string{"name": "eleven", "bucket": "eleven-fleet-data"}, token); status != http.StatusOK {
t.Fatalf("create fleet = %d %v, want 200", status, body)
}
+ owner := cliToken(t, fx, "paul@keymail.dev", "code-side-placed-owner") // place is owner-only (H4-M4)
if status, body := postJSON(t, fx.ts.URL+"/api/cli/apps/bab/titogo/place",
- map[string]string{"target": "fleet/eleven"}, token); status != http.StatusOK {
+ map[string]string{"target": "fleet/eleven"}, owner); status != http.StatusOK {
t.Fatalf("place = %d %v, want 200", status, body)
}
diff --git a/internal/console/apitemporary.go b/internal/console/apitemporary.go
index 7bccb1544..3a0dcb608 100644
--- a/internal/console/apitemporary.go
+++ b/internal/console/apitemporary.go
@@ -357,6 +357,13 @@ func (s *Server) handleAPIAppTTL(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's Extend is owner-only (handleAppExtend), and a short TTL
+ // is a delete by another door now that delete is owner-only (review
+ // round 1), so it holds delete's rule: no platform per-customer
+ // delegation (round 4).
+ if !s.apiStepUpOwnerOnly(w, r, acct, "change when a temporary app expires") {
+ return
+ }
p, _ := principalFrom(r.Context())
if !s.allowWrite(p, time.Now()) {
jsonError(w, http.StatusTooManyRequests, "too many requests. Wait a minute and try again")
diff --git a/internal/console/apitemporary_test.go b/internal/console/apitemporary_test.go
index 6a1eb5f44..77de3b5b6 100644
--- a/internal/console/apitemporary_test.go
+++ b/internal/console/apitemporary_test.go
@@ -460,3 +460,23 @@ func TestKeepAndTTLRecheckAfterTheLock(t *testing.T) {
}
})
}
+
+// TestTTLIsOwnerOnly (review round 1): the browser's Extend is owner-only,
+// and a one-hour TTL is a delete by another door, so a member's
+// `carlos apps ttl` meets the owner gate's 403 and the expiry stays.
+func TestTTLIsOwnerOnly(t *testing.T) {
+ fx, _ := temporaryFixture(t)
+ exp := time.Now().Add(48 * time.Hour)
+ tempApp(t, fx, "tmp-a", exp)
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ member := cliToken(t, fx, "alice@keymail.dev", "code-ttl-member")
+ status, out := postJSON(t, appURL(fx, "tmp-a", "/ttl"), map[string]int64{"ttl_seconds": 3600}, member)
+ if status != http.StatusForbidden {
+ t.Fatalf("member ttl = %d %v, want 403", status, out)
+ }
+ if l := lifeOf(t, fx, "tmp-a"); l.ExpiresAt != exp.Unix() {
+ t.Fatalf("expiry after a refused ttl = %d, want %d", l.ExpiresAt, exp.Unix())
+ }
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 2214bc653..75db192e9 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1171,13 +1171,14 @@ func renameAdvice(err error, to string) string {
}
// handleAppGate is the Settings page's password-gate form: set a password
-// on one instance host, or turn it off. Member-gated, matching the API
-// PATCH's door — the CLI already lets a member do this, and a form that
-// refuses what the CLI allows is a rule in the wrong place. CSRF first,
-// then the same read-mutate-validate-write-audit sequence as the PATCH,
-// against one field. The password is never logged, audited or echoed.
+// on one instance host, or turn it off. Setting is any member's, matching
+// the API PATCH's door. Turning it off exposes the host to everyone, so it
+// is the owner's, with a passkey (security hunt H4-M12): a member meets the
+// owner gate's 404, and requireFreshAuth runs last, before the write. CSRF
+// first, then the same read-mutate-validate-write-audit sequence as the
+// PATCH, against one field. The password is never logged, audited or echoed.
func (s *Server) handleAppGate(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, _, app, ok := s.accountApp(w, r)
+ addr, raw, acct, role, app, ok := s.accountApp(w, r)
if !ok {
return
}
@@ -1202,6 +1203,10 @@ func (s *Server) handleAppGate(w http.ResponseWriter, r *http.Request) {
var hash string
switch r.FormValue("action") {
case "clear":
+ if role != RoleOwner {
+ http.NotFound(w, r)
+ return
+ }
case "set":
p := r.FormValue("password")
if err := gate.CheckPassword(p); err != nil {
@@ -1236,6 +1241,9 @@ func (s *Server) handleAppGate(w http.ResponseWriter, r *http.Request) {
back("err", err.Error()+".")
return
}
+ if hash == "" && !s.requireFreshAuth(w, r, addr, raw) {
+ return
+ }
if err := s.withRecordLock(rec.Account, rec.App, func() error { return provision.UpdateRecord(ctx, s.cfg.Releases, *rec, etag) }); err != nil {
if errors.Is(err, release.ErrCASConflict) {
back("err", "The instance changed while this request was in flight — try again.")
diff --git a/internal/console/appsettings_gate_test.go b/internal/console/appsettings_gate_test.go
index e62d138cb..00b43e0e3 100644
--- a/internal/console/appsettings_gate_test.go
+++ b/internal/console/appsettings_gate_test.go
@@ -56,8 +56,18 @@ func TestAppSettingsGateSetAndClear(t *testing.T) {
t.Fatalf("short password not refused on the page: %s", body)
}
+ // Turning it off is the owner's, with a passkey (security hunt H4-M12):
+ // the member meets the owner gate's 404, the owner steps up.
status, _, _ = postForm(t, c, fx.u("/apps/titogo/gate"),
url.Values{"csrf": {csrf}, "host": {"pw.go.tito.io"}, "action": {"clear"}})
+ if status != http.StatusNotFound {
+ t.Fatalf("member clear = %d, want 404", status)
+ }
+ fx.setUser("paul@keymail.dev")
+ owner := newBrowser(t)
+ signUp(t, fx, owner, "code-settings-gate-owner")
+ status, _, _ = postGated(t, fx, owner, fx.u("/apps/titogo/gate"),
+ url.Values{"csrf": {sessionToken(t, fx, owner)}, "host": {"pw.go.tito.io"}, "action": {"clear"}})
if status != http.StatusSeeOther {
t.Fatalf("clear = %d", status)
}
diff --git a/internal/console/authstore.go b/internal/console/authstore.go
index a38121aca..64939c680 100644
--- a/internal/console/authstore.go
+++ b/internal/console/authstore.go
@@ -782,15 +782,30 @@ func (s *Store) claimRawNewAppToken(accountID int64, app, mintedBy, label string
if err != nil {
return "", err
}
- if _, err := s.db.Exec(`INSERT INTO cli_tokens
+ // The minter's membership is re-read in the same statement as the
+ // insert (security hunt H4-M1): a mint whose request began before the
+ // minter's removal cannot land after it, because the removal's
+ // transaction and this statement are serialised by SQLite.
+ res, err := s.db.Exec(`INSERT INTO cli_tokens
(token_hash, address, label, remote_addr, created_at, expires_at, kind, account_id, app, credential_id)
-VALUES (?, ?, ?, '', ?, 0, ?, ?, ?, ?)`,
- hashToken(raw), mintedBy, label, now.Unix(), cliKindApp, accountID, app, credID); err != nil {
+SELECT ?, ?, ?, '', ?, 0, ?, ?, ?, ?
+WHERE EXISTS (SELECT 1 FROM memberships WHERE account_id = ? AND address = ?)`,
+ hashToken(raw), mintedBy, label, now.Unix(), cliKindApp, accountID, app, credID, accountID, mintedBy)
+ if err != nil {
+ return "", err
+ }
+ if n, err := res.RowsAffected(); err != nil {
return "", err
+ } else if n == 0 {
+ return "", errMinterNotMember
}
return raw, nil
}
+// errMinterNotMember is a credential mint refused because the minter is no
+// longer a member of the account by the time the row would be written.
+var errMinterNotMember = errors.New("console: the minter is not a member of the account")
+
// CLITokenAddress resolves a bearer token to the address that approved it; ok
// is false for unknown, revoked and expired tokens. This is the whole
// authorization decision for every CLI-facing endpoint.
diff --git a/internal/console/authstore_test.go b/internal/console/authstore_test.go
index 68b083351..b491087cc 100644
--- a/internal/console/authstore_test.go
+++ b/internal/console/authstore_test.go
@@ -243,6 +243,7 @@ func TestAppTokenContainment(t *testing.T) {
s := openTestStore(t)
now := time.Now()
+ mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now)
if err != nil {
t.Fatal(err)
@@ -307,6 +308,7 @@ VALUES (?, 'paul@keymail.dev', 'dated', '', ?, ?, 'app', 9, 'tito')`,
func TestAppTokenNeverExpires(t *testing.T) {
s := openTestStore(t)
now := time.Now()
+ mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now)
if err != nil {
t.Fatal(err)
@@ -336,6 +338,7 @@ func TestAppTokenNeverExpires(t *testing.T) {
func TestAppTokenRevocation(t *testing.T) {
s := openTestStore(t)
now := time.Now()
+ mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now)
if err != nil {
t.Fatal(err)
@@ -373,6 +376,7 @@ func TestCLITokenMigrationReopens(t *testing.T) {
t.Fatal(err)
}
user := mintUserToken(t, first, "paul@keymail.dev", now)
+ mustMember(t, first, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1)
app, err := first.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now)
if err != nil {
t.Fatal(err)
@@ -406,6 +410,7 @@ func TestCLITokensReportsKind(t *testing.T) {
s := openTestStore(t)
now := time.Now()
mintUserToken(t, s, "paul@keymail.dev", now)
+ mustMember(t, s, 7, "paul@keymail.dev") // a mint re-reads the minter's membership (H4-M1)
if _, err := s.NewAppToken(7, "tito", "paul@keymail.dev", "tito signup", now); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/catchallchild_test.go b/internal/console/catchallchild_test.go
new file mode 100644
index 000000000..53e3b971f
--- /dev/null
+++ b/internal/console/catchallchild_test.go
@@ -0,0 +1,227 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+// Security hunt H5-M1, review round 1: first claim wins between a parent's
+// catch-all and another account's child one label below it.
+func catchallChildWorld(t *testing.T, code, childAccount string) (*consoleFixture, string) {
+ t.Helper()
+ const zone = "acme.oncarlos.com"
+ fx, owner := domainOwnerFixture(t, code)
+ fx.srv.delegationZone = zone
+ fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
+ return name + "." + zone + ".", nil
+ }
+ ctx := context.Background()
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{Host: "victim.example", Account: "bab", App: "titogo",
+ Route: "go.tito.io", CreatedAt: time.Now().UTC().Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{Host: "shop.victim.example", Account: childAccount, App: "widgets",
+ Route: "w.attacker.example", CreatedAt: time.Now().UTC().Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ return fx, owner
+}
+
+// TestCatchallRefusedOverForeignChild: turning on wildcard and catch-all
+// over a parent is a 409 while another account holds a verified child, and
+// nothing changes. The refusal says why and names the way through (review
+// round 2, Fable N4): the parent's domain challenge. Once the owner's DNS
+// carries it, the catch-all turns on; the child keeps its exact claim.
+func TestCatchallRefusedOverForeignChild(t *testing.T) {
+ fx, owner := catchallChildWorld(t, "code-h5-child-foreign", "cdef")
+ noCatchallProof(fx)
+ body := `{"host":"victim.example","route":"go.tito.io","wildcard":true,"catchall":true}`
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), owner, body)
+ proof := fx.srv.domainChallenge("victim.example", "bab")
+ msg := cutoverErrorOf(out)
+ if code != http.StatusConflict || !strings.Contains(msg, proof.Name) || !strings.Contains(msg, proof.Value) {
+ t.Fatalf("catch-all over a foreign child = %d %s, want 409 naming TXT %s = %s", code, out, proof.Name, proof.Value)
+ }
+ if strings.Contains(msg, "shop.victim.example") || strings.Contains(msg, "cdef") {
+ t.Fatalf("the refusal %q names the child or its holder", msg)
+ }
+ if c := claimOf(t, fx, "victim.example"); c.Wildcard || c.Catchall {
+ t.Fatalf("parent after the refusal = %+v, want unchanged", *c)
+ }
+ fx.srv.lookupTXT = func(_ context.Context, name string) ([]string, error) {
+ if name == proof.Name {
+ return []string{proof.Value}, nil
+ }
+ return nil, errors.New("no such record")
+ }
+ if code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), owner, body); code != http.StatusOK {
+ t.Fatalf("catch-all with the parent's challenge published = %d %s, want 200", code, out)
+ }
+ if c := claimOf(t, fx, "victim.example"); !c.Wildcard || !c.Catchall {
+ t.Fatalf("parent = %+v, want wildcard and catch-all on", *c)
+ }
+ if c := claimOf(t, fx, "shop.victim.example"); c.Account != "cdef" || c.Pending {
+ t.Fatalf("child = %+v, want cdef's verified claim kept", *c)
+ }
+}
+
+// TestCatchallOverOwnChildAllowed: the same account's child is no bar.
+func TestCatchallOverOwnChildAllowed(t *testing.T) {
+ fx, owner := catchallChildWorld(t, "code-h5-child-own", "bab")
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), owner,
+ `{"host":"victim.example","route":"go.tito.io","wildcard":true,"catchall":true}`)
+ if code != http.StatusOK {
+ t.Fatalf("catch-all over the account's own child = %d %s, want 200", code, out)
+ }
+ if c := claimOf(t, fx, "victim.example"); !c.Wildcard || !c.Catchall {
+ t.Fatalf("parent = %+v, want wildcard and catch-all on", *c)
+ }
+}
+
+// TestChildPredatingCatchallReattaches: a child claim held before the
+// parent's catch-all keeps its name: its holder's re-attach passes the
+// attach door's catch-all check.
+func TestChildPredatingCatchallReattaches(t *testing.T) {
+ fx, _ := catchallChildWorld(t, "code-h5-child-old", "cdef")
+ if _, err := domains.SetClaimCapabilities(context.Background(), fx.rel, "victim.example", "bab", "titogo", true, true); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-h5-child-old-bob")
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "cdef", "widgets"), bob,
+ attachBody("shop.victim.example", "w.attacker.example"))
+ if code != http.StatusOK {
+ t.Fatalf("the earlier child's re-attach = %d %s, want 200", code, out)
+ }
+}
+
+// bobWidgets makes account cdef with app widgets and returns bob's token.
+func bobWidgets(t *testing.T, fx *consoleFixture, code string) string {
+ t.Helper()
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ return cliToken(t, fx, "bob@keymail.dev", code)
+}
+
+// TestPendingChildUnderForeignCatchallStaysPending (review round 2, Astra
+// finding 3): a child reservation that is only pending does not bar the
+// parent's catch-all, so it gets no holder's allowance under it either:
+// once the catch-all is on, publishing the child's proof and re-attaching
+// is the neutral 409, and the reservation stays pending.
+func TestPendingChildUnderForeignCatchallStaysPending(t *testing.T) {
+ const zone = "acme.oncarlos.com"
+ fx, owner := domainOwnerFixture(t, "code-h5-pending-child")
+ fx.srv.delegationZone = zone
+ fx.srv.lookupCNAME = func(_ context.Context, name string) (string, error) {
+ return name + "." + zone + ".", nil
+ }
+ noCatchallProof(fx)
+ fx.srv.cfg.DomainProof = true
+ ctx := context.Background()
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{Host: "victim.example", Account: "bab", App: "titogo",
+ Route: "go.tito.io", CreatedAt: time.Now().UTC().Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ bob := bobWidgets(t, fx, "code-h5-pending-child-bob")
+ child := attachBody("shop.victim.example", "w.attacker.example")
+ if code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "cdef", "widgets"), bob, child); code != http.StatusOK {
+ t.Fatalf("the child's reservation = %d %s", code, out)
+ }
+ if c := claimOf(t, fx, "shop.victim.example"); !c.Pending {
+ t.Fatalf("test bug: the child = %+v, want pending", *c)
+ }
+ if code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), owner,
+ `{"host":"victim.example","route":"go.tito.io","wildcard":true,"catchall":true}`); code != http.StatusOK {
+ t.Fatalf("catch-all over a pending child = %d %s, want 200", code, out)
+ }
+ proof := fx.srv.domainChallenge("shop.victim.example", "cdef")
+ fx.srv.lookupTXT = func(_ context.Context, name string) ([]string, error) {
+ if name == proof.Name {
+ return []string{proof.Value}, nil
+ }
+ return nil, errors.New("no such record")
+ }
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "cdef", "widgets"), bob, child)
+ if code != http.StatusConflict || cutoverErrorOf(out) != hostUnavailableMsg {
+ t.Fatalf("the pending child's proven re-attach = %d %s, want the neutral 409", code, out)
+ }
+ if c := claimOf(t, fx, "shop.victim.example"); !c.Pending {
+ t.Fatalf("the child under the foreign catch-all = %+v, want still pending", *c)
+ }
+}
+
+// TestChildWriteRechecksTheCatchallUnderTheMutex (review round 2, Astra
+// finding 2): the attach doors' catch-all check (heldElsewhere) runs
+// before regionalMu, so a parent's catch-all can come on between it and
+// the write. attachDomainClaim, the write both attach doors share, judges
+// the parent again under the mutex: a child that reaches it after another
+// account's catch-all came on writes nothing.
+func TestChildWriteRechecksTheCatchallUnderTheMutex(t *testing.T) {
+ fx, _ := catchallChildWorld(t, "code-h5-child-race", "bab")
+ ctx := context.Background()
+ if _, err := domains.SetClaimCapabilities(ctx, fx.rel, "victim.example", "bab", "titogo", true, true); err != nil {
+ t.Fatal(err)
+ }
+ bobWidgets(t, fx, "code-h5-child-race-bob")
+ acct, err := fx.st.AccountBySqid("cdef")
+ if err != nil || acct == nil {
+ t.Fatalf("account cdef: %+v %v", acct, err)
+ }
+ _, _, _, err = fx.srv.attachDomainClaim(ctx, acct, "widgets", domains.Claim{Host: "late.victim.example", Account: "cdef",
+ App: "widgets", Route: "w.attacker.example", CreatedAt: time.Now().UTC().Format(time.RFC3339)}, time.Now(), nil)
+ if !errors.Is(err, domains.ErrHostUnavailable) {
+ t.Fatalf("a child write under another account's live catch-all = %v, want ErrHostUnavailable", err)
+ }
+ claimAbsent(t, fx, "late.victim.example")
+}
+
+// TestVerifyingAPendingCatchallScansItsChildren (review round 2, Astra
+// finding 3): a pending parent may carry wildcard and catch-all, and the
+// re-attach that verifies it turns the catch-all on without the capability
+// door. That re-attach meets the same foreign-child refusal: here a pending
+// parent left from when domain proof was on, verified by a bare re-attach
+// once it is off, while another account holds a verified child.
+func TestVerifyingAPendingCatchallScansItsChildren(t *testing.T) {
+ fx, owner := domainOwnerFixture(t, "code-h5-pending-parent")
+ noCatchallProof(fx)
+ ctx := context.Background()
+ if _, _, _, err := domains.AttachClaimProven(ctx, fx.rel, domains.Claim{Host: "victim.example", Account: "bab", App: "titogo",
+ Route: "go.tito.io", CreatedAt: time.Now().UTC().Format(time.RFC3339)}, time.Now(), func() bool { return false }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := domains.SetClaimCapabilities(ctx, fx.rel, "victim.example", "bab", "titogo", true, true); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{Host: "shop.victim.example", Account: "cdef", App: "widgets",
+ Route: "w.attacker.example", CreatedAt: time.Now().UTC().Format(time.RFC3339)}); err != nil {
+ t.Fatal(err)
+ }
+ if c := claimOf(t, fx, "victim.example"); !c.Pending || !c.Wildcard || !c.Catchall {
+ t.Fatalf("test bug: parent = %+v, want pending with both capabilities", *c)
+ }
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), owner, attachBody("victim.example", "go.tito.io"))
+ proof := fx.srv.domainChallenge("victim.example", "bab")
+ if code != http.StatusConflict || !strings.Contains(cutoverErrorOf(out), proof.Name) {
+ t.Fatalf("verifying a pending catch-all over a foreign child = %d %s, want 409 naming %s", code, out, proof.Name)
+ }
+ if c := claimOf(t, fx, "victim.example"); !c.Pending {
+ t.Fatalf("parent after the refusal = %+v, want still pending", *c)
+ }
+}
diff --git a/internal/console/claim_alias.go b/internal/console/claim_alias.go
index 94ede5240..22beeae03 100644
--- a/internal/console/claim_alias.go
+++ b/internal/console/claim_alias.go
@@ -44,6 +44,11 @@ func (s *Server) attachDomainClaim(ctx context.Context, acct *Account, app strin
if !s.cfg.HostClaim {
s.regionalMu.Lock()
defer s.regionalMu.Unlock()
+ // The catch-all checks again, under the mutex the capability
+ // doors decide under (security hunt H5-M1, review round 2).
+ if err := s.attachCatchallRefusalLocked(ctx, acct.Sqid, app, incoming.Host); err != nil {
+ return false, false, false, err
+ }
return domains.AttachClaimProven(ctx, store, incoming, now, prove)
}
a := s.cfg.ClaimAuthority
diff --git a/internal/console/controlplane_test.go b/internal/console/controlplane_test.go
index d7ebc1b16..17bef1460 100644
--- a/internal/console/controlplane_test.go
+++ b/internal/console/controlplane_test.go
@@ -1230,6 +1230,7 @@ func TestControlPlaneDomainDetachRefusalIsNotAnOracle(t *testing.T) {
// deliberately not conditional on which branch would have run.
func TestControlPlaneAppRefusesAServiceDomainAttach(t *testing.T) {
fx := newConsoleFixture(t)
+ ownerMintsServices(t, fx)
if err := fx.st.SetAppControlPlane(OpsAccountID, "kass", true); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/deletion_evidence_test.go b/internal/console/deletion_evidence_test.go
index a92ab097a..ed6bf2fa3 100644
--- a/internal/console/deletion_evidence_test.go
+++ b/internal/console/deletion_evidence_test.go
@@ -169,7 +169,7 @@ func lifetimeDetachedApp(t *testing.T) ltOn {
l := newLtOn(t)
l.fx.srv.cfg.Releases = ltModStore{l.bucket}
ctx := context.Background()
- code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member,
+ code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.operator,
`{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`)
if code != http.StatusOK {
t.Fatalf("attach = %d %s", code, body)
@@ -191,7 +191,7 @@ func lifetimeDetachedApp(t *testing.T) ltOn {
if _, err := l.fx.srv.channelHosts(ctx, "bab", ltApp, "canary/x"); err != nil {
t.Fatalf("fixture: a still app = %v", err)
}
- if code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, ""); code != http.StatusOK {
+ if code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.operator, ""); code != http.StatusOK {
t.Fatalf("detach = %d %s", code, body)
}
if raw, _ := rawOf(t, l.fx.rel, ltApp, ltDomain); raw != nil {
diff --git a/internal/console/deletion_test.go b/internal/console/deletion_test.go
index eab2fb3aa..ba514ff12 100644
--- a/internal/console/deletion_test.go
+++ b/internal/console/deletion_test.go
@@ -421,7 +421,7 @@ func TestDeleteNowDestroysEverythingAndFreesTheName(t *testing.T) {
// 12-hourly re-sign.
func TestDeleteNowSweepsLedgersAndDoorKeys(t *testing.T) {
fx, c, csrf := trashPageFixture(t)
- if _, err := fx.st.DoorKeyInsert(OpsAccountID, "kass", doorkey.Entry{ID: "0123456789abcdef", SHA256: strings.Repeat("a", 64)}); err != nil {
+ if _, err := fx.st.DoorKeyInsert(OpsAccountID, "kass", doorkey.Entry{ID: "0123456789abcdef", SHA256: strings.Repeat("a", 64)}, ""); err != nil {
t.Fatal(err)
}
ledgerKey := release.LedgerAppPrefix(fx.sqid, "kass") + "ledgers.json"
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go
index 3b83cf960..115eb2437 100644
--- a/internal/console/demo_api_origin_test.go
+++ b/internal/console/demo_api_origin_test.go
@@ -324,7 +324,9 @@ func TestDemoAPIHostOwnership(t *testing.T) {
}
}
claimAbsent(t, fx, "example.com")
- for _, token := range []string{member, service} {
+ // The owner and an owner-minted app token: the attach door is
+ // owner-only (H4-M7), so the member meets its 403 here.
+ for _, token := range []string{owner, service} {
if code, _, _ := rawReq(t, "POST", base, token, attachBody("other.example.com", "shop.example.net")); code != 200 {
t.Errorf("unrelated host status=%d", code)
}
diff --git a/internal/console/demo_members.go b/internal/console/demo_members.go
index eb8f6ac8e..c6b7b1ddf 100644
--- a/internal/console/demo_members.go
+++ b/internal/console/demo_members.go
@@ -15,7 +15,10 @@ import (
// RemoveDemoHoldingMember is only for the box-side member tool. The registry
// is attached read-only so fleet ownership and membership are read in the same
// transaction. Use a dedicated Store: the attachment lasts for this call.
-// HTTP removal continues to use removeMemberTx and its last-owner guard.
+// HTTP removal continues to use removeMemberRevokingTx and its last-owner
+// guard. Like every removal, this one revokes what the member minted for
+// the account (revokeMemberCredentialsTx); the console's link sync loop
+// publishes the door-key records it queues.
func (s *Store) RemoveDemoHoldingMember(accountID int64, address string, cfg demo.Config, registryPath string, _ *plans.Catalog, _ time.Time) (err error) {
// Preparation works before admission is enabled, but needs the complete
// admission tuple. Validate a copy without changing the operator's switch.
@@ -40,13 +43,16 @@ func (s *Store) RemoveDemoHoldingMember(accountID int64, address string, cfg dem
err = fmt.Errorf("console: removal committed but registry detach failed: %w", detachErr)
}
}()
- err = s.MembershipTransition(removeDemoHoldingMemberWrite(accountID, address, cfg))
+ err = s.MembershipTransition(removeDemoHoldingMemberWrite(accountID, address, cfg, s.gate != nil))
return err
}
// Recheck both identities here; an earlier command-side lookup cannot grant
-// the exception. No token is revoked by this write.
-func removeDemoHoldingMemberWrite(accountID int64, address string, cfg demo.Config) func(*sql.Tx) error {
+// the exception. The last-owner refusal below still stands for anyone's
+// live tokens; past it, the removed member's own credentials are revoked
+// in this transaction, as every removal does (security hunt H4-M1, review
+// round 2). gated is the host claim's SQL gate being on (Store.gate).
+func removeDemoHoldingMemberWrite(accountID int64, address string, cfg demo.Config, gated bool) func(*sql.Tx) error {
return func(tx *sql.Tx) error {
cfg.Enabled = true
if err := cfg.Validate(); err != nil {
@@ -101,14 +107,10 @@ func removeDemoHoldingMemberWrite(accountID int64, address string, cfg demo.Conf
}
}
}
- if _, err := tx.Exec(`DELETE FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
+ if _, err := revokeMemberCredentialsTx(tx, accountID, address, time.Now(), gated); err != nil {
return err
}
- if _, err := tx.Exec(`DELETE FROM getting_started_marks WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
- return err
- }
- _, err = tx.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`, accountID, address)
- return err
+ return removeMembershipRowsTx(tx, accountID, address)
}
}
diff --git a/internal/console/deploycred_test.go b/internal/console/deploycred_test.go
index 1e0079c84..ae1524418 100644
--- a/internal/console/deploycred_test.go
+++ b/internal/console/deploycred_test.go
@@ -150,5 +150,8 @@ func newDeployStore(t *testing.T) *Store {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
+ // The tests here mint into account 1 as serviceMinter, and a service
+ // mint re-reads its minter's role (H4-M1 review round 2).
+ mustMintingOwner(t, st, 1, serviceMinter)
return st
}
diff --git a/internal/console/domainattach.go b/internal/console/domainattach.go
index 765d8f848..ec4ae85eb 100644
--- a/internal/console/domainattach.go
+++ b/internal/console/domainattach.go
@@ -847,6 +847,9 @@ func claimRefusal(host string, err error) *doorRefusal {
if pe := (*claimPinError)(nil); errors.As(err, &pe) {
return pe.ref
}
+ if de := (*claimDoorError)(nil); errors.As(err, &de) {
+ return de.ref
+ }
if msg, ok := claimAliasRefusal(err); ok {
return &doorRefusal{Status: http.StatusConflict, Msg: msg}
}
diff --git a/internal/console/domaincatchall.go b/internal/console/domaincatchall.go
index 06fbe230c..657a204a9 100644
--- a/internal/console/domaincatchall.go
+++ b/internal/console/domaincatchall.go
@@ -188,12 +188,14 @@ func (s *Server) detachInstanceCatchall(ctx context.Context, acct *Account, app,
}
// heldElsewhere is the attach doors' last check before a claim write: a
-// real route another app serves (deploymentRouteTaken), or a live instance's
-// name under another account's instance catch-all (catchallInstanceName).
-// Both answer with the same neutral 409, from the same place in each door,
-// so neither reads apart from an ordinary "someone holds it".
+// real route another app serves (deploymentRouteTaken), a live instance's
+// name under another account's instance catch-all (catchallInstanceName),
+// or any name under another account's ordinary catch-all
+// (underForeignCatchall). All answer with the same neutral 409, from the
+// same place in each door, so none reads apart from an ordinary "someone
+// holds it".
//
-// A bucket read the catch-all check could not make is answered as a
+// A bucket read a catch-all check could not make is answered as a
// retryable error rather than a guess: refusing would read as "someone
// holds it", and admitting would skip the guard.
func (s *Server) heldElsewhere(ctx context.Context, host, sqid, app string) *doorRefusal {
@@ -201,8 +203,11 @@ func (s *Server) heldElsewhere(ctx context.Context, host, sqid, app string) *doo
return claimRefusal(host, domains.ErrHostUnavailable)
}
held, err := s.catchallInstanceName(ctx, host, sqid, app)
+ if err == nil && !held {
+ held, err = s.underForeignCatchall(ctx, host, sqid, app)
+ }
if err != nil {
- log.Printf("console: attach %s: instance catch-all check: %v", host, err)
+ log.Printf("console: attach %s: catch-all check: %v", host, err)
return &doorRefusal{Status: http.StatusBadGateway, Msg: "could not check the hostname — try again"}
}
if held {
@@ -211,6 +216,140 @@ func (s *Server) heldElsewhere(ctx context.Context, host, sqid, app string) *doo
return nil
}
+// underForeignCatchall reports whether host is one label below a parent
+// whose verified claim, held by another account, has Wildcard and Catchall
+// on (security hunt H5-M1). That catch-all serves every such name, and an
+// exact claim from another account would beat its star at the edge and
+// carve the name out of the parent's domain. First claim wins: the
+// capability door refuses turning a catch-all on over another account's
+// existing child (foreignChildRefusal), so a child that predates the
+// catch-all keeps its name, and its holder's re-attach passes here, the
+// allowance catchallInstanceName makes. Only a verified child: a pending
+// one did not bar the catch-all (foreignChildRefusal skips it), so it may
+// not be proved and served under it either (review round 2). The parent's
+// own account may carve names out, as before.
+//
+// attachDomainClaim asks again under regionalMu, where the capability
+// doors decide, so a catch-all turned on after the door's first ask is
+// still seen before the write.
+//
+// One GET (usually a 404), and a second only under such a catch-all.
+func (s *Server) underForeignCatchall(ctx context.Context, host, sqid, app string) (bool, error) {
+ label, parent, ok := strings.Cut(host, ".")
+ if !ok || label == "" || label == "*" || !strings.Contains(parent, ".") {
+ return false, nil
+ }
+ c, err := domains.GetClaim(ctx, s.cfg.Releases, parent)
+ if errors.Is(err, os.ErrNotExist) {
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ if c.Pending || !c.Wildcard || !c.Catchall || c.Account == sqid {
+ return false, nil
+ }
+ if own, err := domains.GetClaim(ctx, s.cfg.Releases, host); err == nil && own.Account == sqid && own.App == app && !own.Pending {
+ return false, nil
+ } else if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return false, err
+ }
+ return true, nil
+}
+
+// attachCatchallRefusalLocked is attachDomainClaim's catch-all check,
+// under regionalMu (security hunt H5-M1, review round 2), so the capability
+// doors cannot turn a catch-all on between it and the write:
+//
+// - host is one label below another account's live catch-all
+// (underForeignCatchall): domains.ErrHostUnavailable, the neutral 409
+// heldElsewhere gives;
+// - host is the caller's own pending claim carrying wildcard and
+// catch-all: the re-attach that verifies it turns the catch-all on, so
+// it meets the capability door's foreignChildRefusal.
+//
+// A refusal with its own answer comes back as a *claimDoorError.
+func (s *Server) attachCatchallRefusalLocked(ctx context.Context, sqid, app, host string) error {
+ held, err := s.underForeignCatchall(ctx, host, sqid, app)
+ if err != nil {
+ return err
+ }
+ if held {
+ return domains.ErrHostUnavailable
+ }
+ cur, err := domains.GetClaim(ctx, s.cfg.Releases, host)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if cur.Account == sqid && cur.App == app && cur.Pending && cur.Wildcard && cur.Catchall {
+ if ref := s.foreignChildRefusal(ctx, host, sqid); ref != nil {
+ return &claimDoorError{ref}
+ }
+ }
+ return nil
+}
+
+// claimDoorError is a claim write refused with its own door answer: both
+// attach doors answer ref as it stands (claimRefusal, handleAPIDomainAttach).
+type claimDoorError struct{ ref *doorRefusal }
+
+func (e *claimDoorError) Error() string { return "console: claim refused: " + e.ref.Msg }
+
+// catchallOverForeignChildMsg is the refusal of a catch-all over another
+// account's child (review round 2, Fable N4, the controller's ruling: keep
+// the refusal, but bounded and with its reason). It names the reason and
+// the one way through, proving control of parent with its domain
+// challenge, and never the child or its holder.
+func catchallOverForeignChildMsg(parent string, proof dnsRecord) string {
+ return "another account already holds a name directly under " + parent + ", so a catch-all on " + parent +
+ " is refused. To turn it on, show that " + parent + " is yours: publish TXT " + proof.Name + " = \"" + proof.Value +
+ "\" and try again. The other account's name keeps working."
+}
+
+// foreignChildRefusal is the capability doors' half of first-claim-wins
+// (security hunt H5-M1): turning on Wildcard and Catchall together over
+// parent is refused while ANOTHER account holds a verified claim one label
+// below it, or the listing shows such a name it could not read. The
+// enabling CNAME check names no account and is made once, so it is no
+// reason for the parent to take a name someone else already serves. A
+// listing error is a retry.
+//
+// The refusal is bounded (review round 2, the controller's ruling on Fable
+// N4): an account whose parent's DNS carries its domain challenge right
+// now (domainChallengeHeld) has shown the domain is its own, and passes.
+// The child keeps its exact claim, which beats the catch-all's star at the
+// edge, so the catch-all takes nothing from it. Otherwise the 409 says
+// why and names that record (catchallOverForeignChildMsg), rather than the
+// neutral answer that left the owner with nothing to act on. Asked only
+// when there is a child to answer for, so the common case makes no lookup.
+// The doors: setDomainCapabilities, the placements PUT that creates a
+// catch-all, and attachDomainClaim verifying a pending one.
+func (s *Server) foreignChildRefusal(ctx context.Context, parent, sqid string) *doorRefusal {
+ claims, unread, err := s.claims.ListWithUnread(ctx, s.cfg.Releases)
+ if err != nil {
+ log.Printf("console: catch-all over %s: child scan: %v", parent, err)
+ return &doorRefusal{Status: http.StatusBadGateway, Msg: "could not check the hostname — try again"}
+ }
+ under := func(h string) bool {
+ label, ok := strings.CutSuffix(h, "."+parent)
+ return ok && label != "" && label != "*" && !strings.Contains(label, ".")
+ }
+ blocked := false
+ for _, c := range claims {
+ blocked = blocked || (under(c.Host) && c.Account != sqid && !c.Pending)
+ }
+ for _, u := range unread {
+ blocked = blocked || under(u.Host)
+ }
+ if !blocked || s.domainChallengeHeld(ctx, parent, sqid) {
+ return nil
+ }
+ return &doorRefusal{Status: http.StatusConflict, Msg: catchallOverForeignChildMsg(parent, s.domainChallenge(parent, sqid))}
+}
+
// catchallInstanceName reports whether host is a one-label name under
// another account's live instance catch-all that the catch-all reserves.
//
diff --git a/internal/console/domaincatchall_test.go b/internal/console/domaincatchall_test.go
index b657a70a5..7e125eebf 100644
--- a/internal/console/domaincatchall_test.go
+++ b/internal/console/domaincatchall_test.go
@@ -28,7 +28,7 @@ import (
// go.tito.io.
func catchallFixture(t *testing.T, code string) (*consoleFixture, string) {
t.Helper()
- fx, member := instanceFixture(t, code)
+ fx, member := domainOwnerFixture(t, code) // attach is owner-only (H4-M7)
noCatchallProof(fx)
enableInstances(t, fx, "titogo", titoManifest())
if _, _, err := domains.AttachClaim(context.Background(), fx.rel, domains.Claim{
diff --git a/internal/console/domainplatform_test.go b/internal/console/domainplatform_test.go
index e5f3a2169..7d5bbd317 100644
--- a/internal/console/domainplatform_test.go
+++ b/internal/console/domainplatform_test.go
@@ -85,13 +85,14 @@ func TestDomainHostPolicyMatrix(t *testing.T) {
}
}
-// TestPlatformAttachRefusesMembers: an ordinary member gets the old refusal
-// without the flag and a 403 with it, and no claim is written either way.
+// TestPlatformAttachRefusesMembers: an ordinary member gets a 403 with the
+// flag or without it (without it, the attach door's owner gate, H4-M7), and
+// no claim is written either way.
func TestPlatformAttachRefusesMembers(t *testing.T) {
fx, alice, _ := platformFixture(t, "code-plat-member")
if code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), alice,
- attachBody("carloku.test", "go.tito.io")); code != http.StatusBadRequest {
- t.Errorf("member attach without --platform = %d %s, want 400", code, out)
+ attachBody("carloku.test", "go.tito.io")); code != http.StatusForbidden {
+ t.Errorf("member attach without --platform = %d %s, want 403", code, out)
}
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), alice,
platformAttachBody("carloku.test", "go.tito.io"))
@@ -165,7 +166,8 @@ func TestPlatformAttachBySystemOperator(t *testing.T) {
if _, err := fx.st.CreateAppIn(42, "website", "bob@keymail.dev", now); err != nil {
t.Fatal(err)
}
- if err := fx.st.AddMember(42, "bill@keymail.dev", RoleMember, now); err != nil {
+ // An owner of cdef: the attach door is owner-only (H4-M7).
+ if err := fx.st.AddMember(42, "bill@keymail.dev", RoleOwner, now); err != nil {
t.Fatal(err)
}
bill := cliToken(t, fx, "bill@keymail.dev", "code-plat-bill")
@@ -304,6 +306,7 @@ func TestPlatformBrowserDoors(t *testing.T) {
// sidecar name to a member too, with or without a deny entry covering it.
func TestAPIAttachRefusesSidecarNames(t *testing.T) {
fx, alice, _ := platformFixture(t, "code-plat-sidecar")
+ makeOwner(t, fx, "alice@keymail.dev") // the attach door is owner-only (H4-M7)
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), alice,
attachBody("web.sidecar.internal", "go.tito.io"))
if code != http.StatusBadRequest {
diff --git a/internal/console/domainpolicy.go b/internal/console/domainpolicy.go
index 55fb123b0..1a5a4e5cb 100644
--- a/internal/console/domainpolicy.go
+++ b/internal/console/domainpolicy.go
@@ -302,16 +302,26 @@ func (s *Server) domainProver(ctx context.Context, v namespaceView, host, accoun
if !s.cfg.DomainProof || s.domainProofExempt(v, host, account) {
return true
}
- want := domains.ChallengeToken(s.challengeDeployment(), account, host)
- got, err := s.lookupTXT(ctx, domains.ChallengeName(host))
- if err != nil {
- return false
- }
- for _, v := range got {
- if strings.TrimSpace(v) == want {
- return true
- }
- }
+ return s.domainChallengeHeld(ctx, host, account)
+ }
+}
+
+// domainChallengeHeld reports whether ChallengeName(host) carries
+// account's token right now, whatever DomainProof says. Any lookup failure
+// is "not held".
+func (s *Server) domainChallengeHeld(ctx context.Context, host, account string) bool {
+ if s.lookupTXT == nil {
return false
}
+ want := domains.ChallengeToken(s.challengeDeployment(), account, host)
+ got, err := s.lookupTXT(ctx, domains.ChallengeName(host))
+ if err != nil {
+ return false
+ }
+ for _, v := range got {
+ if strings.TrimSpace(v) == want {
+ return true
+ }
+ }
+ return false
}
diff --git a/internal/console/domainpolicy_test.go b/internal/console/domainpolicy_test.go
index 23753ed45..ed1a7c99e 100644
--- a/internal/console/domainpolicy_test.go
+++ b/internal/console/domainpolicy_test.go
@@ -85,7 +85,7 @@ func TestDomainHostDeniedPolicyMatrix(t *testing.T) {
}
func TestAPIDomainAttachDeniesAppsDomainAliasByDefault(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-alias-default")
+ fx, member := domainOwnerFixture(t, "code-dom-alias-default")
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.ReservePlatformDomains = true
code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member,
@@ -97,7 +97,7 @@ func TestAPIDomainAttachDeniesAppsDomainAliasByDefault(t *testing.T) {
}
func TestAPIDomainAttachAllowsAppsDomainAlias(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-alias-allow")
+ fx, member := domainOwnerFixture(t, "code-dom-alias-allow")
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.ReservePlatformDomains = true
fx.srv.cfg.AppsDomainAliasAccounts = []string{fx.sqid}
@@ -120,7 +120,7 @@ func TestAPIDomainAttachAllowsAppsDomainAlias(t *testing.T) {
}
func TestAPIDomainAttachAppsDomainAliasRejectsWildcardAndCatchall(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-alias-wild")
+ fx, member := domainOwnerFixture(t, "code-dom-alias-wild")
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.ReservePlatformDomains = true
fx.srv.cfg.AppsDomainAliasAccounts = []string{fx.sqid}
@@ -142,7 +142,7 @@ func TestAPIDomainAttachAppsDomainAliasRejectsWildcardAndCatchall(t *testing.T)
}
func TestAPIDomainAttachAppsDomainAliasStillRefusesForeignClaim(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-alias-conflict")
+ fx, member := domainOwnerFixture(t, "code-dom-alias-conflict")
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.ReservePlatformDomains = true
fx.srv.cfg.AppsDomainAliasAccounts = []string{fx.sqid}
@@ -165,7 +165,7 @@ func TestAPIDomainAttachAppsDomainAliasStillRefusesForeignClaim(t *testing.T) {
func TestAPIDomainAttachAppsDomainAliasStillRefusesDeploymentRoute(t *testing.T) {
ctx := context.Background()
- fx, member := instanceFixture(t, "code-dom-alias-route")
+ fx, member := domainOwnerFixture(t, "code-dom-alias-route")
fx.srv.cfg.AppsDomain = "oncarlos.test"
fx.srv.cfg.ReservePlatformDomains = true
fx.srv.cfg.AppsDomainAliasAccounts = []string{fx.sqid}
diff --git a/internal/console/domainproof_test.go b/internal/console/domainproof_test.go
index 8071c126c..73a1a081a 100644
--- a/internal/console/domainproof_test.go
+++ b/internal/console/domainproof_test.go
@@ -66,7 +66,7 @@ type proofListResp struct {
// answer says exactly which record proves it, nothing is announced to the
// fleet, and repeating the attach once the record exists verifies it.
func TestAPIDomainAttachWithoutProofIsPending(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-proof")
+ fx, member := domainOwnerFixture(t, "code-dom-proof")
fx.srv.cfg.DomainProof = true
lookups := 0
fx.srv.lookupTXT = noTXT(&lookups)
@@ -141,7 +141,7 @@ func TestAPIDomainAttachWithoutProofIsPending(t *testing.T) {
// Another account's proof is not this account's proof: the token is
// account-bound, so a record published for one account cannot be replayed.
func TestAPIDomainAttachRefusesAnotherAccountsProof(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-replay")
+ fx, member := domainOwnerFixture(t, "code-dom-replay")
fx.srv.cfg.DomainProof = true
const host = "shop.example.com"
fx.srv.lookupTXT = txtFor(fx.srv, "cdef", host)
@@ -159,7 +159,7 @@ func TestAPIDomainAttachRefusesAnotherAccountsProof(t *testing.T) {
// same bytes a verified holder produces, so a refusal still never says how
// firmly a name is held.
func TestAPIDomainProvenOwnerSupersedesSquatter(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-squat")
+ fx, member := domainOwnerFixture(t, "code-dom-squat")
fx.srv.cfg.DomainProof = true
ctx := context.Background()
const squatted, held = "shop.example.com", "held.example.com"
@@ -318,7 +318,7 @@ func serialValue(t *testing.T, fx *consoleFixture) string {
// no TXT lookup is ever made, every claim is written verified and announced,
// a first route declares its record at once, and the answer says verified.
func TestDomainProofOffBehavesAsBefore(t *testing.T) {
- fx, member := instanceFixture(t, "code-dom-proof-off")
+ fx, member := domainOwnerFixture(t, "code-dom-proof-off")
if fx.srv.cfg.DomainProof {
t.Fatal("DomainProof is on by default")
}
diff --git a/internal/console/doorkeys_store.go b/internal/console/doorkeys_store.go
index 9d74cd35b..a0d878d1b 100644
--- a/internal/console/doorkeys_store.go
+++ b/internal/console/doorkeys_store.go
@@ -16,7 +16,9 @@ import (
"database/sql"
"errors"
"fmt"
+ "log"
"os"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/doorkey"
@@ -29,6 +31,7 @@ var errDoorKeysFull = errors.New("console: door keys full")
// migrateDoorKeys creates the door-key tables. Additive and idempotent,
// called from Store.migrate.
func (s *Store) migrateDoorKeys() error {
+ ctx := context.Background()
for _, stmt := range []string{
`CREATE TABLE IF NOT EXISTS door_keys (
account_id INTEGER NOT NULL,
@@ -47,10 +50,36 @@ func (s *Store) migrateDoorKeys() error {
PRIMARY KEY (account_id, app)
);`,
} {
- if _, err := s.db.Exec(stmt); err != nil {
+ if _, err := s.db.ExecContext(ctx, stmt); err != nil {
return err
}
}
+ // created_by is the address that minted the key, so removing that
+ // person from the account revokes it (security hunt H4-M1,
+ // revokeMemberCredentialsTx). '' is a key whose minter is unknown.
+ if _, err := s.db.ExecContext(ctx, `ALTER TABLE door_keys ADD COLUMN created_by TEXT NOT NULL DEFAULT ''`); err != nil &&
+ !strings.Contains(err.Error(), "duplicate column") {
+ return err
+ }
+ // A key minted before the column existed takes its minter from the
+ // mint's audit row (handleAPIDoorKeyMint's detail, the only mint
+ // door). Idempotent: a key with no such row stays ''.
+ _, err := s.db.ExecContext(ctx, `UPDATE door_keys SET created_by = COALESCE((SELECT a.address FROM audit a
+WHERE a.account_id = door_keys.account_id AND a.app = door_keys.app AND a.action = 'door-key'
+AND a.detail = 'minted door key ' || door_keys.id || ' for ' || door_keys.app || ' (cli)'
+ORDER BY a.id LIMIT 1), '') WHERE created_by = ''`)
+ if err != nil {
+ return err
+ }
+ // What is still unattributed is revoked by the next removal of any
+ // member of its account (revokeMemberCredentialsTx); say how many.
+ var unknown int
+ if err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM door_keys WHERE created_by = '' AND revoked_at = 0`).Scan(&unknown); err != nil {
+ return err
+ }
+ if unknown > 0 {
+ log.Printf("console: %d live door key(s) have no recorded minter; removing any member of their account revokes them", unknown)
+ }
return nil
}
@@ -70,12 +99,25 @@ ON CONFLICT (account_id, app) DO UPDATE SET revision = revision + 1`, accountID,
// DoorKeyInsert stores a newly minted key's digest and bumps the app's
// revision in the same transaction. It refuses with errDoorKeysFull when the
// app already has doorkey.MaxKeys live keys.
-func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Entry) (uint64, error) {
+func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Entry, createdBy string) (uint64, error) {
tx, err := s.db.Begin()
if err != nil {
return 0, err
}
defer tx.Rollback()
+ // The minter's membership, re-read inside the insert's transaction
+ // (security hunt H4-M1), so a mint cannot land after its minter's
+ // removal. "" is a key with no recorded minter (tests and older rows).
+ if createdBy != "" {
+ var one int
+ err := tx.QueryRowContext(context.Background(), `SELECT 1 FROM memberships WHERE account_id = ? AND address = ?`, accountID, createdBy).Scan(&one)
+ if errors.Is(err, sql.ErrNoRows) {
+ return 0, errMinterNotMember
+ }
+ if err != nil {
+ return 0, err
+ }
+ }
var live int
if err := tx.QueryRow(`SELECT COUNT(*) FROM door_keys WHERE account_id = ? AND app = ? AND revoked_at = 0`,
accountID, app).Scan(&live); err != nil {
@@ -88,8 +130,8 @@ func (s *Store) claimRawDoorKeyInsert(accountID int64, app string, e doorkey.Ent
if created.IsZero() {
created = time.Now()
}
- if _, err := tx.Exec(`INSERT INTO door_keys (account_id, app, id, sha256, label, created_at)
-VALUES (?, ?, ?, ?, ?, ?)`, accountID, app, e.ID, e.SHA256, e.Label, created.UnixNano()); err != nil {
+ if _, err := tx.Exec(`INSERT INTO door_keys (account_id, app, id, sha256, label, created_at, created_by)
+VALUES (?, ?, ?, ?, ?, ?, ?)`, accountID, app, e.ID, e.SHA256, e.Label, created.UnixNano(), createdBy); err != nil {
return 0, err
}
rev, err := bumpDoorKeyRevision(tx, accountID, app)
@@ -242,12 +284,12 @@ func (s *Store) DoorKeyAdvanceRevisionContext(claimContext context.Context, acco
})
return
}
-func (s *Store) DoorKeyInsert(accountID int64, app string, e doorkey.Entry) (claimResult0 uint64, claimResult1 error) {
- return s.DoorKeyInsertContext(context.Background(), accountID, app, e)
+func (s *Store) DoorKeyInsert(accountID int64, app string, e doorkey.Entry, createdBy string) (claimResult0 uint64, claimResult1 error) {
+ return s.DoorKeyInsertContext(context.Background(), accountID, app, e, createdBy)
}
-func (s *Store) DoorKeyInsertContext(claimContext context.Context, accountID int64, app string, e doorkey.Entry) (claimResult0 uint64, claimResult1 error) {
+func (s *Store) DoorKeyInsertContext(claimContext context.Context, accountID int64, app string, e doorkey.Entry, createdBy string) (claimResult0 uint64, claimResult1 error) {
claimResult1 = s.withAutoAppSQL(claimContext, accountID, app, "sql.DoorKeyInsert", func(claimView *Store) error {
- claimResult0, claimResult1 = claimView.claimRawDoorKeyInsert(accountID, app, e)
+ claimResult0, claimResult1 = claimView.claimRawDoorKeyInsert(accountID, app, e, createdBy)
return claimResult1
})
return
diff --git a/internal/console/fleets.go b/internal/console/fleets.go
index cbe8623ad..d6c144d3d 100644
--- a/internal/console/fleets.go
+++ b/internal/console/fleets.go
@@ -97,6 +97,23 @@ func (s *Server) apiFleet(w http.ResponseWriter, r *http.Request) (addr string,
return addr, acct, fleet, reg, true
}
+// apiOwnerFleet is apiFleet behind the owner gate the browser's fleet box
+// doors hold (ownerFleet), for the CLI doors that mint, swap or withdraw a
+// box's credential (security hunt H4-M3). A member gets
+// apiOwnerAccountFor's 403; the family's byte-identical 404 still comes
+// first, and the fleet's own 404 after.
+func (s *Server) apiOwnerFleet(w http.ResponseWriter, r *http.Request, purpose string) (addr string, acct *Account, fleet *registry.Fleet, reg consoleRegistry, ok bool) {
+ p, acct, ok := s.apiOwnerAccountFor(w, r, purpose)
+ if !ok {
+ return "", nil, nil, nil, false
+ }
+ fleet, reg, ok = s.apiFleetOf(w, r, acct)
+ if !ok {
+ return "", nil, nil, nil, false
+ }
+ return auditActor(p, acct), acct, fleet, reg, true
+}
+
// apiFleetOf is apiFleet's fleet half for a door that has already resolved
// the account its own way (the secrets key door's owner gate): the
// {fleet} segment read from the registry, with an unknown fleet and one
@@ -387,7 +404,7 @@ func (s *Server) handleAPIFleetList(w http.ResponseWriter, r *http.Request) {
// only its sha256 hex reaches the registry (AddFleetBox), and it is never
// logged.
func (s *Server) handleAPIFleetAddBox(w http.ResponseWriter, r *http.Request) {
- addr, acct, fleet, reg, ok := s.apiFleet(w, r)
+ addr, acct, fleet, reg, ok := s.apiOwnerFleet(w, r, "add a box to a fleet")
if !ok {
return
}
@@ -471,7 +488,7 @@ func (s *Server) handleAPIFleetAddBox(w http.ResponseWriter, r *http.Request) {
// which the edge honours by closing the live channel outright — rotation
// alone is the wrong tool for "get this box off the network right now".
func (s *Server) handleAPIFleetRotateBox(w http.ResponseWriter, r *http.Request) {
- addr, acct, fleet, reg, ok := s.apiFleet(w, r)
+ addr, acct, fleet, reg, ok := s.apiOwnerFleet(w, r, "rotate a fleet box's token")
if !ok {
return
}
@@ -532,7 +549,7 @@ func (s *Server) handleAPIFleetRotateBox(w http.ResponseWriter, r *http.Request)
// findFleetBox's doc comment for why that one is not the cross-tenant-probe
// 404.
func (s *Server) handleAPIFleetTagBox(w http.ResponseWriter, r *http.Request) {
- addr, acct, fleet, reg, ok := s.apiFleet(w, r)
+ addr, acct, fleet, reg, ok := s.apiOwnerFleet(w, r, "tag a fleet box")
if !ok {
return
}
@@ -578,7 +595,7 @@ func (s *Server) handleAPIFleetTagBox(w http.ResponseWriter, r *http.Request) {
// refused, and — unlike rotation — an already-connected channel is closed).
// This is the hard revocation rotation is not.
func (s *Server) handleAPIFleetDetachBox(w http.ResponseWriter, r *http.Request) {
- addr, acct, fleet, reg, ok := s.apiFleet(w, r)
+ addr, acct, fleet, reg, ok := s.apiOwnerFleet(w, r, "detach a fleet box")
if !ok {
return
}
@@ -1213,6 +1230,11 @@ func (s *Server) handleAPIPlace(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ // The browser's place is owner-only (handleAppPlace, handleFleetPlacePage);
+ // so is this door (H4-M4).
+ if !s.apiOwnerOnly(w, r, acct, "place an app") {
+ return
+ }
p, _ := principalFrom(r.Context())
if !s.allowWrite(p, time.Now()) {
jsonError(w, http.StatusTooManyRequests, "too many requests — wait a minute and try again")
diff --git a/internal/console/hap2_wiring_test.go b/internal/console/hap2_wiring_test.go
index bfef79432..f5ece687e 100644
--- a/internal/console/hap2_wiring_test.go
+++ b/internal/console/hap2_wiring_test.go
@@ -493,7 +493,7 @@ func TestHAP2ProductionDoors(t *testing.T) {
}
})
t.Run("first-domain static", func(t *testing.T) {
- fx, token := instanceFixture(t, "hap2-static")
+ fx, token := domainOwnerFixture(t, "hap2-static") // attach is owner-only (H4-M7)
shipVersion(t, fx, "titogo", "v1")
seedChannel(t, fx, "titogo", "canary/live", "v1")
fx.srv.cfg.HomeRegion, fx.srv.cfg.HARegions = "ie", []string{"ie"}
diff --git a/internal/console/hostsused_writers_test.go b/internal/console/hostsused_writers_test.go
index d1dc9bc7f..d81836883 100644
--- a/internal/console/hostsused_writers_test.go
+++ b/internal/console/hostsused_writers_test.go
@@ -389,7 +389,7 @@ func TestExemptCreatesDoNotMark(t *testing.T) {
noMarks(t, c.bucket.Store)
})
t.Run("attach first route", func(t *testing.T) {
- fx, member := instanceFixture(t, "code-exempt-attach")
+ fx, member := domainOwnerFixture(t, "code-exempt-attach") // attach is owner-only (H4-M7)
c := markCase{fx: fx, bucket: wrapBucket(fx)}
on(t, c)
shipVersion(t, fx, "titogo", "v1")
diff --git a/internal/console/hunt_H4-M10_test.go b/internal/console/hunt_H4-M10_test.go
new file mode 100644
index 000000000..8590db049
--- /dev/null
+++ b/internal/console/hunt_H4-M10_test.go
@@ -0,0 +1,39 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestHunt_H4_M10_PipelineCannotBypassLegacyStableGate(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m10")
+ shipVersion(t, fx, "titogo", "abc1234")
+ shipVersion(t, fx, "titogo", "def5678")
+ if err := release.Promote(context.Background(), fx.rel, fx.priv, fx.sqid, "titogo", "stable", "def5678"); err != nil {
+ t.Fatal(err)
+ }
+ base := fx.ts.URL + "/api/cli/apps/bab/titogo"
+ body := map[string]string{"version": "abc1234", "channel": "stable"}
+ if code, out := postJSON(t, base+"/promote", body, member); code != http.StatusForbidden {
+ t.Fatalf("legacy stable control: %d %v", code, out)
+ }
+ code, out := putJSON(t, base+"/pipeline", map[string]any{"channels": []map[string]any{{"name": "stable"}}}, member)
+ if code == http.StatusForbidden || code == http.StatusNotFound {
+ return
+ }
+ if code != http.StatusOK {
+ t.Fatalf("pipeline setup: %d %v", code, out)
+ }
+ code, out = postJSON(t, base+"/promote", body, member)
+ cp, err := release.Channel(context.Background(), fx.rel, fx.pub, fx.sqid, "titogo", "stable")
+ if code != http.StatusForbidden || err != nil || cp.Version != "def5678" {
+ version := ""
+ if cp != nil {
+ version = cp.Version
+ }
+ t.Errorf("pipeline bypassed legacy stable passkey gate: promote_status=%d signed_pointer_version=%q verify_error=%v; want 403 and original def5678 pointer; response=%v", code, version, err, out)
+ }
+}
diff --git a/internal/console/hunt_H4-M12_test.go b/internal/console/hunt_H4-M12_test.go
new file mode 100644
index 000000000..a7710b11f
--- /dev/null
+++ b/internal/console/hunt_H4-M12_test.go
@@ -0,0 +1,52 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/gate"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestHunt_H4_M12_MemberCannotClearPasswordGate(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m12")
+ hash, err := gate.Hash("hunt password gate")
+ if err != nil {
+ t.Fatal(err)
+ }
+ rec := provision.Record{Schema: 1, Host: "hunt.go.tito.io", Slug: "hunt", App: "titogo", Account: fx.sqid, Region: "ie", Channel: "stable", CreatedAt: time.Now().UTC(), Gate: hash}
+ if err := provision.CreateRecord(context.Background(), fx.rel, rec); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "sibling", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ sibling := mintInstanceToken(t, fx, member, "sibling")
+ if code, _, _ := rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/"+rec.Host, sibling, `{"gate":""}`); code != http.StatusNotFound {
+ t.Fatalf("sibling token control: %d", code)
+ }
+ fx.setUser("stranger@keymail.dev")
+ stranger := newBrowser(t)
+ signUp(t, fx, stranger, "hunt-m12-stranger")
+ if code, _, _ := postForm(t, stranger, fx.u("/apps/titogo/gate"), url.Values{"csrf": {sessionToken(t, fx, stranger)}, "host": {rec.Host}, "action": {"clear"}}); code != http.StatusNotFound {
+ t.Fatalf("foreign member control: %d", code)
+ }
+ untouched, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", rec.Host)
+ if err != nil || untouched.Gate != hash {
+ t.Fatal("negative control changed gate")
+ }
+ fx.setUser("alice@keymail.dev")
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "hunt-m12-browser")
+ code, _, _ := postForm(t, browser, fx.u("/apps/titogo/gate"), url.Values{"csrf": {sessionToken(t, fx, browser)}, "host": {rec.Host}, "action": {"clear"}})
+ got, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", rec.Host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != http.StatusForbidden && code != http.StatusNotFound || got.Gate != hash {
+ t.Errorf("member cleared password gate without step-up: status=%d gate_empty=%v; want refusal and unchanged gate", code, got.Gate == "")
+ }
+}
diff --git a/internal/console/hunt_H4-M1_test.go b/internal/console/hunt_H4-M1_test.go
new file mode 100644
index 000000000..17ef2b6c5
--- /dev/null
+++ b/internal/console/hunt_H4-M1_test.go
@@ -0,0 +1,180 @@
+package console
+
+import (
+ "context"
+ "crypto/ecdh"
+ "crypto/rand"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+func TestHunt_H4_M1_RemovalRevokesDerivedCredentials(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m1")
+ enableInstances(t, fx, "titogo", titoManifest())
+ token := mintInstanceToken(t, fx, member, "titogo")
+ door := mintDoorKey(t, fx, member)
+ status, _, out := rawReq(t, http.MethodPost, instancesURL(fx, "bab", "titogo"), token, `{"host":"hunt.go.tito.io","region":"ie"}`)
+ if status != http.StatusCreated {
+ t.Fatalf("setup instance: %d %s", status, out)
+ }
+ status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", member, `{"gate":"hunt original password"}`)
+ if status != http.StatusOK {
+ t.Fatalf("setup password gate: %d %s", status, out)
+ }
+ beforeRecord, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", "hunt.go.tito.io")
+ if err != nil || beforeRecord.Gate == "" {
+ t.Fatalf("setup gate: %v", err)
+ }
+ fx.setUser("paul@keymail.dev")
+ owner := signInPaul(t, fx)
+ status, _, _ = postGated(t, fx, owner, fx.u("/members/remove"), url.Values{"csrf": {sessionToken(t, fx, owner)}, "address": {"alice@keymail.dev"}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("remove member: %d", status)
+ }
+ if role, err := fx.st.Role(OpsAccountID, "alice@keymail.dev"); err != nil || role != "" {
+ t.Fatalf("member still present: %q %v", role, err)
+ }
+ status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", member, `{"gate":""}`)
+ if status != http.StatusNotFound {
+ t.Fatalf("removed personal credential must fail: %d %s", status, out)
+ }
+ status, _, out = rawReq(t, http.MethodPatch, instancesURL(fx, "bab", "titogo")+"/hunt.go.tito.io", token, `{"gate":""}`)
+ if status != http.StatusUnauthorized && status != http.StatusNotFound && status != http.StatusForbidden {
+ afterRecord, err := provision.GetRecord(context.Background(), fx.rel, fx.sqid, "titogo", "hunt.go.tito.io")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Errorf("removed member's instance token still mutates instance: status=%d gate_cleared=%v body=%s; want 401/403/404 and unchanged gate", status, afterRecord.Gate == "", out)
+ }
+ before := readDoorRecord(t, fx)
+ fx.srv.resignDoorKeys(context.Background())
+ after := readDoorRecord(t, fx)
+ if after.Admits(door) {
+ t.Errorf("removed member's door key remains admitted after production re-sign; expiry extended=%v", after.ExpiresAt.After(before.ExpiresAt))
+ }
+ future := time.Now().Add(CLITokenTTL + time.Hour)
+ if _, ok := fx.st.CLIPrincipal(member, future); ok {
+ t.Fatal("personal token did not expire at day 91")
+ }
+ if _, ok := fx.st.CLIPrincipal(token, future); ok {
+ t.Errorf("derived instance token still authenticates after its minter's 90-day bearer expires")
+ }
+}
+
+// The sandbox disallows sockets. Reuse the fixture's real SQLite/DirStore
+// setup and OAuth handlers, replacing only the HTTP transport with direct
+// ServeHTTP calls. Every console request still traverses NewServer's mux,
+// cliRoute, session/CSRF checks, and the production handler. Other outbound
+// destinations are refused; none of these tests can access the network.
+// Tests using this fixture must not call t.Parallel (DefaultTransport is
+// scoped to the test and restored by Cleanup).
+type huntTransport func(*http.Request) (*http.Response, error)
+
+func (f huntTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func huntConsoleFixture(t *testing.T) *consoleFixture {
+ t.Helper()
+ regPath, rel, priv, pub := buildFixtures(t)
+ st, err := Open(filepath.Join(t.TempDir(), "console.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { st.Close() })
+ key, err := ecdh.P256().GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ fk := &fakeKeymail{t: t, address: "paul@keymail.dev", boxPriv: key, reauth: true, powBits: 8,
+ noMailbox: map[string]bool{}, blocked: map[string]bool{}, lookupStatus: map[string]int{},
+ lookupStall: map[string]time.Duration{}, senders: map[string]string{}}
+ km := http.NewServeMux()
+ km.HandleFunc("GET /.well-known/keymail", fk.handleWellKnown)
+ km.HandleFunc("POST /api/oauth/token", fk.handleToken)
+ km.HandleFunc("POST /api/oauth/revoke", fk.handleRevoke)
+ km.HandleFunc("GET /api/federation/lookup", fk.handleLookup)
+ km.HandleFunc("POST /api/app/send", fk.handleSend)
+ km.HandleFunc("POST /api/federation/challenge", fk.handleChallenge)
+ km.HandleFunc("POST /api/federation/register", fk.handleRegister)
+ km.HandleFunc("POST /api/federation/deliver", fk.handleDeliver)
+ fk.srv = &httptest.Server{URL: "http://keymail.hunt.invalid"}
+ ts := &httptest.Server{URL: "http://console.hunt.invalid"}
+ srv, err := NewServer(Config{Origin: ts.URL, Keymail: fk.srv.URL, Registry: regPath, Releases: rel, ReleasePub: pub, Key: priv, AppScheme: "http"}, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // The swap follows NewServer, whose PDF clients clone the real
+ // *http.Transport (merge of main's dpapdfroute.go).
+ old := http.DefaultTransport
+ http.DefaultTransport = huntTransport(func(req *http.Request) (*http.Response, error) {
+ r := req.Clone(req.Context())
+ r.RequestURI = r.URL.RequestURI()
+ if r.RemoteAddr == "" {
+ r.RemoteAddr = "192.0.2.1:54321"
+ }
+ w := httptest.NewRecorder()
+ switch r.URL.Host {
+ case "console.hunt.invalid":
+ srv.ServeHTTP(w, r)
+ case "keymail.hunt.invalid":
+ km.ServeHTTP(w, r)
+ default:
+ return nil, fmt.Errorf("hunt forbids outbound request to %s", r.URL.Host)
+ }
+ res := w.Result()
+ res.Request = req
+ return res, nil
+ })
+ t.Cleanup(func() { http.DefaultTransport = old })
+ srv.km.httpc.Transport = http.DefaultTransport
+ srv.cliNotified = make(chan struct{}, 16)
+ if err := st.AddMember(OpsAccountID, "paul@keymail.dev", RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateAppIn(OpsAccountID, "kass", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return &consoleFixture{ts: ts, srv: srv, st: st, fk: fk, rel: rel, regPath: regPath, priv: priv, pub: pub, sqid: "bab"}
+}
+
+func huntInstanceFixture(t *testing.T, code string) (*consoleFixture, string) {
+ t.Helper()
+ fx := huntConsoleFixture(t)
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return fx, huntCLIToken(t, fx, "alice@keymail.dev", code)
+}
+func huntFleetFixture(t *testing.T, code string) (*consoleFixture, string) {
+ t.Helper()
+ fx := huntConsoleFixture(t)
+ return fx, huntCLIToken(t, fx, "paul@keymail.dev", code)
+}
+func huntEmailFixture(t *testing.T) (*consoleFixture, *fakeConsoleMail) {
+ t.Helper()
+ fx := huntConsoleFixture(t)
+ m := &fakeConsoleMail{ready: true}
+ fx.srv.consoleMail = m
+ fx.srv.challengeSent = make(chan struct{}, 16)
+ return fx, m
+}
+
+func huntCLIToken(t *testing.T, fx *consoleFixture, address, code string) string {
+ t.Helper()
+ token := cliToken(t, fx, address, code)
+ select {
+ case <-fx.srv.cliNotified:
+ case <-time.After(5 * time.Second):
+ t.Fatal("CLI issuance notification did not finish")
+ }
+ return token
+}
diff --git a/internal/console/hunt_H4-M2_test.go b/internal/console/hunt_H4-M2_test.go
new file mode 100644
index 000000000..2cffe3094
--- /dev/null
+++ b/internal/console/hunt_H4-M2_test.go
@@ -0,0 +1,26 @@
+package console
+
+import (
+ "net/http"
+ "net/url"
+ "testing"
+)
+
+func TestHunt_H4_M2_MemberCannotTrash(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m2")
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "hunt-m2-browser")
+ status, _, _ := postForm(t, browser, fx.u("/apps/titogo/delete"), url.Values{"csrf": {sessionToken(t, fx, browser)}})
+ if status != http.StatusNotFound {
+ t.Fatalf("browser member control: %d; want 404", status)
+ }
+ status, out := postBody(t, fx.ts.URL+"/api/cli/apps/bab/titogo/delete", member, "")
+ has, err := fx.st.HasTrashedAppIn(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ tomb := tombstone(t, fx, "titogo")
+ if status != http.StatusForbidden && status != http.StatusNotFound || tomb != nil || has {
+ t.Errorf("member trashed app: status=%d tombstone=%v trashed_row=%v; want refusal and unchanged app; response=%s", status, tomb != nil, has, out)
+ }
+}
diff --git a/internal/console/hunt_H4-M3_test.go b/internal/console/hunt_H4-M3_test.go
new file mode 100644
index 000000000..b63e37fe2
--- /dev/null
+++ b/internal/console/hunt_H4-M3_test.go
@@ -0,0 +1,72 @@
+package console
+
+import (
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/edge"
+)
+
+func TestHunt_H4_M3_MemberCannotManageFleetBoxes(t *testing.T) {
+ for _, action := range []string{"add", "rotate", "detach", "tags"} {
+ t.Run(action, func(t *testing.T) {
+ fx, owner := huntFleetFixture(t, "hunt-m3-owner")
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ member := huntCLIToken(t, fx, "alice@keymail.dev", "hunt-m3-member")
+ base := fleetsURL(fx, fx.sqid)
+ if code, out := postJSON(t, base+"/new", map[string]string{"name": "hunt", "bucket": "hunt-data"}, owner); code != http.StatusOK {
+ t.Fatalf("setup fleet: %d %v", code, out)
+ }
+ base += "/hunt/boxes"
+ if code, out := postJSON(t, base, map[string]string{"label": "existing"}, owner); code != http.StatusOK {
+ t.Fatalf("setup box: %d %v", code, out)
+ }
+ reg := openTestReg(t, fx)
+ defer reg.Close()
+ before, err := reg.ListFleetBoxes("hunt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ path := base + "/existing/" + action
+ body := map[string]string{}
+ if action == "add" {
+ path = base
+ body["label"] = "attacker"
+ }
+ if action == "tags" {
+ body["tags"] = "attacker"
+ }
+ code, out := postJSON(t, path, body, member)
+ after, err := reg.ListFleetBoxes("hunt")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if action == "add" || action == "rotate" {
+ auth, err := reg.FleetChannelAuth()
+ if err != nil {
+ t.Fatal(err)
+ }
+ hub := &edge.TunnelHub{}
+ hub.SetDynamicAuth(auth)
+ label := "existing"
+ if action == "add" {
+ label = "attacker"
+ }
+ token, _ := out["token"].(string)
+ if fleet, ok := hub.VerifyDynamic("hunt/"+label, token); ok {
+ t.Errorf("member-issued %s token authenticates at edge as fleet=%q; want rejection", action, fleet)
+ }
+ }
+ changed := len(before) != len(after)
+ if len(before) == len(after) {
+ changed = before[0].TokenHash != after[0].TokenHash || before[0].Status != after[0].Status || before[0].Tags != after[0].Tags
+ }
+ if code != http.StatusForbidden && code != http.StatusNotFound || changed {
+ t.Errorf("member fleet %s: status=%d state_changed=%v token_returned=%v; want refusal and unchanged registry", action, code, changed, out["token"] != "" && out["token"] != nil)
+ }
+ })
+ }
+}
diff --git a/internal/console/hunt_H4-M4_test.go b/internal/console/hunt_H4-M4_test.go
new file mode 100644
index 000000000..42a365a42
--- /dev/null
+++ b/internal/console/hunt_H4-M4_test.go
@@ -0,0 +1,53 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestHunt_H4_M4_MemberCannotPlaceProductionApp(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m4")
+ owner := huntCLIToken(t, fx, "paul@keymail.dev", "hunt-m4-owner")
+ ctx := context.Background()
+ if err := release.SetProduction(ctx, fx.rel, fx.priv, fx.sqid, "titogo", true, "paul@keymail.dev"); err != nil {
+ t.Fatal(err)
+ }
+ reg := openTestReg(t, fx)
+ defer reg.Close()
+ host := "hunt.go.tito.io"
+ if err := reg.Upsert(registry.Route{Host: host, Kind: "instance", App: "titogo", Account: fx.sqid, Region: "ie", Channel: "stable"}); err != nil {
+ t.Fatal(err)
+ }
+ if err := provision.CreateRecord(ctx, fx.rel, provision.Record{Schema: 1, Host: host, Slug: "hunt", App: "titogo", Account: fx.sqid, Region: "ie", Channel: "stable", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ if code, out := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "hunt", "bucket": "hunt-data"}, owner); code != http.StatusOK {
+ t.Fatalf("setup fleet: %d %v", code, out)
+ }
+ fx.setUser("alice@keymail.dev")
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "hunt-m4-browser")
+ code, _, _ := postForm(t, browser, fx.u("/apps/titogo/place"), url.Values{"csrf": {sessionToken(t, fx, browser)}, "target": {"fleet/hunt"}})
+ if code != http.StatusNotFound {
+ t.Fatalf("browser member control=%d", code)
+ }
+ code, out := postJSON(t, placeURL(fx, "titogo"), map[string]string{"target": "fleet/hunt"}, member)
+ rt, err := reg.Get(host)
+ if err != nil || rt == nil {
+ t.Fatalf("read route: %v", err)
+ }
+ rec, err := provision.GetRecord(ctx, fx.rel, fx.sqid, "titogo", host)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != http.StatusForbidden && code != http.StatusNotFound || rt.Region != "ie" || rec.Region != "ie" {
+ t.Errorf("member moved production app: status=%d route_region=%q record_region=%q; want refusal and ie; response=%v", code, rt.Region, rec.Region, out)
+ }
+}
diff --git a/internal/console/hunt_H4-M7_test.go b/internal/console/hunt_H4-M7_test.go
new file mode 100644
index 000000000..2a60db93d
--- /dev/null
+++ b/internal/console/hunt_H4-M7_test.go
@@ -0,0 +1,27 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/url"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+func TestHunt_H4_M7_MemberCannotDetachDomain(t *testing.T) {
+ fx, member := huntInstanceFixture(t, "hunt-m7")
+ owner := huntCLIToken(t, fx, "paul@keymail.dev", "hunt-m7-owner")
+ attachDomain(t, fx, owner, "hunt.example.com", "go.tito.io")
+ fx.setUser("alice@keymail.dev")
+ browser := newBrowser(t)
+ signUp(t, fx, browser, "hunt-m7-browser")
+ if code, _, _ := postForm(t, browser, fx.u("/apps/titogo/domains/detach"), url.Values{"csrf": {sessionToken(t, fx, browser)}, "host": {"hunt.example.com"}, "confirm": {"hunt.example.com"}}); code != http.StatusNotFound {
+ t.Fatalf("browser member control: %d", code)
+ }
+ code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, fx.sqid, "titogo")+"/hunt.example.com", member, "")
+ claim, err := domains.GetClaim(context.Background(), fx.rel, "hunt.example.com")
+ if code != http.StatusForbidden && code != http.StatusNotFound || err != nil || claim == nil {
+ t.Errorf("member detached domain: status=%d claim_present=%v read_error=%v; want refusal and original claim; response=%s", code, claim != nil, err, out)
+ }
+}
diff --git a/internal/console/hunt_H5-M1_test.go b/internal/console/hunt_H5-M1_test.go
new file mode 100644
index 000000000..c8c0a12a7
--- /dev/null
+++ b/internal/console/hunt_H5-M1_test.go
@@ -0,0 +1,106 @@
+package console
+
+// Hunt H5-M1 (verifier: opus). A parent claim carrying Wildcard+Catchall
+// derives "*.<parent>" -> the holder's route on every box. The attach door's
+// last collision check (heldElsewhere) covers real routes and INSTANCE
+// catch-alls only, and with DomainProof at its default (off) every attach is
+// proven by definition (domainPolicy.domainProver). So another account can
+// attach an unclaimed child of somebody else's catch-all and get a VERIFIED
+// exact claim, which every box then turns into an exact alias that beats the
+// star (edge lookupIn).
+//
+// The test asserts the SECURE answer (the foreign child is refused, or at
+// least written pending) through the real CLI door with two real accounts.
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "os"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/domains"
+)
+
+func TestHunt_H5_M1_ForeignChildOfOrdinaryCatchall(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-h5m1")
+ noCatchallProof(fx)
+ ctx := context.Background()
+
+ // The victim: account bab (ops account), app titogo, holds the parent
+ // with both capabilities, routed at its own route. Written through the
+ // production writers (AttachClaim then SetClaimCapabilities) — the
+ // victim's own setup is not the gate under test.
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{
+ Host: "victim.example", Account: "bab", App: "titogo", Route: "go.tito.io",
+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := domains.SetClaimCapabilities(ctx, fx.rel, "victim.example", "bab", "titogo", true, true); err != nil {
+ t.Fatal(err)
+ }
+ parent, err := domains.GetClaim(ctx, fx.rel, "victim.example")
+ if err != nil || !parent.Wildcard || !parent.Catchall || parent.Pending {
+ t.Fatalf("test bug: parent claim = %+v err=%v, want verified wildcard+catchall", parent, err)
+ }
+
+ // The attacker: a different account with its own app and CLI token.
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-h5m1-bob")
+
+ if fx.srv.cfg.DomainProof {
+ t.Fatal("test bug: the fixture must run with DomainProof at its default (off)")
+ }
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "cdef", "widgets"), bob,
+ attachBody("shop.victim.example", "w.attacker.example"))
+ c, gerr := domains.GetClaim(ctx, fx.rel, "shop.victim.example")
+ if gerr == nil && c.Account == "cdef" && !c.Pending {
+ t.Fatalf("H5-M1: a foreign account attached shop.victim.example under bab's wildcard+catchall parent: "+
+ "door answered %d %s and stored a VERIFIED claim %s/%s -> %s (want the neutral 409 or at least a pending claim)",
+ code, strings.TrimSpace(out), c.Account, c.App, c.Route)
+ }
+ if gerr != nil && !errors.Is(gerr, os.ErrNotExist) {
+ t.Fatalf("read claim: %v", gerr)
+ }
+}
+
+// Negative control: the same attach with DomainProof on and no TXT proof
+// is written PENDING, so no box derives an alias from it.
+func TestHunt_H5_M1_ControlDomainProofOn(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-h5m1c")
+ noCatchallProof(fx)
+ fx.srv.cfg.DomainProof = true
+ ctx := context.Background()
+ if _, _, err := domains.AttachClaim(ctx, fx.rel, domains.Claim{
+ Host: "victim.example", Account: "bab", App: "titogo", Route: "go.tito.io",
+ CreatedAt: time.Now().UTC().Format(time.RFC3339),
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := domains.SetClaimCapabilities(ctx, fx.rel, "victim.example", "bab", "titogo", true, true); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := fx.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.CreateAppIn(42, "widgets", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ bob := cliToken(t, fx, "bob@keymail.dev", "code-h5m1c-bob")
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "cdef", "widgets"), bob,
+ attachBody("shop.victim.example", "w.attacker.example"))
+ c, err := domains.GetClaim(ctx, fx.rel, "shop.victim.example")
+ if err == nil && !c.Pending {
+ t.Fatalf("control: with DomainProof on and no TXT proof the claim is verified (%d %s): %+v", code, out, c)
+ }
+}
diff --git a/internal/console/lifetimes_create_test.go b/internal/console/lifetimes_create_test.go
index a8adae82f..94071021a 100644
--- a/internal/console/lifetimes_create_test.go
+++ b/internal/console/lifetimes_create_test.go
@@ -1456,7 +1456,7 @@ func TestCreateChecksTheAppUnderTheLock(t *testing.T) {
once.Do(func() { purgeShop(t, l) })
}
})
- status, h, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member,
+ status, h, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.operator,
`{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`)
assertNotFound(t, "attach with the app gone under the lock", canonicalNotFound(t), status, h, body)
if got := claimHolder(t, l.fx.rel, ltDomain); got != "" {
@@ -1883,7 +1883,7 @@ func TestDetachCompletesThroughTheRealHandlers(t *testing.T) {
for _, door := range []string{"api", "browser"} {
t.Run(door, func(t *testing.T) {
l := newLtOn(t)
- code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member,
+ code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.operator,
`{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`)
if code != http.StatusOK {
t.Fatalf("attach = %d %s", code, body)
@@ -1892,7 +1892,7 @@ func TestDetachCompletesThroughTheRealHandlers(t *testing.T) {
done := make(chan int, 1)
go func() {
if door == "api" {
- code, _, _ := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, "")
+ code, _, _ := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.operator, "")
done <- code
return
}
@@ -2263,7 +2263,7 @@ func TestDispatchFollowsTheUnit(t *testing.T) {
answers <- fmt.Sprintf("delete %d", code)
}()
go func() {
- code, _, _ := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, "")
+ code, _, _ := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.operator, "")
answers <- fmt.Sprintf("detach %d", code)
}()
for what, g := range map[string]*pauseGate{"create": createGate, "delete": deleteGate, "detach": detachGate} {
@@ -2466,10 +2466,10 @@ func testLockOrderOfTheDoors(t *testing.T) {
t.Fatalf("the orphan retirement took %v", got)
}
// Attach and detach, through the API and the browser.
- if code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member, `{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`); code != http.StatusOK {
+ if code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.operator, `{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`); code != http.StatusOK {
t.Fatalf("attach = %d %s", code, body)
}
- if code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, ""); code != http.StatusOK {
+ if code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.operator, ""); code != http.StatusOK {
t.Fatalf("detach = %d %s", code, body)
}
if _, ref := l.attach(t, onCtx(t, l.fx.srv), ltApp); ref != nil {
diff --git a/internal/console/lifetimes_retire_test.go b/internal/console/lifetimes_retire_test.go
index 52ce375bd..3619fb0b7 100644
--- a/internal/console/lifetimes_retire_test.go
+++ b/internal/console/lifetimes_retire_test.go
@@ -1116,7 +1116,7 @@ func TestTerminationFencesFirst(t *testing.T) {
func TestDetachMapsLifetimeErrors(t *testing.T) {
attach := func(t *testing.T, l ltOn) {
t.Helper()
- code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.member,
+ code, _, body := rawReq(t, http.MethodPost, domainsURL(l.fx, "bab", ltApp), l.operator,
`{"host":"`+ltDomain+`","kind":"static","channel":"stable"}`)
if code != http.StatusOK {
t.Fatalf("attach = %d %s", code, body)
@@ -1146,7 +1146,7 @@ func TestDetachMapsLifetimeErrors(t *testing.T) {
attach(t, l)
c.arrange(t, l)
if door == "api" {
- code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.member, "")
+ code, _, body := rawReq(t, http.MethodDelete, domainsURL(l.fx, "bab", ltApp)+"/"+ltDomain, l.operator, "")
if code != http.StatusConflict || ltErr(body) != c.msg {
t.Fatalf("detach = %d %s, want 409 %q", code, body, c.msg)
}
diff --git a/internal/console/links_sync.go b/internal/console/links_sync.go
index f84d9c541..959c3f560 100644
--- a/internal/console/links_sync.go
+++ b/internal/console/links_sync.go
@@ -176,5 +176,10 @@ func (s *Server) linkSyncPass(ctx context.Context) error {
errs = append(errs, fmt.Errorf("link %s: finish unlink: %w", id, err))
}
}
+ // Member removals' door-key follow-up rides the same cadence
+ // (memberrevoke.go): each row retries until its publishes land.
+ if err := s.drainMemberRevocations(ctx, 0); err != nil {
+ errs = append(errs, err)
+ }
return errors.Join(errs...)
}
diff --git a/internal/console/member_demo_test.go b/internal/console/member_demo_test.go
index fc4fdd3a4..49502e817 100644
--- a/internal/console/member_demo_test.go
+++ b/internal/console/member_demo_test.go
@@ -82,7 +82,7 @@ func TestDemoHoldingMemberWriteRechecksAndRollsBack(t *testing.T) {
if tc.edit != nil {
tc.edit(&cfg)
}
- write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg)
+ write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg, false)
if tc.moveFleet {
fleet.Account = "other"
if err := reg.UpsertFleet(fleet); err != nil {
@@ -195,7 +195,7 @@ func TestDemoHoldingOpsAccountRefused(t *testing.T) {
if _, err := st.db.Exec(`ATTACH DATABASE ? AS demo_holding_registry`, path); err != nil {
t.Fatal(err)
}
- err = st.MembershipTransition(removeDemoHoldingMemberWrite(OpsAccountID, "owner@keymail.dev", cfg))
+ err = st.MembershipTransition(removeDemoHoldingMemberWrite(OpsAccountID, "owner@keymail.dev", cfg, false))
want = "not the configured demo holding account"
}
if err == nil || !strings.Contains(err.Error(), want) {
@@ -249,7 +249,7 @@ func TestDemoHoldingLastOwnerTokens(t *testing.T) {
}
// Construct the write before minting credentials to catch a check
// that moves outside the membership transaction.
- write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg)
+ write := removeDemoHoldingMemberWrite(42, "owner@keymail.dev", cfg, false)
for _, id := range []string{"first-token-id", "second-token-id"} {
_, err := st.db.Exec(`INSERT INTO cli_tokens(token_hash,address,label,name,created_at,expires_at,account_id,kind,revoked_at)
VALUES(?, 'another@keymail.dev', 'deploy label', ?, ?, ?, ?, ?, ?)`, id, "deploy name "+id, now.Unix(), expires, tc.account, tc.kind, revoked)
diff --git a/internal/console/memberrevoke.go b/internal/console/memberrevoke.go
new file mode 100644
index 000000000..5a6f8741a
--- /dev/null
+++ b/internal/console/memberrevoke.go
@@ -0,0 +1,466 @@
+package console
+
+// Removing a member ends what they minted for the account (security hunt
+// H4-M1). A person's own authority over an account is their membership,
+// read on every request, so it ends with the row. The credentials they
+// minted for the account do not read it: an instance token, a service
+// credential, a link credential and a door key each name the account
+// themselves and never expire. Left alone, every one of them outlives the
+// removal, so a removed member keeps whatever they minted on the way out.
+//
+// revokeMemberCredentialsTx is the one place that ends them, inside the
+// removal's own transaction, so there is no moment with the member gone
+// and their credentials live. Every kind the store can mint for an
+// account and record a minter on:
+//
+// cli_tokens kind 'app' instance tokens (NewAppToken; any member)
+// cli_tokens kind 'service' service credentials of every role, team and
+// deploy and run among them (owner-minted)
+// cli_tokens kind 'platform' per-customer credentials on a platform
+// account's customers: those the member minted
+// in person, and every one a platform
+// credential the member minted had minted
+// (endMemberPlatformDelegationTx, which a
+// demotion runs too); revoked with no permit
+// cli_tokens kind 'link' link credentials, with their links rows
+// (approved by any member who creates apps)
+// door_keys door keys (any member), by created_by, and
+// every key of the account with no recorded
+// minter (created_by '')
+// invites pending invitations the member sent (owner)
+//
+// Each is refused at its check the moment the transaction commits:
+// CLIPrincipal reads revoked_at on every request (no cache), and
+// linkPrincipalLive reads the links row. Door keys and link channels also
+// live outside this database, and their publication is durable:
+//
+// - door keys: the removal writes a member_revocations row in its own
+// transaction; drainMemberRevocations republishes the account's
+// door-key records and deletes the row only once every publish
+// landed. Each app is attempted on its own: one app that cannot
+// publish (or, in claims mode, cannot take its permit) never stops
+// another app's revoke or publish on the same pass; it only keeps the
+// row. (The row names no app: member_revocations is a non-app table,
+// which the claims census allows no app column.) The browser door
+// drains at once after the commit; the link sync loop retries until it
+// succeeds, which also covers `console member remove` on the box. A
+// console with no signing key or deployment bucket keeps the row:
+// nothing was published, so the work is not done.
+// - link channels: the links row's revoke_synced flag, which the same
+// loop already retries (syncLinkChannel).
+//
+// So a revoked door key is refused at the edge within the drain cadence
+// (10 seconds, when the immediate publish fails) plus the edge's 30-second
+// door-key record poll; a successful immediate publish leaves the poll.
+// Ten seconds is the first retry, not a bound: an app whose permit or
+// publish keeps failing keeps the row, retried with a backoff that doubles
+// to memberRevocationMaxBackoff (a minute), so a stuck row re-signs the
+// account's records at most once a minute. Each failure is the LinkSync
+// job's error on the operator pages, and once the row is older than
+// memberRevocationOverdue each failure is logged as overdue.
+//
+// A person's own CLI token (kind '') is not touched: it names no account,
+// and its reach into this one already ended with the membership.
+
+import (
+ "context"
+ "crypto/ed25519"
+ "database/sql"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "time"
+
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// memberRevocationOverdue is the age past which a queued row that still
+// fails is logged as overdue: a revocation the drain has not finished in
+// five minutes is blocked, not slow. memberRevocationMaxBackoff caps the
+// wait between a failing row's attempts.
+const (
+ memberRevocationOverdue = 5 * time.Minute
+ memberRevocationMaxBackoff = time.Minute
+)
+
+// errDoorKeyPublishUnavailable is a queued door-key publication on a
+// console with no signing key or deployment bucket: nothing was published,
+// so the row stays.
+var errDoorKeyPublishUnavailable = errors.New("console: door keys: no signing key or deployment bucket, so the record was not republished")
+
+// memberRevocation is what one removal revoked outside cli_tokens, for the
+// publish after the commit: the apps whose door-key record changed and the
+// links whose channel must be revoked.
+type memberRevocation struct {
+ doorKeyApps []string
+ links []string
+}
+
+// revokeMemberCredentialsTx revokes, inside tx, every credential address
+// minted for accountID (the list above). It never commits.
+//
+// With the host claim on (gated), cli_tokens rows that name an app and
+// door_keys are gated tables a plain transaction may not write. Then the
+// transaction revokes only what names no app (account-scoped service and
+// link credentials, links, invites) and queues the rest:
+// drainMemberRevocations revokes each app's rows under that app's own SQL
+// permit, the way every other gated write to those tables is made. Until
+// it has, the removed member's app-scoped credentials in that app still
+// resolve; the drain runs at once after a browser removal and then from
+// the link sync loop, each app on its own.
+func revokeMemberCredentialsTx(tx *sql.Tx, accountID int64, address string, now time.Time, gated bool) (memberRevocation, error) {
+ ctx := context.Background()
+ var out memberRevocation
+ appFree := ""
+ if gated {
+ appFree = " AND app = ''"
+ }
+ // Before the update below revokes the member's platform credentials:
+ // the per-customer delegation reads them by their live rows.
+ if err := endMemberPlatformDelegationTx(ctx, tx, accountID, address, now); err != nil {
+ return out, err
+ }
+ if _, err := tx.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = ?
+WHERE account_id = ? AND address = ? AND kind IN (?, ?, ?) AND revoked_at = 0`+appFree,
+ now.Unix(), accountID, address, cliKindApp, cliKindService, cliKindLink); err != nil {
+ return out, err
+ }
+ links, err := tx.QueryContext(ctx, `SELECT id FROM links WHERE account_id = ? AND created_by = ? AND revoked_at = 0 ORDER BY id`,
+ accountID, address)
+ if err != nil {
+ return out, err
+ }
+ out.links, err = scanStrings(links)
+ if err != nil {
+ return out, err
+ }
+ if _, err := tx.ExecContext(ctx, `UPDATE links SET revoked_at = ? WHERE account_id = ? AND created_by = ? AND revoked_at = 0`,
+ now.Unix(), accountID, address); err != nil {
+ return out, err
+ }
+ // A link's credential row names its approver as address, rotation
+ // included (RotateLinkToken), so the cli_tokens update above has
+ // already revoked it (a link credential names no app).
+ apps, err := memberCredentialApps(ctx, tx, accountID, address, now.Unix())
+ if err != nil {
+ return out, err
+ }
+ queue := gated && len(apps) > 0
+ if !gated {
+ for _, app := range apps {
+ keys, err := revokeMemberAppCredentials(ctx, tx, accountID, app, address, now.Unix(), now)
+ if err != nil {
+ return out, err
+ }
+ if keys {
+ out.doorKeyApps = append(out.doorKeyApps, app)
+ }
+ }
+ queue = len(out.doorKeyApps) > 0
+ }
+ if _, err := tx.ExecContext(ctx, `DELETE FROM invites WHERE account_id = ? AND invited_by = ? AND accepted_at = 0`, accountID, address); err != nil {
+ return out, err
+ }
+ if queue {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO member_revocations (account_id, address, created_at) VALUES (?, ?, ?)`,
+ accountID, address, now.Unix()); err != nil {
+ return out, err
+ }
+ }
+ return out, nil
+}
+
+// endMemberPlatformDelegationTx revokes, inside tx, the per-customer
+// credentials (kind platform) address holds through the platform account
+// accountID: those they minted in person, and every one minted by a live
+// platform credential they minted (endPlatformMintsTx). It never commits.
+//
+// A per-customer Publish credential is an owner of its customer account
+// (ownerAuthority), so it is owner reach its minter keeps only while they
+// own the platform account. Removal runs this (revokeMemberCredentialsTx),
+// and so does every demotion, in the demotion's own transaction: a
+// transfer (TransferOwnership) and a role change to member (addMemberTx;
+// the browser, AddMember and the box tool's AddMemberWrite). Review round 4.
+// The platform credentials themselves are the caller's: removal revokes
+// them, and a demotion leaves them, refused at every platform door while
+// their minter is not an owner (platformAuthorizeDoor).
+//
+// Every row it touches carries a platform_account_id, so revoking one
+// needs no permit under the claim gate (store_gate.go RevokeFree),
+// app-bound or not. On an account that is no platform it matches nothing.
+func endMemberPlatformDelegationTx(ctx context.Context, tx *sql.Tx, accountID int64, address string, now time.Time) error {
+ rows, err := tx.QueryContext(ctx, `SELECT name FROM cli_tokens
+WHERE account_id = ? AND address = ? AND kind = ? AND role = ? AND name != '' AND revoked_at = 0`,
+ accountID, address, cliKindService, string(svcrole.Platform))
+ if err != nil {
+ return err
+ }
+ names, err := scanStrings(rows)
+ if err != nil {
+ return err
+ }
+ for _, name := range names {
+ if err := endPlatformMintsTx(ctx, tx, accountID, name, now); err != nil {
+ return err
+ }
+ }
+ // Minted in person: the rows sit on the customer's account and carry
+ // the person's address.
+ _, err = tx.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = ?
+WHERE kind = ? AND platform_account_id = ? AND address = ? AND revoked_at = 0`,
+ now.Unix(), cliKindPlatform, accountID, address)
+ return err
+}
+
+// sqlExecQuery is what the per-app revocation needs from a transaction or
+// a bound view.
+type sqlExecQuery interface {
+ ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
+ QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
+}
+
+// memberCredentialApps lists the apps where address still holds a live
+// app-scoped credential in accountID minted no later than before (Unix
+// seconds): instance tokens and app-bound service credentials it minted,
+// and door keys it minted or whose minter is unknown (an empty created_by,
+// which fails safe: removing any member ends them, review round 1).
+func memberCredentialApps(ctx context.Context, q sqlExecQuery, accountID int64, address string, before int64) ([]string, error) {
+ rows, err := q.QueryContext(ctx, `SELECT app FROM cli_tokens
+WHERE account_id = ? AND address = ? AND kind IN (?, ?) AND app != '' AND revoked_at = 0 AND created_at <= ?
+UNION SELECT app FROM door_keys
+WHERE account_id = ? AND created_by IN (?, '') AND revoked_at = 0 AND created_at <= ?
+ORDER BY 1`, accountID, address, cliKindApp, cliKindService, before,
+ accountID, address, before*int64(time.Second)+int64(time.Second)-1)
+ if err != nil {
+ return nil, err
+ }
+ return scanStrings(rows)
+}
+
+// revokeMemberAppCredentials revokes, on q, address's app-scoped
+// credentials in one app minted no later than before (Unix seconds), and
+// the app's door keys with no recorded minter; it bumps the door-key
+// revision when a key went, and reports whether one did. Run inside the
+// removal's transaction, or inside the app's own permit by the drain.
+func revokeMemberAppCredentials(ctx context.Context, q sqlExecQuery, accountID int64, app, address string, before int64, now time.Time) (bool, error) {
+ if _, err := q.ExecContext(ctx, `UPDATE cli_tokens SET revoked_at = ?
+WHERE account_id = ? AND app = ? AND address = ? AND kind IN (?, ?) AND revoked_at = 0 AND created_at <= ?`,
+ now.Unix(), accountID, app, address, cliKindApp, cliKindService, before); err != nil {
+ return false, err
+ }
+ res, err := q.ExecContext(ctx, `UPDATE door_keys SET revoked_at = ?
+WHERE account_id = ? AND app = ? AND created_by IN (?, '') AND revoked_at = 0 AND created_at <= ?`,
+ now.UnixNano(), accountID, app, address, before*int64(time.Second)+int64(time.Second)-1)
+ if err != nil {
+ return false, err
+ }
+ n, err := res.RowsAffected()
+ if err != nil || n == 0 {
+ return false, err
+ }
+ if _, err := q.ExecContext(ctx, `INSERT INTO door_key_revisions (account_id, app, revision) VALUES (?, ?, 1)
+ON CONFLICT (account_id, app) DO UPDATE SET revision = revision + 1`, accountID, app); err != nil {
+ return false, err
+ }
+ return true, nil
+}
+
+// claimRawRevokeMemberAppCredentials is revokeMemberAppCredentials in one
+// transaction of its own, for the drain under the app's permit.
+func (s *Store) claimRawRevokeMemberAppCredentials(ctx context.Context, accountID int64, app, address string, before int64, now time.Time) error {
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ if _, err := revokeMemberAppCredentials(ctx, tx, accountID, app, address, before, now); err != nil {
+ return err
+ }
+ return tx.Commit()
+}
+
+// migrateMemberRevocations creates the follow-up queue. Additive and
+// idempotent, called from Store.migrate. attempts and next_at are a
+// failing row's backoff (Unix seconds; 0 is due now).
+func (s *Store) migrateMemberRevocations() error {
+ _, err := s.db.ExecContext(context.Background(), `CREATE TABLE IF NOT EXISTS member_revocations (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ account_id INTEGER NOT NULL,
+ address TEXT NOT NULL,
+ created_at INTEGER NOT NULL,
+ attempts INTEGER NOT NULL DEFAULT 0,
+ next_at INTEGER NOT NULL DEFAULT 0
+);`)
+ return err
+}
+
+// memberRevocationRow is one queued follow-up.
+type memberRevocationRow struct {
+ ID int64
+ AccountID int64
+ Address string
+ CreatedAt int64 // Unix seconds: the removal's time
+ Attempts int
+ NextAt int64 // Unix seconds: not retried before
+}
+
+// pendingMemberRevocations lists the queue, oldest first; accountID 0 is
+// every account.
+func (s *Store) pendingMemberRevocations(ctx context.Context, accountID int64) ([]memberRevocationRow, error) {
+ rows, err := s.db.QueryContext(ctx, `SELECT id, account_id, address, created_at, attempts, next_at FROM member_revocations
+WHERE ? = 0 OR account_id = ? ORDER BY id`, accountID, accountID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var out []memberRevocationRow
+ for rows.Next() {
+ var r memberRevocationRow
+ if err := rows.Scan(&r.ID, &r.AccountID, &r.Address, &r.CreatedAt, &r.Attempts, &r.NextAt); err != nil {
+ return nil, err
+ }
+ out = append(out, r)
+ }
+ return out, rows.Err()
+}
+
+// deferMemberRevocation records a failed attempt on a row: the next is
+// not before linkSyncInterval doubled per earlier failure, at most
+// memberRevocationMaxBackoff.
+func (s *Store) deferMemberRevocation(ctx context.Context, row memberRevocationRow, now time.Time) error {
+ wait := memberRevocationMaxBackoff
+ if row.Attempts < 8 {
+ wait = min(linkSyncInterval<<row.Attempts, memberRevocationMaxBackoff)
+ }
+ _, err := s.db.ExecContext(ctx, `UPDATE member_revocations SET attempts = attempts + 1, next_at = ? WHERE id = ?`,
+ now.Add(wait).Unix(), row.ID)
+ return err
+}
+
+// finishMemberRevocation deletes a drained row.
+func (s *Store) finishMemberRevocation(ctx context.Context, id int64) error {
+ _, err := s.db.ExecContext(ctx, `DELETE FROM member_revocations WHERE id = ?`, id)
+ return err
+}
+
+// drainMemberRevocations finishes queued removals: each app's revoke
+// under its own permit, then every door-key record of the row's account
+// republished (the revoke bumped the changed apps' revisions; an unchanged
+// record re-signs harmlessly). The row goes once all of it landed.
+// accountID 0 drains every account. Every app is attempted whatever another
+// app did; a row with any failure stays, retried after its backoff. The
+// errors are returned joined, each overdue one marked so.
+func (s *Server) drainMemberRevocations(ctx context.Context, accountID int64) error {
+ rows, err := s.store.pendingMemberRevocations(ctx, accountID)
+ if err != nil {
+ return fmt.Errorf("member revocations: %w", err)
+ }
+ now := time.Now()
+ var errs []error
+ for _, row := range rows {
+ if row.NextAt > now.Unix() {
+ continue
+ }
+ if err := s.finishOneMemberRevocation(ctx, row); err != nil {
+ err = fmt.Errorf("member revocation %d (account %d): %w", row.ID, row.AccountID, err)
+ if age := now.Sub(time.Unix(row.CreatedAt, 0)); age >= memberRevocationOverdue {
+ err = fmt.Errorf("%w (overdue: queued %s ago)", err, age.Round(time.Second))
+ log.Printf("console: OVERDUE %v", err)
+ }
+ errs = append(errs, err)
+ if derr := s.store.deferMemberRevocation(ctx, row, now); derr != nil {
+ errs = append(errs, derr)
+ }
+ continue
+ }
+ if err := s.store.finishMemberRevocation(ctx, row.ID); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// finishOneMemberRevocation is one row's work: the revokes the removal
+// could not make in its own transaction (with the host claim on), each
+// under its app's permit, and the account's door-key publication. Each app
+// and each publish is attempted even when another failed, so a healthy
+// app's revoke lands and is published while a blocked app keeps the row.
+// An account that is gone has nothing left to do.
+func (s *Server) finishOneMemberRevocation(ctx context.Context, row memberRevocationRow) error {
+ acct, err := s.store.AccountByID(row.AccountID)
+ if err != nil {
+ return err
+ }
+ if acct == nil {
+ return nil
+ }
+ // Only rows minted no later than the removal: a member added back
+ // since keeps what they minted after rejoining.
+ apps, err := memberCredentialApps(ctx, s.store.db, row.AccountID, row.Address, row.CreatedAt)
+ if err != nil {
+ return err
+ }
+ var errs []error
+ for _, app := range apps {
+ err := s.store.withAutoAppSQL(ctx, row.AccountID, app, "sql.RevokeMemberCredentials", func(v *Store) error {
+ return v.claimRawRevokeMemberAppCredentials(ctx, row.AccountID, app, row.Address, row.CreatedAt, time.Now())
+ })
+ if err != nil {
+ errs = append(errs, fmt.Errorf("app %s: revoke: %w", app, err))
+ }
+ }
+ keyApps, err := s.store.DoorKeyApps()
+ if err != nil {
+ return errors.Join(append(errs, err)...)
+ }
+ for _, a := range keyApps {
+ if a.AccountID != row.AccountID {
+ continue
+ }
+ if len(s.cfg.Key) != ed25519.PrivateKeySize || s.cfg.Releases == nil {
+ errs = append(errs, errDoorKeyPublishUnavailable)
+ break
+ }
+ pctx, cancel := context.WithTimeout(ctx, doorKeyPublishBudget)
+ err := s.publishDoorKeys(pctx, acct, a.App)
+ cancel()
+ if err != nil {
+ errs = append(errs, fmt.Errorf("app %s: publish: %w", a.App, err))
+ }
+ }
+ return errors.Join(errs...)
+}
+
+// scanStrings reads one string column to the end and closes rows.
+func scanStrings(rows *sql.Rows) ([]string, error) {
+ defer rows.Close()
+ var out []string
+ for rows.Next() {
+ var v string
+ if err := rows.Scan(&v); err != nil {
+ return nil, err
+ }
+ out = append(out, v)
+ }
+ return out, rows.Err()
+}
+
+// afterMemberRemoved publishes, at once, what a committed removal revoked
+// outside the database: the queued door-key records (drainMemberRevocations)
+// and each link's channel (syncLinkChannel, as unlink does). A failure here
+// is retried by the link sync loop: the queue row and revoke_synced stay.
+func (s *Server) afterMemberRemoved(r *http.Request, acct *Account, rev memberRevocation) {
+ dctx, dcancel := context.WithTimeout(context.WithoutCancel(r.Context()), doorKeyPublishBudget)
+ if err := s.drainMemberRevocations(dctx, acct.ID); err != nil {
+ log.Printf("console: door keys after member removal: %v (the link sync loop retries)", err)
+ }
+ dcancel()
+ for _, id := range rev.links {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), linkFirstSyncTimeout)
+ if err := s.syncLinkChannel(ctx, id); err != nil {
+ log.Printf("console: link %s: revoke after member removal: %v (linkSyncLoop retries)", id, err)
+ }
+ cancel()
+ }
+}
diff --git a/internal/console/memberrevoke_claim_test.go b/internal/console/memberrevoke_claim_test.go
new file mode 100644
index 000000000..006e8366f
--- /dev/null
+++ b/internal/console/memberrevoke_claim_test.go
@@ -0,0 +1,121 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+// TestClaimsModeRemovalRevokesAppCredentials (security hunt H4-M1, review
+// round 1): with the host claim on, cli_tokens and door_keys are gated
+// tables. Removing a member who minted an instance token and a door key
+// still succeeds, and both credentials stop working: the app-scoped
+// revocations take each app's own SQL permit.
+func TestClaimsModeRemovalRevokesAppCredentials(t *testing.T) {
+ cx := newClaimCase(t)
+ const kim = "kim@keymail.dev"
+ if err := cx.st.AddMember(OpsAccountID, kim, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ bearer := mintUserToken(t, cx.st, kim, time.Now())
+ status, _, out := rawReq(t, http.MethodPost, cx.ts.URL+"/api/cli/apps/bab/titogo/instance-token", bearer, `{}`)
+ if status != http.StatusCreated {
+ t.Fatalf("mint instance token = %d %s", status, out)
+ }
+ var minted struct{ Token string }
+ if err := json.Unmarshal([]byte(out), &minted); err != nil || minted.Token == "" {
+ t.Fatalf("instance token answer %s: %v", out, err)
+ }
+ status, _, out = rawReq(t, http.MethodPost, cx.ts.URL+"/api/cli/apps/bab/titogo/door-keys", bearer, `{"label":"router"}`)
+ if status != http.StatusCreated {
+ t.Fatalf("mint door key = %d %s", status, out)
+ }
+ cx.form(t, "/a/bab/members/remove", "address", kim)
+ if role, err := cx.st.Role(OpsAccountID, kim); err != nil || role != "" {
+ t.Fatalf("kim's role after removal = %q, %v; want removed", role, err)
+ }
+ if _, ok := cx.st.CLIPrincipal(minted.Token, time.Now()); ok {
+ t.Error("the removed member's instance token still resolves")
+ }
+ if keys, _, err := cx.st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || len(keys) != 0 {
+ t.Errorf("live door keys after removal = %+v, %v; want none", keys, err)
+ }
+}
+
+// TestBlockedAppDoesNotHoldBackOtherAppsRevocation (review round 2, Astra
+// P1-4 and new finding 1, Fable N2): with the host claim on, a removal
+// made by the box-side member tool queues its app revocations for the
+// link sync loop. One app under a stuck operation does not hold back
+// another: the healthy app's credentials are revoked and its door-key
+// record is republished on the same pass, the row stays (backed off) for
+// the stuck app, whose credentials go on the first pass after its
+// operation clears.
+func TestBlockedAppDoesNotHoldBackOtherAppsRevocation(t *testing.T) {
+ cx := newClaimCase(t)
+ const kim = "kim@keymail.dev"
+ if err := cx.st.AddMember(OpsAccountID, kim, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ bearer := mintUserToken(t, cx.st, kim, time.Now())
+ instance := map[string]string{}
+ for _, app := range []string{"kass", "titogo"} {
+ status, _, out := rawReq(t, http.MethodPost, cx.ts.URL+"/api/cli/apps/bab/"+app+"/instance-token", bearer, `{}`)
+ if status != http.StatusCreated {
+ t.Fatalf("mint %s instance token = %d %s", app, status, out)
+ }
+ var minted struct{ Token string }
+ if err := json.Unmarshal([]byte(out), &minted); err != nil || minted.Token == "" {
+ t.Fatalf("%s instance token answer %s: %v", app, out, err)
+ }
+ instance[app] = minted.Token
+ }
+ key := mintDoorKey(t, cx.consoleFixture, bearer)
+ if !readDoorRecord(t, cx.consoleFixture).Admits(key) {
+ t.Fatal("test bug: the minted key is not published")
+ }
+
+ // kass sorts first and is held by an operation this console does not own.
+ restore := cx.foreign(t, claimAppRef{Account: release.OpsAccount, App: "kass"})
+ if err := cx.st.MembershipTransition(cx.st.RemoveMemberWrite(OpsAccountID, kim)); err != nil {
+ t.Fatal(err)
+ }
+ err := cx.srv.linkSyncPass(context.Background())
+ if err == nil || !strings.Contains(err.Error(), "kass") || strings.Contains(err.Error(), "titogo") {
+ t.Fatalf("first pass = %v; want only kass's row failing", err)
+ }
+ if _, ok := cx.st.CLIPrincipal(instance["titogo"], time.Now()); ok {
+ t.Error("titogo's instance token still resolves while kass is blocked")
+ }
+ if keys, _, err := cx.st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || len(keys) != 0 {
+ t.Errorf("titogo's live door keys = %+v, %v; want none", keys, err)
+ }
+ if readDoorRecord(t, cx.consoleFixture).Admits(key) {
+ t.Error("titogo's door-key record still admits the removed member's key while kass is blocked")
+ }
+ if _, ok := cx.st.CLIPrincipal(instance["kass"], time.Now()); !ok {
+ t.Fatal("test bug: kass's token was revoked through a stuck operation")
+ }
+ if rows, err := cx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 1 || rows[0].NextAt <= time.Now().Unix() {
+ t.Fatalf("queue after the first pass = %+v, %v; want the row kept, backed off", rows, err)
+ }
+
+ restore()
+ // As if the row's backoff had elapsed.
+ if _, err := cx.st.db.Exec(`UPDATE member_revocations SET next_at = 0`); err != nil {
+ t.Fatal(err)
+ }
+ if err := cx.srv.linkSyncPass(context.Background()); err != nil {
+ t.Fatalf("pass after kass's operation cleared: %v", err)
+ }
+ if _, ok := cx.st.CLIPrincipal(instance["kass"], time.Now()); ok {
+ t.Error("kass's instance token still resolves after its operation cleared")
+ }
+ if rows, err := cx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 0 {
+ t.Errorf("queue after the second pass = %+v, %v; want empty", rows, err)
+ }
+}
diff --git a/internal/console/memberrevoke_test.go b/internal/console/memberrevoke_test.go
new file mode 100644
index 000000000..232c27695
--- /dev/null
+++ b/internal/console/memberrevoke_test.go
@@ -0,0 +1,597 @@
+package console
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/doorkey"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// TestRemoveMemberRevokesEveryKindTheyMinted (security hunt H4-M1): every
+// credential kind revokeMemberCredentialsTx lists, minted by the removed
+// member, is refused once the removal commits; the same kinds minted by
+// the owner, and the member's credentials in another account, are not.
+func TestRemoveMemberRevokesEveryKindTheyMinted(t *testing.T) {
+ fx := newConsoleFixture(t)
+ st := fx.st
+ now := time.Now()
+ const alice, paul = "alice@keymail.dev", "paul@keymail.dev"
+ if _, err := st.CreateAppIn(OpsAccountID, "titogo", paul, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.AddMember(OpsAccountID, alice, RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.CreateAccount(42, "bbw", "other", alice, now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateAppIn(42, "elsewhere", alice, now); err != nil {
+ t.Fatal(err)
+ }
+
+ type minted struct{ instance, service, link, linkID, door, invite string }
+ mint := func(who, tag string, accountID int64, app string) minted {
+ t.Helper()
+ var m minted
+ var err error
+ if m.instance, err = st.NewAppToken(accountID, app, who, "inst-"+tag, now); err != nil {
+ t.Fatal(err)
+ }
+ if m.service, err = st.NewServicePrincipal(accountID, "svc-"+tag, app, svcrole.Publish, who, now); err != nil {
+ t.Fatal(err)
+ }
+ tx, err := st.db.Begin()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if m.link, err = randomToken(); err != nil {
+ t.Fatal(err)
+ }
+ if m.linkID, err = mintLinkTx(tx, st.linkIDSource(), accountID, "home-"+tag, who, "", m.link, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ m.door = tag + strings.Repeat("0", 16-len(tag))
+ if _, err := st.DoorKeyInsert(accountID, app, doorkey.Entry{ID: m.door, SHA256: strings.Repeat("a", 64)}, who); err != nil {
+ t.Fatal(err)
+ }
+ if m.invite, err = st.CreateInvite(accountID, tag+"-invitee@example.com", who, now); err != nil {
+ t.Fatal(err)
+ }
+ return m
+ }
+ gone := mint(alice, "a", OpsAccountID, "titogo")
+ kept := mint(paul, "b", OpsAccountID, "titogo")
+ elsewhere := mint(alice, "c", 42, "elsewhere")
+ _, revBefore, err := st.DoorKeysLive(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := st.RemoveMember(OpsAccountID, alice); err != nil {
+ t.Fatal(err)
+ }
+
+ check := func(label string, m minted, accountID int64, app string, wantLive bool) {
+ t.Helper()
+ for kind, tok := range map[string]string{"instance token": m.instance, "service credential": m.service, "link credential": m.link} {
+ if _, ok := st.CLIPrincipal(tok, now); ok != wantLive {
+ t.Errorf("%s: %s resolves = %v, want %v", label, kind, ok, wantLive)
+ }
+ }
+ l, err := st.LinkByID(m.linkID)
+ if err != nil || l == nil {
+ t.Fatalf("%s: link %s: %+v %v", label, m.linkID, l, err)
+ }
+ if l.RevokedAt.IsZero() != wantLive {
+ t.Errorf("%s: link revoked at %v, want live %v", label, l.RevokedAt, wantLive)
+ }
+ keys, _, err := st.DoorKeysLive(accountID, app)
+ if err != nil {
+ t.Fatal(err)
+ }
+ live := false
+ for _, k := range keys {
+ live = live || k.ID == m.door
+ }
+ if live != wantLive {
+ t.Errorf("%s: door key %s live = %v, want %v", label, m.door, live, wantLive)
+ }
+ if _, ok := st.PendingInviteAddress(m.invite, now); ok != wantLive {
+ t.Errorf("%s: invite pending = %v, want %v", label, ok, wantLive)
+ }
+ }
+ check("removed member", gone, OpsAccountID, "titogo", false)
+ check("owner", kept, OpsAccountID, "titogo", true)
+ check("removed member's other account", elsewhere, 42, "elsewhere", true)
+ if _, revAfter, err := st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || revAfter <= revBefore {
+ t.Errorf("door-key revision %d -> %d (%v); a revoke must bump it so the record is re-signed", revBefore, revAfter, err)
+ }
+}
+
+// TestDoorKeyMinterBackfilledFromAudit: a key minted before created_by
+// existed takes its minter from the mint's audit row, so removing that
+// member revokes it too.
+func TestDoorKeyMinterBackfilledFromAudit(t *testing.T) {
+ fx := newConsoleFixture(t)
+ st := fx.st
+ now := time.Now()
+ if _, err := st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ const id = "0123456789abcdef"
+ if _, err := st.DoorKeyInsert(OpsAccountID, "titogo", doorkey.Entry{ID: id, SHA256: strings.Repeat("a", 64)}, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.RecordEvent(OpsAccountID, "titogo", "alice@keymail.dev", "door-key", "minted door key "+id+" for titogo (cli)", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.migrateDoorKeys(); err != nil {
+ t.Fatal(err)
+ }
+ var by string
+ if err := st.db.QueryRow(`SELECT created_by FROM door_keys WHERE id = ?`, id).Scan(&by); err != nil || by != "alice@keymail.dev" {
+ t.Fatalf("created_by = %q, %v; want the audit row's minter", by, err)
+ }
+ if err := st.RemoveMember(OpsAccountID, "alice@keymail.dev"); err != nil {
+ t.Fatal(err)
+ }
+ if keys, _, err := st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || len(keys) != 0 {
+ t.Fatalf("live keys after removing their minter = %+v, %v; want none", keys, err)
+ }
+}
+
+// pausedBody is a request body whose first Read runs pause before any
+// byte is returned: the handler has passed its membership gate and is
+// waiting on the body when pause runs.
+type pausedBody struct {
+ pause func()
+ body *strings.Reader
+ once bool
+}
+
+func (p *pausedBody) Read(b []byte) (int, error) {
+ if !p.once {
+ p.once = true
+ p.pause()
+ }
+ return p.body.Read(b)
+}
+
+// TestMintInFlightDuringRemovalLandsNothing (security hunt H4-M1, review
+// round 1): a member's instance-token and door-key mints that passed the
+// membership gate, then waited on their body while the member was
+// removed, write no credential. The insert re-reads membership itself.
+func TestMintInFlightDuringRemovalLandsNothing(t *testing.T) {
+ for _, door := range []string{"instance-token", "door-keys"} {
+ t.Run(door, func(t *testing.T) {
+ fx, member := instanceFixture(t, "code-mint-race-"+door)
+ removed := false
+ body := &pausedBody{body: strings.NewReader(`{"label":"race"}`), pause: func() {
+ if err := fx.st.RemoveMember(OpsAccountID, "alice@keymail.dev"); err != nil {
+ t.Error(err)
+ }
+ removed = true
+ }}
+ req := httptest.NewRequest(http.MethodPost, "/api/cli/apps/bab/titogo/"+door, body)
+ req.Header.Set("Authorization", "Bearer "+member)
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rec, req)
+ if !removed {
+ t.Fatalf("the handler answered %d %s before reading the body; the race was not staged", rec.Code, rec.Body)
+ }
+ if rec.Code == http.StatusCreated {
+ t.Fatalf("mint after removal = %d %s, want refusal", rec.Code, rec.Body)
+ }
+ var n int
+ q := `SELECT COUNT(*) FROM cli_tokens WHERE kind = 'app' AND address = ? AND revoked_at = 0`
+ if door == "door-keys" {
+ q = `SELECT COUNT(*) FROM door_keys WHERE created_by = ? AND revoked_at = 0`
+ }
+ if err := fx.st.db.QueryRow(q, "alice@keymail.dev").Scan(&n); err != nil || n != 0 {
+ t.Fatalf("live credentials minted by the removed member = %d (%v), want 0", n, err)
+ }
+ })
+ }
+}
+
+// mustMember makes address a member of accountID unless it already holds a
+// role there: credential mints re-read the minter's membership (H4-M1), so
+// a store-level test that mints as an address must make it a member.
+func mustMember(t *testing.T, s *Store, accountID int64, address string) {
+ t.Helper()
+ if role, err := s.Role(accountID, address); err != nil {
+ t.Fatal(err)
+ } else if role != "" {
+ return
+ }
+ if err := s.AddMember(accountID, address, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// TestRemoveMemberRevokesUnattributedDoorKeys (review round 1): a key with
+// no recorded minter (an empty created_by) fails safe: removing any member of
+// its account revokes it. Another account's unattributed key stays.
+func TestRemoveMemberRevokesUnattributedDoorKeys(t *testing.T) {
+ fx := newConsoleFixture(t)
+ st := fx.st
+ now := time.Now()
+ if _, err := st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.CreateAccount(42, "bbw", "other", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := st.CreateAppIn(42, "elsewhere", "bob@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []struct {
+ acct int64
+ app string
+ id string
+ }{{OpsAccountID, "titogo", "aaaaaaaaaaaaaaaa"}, {42, "elsewhere", "bbbbbbbbbbbbbbbb"}} {
+ if _, err := st.DoorKeyInsert(k.acct, k.app, doorkey.Entry{ID: k.id, SHA256: strings.Repeat("a", 64)}, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := st.RemoveMember(OpsAccountID, "alice@keymail.dev"); err != nil {
+ t.Fatal(err)
+ }
+ if keys, _, err := st.DoorKeysLive(OpsAccountID, "titogo"); err != nil || len(keys) != 0 {
+ t.Errorf("the account's unattributed key after a removal = %+v, %v; want revoked", keys, err)
+ }
+ if keys, _, err := st.DoorKeysLive(42, "elsewhere"); err != nil || len(keys) != 1 {
+ t.Errorf("another account's unattributed key = %+v, %v; want it live", keys, err)
+ }
+}
+
+// TestRemovalDoorKeyPublicationIsDurable (review round 1): a removal that
+// publishes nothing itself (the box-side member tool, or a browser
+// removal whose publish failed) leaves a queue row, and the link sync
+// pass republishes the record and clears the row.
+func TestRemovalDoorKeyPublicationIsDurable(t *testing.T) {
+ fx, member := instanceFixture(t, "code-revoke-durable")
+ key := mintDoorKey(t, fx, member)
+ if !readDoorRecord(t, fx).Admits(key) {
+ t.Fatal("test bug: the minted key is not published")
+ }
+ if err := fx.st.MembershipTransition(fx.st.RemoveMemberWrite(OpsAccountID, "alice@keymail.dev")); err != nil {
+ t.Fatal(err)
+ }
+ if rows, err := fx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 1 {
+ t.Fatalf("queued follow-ups = %+v, %v; want one", rows, err)
+ }
+ if !readDoorRecord(t, fx).Admits(key) {
+ t.Fatal("test bug: the record changed with no publish")
+ }
+ if err := fx.srv.linkSyncPass(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if readDoorRecord(t, fx).Admits(key) {
+ t.Error("the link sync pass did not republish the record without the removed member's key")
+ }
+ if rows, err := fx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 0 {
+ t.Errorf("queued follow-ups after the drain = %+v, %v; want none", rows, err)
+ }
+}
+
+// TestDemotedOwnersServiceLosesOwnerDoors (review round 1, Fable P2-3): a
+// service credential is held to its minter's current role at every owner
+// gate. Minted by an owner it passes; once that owner steps down to
+// member, it meets the owner gate's 403.
+func TestDemotedOwnersServiceLosesOwnerDoors(t *testing.T) {
+ fx := newConsoleFixture(t)
+ now := time.Now()
+ if _, err := fx.st.CreateAppIn(OpsAccountID, "titogo", "paul@keymail.dev", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleOwner, now); err != nil {
+ t.Fatal(err)
+ }
+ svc, err := fx.st.NewServicePrincipal(OpsAccountID, "ci", "titogo", svcrole.Publish, "alice@keymail.dev", now)
+ if err != nil {
+ t.Fatal(err)
+ }
+ detach := domainsURL(fx, "bab", "titogo") + "/nothing.example.com"
+ if code, _, out := rawReq(t, http.MethodDelete, detach, svc, ""); code != http.StatusOK {
+ t.Fatalf("owner-minted service at an owner door = %d %s, want 200", code, out)
+ }
+ if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, now); err != nil {
+ t.Fatal(err)
+ }
+ if code, _, out := rawReq(t, http.MethodDelete, detach, svc, ""); code != http.StatusForbidden {
+ t.Fatalf("a demoted owner's service at an owner door = %d %s, want 403", code, out)
+ }
+}
+
+// TestServiceMintInFlightDuringRemovalLandsNothing (review round 2, Astra
+// P1-1 / Fable N1): an owner's `carlos services create` that passed the
+// owner gate, then waited on its body while the owner was removed (or
+// stepped down to member), writes no credential. The insert re-reads the
+// minter's role in its own transaction.
+func TestServiceMintInFlightDuringRemovalLandsNothing(t *testing.T) {
+ for _, change := range []string{"removed", "demoted"} {
+ t.Run(change, func(t *testing.T) {
+ fx, _ := instanceFixture(t, "code-svc-race-"+change)
+ const alice = "alice@keymail.dev"
+ if err := fx.st.AddMember(OpsAccountID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ bearer := mintUserToken(t, fx.st, alice, time.Now())
+ changed := false
+ body := &pausedBody{body: strings.NewReader(`{"name":"ci","role":"publish","app":"titogo"}`), pause: func() {
+ var err error
+ if change == "removed" {
+ err = fx.st.RemoveMember(OpsAccountID, alice)
+ } else {
+ err = fx.st.AddMember(OpsAccountID, alice, RoleMember, time.Now())
+ }
+ if err != nil {
+ t.Error(err)
+ }
+ changed = true
+ }}
+ req := httptest.NewRequest(http.MethodPost, "/api/cli/services/bab", body)
+ req.Header.Set("Authorization", "Bearer "+bearer)
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ fx.srv.ServeHTTP(rec, req)
+ if !changed {
+ t.Fatalf("the handler answered %d %s before reading the body; the race was not staged", rec.Code, rec.Body)
+ }
+ if rec.Code == http.StatusCreated {
+ t.Fatalf("service mint after the minter was %s = %d %s, want refusal", change, rec.Code, rec.Body)
+ }
+ var n int
+ if err := fx.st.db.QueryRow(`SELECT COUNT(*) FROM cli_tokens WHERE kind = 'service' AND address = ? AND revoked_at = 0`,
+ alice).Scan(&n); err != nil || n != 0 {
+ t.Fatalf("live service credentials minted by the %s owner = %d (%v), want 0", change, n, err)
+ }
+ })
+ }
+}
+
+// TestRemovalPublicationWaitsForASigningKey (review round 2, Astra new
+// finding 4): a console with no signing key cannot republish the door-key
+// record, so the queued row stays and the pass says so; once the key is
+// back, the first pass after the row's backoff publishes and clears it. A
+// row queued past memberRevocationOverdue is reported as overdue.
+func TestRemovalPublicationWaitsForASigningKey(t *testing.T) {
+ fx, member := instanceFixture(t, "code-revoke-nokey")
+ key := mintDoorKey(t, fx, member)
+ if err := fx.st.MembershipTransition(fx.st.RemoveMemberWrite(OpsAccountID, "alice@keymail.dev")); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := fx.st.db.Exec(`UPDATE member_revocations SET created_at = ?`, time.Now().Add(-time.Hour).Unix()); err != nil {
+ t.Fatal(err)
+ }
+ signing := fx.srv.cfg.Key
+ fx.srv.cfg.Key = nil
+ err := fx.srv.linkSyncPass(context.Background())
+ if err == nil || !strings.Contains(err.Error(), "overdue") {
+ t.Fatalf("pass with no signing key = %v; want the row reported, overdue", err)
+ }
+ if rows, err := fx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 1 {
+ t.Fatalf("queue after a pass that could not publish = %+v, %v; want the row kept", rows, err)
+ }
+ fx.srv.cfg.Key = signing
+ if err := fx.srv.linkSyncPass(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if !readDoorRecord(t, fx).Admits(key) {
+ t.Fatal("a pass inside the row's backoff published; want it to wait")
+ }
+ if _, err := fx.st.db.Exec(`UPDATE member_revocations SET next_at = 0`); err != nil { // the backoff elapses
+ t.Fatal(err)
+ }
+ if err := fx.srv.linkSyncPass(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if readDoorRecord(t, fx).Admits(key) {
+ t.Error("the record still admits the removed member's key once the key is back")
+ }
+ if rows, err := fx.st.pendingMemberRevocations(context.Background(), 0); err != nil || len(rows) != 0 {
+ t.Errorf("queue after publishing = %+v, %v; want empty", rows, err)
+ }
+}
+
+// TestRemovingAPlatformOwnerEndsTheirCustomerCredentials (review round 3,
+// Astra P1 / Fable P2): removing an owner of a platform account ends the
+// per-customer credentials they minted in person and every one their own
+// platform credential minted, in the removal's transaction. Another
+// owner's platform credential, and what it minted, go on working.
+func TestRemovingAPlatformOwnerEndsTheirCustomerCredentials(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ const alice = "alice@example.com"
+ if err := fx.st.AddMember(p.ID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ person := cliToken(t, fx, alice, "code-platform-owner-removal")
+ status, out := postJSON(t, servicesURL(fx, p.Sqid), map[string]any{"name": "alice-cms", "role": "platform"}, person)
+ if status != http.StatusCreated {
+ t.Fatalf("alice's platform credential = %d %v, want 201", status, out)
+ }
+ aliceCMS, _ := out["token"].(string)
+ if _, err := fx.st.CreateAppIn(cust.ID, "site", "service:"+p.Sqid+"/cms", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ publish := map[string]any{"role": "publish"}
+ deploy := map[string]any{"role": "deploy", "app": "site", "rungs": []string{"edge"}}
+ gone := map[string]string{
+ "alice's platform credential": aliceCMS,
+ "its publish mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, aliceCMS, publish)),
+ "its deploy mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, aliceCMS, deploy)),
+ "the publish credential alice minted": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, person, publish)),
+ }
+ kept := map[string]string{
+ "the other owner's platform credential": tok,
+ "its mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, publish)),
+ }
+
+ if err := fx.st.RemoveMember(p.ID, alice); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ for what, raw := range gone {
+ if pr, ok := fx.st.CLIPrincipal(raw, now); ok {
+ t.Errorf("after alice's removal, %s resolves to %+v", what, pr)
+ }
+ }
+ for what, raw := range kept {
+ if _, ok := fx.st.CLIPrincipal(raw, now); !ok {
+ t.Errorf("after alice's removal, %s no longer resolves", what)
+ }
+ }
+}
+
+// TestDemotingAPlatformOwnerEndsTheirCustomerCredentials (review round 4):
+// an owner of a platform account who stops being an owner, by a transfer
+// or a role change, loses the per-customer credentials they minted in
+// person and every one their platform credential minted, in the demotion's
+// own transaction, as removal does: a per-customer Publish credential is an
+// owner of its customer, so leaving them live keeps owner reach after the
+// demotion. Their platform credential itself stays (it mints nothing while
+// its minter is a member), and another owner's go on working. A re-role
+// that leaves an owner an owner ends nothing.
+func TestDemotingAPlatformOwnerEndsTheirCustomerCredentials(t *testing.T) {
+ const alice, bob = "alice@example.com", "bob@example.com"
+ for _, path := range []struct {
+ name string
+ demote func(st *Store, platformID int64) error
+ }{
+ {"transfer", func(st *Store, platformID int64) error {
+ if err := st.AddMember(platformID, bob, RoleMember, time.Now()); err != nil {
+ return err
+ }
+ return st.TransferOwnership(platformID, alice, bob, time.Now())
+ }},
+ {"role change", func(st *Store, platformID int64) error {
+ return st.AddMember(platformID, alice, RoleMember, time.Now())
+ }},
+ {"box member tool", func(st *Store, platformID int64) error {
+ return st.MembershipTransition(AddMemberWrite(platformID, alice, RoleMember, time.Now()))
+ }},
+ } {
+ t.Run(path.name, func(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ if err := fx.st.AddMember(p.ID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ person := cliToken(t, fx, alice, "code-platform-owner-demotion")
+ status, out := postJSON(t, servicesURL(fx, p.Sqid), map[string]any{"name": "alice-cms", "role": "platform"}, person)
+ if status != http.StatusCreated {
+ t.Fatalf("alice's platform credential = %d %v, want 201", status, out)
+ }
+ aliceCMS, _ := out["token"].(string)
+ if _, err := fx.st.CreateAppIn(cust.ID, "site", "service:"+p.Sqid+"/cms", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ publish := map[string]any{"role": "publish"}
+ deploy := map[string]any{"role": "deploy", "app": "site", "rungs": []string{"edge"}}
+ gone := map[string]string{
+ "its publish mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, aliceCMS, publish)),
+ "its deploy mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, aliceCMS, deploy)),
+ "the publish credential alice minted": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, person, publish)),
+ }
+ kept := map[string]string{
+ "alice's platform credential": aliceCMS,
+ "the other owner's platform credential": tok,
+ "its mint": tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, publish)),
+ }
+
+ // Re-affirming an owner is not a demotion.
+ if err := fx.st.AddMember(p.ID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ for what, raw := range gone {
+ if _, ok := fx.st.CLIPrincipal(raw, time.Now()); !ok {
+ t.Fatalf("re-adding alice as an owner ended %s", what)
+ }
+ }
+
+ if err := path.demote(fx.st, p.ID); err != nil {
+ t.Fatal(err)
+ }
+ if role, err := fx.st.Role(p.ID, alice); err != nil || role != RoleMember {
+ t.Fatalf("alice's role after the %s = %q %v, want member", path.name, role, err)
+ }
+ now := time.Now()
+ for what, raw := range gone {
+ if pr, ok := fx.st.CLIPrincipal(raw, now); ok {
+ t.Errorf("after alice's %s, %s resolves to %+v", path.name, what, pr)
+ }
+ }
+ for what, raw := range kept {
+ if _, ok := fx.st.CLIPrincipal(raw, now); !ok {
+ t.Errorf("after alice's %s, %s no longer resolves", path.name, what)
+ }
+ }
+ })
+ }
+}
+
+// TestRemovingAPlatformOwnerUnderTheGateEndsTheirCustomerCredentials is
+// the same removal with the host claim's SQL gate armed: a per-customer
+// credential, app-bound or not, is revoked with no permit, so the removal
+// ends it in its own transaction rather than leaving it to a queue.
+func TestRemovingAPlatformOwnerUnderTheGateEndsTheirCustomerCredentials(t *testing.T) {
+ s, _, _ := sqlIngestFixture(t)
+ ctx := context.Background()
+ p := newPlatform(t, s, "bcd")
+ grantPlatform(t, s, p)
+ if _, err := s.db.ExecContext(ctx, `UPDATE accounts SET platform = 'bcd', platform_ref = 'census' WHERE id = ?`, gateAcct); err != nil {
+ t.Fatal(err)
+ }
+ const alice = "alice@example.com"
+ if err := s.AddMember(p, alice, RoleOwner, platformNow); err != nil {
+ t.Fatal(err)
+ }
+ platformTok, err := s.NewServicePrincipal(p, "alice-cms", "", svcrole.Platform, alice, platformNow)
+ if err != nil {
+ t.Fatal(err)
+ }
+ minter, ok := s.CLIPrincipal(platformTok, time.Now())
+ if !ok {
+ t.Fatal("platform credential does not resolve")
+ }
+ now := time.Now()
+ viaService, _, err := s.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{CustomerID: gateAcct, PlatformAccountID: p,
+ Generation: minter.PlatformGeneration, Minter: minter, MinterTokenHash: hashToken(platformTok), Name: "alice-cms",
+ MintedBy: "service:bcd/alice-cms", Role: svcrole.Deploy, App: "blog", Rungs: []string{"edge"}}, now)
+ if err != nil {
+ t.Fatalf("gated mint by the platform credential: %v", err)
+ }
+ inPerson, _, err := s.NewPlatformCustomerCredential(ctx, PlatformCredentialRequest{CustomerID: gateAcct, PlatformAccountID: p,
+ Generation: minter.PlatformGeneration, Minter: Principal{Kind: PrincipalUser, Address: alice}, Name: alice,
+ MintedBy: alice, Role: svcrole.Publish}, now)
+ if err != nil {
+ t.Fatalf("gated mint in person: %v", err)
+ }
+
+ if err := s.RemoveMember(p, alice); err != nil {
+ t.Fatalf("RemoveMember under the gate = %v", err)
+ }
+ for what, raw := range map[string]string{"platform credential": platformTok, "its deploy mint": viaService, "alice's own mint": inPerson} {
+ if tokenRevokedAt(t, s, hashToken(raw)) == 0 {
+ t.Errorf("%s not revoked by the removal", what)
+ }
+ if pr, ok := s.CLIPrincipal(raw, time.Now()); ok {
+ t.Errorf("%s resolves to %+v after the removal", what, pr)
+ }
+ }
+}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 16834ade4..548eb2b95 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -29,12 +29,12 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-// handleRemoveMember drops someone's membership. Owner-only, CSRF-checked and
-// step-up gated, in that order: a non-owner must meet the byte-identical 404
-// before step-up is ever mentioned, or the redirect itself would confirm the
-// account exists.
+// handleRemoveMember drops someone's membership. Session, CSRF, owner and
+// step-up, in that order (review round 1): a non-owner meets the
+// byte-identical 404 before step-up is ever mentioned, or the redirect
+// itself would confirm the account exists.
func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, ok := s.owner(w, r)
+ addr, raw, acct, role, ok := s.account(w, r)
if !ok {
return
}
@@ -42,6 +42,10 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
s.renderMessage(w, r, http.StatusForbidden, "Refused", "Cross-site request blocked.")
return
}
+ if role != RoleOwner {
+ http.NotFound(w, r) // owner()'s answer for a member
+ return
+ }
if !s.requireFreshAuth(w, r, addr, raw) {
return
}
@@ -49,14 +53,18 @@ func (s *Server) handleRemoveMember(w http.ResponseWriter, r *http.Request) {
// Under the member lock (plans 6b), so it and an accept or an invite
// are one after the other.
unlock := s.lockMembers(acct.Sqid)
+ var rev memberRevocation
err := s.membershipTransition(r.Context(), acct, time.Now(), func(tx *sql.Tx) error {
- return removeMemberTx(tx, acct.ID, target)
+ var err error
+ rev, err = removeMemberRevokingTx(tx, acct.ID, target, s.store.gate != nil)
+ return err
})
unlock()
if err != nil {
log.Printf("console: remove member: %v", err)
s.setFlash(w, "err", removalAdvice(err, target))
} else {
+ s.afterMemberRemoved(r, acct, rev)
s.setFlash(w, "ok", target+" is no longer a member of this account.")
}
http.Redirect(w, r, "/a/"+acct.Sqid+"/team", http.StatusSeeOther)
@@ -874,6 +882,11 @@ func (s *Store) TransferOwnership(accountID int64, from, to string, now time.Tim
RoleMember, accountID, from); err != nil {
return err
}
+ // The demoted owner's per-customer delegation goes with the role, in
+ // the same commit (review round 4).
+ if err := endMemberPlatformDelegationTx(context.Background(), tx, accountID, from, now); err != nil {
+ return err
+ }
return tx.Commit()
}
diff --git a/internal/console/plancaps_doors_test.go b/internal/console/plancaps_doors_test.go
index d83938067..e4117afbb 100644
--- a/internal/console/plancaps_doors_test.go
+++ b/internal/console/plancaps_doors_test.go
@@ -188,7 +188,7 @@ func TestInstanceCreateRefusedAtTheRunningThingsCap(t *testing.T) {
}
func TestFirstRouteAttachRefusedAtTheRunningThingsCap(t *testing.T) {
- fx, token := instanceFixture(t, "code-cap-firstroute")
+ fx, token := domainOwnerFixture(t, "code-cap-firstroute")
shipVersion(t, fx, "titogo", "v1")
seedChannel(t, fx, "titogo", "canary/live", "v1")
acct := atRunningCap(t, fx, 3)
@@ -363,7 +363,7 @@ func TestFleetCreateRefusedOnAPlanWithoutFleets(t *testing.T) {
}
func TestCustomDomainRefusedOnAFreePlan(t *testing.T) {
- fx, member := instanceFixture(t, "code-cap-domain")
+ fx, member := domainOwnerFixture(t, "code-cap-domain")
shipVersion(t, fx, "titogo", "v1")
seedChannel(t, fx, "titogo", "canary/live", "v1")
fx.srv.cfg.PlanCatalog = examplePlanCatalog(t)
@@ -382,7 +382,7 @@ func TestCustomDomainRefusedOnAFreePlan(t *testing.T) {
}
func TestFleetsAndDomainsWithoutACatalogUnchanged(t *testing.T) {
- fx, member := instanceFixture(t, "code-cap-domain-nocat")
+ fx, member := domainOwnerFixture(t, "code-cap-domain-nocat")
if code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "titogo"), member, `{"host":"tickets.example.com","route":"go.tito.io"}`); code != http.StatusOK {
t.Fatalf("alias attach with no catalog = %d %s", code, out)
}
diff --git a/internal/console/planmembers_test.go b/internal/console/planmembers_test.go
index 14fb8d94d..2cba431e9 100644
--- a/internal/console/planmembers_test.go
+++ b/internal/console/planmembers_test.go
@@ -68,7 +68,7 @@ func removeMembers(t *testing.T, fx *consoleFixture, acct *Account, now time.Tim
t.Helper()
err := fx.srv.membershipTransition(context.Background(), acct, now, func(tx *sql.Tx) error {
for _, a := range addrs {
- if err := removeMemberTx(tx, acct.ID, a); err != nil {
+ if _, err := removeMemberRevokingTx(tx, acct.ID, a, fx.st.gate != nil); err != nil {
return err
}
}
@@ -322,7 +322,7 @@ func TestMemberCountExcludesInvitesAndServices(t *testing.T) {
if _, err := fx.st.CreateInvite(acct.ID, "invited@example.com", "owner@example.com", planNow); err != nil {
t.Fatal(err)
}
- if _, err := fx.st.NewServicePrincipal(acct.ID, "svc", "", svcrole.Publish, "owner@example.com", planNow); err != nil {
+ if _, err := fx.st.NewServicePrincipal(acct.ID, "svc", "", svcrole.Publish, "owner"+acct.Sqid+"@example.com", planNow); err != nil {
t.Fatal(err)
}
if n := memberCount(t, fx, acct.ID); n != 2 {
diff --git a/internal/console/platform_credentials.go b/internal/console/platform_credentials.go
index 21c57b492..ef1bbe2d7 100644
--- a/internal/console/platform_credentials.go
+++ b/internal/console/platform_credentials.go
@@ -42,7 +42,8 @@ var (
// ErrPlatformAuthorityEnded is a mint whose authority was gone by the
// time its insert transaction ran: the grant generation ended, the
// customer's link ended, or the minter lost its own authority (its
- // platform credential revoked, or the person no longer an owner).
+ // platform credential revoked, or the person, or the person who minted
+ // that platform credential, no longer an owner).
// Nothing is written.
ErrPlatformAuthorityEnded = errors.New("console: the platform's grant or the minter's authority ended during the request")
// errPlatformCredentialNoApp is a Deploy mint whose app the customer no
@@ -199,8 +200,10 @@ VALUES (?, ?, '', '', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, '', '', ?, ?)`,
// own row (by credential id) is a live platform credential of this platform
// at req.Generation, and still holds the secret the request authenticated
// with (req.MinterTokenHash: a rotation replaces it, a revoke sets
-// revoked_at, and either ends the mint); a person is an owner of the
-// platform account. Any other principal holds nothing.
+// revoked_at, and either ends the mint), and the person who minted that
+// credential (its address) is still an owner of the platform account
+// (review round 3, Astra P2); a person is an owner of the platform
+// account. Any other principal holds nothing.
func platformMinterHolds(ctx context.Context, tx *sql.Tx, req PlatformCredentialRequest, now time.Time) (bool, error) {
var one int
var err error
@@ -209,11 +212,12 @@ func platformMinterHolds(ctx context.Context, tx *sql.Tx, req PlatformCredential
if req.Minter.CredentialID == "" || req.MinterTokenHash == "" {
return false, nil
}
- err = tx.QueryRowContext(ctx, `SELECT 1 FROM cli_tokens WHERE credential_id = ? AND token_hash = ? AND kind = ?
+ err = tx.QueryRowContext(ctx, `SELECT 1 FROM cli_tokens t WHERE credential_id = ? AND token_hash = ? AND kind = ?
AND role = ? AND account_id = ? AND platform_account_id = ? AND platform_generation = ? AND revoked_at = 0
- AND (expires_at = 0 OR expires_at >= ?)`,
+ AND (expires_at = 0 OR expires_at >= ?)
+ AND EXISTS (SELECT 1 FROM memberships m WHERE m.account_id = t.account_id AND m.address = t.address AND m.role = ?)`,
req.Minter.CredentialID, req.MinterTokenHash, cliKindService, string(svcrole.Platform), req.PlatformAccountID,
- req.PlatformAccountID, req.Generation, now.Unix()).Scan(&one)
+ req.PlatformAccountID, req.Generation, now.Unix(), RoleOwner).Scan(&one)
case PrincipalUser:
if req.Minter.Address == "" {
return false, nil
diff --git a/internal/console/platform_credentials_test.go b/internal/console/platform_credentials_test.go
index 0b8c581cc..3e04484ba 100644
--- a/internal/console/platform_credentials_test.go
+++ b/internal/console/platform_credentials_test.go
@@ -954,7 +954,7 @@ func TestUnknownTokenKindStillRefused(t *testing.T) {
}
func TestPersonalTokenListOmitsCustomerCredentials(t *testing.T) {
- fx, p, _, cust := customerWorld(t, "free")
+ fx, p, cms, cust := customerWorld(t, "free")
addr := "owner" + p.Sqid + "@example.com"
owner := cliToken(t, fx, addr, "code-customer-cred-list")
raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, owner, map[string]any{"role": "publish"}))
@@ -973,8 +973,18 @@ func TestPersonalTokenListOmitsCustomerCredentials(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- if len(tokens) != 1 || tokens[0].ID != hashToken(owner) {
- t.Fatalf("CLITokens(%s) = %+v, want the person's own terminal alone", addr, tokens)
+ // The person's terminal and the platform credential cms they minted
+ // (platformToken mints as the platform's owner); never the customer
+ // credential.
+ ids := make([]string, 0, len(tokens))
+ for _, tk := range tokens {
+ ids = append(ids, tk.ID)
+ }
+ slices.Sort(ids)
+ want := []string{hashToken(owner), hashToken(cms)}
+ slices.Sort(want)
+ if !slices.Equal(ids, want) {
+ t.Fatalf("CLITokens(%s) = %+v, want the person's own terminal and cms alone", addr, tokens)
}
}
@@ -1319,3 +1329,122 @@ func TestCustomerDeployCredentialEndsWithItsApp(t *testing.T) {
wantEnded(t, fx, "while site is trashed", cust.Sqid, "site", raw)
})
}
+
+// TestDemotedOwnersPlatformCredentialMintsNothing (review round 3, Astra
+// P2): a platform credential is held to its minter's current role, as a
+// person is. Once its minter steps down to member it mints no per-customer
+// credential, whether the demotion lands before the request or while the
+// mint waits on its insert.
+func TestDemotedOwnersPlatformCredentialMintsNothing(t *testing.T) {
+ fx, p, _, cust := customerWorld(t, "free")
+ const alice = "alice@example.com"
+ if err := fx.st.AddMember(p.ID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ person := cliToken(t, fx, alice, "code-demoted-platform-minter")
+ status, out := postJSON(t, servicesURL(fx, p.Sqid), map[string]any{"name": "alice-cms", "role": "platform"}, person)
+ if status != http.StatusCreated {
+ t.Fatalf("alice's platform credential = %d %v, want 201", status, out)
+ }
+ aliceCMS, _ := out["token"].(string)
+ customerCredential(t, fx, p.Sqid, cust.Sqid, aliceCMS, map[string]any{"role": "publish"})
+
+ demote := func() {
+ if err := fx.st.AddMember(p.ID, alice, RoleMember, time.Now()); err != nil {
+ t.Error(err)
+ }
+ }
+ demote()
+ status, out, _ = mintCustomerCredential(t, fx.ts.URL, p.Sqid, cust.Sqid, aliceCMS, map[string]any{"role": "publish"})
+ wantPlatformError(t, "a demoted owner's platform credential", status, out, http.StatusForbidden, "door.not_owner")
+ if n := customerCredentialRows(t, fx.st, cust.ID); n != 1 {
+ t.Fatalf("kind platform rows = %d, want only the mint made while alice was an owner", n)
+ }
+
+ // Demoted while the mint waits: the door admitted it, and the insert
+ // transaction's re-check refuses it.
+ if err := fx.st.AddMember(p.ID, alice, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var mu sync.Mutex
+ var cur *seamGate
+ set := func(g *seamGate) { mu.Lock(); cur = g; mu.Unlock() }
+ fx.srv.platformCredentialBeforeInsert = func() {
+ mu.Lock()
+ g := cur
+ mu.Unlock()
+ if g != nil {
+ g.block()
+ }
+ }
+ status, out, _ = pausedMint(t, fx, set, p.Sqid, cust.Sqid, aliceCMS, demote)
+ wantPlatformError(t, "a platform credential whose minter is demoted during the mint", status, out, http.StatusForbidden, "door.revoked")
+ if n := customerCredentialRows(t, fx.st, cust.ID); n != 1 {
+ t.Fatalf("kind platform rows = %d after the paused mint, want 1", n)
+ }
+}
+
+// TestCustomerPublishCredentialIsTheCustomersOwner (review round 3, Paul's
+// ruling): a live per-customer Publish credential counts as an owner at the
+// customer account's owner-only doors, so a platform keeps attaching and
+// detaching domains for a customer nobody has claimed (platform accounts
+// spec §6.2, §7). A door the browser also holds behind a step-up is not
+// one of them (round 4): deleting an app (owner plus passkey), a temporary
+// app's TTL (a delete by another door) and turning an instance's password
+// off refuse it before anything changes.
+func TestCustomerPublishCredentialIsTheCustomersOwner(t *testing.T) {
+ fx, p, tok, cust := customerWorld(t, "free")
+ raw := tokenIn(t, customerCredential(t, fx, p.Sqid, cust.Sqid, tok, map[string]any{"role": "publish"}))
+ if status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+cust.Sqid+"/new", raw, `{"name":"site"}`); status/100 != 2 {
+ t.Fatalf("create site = %d %s", status, body)
+ }
+ detach := domainsURL(fx, cust.Sqid, "site") + "/nothing.example.com"
+ if status, _, body := rawReq(t, http.MethodDelete, detach, raw, ""); status != http.StatusOK {
+ t.Fatalf("detach with the customer's publish credential = %d %s, want 200", status, body)
+ }
+ if ok, err := fx.st.CreateTemporaryAppIn(cust.ID, "tmp-site", "service:"+p.Sqid+"/cms", time.Now(), time.Now().Add(time.Hour)); err != nil || !ok {
+ t.Fatalf("CreateTemporaryAppIn = %v %v", ok, err)
+ }
+ life := func(app string) AppLife {
+ t.Helper()
+ l, err := fx.st.AppLife(cust.ID, app)
+ if err != nil || l == nil {
+ t.Fatalf("AppLife(%s) = %+v %v", app, l, err)
+ }
+ return *l
+ }
+ for _, step := range []struct{ what, app, tail, body string }{
+ {"delete site", "site", "/delete", ""},
+ {"set tmp-site's TTL", "tmp-site", "/ttl", `{"ttl_seconds":172800}`},
+ } {
+ before := life(step.app)
+ status, _, body := rawReq(t, http.MethodPost, fx.ts.URL+"/api/cli/apps/"+cust.Sqid+"/"+step.app+step.tail, raw, step.body)
+ if status != http.StatusForbidden {
+ t.Errorf("%s with the customer's publish credential = %d %s, want 403 (a step-up door)", step.what, status, body)
+ }
+ if after := life(step.app); after != before {
+ t.Errorf("%s refused, but %s changed: %+v, was %+v", step.what, step.app, after, before)
+ }
+ }
+ if trashed, err := fx.st.HasTrashedAppIn(cust.ID, "site"); err != nil || trashed {
+ t.Errorf("site in the Trash = %v %v after a refused delete", trashed, err)
+ }
+
+ pr, ok := fx.st.CLIPrincipal(raw, time.Now())
+ if !ok {
+ t.Fatal("the customer credential does not resolve")
+ }
+ if !fx.srv.ownerAuthority(pr, cust) {
+ t.Error("ownerAuthority refuses the customer's publish credential")
+ }
+ if fx.srv.stepUpOwnerAuthority(pr, cust) {
+ t.Error("the step-up owner rule admits the customer's publish credential")
+ }
+ // Not on any other account: the platform's own, or another customer.
+ c2 := secondCustomer(t, fx, p, tok)
+ for _, acct := range []*Account{p, c2} {
+ if fx.srv.ownerAuthority(pr, acct) {
+ t.Errorf("ownerAuthority admits the customer's credential on %s", acct.Sqid)
+ }
+ }
+}
diff --git a/internal/console/regional_writers_test.go b/internal/console/regional_writers_test.go
index 533c8e47b..5b9ffed02 100644
--- a/internal/console/regional_writers_test.go
+++ b/internal/console/regional_writers_test.go
@@ -121,6 +121,7 @@ func newShopApp(t *testing.T, fx *consoleFixture) {
// list leaves it out, and the claim is untouched.
func TestTeamScopeRefusesRegionalClaim(t *testing.T) {
w := newTeamWorld(t, "code-team-regional")
+ ownerMintsServices(t, w.fx)
const host = "shop.example.com"
putRegionalClaim(t, w.fx.rel, host, "bab", "titogo", "mine.go.tito.io", false, false)
raw, etag := regionalClaimBytes(t, w.fx.rel, host)
@@ -140,7 +141,8 @@ func TestTeamScopeRefusesRegionalClaim(t *testing.T) {
}
// Attach: a hostname this app holds for a route out of the team's
// scope answers as taken, the same bytes as any other holder's.
- attachDomain(t, w.fx, w.member, "theirs.example.com", "theirs.go.tito.io")
+ owner := cliToken(t, w.fx, "paul@keymail.dev", "code-team-regional-owner") // attach is owner-only (H4-M7)
+ attachDomain(t, w.fx, owner, "theirs.example.com", "theirs.go.tito.io")
wantStatus, _, want := rawReq(t, http.MethodPost, w.url("/domains"), w.team, attachBody("theirs.example.com", "mine.go.tito.io"))
if wantStatus != http.StatusConflict {
t.Fatalf("attach over an out-of-scope claim = %d %s", wantStatus, want)
@@ -176,7 +178,7 @@ func TestTeamScopeRefusesRegionalClaim(t *testing.T) {
// other route is 409 with RD-26's text, and writes nothing. The paths door
// answers the same 409.
func TestAttachOnARegionalClaim(t *testing.T) {
- fx, member := instanceFixture(t, "code-rd-attach")
+ fx, member := domainOwnerFixture(t, "code-rd-attach")
newShopApp(t, fx)
const host = "shop.example.com"
putRegionalClaim(t, fx.rel, host, "bab", "shop", rdHomeHost, false, false)
@@ -271,7 +273,7 @@ func TestFirstRouteAttachOnARegionalHostWritesNoRecord(t *testing.T) {
// writes nothing; the same values are a 200 that writes nothing, audits
// nothing and bumps no serial.
func TestSetDomainCapabilitiesRefusesARegionalChangeBeforeDNS(t *testing.T) {
- fx, member := instanceFixture(t, "code-rd-caps")
+ fx, member := domainOwnerFixture(t, "code-rd-caps")
newShopApp(t, fx)
fx.srv.delegationZone = "acme.example.org"
var lookups atomic.Int32
@@ -464,6 +466,7 @@ func TestTeamScopeHoldsForTheClaimRevisionServed(t *testing.T) {
clock = useLifetimesClock(t)
}
w := newTeamWorld(t, "code-team-race")
+ ownerMintsServices(t, w.fx)
if c.lifetimesOn {
turnLifetimesOn(t, w.fx.srv, clock)
}
diff --git a/internal/console/seedholdreview_test.go b/internal/console/seedholdreview_test.go
index 3b2a06445..3e2115a99 100644
--- a/internal/console/seedholdreview_test.go
+++ b/internal/console/seedholdreview_test.go
@@ -78,6 +78,8 @@ func TestDomainDetachRefusesHeldFleetFileSeed(t *testing.T) {
mode := map[bool]string{false: "lifetimes off", true: "lifetimes on"}[on]
t.Run(mode+", the CLI door", func(t *testing.T) {
fx, member, _ := holdWorld(t, on)
+ // Detach is the owner's at the CLI door too (security hunt H4-M7).
+ makeOwner(t, fx, "alice@keymail.dev")
code, _, out := rawReq(t, http.MethodDelete, domainsURL(fx, "bab", "titogo")+"/"+holdHost, member, "")
if code != http.StatusConflict || errorOf(t, out) != held {
t.Fatalf("detach = %d %s, want 409 %q", code, out, held)
diff --git a/internal/console/seedslice3review_test.go b/internal/console/seedslice3review_test.go
index b48bd5e26..3629ccbb1 100644
--- a/internal/console/seedslice3review_test.go
+++ b/internal/console/seedslice3review_test.go
@@ -23,6 +23,8 @@ import (
// box's rollback and the finish, lets the trash through.
func TestTrashAppRefusesHeldFleetFileSeed(t *testing.T) {
f := newFleetFileFixture(t)
+ // Trash is the owner's at the CLI door too (security hunt H4-M2).
+ makeOwner(t, f.fx, "alice@keymail.dev")
ctx := context.Background()
id := f.fleetSeedRecord(t, fileHost, seeds.StateAborted, "", "", time.Now())
trash := func() (int, string) {
diff --git a/internal/console/store.go b/internal/console/store.go
index 8ad175e5d..51356dc11 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -744,6 +744,8 @@ func (s *Store) migrateFeatures() error {
s.migratePendingChanges,
// Door keys' own tables (doorkeys_store.go), for the same reason.
s.migrateDoorKeys,
+ // Member removals' follow-up queue (memberrevoke.go), same reason.
+ s.migrateMemberRevocations,
// Plans 4a's cap state (plangrace_store.go), for the same reason.
s.migratePlanGrace,
// The app policy's revision and recorded content (apppolicy_store.go),
@@ -1631,6 +1633,11 @@ func addMemberTx(tx *sql.Tx, accountID int64, address, role string, now time.Tim
if err := lastOwnerGuard(tx, accountID, address); err != nil {
return err
}
+ // A member holds no owner reach through a platform account's
+ // customers: a demoted owner's goes now (review round 4).
+ if err := endMemberPlatformDelegationTx(context.Background(), tx, accountID, address, now); err != nil {
+ return err
+ }
}
_, err := tx.Exec(`INSERT INTO memberships (account_id, address, role, added_at)
VALUES (?, ?, ?, ?)
@@ -1646,25 +1653,41 @@ func (s *Store) RemoveMember(accountID int64, address string) error {
return err
}
defer tx.Rollback()
- if err := removeMemberTx(tx, accountID, address); err != nil {
+ if _, err := removeMemberRevokingTx(tx, accountID, address, s.gate != nil); err != nil {
return err
}
return tx.Commit()
}
-// removeMemberTx is RemoveMember inside the caller's transaction (a
-// MembershipTransition write). It never commits.
-func removeMemberTx(tx *sql.Tx, accountID int64, address string) error {
+// removeMemberRevokingTx is RemoveMember inside the caller's transaction
+// (a MembershipTransition write; it never commits), answering what it
+// revoked: every credential the member minted for the account goes in the same
+// transaction (revokeMemberCredentialsTx, security hunt H4-M1), and the
+// caller publishes the door keys and link channels after the commit.
+//
+// gated is the host claim's SQL gate being on (Store.gate): then the
+// app-scoped revocations are queued for the drain (revokeMemberCredentialsTx).
+func removeMemberRevokingTx(tx *sql.Tx, accountID int64, address string, gated bool) (memberRevocation, error) {
if err := lastOwnerGuard(tx, accountID, address); err != nil {
- return err
+ return memberRevocation{}, err
+ }
+ rev, err := revokeMemberCredentialsTx(tx, accountID, address, time.Now(), gated)
+ if err != nil {
+ return memberRevocation{}, err
}
- if _, err := tx.Exec(`DELETE FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
+ return rev, removeMembershipRowsTx(tx, accountID, address)
+}
+
+// removeMembershipRowsTx deletes the membership and the member's own rows.
+func removeMembershipRowsTx(tx *sql.Tx, accountID int64, address string) error {
+ ctx := context.Background()
+ if _, err := tx.ExecContext(ctx, `DELETE FROM app_stars WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
return err
}
- if _, err := tx.Exec(`DELETE FROM getting_started_marks WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
+ if _, err := tx.ExecContext(ctx, `DELETE FROM getting_started_marks WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
return err
}
- _, err := tx.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`,
+ _, err := tx.ExecContext(ctx, `DELETE FROM memberships WHERE account_id = ? AND address = ?`,
accountID, address)
return err
}
@@ -1675,10 +1698,15 @@ func AddMemberWrite(accountID int64, address, role string, now time.Time) func(*
return func(tx *sql.Tx) error { return addMemberTx(tx, accountID, address, role, now) }
}
-// RemoveMemberWrite is removeMemberTx as a MembershipTransition write, for
-// the box-side membership tool (cmd/console).
-func RemoveMemberWrite(accountID int64, address string) func(*sql.Tx) error {
- return func(tx *sql.Tx) error { return removeMemberTx(tx, accountID, address) }
+// RemoveMemberWrite is removeMemberRevokingTx as a MembershipTransition write, for
+// the box-side membership tool (cmd/console). A method so the write knows
+// whether s's host claim gate is on.
+func (s *Store) RemoveMemberWrite(accountID int64, address string) func(*sql.Tx) error {
+ gated := s.gate != nil
+ return func(tx *sql.Tx) error {
+ _, err := removeMemberRevokingTx(tx, accountID, address, gated)
+ return err
+ }
}
// lastOwnerGuard refuses a change that would leave an account with no owner.
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index fb1a12a65..ca10127d3 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -290,6 +290,7 @@ var claimSQLTables = map[string]claimSQLTable{
"move_log_outbox": {NonApp: "a moves audit outbox that stores no app name: rows are keyed by host, move and entry and bound to an instance incarnation, verified against the host's claim and record at every write, written only by the moves recovery and log passes, and purged with the incarnation"},
"edge_proof_seen": {NonApp: "single-row edge proof marker"},
"cli_auth_requests": {NonApp: "device-code logins in flight, keyed by code hash"},
+ "member_revocations": {NonApp: "member removals whose credential follow-up has not finished, keyed by account and address; names no app and grants nothing: the drain republishes door-key records and revokes through each app's own permit"},
"links": {NonApp: "linked deployments, keyed by link id and bound to an account; names no app"},
"step_ups": {NonApp: "passkey step-up marks, keyed by session hash"},
"claim_sql_identity": {NonApp: "private receipt database identity"},
diff --git a/internal/console/subdomains_test.go b/internal/console/subdomains_test.go
index ec015685c..1e74aa2c0 100644
--- a/internal/console/subdomains_test.go
+++ b/internal/console/subdomains_test.go
@@ -27,6 +27,7 @@ import (
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/svcrole"
)
const (
@@ -56,6 +57,16 @@ func nsShopFixture(t *testing.T, code string) (fx *consoleFixture, member, opera
return fx, cliToken(t, fx, nsActor, code), cliToken(t, fx, "ops@example.com", code+"-ops")
}
+// nsAttacher is a publish-role credential for shop, minted by an owner: a
+// caller the CLI domain doors admit (they are owner-only, security hunt
+// H4-M7) that is no platform operator, as every owner of the ops account
+// is. The namespace refusals below exempt no operator either way.
+func nsAttacher(t *testing.T, fx *consoleFixture) string {
+ t.Helper()
+ ownerMintsServices(t, fx)
+ return serviceToken(t, fx.st, OpsAccountID, "ns-attacher", "shop", svcrole.Publish)
+}
+
// nsNobodysCopy is the create refusal for a label no account holds, under
// the apps domain: team and www can never be names (team is a short
// sqid-shaped word, www is reserved), so they get the answer that says to
@@ -320,6 +331,7 @@ func TestCreateUnderUnassignedLabelRefused(t *testing.T) {
// approved other-account copy.
func TestCreateUnderOtherAccountsNameRefused(t *testing.T) {
fx, member, operator := nsShopFixture(t, "code-ns-other")
+ attacher := nsAttacher(t, fx)
route := nsShopRoute(fx)
nsAccount(t, fx, 82, "bdq")
nsHold(t, fx, "harbour", "bdq")
@@ -343,13 +355,13 @@ func TestCreateUnderOtherAccountsNameRefused(t *testing.T) {
door, token, body string
want int
}{
- {"API alias", member, attachBody(host, route), http.StatusBadRequest},
- {"API first route", member, attachBodyKind(host, "", "static", ""), http.StatusBadRequest},
- {"API wildcard and catchall", member, `{"host":"` + host + `","route":"` + route + `","wildcard":true,"catchall":true}`, http.StatusBadRequest},
+ {"API alias", attacher, attachBody(host, route), http.StatusBadRequest},
+ {"API first route", attacher, attachBodyKind(host, "", "static", ""), http.StatusBadRequest},
+ {"API wildcard and catchall", attacher, `{"host":"` + host + `","route":"` + route + `","wildcard":true,"catchall":true}`, http.StatusBadRequest},
{"platform door", operator, platformAttachBody(host, route), http.StatusBadRequest},
{"one-label platform door", operator, platformAttachBody("harbour."+nsApps, route), http.StatusBadRequest},
- {"instance catch-all on the name", member, `{"host":"*.harbour.` + nsApps + `"}`, http.StatusBadRequest},
- {"instance catch-all under the name", member, `{"host":"*.` + host + `"}`, http.StatusBadRequest},
+ {"instance catch-all on the name", operator, `{"host":"*.harbour.` + nsApps + `"}`, http.StatusBadRequest},
+ {"instance catch-all under the name", operator, `{"host":"*.` + host + `"}`, http.StatusBadRequest},
} {
if code, _, out := rawReq(t, http.MethodPost, u, c.token, c.body); code != c.want {
t.Errorf("%s = %d %s, want %d", c.door, code, out, c.want)
@@ -410,7 +422,8 @@ func TestPlacementsUnderOtherAccountsNameRefused(t *testing.T) {
// never a name) and marina are both nobody's; marina is then given to the
// account, and its catch-all goes through.
func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
- fx, member, _ := nsShopFixture(t, "code-ns-catchall")
+ fx, _, operator := nsShopFixture(t, "code-ns-catchall")
+ attacher := nsAttacher(t, fx)
route := nsShopRoute(fx)
enableInstances(t, fx, "shop", nsShopManifest("shop.example.com"))
ctx := context.Background()
@@ -419,12 +432,13 @@ func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
for _, label := range []string{"team", "marina"} {
parent := label + "." + nsApps
unassigned := nsNobodysCopy(label)
- code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"`+route+`","wildcard":true,"catchall":true}`)
+ code, _, out := rawReq(t, http.MethodPost, u, attacher, `{"host":"`+parent+`","route":"`+route+`","wildcard":true,"catchall":true}`)
if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
t.Errorf("wildcard and catchall on %s = %d %s, want 422 %q", parent, code, out, unassigned)
}
noClaim(t, fx, parent)
- code, _, out = rawReq(t, http.MethodPost, u, member, `{"host":"*.`+parent+`"}`)
+ // An instance catch-all is a person's act: the operator, an owner.
+ code, _, out = rawReq(t, http.MethodPost, u, operator, `{"host":"*.`+parent+`"}`)
if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
t.Errorf("instance catch-all on *.%s = %d %s, want 422 %q", parent, code, out, unassigned)
}
@@ -439,7 +453,7 @@ func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
if _, err := domains.SetClaimCapabilities(ctx, fx.rel, parent, fx.sqid, "shop", true, false); err != nil {
t.Fatal(err)
}
- code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"`+route+`","catchall":true}`)
+ code, _, out := rawReq(t, http.MethodPost, u, attacher, `{"host":"`+parent+`","route":"`+route+`","catchall":true}`)
if code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != unassigned {
t.Errorf("catchall on the existing %s = %d %s, want 422 %q", parent, code, out, unassigned)
}
@@ -447,7 +461,7 @@ func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
`{"host":"` + parent + `","route":"` + route + `","wildcard":true}`,
`{"host":"` + parent + `","route":"` + route + `"}`,
} {
- if code, _, out := rawReq(t, http.MethodPost, u, member, body); code != http.StatusOK {
+ if code, _, out := rawReq(t, http.MethodPost, u, attacher, body); code != http.StatusOK {
t.Errorf("re-attach unchanged %s = %d %s, want 200", body, code, out)
}
}
@@ -473,7 +487,7 @@ func TestCatchallUnderUnassignedLabelRefused(t *testing.T) {
// Once marina is the account's, the catch-all is its to turn on.
nsHold(t, fx, "marina", fx.sqid)
- if code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+parent+`","route":"`+route+`","catchall":true}`); code != http.StatusOK {
+ if code, _, out := rawReq(t, http.MethodPost, u, attacher, `{"host":"`+parent+`","route":"`+route+`","catchall":true}`); code != http.StatusOK {
t.Errorf("catchall once marina is the account's = %d %s, want 200", code, out)
}
if c, err := domains.GetClaim(ctx, fx.rel, parent); err != nil || !c.Catchall {
@@ -854,7 +868,8 @@ func TestPendingCatchallClaimNotVerifiedUnderUnassignedLabel(t *testing.T) {
// that is not the account's it is refused, before any DNS gate, and the
// claim is unchanged.
func TestWildcardBesideLegacyCatchallRefused(t *testing.T) {
- fx, member, _ := nsShopFixture(t, "code-ns-wildcard")
+ fx, _, _ := nsShopFixture(t, "code-ns-wildcard")
+ attacher := nsAttacher(t, fx)
route := nsShopRoute(fx)
ctx := context.Background()
// The wildcard gate would pass: a delegation zone and the right CNAME
@@ -869,7 +884,7 @@ func TestWildcardBesideLegacyCatchallRefused(t *testing.T) {
for _, host := range []string{"marina." + nsApps, "x.marina." + nsApps} {
nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: host, Account: fx.sqid, App: "shop", Route: route,
CreatedAt: "2026-11-11T00:00:00Z", Catchall: true})
- code, _, out := rawReq(t, http.MethodPost, u, member, `{"host":"`+host+`","route":"`+route+`","wildcard":true}`)
+ code, _, out := rawReq(t, http.MethodPost, u, attacher, `{"host":"`+host+`","route":"`+route+`","wildcard":true}`)
if want := nsNobodysCopy("marina"); code != http.StatusUnprocessableEntity || cutoverErrorOf(out) != want {
t.Errorf("wildcard on beside the legacy catch-all %s = %d %s, want 422 %q", host, code, out, want)
}
@@ -980,7 +995,8 @@ func TestRestoreUnderUnassignedLabelRefused(t *testing.T) {
// a catch-all on, at the attach door (the policy answer) or at the
// capability core (the other-account answer).
func TestCapabilityChangeUnderOtherAccountsNameRefused(t *testing.T) {
- fx, member, _ := nsShopFixture(t, "code-ns-cap-other")
+ fx, _, _ := nsShopFixture(t, "code-ns-cap-other")
+ attacher := nsAttacher(t, fx)
route := nsShopRoute(fx)
nsAccount(t, fx, 82, "bdq")
nsHold(t, fx, "harbour", "bdq")
@@ -988,7 +1004,7 @@ func TestCapabilityChangeUnderOtherAccountsNameRefused(t *testing.T) {
host := "x.harbour." + nsApps
nsPutClaim(t, fx, domains.Claim{Schema: 1, Host: host, Account: fx.sqid, App: "shop", Route: route,
CreatedAt: "2026-11-11T00:00:00Z", Wildcard: true})
- code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "shop"), member, `{"host":"`+host+`","route":"`+route+`","catchall":true}`)
+ code, _, out := rawReq(t, http.MethodPost, domainsURL(fx, "bab", "shop"), attacher, `{"host":"`+host+`","route":"`+route+`","catchall":true}`)
if code != http.StatusBadRequest || cutoverErrorOf(out) != "that hostname is platform-managed" {
t.Errorf("catchall at the attach door = %d %s, want 400 platform-managed", code, out)
}
diff --git a/internal/console/svcfixture_test.go b/internal/console/svcfixture_test.go
index f771faeab..7630c36e4 100644
--- a/internal/console/svcfixture_test.go
+++ b/internal/console/svcfixture_test.go
@@ -19,6 +19,7 @@ func serviceToken(t *testing.T, st *Store, accountID int64, name, app string, ro
// scope is "alta", which teamToken takes a caller's choice of.
return teamToken(t, st, accountID, name, app, "alta")
}
+ defer mintAsOwner(t, st, accountID, "paul@example.test")()
raw, err := st.NewServicePrincipal(accountID, name, app, role, "paul@example.test", time.Now())
if err != nil {
t.Fatalf("NewServicePrincipal(%q): %v", name, err)
@@ -30,9 +31,55 @@ func serviceToken(t *testing.T, st *Store, accountID int64, name, app string, ro
// its bearer: serviceToken for the one role that takes a scope.
func teamToken(t *testing.T, st *Store, accountID int64, name, app, scope string) string {
t.Helper()
+ defer mintAsOwner(t, st, accountID, "paul@example.test")()
raw, err := st.NewServicePrincipalWithScopeContext(context.Background(), accountID, name, app, svcrole.Team, nil, nil, scope, "paul@example.test", time.Now())
if err != nil {
t.Fatalf("NewServicePrincipalWithScope(%q): %v", name, err)
}
return raw
}
+
+// ownerMintsServices makes serviceToken's and teamToken's minter an owner
+// of the ops account: every owner gate holds a service credential to its
+// minter's current role (review round 1), so a test that drives an
+// owner-only door with a fixture credential needs an owner to have minted
+// it. A service is never a platform operator, whatever its minter is.
+func ownerMintsServices(t *testing.T, fx *consoleFixture) {
+ t.Helper()
+ makeOwner(t, fx, "paul@example.test")
+}
+
+// mustMintingOwner makes address an owner of accountID when it holds no
+// membership there, and reports whether it did: a service credential mint
+// re-reads its minter's role and refuses anyone but an owner (security
+// hunt H4-M1, review round 2). A member is left a member, so a test that
+// mints as one meets the refusal.
+func mustMintingOwner(t *testing.T, s *Store, accountID int64, address string) bool {
+ t.Helper()
+ if role, err := s.Role(accountID, address); err != nil {
+ t.Fatal(err)
+ } else if role != "" {
+ return false
+ }
+ if err := s.AddMember(accountID, address, RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ return true
+}
+
+// mintAsOwner is mustMintingOwner for one mint: the returned func, run
+// after the mint, deletes the membership row it added (by hand, so nothing
+// is revoked), leaving the world's members as the test made them. A test
+// that drives an owner gate with the credential makes its minter an owner
+// itself (ownerMintsServices).
+func mintAsOwner(t *testing.T, s *Store, accountID int64, address string) func() {
+ t.Helper()
+ if !mustMintingOwner(t, s, accountID, address) {
+ return func() {}
+ }
+ return func() {
+ if _, err := s.db.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`, accountID, address); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
diff --git a/internal/console/svcpage.go b/internal/console/svcpage.go
index 34f30f91e..481903607 100644
--- a/internal/console/svcpage.go
+++ b/internal/console/svcpage.go
@@ -373,6 +373,12 @@ func (s *Server) handleServiceCreatePage(w http.ResponseWriter, r *http.Request)
}
secret, err := s.store.NewServicePrincipalWithScopeContext(r.Context(), acct.ID, name, app, role, r.Form["rungs"], commands, teamScope, addr, time.Now())
if err != nil {
+ // Removed, or stepped down, while the request was in flight: the
+ // owner gate's 404, as a fresh request gets.
+ if errors.Is(err, errMinterNotMember) || errors.Is(err, errMinterNotOwner) {
+ http.NotFound(w, r)
+ return
+ }
// The sentinel, not a string match: a name collision is the owner's
// to fix and a busy database is not.
if errors.Is(err, ErrServiceNameTaken) {
diff --git a/internal/console/svcpage_test.go b/internal/console/svcpage_test.go
index 407d6b093..3fde1ab86 100644
--- a/internal/console/svcpage_test.go
+++ b/internal/console/svcpage_test.go
@@ -576,7 +576,11 @@ func TestPersonalSettingsRefusesAnAppTokenRevokeAfterRemoval(t *testing.T) {
t.Fatalf("CLITokens = %d rows %v, want the app token", len(toks), err)
}
id := toks[0].ID
- if err := fx.st.RemoveMember(otherID, "paul@keymail.dev"); err != nil {
+ // The membership ends WITHOUT RemoveMember's revocation (security hunt
+ // H4-M1 now revokes what a removed member minted): a token that
+ // survived a removal made before that, which this door must still
+ // refuse to let its old minter revoke.
+ if _, err := fx.st.db.Exec(`DELETE FROM memberships WHERE account_id = ? AND address = ?`, otherID, "paul@keymail.dev"); err != nil {
t.Fatal(err)
}
diff --git a/internal/console/svcprincipal.go b/internal/console/svcprincipal.go
index 7730f6ec9..47980319c 100644
--- a/internal/console/svcprincipal.go
+++ b/internal/console/svcprincipal.go
@@ -376,6 +376,28 @@ func (s *Store) claimRawNewServicePrincipal(accountID int64, name, app string, r
return s.NewServicePrincipalScoped(accountID, name, app, role, nil, nil, mintedBy, now)
}
+// minterIsOwnerTx is the service mint's re-check of its minter, inside
+// tx: errMinterNotMember when address holds no membership in accountID,
+// errMinterNotOwner when it holds one that is not owner.
+func minterIsOwnerTx(tx *sql.Tx, accountID int64, address string) error {
+ var role string
+ err := tx.QueryRowContext(context.Background(), `SELECT role FROM memberships WHERE account_id = ? AND address = ?`, accountID, address).Scan(&role)
+ if errors.Is(err, sql.ErrNoRows) {
+ return errMinterNotMember
+ }
+ if err != nil {
+ return err
+ }
+ if role != RoleOwner {
+ return errMinterNotOwner
+ }
+ return nil
+}
+
+// errMinterNotOwner is a service credential mint refused because its minter
+// is no longer an owner of the account by the time the row would be written.
+var errMinterNotOwner = errors.New("console: the minter is not an owner of the account")
+
// The team mint rules (design §2, §5), the deploy rules' twin: a team
// credential names one app and a canonical scope; a scope on any other
// role is refused.
@@ -478,6 +500,13 @@ func (s *Store) claimRawNewServicePrincipalScoped(accountID int64, name, app str
return "", err
}
defer tx.Rollback()
+ // Both mint doors are owner-only, so the minter's role is re-read here,
+ // in the insert's transaction (security hunt H4-M1, review round 2): a
+ // mint that passed the owner gate cannot land after its minter was
+ // removed or stepped down to member.
+ if err := minterIsOwnerTx(tx, accountID, mintedBy); err != nil {
+ return "", err
+ }
var count int
if err := tx.QueryRow(`SELECT COUNT(*) FROM cli_tokens WHERE kind = ? AND account_id = ? AND name = ? AND revoked_at = 0`,
cliKindService, accountID, name).Scan(&count); err != nil {
diff --git a/internal/console/svcprincipal_run_test.go b/internal/console/svcprincipal_run_test.go
index 09486f4b4..470aeede0 100644
--- a/internal/console/svcprincipal_run_test.go
+++ b/internal/console/svcprincipal_run_test.go
@@ -244,6 +244,7 @@ func TestCredentialIDBackfillIsIdempotent(t *testing.T) {
t.Fatal(err)
}
now := time.Now()
+ mustMintingOwner(t, st, 1, "paul@example.test") // a mint re-reads the minter's role (H4-M1)
svc, err := st.NewServicePrincipalScoped(1, "pub", "hello", svcrole.Publish, nil, nil, "paul@example.test", now)
if err != nil {
t.Fatal(err)
diff --git a/internal/console/svcprincipal_test.go b/internal/console/svcprincipal_test.go
index 2ab0ebc13..631861d55 100644
--- a/internal/console/svcprincipal_test.go
+++ b/internal/console/svcprincipal_test.go
@@ -17,6 +17,9 @@ func mustAccount(t *testing.T, s *Store, name string) *Account {
if err := s.CreateAccount(id, name, name, "paul@keymail.dev", time.Now()); err != nil {
t.Fatalf("CreateAccount(%q): %v", name, err)
}
+ // The tests here mint as serviceMinter, and a service mint re-reads
+ // its minter's role (H4-M1 review round 2): make it an owner.
+ mustMintingOwner(t, s, id, serviceMinter)
return &Account{ID: id, Sqid: name, Name: name}
}
@@ -26,6 +29,7 @@ func TestCLIPrincipalLegacyAppTokenIsInstanceRole(t *testing.T) {
s := openTestStore(t)
now := time.Now()
acct := mustAccount(t, s, "legacy")
+ mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1)
raw, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now)
if err != nil {
t.Fatalf("NewAppToken: %v", err)
@@ -206,6 +210,7 @@ func TestServicePrincipalsListsBothKinds(t *testing.T) {
if _, err := s.NewServicePrincipal(acct.ID, "hub", "", svcrole.Publish, "paul@example.test", now); err != nil {
t.Fatalf("NewServicePrincipal: %v", err)
}
+ mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1)
if _, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now); err != nil {
t.Fatalf("NewAppToken: %v", err)
}
@@ -244,6 +249,7 @@ func TestRotateAndRevokeIgnoreLegacyNamelessRows(t *testing.T) {
s := openTestStore(t)
now := time.Now()
acct := mustAccount(t, s, "amadan")
+ mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now)
if err != nil {
t.Fatalf("NewAppToken: %v", err)
@@ -268,6 +274,7 @@ func TestRevokeAccountTokenScopesByAccountNotAddress(t *testing.T) {
now := time.Now()
acct := mustAccount(t, s, "amadan")
other := mustAccount(t, s, "other")
+ mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now)
if err != nil {
t.Fatalf("NewAppToken: %v", err)
@@ -616,6 +623,7 @@ func TestRevokeAccountTokenSoftRevokesNotDeletes(t *testing.T) {
s := openTestStore(t)
now := time.Now()
acct := mustAccount(t, s, "amadan")
+ mustMember(t, s, acct.ID, "paul@example.test") // a mint re-reads the minter's membership (H4-M1)
app, err := s.NewAppToken(acct.ID, "titogo", "paul@example.test", "router", now)
if err != nil {
t.Fatalf("NewAppToken: %v", err)
diff --git a/internal/console/svcscope_test.go b/internal/console/svcscope_test.go
index 03c9493d7..52f295022 100644
--- a/internal/console/svcscope_test.go
+++ b/internal/console/svcscope_test.go
@@ -194,6 +194,7 @@ func TestAppsListForAServiceIsItsOwnScope(t *testing.T) {
}
// A legacy kind='app' credential is a service principal too, and reads
// the same way here — its scope is its one app.
+ mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1)
legacy, err := fx.st.NewAppToken(OpsAccountID, "two", serviceMinter, "router", now)
if err != nil {
t.Fatal(err)
@@ -270,6 +271,7 @@ func TestServiceAuditActorIsNotABareAddress(t *testing.T) {
// move — it is the exact failure mode the collapse could have introduced.
func TestLegacyBindingWithNoAppIsNotAWildcard(t *testing.T) {
fx := newConsoleFixture(t)
+ mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1)
raw, err := fx.st.NewAppToken(OpsAccountID, "", serviceMinter, "bound to nothing", time.Now())
if err != nil {
t.Fatal(err)
@@ -313,6 +315,7 @@ func TestEnableStaysAHumanAct(t *testing.T) {
fx, _ := instanceFixture(t, "code-scope-enable-human")
fx.srv.cfg.AppsDomain = "oncarlos.test"
named := serviceToken(t, fx.st, OpsAccountID, "hub", "titogo", svcrole.Instance)
+ mustMember(t, fx.st, OpsAccountID, serviceMinter) // a mint re-reads the minter's membership (H4-M1)
legacy, err := fx.st.NewAppToken(OpsAccountID, "titogo", serviceMinter, "router", time.Now())
if err != nil {
t.Fatal(err)
@@ -450,7 +453,12 @@ func TestAppScopedServiceCannotClaimANewApp(t *testing.T) {
// walls are not confused for one — if the role table ever put `instance`
// on this door, THIS is the assertion that would move, and the guard
// above is what would then be doing the work.
- legacy, err := fx.st.NewAppToken(OpsAccountID, "one", serviceMinter, "router", time.Now())
+ // Any member may mint one, and the mint re-reads the minter's
+ // membership (H4-M1). A minter of its own: serviceMinter stays no
+ // member, so serviceToken below can make it the owner its mint needs.
+ const legacyMinter = "router@example.test"
+ mustMember(t, fx.st, OpsAccountID, legacyMinter)
+ legacy, err := fx.st.NewAppToken(OpsAccountID, "one", legacyMinter, "router", time.Now())
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/teamdoors_test.go b/internal/console/teamdoors_test.go
index 5a044df84..d3a9381e1 100644
--- a/internal/console/teamdoors_test.go
+++ b/internal/console/teamdoors_test.go
@@ -582,9 +582,11 @@ func TestTeamRestartScopeDoor(t *testing.T) {
// with Route "" is out of scope at every door.
func TestTeamDomainDoors(t *testing.T) {
w := newTeamWorld(t, "code-team-domains")
+ ownerMintsServices(t, w.fx)
ctx := context.Background()
// A member's claims: one on theirs, one first-route claim (Route "").
- attachDomain(t, w.fx, w.member, "theirs.example.com", "theirs.go.tito.io")
+ owner := cliToken(t, w.fx, "paul@keymail.dev", "code-team-domains-owner") // attach is owner-only (H4-M7)
+ attachDomain(t, w.fx, owner, "theirs.example.com", "theirs.go.tito.io")
if _, _, err := domains.AttachClaim(ctx, w.fx.rel, domains.Claim{Host: "first.example.com", Account: "bab", App: "titogo"}); err != nil {
t.Fatal(err)
}
diff --git a/internal/provision/ffr_census_test.go b/internal/provision/ffr_census_test.go
index b133f42a1..6c1c70ca0 100644
--- a/internal/provision/ffr_census_test.go
+++ b/internal/provision/ffr_census_test.go
@@ -20,12 +20,22 @@ package provision
// becomes csrfFormOK) and, in handleBrowserRestart and handleInstanceRetry,
// the confirm card's csrf field (raw becomes csrfToken(raw)). Which records
// they write, and how, is unchanged; class and kinds are as before.
+//
+// sec-h4-member-doors re-pins three console units whose only change is an
+// owner gate before any write (security hunt H4-M7, H4-M12):
+// handleAPIDomainAttach calls apiOwnerOnly after domainsGate;
+// handleAPIInstanceUpdate refuses a non-owner's gate:"" (apiOwnerOnly);
+// handleAppGate refuses a member's clear (404) and asks requireFreshAuth
+// before a clear's write. Which records they write, and how, is unchanged;
+// class and kinds are as before.
func ffrWriteCensusInventory() []censusEntry {
entries := append([]censusEntry(nil), omrRunWriteCensusInventory()...)
for _, r := range []censusEntry{
{"internal/host/startuptiming.go", "opCountingStore.Put", "record-transport", "def:Put,sel:Put", "3c40a2e5877b6d0bc189d8d5bf1229d7eafd08dd70655773f1ea9ff75c62ebc5"},
{"internal/host/startuptiming.go", "dirCountingStore.PutFrom", "record-transport", "def:PutFrom,sel:PutFrom", "90b82a86936f37c9dd53d3afd6c5d9ebbaab9df6e8d2b883a69dcf52a125b2fc"},
- {"internal/console/appsettings.go", "Server.handleAppGate", "record-writer", "key:UpdateRecord", "1e53ebef92fd70db108d2714e09e9e9f9742fc96c63aa86c663bf41684f7cb69"},
+ {"internal/console/appsettings.go", "Server.handleAppGate", "record-writer", "key:UpdateRecord", "262bf3d96c9b9236c735122c5a2f1e43bc28e515ab6178da5424e1307ef976b0"},
+ {"internal/console/apidomains.go", "Server.handleAPIDomainAttach", "key-site", "lit:instances", "10b12e14c4a2d26d767d0b6c4d81f0245e67c47dd974d392f856d452dfb9e74e"},
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceUpdate", "record-writer", "key:UpdateRecord", "2ba3c3eab8f66a3902d8c9634e2f33bac640384cdf8a1dd92a2e402342cd8ae4"},
{"internal/console/appsettings.go", "Server.handleAppRateLimit", "record-writer", "key:UpdateRecord", "9e34ff9f2347c591ce0b4668b385b2edd4c2d8dd2a3a535a870becdc33842516"},
{"internal/console/browserrestart.go", "Server.handleBrowserRestart", "key-site", "lit:instances", "d1f4000a3212a5124bafb0c1275228b1648bf6cf4cefe8ba27fcace6ad03534e"},
{"internal/console/browserretry.go", "Server.handleInstanceRetry", "key-site", "lit:instances", "871e5a4672eedc5bd8b80b42ed34e424b3031adde25f1b779125e8b5eca28658"},
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index a50e82c25..c9acabb5b 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 := s3Polling3WriteCensusInventory()
+ inventory := secH4MemberDoorsWriteCensusInventory()
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_h4_member_doors_census_test.go b/internal/provision/sec_h4_member_doors_census_test.go
new file mode 100644
index 000000000..81a67f32a
--- /dev/null
+++ b/internal/provision/sec_h4_member_doors_census_test.go
@@ -0,0 +1,34 @@
+package provision
+
+// secH4MemberDoorsWriteCensusInventory is the record-write census for branch
+// sec-h4-member-doors, layered on s3Polling3WriteCensusInventory
+// (main's newest; the inventory TestPlan9B8RecordWriteCensus used before this layer). Two
+// console units are re-pinned; class and kinds are unchanged, no unit is
+// added or moved:
+//
+// - Server.handleAPIDomainAttach: apiOwnerOnly runs after domainsGate,
+// before any write. Still key-site, lit:instances.
+// - Server.handleAPIInstanceUpdate: a non-owner's gate:"" is refused
+// (apiOwnerOnly) before the write. Still record-writer, key:UpdateRecord.
+func secH4MemberDoorsWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), s3Polling3WriteCensusInventory()...)
+ for _, r := range []censusEntry{
+ {"internal/console/apidomains.go", "Server.handleAPIDomainAttach", "key-site", "lit:instances", "e0ca35fb3ce6c70c710342af322aff219dff05bc89b98db32f3a40198a11964e"},
+ {"internal/console/apiinstances.go", "Server.handleAPIInstanceUpdate", "record-writer", "key:UpdateRecord", "cf112a7ad9622435b35ad06cb1ba5bda9f199eee5481973ed48f2db225347996"},
+ } {
+ replaced := false
+ for i, e := range entries {
+ if e.File == r.File && e.Unit == r.Unit {
+ if e.Class != r.Class || e.Kinds != r.Kinds {
+ panic("sec-h4-member-doors census: classification changed for " + r.File + ":" + r.Unit)
+ }
+ entries[i], replaced = r, true
+ break
+ }
+ }
+ if !replaced {
+ panic("sec-h4-member-doors census: re-pin of an unlisted unit " + r.File + ":" + r.Unit)
+ }
+ }
+ return entries
+}