Use time format constants (#6694)

Use constants from the go stdlib time package, such as time.DateTime and
time.RFC3339, when parsing and formatting timestamps. Additionally,
simplify or remove some of our uses of parsing timestamps, such as to
set fake clocks in tests.
This commit is contained in:
Aaron Gable 2023-02-24 11:22:23 -08:00 committed by GitHub
parent 991995cb5c
commit 5ce4b5a6d4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 60 additions and 97 deletions

View File

@ -1003,7 +1003,7 @@ func TestOrphanQueue(t *testing.T) {
qsa := &queueSA{fail: true}
testCtx := setup(t)
fakeNow, err := time.Parse("Mon Jan 2 15:04:05 2006", "Mon Jan 2 15:04:05 2006")
fakeNow, err := time.Parse(time.ANSIC, "Mon Jan 2 15:04:05 2006")
if err != nil {
t.Fatal(err)
}

View File

@ -99,7 +99,7 @@ func TestRevokeIncidentTableSerials(t *testing.T) {
core.SerialToString(entries[0].serial),
entries[0].regId,
42,
testCtx.revoker.clk.Now().Add(-time.Hour*24*7).Format("2006-01-02 15:04:05"),
testCtx.revoker.clk.Now().Add(-time.Hour*24*7).Format(time.DateTime),
),
)
test.AssertNotError(t, err, "while inserting row into incident table")

View File

@ -284,12 +284,12 @@ func makeTemplate(randReader io.Reader, profile *certProfile, pubKey []byte, ct
return nil, fmt.Errorf("unsupported signature algorithm %q", profile.SignatureAlgorithm)
}
cert.SignatureAlgorithm = sigAlg
notBefore, err := time.Parse(configDateLayout, profile.NotBefore)
notBefore, err := time.Parse(time.DateTime, profile.NotBefore)
if err != nil {
return nil, err
}
cert.NotBefore = notBefore
notAfter, err := time.Parse(configDateLayout, profile.NotAfter)
notAfter, err := time.Parse(time.DateTime, profile.NotAfter)
if err != nil {
return nil, err
}

View File

@ -22,8 +22,6 @@ import (
"gopkg.in/yaml.v3"
)
const configDateLayout = "2006-01-02 15:04:05"
type keyGenConfig struct {
Type string `yaml:"type"`
RSAModLength uint `yaml:"rsa-mod-length"`
@ -662,11 +660,11 @@ func ocspRespCeremony(configBytes []byte) error {
}
}
thisUpdate, err := time.Parse(configDateLayout, config.OCSPProfile.ThisUpdate)
thisUpdate, err := time.Parse(time.DateTime, config.OCSPProfile.ThisUpdate)
if err != nil {
return fmt.Errorf("unable to parse ocsp-profile.this-update: %s", err)
}
nextUpdate, err := time.Parse(configDateLayout, config.OCSPProfile.NextUpdate)
nextUpdate, err := time.Parse(time.DateTime, config.OCSPProfile.NextUpdate)
if err != nil {
return fmt.Errorf("unable to parse ocsp-profile.next-update: %s", err)
}
@ -714,11 +712,11 @@ func crlCeremony(configBytes []byte) error {
return err
}
thisUpdate, err := time.Parse(configDateLayout, config.CRLProfile.ThisUpdate)
thisUpdate, err := time.Parse(time.DateTime, config.CRLProfile.ThisUpdate)
if err != nil {
return fmt.Errorf("unable to parse crl-profile.this-update: %s", err)
}
nextUpdate, err := time.Parse(configDateLayout, config.CRLProfile.NextUpdate)
nextUpdate, err := time.Parse(time.DateTime, config.CRLProfile.NextUpdate)
if err != nil {
return fmt.Errorf("unable to parse crl-profile.next-update: %s", err)
}
@ -729,7 +727,7 @@ func crlCeremony(configBytes []byte) error {
if err != nil {
return fmt.Errorf("failed to load revoked certificate %q: %s", rc.CertificatePath, err)
}
revokedAt, err := time.Parse(configDateLayout, rc.RevocationDate)
revokedAt, err := time.Parse(time.DateTime, rc.RevocationDate)
if err != nil {
return fmt.Errorf("unable to parse crl-profile.revoked-certificates.revocation-date")
}

View File

@ -504,7 +504,7 @@ func (m *mailer) findExpiringCertificates(ctx context.Context) error {
m.stats.nagsAtCapacity.With(prometheus.Labels{"nag_group": expiresIn.String()}).Set(atCapacity)
m.log.Infof("Found %d certificates expiring between %s and %s", len(certs),
left.Format("2006-01-02 03:04"), right.Format("2006-01-02 03:04"))
left.Format(time.DateTime), right.Format(time.DateTime))
if len(certs) == 0 {
continue // nothing to do

View File

@ -51,17 +51,6 @@ func newFakeRegStore() fakeRegStore {
return fakeRegStore{RegByID: make(map[int64]*corepb.Registration)}
}
func newFakeClock(t *testing.T) clock.FakeClock {
const fakeTimeFormat = "2006-01-02T15:04:05.999999999Z"
ft, err := time.Parse(fakeTimeFormat, fakeTimeFormat)
if err != nil {
t.Fatal(err)
}
fc := clock.NewFake()
fc.Set(ft.UTC())
return fc
}
const testTmpl = `hi, cert for DNS names {{.DNSNames}} is going to expire in {{.DaysToExpiration}} days ({{.ExpirationDate}})`
const testEmailSubject = `email subject for test`
const emailARaw = "rolandshoemaker@gmail.com"
@ -92,7 +81,7 @@ var (
func TestSendNagsManyCerts(t *testing.T) {
mc := mocks.Mailer{}
rs := newFakeRegStore()
fc := newFakeClock(t)
fc := clock.NewFake()
staticTmpl := template.Must(template.New("expiry-email-subject-static").Parse(testEmailSubject))
tmpl := template.Must(template.New("expiry-email").Parse(
@ -133,7 +122,7 @@ func TestSendNagsManyCerts(t *testing.T) {
func TestSendNags(t *testing.T) {
mc := mocks.Mailer{}
rs := newFakeRegStore()
fc := newFakeClock(t)
fc := clock.NewFake()
staticTmpl := template.Must(template.New("expiry-email-subject-static").Parse(testEmailSubject))
@ -161,11 +150,11 @@ func TestSendNags(t *testing.T) {
err = m.sendNags(conn, []string{emailA}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "Failed to send warning messages")
test.AssertEquals(t, len(mc.Messages), 1)
test.AssertEquals(t, mocks.MailerMessage{
test.AssertEquals(t, mc.Messages[0], mocks.MailerMessage{
To: emailARaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.DateOnly)),
}, mc.Messages[0])
})
mc.Clear()
conn, err = m.mailer.Connect()
@ -173,16 +162,16 @@ func TestSendNags(t *testing.T) {
err = m.sendNags(conn, []string{emailA, emailB}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "Failed to send warning messages")
test.AssertEquals(t, len(mc.Messages), 2)
test.AssertEquals(t, mocks.MailerMessage{
test.AssertEquals(t, mc.Messages[0], mocks.MailerMessage{
To: emailARaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.DateOnly)),
}, mc.Messages[0])
test.AssertEquals(t, mocks.MailerMessage{
})
test.AssertEquals(t, mc.Messages[1], mocks.MailerMessage{
To: emailBRaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.DateOnly)),
}, mc.Messages[1])
})
mc.Clear()
conn, err = m.mailer.Connect()
@ -212,7 +201,7 @@ func TestSendNags(t *testing.T) {
func TestSendNagsAddressLimited(t *testing.T) {
mc := mocks.Mailer{}
rs := newFakeRegStore()
fc := newFakeClock(t)
fc := clock.NewFake()
staticTmpl := template.Must(template.New("expiry-email-subject-static").Parse(testEmailSubject))
@ -251,11 +240,11 @@ func TestSendNagsAddressLimited(t *testing.T) {
err = m.sendNags(conn, []string{emailA, emailB}, []*x509.Certificate{cert})
test.AssertNotError(t, err, "sending warning messages to two addresses")
test.AssertEquals(t, len(mc.Messages), 1)
test.AssertEquals(t, mocks.MailerMessage{
test.AssertEquals(t, mc.Messages[0], mocks.MailerMessage{
To: emailBRaw,
Subject: testEmailSubject,
Body: fmt.Sprintf(`hi, cert for DNS names example.com is going to expire in 2 days (%s)`, cert.NotAfter.Format(time.DateOnly)),
}, mc.Messages[0])
})
}
var serial1 = big.NewInt(0x1336)
@ -289,9 +278,9 @@ func TestProcessCerts(t *testing.T) {
// Test that the lastExpirationNagSent was updated for the certificate
// corresponding to serial4, which is set up as "already renewed" by
// addExpiringCerts.
if len(testCtx.log.GetAllMatching("DEBUG: SQL: UPDATE certificateStatus .*2006-01-02 15:04:05.999999999.*\"000000000000000000000000000000001339\"")) != 1 {
if len(testCtx.log.GetAllMatching("UPDATE certificateStatus.*000000000000000000000000000000001339")) != 1 {
t.Errorf("Expected an update to certificateStatus, got these log lines:\n%s",
strings.Join(testCtx.log.GetAllMatching(".*"), "\n"))
strings.Join(testCtx.log.GetAll(), "\n"))
}
}
@ -396,9 +385,9 @@ func TestProcessCertsParallel(t *testing.T) {
// Test that the lastExpirationNagSent was updated for the certificate
// corresponding to serial4, which is set up as "already renewed" by
// addExpiringCerts.
if len(testCtx.log.GetAllMatching("DEBUG: SQL: UPDATE certificateStatus .*2006-01-02 15:04:05.999999999.*\"000000000000000000000000000000001339\"")) != 1 {
if len(testCtx.log.GetAllMatching("UPDATE certificateStatus.*000000000000000000000000000000001339")) != 1 {
t.Errorf("Expected an update to certificateStatus, got these log lines:\n%s",
strings.Join(testCtx.log.GetAllMatching(".*"), "\n"))
strings.Join(testCtx.log.GetAll(), "\n"))
}
}
@ -439,20 +428,20 @@ func TestFindExpiringCertificates(t *testing.T) {
builder.String())
}
test.AssertEquals(t, mocks.MailerMessage{
test.AssertEquals(t, testCtx.mc.Messages[0], mocks.MailerMessage{
To: emailARaw,
// A certificate with only one domain should have only one domain listed in
// the subject
Subject: "Testing: Let's Encrypt certificate expiration notice for domain \"example-a.com\"",
Body: "hi, cert for DNS names example-a.com is going to expire in 0 days (2006-01-03)",
}, testCtx.mc.Messages[0])
test.AssertEquals(t, mocks.MailerMessage{
Body: "hi, cert for DNS names example-a.com is going to expire in 0 days (1970-01-01)",
})
test.AssertEquals(t, testCtx.mc.Messages[1], mocks.MailerMessage{
To: emailBRaw,
// A certificate with two domains should have only one domain listed and an
// additional count included
Subject: "Testing: Let's Encrypt certificate expiration notice for domain \"another.example-c.com\" (and 1 more)",
Body: "hi, cert for DNS names another.example-c.com\nexample-c.com is going to expire in 7 days (2006-01-09)",
}, testCtx.mc.Messages[1])
Body: "hi, cert for DNS names another.example-c.com\nexample-c.com is going to expire in 7 days (1970-01-08)",
})
// Check that regC's only certificate being renewed does not cause a log
test.AssertEquals(t, len(testCtx.log.GetAllMatching("no certs given to send nags for")), 0)
@ -893,6 +882,8 @@ func TestDedupOnRegistration(t *testing.T) {
72*time.Hour,
testCtx.fc)
test.AssertNotError(t, err, "making certificate")
err = insertCertificate(certA, time.Time{})
test.AssertNotError(t, err, "inserting certificate")
certB, err := makeCertificate(
regA.Id,
@ -901,14 +892,11 @@ func TestDedupOnRegistration(t *testing.T) {
48*time.Hour,
testCtx.fc)
test.AssertNotError(t, err, "making certificate")
err = insertCertificate(certB, time.Time{})
test.AssertNotError(t, err, "inserting certificate")
expires := testCtx.fc.Now().Add(48 * time.Hour)
err = insertCertificate(certA, time.Unix(0, 0))
test.AssertNotError(t, err, "inserting certificate")
err = insertCertificate(certB, time.Unix(0, 0))
test.AssertNotError(t, err, "inserting certificate")
err = testCtx.m.findExpiringCertificates(context.Background())
test.AssertNotError(t, err, "error calling findExpiringCertificates")
if len(testCtx.mc.Messages) > 1 {
@ -918,16 +906,15 @@ func TestDedupOnRegistration(t *testing.T) {
t.Fatalf("no messages sent")
}
domains := "example-a.com\nexample-b.com\nshared-example.com"
expected := mocks.MailerMessage{
test.AssertEquals(t, testCtx.mc.Messages[0], mocks.MailerMessage{
To: emailARaw,
// A certificate with three domain names should have one in the subject and
// a count of '2 more' at the end
Subject: "Testing: Let's Encrypt certificate expiration notice for domain \"example-a.com\" (and 2 more)",
Body: fmt.Sprintf(`hi, cert for DNS names %s is going to expire in 1 days (%s)`,
Body: fmt.Sprintf(`hi, cert for DNS names %s is going to expire in 2 days (%s)`,
domains,
expires.Format(time.DateOnly)),
}
test.AssertEquals(t, expected, testCtx.mc.Messages[0])
})
}
type testCtx struct {
@ -948,7 +935,7 @@ func setup(t *testing.T, nagTimes []time.Duration) *testCtx {
t.Fatalf("Couldn't connect the database: %s", err)
}
fc := newFakeClock(t)
fc := clock.NewFake()
log := blog.NewMock()
ssa, err := sa.NewSQLStorageAuthority(dbMap, dbMap, nil, 1, 0, fc, log, metrics.NoopRegisterer)
if err != nil {

View File

@ -334,7 +334,7 @@ func (tc testCtx) addCertificates(t *testing.T) {
Primes: []*big.Int{p, q},
}
fc := newFakeClock(t)
fc := clock.NewFake()
// Add one cert for RegA that expires in 30 days
rawCertA := x509.Certificate{
@ -439,6 +439,7 @@ func (tc testCtx) addCertificates(t *testing.T) {
func setup(t *testing.T) testCtx {
log := blog.UseMock()
fc := clock.NewFake()
// Using DBConnSAFullPerms to be able to insert registrations and certificates
dbMap, err := sa.NewDbMap(vars.DBConnSAFullPerms, sa.DbSettings{})
@ -447,7 +448,6 @@ func setup(t *testing.T) testCtx {
}
cleanUp := test.ResetBoulderTestDatabase(t)
fc := newFakeClock(t)
ssa, err := sa.NewSQLStorageAuthority(dbMap, dbMap, nil, 1, 0, fc, log, metrics.NoopRegisterer)
if err != nil {
t.Fatalf("unable to create SQLStorageAuthority: %s", err)
@ -474,14 +474,3 @@ func bigIntFromB64(b64 string) *big.Int {
func intFromB64(b64 string) int {
return int(bigIntFromB64(b64).Int64())
}
func newFakeClock(t *testing.T) clock.FakeClock {
const fakeTimeFormat = "2006-01-02T15:04:05.999999999Z"
ft, err := time.Parse(fakeTimeFormat, fakeTimeFormat)
if err != nil {
t.Fatal(err)
}
fc := clock.NewFake()
fc.Set(ft.UTC())
return fc
}

View File

@ -236,7 +236,7 @@ func TestMakeMessageBody(t *testing.T) {
emailTemplate: template.Must(template.New("email").Parse(emailTemplate)).Option("missingkey=error"),
sleepInterval: 0,
targetRange: interval{end: "\xFF"},
clk: newFakeClock(t),
clk: clock.NewFake(),
recipients: nil,
dbMap: mockEmailResolver{},
}
@ -286,7 +286,7 @@ func TestSleepInterval(t *testing.T) {
sleepInterval: sleepLen * time.Second,
parallelSends: 1,
targetRange: interval{start: "", end: "\xFF"},
clk: newFakeClock(t),
clk: clock.NewFake(),
recipients: recipients,
dbMap: dbMap,
}
@ -296,7 +296,7 @@ func TestSleepInterval(t *testing.T) {
// elapsed
err := m.run()
test.AssertNotError(t, err, "error calling mailer run()")
expectedEnd := newFakeClock(t)
expectedEnd := clock.NewFake()
expectedEnd.Add(time.Second * time.Duration(sleepLen*len(recipients)))
test.AssertEquals(t, m.clk.Now(), expectedEnd.Now())
@ -307,7 +307,7 @@ func TestSleepInterval(t *testing.T) {
emailTemplate: tmpl,
sleepInterval: 0,
targetRange: interval{end: "\xFF"},
clk: newFakeClock(t),
clk: clock.NewFake(),
recipients: recipients,
dbMap: dbMap,
}
@ -316,7 +316,7 @@ func TestSleepInterval(t *testing.T) {
// After it returns, we expect no clock time to have elapsed on the fake clock
err = m.run()
test.AssertNotError(t, err, "error calling mailer run()")
expectedEnd = newFakeClock(t)
expectedEnd = clock.NewFake()
test.AssertEquals(t, m.clk.Now(), expectedEnd.Now())
}
@ -340,7 +340,7 @@ func TestMailIntervals(t *testing.T) {
emailTemplate: tmpl,
targetRange: interval{start: "\xFF", end: "\xFF\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer. It should produce an error about the interval start
@ -359,7 +359,7 @@ func TestMailIntervals(t *testing.T) {
emailTemplate: tmpl,
targetRange: interval{},
sleepInterval: -10,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer. It should produce an error about the sleep interval
@ -379,7 +379,7 @@ func TestMailIntervals(t *testing.T) {
emailTemplate: tmpl,
targetRange: interval{start: "test-example-updated@letsencrypt.org", end: "\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer. Two messages should have been produced, one to
@ -411,7 +411,7 @@ func TestMailIntervals(t *testing.T) {
emailTemplate: tmpl,
targetRange: interval{end: "test-example-updated@letsencrypt.org"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer. Two messages should have been produced, one to
@ -452,7 +452,7 @@ func TestParallelism(t *testing.T) {
targetRange: interval{end: "\xFF"},
sleepInterval: 0,
parallelSends: 10,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
mc.Clear()
@ -461,7 +461,7 @@ func TestParallelism(t *testing.T) {
// The fake clock should have advanced 9 seconds, one for each parallel
// goroutine after the first doing its polite 1-second sleep at startup.
expectedEnd := newFakeClock(t)
expectedEnd := clock.NewFake()
expectedEnd.Add(9 * time.Second)
test.AssertEquals(t, m.clk.Now(), expectedEnd.Now())
@ -494,7 +494,7 @@ func TestMessageContentStatic(t *testing.T) {
emailTemplate: template.Must(template.New("letter").Parse("an email body")),
targetRange: interval{end: "\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer, one message should have been created with the content
@ -531,7 +531,7 @@ func TestMessageContentInterpolated(t *testing.T) {
`issued by {{range .}}{{ .Data.validationMethod }}{{end}}`)),
targetRange: interval{end: "\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer, one message should have been created with the content
@ -589,7 +589,7 @@ func TestMessageContentInterpolatedMultiple(t *testing.T) {
{{end}}Thanks`)),
targetRange: interval{end: "\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
// Run the mailer, one message should have been created with the content
@ -759,7 +759,7 @@ func TestResolveEmails(t *testing.T) {
emailTemplate: tmpl,
targetRange: interval{end: "\xFF"},
sleepInterval: 0,
clk: newFakeClock(t),
clk: clock.NewFake(),
}
addressesToRecipients, err := m.resolveAddresses()
@ -779,14 +779,3 @@ func TestResolveEmails(t *testing.T) {
}
}
}
func newFakeClock(t *testing.T) clock.FakeClock {
const fakeTimeFormat = "2006-01-02T15:04:05.999999999Z"
ft, err := time.Parse(fakeTimeFormat, fakeTimeFormat)
if err != nil {
t.Fatal(err)
}
fc := clock.NewFake()
fc.Set(ft.UTC())
return fc
}

View File

@ -2647,7 +2647,7 @@ func TestIncidentsForSerial(t *testing.T) {
affectedCertA.Serial,
affectedCertA.RegistrationID,
affectedCertA.OrderID,
affectedCertA.LastNoticeSent.Format("2006-01-02 15:04:05"),
affectedCertA.LastNoticeSent.Format(time.DateTime),
),
)
test.AssertNotError(t, err, "Error while inserting row for '1338' into incident table")
@ -2670,7 +2670,7 @@ func TestIncidentsForSerial(t *testing.T) {
affectedCertB.Serial,
affectedCertB.RegistrationID,
affectedCertB.OrderID,
affectedCertB.LastNoticeSent.Format("2006-01-02 15:04:05"),
affectedCertB.LastNoticeSent.Format(time.DateTime),
),
)
test.AssertNotError(t, err, "Error while inserting row for '1337' into incident table")
@ -2777,7 +2777,7 @@ func TestSerialsForIncident(t *testing.T) {
i,
randInt(),
randInt(),
sa.clk.Now().Add(time.Hour*24*7).Format("2006-01-02 15:04:05"),
sa.clk.Now().Add(time.Hour*24*7).Format(time.DateTime),
),
)
test.AssertNotError(t, err, fmt.Sprintf("Error while inserting row for '%s' into incident table", i))

View File

@ -415,7 +415,7 @@ func (s *State) Run(
curReqTotal := atomic.LoadInt64(&s.reqTotal)
fmt.Printf(
"%s Action rate: %d/s [expected: %d/s], Request rate: %d/s, Responses: [%s]\n",
time.Now().Format("2006-01-02 15:04:05"),
time.Now().Format(time.DateTime),
curTotal-lastTotal,
atomic.LoadInt64(&p.Rate),
curReqTotal-lastReqTotal,