fix(block): retain usable roots in mixed CA bundles (#13522)

* test: cover a malformed alternative CA in an mTLS bundle

* test: pin loadable CA alternatives and valid certificate chains

* fix: retain usable roots beside malformed CA bundle blocks

* test: reject header-only eligibility for expired CA roots
This commit is contained in:
Ping Qiu authored and GitHub committed 2026-12-06 05:14:27 -08:00
1 parent 31867a5b0a
commit e987ffb8f3
5 files changed
+109 -4

No files matched your search

+4 -2
View File
@@ -19,12 +19,14 @@ func CertificatePool(raw []byte, now time.Time) (*x509.CertPool, error) {
break
}
rest = remaining
if block.Type != "CERTIFICATE" {
if block.Type != "CERTIFICATE" || len(block.Headers) != 0 {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, LocalCredential(err)
// Match AppendCertsFromPEM: an unusable alternative does not
// invalidate the certificates that the pool can actually load.
continue
}
if err := ValidateCertificate(cert, now); err != nil {
if dateErr == nil {
@@ -0,0 +1,89 @@
package answer_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/auth/authtest"
"github.com/seaweedfs/seaweed-block/core/rpc/answer"
)
func TestCertificatePoolSkipsUnparseableAlternatives(t *testing.T) {
good := authtest.NewCA(t, "bundle-good")
malformed := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("not a certificate")})
block, _ := pem.Decode(good.PEM)
block.Headers = map[string]string{"Ignored": "header"}
header := pem.EncodeToMemory(block)
for _, row := range []struct {
name string
bundle []byte
valid bool
}{
{"valid-before-malformed", append(append([]byte{}, good.PEM...), malformed...), true},
{"valid-after-malformed", append(append([]byte{}, malformed...), good.PEM...), true},
{"valid-beside-header", append(append([]byte{}, good.PEM...), header...), true},
{"malformed-only", malformed, false},
{"header-only", header, false},
} {
t.Run(row.name, func(t *testing.T) {
baseline := x509.NewCertPool()
if got := baseline.AppendCertsFromPEM(row.bundle); got != row.valid {
t.Fatalf("baseline loaded=%v want=%v", got, row.valid)
}
pool, err := answer.CertificatePool(row.bundle, time.Now())
if row.valid {
if err != nil || !pool.Equal(baseline) {
t.Fatalf("pool=%v err=%v; want the baseline pool", pool, err)
}
} else {
if err == nil {
t.Fatal("bundle without a loadable certificate accepted")
}
policy, check := answer.PolicyOf(err)
if check != nil || policy.Exit != 78 || policy.Retryable {
t.Fatalf("policy=%+v check=%v err=%v", policy, check, err)
}
}
})
}
}
// A header-bearing current certificate must not make an otherwise expired
// loadable bundle pass local date validation: AppendCertsFromPEM ignores it.
func TestCertificatePoolHeaderDoesNotMakeExpiredRootsCurrent(t *testing.T) {
now := time.Now()
good := authtest.NewCA(t, "current-header-only")
block, _ := pem.Decode(good.PEM)
block.Headers = map[string]string{"Ignored": "header"}
header := pem.EncodeToMemory(block)
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
expired := *good.Cert
expired.PublicKey = &key.PublicKey
expired.NotBefore, expired.NotAfter = now.Add(-2*time.Hour), now.Add(-time.Hour)
der, err := x509.CreateCertificate(rand.Reader, &expired, &expired, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
expiredPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
bundle := append(append([]byte{}, expiredPEM...), header...)
baseline, onlyExpired := x509.NewCertPool(), x509.NewCertPool()
if !baseline.AppendCertsFromPEM(bundle) || !onlyExpired.AppendCertsFromPEM(expiredPEM) || !baseline.Equal(onlyExpired) {
t.Fatal("fixture must load only the expired root")
}
pool, err := answer.CertificatePool(bundle, now)
if err == nil || pool != nil {
t.Fatalf("header-bearing certificate rescued expired roots: pool=%v err=%v", pool, err)
}
policy, check := answer.PolicyOf(err)
if check != nil || policy.Exit != 78 || policy.Retryable || policy.Retry != answer.Never {
t.Fatalf("policy=%+v check=%v err=%v", policy, check, err)
}
}
@@ -63,14 +63,19 @@ func TestMasterLinkCARotationUsesTheVerifiedChain(t *testing.T) {
for _, row := range []struct {
name string
from, until time.Time
malformed bool
}{
{"expired", now.Add(-2 * time.Hour), now.Add(-time.Hour)},
{"future", now.Add(time.Hour), now.Add(2 * time.Hour)},
{"expired", now.Add(-2 * time.Hour), now.Add(-time.Hour), false},
{"future", now.Add(time.Hour), now.Add(2 * time.Hour), false},
{"malformed", now.Add(-2 * time.Hour), now.Add(-time.Hour), true},
} {
t.Run(row.name, func(t *testing.T) {
dir := t.TempDir()
good := authtest.NewCA(t, "rotation-good")
badPEM, badClient, badKey := datedRotationRoot(t, dir, row.from, row.until)
if row.malformed {
badPEM = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("not an X.509 certificate")})
}
caPath := filepath.Join(dir, "rotation-ca.pem")
if err := os.WriteFile(caPath, append(append([]byte{}, good.PEM...), badPEM...), 0o600); err != nil {
t.Fatal(err)
@@ -80,6 +85,9 @@ func TestMasterLinkCARotationUsesTheVerifiedChain(t *testing.T) {
// A transmitted chain may retain an unused alternative too.
// The peer builds its own chain; only our leaf is locally dated.
for _, path := range []string{sc, cc} {
if row.malformed {
continue // The malformed alternative belongs only in the CA bundle.
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
@@ -233,6 +233,11 @@ and deadline causes with zero census calls.
## Local certificate dates during rotation
CA bundle loading follows `x509.CertPool.AppendCertsFromPEM`: skip blocks
that are not header-free, parseable certificates and retain usable roots.
An unusable alternative does not reject the entire bundle. If no certificate
loads, credential construction refuses locally with exit 78.
CA bundles may retain unused expired or not-yet-valid certificates when the
bundle also contains a certificate valid at the current time. Local key-pair
loading checks the identity leaf's dates; unused supplied chain alternatives
+1
View File
@@ -1325,6 +1325,7 @@ Notes:
| `INV-SNAPSHOT-REPLAY-FLAG-001` | A successful same-ID snapshot admission reports replayed true without changing HEAD or its retained outcome. First creation reports false; the flag decorates only the response. | M9 snapshot outcome projection | `core/host/volume/snapshot_operation.go`, `chunk_control.go`; `cmd/sw-block/snapshot_operation.go` | `TestSnapshotReplayFlagDoesNotRewriteOutcome`, `TestSnapshotCLIUsesReplayedAdmissionAnswer` | SnapOps.Poll; SnapOps.Start (no transition change) | STUB |
| `INV-CLI-UNSENT-REQUEST-001` | An observed operation's initial typed dial failure sends no admission and is remote_unavailable (75) through the shared classifier. A lost answer after send, or a dial failure while polling an admitted handle, retains outcome_unknown. | CLI pre-admission error projection; no server transition | `cmd/sw-block/cut_progress_poll.go` `chunkObserveHandle`; `chunkTransportFailure`, `chunkFail` | `TestPlainDetachRefusedDialIsRemoteUnavailable`, `TestPlainDetachLostAnswerAfterSendStaysUnknown`, `TestPlainDetachPollDialFailureKeepsAdmittedOutcomeUnknown`, `TestOpsChunk_ErrorsAreJSONOnStdout` | CutTime Poll/CliGiveUp boundary; pre-admission transport proof | ACTIVE |
| `INV-CLI-MINI-EXECUTABLE-001` | Mini records and launches the executable selected by --weed without changing symlink/.. resolution; fresh and legacy runs use an absolute path. | TrialLauncher path wiring, no protocol transition | `cmd/sw-block/mini.go` `miniExecutablePath`, `mini`, `reuseMiniRecord` | `TestMiniWeedSymlinkParentKeepsSelectedExecutable`, `TestMiniRelativeWeedIsRecordedAndPrintedAbsolutely` (`cmd/sw-block`); `TestMiniCleanupFailStopAndSettlement` (`cmd/blockvolume`: failed-start proof rejects watchdog intervention; settled capture completes and live residue refuses cleanup) | NONE (path selection and test ownership only; fresh Linux qualification pending) | STUB |
| `INV-TLS-CA-BUNDLE-PARSE-001` | CA loading skips unparseable or PEM-header certificate blocks, retaining loadable alternatives as AppendCertsFromPEM does. No loadable root is a local credential refusal; the selected TLS chain still must verify. | Local credential parsing (pure function) | `core/rpc/answer/credentials.go` `CertificatePool`; `core/rpc/link/tls.go` `pool` | `TestCertificatePoolSkipsUnparseableAlternatives` (`core/rpc/answer/credentials_bundle_test.go`); `TestMasterLinkCARotationUsesTheVerifiedChain/malformed` (`core/rpc/link/ca_rotation_test.go`) | NONE (pure certificate parsing; no protocol transition) | ACTIVE |
| `INV-CLI-CATALOG-ERROR-001` | The chunk CLI preserves admission evidence and definite domain/certificate answers. Possibly-sent requests require replay/poll. Incomplete verify never exits 3; non-retryable server answers never exit 75. Absent snapshot delete is snapshot_not_found. | M9 client error projection; M4 census refusal, no transition change | `core/rpc/answer` `Lookup`; `cmd/sw-block/chunk_answer.go` `chunkAnswer`; `cmd/sw-block/chunk.go` `chunkResult`; `cmd/sw-block/catalog_snapshot_operation.go` `catalogSnapshotDeleteRefusal`; `core/frontend/chunkstore/single_filer.go` `CheckSingleFiler`; `core/frontend/chunkstore/layout/delete.go` `RunMarkDeleting` | `TestOpsChunkTransportFailureMatrix`, `TestOpsChunkVerifyUnreachableCensusPreservesTransport`, `TestCheckSingleFilerKeepsTransportCause`, `TestSingleFilerConfigurationErrorDeadlineBetweenReads`, `TestCheckSingleFilerSlowDialOrdering`, `TestDialBCatalogKeepsCustomCallerDeadline`, `TestMasterCensusKeepsCustomCallerDeadline`, `TestCheckSingleFilerValidatesAllMasterAddressesBeforeCensus`; `TestOpsChunkCatalogUnavailableIsTyped`, `TestCatalogTransportClassificationKeepsDefiniteAnswers`, `TestSnapshotDeleteAbsentCLIUsesContractCodeAndKeepsReceipt`; `TestLinkNeverTurnsASentRequestIntoSafeResend`; `TestChunkHTTPPostLostAnswerIsUnknown`; `TestCommandFamilyTransportGrid`; `TestLocalCredentialsFailBeforeDialWithTypedPolicy`; `TestHTTPCancellationBeforeDispatchKeepsOperationPhase`; `TestDeclaredDomainCodesHaveRegistryRows`; `TestOwnedClientTransportsKeepAdmissionEvidence`; `TestPresentationFailsClosedForUnknownContract`; `TestUnsentRPCWithMixedPeerFailuresIsRetryable`; `TestRPCPeerCertificateFailureDoesNotHideHandshakeTimeout`; `TestRPCSucceedsOnGoodPeerAfterBadCertificate`; `TestPeerCertificateProofRequiresEveryFreshCompletedAttempt`; `TestPeerDiagnosticTruncationNeverAuthorizesTerminalClassification`; `TestTypedRemoteUnavailableRespectsRetryable`; `TestNonRetryableServerAnswerNeverInvitesTemporaryRetry`; `TestVerifyStartCheckLostAnswerNeverLooksLikeFindings`; `TestVerifyIncompleteTransportPreservesPartialProgress`; `TestOpsFailoverUsesSharedDefiniteExitProjection`; `TestBlobHTTPAnswerSurvivesLayoutFetch`; `TestPlaintextPrefaceFailureKeepsUnsentRetryAndTLSHint`; `TestHTTPPartialCustomTraceCannotProveUnsentAfterReceivedPOST`; `TestHTTPRegisteredProtocolCannotProveUnsentAfterReceivedPOST`; `TestHTTPOwnedTransportDoesNotInheritRegisteredDefault`; `TestDelayedPeerNotificationCannotRefreshAnOldTLSFailure`; `TestObservedTLSForwardsPerCallAuthorityValidation`; `TestChunkCensusPreflightPreservesOpaqueContextCause`; `TestSingleFilerReviewPreservesDefiniteAndCallerWinner`; `TestReviewContextAndDefiniteAnswerPrecedence`; `TestReviewOldPickerCannotBorrowNewPeerGeneration`; `TestReviewContractProjectionAndReadOnlyRecovery`; `TestReviewAdmittedPollTLSFailureKeepsOperationRecoverable`; `TestReviewPickerCannotReplaceCustomCallerDeadline`; `TestReviewSelectedTLSCannotReplaceCallerCompletion`; `TestReviewHTTPStatusOverridesNestedTransport`; `TestReviewVerifyPreservesServerRetryRefusal`; `TestReviewInitialPostBodyFailurePreservesStatus`; `TestReviewForceMovePreservesServerPolicyExit`; `TestReviewFailoverDomainAnswerRequiresRecovery`; `TestSnapshotOperationCLIInterruptThenResumeUsesPrintedID`; `TestSnapshotOperationCLIInterruptedTLSKeepsUnknownAndHandle`; `TestReviewCompleteBodyKeepsStatusAndAdmission`; `TestChunkUnusableConflictAnswerIsUnknown`; `TestChunkConflictLoopKeepsOriginalRequest`; `TestReviewInvalidAdmissionKeepsOriginalRequest`; `TestReviewUnsafeSnapshotLocationKeepsOriginalUnknown`; `TestReviewAdmittedMissingResultKeepsUnknown`; `TestCutBusyHasItsOwnLegacyExitClass`; `TestCutCLIBusyIsDistinctAndDoesNotStartAnotherCut` | SnapOps.Poll; CutTime.Poll; CutTime.CliGiveUp (result projection; no new transition) | STUB |
| `INV-CLI-CHUNK-LOOP-001` | Above the per-request bound, sw-block ops chunk snapshot\|detach repeats the SAME request (same name and request id) only after a retryable or outcome_unknown answer. Manual cut and plain detach use the separate one-POST/read-only-poll contract. | client (no state machine): the CLI side of M5 requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop`; `cmd/sw-block/chunk.go` `chunkPostUntil` | `TestChunkSnapshotRepeatsTimedOutRequestsWithTheSameBody`, `TestChunkSnapshotLoopReusesTheGeneratedRequestID`, `TestChunkLoopRepeatsAnOutcomeUnknownNotMarkedRetryable` (`cmd/sw-block`) | — | ACTIVE |
| `INV-CLI-CHUNK-LOOP-002` | Above the per-request bound, sw-block ops chunk snapshot\|detach stops at the first definite answer (success or non-retryable refusal). | client (no state machine): the CLI side of M5 cut requests | `cmd/sw-block/chunk_loop.go` `chunkPostLoop` | `TestChunkLoopStopsOnANonRetryableRefusal`, `TestChunkDetachOutcomeUnknownSettles` (`cmd/sw-block`) | — | ACTIVE |