Addressing comments and adjusting for future CQRP changes
diff --git a/bs3/bs3test/bs3test.go b/bs3/bs3test/bs3test.go index fdfdcbe..9ae760c 100644 --- a/bs3/bs3test/bs3test.go +++ b/bs3/bs3test/bs3test.go
@@ -5,8 +5,9 @@ import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "errors" - "fmt" "io" "net/http" "sync" @@ -20,12 +21,15 @@ type StoredObject struct { Data []byte ContentEncoding *string + ETag string } // FakeS3 implements the PutObject/GetObject/Bucket subset of the S3 API // with an in-memory map. // -// PutObject fails for an existing key only when IfNoneMatch is set. +// PutObject fails with 412 Precondition Failed when IfNoneMatch is set and the +// key exists, or when IfMatch does not match the stored ETag. GetObject fails +// with 404 Not Found for a missing key. type FakeS3 struct { mu sync.Mutex @@ -36,37 +40,47 @@ return &FakeS3{Objects: make(map[string]StoredObject)} } +func responseError(status int) error { + return &awshttp.ResponseError{ + ResponseError: &smithyhttp.ResponseError{ + Response: &smithyhttp.Response{Response: &http.Response{StatusCode: status}}, + Err: errors.New(http.StatusText(status)), + }, + } +} + func (f *FakeS3) PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { f.mu.Lock() defer f.mu.Unlock() - _, ok := f.Objects[*params.Key] + existing, ok := f.Objects[*params.Key] if ok && params.IfNoneMatch != nil { - return nil, &awshttp.ResponseError{ - ResponseError: &smithyhttp.ResponseError{ - Response: &smithyhttp.Response{Response: &http.Response{StatusCode: http.StatusPreconditionFailed}}, - Err: errors.New("PreconditionFailed"), - }, - } + return nil, responseError(http.StatusPreconditionFailed) + } + if params.IfMatch != nil && (!ok || existing.ETag != *params.IfMatch) { + return nil, responseError(http.StatusPreconditionFailed) } body, err := io.ReadAll(params.Body) if err != nil { return nil, err } - f.Objects[*params.Key] = StoredObject{Data: body, ContentEncoding: params.ContentEncoding} - return nil, nil + sum := sha256.Sum256(body) + etag := "\"" + hex.EncodeToString(sum[:]) + "\"" + f.Objects[*params.Key] = StoredObject{Data: body, ContentEncoding: params.ContentEncoding, ETag: etag} + return &s3.PutObjectOutput{ETag: &etag}, nil } func (f *FakeS3) GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error) { f.mu.Lock() defer f.mu.Unlock() o, ok := f.Objects[*params.Key] - if ok { - return &s3.GetObjectOutput{ - Body: io.NopCloser(bytes.NewReader(o.Data)), - ContentEncoding: o.ContentEncoding, - }, nil + if !ok { + return nil, responseError(http.StatusNotFound) } - return nil, fmt.Errorf("not found") + return &s3.GetObjectOutput{ + Body: io.NopCloser(bytes.NewReader(o.Data)), + ContentEncoding: o.ContentEncoding, + ETag: &o.ETag, + }, nil } func (f *FakeS3) Bucket() string {
diff --git a/cmd/boulder-mtca/main.go b/cmd/boulder-mtca/main.go index 45bd17b..32f33f7 100644 --- a/cmd/boulder-mtca/main.go +++ b/cmd/boulder-mtca/main.go
@@ -4,13 +4,9 @@ import ( "context" - "crypto/mldsa" - "crypto/x509" "database/sql" - "encoding/pem" "errors" "flag" - "fmt" "os" "sync" "time" @@ -54,37 +50,12 @@ // SequencingPeriod controls how frequently the MTCA sequences a batch and signs a checkpoint. SequencingPeriod config.Duration `validate:"required"` - - // Mirror identifies the mirror whose cosignatures must be verified - // before the MTCA serves them as part of a checkpoint. - Mirror cmd.MirrorConfig `validate:"required"` } Syslog cmd.SyslogConfig OpenTelemetry cmd.OpenTelemetryConfig } -// loadMLDSAPublicKey reads a PEM-encoded PKIX ML-DSA-44 public key. -func loadMLDSAPublicKey(filename string) (*mldsa.PublicKey, error) { - data, err := os.ReadFile(filename) - if err != nil { - return nil, err - } - block, _ := pem.Decode(data) - if block == nil || block.Type != "PUBLIC KEY" { - return nil, fmt.Errorf("no PUBLIC KEY PEM block in %s", filename) - } - parsed, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - return nil, err - } - pubKey, ok := parsed.(*mldsa.PublicKey) - if !ok { - return nil, fmt.Errorf("key in %s is %T, must be ML-DSA-44", filename, parsed) - } - return pubKey, nil -} - func main() { grpcAddr := flag.String("addr", "", "gRPC listen address override") debugAddr := flag.String("debug-addr", "", "Debug server address override") @@ -146,9 +117,6 @@ s3c, err := bs3.FromConfig(c.MTCA.S3, logger) cmd.FailOnError(err, "Loading S3 config") - mirrorPublicKey, err := loadMLDSAPublicKey(c.MTCA.Mirror.PublicKeyFile) - cmd.FailOnError(err, "Loading mirror public key") - mtcaImpl, err := mtca.New( issuer, profiles, @@ -156,8 +124,6 @@ c.MTCA.SequencingPeriod.Duration, dbMap, s3c, - c.MTCA.Mirror.ID, - mirrorPublicKey, logger, clk) cmd.FailOnError(err, "Building MTCA")
diff --git a/cmd/config.go b/cmd/config.go index 9d9c149..853d2b6 100644 --- a/cmd/config.go +++ b/cmd/config.go
@@ -129,14 +129,6 @@ HostnamePolicyFile string `validate:"required"` } -// MirrorConfig identifies an MTC mirror cosigner. -type MirrorConfig struct { - // ID is the mirror's ID (e.g. "32473.9"). - ID string `validate:"required"` - // PublicKeyFile holds the mirror's PEM-encoded ML-DSA-44 public key. - PublicKeyFile string `validate:"required"` -} - // TLSConfig represents certificates and a key for authenticated TLS. type TLSConfig struct { CertFile string `validate:"required"`
diff --git a/mtca/mtca.go b/mtca/mtca.go index fa3a4a8a..6ae2839 100644 --- a/mtca/mtca.go +++ b/mtca/mtca.go
@@ -13,9 +13,12 @@ "encoding/hex" "errors" "fmt" + "net/http" + "path" "sync" "time" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/jmhodges/clock" "golang.org/x/mod/sumdb/tlog" @@ -37,6 +40,7 @@ var ErrIssuanceLogAlreadyInitialized = errors.New("issuance log already initialized") var ErrCheckpointNotReady = errors.New("not ready - no mirror signature") +var ErrCheckpointChanged = errors.New("checkpoint in tile storage changed since it was last written") var _ mtcapb.MTCAServer = &mtca{} @@ -48,8 +52,6 @@ sequencingPeriod time.Duration, dbMap *borp.DbMap, s3c simpleS3, - mirrorID string, - mirrorPublicKey *mldsa.PublicKey, logger blog.Logger, clk clock.Clock, ) (*mtca, error) { @@ -69,7 +71,6 @@ issuer: issuer, profiles: profiles, logID: logID, - mirrorID: mirrorID, pool: &pool{maxSize: 100}, sequencingPeriod: sequencingPeriod, @@ -97,12 +98,6 @@ } m.verifier = verifier - mirrorVerifier, err := cosignature.NewVerifier(mirrorID, mirrorPublicKey) - if err != nil { - return nil, fmt.Errorf("creating mirror verifier: %s", err) - } - m.mirrorVerifier = mirrorVerifier - return m, nil } @@ -115,10 +110,9 @@ cosigner *cosignature.Cosigner verifier *cosignature.Verifier - mirrorID string - mirrorVerifier *cosignature.Verifier - - servedCheckpointID int64 + // servedCheckpointETag is the ETag of the checkpoint object in tile storage + // as this MTCA last wrote or read it, nil until it has done either. + servedCheckpointETag *string pool *pool @@ -179,6 +173,7 @@ rootHash := candidate.RootHash() + var caSig []byte _, err = db.WithTransaction(ctx, m.db, func(tx db.Executor) (any, error) { var numLatestCheckpoints int64 err := tx.SelectOne(ctx, &numLatestCheckpoints, "SELECT COUNT(*) FROM latestCheckpoint WHERE mtcLogID = ?", @@ -209,7 +204,7 @@ RootHash: rootHash[:], } - caSig, err := m.signCheckpoint(firstCheckpoint) + caSig, err = m.signCheckpoint(firstCheckpoint) if err != nil { return nil, err } @@ -253,11 +248,13 @@ return fmt.Errorf("fetching first checkpoint: %s", err) } - return err + return m.serveCheckpoint(ctx, tlog.Tree{N: candidate.TreeSize(), Hash: rootHash}, caSig) } -// Preflight gets the latest checkpoint from the database and reads the corresponding -// frontier tiles from storage. It must be called on startup, before Loop(). +// Preflight gets the latest checkpoint from the database, reads the +// corresponding frontier tiles from storage, and serves the checkpoint, in case +// a previous process stopped between publishing tiles and serving. It must be +// called on startup, before Loop(). func (m *mtca) Preflight(ctx context.Context) error { latest, err := treedb.New(m.db).LatestCheckpoint(ctx, m.logID.String()) if err != nil { @@ -277,7 +274,7 @@ } m.frontier = frontier - return nil + return m.serveCheckpoint(ctx, tlog.Tree{N: latest.TreeSize, Hash: tlog.Hash(latest.RootHash)}, latest.MTCASignature) } type pool struct { @@ -428,9 +425,9 @@ } } -// sequence takes all entries from the pool, simulates writing them to tile storage, signs -// and stores a new checkpoint, and notifies waiting RPCs. It also serves the latest -// checkpoint's cosigned note once the mirror signature arrives, when the pool is empty. +// sequence takes all entries from the pool, writes them to tile storage, signs +// a new checkpoint, stores the checkpoint signature, serves the checkpoint, and +// notifies waiting RPCs. // // If the pool is empty, no sequencing happens. // If the pool is non-empty, but the previous checkpoint doesn't have a mirror signature, @@ -446,22 +443,15 @@ return fmt.Errorf("call mtca.Preflight() before sequencing") } + if m.pool.len() == 0 { + return nil + } + latest, err := treedb.New(m.db).LatestCheckpoint(ctx, m.logID.String()) if err != nil { return err } - if latest.Mirrored() { - err = m.serveCheckpoint(ctx, latest) - if err != nil { - return err - } - } - - if m.pool.len() == 0 { - return nil - } - if !latest.Mirrored() { return fmt.Errorf("temporary: checkpoint ID %d (tree size %d): %w", latest.ID, latest.TreeSize, ErrCheckpointNotReady) @@ -540,6 +530,7 @@ return err } + var caSig []byte _, err = db.WithTransaction(ctx, m.db, func(tx db.Executor) (any, error) { var latestID int64 // Lock the latestCheckpoint to make sure there is no concurrent signer/writer, avoiding signing a split view. @@ -558,7 +549,7 @@ // Note that we're doing HSM work while holding a database lock. That's intentional; the database lock // is to prevent the possibility of a concurrent signer on the same tree. - caSig, err := m.signCheckpoint(newCheckpoint) + caSig, err = m.signCheckpoint(newCheckpoint) if err != nil { return nil, err } @@ -613,7 +604,8 @@ // Empty out the entries list so the deferred error path doesn't try to notify them. entries = nil - return nil + // Serve the new checkpoint. + return m.serveCheckpoint(ctx, tlog.Tree{N: candidate.TreeSize(), Hash: newRootHash}, caSig) } func (m *mtca) signCheckpoint(c *treedb.CheckpointModel) ([]byte, error) { @@ -641,52 +633,83 @@ return cosignature.RawSignature(timestampedCosignature) } -// serveCheckpoint writes latest's note, carrying the MTCA signature and a -// mirror cosignature, to the checkpoint path in tile storage. Per CQRP: "In -// order for landmarks to be served by Chrome's Landmark Service, all -// checkpoints MUST be served with a minimum of 2 cosignatures. One of these -// MUST be from the MTC CA Operator and one MUST be from a Mirroring Cosigner -// recognized by Chrome and not operated by the MTC CA Operator." -func (m *mtca) serveCheckpoint(ctx context.Context, latest *treedb.CheckpointModel) error { - if latest.ID == m.servedCheckpointID { - return nil - } - if len(latest.RootHash) != tlog.HashSize { - return fmt.Errorf("checkpoint %d root hash is %d bytes, want %d", latest.ID, len(latest.RootHash), tlog.HashSize) - } - - // Verify the MTCA cosignature and produce its signature line. - tree := tlog.Tree{N: latest.TreeSize, Hash: tlog.Hash(latest.RootHash)} - caCosignatureLine, err := m.verifier.SignatureLine(m.logID.Origin(), tree, latest.MTCASignature) +// serveCheckpoint assembles the signed note for the checkpoint of tree, carrying +// the MTCA cosignature line, verifies it, and writes it to the checkpoint path +// in tile storage. It must be called only after the tiles the tree covers are +// published. +func (m *mtca) serveCheckpoint(ctx context.Context, tree tlog.Tree, mtcaSignature []byte) error { + caCosignatureLine, err := cosignature.SignatureLine(m.verifier.Name(), m.verifier.KeyHash(), mtcaSignature) if err != nil { - return fmt.Errorf("checkpoint %d MTCA signature: %s", latest.ID, err) + return fmt.Errorf("checkpoint of tree size %d MTCA signature: %s", tree.N, err) } - - // Verify the mirror cosignature and produce its signature line. - mirrorID := "" - if latest.MirrorID != nil { - mirrorID = *latest.MirrorID - } - if mirrorID != m.mirrorID { - return fmt.Errorf("checkpoint %d cosigned by mirror %q, want %q", latest.ID, mirrorID, m.mirrorID) - } - mirrorCosignatureLine, err := m.mirrorVerifier.SignatureLine(m.logID.Origin(), tree, latest.MirrorSignature) - if err != nil { - return fmt.Errorf("checkpoint %d mirror cosignature: %s", latest.ID, err) - } - - // Produce a note containing both cosgnatures. + // Produce a signed note containing the MTCA's cosignature line. cp := checkpoint.Checkpoint{Origin: m.logID.Origin(), Tree: tree} - note, err := cp.SignedNoteForServing(caCosignatureLine, mirrorCosignatureLine) + signedNote, err := cp.SignedNote(caCosignatureLine) if err != nil { return err } - // Finally, write it to the checkpoint path for serving. - err = tiles.WriteCheckpoint(ctx, m.s3c, m.logID.TilePrefix(), note) + // Verify the signed note before writing it to storage. + _, _, err = checkpoint.Open(signedNote, m.verifier) if err != nil { - return fmt.Errorf("serving checkpoint %d: %s", latest.ID, err) + return fmt.Errorf("verifying signed checkpoint note of tree size %d: %s", tree.N, err) } - m.servedCheckpointID = latest.ID + + // Finally, write the signed note to the checkpoint path in tile storage. + etag, err := m.writeCheckpoint(ctx, signedNote, m.servedCheckpointETag) + if err != nil { + // Reset the ETag so the next write reads the current one. + if errors.Is(err, ErrCheckpointChanged) { + m.servedCheckpointETag = nil + } + return fmt.Errorf("serving checkpoint of tree size %d: %w", tree.N, err) + } + m.servedCheckpointETag = etag return nil } + +// writeCheckpoint takes the previous ETag, stores signedNote at the log's +// "checkpoint" key per c2sp.org/tlog-tiles and returns the new ETag. It +// replaces only the checkpoint whose ETag is prevETag, reading the current ETag +// first when given none, and returns ErrCheckpointChanged if the stored +// checkpoint does not match. +func (m *mtca) writeCheckpoint(ctx context.Context, signedNote []byte, prevETag *string) (*string, error) { + bucket := m.s3c.Bucket() + key := path.Join(m.logID.TilePrefix(), "checkpoint") + if prevETag == nil { + current, err := m.s3c.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: &key}) + if err == nil { + current.Body.Close() + prevETag = current.ETag + } else { + respErr, ok := errors.AsType[*awshttp.ResponseError](err) + if !ok || respErr.HTTPStatusCode() != http.StatusNotFound { + return nil, fmt.Errorf("reading s3://%s/%s: %w", bucket, key, err) + } + } + } + + contentType := "text/plain; charset=utf-8" + cacheControl := "no-store" + input := &s3.PutObjectInput{ + Bucket: &bucket, + Key: &key, + ContentType: &contentType, + CacheControl: &cacheControl, + Body: bytes.NewReader(signedNote), + IfMatch: prevETag, + } + if prevETag == nil { + star := "*" + input.IfNoneMatch = &star + } + out, err := m.s3c.PutObject(ctx, input) + if err != nil { + respErr, ok := errors.AsType[*awshttp.ResponseError](err) + if ok && respErr.HTTPStatusCode() == http.StatusPreconditionFailed { + return nil, fmt.Errorf("writing s3://%s/%s: %w", bucket, key, ErrCheckpointChanged) + } + return nil, fmt.Errorf("writing s3://%s/%s: %w", bucket, key, err) + } + return out.ETag, nil +}
diff --git a/mtca/mtca_test.go b/mtca/mtca_test.go index d4b03b9..d60eff8 100644 --- a/mtca/mtca_test.go +++ b/mtca/mtca_test.go
@@ -39,11 +39,13 @@ "github.com/letsencrypt/boulder/privatekey" "github.com/letsencrypt/boulder/sa" "github.com/letsencrypt/boulder/test/vars" + "github.com/letsencrypt/boulder/trees/checkpoint" "github.com/letsencrypt/boulder/trees/cosigned" "github.com/letsencrypt/boulder/trees/entry" "github.com/letsencrypt/boulder/trees/issuancelog" "github.com/letsencrypt/boulder/trees/tiles" "github.com/letsencrypt/boulder/trees/treedb" + "golang.org/x/mod/sumdb/tlog" ) // setup returns a working mtca, its fake tile storage, and a cleanup @@ -95,10 +97,6 @@ } fs3 := bs3test.New() - mirrorKey, err := mldsa.NewPrivateKey(mldsa.MLDSA44(), make([]byte, 32)) - if err != nil { - return nil, nil, nil, err - } mtca, err := New( issuer, map[string]*issuance.Profile{"mtcExample": profile}, @@ -106,8 +104,6 @@ 100*time.Millisecond, dbMap, fs3, - "32473.9", - mirrorKey.PublicKey(), logger, clk) if err != nil { @@ -275,6 +271,98 @@ return ch } +// TestWriteCheckpoint checks that writeCheckpoint replaces only the checkpoint +// whose ETag is prevETag, reads the current ETag when given none, and returns +// ErrCheckpointChanged instead of replacing a checkpoint with any other ETag. +func TestWriteCheckpoint(t *testing.T) { + m, fs3, cleanup, err := setup() + if err != nil { + t.Fatalf("setup: %s", err) + } + defer cleanup() + key := m.logID.TilePrefix() + "/checkpoint" + + first, err := m.writeCheckpoint(t.Context(), []byte("first note\n"), nil) + 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") + } + + third, err := m.writeCheckpoint(t.Context(), []byte("third note\n"), nil) + if err != nil { + t.Fatalf("replacing the checkpoint with an unknown ETag: %s", err) + } + if string(fs3.Objects[key].Data) != "third note\n" { + t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "third note\n") + } + if *third == *second { + t.Error("ETag did not change with the checkpoint's contents") + } + + fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} + _, err = m.writeCheckpoint(t.Context(), []byte("fourth note\n"), third) + 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") + } +} + +// 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, cleanup, err := setup() + if err != nil { + t.Fatalf("setup: %s", err) + } + defer cleanup() + + delete(fs3.Objects, m.logID.TilePrefix()+"/checkpoint") + m.servedCheckpointETag = nil + err = m.Preflight(t.Context()) + if err != nil { + t.Fatalf("Preflight: %s", err) + } + verifyStores(t, m, fs3) +} + +// TestServeCheckpointRecovers checks that when the served checkpoint is +// replaced in storage, the next serve fails with ErrCheckpointChanged and the +// one after it reads the current ETag and succeeds. +func TestServeCheckpointRecovers(t *testing.T) { + m, fs3, cleanup, err := setup() + if err != nil { + t.Fatalf("setup: %s", err) + } + defer cleanup() + latest := verifyStores(t, m, fs3) + tree := tlog.Tree{N: latest.TreeSize, Hash: tlog.Hash(latest.RootHash)} + + key := m.logID.TilePrefix() + "/checkpoint" + fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} + err = m.serveCheckpoint(t.Context(), tree, latest.MTCASignature) + if !errors.Is(err, ErrCheckpointChanged) { + t.Errorf("serving over a replaced checkpoint = %s, want ErrCheckpointChanged", err) + } + err = m.serveCheckpoint(t.Context(), tree, latest.MTCASignature) + if err != nil { + t.Fatalf("serving after the checkpoint was replaced: %s", err) + } + verifyStores(t, m, fs3) +} + // 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 { @@ -351,6 +439,19 @@ 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 } @@ -497,13 +598,6 @@ t.Cleanup(cleanup) mirrorCosign(t, mtca) - // Serve the cosigned checkpoint while storage is healthy, so the failure - // below lands on staging. - err = mtca.sequence(t.Context()) - if err != nil { - t.Fatalf("sequencing to serve the cosigned checkpoint: %s", err) - } - mtca.pool.maxSize = 2 results := issueMany(t, mtca, 2) @@ -547,7 +641,7 @@ } func TestInitLog(t *testing.T) { - mtca, _, cleanup, err := setup() + mtca, fs3, cleanup, err := setup() if err != nil { t.Fatalf("setting up mtca: %s", err) } @@ -559,11 +653,7 @@ t.Errorf("second InitLog: got nil error, want error") } - latest, err := treedb.New(mtca.db).LatestCheckpoint(t.Context(), mtca.logID.String()) - if err != nil { - t.Fatalf("getting latest: %s", err) - } - + latest := verifyStores(t, mtca, fs3) if latest.TreeSize != 1 { t.Errorf("just-initialized log: got TreeSize %d, want 1", latest.TreeSize) }
diff --git a/test/config-next/mtca.json b/test/config-next/mtca.json index 01a2d9f..29b3ab7 100644 --- a/test/config-next/mtca.json +++ b/test/config-next/mtca.json
@@ -5,10 +5,6 @@ "logNumber": 44 }, "sequencingPeriod": "100ms", - "mirror": { - "id": "32473.9", - "publicKeyFile": "test/certs/sunlight/mirror.pub.pem" - }, "db": { "dbConnectFile": "test/secrets/mtca1_dburl" },
diff --git a/test/integration/issuance_test.go b/test/integration/issuance_test.go index 8f35f2b..e69533b 100644 --- a/test/integration/issuance_test.go +++ b/test/integration/issuance_test.go
@@ -15,6 +15,7 @@ "net" "net/http" "os" + "strconv" "strings" "testing" "time" @@ -210,32 +211,57 @@ t.Fatalf("issuing certificate: expected 'finalized order timeout', got %q", err) } - // The mtpublisher submits each checkpoint to the sunlight mirror, and the - // mtca serves it once cosigned, so the served checkpoint and the mirror's - // checkpoint must converge on the same tree head. They update a sequencing - // period apart, so poll until they agree. + // The mtca serves each checkpoint as soon as it is sequenced, and the + // mtpublisher then submits it to the sunlight mirror, so the mirror's + // checkpoint must converge on the served tree head. Poll until they agree. + origin := "oid/1.3.6.1.4.1.44947.4.1.0.44" + originHash := sha256.Sum256([]byte(origin)) localURL := "http://boulder-minio:9000/boulder-mtc-tiles/44947.4.1/44/checkpoint" - originHash := sha256.Sum256([]byte("oid/1.3.6.1.4.1.44947.4.1.0.44")) mirrorURL := "http://boulder-minio:9000/boulder-sunlight/mirror/" + hex.EncodeToString(originHash[:]) + "/checkpoint" deadline := time.Now().Add(5 * time.Second) + var localText string + var localSignatures string + var mirrorSignatures string for { - local := checkpointText(t, localURL) - mirror := checkpointText(t, mirrorURL) - if local != "" && local == mirror { + var mirrorText string + localText, localSignatures = checkpointNote(t, localURL) + mirrorText, mirrorSignatures = checkpointNote(t, mirrorURL) + if localText != "" && localText == mirrorText { break } if time.Now().After(deadline) { - t.Fatalf("served checkpoint %q and mirror checkpoint %q have not converged", local, mirror) + t.Fatalf("served checkpoint %q and mirror checkpoint %q have not converged", localText, mirrorText) } time.Sleep(100 * time.Millisecond) } + + // The checkpoint names the issuance log and covers at least the genesis + // null entry and the entry issued above. + lines := strings.Split(localText, "\n") + if lines[0] != origin { + t.Errorf("checkpoint origin = %q, want %q", lines[0], origin) + } + size, err := strconv.Atoi(lines[1]) + if err != nil || size < 2 { + t.Errorf("checkpoint tree size = %q, want at least 2", lines[1]) + } + + // The served checkpoint carries only the MTCA's signature. The mirror's + // checkpoint carries that same line. + caLine := "— oid/1.3.6.1.4.1.44947.4.1 " + if strings.Count(localSignatures, "\n") != 1 || !strings.HasPrefix(localSignatures, caLine) { + t.Errorf("served checkpoint signatures %q, want one line by the MTCA", localSignatures) + } + if !strings.Contains(mirrorSignatures, localSignatures) { + t.Errorf("mirror checkpoint signatures %q do not include the served MTCA line %q", mirrorSignatures, localSignatures) + } } -// checkpointText fetches a signed checkpoint note from url and returns its -// text, the part before the signature lines. It returns "" while the checkpoint -// does not exist yet. -func checkpointText(t *testing.T, url string) string { +// checkpointNote fetches a signed checkpoint note from url and returns its text +// and its signature lines. It returns empty strings while the checkpoint does +// not exist yet. +func checkpointNote(t *testing.T, url string) (string, string) { t.Helper() resp, err := http.Get(url) if err != nil { @@ -247,16 +273,16 @@ t.Fatalf("reading %s: %s", url, err) } if resp.StatusCode == http.StatusNotFound { - return "" + return "", "" } if resp.StatusCode != http.StatusOK { t.Fatalf("fetching %s: status %d", url, resp.StatusCode) } - text, _, ok := strings.Cut(string(body), "\n\n") + text, signatureLines, ok := strings.Cut(string(body), "\n\n") if !ok { t.Fatalf("checkpoint at %s has no signature lines: %q", url, body) } - return text + return text, signatureLines } // TestIPShortLived verifies that we will allow IP address identifiers only in
diff --git a/trees/checkpoint/checkpoint.go b/trees/checkpoint/checkpoint.go index c1c2e43..0264936 100644 --- a/trees/checkpoint/checkpoint.go +++ b/trees/checkpoint/checkpoint.go
@@ -108,32 +108,6 @@ return append(append(text, '\n'), signatureLines...), nil } -// signedNote returns the checkpoint as a signed note: the note text followed by -// the given signature line(s). -func (c *Checkpoint) signedNote(signatureLines ...[]byte) ([]byte, error) { - text, err := c.Marshal() - if err != nil { - return nil, err - } - assembled := append(text, '\n') - for _, line := range signatureLines { - assembled = append(assembled, line...) - } - return assembled, nil -} - -// SignedNoteForServing returns the checkpoint as a signed note carrying the -// MTCA and mirror cosignature lines, for serving at the checkpoint path. -func (c *Checkpoint) SignedNoteForServing(caCosignatureLine, mirrorCosignatureLine []byte) ([]byte, error) { - if len(caCosignatureLine) == 0 { - return nil, errors.New("missing MTCA cosignature line") - } - if len(mirrorCosignatureLine) == 0 { - return nil, errors.New("missing mirror cosignature line") - } - return c.signedNote(caCosignatureLine, mirrorCosignatureLine) -} - // Unmarshal parses a checkpoint note text. The text must not have any signature // lines. For a signed note, use Open. //
diff --git a/trees/checkpoint/checkpoint_test.go b/trees/checkpoint/checkpoint_test.go index ba927a4..5cdfee3 100644 --- a/trees/checkpoint/checkpoint_test.go +++ b/trees/checkpoint/checkpoint_test.go
@@ -178,35 +178,6 @@ } } -// TestSignedNotes checks note assembly through SignedNoteForServing and that -// it rejects a missing signature line. -func TestSignedNotes(t *testing.T) { - cp := &Checkpoint{Origin: "example.com/log", Tree: tlog.Tree{N: 5}} - text, err := cp.Marshal() - if err != nil { - t.Fatalf("Marshal: %s", err) - } - caLine := []byte("— ca sig\n") - mirrorLine := []byte("— mirror sig\n") - - forServing, err := cp.SignedNoteForServing(caLine, mirrorLine) - if err != nil { - t.Fatalf("SignedNoteForServing: %s", err) - } - if string(forServing) != string(text)+"\n"+string(caLine)+string(mirrorLine) { - t.Errorf("SignedNoteForServing = %q", forServing) - } - - _, err = cp.SignedNoteForServing(nil, mirrorLine) - if err == nil { - t.Error("SignedNoteForServing without the MTCA line = nil error, want error") - } - _, err = cp.SignedNoteForServing(caLine, nil) - if err == nil { - t.Error("SignedNoteForServing without the mirror line = nil error, want error") - } -} - // TestOpenCheckpoint covers Open's happy path and its rejection of a note no // trusted key signed, using a generic note signer. func TestOpenCheckpoint(t *testing.T) {
diff --git a/trees/cosignature/cosignature.go b/trees/cosignature/cosignature.go index 44c8ebc..2e2d7fe 100644 --- a/trees/cosignature/cosignature.go +++ b/trees/cosignature/cosignature.go
@@ -256,31 +256,6 @@ return idSignature[keyIDSize:], nil } -// signatureLineFor assembles the signature line "— <name> base64(keyID || -// timestamped_signature)\n". -func signatureLineFor(name string, keyID uint32, timestampedSignature []byte) string { - idSignature := make([]byte, keyIDSize+len(timestampedSignature)) - binary.BigEndian.PutUint32(idSignature[:keyIDSize], keyID) - copy(idSignature[keyIDSize:], timestampedSignature) - return noteSignatureLinePrefix + name + " " + base64.StdEncoding.EncodeToString(idSignature) + "\n" -} - -// SignatureLine verifies rawSignature over the checkpoint described by origin -// and tree, and reassembles the cosigner's note signature line, restoring the -// zero timestamp RawSignature stripped. -func (v *Verifier) SignatureLine(origin string, tree tlog.Tree, rawSignature []byte) ([]byte, error) { - if len(rawSignature) != mldsa.MLDSA44SignatureSize { - return nil, fmt.Errorf("raw signature is %d bytes, want %d", len(rawSignature), mldsa.MLDSA44SignatureSize) - } - timestamped := make([]byte, timestampedSignatureSize) - copy(timestamped[timestampSize:], rawSignature) - err := v.VerifyCheckpoint(origin, tree, timestamped) - if err != nil { - return nil, err - } - return []byte(signatureLineFor(v.keyName, v.keyID, timestamped)), nil -} - // RawSignature returns the ML-DSA-44 signature from a timestamped_signature, // the form certificates embed. It errors if the input has the wrong length or a // non-zero timestamp, which certificates cannot carry.
diff --git a/trees/tiles/tiles.go b/trees/tiles/tiles.go index 038014f..af5c03d 100644 --- a/trees/tiles/tiles.go +++ b/trees/tiles/tiles.go
@@ -846,24 +846,3 @@ } return body[entriesBegin : len(body)-len(rest)], nil } - -// WriteCheckpoint stores the log's signed checkpoint note at the "checkpoint" -// key under prefix per c2sp.org/tlog-tiles, overwriting the previous one. The -// note must be written only after the tiles its tree covers are published. -func WriteCheckpoint(ctx context.Context, s3c simpleS3, prefix string, signedNote []byte) error { - key := path.Join(prefix, "checkpoint") - contentType := "text/plain; charset=utf-8" - cacheControl := "no-store" - bucket := s3c.Bucket() - _, err := s3c.PutObject(ctx, &s3.PutObjectInput{ - Bucket: &bucket, - Key: &key, - ContentType: &contentType, - CacheControl: &cacheControl, - Body: bytes.NewReader(signedNote), - }) - if err != nil { - return fmt.Errorf("writing s3://%s/%s: %w", bucket, key, err) - } - return nil -}
diff --git a/trees/tiles/tiles_test.go b/trees/tiles/tiles_test.go index 191267a..a5ca253 100644 --- a/trees/tiles/tiles_test.go +++ b/trees/tiles/tiles_test.go
@@ -620,36 +620,6 @@ } } -// readCheckpoint fetches the "checkpoint" key under prefix, checking what -// WriteCheckpoint stored. Nothing outside tests reads it back through this -// package. -func readCheckpoint(t *testing.T, s3c *bs3test.FakeS3, prefix string) []byte { - t.Helper() - obj, ok := s3c.Objects[prefix+"/checkpoint"] - if !ok { - t.Fatalf("no checkpoint stored under %q", prefix) - } - return obj.Data -} - -// TestWriteReadCheckpoint checks the checkpoint note round trip and that a -// newer note overwrites the previous one. -func TestWriteReadCheckpoint(t *testing.T) { - fs3 := bs3test.New() - err := WriteCheckpoint(t.Context(), fs3, testPrefix, []byte("first note\n")) - if err != nil { - t.Fatalf("WriteCheckpoint: %s", err) - } - err = WriteCheckpoint(t.Context(), fs3, testPrefix, []byte("second note\n")) - if err != nil { - t.Fatalf("WriteCheckpoint overwriting: %s", err) - } - got := readCheckpoint(t, fs3, testPrefix) - if string(got) != "second note\n" { - t.Errorf("stored checkpoint = %q, want %q", got, "second note\n") - } -} - // TestEntriesForPackage checks reading entry intervals back from stored // bundles in wire form, from both full and partial bundles, and that invalid // and bundle-spanning intervals are rejected.