| package mtca | |
| import ( | |
| "bytes" | |
| "compress/gzip" | |
| "context" | |
| "crypto/ecdsa" | |
| "crypto/elliptic" | |
| "crypto/mldsa" | |
| "crypto/rand" | |
| "crypto/sha256" | |
| "crypto/x509" | |
| "encoding/base64" | |
| "encoding/hex" | |
| "errors" | |
| "fmt" | |
| "io" | |
| "strings" | |
| "sync" | |
| "testing" | |
| "time" | |
| "github.com/aws/aws-sdk-go-v2/service/s3" | |
| "github.com/jmhodges/clock" | |
| "golang.org/x/mod/sumdb/tlog" | |
| "github.com/letsencrypt/boulder/blog" | |
| "github.com/letsencrypt/boulder/bs3/bs3test" | |
| "github.com/letsencrypt/boulder/config" | |
| "github.com/letsencrypt/boulder/core" | |
| corepb "github.com/letsencrypt/boulder/core/proto" | |
| "github.com/letsencrypt/boulder/issuance" | |
| mtcapb "github.com/letsencrypt/boulder/mtca/proto" | |
| "github.com/letsencrypt/boulder/mtpublisher" | |
| "github.com/letsencrypt/boulder/mtpublisher/mtpublishertest" | |
| "github.com/letsencrypt/boulder/must" | |
| "github.com/letsencrypt/boulder/privatekey" | |
| "github.com/letsencrypt/boulder/trees" | |
| "github.com/letsencrypt/boulder/trees/checkpoint" | |
| "github.com/letsencrypt/boulder/trees/cosignature" | |
| "github.com/letsencrypt/boulder/trees/entry" | |
| "github.com/letsencrypt/boulder/trees/issuancelog" | |
| "github.com/letsencrypt/boulder/trees/tiles" | |
| "github.com/letsencrypt/boulder/trees/treedb" | |
| ) | |
| const logNumber = 3 | |
| const testTimeUnix = 888888888 | |
| // setup returns a working mtca, its fake tile storage, and a cleanup | |
| // function, or an error. | |
| func setup() (*mtca, *bs3test.FakeS3, error) { | |
| clk := clock.NewFake() | |
| clk.Set(time.Unix(testTimeUnix, 0)) | |
| issuer, err := issuance.LoadIssuer(issuance.IssuerConfig{ | |
| Profiles: []string{"some profile"}, | |
| IssuerURL: "http://ignored.letsencrypt.org", | |
| CRLURLBase: "http://ignored.letsencrypt.org/", | |
| CRLShards: 1, | |
| Location: issuance.IssuerLoc{ | |
| File: "../test/certs/webpki/mtca-1.privkey.pem", | |
| CertFile: "../test/certs/webpki/mtca-1.cert.pem", | |
| }, | |
| }, clk) | |
| if err != nil { | |
| return nil, nil, err | |
| } | |
| logger := blog.NewMock() | |
| profile, err := issuance.NewProfile(issuance.ProfileConfig{ | |
| OmitCommonName: true, | |
| OmitKeyEncipherment: true, | |
| OmitClientAuth: true, | |
| OmitSKID: true, | |
| MTC: true, | |
| MaxValidityPeriod: config.Duration{Duration: time.Hour}, | |
| LintConfig: "", | |
| IgnoredLints: []string{ | |
| "w_ext_subject_key_identifier_missing_sub_cert", | |
| "n_ct_sct_policy_count_unsatisfied", | |
| "e_signature_algorithm_not_supported", | |
| }, | |
| }) | |
| if err != nil { | |
| return nil, nil, err | |
| } | |
| logID, err := issuancelog.Config{CAID: "44947.4.1", LogNumber: logNumber}.Load() | |
| if err != nil { | |
| return nil, nil, err | |
| } | |
| fs3 := bs3test.New() | |
| mtca, err := New( | |
| issuer, | |
| map[string]*issuance.Profile{"mtcExample": profile}, | |
| logID, | |
| 100*time.Millisecond, | |
| newFakeDB(logID.String()), | |
| fs3, | |
| logger, | |
| clk) | |
| if err != nil { | |
| return nil, nil, err | |
| } | |
| err = mtca.InitLog(context.Background()) | |
| if err != nil { | |
| return nil, nil, fmt.Errorf("initializing log: %w", err) | |
| } | |
| return mtca, fs3, nil | |
| } | |
| type fakeDB struct { | |
| mtcLogID string | |
| latestCheckpoint int64 | |
| checkpoints []treedb.CheckpointModel | |
| subtrees []treedb.SubtreeModel | |
| } | |
| func newFakeDB(mtcLogID string) *fakeDB { | |
| return &fakeDB{mtcLogID: mtcLogID} | |
| } | |
| func (f *fakeDB) LatestCheckpoint(ctx context.Context, mtcLogID string) (_ *treedb.CheckpointModel, _ error) { | |
| if mtcLogID != f.mtcLogID { | |
| return nil, fmt.Errorf("wrong log") | |
| } | |
| for _, c := range f.checkpoints { | |
| if c.ID == f.latestCheckpoint { | |
| return &c, nil | |
| } | |
| } | |
| return nil, fmt.Errorf("latestCheckpoint %d not found", f.latestCheckpoint) | |
| } | |
| func (f *fakeDB) InsertCheckpoint(ctx context.Context, c *treedb.CheckpointModel) (_ error) { | |
| if c.MTCLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| if len(f.checkpoints) == 0 { | |
| return fmt.Errorf("InsertCheckpoint called on an uninitialized log") | |
| } | |
| c.ID = f.checkpoints[len(f.checkpoints)-1].ID + 1 | |
| f.checkpoints = append(f.checkpoints, *c) | |
| return nil | |
| } | |
| func (f *fakeDB) InsertSubtree(ctx context.Context, s *treedb.SubtreeModel) (_ int64, _ error) { | |
| if s.MTCLogID != f.mtcLogID { | |
| return 0, fmt.Errorf("wrong log") | |
| } | |
| if len(f.subtrees) == 0 { | |
| s.ID = 19000 // arbitrary start point for fake autoincrement | |
| } else { | |
| s.ID = f.subtrees[len(f.subtrees)-1].ID + 1 | |
| } | |
| f.subtrees = append(f.subtrees, *s) | |
| return s.ID, nil | |
| } | |
| func (f *fakeDB) GetUnsignedSubtrees(ctx context.Context, mtcLogID string, maxEnd int64, limit int) ([]*treedb.SubtreeModel, error) { | |
| if mtcLogID != f.mtcLogID { | |
| return nil, fmt.Errorf("wrong log") | |
| } | |
| var subtrees []*treedb.SubtreeModel | |
| for i := len(f.subtrees) - 1; i >= 0 && len(subtrees) < limit; i-- { | |
| if f.subtrees[i].MirrorID == nil && f.subtrees[i].SubtreeEnd <= maxEnd { | |
| subtrees = append(subtrees, &f.subtrees[i]) | |
| } | |
| } | |
| return subtrees, nil | |
| } | |
| func (f *fakeDB) AddSubtreeMirrorSignature(ctx context.Context, id int64, mirrorID string, mirrorSignature []byte, mtcLogID string) error { | |
| if mtcLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| for i, s := range f.subtrees { | |
| if s.ID == id { | |
| f.subtrees[i].MirrorID = &mirrorID | |
| f.subtrees[i].MirrorSignature = mirrorSignature | |
| return nil | |
| } | |
| } | |
| return fmt.Errorf("subtree %d not found", id) | |
| } | |
| func (f *fakeDB) getSubtree(mtcLogID string, id int64) (*treedb.SubtreeModel, error) { | |
| if mtcLogID != f.mtcLogID { | |
| return nil, fmt.Errorf("wrong log") | |
| } | |
| for _, s := range f.subtrees { | |
| if s.ID == id { | |
| return &s, nil | |
| } | |
| } | |
| return nil, fmt.Errorf("subtree ID %d not found", id) | |
| } | |
| func (f *fakeDB) WithTransaction(ctx context.Context, txFunc treedb.TxFunc) (_ any, _ error) { | |
| return txFunc(f) | |
| } | |
| func (f *fakeDB) AlreadyInitialized(ctx context.Context, mtcLogID string) (bool, error) { | |
| if mtcLogID != f.mtcLogID { | |
| return false, fmt.Errorf("wrong log") | |
| } | |
| return len(f.checkpoints) > 0 && f.latestCheckpoint != 0, nil | |
| } | |
| func (f *fakeDB) InsertFirstCheckpoint(ctx context.Context, firstCheckpoint *treedb.CheckpointModel) error { | |
| if firstCheckpoint.MTCLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| if len(f.checkpoints) > 0 || len(f.subtrees) > 0 || f.latestCheckpoint != 0 { | |
| return fmt.Errorf("already initialized") | |
| } | |
| firstCheckpoint.ID = 17000 // arbitrary start point for fake autoincrement | |
| f.checkpoints = append(f.checkpoints, *firstCheckpoint) | |
| f.latestCheckpoint = firstCheckpoint.ID | |
| return nil | |
| } | |
| func (f *fakeDB) AddMTCASignature(ctx context.Context, id int64, caSig []byte, mtcLogID string) error { | |
| if mtcLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| for i, c := range f.checkpoints { | |
| if c.ID == id { | |
| f.checkpoints[i].MTCASignature = caSig | |
| return nil | |
| } | |
| } | |
| return fmt.Errorf("id %d not found", id) | |
| } | |
| func (f *fakeDB) AddMirrorSignature(ctx context.Context, id int64, mirrorID string, mirrorCosig []byte, mtcLogID string) error { | |
| if mtcLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| for i, c := range f.checkpoints { | |
| if c.ID == id { | |
| f.checkpoints[i].MirrorID = &mirrorID | |
| f.checkpoints[i].MirrorSignature = mirrorCosig | |
| return nil | |
| } | |
| } | |
| return fmt.Errorf("id %d not found", id) | |
| } | |
| func (f *fakeDB) SelectLatestForUpdate(ctx context.Context, mtcLogID string) (int64, error) { | |
| if mtcLogID != f.mtcLogID { | |
| return 0, fmt.Errorf("wrong log") | |
| } | |
| return f.latestCheckpoint, nil | |
| } | |
| func (f *fakeDB) SetLatestCheckpointID(ctx context.Context, mtcLogID string, oldID int64, newID int64) error { | |
| if mtcLogID != f.mtcLogID { | |
| return fmt.Errorf("wrong log") | |
| } | |
| if f.latestCheckpoint != oldID { | |
| return fmt.Errorf("latestCheckpoint = %d, want %d", f.latestCheckpoint, oldID) | |
| } | |
| f.latestCheckpoint = newID | |
| return nil | |
| } | |
| func TestPool(t *testing.T) { | |
| p := &pool{maxSize: 20} | |
| var wg sync.WaitGroup | |
| for i := 0; i < 20; i++ { | |
| wg.Go(func() { | |
| err := p.append(pendingEntry{}) | |
| if err != nil { | |
| t.Errorf("appending entry: %s", err) | |
| } | |
| }) | |
| } | |
| wg.Wait() | |
| err := p.append(pendingEntry{}) | |
| if err == nil { | |
| t.Errorf("append to full pool: got nil, want err") | |
| } | |
| length := p.len() | |
| if length != 20 { | |
| t.Errorf("p.len(): got %d, want 20", length) | |
| } | |
| entries := p.take() | |
| if len(entries) != 20 { | |
| t.Errorf("p.take(): got %d entries, want 20", len(entries)) | |
| } | |
| length = p.len() | |
| if length != 0 { | |
| t.Errorf("p.len(): got %d after take, want 0", length) | |
| } | |
| } | |
| func TestCheckpointValid(t *testing.T) { | |
| type testCase struct { | |
| name string | |
| value treedb.CheckpointModel | |
| } | |
| rootHash := [32]byte{} | |
| testCases := []testCase{ | |
| {"no MTCLogID", treedb.CheckpointModel{ID: 7, TreeSize: 9, RootHash: rootHash[:]}}, | |
| {"no TreeSize", treedb.CheckpointModel{ID: 7, MTCLogID: "TestLog", RootHash: rootHash[:]}}, | |
| {"TreeSize too big", treedb.CheckpointModel{ID: 7, MTCLogID: "TestLog", TreeSize: trees.MaxSize + 1, RootHash: rootHash[:]}}, | |
| {"short RootHash", treedb.CheckpointModel{ID: 7, MTCLogID: "TestLog", TreeSize: 9, RootHash: rootHash[:4]}}, | |
| {"no RootHash", treedb.CheckpointModel{ID: 7, MTCLogID: "TestLog", TreeSize: 9}}, | |
| } | |
| for _, tc := range testCases { | |
| t.Run(tc.name, func(t *testing.T) { | |
| err := tc.value.Valid() | |
| if err == nil { | |
| t.Errorf("checkpoint.valid(): got nil, want error") | |
| } | |
| }) | |
| } | |
| goodCheckpoint := treedb.CheckpointModel{ | |
| ID: 7, | |
| MTCLogID: "TestLog", | |
| TreeSize: 9, | |
| RootHash: rootHash[:], | |
| } | |
| err := goodCheckpoint.Valid() | |
| if err != nil { | |
| t.Errorf("goodCheckpoint.valid(): got %q, want no error", err) | |
| } | |
| } | |
| // issueResult is the outcome of one async Issue call, along with the values | |
| // we expect to find in the entry sequenced for it. | |
| type issueResult struct { | |
| *mtcapb.IssueResponse | |
| err error | |
| expectedSPKIHash [sha256.Size]byte | |
| expectedDNSName string | |
| } | |
| // makeIssueRequest returns an IssueRequest with a freshly generated key and | |
| // a random DNS name under example.com. | |
| func makeIssueRequest(t *testing.T) *mtcapb.IssueRequest { | |
| t.Helper() | |
| key, err := ecdsa.GenerateKey(elliptic.P256(), nil) | |
| if err != nil { | |
| t.Fatalf("generating key: %s", err) | |
| } | |
| pubkeyBytes, err := x509.MarshalPKIXPublicKey(key.Public()) | |
| if err != nil { | |
| t.Fatalf("marshaling pubkey: %s", err) | |
| } | |
| var buf [4]byte | |
| _, err = rand.Read(buf[:]) | |
| if err != nil { | |
| t.Fatalf("generating random DNS name: %s", err) | |
| } | |
| dnsName := fmt.Sprintf("%x.example.com", buf) | |
| return &mtcapb.IssueRequest{ | |
| Pubkey: pubkeyBytes, | |
| Identifiers: []*corepb.Identifier{ | |
| {Type: "dns", Value: dnsName}, | |
| }, | |
| Profile: "mtcExample", | |
| } | |
| } | |
| // issueMany calls Issue() `n` times concurrently and waits for all of the requests | |
| // to be included in the pool. Returns a channel that will supply results once `Issue()` | |
| // returns. | |
| // | |
| // Does not call `sequence()`. The caller is responsible for that. | |
| func issueMany(t *testing.T, m *mtca, n int) <-chan issueResult { | |
| t.Helper() | |
| ch := make(chan issueResult, n) | |
| for i := 0; i < n; i++ { | |
| req := makeIssueRequest(t) | |
| go func() { | |
| resp, err := m.Issue(t.Context(), req) | |
| ch <- issueResult{ | |
| IssueResponse: resp, | |
| err: err, | |
| expectedSPKIHash: sha256.Sum256(req.Pubkey), | |
| expectedDNSName: req.Identifiers[0].Value, | |
| } | |
| }() | |
| } | |
| // Waiting for inclusion in the pool lets us check "pool full" conditions. | |
| for m.pool.len() < n { | |
| time.Sleep(time.Millisecond) | |
| } | |
| return ch | |
| } | |
| // TestWriteCheckpoint checks that writeCheckpoint creates the checkpoint only | |
| // when given no ETag, replaces only the checkpoint whose ETag is prevETag, and | |
| // otherwise returns ErrCheckpointChanged without writing. | |
| func TestWriteCheckpoint(t *testing.T) { | |
| m, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setup: %s", err) | |
| } | |
| key := m.logID.CheckpointPath() | |
| delete(fs3.Objects, key) | |
| first, err := m.writeCheckpoint(t.Context(), []byte("first note\n"), "") | |
| if err != nil { | |
| t.Fatalf("writing the first checkpoint: %s", err) | |
| } | |
| if string(fs3.Objects[key].Data) != "first note\n" { | |
| t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "first note\n") | |
| } | |
| second, err := m.writeCheckpoint(t.Context(), []byte("second note\n"), first) | |
| if err != nil { | |
| t.Fatalf("replacing the checkpoint: %s", err) | |
| } | |
| if string(fs3.Objects[key].Data) != "second note\n" { | |
| t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "second note\n") | |
| } | |
| if second == first { | |
| t.Error("ETag did not change with the checkpoint's contents") | |
| } | |
| _, err = m.writeCheckpoint(t.Context(), []byte("third note\n"), "") | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("writeCheckpoint creating over an existing checkpoint = %s, want ErrCheckpointChanged", err) | |
| } | |
| if string(fs3.Objects[key].Data) != "second note\n" { | |
| t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "second note\n") | |
| } | |
| fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} | |
| _, err = m.writeCheckpoint(t.Context(), []byte("fourth note\n"), second) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("writeCheckpoint over another writer's checkpoint = %s, want ErrCheckpointChanged", err) | |
| } | |
| if string(fs3.Objects[key].Data) != "foreign note\n" { | |
| t.Errorf("stored checkpoint = %q, want the other writer's %q", fs3.Objects[key].Data, "foreign note\n") | |
| } | |
| delete(fs3.Objects, key) | |
| _, err = m.writeCheckpoint(t.Context(), []byte("fifth note\n"), second) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("writeCheckpoint replacing a deleted checkpoint = %s, want ErrCheckpointChanged", err) | |
| } | |
| } | |
| // TestInitLogRefusesServedCheckpoint checks that InitLog fails when a | |
| // checkpoint is already served, leaving it in place. | |
| func TestInitLogRefusesServedCheckpoint(t *testing.T) { | |
| m, _, err := setup() | |
| if err != nil { | |
| t.Fatalf("setup: %s", err) | |
| } | |
| fs3 := bs3test.New() | |
| m.s3c = fs3 | |
| m.treedb = newFakeDB(m.logID.String()) | |
| m.servedCheckpointETag = "" | |
| key := m.logID.CheckpointPath() | |
| fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} | |
| err = m.InitLog(t.Context()) | |
| if !errors.Is(err, ErrCheckpointChanged) || !strings.Contains(err.Error(), "already served") { | |
| t.Errorf("InitLog with a checkpoint already served = %q, want ErrCheckpointChanged naming it", err) | |
| } | |
| if string(fs3.Objects[key].Data) != "foreign note\n" { | |
| t.Errorf("stored checkpoint = %q, want the existing %q", fs3.Objects[key].Data, "foreign note\n") | |
| } | |
| } | |
| // TestPreflightServesCheckpoint checks that Preflight serves the latest | |
| // checkpoint, covering a process that stopped between publishing tiles and | |
| // serving. | |
| func TestPreflightServesCheckpoint(t *testing.T) { | |
| m, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setup: %s", err) | |
| } | |
| m.servedCheckpointETag = "" | |
| err = m.Preflight(t.Context()) | |
| if err != nil { | |
| t.Fatalf("Preflight over our served checkpoint: %s", err) | |
| } | |
| verifyStores(t, m, fs3) | |
| delete(fs3.Objects, m.logID.CheckpointPath()) | |
| m.servedCheckpointETag = "" | |
| err = m.Preflight(t.Context()) | |
| if err != nil { | |
| t.Fatalf("Preflight with nothing served: %s", err) | |
| } | |
| verifyStores(t, m, fs3) | |
| } | |
| // TestServeCheckpointMismatch checks that a serve over an earlier checkpoint | |
| // of ours adopts its ETag and succeeds, and that a serve over nothing, another | |
| // writer's checkpoint, or a larger one of ours fails with ErrCheckpointChanged | |
| // and keeps failing. | |
| func TestServeCheckpointMismatch(t *testing.T) { | |
| m, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setup: %s", err) | |
| } | |
| latest := verifyStores(t, m, fs3) | |
| tree := tlog.Tree{N: latest.TreeSize, Hash: tlog.Hash(latest.RootHash)} | |
| key := m.logID.CheckpointPath() | |
| signedNote := fs3.Objects[key].Data | |
| fs3.Objects[key] = bs3test.StoredObject{Data: signedNote, ETag: "\"lost response\""} | |
| err = m.serveCheckpoint(t.Context(), tree, signedNote) | |
| if err != nil { | |
| t.Fatalf("serving over our own checkpoint under an unknown ETag: %s", err) | |
| } | |
| if m.servedCheckpointETag == "\"lost response\"" { | |
| t.Error("servedCheckpointETag still holds the ETag of the replaced checkpoint") | |
| } | |
| delete(fs3.Objects, key) | |
| err = m.serveCheckpoint(t.Context(), tree, signedNote) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("serving after the checkpoint was deleted = %s, want ErrCheckpointChanged", err) | |
| } | |
| fs3.Objects[key] = bs3test.StoredObject{Data: signedNote} | |
| m.servedCheckpointETag = "" | |
| larger := tlog.Tree{N: latest.TreeSize + 1, Hash: tlog.Hash(latest.RootHash)} | |
| timestamp := time.Now() | |
| largerLine, err := m.cosigner.CosignCheckpoint(larger, timestamp) | |
| if err != nil { | |
| t.Fatalf("CosignCheckpoint: %s", err) | |
| } | |
| largerNote, err := m.checkpointNote(larger, largerLine) | |
| if err != nil { | |
| t.Fatalf("checkpointNote: %s", err) | |
| } | |
| fs3.Objects[key] = bs3test.StoredObject{Data: largerNote, ETag: "\"larger\""} | |
| m.servedCheckpointETag = "" | |
| err = m.serveCheckpoint(t.Context(), tree, signedNote) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("serving over a larger checkpoint of ours = %s, want ErrCheckpointChanged", err) | |
| } | |
| // Build a checkpoint signed by the same key, but for a different log origin. It should error. | |
| otherLog := must.Do(issuancelog.Config{CAID: m.logID.CAID().String(), LogNumber: logNumber + 1}.Load()) | |
| otherCosigner, err := cosignature.NewCosigner(otherLog.CAID(), otherLog.Origin(), m.issuer.Signer) | |
| if err != nil { | |
| t.Fatalf("NewCosigner: %s", err) | |
| } | |
| timestamp = time.Now() | |
| otherLine, err := otherCosigner.CosignCheckpoint(tree, timestamp) | |
| if err != nil { | |
| t.Fatalf("CosignCheckpoint: %s", err) | |
| } | |
| otherNote, err := (&checkpoint.Checkpoint{Origin: otherLog.Origin(), Tree: tree}).SignedNote(otherLine) | |
| if err != nil { | |
| t.Fatalf("SignedNote: %s", err) | |
| } | |
| _, _, err = checkpoint.Open(otherNote, m.verifier) | |
| if err != nil { | |
| t.Fatalf("opening checkpoint of another log: %s", err) | |
| } | |
| fs3.Objects[key] = bs3test.StoredObject{Data: otherNote, ETag: "\"other log\""} | |
| m.servedCheckpointETag = "" | |
| err = m.serveCheckpoint(t.Context(), tree, signedNote) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("serving over a checkpoint of another log = %s, want ErrCheckpointChanged", err) | |
| } | |
| if !bytes.Equal(fs3.Objects[key].Data, otherNote) { | |
| t.Error("checkpoint of another log was replaced") | |
| } | |
| fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} | |
| for range 2 { | |
| err = m.serveCheckpoint(t.Context(), tree, signedNote) | |
| if !errors.Is(err, ErrCheckpointChanged) { | |
| t.Errorf("serving over another writer's checkpoint = %s, want ErrCheckpointChanged", err) | |
| } | |
| } | |
| if string(fs3.Objects[key].Data) != "foreign note\n" { | |
| t.Errorf("stored checkpoint = %q, want the other writer's %q", fs3.Objects[key].Data, "foreign note\n") | |
| } | |
| } | |
| // errorS3 wraps a bs3test.FakeS3, failing every PutObject with `err` while | |
| // it is non-nil and passing through to the wrapped fake otherwise. | |
| type errorS3 struct { | |
| *bs3test.FakeS3 | |
| err error | |
| } | |
| func (e *errorS3) PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { | |
| if e.err != nil { | |
| return nil, e.err | |
| } | |
| return e.FakeS3.PutObject(ctx, params, optFns...) | |
| } | |
| // mirrorCosign cosigns the latest checkpoint with a real mtpublisher, standing | |
| // in for the daemon, so sequencing can proceed. | |
| func mirrorCosign(t *testing.T, m *mtca) { | |
| t.Helper() | |
| key, err := mldsa.NewPrivateKey(mldsa.MLDSA44(), make([]byte, 32)) | |
| if err != nil { | |
| t.Fatalf("NewPrivateKey: %s", err) | |
| } | |
| mirror, err := mtpublishertest.NewTestMirror("32473.9", m.logID.Origin(), privatekey.NewDeterministicSigner(key)) | |
| if err != nil { | |
| t.Fatalf("mtpublishertest.NewTestMirror: %s", err) | |
| } | |
| fake := m.treedb.(*fakeDB) | |
| p, err := mtpublisher.New(fake, time.Second, m.logID, m.verifier, mirror, blog.NewMock()) | |
| if err != nil { | |
| t.Fatalf("mtpublisher.New: %s", err) | |
| } | |
| err = p.PublishCheckpoint(t.Context()) | |
| if err != nil { | |
| t.Fatalf("mtpublisher.PublishCheckpoint: %s", err) | |
| } | |
| } | |
| // verifyStores checks at a given point in time that tree size and root hash | |
| // are the same between: | |
| // | |
| // - m.frontier | |
| // - m.latestCheckpoint() | |
| // - fake tile storage | |
| func verifyStores(t *testing.T, m *mtca, fs3 *bs3test.FakeS3) *treedb.CheckpointModel { | |
| t.Helper() | |
| latest, err := m.treedb.LatestCheckpoint(t.Context(), m.logID.String()) | |
| if err != nil { | |
| t.Fatalf("getting latest: %s", err) | |
| } | |
| memTreeSize := m.frontier.TreeSize() | |
| if memTreeSize != latest.TreeSize { | |
| t.Errorf("in-memory frontier TreeSize %d != DB TreeSize %d", memTreeSize, latest.TreeSize) | |
| } | |
| memHash := m.frontier.RootHash() | |
| if !bytes.Equal(latest.RootHash, memHash[:]) { | |
| t.Errorf("in-memory frontier RootHash %s != DB RootHash %s", | |
| memHash, base64.StdEncoding.EncodeToString(latest.RootHash)) | |
| } | |
| loaded, err := tiles.LoadFrontier(t.Context(), fs3, latest.TreeSize, m.logID.TilePrefix()) | |
| if err != nil { | |
| t.Fatalf("loading frontier from tile storage: %s", err) | |
| } | |
| tileHash := loaded.RootHash() | |
| if !bytes.Equal(latest.RootHash, tileHash[:]) { | |
| t.Errorf("tile storage RootHash %s != DB RootHash %s", | |
| tileHash, base64.StdEncoding.EncodeToString(latest.RootHash)) | |
| } | |
| served, ok := fs3.Objects[m.logID.TilePrefix()+"/checkpoint"] | |
| if !ok { | |
| t.Fatal("no checkpoint served in tile storage") | |
| } | |
| servedCheckpoint, _, err := checkpoint.Open(served.Data, m.verifier) | |
| if err != nil { | |
| t.Fatalf("opening the served checkpoint: %s", err) | |
| } | |
| if servedCheckpoint.Tree.N != latest.TreeSize || !bytes.Equal(servedCheckpoint.Tree.Hash[:], latest.RootHash) { | |
| t.Errorf("served checkpoint is tree size %d hash %s, DB latest is size %d hash %s", | |
| servedCheckpoint.Tree.N, servedCheckpoint.Tree.Hash, latest.TreeSize, base64.StdEncoding.EncodeToString(latest.RootHash)) | |
| } | |
| return latest | |
| } | |
| // validateStoredEntries reads and parses the rightmost entries tile from | |
| // storage, then verifies that the entry at each index in `got` contains the | |
| // SPKI hash and DNS name of the request that was assigned that index. | |
| // | |
| // Only valid for tree sizes below 256. | |
| func validateStoredEntries(t *testing.T, fs3 *bs3test.FakeS3, prefix string, treeSize int64, got map[int64]issueResult) { | |
| t.Helper() | |
| obj, ok := fs3.Objects[fmt.Sprintf("%s/tile/entries/000.p/%d", prefix, treeSize)] | |
| if !ok { | |
| t.Fatalf("no entries tile in storage for tree size %d", treeSize) | |
| } | |
| data := obj.Data | |
| if obj.ContentEncoding != nil && *obj.ContentEncoding == "gzip" { | |
| r, err := gzip.NewReader(bytes.NewReader(data)) | |
| if err != nil { | |
| t.Fatalf("decompressing entries tile: %s", err) | |
| } | |
| data, err = io.ReadAll(r) | |
| if err != nil { | |
| t.Fatalf("decompressing entries tile: %s", err) | |
| } | |
| } | |
| br := entry.NewBundleReader(data) | |
| var entries []*entry.MTCLogEntry | |
| for { | |
| mtcle, _, err := br.ReadEntry() | |
| if errors.Is(err, io.EOF) { | |
| break | |
| } | |
| if err != nil { | |
| t.Fatalf("parsing entries tile: %s", err) | |
| } | |
| entries = append(entries, mtcle) | |
| } | |
| if int64(len(entries)) != treeSize { | |
| t.Fatalf("entries tile at tree size %d: got %d entries", treeSize, len(entries)) | |
| } | |
| for idx, res := range got { | |
| tbs := entries[idx].TBS() | |
| if !bytes.Contains(tbs, res.expectedSPKIHash[:]) { | |
| t.Errorf("entry at index %d does not contain the SPKI hash of the request that was assigned that index", idx) | |
| } | |
| if !bytes.Contains(tbs, []byte(res.expectedDNSName)) { | |
| t.Errorf("entry at index %d does not contain the DNS name %q of the request that was assigned that index", idx, res.expectedDNSName) | |
| } | |
| } | |
| } | |
| // collectResults reads n results. The entryIndexes must exactly cover [firstIndex, firstIndex+n). | |
| // | |
| // Returns a map from entry index to the result of the request that received that index. | |
| func collectResults(t *testing.T, results <-chan issueResult, firstIndex int64, n int) map[int64]issueResult { | |
| t.Helper() | |
| got := map[int64]issueResult{} | |
| for i := 0; i < n; i++ { | |
| res := <-results | |
| if res.err != nil { | |
| t.Errorf("Issue: %s", res.err) | |
| continue | |
| } | |
| serialLogNumber, entryIndex, err := core.DecodeMTCSerial(res.MtcSerialNumber) | |
| if err != nil { | |
| t.Errorf("DecodeMTCSerial: %s", err) | |
| continue | |
| } | |
| if serialLogNumber != logNumber { | |
| t.Errorf("MTC serial number of %016x does not have expected logNumber %04x", | |
| res.MtcSerialNumber, logNumber) | |
| } | |
| _, ok := got[entryIndex] | |
| if ok { | |
| t.Errorf("entryIndex %d returned twice", entryIndex) | |
| } | |
| got[entryIndex] = res | |
| } | |
| for i := firstIndex; i < firstIndex+int64(n); i++ { | |
| _, ok := got[i] | |
| if !ok { | |
| t.Errorf("no Issue call got entryIndex %d", i) | |
| } | |
| } | |
| return got | |
| } | |
| func TestSequence(t *testing.T) { | |
| mtca, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setting up mtca: %s", err) | |
| } | |
| // An empty pool is a no-op regardless of checkpoint state. | |
| err = mtca.sequence(t.Context()) | |
| if err != nil { | |
| t.Fatalf("sequencing with empty pool: %s", err) | |
| } | |
| // Fill the pool with five concurrent requests. | |
| mtca.pool.maxSize = 5 | |
| results := issueMany(t, mtca, 5) | |
| // With the pool full, a sixth request should fail. | |
| req := makeIssueRequest(t) | |
| _, err = mtca.Issue(t.Context(), req) | |
| if err == nil { | |
| t.Fatal("Issue with a full pool: got nil error, want error") | |
| } | |
| if !strings.Contains(err.Error(), "pool is full") { | |
| t.Errorf("Issue with a full pool: expected 'pool is full', got %q", err) | |
| } | |
| // The checkpoint has no mirror signature yet, so sequencing must fail. | |
| err = mtca.sequence(t.Context()) | |
| if err == nil { | |
| t.Fatalf("sequencing with an unready checkpoint: got nil error, want error") | |
| } | |
| if !errors.Is(err, ErrCheckpointNotReady) { | |
| t.Errorf("sequencing with an unready checkpoint: want ErrCheckpointNotReady, got %q", err) | |
| } | |
| if mtca.pool.len() != 5 { | |
| t.Errorf("pool after refused sequencing: got len %d, want 5", mtca.pool.len()) | |
| } | |
| mirrorCosign(t, mtca) | |
| // Now sequencing should succeed, assigning indexes 1 through 5 (the | |
| // genesis null entry occupies index 0). | |
| err = mtca.sequence(t.Context()) | |
| if err != nil { | |
| t.Fatalf("sequencing with waiting entries: %s", err) | |
| } | |
| got := collectResults(t, results, 1, 5) | |
| for entryIndex, issuanceResult := range got { | |
| fake := mtca.treedb.(*fakeDB) | |
| subtree, err := fake.getSubtree(mtca.logID.String(), issuanceResult.MtcSubtreeID) | |
| if err != nil { | |
| t.Fatalf("getting subtree: %s", err) | |
| } | |
| if subtree.MTCLogID != mtca.logID.String() { | |
| t.Errorf("subtree.MTCLogID: got %q, want %q", subtree.MTCLogID, mtca.logID.String()) | |
| } | |
| if len(subtree.MTCASignature) == 0 { | |
| t.Error("subtree.MTCASignature: got empty slice, want non-empty slice") | |
| } | |
| if !mtca.verifier.VerifySubtreeSignature(mtca.logID.Origin(), subtree.SubtreeStart, subtree.SubtreeEnd, tlog.Hash(subtree.SubtreeHash), subtree.MTCASignature) { | |
| t.Error("subtree.MTCASignature: does not verify") | |
| } | |
| if subtree.MirrorID != nil { | |
| t.Error("subtree.MirrorID: got non-nil string pointer, want nil") | |
| } | |
| if len(subtree.MirrorSignature) != 0 { | |
| t.Error("subtree.MirrorSignature: got non-empty slice, want empty slice") | |
| } | |
| if !(subtree.SubtreeStart <= entryIndex && entryIndex < subtree.SubtreeEnd) { | |
| t.Errorf("subtree.MTCSerialNumber: got entryIndex %d, want entryIndex in interval [%d,%d)", | |
| entryIndex, subtree.SubtreeStart, subtree.SubtreeEnd) | |
| } | |
| if len(subtree.SubtreeHash) != 32 { | |
| t.Errorf("subtree.SubtreeHash: got length %d, want length 32", len(subtree.SubtreeHash)) | |
| } | |
| } | |
| // The in-memory frontier, DB checkpoint, and stored tiles must agree, | |
| // and the resulting checkpoint signature must be valid. | |
| latest := verifyStores(t, mtca, fs3) | |
| verifyCheckpoint(t, mtca, latest) | |
| // Each client's returned index must point at its own entry in the | |
| // published entries tile. | |
| validateStoredEntries(t, fs3, mtca.logID.TilePrefix(), latest.TreeSize, got) | |
| } | |
| // TestSequenceStorageFailure checks that a failed sequencing pass leaves the | |
| // in-memory frontier consistent with the database, and that sequencing | |
| // recovers cleanly once storage is healthy again. | |
| func TestSequenceStorageFailure(t *testing.T) { | |
| mtca, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setting up mtca: %s", err) | |
| } | |
| mirrorCosign(t, mtca) | |
| mtca.pool.maxSize = 2 | |
| results := issueMany(t, mtca, 2) | |
| // Fail writing the tiles. | |
| es3 := &errorS3{FakeS3: fs3, err: errors.New("the tiles will not tesselate")} | |
| mtca.s3c = es3 | |
| err = mtca.sequence(t.Context()) | |
| if err == nil { | |
| t.Fatal("sequencing with failing storage: got nil error, want error") | |
| } | |
| if !strings.Contains(err.Error(), "staging candidate tiles") { | |
| t.Fatalf("sequencing with failing storage: got %q, want a 'staging candidate tiles' error", err) | |
| } | |
| // The waiting RPCs should get their responses. | |
| for i := 0; i < 2; i++ { | |
| res := <-results | |
| if res.err == nil { | |
| t.Errorf("Issue with failing storage: got entryIndex %d, want error", res.MtcSerialNumber) | |
| } | |
| } | |
| // The in-memory frontier must be unchanged, still matching the DB. | |
| verifyStores(t, mtca, fs3) | |
| // Storage is working again! | |
| es3.err = nil | |
| results = issueMany(t, mtca, 2) | |
| err = mtca.sequence(t.Context()) | |
| if err != nil { | |
| t.Fatalf("sequencing after storage recovered: %s", err) | |
| } | |
| // After storage recovered, we should pick up where we left off | |
| // and sequence 2 entries starting at entryIndex 1. | |
| got := collectResults(t, results, 1, 2) | |
| latest := verifyStores(t, mtca, fs3) | |
| verifyCheckpoint(t, mtca, latest) | |
| validateStoredEntries(t, fs3, mtca.logID.TilePrefix(), latest.TreeSize, got) | |
| } | |
| func TestInitLog(t *testing.T) { | |
| mtca, fs3, err := setup() | |
| if err != nil { | |
| t.Fatalf("setting up mtca: %s", err) | |
| } | |
| // InitLog is called once by setup. A second time should fail. | |
| err = mtca.InitLog(t.Context()) | |
| if err == nil { | |
| t.Errorf("second InitLog: got nil error, want error") | |
| } | |
| latest := verifyStores(t, mtca, fs3) | |
| if latest.TreeSize != 1 { | |
| t.Errorf("just-initialized log: got TreeSize %d, want 1", latest.TreeSize) | |
| } | |
| expected, _ := hex.DecodeString("8855508aade16ec573d21e6a485dfd0a7624085c1a14b5ecdd6485de0c6839a4") | |
| if !bytes.Equal(latest.RootHash, expected) { | |
| t.Errorf("just-initialized log: got RootHash %x, want %x", latest.RootHash, expected) | |
| } | |
| verifyCheckpoint(t, mtca, latest) | |
| } | |
| func verifyCheckpoint(t *testing.T, mtca *mtca, dbCheckpoint *treedb.CheckpointModel) { | |
| t.Helper() | |
| if len(dbCheckpoint.MTCASignature) == 0 { | |
| t.Fatalf("no MTCASignature") | |
| } | |
| pubkey, ok := mtca.issuer.Signer.Public().(*mldsa.PublicKey) | |
| if !ok { | |
| t.Fatalf("issuer pubkey: got %T, want %T", mtca.issuer.Signer.Public(), &mldsa.PublicKey{}) | |
| } | |
| v, err := cosignature.NewVerifier(mtca.logID.CAID(), pubkey) | |
| if err != nil { | |
| t.Fatalf("NewVerifier: %s", err) | |
| } | |
| signedNote := fmt.Appendf(nil, "%s\n%d\n%s\n\n%s", | |
| mtca.logID.Origin(), | |
| dbCheckpoint.TreeSize, | |
| base64.StdEncoding.EncodeToString(dbCheckpoint.RootHash), | |
| dbCheckpoint.MTCASignature) | |
| _, n, err := checkpoint.Open(signedNote, v) | |
| if err != nil { | |
| t.Fatalf("checkpoint.Open(): %s", err) | |
| } | |
| checkpointCosignature, err := v.CheckpointCosignature(n) | |
| if err != nil { | |
| t.Fatalf("CheckpointCosignature(): %s", err) | |
| } | |
| if checkpointCosignature.Timestamp != testTimeUnix { | |
| t.Errorf("invalid timestamp: %d", checkpointCosignature.Timestamp) | |
| } | |
| } |