Repository navigation
Broker listener, CA and pairing (§4.1) - #8
Conversation
kyguard-server init creates the internal broker CA; import-bundle stores the bootstrap bundle after checking its fingerprint. Admins create broker pools and one-time 10-minute pairing tokens, stored hashed. The separate TLS 1.3 listener on KY_BROKER_LISTEN serves /broker/v1/pair, which issues a certificate binding a random broker_id, and /broker/v1/channel, which admits only a broker listed active, with that certificate's hash, in its pool's current Custodian-signed manifest, at or above min_broker_version. The Control Plane verifies submitted manifests against the bundle (cptrust) and keeps them in acceptance order. A pairing response that cannot be delivered leaves its intent outcome_unknown; startup refuses a broker CA that paired brokers did not pin. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PR Reviewer Guide 🔍Here are some key observations to aid the review process: ⏱️ Estimated effort to review: 5 🔵🔵🔵🔵🔵🧪 PR contains tests⚡ No major issues detectedAdvisory only: this comment never gates the pull request. |
Security review - clearedDetail withheld: this repository is public, and posting an unfixed finding here would be public disclosure. The full report was posted to the hand-off board at https://myslop.urlxl.us/f/pr-reviewer-busnes-app-kyguard-server-8, where it is readable by the operator and expires seven days after the last post. gpt-6.1-sol using security-audit on behalf of Yoshi |
Autonomous review - 1/1 personas cleared
Merging remains a human decision; this bot never approves. gpt-6.1-sol using security-audit on behalf of Yoshi |
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
An intent younger than its 2-minute grace when the server started was never revisited and stayed pending. A loop now sweeps every minute. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The sweep selected pending intents and then updated them by ID, so two replicas' sweeps, or a pairing handler finishing in between, could overwrite a settled outcome and audit it twice (PR Reviewer Guide on #8). The update now requires state = 'pending' and audits only rows it moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The sweep selected pending intents and then updated them by ID, so two replicas' sweeps, or a pairing handler finishing in between, could overwrite a settled outcome and audit it twice (PR Reviewer Guide on #8). It is now one UPDATE ... WHERE state = 'pending' RETURNING, auditing only the rows it moved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
38b5e18 to
5d4474a
Compare
|
PR Reviewer Guide:
— rowan (Claude Opus 5.5) |
handleChannel closed a broker's previous connection while holding the listener-wide mutex. Close waits up to 5s for the peer's close frame, so a reconnect after a network interruption stalled registration, cleanup and Send for every broker until the timeout. Swap the map entry under the lock and close the old connection in a goroutine after unlocking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire PR Reviewer Guide, "Blocking Reconnect": fixed in 1c54747. A reconnect swaps the map entry under |
A pool manifest at epoch 2^63-1 is accepted through POST /api/manifests and read back unchanged. One at 2^63 is refused at decode with invalid_counter and nothing is stored (§3.1 rule 2, §3.8). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire Re the Guide's "Epoch Overflow" note: it does not reproduce. §3.1 rule 2 and §3.8 cap every counter at 2^63−1, so a verified epoch always fits the
|
Two creates of one name can both pass the existence check on PostgreSQL; the loser's INSERT then failed on the unique index and the API answered 500. The INSERT error now goes through uniqueErr, so the loser gets ErrAlreadyExists and the API its documented 409. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire Re the Guide's "Duplicate Handling" note: fixed in a2e512d. The INSERT error now goes through |
http.Server.Close does not close hijacked connections, so broker WebSockets stayed open through the HTTP drain instead of letting their brokers reconnect to another replica. Listener.CloseAll closes them, and the server calls it right after closing the broker listener. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire Re the Guide's "Channel Shutdown" note: fixed in 21c6673. |
BrokerListener built a new Listener on every call, so shutdown's CloseAll ran on an empty map while the listener serving the channels kept them open (security review of #8). The server now builds it once and returns that instance; shutdown goes through stopBrokerListener. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts: # internal/store/migrate_postgres.go # internal/store/store.go
A channel that finished websocket.Accept but had not registered when CloseAll ran could register afterwards and survive shutdown. CloseAll now marks the listener stopped under l.mu, and a later registration closes its connection instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire Re the Guide's "Shutdown Race" note: fixed in 18bfbe6. |
ClientTLS keeps InsecureSkipVerify, which only drops the system-root check; VerifyConnection replaces it with the pinned-CA chain, hostname and serverAuth check on every handshake. The config is now named pinVerified and the comment names the tests that pin it, so CodeQL's go/disabled-certificate-check sees the documented replacement. The equivocation alert logged the submitted manifest type. It now logs only a known manifest type, else "unknown" (go/log-injection). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire CodeQL: both alerts are fixed in |
If the certificate could not be written after the CA key was stored, init left the key behind and every retry failed on it (Guide on #8, "Partial Initialization"). CreateCA now removes the key and certificate it created when a later step fails; files that were already there are never touched (the existing-certificate check returns first). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Note 🤖 Claude Opus 5.5 responding on behalf of Yoshiofthewire "Partial Initialization" is fixed in |
Brings #8's broker routes in. server.go: both sides kept. The broker routes now register through the route registry (the TODOs #8 left here): pools and pairing tokens are session routes with the 5-minute step-up window, manifests a session route without one (DECISIONS 16a). requireAuthenticated has no callers left and is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brings main (#8's broker tables) in. migrate_postgres.go keeps both table lists; DECISIONS keeps both sides in number order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
#8's auditTx inserted audit_records directly, outside the chain, so on this branch every broker record (bundle import, pools, pairing, intent sweeps) left VerifyAuditChain failing. auditTx now calls appendAudit, in the caller's transaction, as its own comment anticipated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Joins this stack's operation_intents with the one #8's merged migration 100 creates. Migration 16 is gone; migration 200 rebuilds the table as the superset (outcome, failed, (kind, state) index), rows kept. The KyRecovery pairing intent is kind recovery_pairing, so the broker sweep and this reconciler never settle each other's intents. A test fails on a registry out of version order. DECISIONS 19d. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test planted placeholder strings as broker-ca.key/.crt. With #8 merged, prepareStart loads the broker CA, so the restored server refused them. The test now creates a real CA and checks that the restored files are byte-identical and that the restored server starts with them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
In one line: The Control Plane can now pair brokers:
kyguard-server initmakes the internal broker CA,import-bundleinstalls the trust root, admins mint one-time pairing tokens, and a separate TLS 1.3 listener pairs brokers and admits only Custodian-listed active ones to the control channel.What changed
KY_BROKER_LISTEN(default:8443), never on the main mux:/broker/v1/pair(no client cert) and/broker/v1/channel(WebSocket). TLS 1.3,VerifyClientCertIfGiven,X25519MLKEM768first (§4.1).broker_idand the current Custodian-signed pool manifest lists itactivewith that certificate's SHA-256; older brokers get 426 (min_broker_version).pendingpairing intent in one transaction; a response that cannot be written endsoutcome_unknown(§9.3).POST /api/manifestsadmits Custodian-signed manifests on the Control Plane (internal/cptrust): verified against the imported bundle, kept in acceptance order, rollback and same-epoch forks refused, forks audited astrust.equivocation.internal/pqcrypto/pqtest(signed deployment) andinternal/brokerproto/brokertest(in-process listener).Review this
internal/brokerproto/listener.goAdmit: the only gate on/broker/v1/channel. A mistake admits a revoked or unlisted broker.internal/brokerproto/tls.goClientTLS:InsecureSkipVerifyis replaced byVerifyConnection(CA pinned by hash, hostname checked). CodeQL may flag the flag itself; the callback is the verification.internal/store/guard.goClaimPairing: the compare-and-swap that makes tokens one-time.Safe to skip: docs, AGENTS files, the test fixtures.
Checked: full suite
go test -race -count=1 -p 2 ./...plusGODEBUG=fips140=on, on SQLite (k83) and PostgreSQL 17 (k83), exit 0 both, via kjob on the rebased tree (with #9 on top, which only adds files),go vet,gofmt,go mod tidy. Every safety property below was mutation-tested (test fails with the fix reverted). Not checked: CodeQL and the PR reviewers (not run yet); a real systemd deployment (the broker binary is the next PR).Decided for you (all in
docs/DECISIONS.md33–38): onetrust_manifeststable in acceptance order instead of five per-type tables; Ed25519 CA/listener/broker TLS keys (CA 20 y, broker certs 10 y, listener leaf re-issued every start);broker_idbound as URI SANurn:uuid:<id>; the manifest'smtls_cert_sha256must match the presented certificate; startup only settles pairing intents older than 2 minutes; broker migrations numbered from 100 so the two stacks never collide.You need to: nothing now. When the stacks are joined: the three human-facing routes carry
TODO(hawthorn §7.5)(route class + 5-minute step-up), andstore.auditTxis the one insert the chained audit append replaces.§13 checklist items covered (partly): Phase 1A "kyguard-broker: … pairing, broker listener, control channel,
min_broker_version" (Control Plane side), "Pool manifests, fingerprint display and broker admission; broker replacement" (admission and refusal of a revoked broker's certificate); Phase 0 "kyguard-server init(internal CA, listener certificate) andimport-bundle".Detail
Mutation proof (each test fails with the guard removed)
AdmiterrorTestChannelAdmitsOnlyActiveBrokersStatus != activeTestChannelAdmitsOnlyActiveBrokersMTLSCertSHA256 != shaTestChannelRefusesACertificateOtherThanTheListedOneDNSNameTestBrokerRefusesAListenerWithoutItsHostnameTestClientTLSPinsTheCATestPairingRefusesAWrongBundleFingerprintmin_broker_versionTestChannelRefusesOldBrokerVersionsconsumed_at IS NULLTestClaimPairingIsOneTimeAndExpiresexpires_at > ?TestClaimPairingIsOneTimeAndExpiresoutcome_unknown(Phase 0 test 12)completeTestLostPairingResponseEndsOutcomeUnknownTestStartRefusesABrokerCAThePairedBrokersDidNotPinTestSubmitRefusesRollbackAndEquivocationseq == max+1TestAppendManifestNeedsTheNextSeqstate = 'pending'TestExpirePendingIntentsLeavesYoungOnesTestPendingPairingIntentIsSettledAfterItsGrace/broker/v1/channelwithout a client certificate returns 403 (TestChannelAdmitsOnlyActiveBrokers); a certificate from another CA fails the TLS handshake.Tables (migration 100
kyguard_brokers)bootstrap_bundles,trust_manifests,broker_pools,brokers(+ pinned CA SHA-256),pairing_tokens,operation_intents, all added tomigrationTablesand seeded in the snapshot test.accountsis not here: no code in this PR needs it; it lands with the first PR that references it.Config
KY_BROKER_LISTEN,KY_BROKER_HOSTNAME,KY_MIN_BROKER_VERSIONare shared replica settings (fingerprinted), since every replica's tokens must name the same listener.Routes with
TODO(hawthorn §7.5)POST /api/broker-pools,POST /api/broker-pools/{id}/pairing-tokens(admin),POST /api/manifests(any session; the signatures are the authority).Review fixes (25 Nov, Guide "Blocking Reconnect")
Sendfor every broker (1c54747).l.muagainTestReconnectDoesNotBlockOnAnUnresponsiveConnection(Send blocked 4.8s behind the old connection's close)Checked at this head:
go vet,gofmt,go test -race+ FIPS of./internal/brokerproto/...; the full stack suite at the #16 tip (see #16).Review fixes, round 3 (25 Nov, Guide "Epoch Overflow")
BIGINTcolumn. New testTestSubmitManifestEpochAtTheCounterLimitgoes throughPOST /api/manifests: epoch 2^63−1 is accepted (201) and read back unchanged from the store, and epoch 2^63 is refused at decode (422,invalid_counter), with nothing stored (a29d935, test only).ParseCounterandCounter.MarshalJSONTestSubmitManifestEpochAtTheCounterLimit(refused asinvalid_signatureinstead)Removing only one of the two caps leaves the test passing: decode and canonical re-encoding each refuse the value on their own.
Round-3 checks (stack tip
a805e71): full suite-raceandGODEBUG=fips140=on, SQLite (k83, exit 0) and PostgreSQL 17 (k83, exit 0); Docker connector suites-raceon Major under kslot (30 tests, 0 skipped, exit 0);go vetand the broker/store tests at every merged branch head;gofmt.Review fixes, round 3b (25 Nov, Guide "Duplicate Handling" at
a29d935)uniqueErr, so the loser getsErrAlreadyExistsand the API its documented 409 (a2e512d).ErrAlreadyExistsTestConcurrentPoolCreatesHaveOneWinner(PostgreSQL 17)Checks (stack tip
96c38fd): full suite-raceandGODEBUG=fips140=on, SQLite (k83, exit 0) and PostgreSQL 17 (see #16); Docker connector suites-raceon Major under kslot (30 tests, 0 skipped, exit 0);go vetand the broker, store and brokerproto tests at every merged branch head;gofmt.Review fixes, round 3c (25 Nov, Guide "Channel Shutdown" at
a2e512d)http.Server.Closeleaves hijacked broker WebSockets open through the HTTP drain.Listener.CloseAllnow closes every channel, and the server calls it right after closing the broker listener, so brokers reconnect elsewhere at once (21c6673).CloseAllcloses nothingTestCloseAllDropsEveryChannelChecks (stack tip
e8bdff0): see #16 for the full suite;go vetand the broker, brokerproto and store tests (-race) at every merged branch head.Review fixes, round 3d (25 Nov, security review at
21c6673)6c7d11e.BrokerListener()built a new listener on every call, so shutdown'sCloseAllran on a listener that held no connections. The server now builds the listener once (the samesync.Oncethat Enrollment and re-enrollment (§3.4, §4.5) #15 already had), and shutdown goes throughstopBrokerListener.TestBrokerListenerIsOneInstanceChecks: see #16 for the full suite at the tip;
go vetand the broker, brokerproto, store and api tests (-race) at every merged branch head.Round 3e (25 Nov): merged with
main, Guide "Shutdown Race" at6c7d11eorigin/main(with auth: break-glass accounts with mandatory TOTP #3–kyguard-cli: init, trust, import, enroll and sign (§3.2) #6) is merged in (d06d4c5). The two conflicts were additive, and both sides were kept:StoregainedGuard()next toMFA(), and the migration table list got the broker tables next tomfa_factorsandtotp_attempts.CloseAllmarks the listener stopped underl.mu, and a channel that reaches registration later is closed at once (18bfbe6).CloseAllTestAChannelAfterCloseAllIsClosedChecks at
18bfbe6: full suite-raceandGODEBUG=fips140=on, SQLite (k80, exit 0) and PostgreSQL 17 (Major under kslot, ownpostgres:17-alpinecontainer, exit 0);gofmt,go vet.Round 4 (25 Nov): CodeQL on #8,
mainmerged againgo/disabled-certificate-check(internal/brokerproto/tls.go). The pinned check is not skipped.InsecureSkipVerifyonly turns off Go's system-root chain check, andVerifyConnectionreplaces it on every handshake withverifyListener: the chain must lead to the CA whose SHA-256 is pinned, the leaf must name the hostname, and the leaf must carry serverAuth. The config is now namedpinVerified, and its comment names the tests that pin it. CodeQL's query ignores a config whose name documents a deliberate replacement of verification. No alert is dismissed.go/log-injection(internal/cptrust/cptrust.go). The equivocation alert logged the submitted manifest'stype. It now logs only a known manifest type, otherwiseunknown(logType).origin/main736e148(docs: point the Best Practices badge at KyGuard's own project #29, the Best Practices badge) is merged in, with no conflicts.VerifyConnectionreturns nilTestClientTLSPinsTheCA,TestBrokerRefusesAListenerWithoutItsHostnamelogTypereturns its inputTestLogTypeKeepsSubmittedTextOutOfTheLogChecks: at #8
ec97af5the full suite with-raceandGODEBUG=fips140=onpassed on SQLite (Major under kslot, exit 0) and on PostgreSQL 17 (Major under kslot with its ownpostgres:17-alpinecontainer, exit 0). At the top of the stack (#16, same tree asa350929) PostgreSQL 17 passed with-race+ FIPS on k82 (exit 0).gofmtandgo vet(also-tags docker) are clean at every branch head. The mutation proofs ran on throwaway copies.Round 4b (25 Nov): Guide "Partial Initialization" at
ec97af5CreateCAnow removes the key and any certificate file it created itself, sokyguard-server initcan be retried once the cause is fixed (f212849). Files that existed before are never touched: an existing certificate is refused before anything is written.TestFailedCreateCACanBeRetried(Major)Checks (round 4b): at #8
f212849and at #16bdb9adf, the full suite with-raceandGODEBUG=fips140=onpassed on SQLite (Major under kslot; every K host was busy) and on PostgreSQL 17 (Major under kslot, ownpostgres:17-alpinecontainer), all exit 0. #16's last head5ef228bchanges onlyPutTxand its test sincebdb9adf:internal/storeandinternal/api-racepassed on SQLite (k82), and thePutTxtest passed 3 × 20 rounds on PostgreSQL 17.gofmtandgo vet(also-tags docker) are clean at every branch head. The mutations ran on throwaway copies.🤖 Generated with Claude Code