context.Context as the first parameter of all RPC calls (#1741)

Change core/interfaces to put context.Context as the first parameter of all RPC calls in preparation for gRPC.
This commit is contained in:
Kane York 2016-04-19 11:34:36 -07:00
parent 0c1ddccd9c
commit b7cf618f5d
40 changed files with 984 additions and 892 deletions

View File

@ -23,6 +23,8 @@ import (
"strings"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
cfsslConfig "github.com/cloudflare/cfssl/config"
cferr "github.com/cloudflare/cfssl/errors"
@ -118,7 +120,7 @@ const (
)
type certificateStorage interface {
AddCertificate([]byte, int64) (string, error)
AddCertificate(context.Context, []byte, int64) (string, error)
}
// CertificateAuthorityImpl represents a CA that signs certificates, CRLs, and
@ -357,7 +359,7 @@ func (ca *CertificateAuthorityImpl) extensionsFromCSR(csr *x509.CertificateReque
}
// GenerateOCSP produces a new OCSP response and returns it
func (ca *CertificateAuthorityImpl) GenerateOCSP(xferObj core.OCSPSigningRequest) ([]byte, error) {
func (ca *CertificateAuthorityImpl) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) ([]byte, error) {
cert, err := x509.ParseCertificate(xferObj.CertDER)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
@ -394,7 +396,7 @@ func (ca *CertificateAuthorityImpl) GenerateOCSP(xferObj core.OCSPSigningRequest
// enforcing all policies. Names (domains) in the CertificateRequest will be
// lowercased before storage.
// Currently it will always sign with the defaultIssuer.
func (ca *CertificateAuthorityImpl) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
func (ca *CertificateAuthorityImpl) IssueCertificate(ctx context.Context, csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
emptyCert := core.Certificate{}
key, ok := csr.PublicKey.(crypto.PublicKey)
@ -584,7 +586,7 @@ func (ca *CertificateAuthorityImpl) IssueCertificate(csr x509.CertificateRequest
}
// Store the cert with the certificate authority, if provided
_, err = ca.SA.AddCertificate(certDER, regID)
_, err = ca.SA.AddCertificate(ctx, certDER, regID)
if err != nil {
err = core.InternalServerError(err.Error())
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
@ -600,7 +602,8 @@ func (ca *CertificateAuthorityImpl) IssueCertificate(csr x509.CertificateRequest
// Submit the certificate to any configured CT logs
go func() {
_ = ca.Publisher.SubmitToCT(certDER)
ctx := context.Background()
_ = ca.Publisher.SubmitToCT(ctx, certDER)
}()
// Do not return an err at this point; caller must know that the Certificate

View File

@ -20,6 +20,7 @@ import (
"github.com/cloudflare/cfssl/helpers"
"github.com/jmhodges/clock"
"golang.org/x/crypto/ocsp"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/core"
@ -165,13 +166,14 @@ type mockSA struct {
certificate core.Certificate
}
func (m *mockSA) AddCertificate(der []byte, _ int64) (string, error) {
func (m *mockSA) AddCertificate(ctx context.Context, der []byte, _ int64) (string, error) {
m.certificate.DER = der
return "", nil
}
var caKey crypto.Signer
var caCert *x509.Certificate
var ctx = context.Background()
func init() {
var err error
@ -286,31 +288,31 @@ func setup(t *testing.T) *testCtx {
}
func TestFailNoSerial(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ctx.caConfig.SerialPrefix = 0
testCtx.caConfig.SerialPrefix = 0
_, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertError(t, err, "CA should have failed with no SerialPrefix")
}
func TestIssueCertificate(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
sa := &mockSA{}
ca.SA = sa
@ -319,7 +321,7 @@ func TestIssueCertificate(t *testing.T) {
csr, _ := x509.ParseCertificateRequest(csrDER)
// Sign CSR
issuedCert, err := ca.IssueCertificate(*csr, 1001)
issuedCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to sign certificate")
if err != nil {
continue
@ -365,8 +367,8 @@ func TestIssueCertificate(t *testing.T) {
// Test issuing when multiple issuers are present.
func TestIssueCertificateMultipleIssuers(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
// Load multiple issuers, and ensure the first one in the list is used.
newIssuerCert, err := core.LoadCert("../test/test-ca2.pem")
test.AssertNotError(t, err, "Failed to load new cert")
@ -381,18 +383,18 @@ func TestIssueCertificateMultipleIssuers(t *testing.T) {
},
}
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
newIssuers,
ctx.keyPolicy)
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to remake CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, _ := x509.ParseCertificateRequest(CNandSANCSR)
issuedCert, err := ca.IssueCertificate(*csr, 1001)
issuedCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to sign certificate")
cert, err := x509.ParseCertificate(issuedCert.DER)
@ -403,25 +405,25 @@ func TestIssueCertificateMultipleIssuers(t *testing.T) {
}
func TestOCSP(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, _ := x509.ParseCertificateRequest(CNandSANCSR)
cert, err := ca.IssueCertificate(*csr, 1001)
cert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to issue")
parsedCert, err := x509.ParseCertificate(cert.DER)
test.AssertNotError(t, err, "Failed to parse cert")
ocspResp, err := ca.GenerateOCSP(core.OCSPSigningRequest{
ocspResp, err := ca.GenerateOCSP(ctx, core.OCSPSigningRequest{
CertDER: cert.DER,
Status: string(core.OCSPStatusGood),
})
@ -433,7 +435,7 @@ func TestOCSP(t *testing.T) {
test.AssertEquals(t, parsed.SerialNumber.Cmp(parsedCert.SerialNumber), 0)
// Test that signatures are checked.
ocspResp, err = ca.GenerateOCSP(core.OCSPSigningRequest{
ocspResp, err = ca.GenerateOCSP(ctx, core.OCSPSigningRequest{
CertDER: append(cert.DER, byte(0)),
Status: string(core.OCSPStatusGood),
})
@ -454,18 +456,18 @@ func TestOCSP(t *testing.T) {
},
}
ca, err = NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
newIssuers,
ctx.keyPolicy)
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to remake CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// Now issue a new cert, signed by newIssuerCert
newCert, err := ca.IssueCertificate(*csr, 1001)
newCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to issue newCert")
parsedNewCert, err := x509.ParseCertificate(newCert.DER)
test.AssertNotError(t, err, "Failed to parse newCert")
@ -475,7 +477,7 @@ func TestOCSP(t *testing.T) {
// ocspResp2 is a second OCSP response for `cert` (issued by caCert), and
// should be signed by caCert.
ocspResp2, err := ca.GenerateOCSP(core.OCSPSigningRequest{
ocspResp2, err := ca.GenerateOCSP(ctx, core.OCSPSigningRequest{
CertDER: append(cert.DER),
Status: string(core.OCSPStatusGood),
})
@ -485,7 +487,7 @@ func TestOCSP(t *testing.T) {
// newCertOcspResp is an OCSP response for `newCert` (issued by newIssuer),
// and should be signed by newIssuer.
newCertOcspResp, err := ca.GenerateOCSP(core.OCSPSigningRequest{
newCertOcspResp, err := ca.GenerateOCSP(ctx, core.OCSPSigningRequest{
CertDER: newCert.DER,
Status: string(core.OCSPStatusGood),
})
@ -498,65 +500,65 @@ func TestOCSP(t *testing.T) {
}
func TestNoHostnames(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, _ := x509.ParseCertificateRequest(NoNamesCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
test.AssertError(t, err, "Issued certificate with no names")
_, ok := err.(core.MalformedRequestError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestRejectTooManyNames(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// Test that the CA rejects a CSR with too many names
csr, _ := x509.ParseCertificateRequest(TooManyNameCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
test.AssertError(t, err, "Issued certificate with too many names")
_, ok := err.(core.MalformedRequestError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestDeduplication(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// Test that the CA collapses duplicate names
csr, _ := x509.ParseCertificateRequest(DupeNameCSR)
cert, err := ca.IssueCertificate(*csr, 1001)
cert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to gracefully handle a CSR with duplicate names")
parsedCert, err := x509.ParseCertificate(cert.DER)
@ -569,70 +571,70 @@ func TestDeduplication(t *testing.T) {
}
func TestRejectValidityTooLong(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Failed to create CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// This time is a few minutes before the notAfter in testdata/ca_cert.pem
future, err := time.Parse(time.RFC3339, "2025-02-10T00:30:00Z")
test.AssertNotError(t, err, "Failed to parse time")
ctx.fc.Set(future)
testCtx.fc.Set(future)
// Test that the CA rejects CSRs that would expire after the intermediate cert
csr, _ := x509.ParseCertificateRequest(NoCNCSR)
_, err = ca.IssueCertificate(*csr, 1)
_, err = ca.IssueCertificate(ctx, *csr, 1)
test.AssertError(t, err, "Cannot issue a certificate that expires after the intermediate certificate")
_, ok := err.(core.InternalServerError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestShortKey(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// Test that the CA rejects CSRs that would expire after the intermediate cert
csr, _ := x509.ParseCertificateRequest(ShortKeyCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
test.AssertError(t, err, "Issued a certificate with too short a key.")
_, ok := err.(core.MalformedRequestError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestAllowNoCN(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
test.AssertNotError(t, err, "Couldn't create new CA")
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, err := x509.ParseCertificateRequest(NoCNCSR)
test.AssertNotError(t, err, "Couldn't parse CSR")
issuedCert, err := ca.IssueCertificate(*csr, 1001)
issuedCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to sign certificate")
cert, err := x509.ParseCertificate(issuedCert.DER)
test.AssertNotError(t, err, fmt.Sprintf("unable to parse no CN cert: %s", err))
@ -658,62 +660,62 @@ func TestAllowNoCN(t *testing.T) {
}
func TestLongCommonName(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, _ := x509.ParseCertificateRequest(LongCNCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
test.AssertError(t, err, "Issued a certificate with a CN over 64 bytes.")
_, ok := err.(core.MalformedRequestError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestRejectBadAlgorithm(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
testCtx := setup(t)
defer testCtx.cleanUp()
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// Test that the CA rejects CSRs that would expire after the intermediate cert
csr, _ := x509.ParseCertificateRequest(BadAlgorithmCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
test.AssertError(t, err, "Issued a certificate based on a CSR with a weak algorithm.")
_, ok := err.(core.MalformedRequestError)
test.Assert(t, ok, "Incorrect error type returned")
}
func TestCapitalizedLetters(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
ctx.caConfig.MaxNames = 3
testCtx := setup(t)
defer testCtx.cleanUp()
testCtx.caConfig.MaxNames = 3
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
csr, _ := x509.ParseCertificateRequest(CapitalizedCSR)
cert, err := ca.IssueCertificate(*csr, 1001)
cert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to gracefully handle a CSR with capitalized names")
parsedCert, err := x509.ParseCertificate(cert.DER)
@ -726,40 +728,40 @@ func TestCapitalizedLetters(t *testing.T) {
}
func TestWrongSignature(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
ctx.caConfig.MaxNames = 3
testCtx := setup(t)
defer testCtx.cleanUp()
testCtx.caConfig.MaxNames = 3
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
// x509.ParseCertificateRequest() does not check for invalid signatures...
csr, _ := x509.ParseCertificateRequest(WrongSignatureCSR)
_, err = ca.IssueCertificate(*csr, 1001)
_, err = ca.IssueCertificate(ctx, *csr, 1001)
if err == nil {
t.Fatalf("Issued a certificate based on a CSR with an invalid signature.")
}
}
func TestProfileSelection(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
ctx.caConfig.MaxNames = 3
testCtx := setup(t)
defer testCtx.cleanUp()
testCtx.caConfig.MaxNames = 3
ca, _ := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
testCases := []struct {
@ -775,7 +777,7 @@ func TestProfileSelection(t *testing.T) {
test.AssertNotError(t, err, "Cannot parse CSR")
// Sign CSR
issuedCert, err := ca.IssueCertificate(*csr, 1001)
issuedCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to sign certificate")
// Verify cert contents
@ -799,17 +801,17 @@ func countMustStaple(t *testing.T, cert *x509.Certificate) (count int) {
}
func TestExtensions(t *testing.T) {
ctx := setup(t)
defer ctx.cleanUp()
ctx.caConfig.MaxNames = 3
testCtx := setup(t)
defer testCtx.cleanUp()
testCtx.caConfig.MaxNames = 3
ca, err := NewCertificateAuthorityImpl(
ctx.caConfig,
ctx.fc,
ctx.stats,
ctx.issuers,
ctx.keyPolicy)
testCtx.caConfig,
testCtx.fc,
testCtx.stats,
testCtx.issuers,
testCtx.keyPolicy)
ca.Publisher = &mocks.Publisher{}
ca.PA = ctx.pa
ca.PA = testCtx.pa
ca.SA = &mockSA{}
mustStapleCSR, err := x509.ParseCertificateRequest(MustStapleCSR)
@ -825,7 +827,7 @@ func TestExtensions(t *testing.T) {
test.AssertNotError(t, err, "Error parsing UnsupportedExtensionCSR")
sign := func(csr *x509.CertificateRequest) *x509.Certificate {
coreCert, err := ca.IssueCertificate(*csr, 1001)
coreCert, err := ca.IssueCertificate(ctx, *csr, 1001)
test.AssertNotError(t, err, "Failed to issue")
cert, err := x509.ParseCertificate(coreCert.DER)
test.AssertNotError(t, err, "Error parsing certificate produced by CA")
@ -842,28 +844,28 @@ func TestExtensions(t *testing.T) {
ca.enableMustStaple = true
singleStapleCert := sign(mustStapleCSR)
test.AssertEquals(t, countMustStaple(t, singleStapleCert), 1)
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionTLSFeature], int64(2))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionTLSFeature], int64(2))
// Even if there are multiple TLS Feature extensions, only one extension should be included
duplicateMustStapleCert := sign(duplicateMustStapleCSR)
test.AssertEquals(t, countMustStaple(t, duplicateMustStapleCert), 1)
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionTLSFeature], int64(3))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionTLSFeature], int64(3))
// ... but if it doesn't ask for stapling, there should be an error
_, err = ca.IssueCertificate(*tlsFeatureUnknownCSR, 1001)
_, err = ca.IssueCertificate(ctx, *tlsFeatureUnknownCSR, 1001)
test.AssertError(t, err, "Allowed a CSR with an empty TLS feature extension")
if _, ok := err.(core.MalformedRequestError); !ok {
t.Errorf("Wrong error type when rejecting a CSR with empty TLS feature extension")
}
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionTLSFeature], int64(4))
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionTLSFeatureInvalid], int64(1))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionTLSFeature], int64(4))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionTLSFeatureInvalid], int64(1))
// Unsupported extensions should be silently ignored, having the same
// extensions as the TLS Feature cert above, minus the TLS Feature Extension
unsupportedExtensionCert := sign(unsupportedExtensionCSR)
test.AssertEquals(t, len(unsupportedExtensionCert.Extensions), len(singleStapleCert.Extensions)-1)
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionOther], int64(1))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionOther], int64(1))
// None of the above CSRs have basic extensions
test.AssertEquals(t, ctx.stats.Counters[metricCSRExtensionBasic], int64(0))
test.AssertEquals(t, testCtx.stats.Counters[metricCSRExtensionBasic], int64(0))
}

View File

@ -16,6 +16,8 @@ import (
"strconv"
"strings"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/codegangsta/cli"
gorp "gopkg.in/gorp.v1"
@ -69,7 +71,7 @@ func addDeniedNames(tx *gorp.Transaction, names []string) (err error) {
return
}
func revokeBySerial(serial string, reasonCode core.RevocationCode, deny bool, rac rpc.RegistrationAuthorityClient, logger blog.Logger, tx *gorp.Transaction) (err error) {
func revokeBySerial(ctx context.Context, serial string, reasonCode core.RevocationCode, deny bool, rac rpc.RegistrationAuthorityClient, logger blog.Logger, tx *gorp.Transaction) (err error) {
if reasonCode < 0 || reasonCode == 7 || reasonCode > 10 {
panic(fmt.Sprintf("Invalid reason code: %d", reasonCode))
}
@ -96,7 +98,7 @@ func revokeBySerial(serial string, reasonCode core.RevocationCode, deny bool, ra
}
u, err := user.Current()
err = rac.AdministrativelyRevokeCertificate(*cert, reasonCode, u.Username)
err = rac.AdministrativelyRevokeCertificate(ctx, *cert, reasonCode, u.Username)
if err != nil {
return
}
@ -105,7 +107,7 @@ func revokeBySerial(serial string, reasonCode core.RevocationCode, deny bool, ra
return
}
func revokeByReg(regID int64, reasonCode core.RevocationCode, deny bool, rac rpc.RegistrationAuthorityClient, logger blog.Logger, tx *gorp.Transaction) (err error) {
func revokeByReg(ctx context.Context, regID int64, reasonCode core.RevocationCode, deny bool, rac rpc.RegistrationAuthorityClient, logger blog.Logger, tx *gorp.Transaction) (err error) {
var certs []core.Certificate
_, err = tx.Select(&certs, "SELECT serial FROM certificates WHERE registrationID = :regID", map[string]interface{}{"regID": regID})
if err != nil {
@ -113,7 +115,7 @@ func revokeByReg(regID int64, reasonCode core.RevocationCode, deny bool, rac rpc
}
for _, cert := range certs {
err = revokeBySerial(cert.Serial, reasonCode, deny, rac, logger, tx)
err = revokeBySerial(ctx, cert.Serial, reasonCode, deny, rac, logger, tx)
if err != nil {
return
}
@ -130,6 +132,7 @@ func (rc revocationCodes) Less(i, j int) bool { return rc[i] < rc[j] }
func (rc revocationCodes) Swap(i, j int) { rc[i], rc[j] = rc[j], rc[i] }
func main() {
ctx := context.Background()
app := cli.NewApp()
app.Name = "admin-revoker"
app.Usage = "Revokes issued certificates"
@ -167,7 +170,7 @@ func main() {
cmd.FailOnError(sa.Rollback(tx, err), "Couldn't begin transaction")
}
err = revokeBySerial(serial, core.RevocationCode(reasonCode), deny, cac, logger, tx)
err = revokeBySerial(ctx, serial, core.RevocationCode(reasonCode), deny, cac, logger, tx)
if err != nil {
cmd.FailOnError(sa.Rollback(tx, err), "Couldn't revoke certificate")
}
@ -196,12 +199,12 @@ func main() {
cmd.FailOnError(sa.Rollback(tx, err), "Couldn't begin transaction")
}
_, err = sac.GetRegistration(regID)
_, err = sac.GetRegistration(ctx, regID)
if err != nil {
cmd.FailOnError(err, "Couldn't fetch registration")
}
err = revokeByReg(regID, core.RevocationCode(reasonCode), deny, cac, logger, tx)
err = revokeByReg(ctx, regID, core.RevocationCode(reasonCode), deny, cac, logger, tx)
if err != nil {
cmd.FailOnError(sa.Rollback(tx, err), "Couldn't revoke certificate")
}
@ -232,7 +235,7 @@ func main() {
domain := c.Args().First()
_, logger, _, sac, stats := setupContext(c)
ident := core.AcmeIdentifier{Value: domain, Type: core.IdentifierDNS}
authsRevoked, pendingAuthsRevoked, err := sac.RevokeAuthorizationsByDomain(ident)
authsRevoked, pendingAuthsRevoked, err := sac.RevokeAuthorizationsByDomain(ctx, ident)
cmd.FailOnError(err, fmt.Sprintf("Failed to revoke authorizations for %s", ident.Value))
logger.Info(fmt.Sprintf(
"Revoked %d pending authorizations and %d final authorizations\n",

View File

@ -18,6 +18,7 @@ import (
"time"
"github.com/jmhodges/clock"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/core"
blog "github.com/letsencrypt/boulder/log"
@ -205,7 +206,7 @@ func TestGetAndProcessCerts(t *testing.T) {
rawCert.SerialNumber = big.NewInt(mrand.Int63())
certDER, err := x509.CreateCertificate(rand.Reader, &rawCert, &rawCert, &testKey.PublicKey, testKey)
test.AssertNotError(t, err, "Couldn't create certificate")
_, err = sa.AddCertificate(certDER, reg.ID)
_, err = sa.AddCertificate(context.Background(), certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add certificate")
}

View File

@ -18,6 +18,8 @@ import (
"text/template"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/codegangsta/cli"
"github.com/jmhodges/clock"
@ -41,7 +43,7 @@ type emailContent struct {
}
type regStore interface {
GetRegistration(int64) (core.Registration, error)
GetRegistration(context.Context, int64) (core.Registration, error)
}
type mailer struct {
@ -162,6 +164,7 @@ func (m *mailer) certIsRenewed(serial string) (renewed bool, err error) {
}
func (m *mailer) processCerts(allCerts []core.Certificate) {
ctx := context.Background()
m.log.Info(fmt.Sprintf("expiration-mailer: Found %d certificates, starting sending messages", len(allCerts)))
regIDToCerts := make(map[int64][]core.Certificate)
@ -173,7 +176,7 @@ func (m *mailer) processCerts(allCerts []core.Certificate) {
}
for regID, certs := range regIDToCerts {
reg, err := m.rs.GetRegistration(regID)
reg, err := m.rs.GetRegistration(ctx, regID)
if err != nil {
m.log.Err(fmt.Sprintf("Error fetching registration %d: %s", regID, err))
m.stats.Inc("Mailer.Expiration.Errors.GetRegistration", 1, 1.0)

View File

@ -20,6 +20,8 @@ import (
"text/template"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"github.com/square/go-jose"
@ -49,7 +51,7 @@ type fakeRegStore struct {
RegByID map[int64]core.Registration
}
func (f fakeRegStore) GetRegistration(id int64) (core.Registration, error) {
func (f fakeRegStore) GetRegistration(ctx context.Context, id int64) (core.Registration, error) {
r, ok := f.RegByID[id]
if !ok {
msg := fmt.Sprintf("no such registration %d", id)
@ -93,6 +95,7 @@ var (
}`)
log = blog.UseMock()
tmpl = template.Must(template.New("expiry-email").Parse(testTmpl))
ctx = context.Background()
)
func TestSendNags(t *testing.T) {
@ -169,10 +172,10 @@ var testKey = rsa.PrivateKey{
}
func TestFindExpiringCertificates(t *testing.T) {
ctx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
testCtx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
log.Clear()
err := ctx.m.findExpiringCertificates()
err := testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "Failed on no certificates")
test.AssertEquals(t, len(log.GetAllMatching("Searching for certificates that expire between.*")), 3)
@ -199,11 +202,11 @@ func TestFindExpiringCertificates(t *testing.T) {
Key: keyB,
InitialIP: net.ParseIP("2.3.2.3"),
}
regA, err = ctx.ssa.NewRegistration(regA)
regA, err = testCtx.ssa.NewRegistration(ctx, regA)
if err != nil {
t.Fatalf("Couldn't store regA: %s", err)
}
regB, err = ctx.ssa.NewRegistration(regB)
regB, err = testCtx.ssa.NewRegistration(ctx, regB)
if err != nil {
t.Fatalf("Couldn't store regB: %s", err)
}
@ -213,7 +216,7 @@ func TestFindExpiringCertificates(t *testing.T) {
Subject: pkix.Name{
CommonName: "happy A",
},
NotAfter: ctx.fc.Now().Add(23 * time.Hour),
NotAfter: testCtx.fc.Now().Add(23 * time.Hour),
DNSNames: []string{"example-a.com"},
SerialNumber: big.NewInt(1337),
}
@ -226,7 +229,7 @@ func TestFindExpiringCertificates(t *testing.T) {
}
certStatusA := &core.CertificateStatus{
Serial: "001",
LastExpirationNagSent: ctx.fc.Now().AddDate(0, 0, -3),
LastExpirationNagSent: testCtx.fc.Now().AddDate(0, 0, -3),
Status: core.OCSPStatusGood,
}
@ -235,7 +238,7 @@ func TestFindExpiringCertificates(t *testing.T) {
Subject: pkix.Name{
CommonName: "happy B",
},
NotAfter: ctx.fc.Now().AddDate(0, 0, 3),
NotAfter: testCtx.fc.Now().AddDate(0, 0, 3),
DNSNames: []string{"example-b.com"},
SerialNumber: big.NewInt(1337),
}
@ -248,7 +251,7 @@ func TestFindExpiringCertificates(t *testing.T) {
}
certStatusB := &core.CertificateStatus{
Serial: "002",
LastExpirationNagSent: ctx.fc.Now().Add(-36 * time.Hour),
LastExpirationNagSent: testCtx.fc.Now().Add(-36 * time.Hour),
Status: core.OCSPStatusGood,
}
@ -257,7 +260,7 @@ func TestFindExpiringCertificates(t *testing.T) {
Subject: pkix.Name{
CommonName: "happy C",
},
NotAfter: ctx.fc.Now().Add((7*24 + 1) * time.Hour),
NotAfter: testCtx.fc.Now().Add((7*24 + 1) * time.Hour),
DNSNames: []string{"example-c.com"},
SerialNumber: big.NewInt(1337),
}
@ -288,34 +291,34 @@ func TestFindExpiringCertificates(t *testing.T) {
test.AssertNotError(t, err, "Couldn't add certStatusC")
log.Clear()
err = ctx.m.findExpiringCertificates()
err = testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "Failed to find expiring certs")
// Should get 001 and 003
test.AssertEquals(t, len(ctx.mc.Messages), 2)
test.AssertEquals(t, len(testCtx.mc.Messages), 2)
test.AssertEquals(t, mocks.MailerMessage{
To: emailARaw,
Subject: "",
Body: fmt.Sprintf(`hi, cert for DNS names example-a.com is going to expire in 0 days (%s)`, rawCertA.NotAfter.UTC().Format(time.RFC822Z)),
}, ctx.mc.Messages[0])
}, testCtx.mc.Messages[0])
test.AssertEquals(t, mocks.MailerMessage{
To: emailBRaw,
Subject: "",
Body: fmt.Sprintf(`hi, cert for DNS names example-c.com is going to expire in 7 days (%s)`, rawCertC.NotAfter.UTC().Format(time.RFC822Z)),
}, ctx.mc.Messages[1])
}, testCtx.mc.Messages[1])
// A consecutive run shouldn't find anything
ctx.mc.Clear()
testCtx.mc.Clear()
log.Clear()
err = ctx.m.findExpiringCertificates()
err = testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "Failed to find expiring certs")
test.AssertEquals(t, len(ctx.mc.Messages), 0)
test.AssertEquals(t, len(testCtx.mc.Messages), 0)
}
func TestCertIsRenewed(t *testing.T) {
ctx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
testCtx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
reg := satest.CreateWorkingRegistration(t, ctx.ssa)
reg := satest.CreateWorkingRegistration(t, testCtx.ssa)
testCerts := []*struct {
Serial int
@ -331,56 +334,56 @@ func TestCertIsRenewed(t *testing.T) {
Serial: 1001,
FQDNHash: []byte("hash of A"),
DNS: "a.example.com",
NotBefore: ctx.fc.Now().Add((-1 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((89 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((-1 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((89 * 24) * time.Hour),
IsRenewed: true,
},
{
Serial: 1002,
FQDNHash: []byte("hash of A"),
DNS: "a.example.com",
NotBefore: ctx.fc.Now().Add((0 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((90 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((0 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((90 * 24) * time.Hour),
IsRenewed: false,
},
{
Serial: 1003,
FQDNHash: []byte("hash of B"),
DNS: "b.example.net",
NotBefore: ctx.fc.Now().Add((0 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((90 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((0 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((90 * 24) * time.Hour),
IsRenewed: false,
},
{
Serial: 1004,
FQDNHash: []byte("hash of C"),
DNS: "c.example.org",
NotBefore: ctx.fc.Now().Add((-100 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((-10 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((-100 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((-10 * 24) * time.Hour),
IsRenewed: true,
},
{
Serial: 1005,
FQDNHash: []byte("hash of C"),
DNS: "c.example.org",
NotBefore: ctx.fc.Now().Add((-80 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((10 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((-80 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((10 * 24) * time.Hour),
IsRenewed: true,
},
{
Serial: 1006,
FQDNHash: []byte("hash of C"),
DNS: "c.example.org",
NotBefore: ctx.fc.Now().Add((-75 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((15 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((-75 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((15 * 24) * time.Hour),
IsRenewed: true,
},
{
Serial: 1007,
FQDNHash: []byte("hash of C"),
DNS: "c.example.org",
NotBefore: ctx.fc.Now().Add((-1 * 24) * time.Hour),
NotAfter: ctx.fc.Now().Add((89 * 24) * time.Hour),
NotBefore: testCtx.fc.Now().Add((-1 * 24) * time.Hour),
NotAfter: testCtx.fc.Now().Add((89 * 24) * time.Hour),
IsRenewed: false,
},
}
@ -433,7 +436,7 @@ func TestCertIsRenewed(t *testing.T) {
}
for _, testData := range testCerts {
renewed, err := ctx.m.certIsRenewed(testData.stringSerial)
renewed, err := testCtx.m.certIsRenewed(testData.stringSerial)
if err != nil {
t.Errorf("error checking renewal state for %s: %v", testData.stringSerial, err)
continue
@ -445,8 +448,8 @@ func TestCertIsRenewed(t *testing.T) {
}
func TestLifetimeOfACert(t *testing.T) {
ctx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
defer ctx.cleanUp()
testCtx := setup(t, []time.Duration{time.Hour * 24, time.Hour * 24 * 4, time.Hour * 24 * 7})
defer testCtx.cleanUp()
var keyA jose.JsonWebKey
err := json.Unmarshal(jsonKeyA, &keyA)
@ -460,7 +463,7 @@ func TestLifetimeOfACert(t *testing.T) {
Key: keyA,
InitialIP: net.ParseIP("1.2.2.1"),
}
regA, err = ctx.ssa.NewRegistration(regA)
regA, err = testCtx.ssa.NewRegistration(ctx, regA)
if err != nil {
t.Fatalf("Couldn't store regA: %s", err)
}
@ -469,7 +472,7 @@ func TestLifetimeOfACert(t *testing.T) {
CommonName: "happy A",
},
NotAfter: ctx.fc.Now(),
NotAfter: testCtx.fc.Now(),
DNSNames: []string{"example-a.com"},
SerialNumber: big.NewInt(1337),
}
@ -537,19 +540,19 @@ func TestLifetimeOfACert(t *testing.T) {
}
for _, tt := range tests {
ctx.fc.Add(-tt.timeLeft)
err = ctx.m.findExpiringCertificates()
testCtx.fc.Add(-tt.timeLeft)
err = testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "error calling findExpiringCertificates")
if len(ctx.mc.Messages) != tt.numMsgs {
t.Errorf(tt.context+" number of messages: expected %d, got %d", tt.numMsgs, len(ctx.mc.Messages))
if len(testCtx.mc.Messages) != tt.numMsgs {
t.Errorf(tt.context+" number of messages: expected %d, got %d", tt.numMsgs, len(testCtx.mc.Messages))
}
ctx.fc.Add(tt.timeLeft)
testCtx.fc.Add(tt.timeLeft)
}
}
func TestDontFindRevokedCert(t *testing.T) {
expiresIn := 24 * time.Hour
ctx := setup(t, []time.Duration{expiresIn})
testCtx := setup(t, []time.Duration{expiresIn})
var keyA jose.JsonWebKey
err := json.Unmarshal(jsonKeyA, &keyA)
@ -565,7 +568,7 @@ func TestDontFindRevokedCert(t *testing.T) {
Key: keyA,
InitialIP: net.ParseIP("6.5.5.6"),
}
regA, err = ctx.ssa.NewRegistration(regA)
regA, err = testCtx.ssa.NewRegistration(ctx, regA)
if err != nil {
t.Fatalf("Couldn't store regA: %s", err)
}
@ -574,7 +577,7 @@ func TestDontFindRevokedCert(t *testing.T) {
CommonName: "happy A",
},
NotAfter: ctx.fc.Now().Add(expiresIn),
NotAfter: testCtx.fc.Now().Add(expiresIn),
DNSNames: []string{"example-a.com"},
SerialNumber: big.NewInt(1337),
}
@ -597,17 +600,17 @@ func TestDontFindRevokedCert(t *testing.T) {
err = setupDBMap.Insert(certStatusA)
test.AssertNotError(t, err, "unable to insert CertificateStatus")
err = ctx.m.findExpiringCertificates()
err = testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "err from findExpiringCertificates")
if len(ctx.mc.Messages) != 0 {
t.Errorf("no emails should have been sent, but sent %d", len(ctx.mc.Messages))
if len(testCtx.mc.Messages) != 0 {
t.Errorf("no emails should have been sent, but sent %d", len(testCtx.mc.Messages))
}
}
func TestDedupOnRegistration(t *testing.T) {
expiresIn := 96 * time.Hour
ctx := setup(t, []time.Duration{expiresIn})
testCtx := setup(t, []time.Duration{expiresIn})
var keyA jose.JsonWebKey
err := json.Unmarshal(jsonKeyA, &keyA)
@ -621,12 +624,12 @@ func TestDedupOnRegistration(t *testing.T) {
Key: keyA,
InitialIP: net.ParseIP("6.5.5.6"),
}
regA, err = ctx.ssa.NewRegistration(regA)
regA, err = testCtx.ssa.NewRegistration(ctx, regA)
if err != nil {
t.Fatalf("Couldn't store regA: %s", err)
}
rawCertA := newX509Cert("happy A",
ctx.fc.Now().Add(72*time.Hour),
testCtx.fc.Now().Add(72*time.Hour),
[]string{"example-a.com", "shared-example.com"},
1338,
)
@ -645,7 +648,7 @@ func TestDedupOnRegistration(t *testing.T) {
}
rawCertB := newX509Cert("happy B",
ctx.fc.Now().Add(48*time.Hour),
testCtx.fc.Now().Add(48*time.Hour),
[]string{"example-b.com", "shared-example.com"},
1337,
)
@ -672,12 +675,12 @@ func TestDedupOnRegistration(t *testing.T) {
err = setupDBMap.Insert(certStatusB)
test.AssertNotError(t, err, "Couldn't add certStatusB")
err = ctx.m.findExpiringCertificates()
err = testCtx.m.findExpiringCertificates()
test.AssertNotError(t, err, "error calling findExpiringCertificates")
if len(ctx.mc.Messages) > 1 {
t.Errorf("num of messages, want %d, got %d", 1, len(ctx.mc.Messages))
if len(testCtx.mc.Messages) > 1 {
t.Errorf("num of messages, want %d, got %d", 1, len(testCtx.mc.Messages))
}
if len(ctx.mc.Messages) == 0 {
if len(testCtx.mc.Messages) == 0 {
t.Fatalf("no messages sent")
}
domains := "example-a.com\nexample-b.com\nshared-example.com"
@ -688,7 +691,7 @@ func TestDedupOnRegistration(t *testing.T) {
domains,
rawCertB.NotAfter.Format(time.RFC822Z)),
}
test.AssertEquals(t, expected, ctx.mc.Messages[0])
test.AssertEquals(t, expected, testCtx.mc.Messages[0])
}
type testCtx struct {

View File

@ -17,6 +17,7 @@ import (
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"golang.org/x/crypto/ocsp"
"golang.org/x/net/context"
gorp "gopkg.in/gorp.v1"
"github.com/letsencrypt/boulder/akamai"
@ -239,7 +240,7 @@ type responseMeta struct {
*core.CertificateStatus
}
func (updater *OCSPUpdater) generateResponse(status core.CertificateStatus) (*core.CertificateStatus, error) {
func (updater *OCSPUpdater) generateResponse(ctx context.Context, status core.CertificateStatus) (*core.CertificateStatus, error) {
var cert core.Certificate
err := updater.dbMap.SelectOne(
&cert,
@ -262,7 +263,7 @@ func (updater *OCSPUpdater) generateResponse(status core.CertificateStatus) (*co
RevokedAt: status.RevokedDate,
}
ocspResponse, err := updater.cac.GenerateOCSP(signRequest)
ocspResponse, err := updater.cac.GenerateOCSP(ctx, signRequest)
if err != nil {
return nil, err
}
@ -278,8 +279,8 @@ func (updater *OCSPUpdater) generateResponse(status core.CertificateStatus) (*co
return &status, nil
}
func (updater *OCSPUpdater) generateRevokedResponse(status core.CertificateStatus) (*core.CertificateStatus, error) {
cert, err := updater.sac.GetCertificate(status.Serial)
func (updater *OCSPUpdater) generateRevokedResponse(ctx context.Context, status core.CertificateStatus) (*core.CertificateStatus, error) {
cert, err := updater.sac.GetCertificate(ctx, status.Serial)
if err != nil {
return nil, err
}
@ -291,7 +292,7 @@ func (updater *OCSPUpdater) generateRevokedResponse(status core.CertificateStatu
RevokedAt: status.RevokedDate,
}
ocspResponse, err := updater.cac.GenerateOCSP(signRequest)
ocspResponse, err := updater.cac.GenerateOCSP(ctx, signRequest)
if err != nil {
return nil, err
}
@ -328,7 +329,7 @@ func (updater *OCSPUpdater) storeResponse(status *core.CertificateStatus) error
// newCertificateTick checks for certificates issued since the last tick and
// generates and stores OCSP responses for these certs
func (updater *OCSPUpdater) newCertificateTick(batchSize int) error {
func (updater *OCSPUpdater) newCertificateTick(ctx context.Context, batchSize int) error {
// Check for anything issued between now and previous tick and generate first
// OCSP responses
statuses, err := updater.getCertificatesWithMissingResponses(batchSize)
@ -338,7 +339,7 @@ func (updater *OCSPUpdater) newCertificateTick(batchSize int) error {
return err
}
return updater.generateOCSPResponses(statuses)
return updater.generateOCSPResponses(ctx, statuses)
}
func (updater *OCSPUpdater) findRevokedCertificatesToUpdate(batchSize int) ([]core.CertificateStatus, error) {
@ -357,7 +358,7 @@ func (updater *OCSPUpdater) findRevokedCertificatesToUpdate(batchSize int) ([]co
return statuses, err
}
func (updater *OCSPUpdater) revokedCertificatesTick(batchSize int) error {
func (updater *OCSPUpdater) revokedCertificatesTick(ctx context.Context, batchSize int) error {
statuses, err := updater.findRevokedCertificatesToUpdate(batchSize)
if err != nil {
updater.stats.Inc("OCSP.Errors.FindRevokedCertificates", 1, 1.0)
@ -366,7 +367,7 @@ func (updater *OCSPUpdater) revokedCertificatesTick(batchSize int) error {
}
for _, status := range statuses {
meta, err := updater.generateRevokedResponse(status)
meta, err := updater.generateRevokedResponse(ctx, status)
if err != nil {
updater.log.AuditErr(fmt.Errorf("Failed to generate revoked OCSP response: %s", err))
updater.stats.Inc("OCSP.Errors.RevokedResponseGeneration", 1, 1.0)
@ -382,9 +383,9 @@ func (updater *OCSPUpdater) revokedCertificatesTick(batchSize int) error {
return nil
}
func (updater *OCSPUpdater) generateOCSPResponses(statuses []core.CertificateStatus) error {
func (updater *OCSPUpdater) generateOCSPResponses(ctx context.Context, statuses []core.CertificateStatus) error {
for _, status := range statuses {
meta, err := updater.generateResponse(status)
meta, err := updater.generateResponse(ctx, status)
if err != nil {
updater.log.AuditErr(fmt.Errorf("Failed to generate OCSP response: %s", err))
updater.stats.Inc("OCSP.Errors.ResponseGeneration", 1, 1.0)
@ -404,7 +405,7 @@ func (updater *OCSPUpdater) generateOCSPResponses(statuses []core.CertificateSta
// oldOCSPResponsesTick looks for certificates with stale OCSP responses and
// generates/stores new ones
func (updater *OCSPUpdater) oldOCSPResponsesTick(batchSize int) error {
func (updater *OCSPUpdater) oldOCSPResponsesTick(ctx context.Context, batchSize int) error {
now := time.Now()
statuses, err := updater.findStaleOCSPResponses(now.Add(-updater.ocspMinTimeToExpiry), batchSize)
if err != nil {
@ -413,7 +414,7 @@ func (updater *OCSPUpdater) oldOCSPResponsesTick(batchSize int) error {
return err
}
return updater.generateOCSPResponses(statuses)
return updater.generateOCSPResponses(ctx, statuses)
}
func (updater *OCSPUpdater) getSerialsIssuedSince(since time.Time, batchSize int) ([]string, error) {
@ -455,7 +456,7 @@ func (updater *OCSPUpdater) getNumberOfReceipts(serial string) (int, error) {
// missingReceiptsTick looks for certificates without the correct number of SCT
// receipts and retrieves them
func (updater *OCSPUpdater) missingReceiptsTick(batchSize int) error {
func (updater *OCSPUpdater) missingReceiptsTick(ctx context.Context, batchSize int) error {
now := updater.clk.Now()
since := now.Add(-updater.oldestIssuedSCT)
serials, err := updater.getSerialsIssuedSince(since, batchSize)
@ -473,12 +474,13 @@ func (updater *OCSPUpdater) missingReceiptsTick(batchSize int) error {
if count >= updater.numLogs {
continue
}
cert, err := updater.sac.GetCertificate(serial)
cert, err := updater.sac.GetCertificate(ctx, serial)
if err != nil {
updater.log.AuditErr(fmt.Errorf("Failed to get certificate: %s", err))
continue
}
err = updater.pubc.SubmitToCT(cert.DER)
// TODO(#1679) only submit to the logs we don't have a SCT for
err = updater.pubc.SubmitToCT(ctx, cert.DER)
if err != nil {
updater.log.AuditErr(fmt.Errorf("Failed to submit certificate to CT log: %s", err))
continue
@ -492,7 +494,7 @@ type looper struct {
stats statsd.Statter
batchSize int
tickDur time.Duration
tickFunc func(int) error
tickFunc func(context.Context, int) error
name string
failureBackoffFactor float64
failureBackoffMax time.Duration
@ -501,7 +503,8 @@ type looper struct {
func (l *looper) tick() {
tickStart := l.clk.Now()
err := l.tickFunc(l.batchSize)
ctx := context.TODO()
err := l.tickFunc(ctx, l.batchSize)
l.stats.TimingDuration(fmt.Sprintf("OCSP.%s.TickDuration", l.name), time.Since(tickStart), 1.0)
l.stats.Inc(fmt.Sprintf("OCSP.%s.Ticks", l.name), 1, 1.0)
tickEnd := tickStart.Add(time.Since(tickStart))

View File

@ -6,6 +6,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"gopkg.in/gorp.v1"
@ -19,13 +21,15 @@ import (
"github.com/letsencrypt/boulder/test/vars"
)
var ctx = context.Background()
type mockCA struct{}
func (ca *mockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
func (ca *mockCA) IssueCertificate(_ context.Context, csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
return core.Certificate{}, nil
}
func (ca *mockCA) GenerateOCSP(xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {
func (ca *mockCA) GenerateOCSP(_ context.Context, xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {
ocsp = []byte{1, 2, 3}
return
}
@ -34,7 +38,7 @@ type mockPub struct {
sa core.StorageAuthority
}
func (p *mockPub) SubmitToCT(_ []byte) error {
func (p *mockPub) SubmitToCT(_ context.Context, _ []byte) error {
sct := core.SignedCertificateTimestamp{
SCTVersion: 0,
LogID: "id",
@ -43,12 +47,12 @@ func (p *mockPub) SubmitToCT(_ []byte) error {
Signature: []byte{0},
CertificateSerial: "00",
}
err := p.sa.AddSCTReceipt(sct)
err := p.sa.AddSCTReceipt(ctx, sct)
if err != nil {
return err
}
sct.LogID = "another-id"
return p.sa.AddSCTReceipt(sct)
return p.sa.AddSCTReceipt(ctx, sct)
}
var log = blog.UseMock()
@ -97,23 +101,23 @@ func TestGenerateAndStoreOCSPResponse(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
status, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Couldn't get the core.CertificateStatus from the database")
meta, err := updater.generateResponse(status)
meta, err := updater.generateResponse(ctx, status)
test.AssertNotError(t, err, "Couldn't generate OCSP response")
err = updater.storeResponse(meta)
test.AssertNotError(t, err, "Couldn't store certificate status")
secondMeta, err := updater.generateRevokedResponse(status)
secondMeta, err := updater.generateRevokedResponse(ctx, status)
test.AssertNotError(t, err, "Couldn't generate revoked OCSP response")
err = updater.storeResponse(secondMeta)
test.AssertNotError(t, err, "Couldn't store certificate status")
newStatus, err := sa.GetCertificateStatus(status.Serial)
newStatus, err := sa.GetCertificateStatus(ctx, status.Serial)
test.AssertNotError(t, err, "Couldn't retrieve certificate status")
test.AssertByteEquals(t, meta.OCSPResponse, newStatus.OCSPResponse)
}
@ -125,11 +129,11 @@ func TestGenerateOCSPResponses(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add test-cert.pem")
parsedCert, err = core.LoadCert("test-cert-b.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add test-cert-b.pem")
earliest := fc.Now().Add(-time.Hour)
@ -137,7 +141,7 @@ func TestGenerateOCSPResponses(t *testing.T) {
test.AssertNotError(t, err, "Couldn't find stale responses")
test.AssertEquals(t, len(certs), 2)
err = updater.generateOCSPResponses(certs)
err = updater.generateOCSPResponses(ctx, certs)
test.AssertNotError(t, err, "Couldn't generate OCSP responses")
certs, err = updater.findStaleOCSPResponses(earliest, 10)
@ -152,7 +156,7 @@ func TestFindStaleOCSPResponses(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
earliest := fc.Now().Add(-time.Hour)
@ -160,10 +164,10 @@ func TestFindStaleOCSPResponses(t *testing.T) {
test.AssertNotError(t, err, "Couldn't find certificate")
test.AssertEquals(t, len(certs), 1)
status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
status, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Couldn't get the core.Certificate from the database")
meta, err := updater.generateResponse(status)
meta, err := updater.generateResponse(ctx, status)
test.AssertNotError(t, err, "Couldn't generate OCSP response")
err = updater.storeResponse(meta)
test.AssertNotError(t, err, "Couldn't store OCSP response")
@ -180,7 +184,7 @@ func TestGetCertificatesWithMissingResponses(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
cert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(cert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, cert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
statuses, err := updater.getCertificatesWithMissingResponses(10)
@ -195,14 +199,14 @@ func TestFindRevokedCertificatesToUpdate(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
cert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(cert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, cert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
statuses, err := updater.findRevokedCertificatesToUpdate(10)
test.AssertNotError(t, err, "Failed to find revoked certificates")
test.AssertEquals(t, len(statuses), 0)
err = sa.MarkCertificateRevoked(core.SerialToString(cert.SerialNumber), core.RevocationCode(1))
err = sa.MarkCertificateRevoked(ctx, core.SerialToString(cert.SerialNumber), core.RevocationCode(1))
test.AssertNotError(t, err, "Failed to revoke certificate")
statuses, err = updater.findRevokedCertificatesToUpdate(10)
@ -217,11 +221,11 @@ func TestNewCertificateTick(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
prev := fc.Now().Add(-time.Hour)
err = updater.newCertificateTick(10)
err = updater.newCertificateTick(ctx, 10)
test.AssertNotError(t, err, "Couldn't run newCertificateTick")
certs, err := updater.findStaleOCSPResponses(prev, 10)
@ -236,11 +240,11 @@ func TestOldOCSPResponsesTick(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
updater.ocspMinTimeToExpiry = 1 * time.Hour
err = updater.oldOCSPResponsesTick(10)
err = updater.oldOCSPResponsesTick(ctx, 10)
test.AssertNotError(t, err, "Couldn't run oldOCSPResponsesTick")
certs, err := updater.findStaleOCSPResponses(fc.Now().Add(-updater.ocspMinTimeToExpiry), 10)
@ -256,7 +260,7 @@ func TestMissingReceiptsTick(t *testing.T) {
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
fc.Set(parsedCert.NotBefore.Add(time.Minute))
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
updater.numLogs = 1
@ -266,7 +270,7 @@ func TestMissingReceiptsTick(t *testing.T) {
test.AssertNotError(t, err, "Failed to retrieve serials")
test.AssertEquals(t, len(serials), 1)
err = updater.missingReceiptsTick(5)
err = updater.missingReceiptsTick(ctx, 5)
test.AssertNotError(t, err, "Failed to run missingReceiptsTick")
count, err := updater.getNumberOfReceipts("00")
@ -276,7 +280,7 @@ func TestMissingReceiptsTick(t *testing.T) {
// make sure we don't spin forever after reducing the
// number of logs we submit to
updater.numLogs = 1
err = updater.missingReceiptsTick(10)
err = updater.missingReceiptsTick(ctx, 10)
test.AssertNotError(t, err, "Failed to run missingReceiptsTick")
}
@ -287,20 +291,20 @@ func TestRevokedCertificatesTick(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
err = sa.MarkCertificateRevoked(core.SerialToString(parsedCert.SerialNumber), core.RevocationCode(1))
err = sa.MarkCertificateRevoked(ctx, core.SerialToString(parsedCert.SerialNumber), core.RevocationCode(1))
test.AssertNotError(t, err, "Failed to revoke certificate")
statuses, err := updater.findRevokedCertificatesToUpdate(10)
test.AssertNotError(t, err, "Failed to find revoked certificates")
test.AssertEquals(t, len(statuses), 1)
err = updater.revokedCertificatesTick(10)
err = updater.revokedCertificatesTick(ctx, 10)
test.AssertNotError(t, err, "Failed to run revokedCertificatesTick")
status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
status, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Failed to get certificate status")
test.AssertEquals(t, status.Status, core.OCSPStatusRevoked)
test.Assert(t, len(status.OCSPResponse) != 0, "Certificate status doesn't contain OCSP response")
@ -313,13 +317,13 @@ func TestStoreResponseGuard(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
parsedCert, err := core.LoadCert("test-cert.pem")
test.AssertNotError(t, err, "Couldn't read test certificate")
_, err = sa.AddCertificate(parsedCert.Raw, reg.ID)
_, err = sa.AddCertificate(ctx, parsedCert.Raw, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
status, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Failed to get certificate status")
err = sa.MarkCertificateRevoked(core.SerialToString(parsedCert.SerialNumber), 0)
err = sa.MarkCertificateRevoked(ctx, core.SerialToString(parsedCert.SerialNumber), 0)
test.AssertNotError(t, err, "Failed to revoked certificate")
// Attempt to update OCSP response where status.Status is good but stored status
@ -329,7 +333,7 @@ func TestStoreResponseGuard(t *testing.T) {
test.AssertNotError(t, err, "Failed to update certificate status")
// Make sure the OCSP response hasn't actually changed
unchangedStatus, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
unchangedStatus, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Failed to get certificate status")
test.AssertEquals(t, len(unchangedStatus.OCSPResponse), 0)
@ -339,7 +343,7 @@ func TestStoreResponseGuard(t *testing.T) {
test.AssertNotError(t, err, "Failed to updated certificate status")
// Make sure the OCSP response has been updated
changedStatus, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
changedStatus, err := sa.GetCertificateStatus(ctx, core.SerialToString(parsedCert.SerialNumber))
test.AssertNotError(t, err, "Failed to get certificate status")
test.AssertEquals(t, len(changedStatus.OCSPResponse), 3)
}
@ -353,7 +357,7 @@ func TestLoopTickBackoff(t *testing.T) {
failureBackoffFactor: 1.5,
failureBackoffMax: 10 * time.Minute,
tickDur: time.Minute,
tickFunc: func(_ int) error { return errors.New("baddie") },
tickFunc: func(context.Context, int) error { return errors.New("baddie") },
}
start := l.clk.Now()
@ -378,7 +382,7 @@ func TestLoopTickBackoff(t *testing.T) {
maxJittered = backoff * 1.2
test.AssertBetween(t, l.clk.Now().Sub(start).Nanoseconds(), int64(backoff), int64(maxJittered))
l.tickFunc = func(_ int) error { return nil }
l.tickFunc = func(context.Context, int) error { return nil }
start = l.clk.Now()
l.tick()
test.AssertEquals(t, l.failures, 0)

View File

@ -11,6 +11,8 @@ import (
"strconv"
"strings"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/codegangsta/cli"
@ -27,8 +29,8 @@ type config struct {
}
type certificateStorage interface {
AddCertificate([]byte, int64) (string, error)
GetCertificate(string) (core.Certificate, error)
AddCertificate(context.Context, []byte, int64) (string, error)
GetCertificate(ctx context.Context, serial string) (core.Certificate, error)
}
var (
@ -38,11 +40,12 @@ var (
)
func checkDER(sai certificateStorage, der []byte) error {
ctx := context.Background()
cert, err := x509.ParseCertificate(der)
if err != nil {
return fmt.Errorf("Failed to parse DER: %s", err)
}
_, err = sai.GetCertificate(core.SerialToString(cert.SerialNumber))
_, err = sai.GetCertificate(ctx, core.SerialToString(cert.SerialNumber))
if err == nil {
return errAlreadyExists
}
@ -53,6 +56,7 @@ func checkDER(sai certificateStorage, der []byte) error {
}
func parseLogLine(sa certificateStorage, logger blog.Logger, line string) (found bool, added bool) {
ctx := context.Background()
if !strings.Contains(line, "b64der=") || !strings.Contains(line, "orphaning certificate") {
return false, false
}
@ -86,7 +90,7 @@ func parseLogLine(sa certificateStorage, logger blog.Logger, line string) (found
logger.Err(fmt.Sprintf("Couldn't parse regID: %s, [%s]", err, line))
return true, false
}
_, err = sa.AddCertificate(der, int64(regID))
_, err = sa.AddCertificate(ctx, der, int64(regID))
if err != nil {
logger.Err(fmt.Sprintf("Failed to store certificate: %s, [%s]", err, line))
return true, false
@ -175,6 +179,7 @@ func main() {
},
},
Action: func(c *cli.Context) {
ctx := context.Background()
_, _, sa := setup(c)
derPath := c.String("der-file")
if derPath == "" {
@ -190,7 +195,7 @@ func main() {
cmd.FailOnError(err, "Failed to read DER file")
err = checkDER(sa, der)
cmd.FailOnError(err, "Pre-AddCertificate checks failed")
_, err = sa.AddCertificate(der, int64(regID))
_, err = sa.AddCertificate(ctx, der, int64(regID))
cmd.FailOnError(err, "Failed to add certificate to database")
},
},

View File

@ -4,6 +4,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
@ -17,12 +19,12 @@ type mockSA struct {
certificate core.Certificate
}
func (m *mockSA) AddCertificate(der []byte, _ int64) (string, error) {
func (m *mockSA) AddCertificate(ctx context.Context, der []byte, _ int64) (string, error) {
m.certificate.DER = der
return "", nil
}
func (m *mockSA) GetCertificate(string) (core.Certificate, error) {
func (m *mockSA) GetCertificate(ctx context.Context, s string) (core.Certificate, error) {
if m.certificate.DER != nil {
return m.certificate, nil
}

View File

@ -1,9 +1,10 @@
package cmd
import (
"gopkg.in/yaml.v2"
"io/ioutil"
"time"
"gopkg.in/yaml.v2"
)
// RateLimitConfig contains all application layer rate limiting policies

View File

@ -11,6 +11,8 @@ import (
"net/http"
"time"
"golang.org/x/net/context"
jose "github.com/square/go-jose"
)
@ -27,101 +29,101 @@ import (
// * One path for certificates -> Cert
type WebFrontEnd interface {
// Set the base URL for authorizations
SetAuthzBase(path string)
SetAuthzBase(ctx context.Context, path string)
// Set the base URL for certificates
SetCertBase(path string)
SetCertBase(ctx context.Context, path string)
// This method represents the ACME new-registration resource
NewRegistration(response http.ResponseWriter, request *http.Request)
NewRegistration(ctx context.Context, response http.ResponseWriter, request *http.Request)
// This method represents the ACME new-authorization resource
NewAuthz(response http.ResponseWriter, request *http.Request)
NewAuthz(ctx context.Context, response http.ResponseWriter, request *http.Request)
// This method represents the ACME new-certificate resource
NewCert(response http.ResponseWriter, request *http.Request)
NewCert(ctx context.Context, response http.ResponseWriter, request *http.Request)
// Provide access to requests for registration resources
Registration(response http.ResponseWriter, request *http.Request)
Registration(ctx context.Context, response http.ResponseWriter, request *http.Request)
// Provide access to requests for authorization resources
Authz(response http.ResponseWriter, request *http.Request)
Authz(ctx context.Context, response http.ResponseWriter, request *http.Request)
// Provide access to requests for authorization resources
Cert(response http.ResponseWriter, request *http.Request)
Cert(ctx context.Context, response http.ResponseWriter, request *http.Request)
}
// RegistrationAuthority defines the public interface for the Boulder RA
type RegistrationAuthority interface {
// [WebFrontEnd]
NewRegistration(Registration) (Registration, error)
NewRegistration(ctx context.Context, reg Registration) (Registration, error)
// [WebFrontEnd]
NewAuthorization(Authorization, int64) (Authorization, error)
NewAuthorization(ctx context.Context, authz Authorization, regID int64) (Authorization, error)
// [WebFrontEnd]
NewCertificate(CertificateRequest, int64) (Certificate, error)
NewCertificate(ctx context.Context, csr CertificateRequest, regID int64) (Certificate, error)
// [WebFrontEnd]
UpdateRegistration(Registration, Registration) (Registration, error)
UpdateRegistration(ctx context.Context, base, updates Registration) (Registration, error)
// [WebFrontEnd]
UpdateAuthorization(Authorization, int, Challenge) (Authorization, error)
UpdateAuthorization(ctx context.Context, authz Authorization, challengeIndex int, response Challenge) (Authorization, error)
// [WebFrontEnd]
RevokeCertificateWithReg(x509.Certificate, RevocationCode, int64) error
RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, code RevocationCode, regID int64) error
// [AdminRevoker]
AdministrativelyRevokeCertificate(x509.Certificate, RevocationCode, string) error
AdministrativelyRevokeCertificate(ctx context.Context, cert x509.Certificate, code RevocationCode, adminName string) error
// [ValidationAuthority]
OnValidationUpdate(Authorization) error
OnValidationUpdate(ctx context.Context, authz Authorization) error
}
// CertificateAuthority defines the public interface for the Boulder CA
type CertificateAuthority interface {
// [RegistrationAuthority]
IssueCertificate(x509.CertificateRequest, int64) (Certificate, error)
GenerateOCSP(OCSPSigningRequest) ([]byte, error)
IssueCertificate(ctx context.Context, csr x509.CertificateRequest, regID int64) (Certificate, error)
GenerateOCSP(ctx context.Context, ocspReq OCSPSigningRequest) ([]byte, error)
}
// PolicyAuthority defines the public interface for the Boulder PA
type PolicyAuthority interface {
WillingToIssue(id AcmeIdentifier, regID int64) error
ChallengesFor(AcmeIdentifier, *jose.JsonWebKey) ([]Challenge, [][]int)
WillingToIssue(domain AcmeIdentifier, regID int64) error
ChallengesFor(domain AcmeIdentifier, jwk *jose.JsonWebKey) (challenges []Challenge, validCombinations [][]int)
}
// StorageGetter are the Boulder SA's read-only methods
type StorageGetter interface {
GetRegistration(int64) (Registration, error)
GetRegistrationByKey(jose.JsonWebKey) (Registration, error)
GetAuthorization(string) (Authorization, error)
GetLatestValidAuthorization(int64, AcmeIdentifier) (Authorization, error)
GetValidAuthorizations(int64, []string, time.Time) (map[string]*Authorization, error)
GetCertificate(string) (Certificate, error)
GetCertificateStatus(string) (CertificateStatus, error)
AlreadyDeniedCSR([]string) (bool, error)
CountCertificatesRange(time.Time, time.Time) (int64, error)
CountCertificatesByNames([]string, time.Time, time.Time) (map[string]int, error)
CountRegistrationsByIP(net.IP, time.Time, time.Time) (int, error)
CountPendingAuthorizations(regID int64) (int, error)
GetSCTReceipt(string, string) (SignedCertificateTimestamp, error)
CountFQDNSets(time.Duration, []string) (int64, error)
FQDNSetExists([]string) (bool, error)
GetRegistration(ctx context.Context, regID int64) (Registration, error)
GetRegistrationByKey(ctx context.Context, jwk jose.JsonWebKey) (Registration, error)
GetAuthorization(ctx context.Context, authzID string) (Authorization, error)
GetLatestValidAuthorization(ctx context.Context, regID int64, domain AcmeIdentifier) (Authorization, error)
GetValidAuthorizations(ctx context.Context, regID int64, domains []string, now time.Time) (map[string]*Authorization, error)
GetCertificate(ctx context.Context, serial string) (Certificate, error)
GetCertificateStatus(ctx context.Context, serial string) (CertificateStatus, error)
AlreadyDeniedCSR(ctx context.Context, names []string) (wasDenied bool, err error)
CountCertificatesRange(ctx context.Context, earliest, latest time.Time) (int64, error)
CountCertificatesByNames(ctx context.Context, domains []string, earliest, latest time.Time) (countByDomain map[string]int, err error)
CountRegistrationsByIP(ctx context.Context, ip net.IP, earliest, latest time.Time) (int, error)
CountPendingAuthorizations(ctx context.Context, regID int64) (int, error)
GetSCTReceipt(ctx context.Context, serial, logID string) (SignedCertificateTimestamp, error)
CountFQDNSets(ctx context.Context, window time.Duration, domains []string) (count int64, err error)
FQDNSetExists(ctx context.Context, domains []string) (exists bool, err error)
}
// StorageAdder are the Boulder SA's write/update methods
type StorageAdder interface {
NewRegistration(Registration) (Registration, error)
UpdateRegistration(Registration) error
NewPendingAuthorization(Authorization) (Authorization, error)
UpdatePendingAuthorization(Authorization) error
FinalizeAuthorization(Authorization) error
MarkCertificateRevoked(serial string, reasonCode RevocationCode) error
UpdateOCSP(serial string, ocspResponse []byte) error
AddCertificate([]byte, int64) (string, error)
AddSCTReceipt(SignedCertificateTimestamp) error
RevokeAuthorizationsByDomain(AcmeIdentifier) (int64, int64, error)
NewRegistration(ctx context.Context, reg Registration) (created Registration, err error)
UpdateRegistration(ctx context.Context, reg Registration) error
NewPendingAuthorization(ctx context.Context, authz Authorization) (Authorization, error)
UpdatePendingAuthorization(ctx context.Context, authz Authorization) error
FinalizeAuthorization(ctx context.Context, authz Authorization) error
MarkCertificateRevoked(ctx context.Context, serial string, reasonCode RevocationCode) error
UpdateOCSP(ctx context.Context, serial string, ocspResponse []byte) error
AddCertificate(ctx context.Context, der []byte, regID int64) (digest string, err error)
AddSCTReceipt(ctx context.Context, sct SignedCertificateTimestamp) error
RevokeAuthorizationsByDomain(ctx context.Context, domain AcmeIdentifier) (finalized, pending int64, err error)
}
// StorageAuthority interface represents a simple key/value
@ -134,5 +136,5 @@ type StorageAuthority interface {
// Publisher defines the public interface for the Boulder Publisher
type Publisher interface {
SubmitToCT([]byte) error
SubmitToCT(ctx context.Context, der []byte) error
}

View File

@ -7,8 +7,9 @@ package core
import (
"fmt"
"github.com/letsencrypt/boulder/test"
"testing"
"github.com/letsencrypt/boulder/test"
)
func TestValidNonce(t *testing.T) {

View File

@ -5,11 +5,13 @@
package core
import "golang.org/x/net/context"
// ValidationAuthority defines the public interface for the Boulder VA
type ValidationAuthority interface {
// [RegistrationAuthority]
// TODO(#1167): remove
UpdateValidations(Authorization, int) error
UpdateValidations(context.Context, Authorization, int) error
// PerformValidation checks the challenge with the given index in the
// given Authorization and returns the updated ValidationRecords.
//
@ -17,8 +19,8 @@ type ValidationAuthority interface {
// *probs.ProblemDetails.
//
// TODO(#1626): remove authz parameter
PerformValidation(string, Challenge, Authorization) ([]ValidationRecord, error)
IsSafeDomain(*IsSafeDomainRequest) (*IsSafeDomainResponse, error)
PerformValidation(context.Context, string, Challenge, Authorization) ([]ValidationRecord, error)
IsSafeDomain(context.Context, *IsSafeDomainRequest) (*IsSafeDomainResponse, error)
}
// IsSafeDomainRequest is the request struct for the IsSafeDomain call. The Domain field

View File

@ -4,8 +4,9 @@
package metrics
import (
gomock "github.com/golang/mock/gomock"
time "time"
gomock "github.com/golang/mock/gomock"
)
// Mock of Statter interface

View File

@ -5,6 +5,8 @@ import (
"encoding/pem"
"fmt"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/core"
)
@ -15,7 +17,7 @@ type MockCA struct {
}
// IssueCertificate is a mock
func (ca *MockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
func (ca *MockCA) IssueCertificate(ctx context.Context, csr x509.CertificateRequest, regID int64) (core.Certificate, error) {
if ca.PEM == nil {
return core.Certificate{}, fmt.Errorf("MockCA's PEM field must be set before calling IssueCertificate")
}
@ -30,11 +32,11 @@ func (ca *MockCA) IssueCertificate(csr x509.CertificateRequest, regID int64) (co
}
// GenerateOCSP is a mock
func (ca *MockCA) GenerateOCSP(xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {
func (ca *MockCA) GenerateOCSP(ctx context.Context, xferObj core.OCSPSigningRequest) (ocsp []byte, err error) {
return
}
// RevokeCertificate is a mock
func (ca *MockCA) RevokeCertificate(serial string, reasonCode core.RevocationCode) (err error) {
func (ca *MockCA) RevokeCertificate(ctx context.Context, serial string, reasonCode core.RevocationCode) (err error) {
return
}

View File

@ -13,6 +13,8 @@ import (
"net"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
@ -61,7 +63,7 @@ const (
)
// GetRegistration is a mock
func (sa *StorageAuthority) GetRegistration(id int64) (core.Registration, error) {
func (sa *StorageAuthority) GetRegistration(_ context.Context, id int64) (core.Registration, error) {
if id == 100 {
// Tag meaning "Missing"
return core.Registration{}, errors.New("missing")
@ -88,7 +90,7 @@ func (sa *StorageAuthority) GetRegistration(id int64) (core.Registration, error)
}
// GetRegistrationByKey is a mock
func (sa *StorageAuthority) GetRegistrationByKey(jwk jose.JsonWebKey) (core.Registration, error) {
func (sa *StorageAuthority) GetRegistrationByKey(_ context.Context, jwk jose.JsonWebKey) (core.Registration, error) {
var test1KeyPublic jose.JsonWebKey
var test2KeyPublic jose.JsonWebKey
var testE1KeyPublic jose.JsonWebKey
@ -133,7 +135,7 @@ func (sa *StorageAuthority) GetRegistrationByKey(jwk jose.JsonWebKey) (core.Regi
}
// GetAuthorization is a mock
func (sa *StorageAuthority) GetAuthorization(id string) (core.Authorization, error) {
func (sa *StorageAuthority) GetAuthorization(_ context.Context, id string) (core.Authorization, error) {
authz := core.Authorization{
ID: "valid",
Status: core.StatusValid,
@ -163,12 +165,12 @@ func (sa *StorageAuthority) GetAuthorization(id string) (core.Authorization, err
}
// RevokeAuthorizationsByDomain is a mock
func (sa *StorageAuthority) RevokeAuthorizationsByDomain(ident core.AcmeIdentifier) (int64, int64, error) {
func (sa *StorageAuthority) RevokeAuthorizationsByDomain(_ context.Context, ident core.AcmeIdentifier) (int64, int64, error) {
return 0, 0, nil
}
// GetCertificate is a mock
func (sa *StorageAuthority) GetCertificate(serial string) (core.Certificate, error) {
func (sa *StorageAuthority) GetCertificate(_ context.Context, serial string) (core.Certificate, error) {
// Serial ee == 238.crt
if serial == "0000000000000000000000000000000000ee" {
certPemBytes, _ := ioutil.ReadFile("test/238.crt")
@ -190,7 +192,7 @@ func (sa *StorageAuthority) GetCertificate(serial string) (core.Certificate, err
}
// GetCertificateStatus is a mock
func (sa *StorageAuthority) GetCertificateStatus(serial string) (core.CertificateStatus, error) {
func (sa *StorageAuthority) GetCertificateStatus(_ context.Context, serial string) (core.CertificateStatus, error) {
// Serial ee == 238.crt
if serial == "0000000000000000000000000000000000ee" {
return core.CertificateStatus{
@ -206,57 +208,57 @@ func (sa *StorageAuthority) GetCertificateStatus(serial string) (core.Certificat
}
// AlreadyDeniedCSR is a mock
func (sa *StorageAuthority) AlreadyDeniedCSR([]string) (bool, error) {
func (sa *StorageAuthority) AlreadyDeniedCSR(_ context.Context, domains []string) (bool, error) {
return false, nil
}
// AddCertificate is a mock
func (sa *StorageAuthority) AddCertificate(certDER []byte, regID int64) (digest string, err error) {
func (sa *StorageAuthority) AddCertificate(_ context.Context, certDER []byte, regID int64) (digest string, err error) {
return
}
// FinalizeAuthorization is a mock
func (sa *StorageAuthority) FinalizeAuthorization(authz core.Authorization) (err error) {
func (sa *StorageAuthority) FinalizeAuthorization(_ context.Context, authz core.Authorization) (err error) {
return
}
// MarkCertificateRevoked is a mock
func (sa *StorageAuthority) MarkCertificateRevoked(serial string, reasonCode core.RevocationCode) (err error) {
func (sa *StorageAuthority) MarkCertificateRevoked(_ context.Context, serial string, reasonCode core.RevocationCode) (err error) {
return
}
// UpdateOCSP is a mock
func (sa *StorageAuthority) UpdateOCSP(serial string, ocspResponse []byte) (err error) {
func (sa *StorageAuthority) UpdateOCSP(_ context.Context, serial string, ocspResponse []byte) (err error) {
return
}
// NewPendingAuthorization is a mock
func (sa *StorageAuthority) NewPendingAuthorization(authz core.Authorization) (output core.Authorization, err error) {
func (sa *StorageAuthority) NewPendingAuthorization(_ context.Context, authz core.Authorization) (output core.Authorization, err error) {
return
}
// NewRegistration is a mock
func (sa *StorageAuthority) NewRegistration(reg core.Registration) (regR core.Registration, err error) {
func (sa *StorageAuthority) NewRegistration(_ context.Context, reg core.Registration) (regR core.Registration, err error) {
return
}
// UpdatePendingAuthorization is a mock
func (sa *StorageAuthority) UpdatePendingAuthorization(authz core.Authorization) (err error) {
func (sa *StorageAuthority) UpdatePendingAuthorization(_ context.Context, authz core.Authorization) (err error) {
return
}
// UpdateRegistration is a mock
func (sa *StorageAuthority) UpdateRegistration(reg core.Registration) (err error) {
func (sa *StorageAuthority) UpdateRegistration(_ context.Context, reg core.Registration) (err error) {
return
}
// GetSCTReceipt is a mock
func (sa *StorageAuthority) GetSCTReceipt(serial string, logID string) (sct core.SignedCertificateTimestamp, err error) {
func (sa *StorageAuthority) GetSCTReceipt(_ context.Context, serial string, logID string) (sct core.SignedCertificateTimestamp, err error) {
return
}
// AddSCTReceipt is a mock
func (sa *StorageAuthority) AddSCTReceipt(sct core.SignedCertificateTimestamp) (err error) {
func (sa *StorageAuthority) AddSCTReceipt(_ context.Context, sct core.SignedCertificateTimestamp) (err error) {
if sct.Signature == nil {
err = fmt.Errorf("Bad times")
}
@ -264,17 +266,17 @@ func (sa *StorageAuthority) AddSCTReceipt(sct core.SignedCertificateTimestamp) (
}
// CountFQDNSets is a mock
func (sa *StorageAuthority) CountFQDNSets(since time.Duration, names []string) (int64, error) {
func (sa *StorageAuthority) CountFQDNSets(_ context.Context, since time.Duration, names []string) (int64, error) {
return 0, nil
}
// FQDNSetExists is a mock
func (sa *StorageAuthority) FQDNSetExists(names []string) (bool, error) {
func (sa *StorageAuthority) FQDNSetExists(_ context.Context, names []string) (bool, error) {
return false, nil
}
// GetLatestValidAuthorization is a mock
func (sa *StorageAuthority) GetLatestValidAuthorization(registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
func (sa *StorageAuthority) GetLatestValidAuthorization(_ context.Context, registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
if registrationID == 1 && identifier.Type == "dns" {
if sa.authorizedDomains[identifier.Value] || identifier.Value == "not-an-example.com" {
exp := sa.clk.Now().AddDate(100, 0, 0)
@ -285,7 +287,7 @@ func (sa *StorageAuthority) GetLatestValidAuthorization(registrationID int64, id
}
// GetValidAuthorizations is a mock
func (sa *StorageAuthority) GetValidAuthorizations(regID int64, names []string, now time.Time) (map[string]*core.Authorization, error) {
func (sa *StorageAuthority) GetValidAuthorizations(_ context.Context, regID int64, names []string, now time.Time) (map[string]*core.Authorization, error) {
if regID == 1 {
auths := make(map[string]*core.Authorization)
for _, name := range names {
@ -308,22 +310,22 @@ func (sa *StorageAuthority) GetValidAuthorizations(regID int64, names []string,
}
// CountCertificatesRange is a mock
func (sa *StorageAuthority) CountCertificatesRange(_, _ time.Time) (int64, error) {
func (sa *StorageAuthority) CountCertificatesRange(_ context.Context, _, _ time.Time) (int64, error) {
return 0, nil
}
// CountCertificatesByNames is a mock
func (sa *StorageAuthority) CountCertificatesByNames(_ []string, _, _ time.Time) (ret map[string]int, err error) {
func (sa *StorageAuthority) CountCertificatesByNames(_ context.Context, _ []string, _, _ time.Time) (ret map[string]int, err error) {
return
}
// CountRegistrationsByIP is a mock
func (sa *StorageAuthority) CountRegistrationsByIP(_ net.IP, _, _ time.Time) (int, error) {
func (sa *StorageAuthority) CountRegistrationsByIP(_ context.Context, _ net.IP, _, _ time.Time) (int, error) {
return 0, nil
}
// CountPendingAuthorizations is a mock
func (sa *StorageAuthority) CountPendingAuthorizations(_ int64) (int, error) {
func (sa *StorageAuthority) CountPendingAuthorizations(_ context.Context, _ int64) (int, error) {
return 0, nil
}
@ -333,7 +335,7 @@ type Publisher struct {
}
// SubmitToCT is a mock
func (*Publisher) SubmitToCT([]byte) error {
func (*Publisher) SubmitToCT(_ context.Context, der []byte) error {
return nil
}

View File

@ -3,8 +3,9 @@ package probs
import (
"testing"
"github.com/letsencrypt/boulder/test"
"net/http"
"github.com/letsencrypt/boulder/test"
)
func TestProblemDetails(t *testing.T) {

View File

@ -83,7 +83,7 @@ func New(bundle []ct.ASN1Cert, logs []*Log, submissionTimeout time.Duration, log
// SubmitToCT will submit the certificate represented by certDER to any CT
// logs configured in pub.CT.Logs
func (pub *Impl) SubmitToCT(der []byte) error {
func (pub *Impl) SubmitToCT(ctx context.Context, der []byte) error {
cert, err := x509.ParseCertificate(der)
if err != nil {
pub.log.Err(fmt.Sprintf("Failed to parse certificate: %s", err))
@ -123,7 +123,7 @@ func (pub *Impl) SubmitToCT(der []byte) error {
continue
}
err = pub.SA.AddSCTReceipt(internalSCT)
err = pub.SA.AddSCTReceipt(ctx, internalSCT)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
pub.log.Err(fmt.Sprintf("Failed to store SCT receipt in database: %s", err))

View File

@ -25,6 +25,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
ct "github.com/google/certificate-transparency/go"
"github.com/jmhodges/clock"
@ -117,6 +119,7 @@ OY8B7wwvZTLzU6WWs781TJXx2CE04PneeeArLpVLkiGIWjk=
const issuerPath = "../test/test-ca.pem"
var log = blog.UseMock()
var ctx = context.Background()
func getPort(hs *httptest.Server) (int, error) {
url, err := url.Parse(hs.URL)
@ -290,14 +293,14 @@ func TestBasicSuccessful(t *testing.T) {
addLog(t, pub, port, &k.PublicKey)
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0)
// No Intermediate
pub.issuerBundle = []ct.ASN1Cert{}
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0)
}
@ -312,7 +315,7 @@ func TestGoodRetry(t *testing.T) {
addLog(t, pub, port, &k.PublicKey)
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0)
}
@ -327,7 +330,7 @@ func TestUnexpectedError(t *testing.T) {
addLog(t, pub, port, &k.PublicKey)
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed .*http://localhost:"+strconv.Itoa(port))), 1)
}
@ -344,7 +347,7 @@ func TestRetryAfter(t *testing.T) {
log.Clear()
startedWaiting := time.Now()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0)
test.Assert(t, time.Since(startedWaiting) > time.Duration(retryAfter*2)*time.Second, fmt.Sprintf("Submitter retried submission too fast: %s", time.Since(startedWaiting)))
@ -362,7 +365,7 @@ func TestRetryAfterContext(t *testing.T) {
pub.submissionTimeout = time.Second
s := time.Now()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Failed to submit to CT")
took := time.Since(s)
test.Assert(t, len(log.GetAllMatching(".*Failed to submit certificate to CT log at .*: context deadline exceeded.*")) == 1, "Submission didn't timeout")
@ -384,7 +387,7 @@ func TestMultiLog(t *testing.T) {
addLog(t, pub, portB, &k.PublicKey)
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0)
}
@ -399,7 +402,7 @@ func TestBadServer(t *testing.T) {
addLog(t, pub, port, &k.PublicKey)
log.Clear()
err = pub.SubmitToCT(leaf.Raw)
err = pub.SubmitToCT(ctx, leaf.Raw)
test.AssertNotError(t, err, "Certificate submission failed")
test.AssertEquals(t, len(log.GetAllMatching("Failed to verify SCT receipt")), 1)
}

View File

@ -180,24 +180,25 @@ func (ra *RegistrationAuthorityImpl) issuanceCountInvalid(now time.Time) bool {
return ra.lastIssuedCount == nil || ra.lastIssuedCount.Add(issuanceCountCacheLife).Before(now)
}
func (ra *RegistrationAuthorityImpl) getIssuanceCount() (int, error) {
func (ra *RegistrationAuthorityImpl) getIssuanceCount(ctx context.Context) (int, error) {
ra.tiMu.RLock()
if ra.issuanceCountInvalid(ra.clk.Now()) {
ra.tiMu.RUnlock()
return ra.setIssuanceCount()
return ra.setIssuanceCount(ctx)
}
count := ra.totalIssuedCache
ra.tiMu.RUnlock()
return count, nil
}
func (ra *RegistrationAuthorityImpl) setIssuanceCount() (int, error) {
func (ra *RegistrationAuthorityImpl) setIssuanceCount(ctx context.Context) (int, error) {
ra.tiMu.Lock()
defer ra.tiMu.Unlock()
now := ra.clk.Now()
if ra.issuanceCountInvalid(now) {
count, err := ra.SA.CountCertificatesRange(
ctx,
now.Add(-ra.rlPolicies.TotalCertificates.Window.Duration),
now,
)
@ -214,11 +215,11 @@ func (ra *RegistrationAuthorityImpl) setIssuanceCount() (int, error) {
// registration-based overrides are necessary.
const noRegistrationID = -1
func (ra *RegistrationAuthorityImpl) checkRegistrationLimit(ip net.IP) error {
func (ra *RegistrationAuthorityImpl) checkRegistrationLimit(ctx context.Context, ip net.IP) error {
limit := ra.rlPolicies.RegistrationsPerIP
if limit.Enabled() {
now := ra.clk.Now()
count, err := ra.SA.CountRegistrationsByIP(ip, limit.WindowBegin(now), now)
count, err := ra.SA.CountRegistrationsByIP(ctx, ip, limit.WindowBegin(now), now)
if err != nil {
return err
}
@ -233,11 +234,11 @@ func (ra *RegistrationAuthorityImpl) checkRegistrationLimit(ip net.IP) error {
}
// NewRegistration constructs a new Registration from a request.
func (ra *RegistrationAuthorityImpl) NewRegistration(init core.Registration) (reg core.Registration, err error) {
func (ra *RegistrationAuthorityImpl) NewRegistration(ctx context.Context, init core.Registration) (reg core.Registration, err error) {
if err = ra.keyPolicy.GoodKey(init.Key.Key); err != nil {
return core.Registration{}, core.MalformedRequestError(fmt.Sprintf("Invalid public key: %s", err.Error()))
}
if err = ra.checkRegistrationLimit(init.InitialIP); err != nil {
if err = ra.checkRegistrationLimit(ctx, init.InitialIP); err != nil {
return core.Registration{}, err
}
@ -250,14 +251,13 @@ func (ra *RegistrationAuthorityImpl) NewRegistration(init core.Registration) (re
// MergeUpdate. But we need to fill it in for new registrations.
reg.InitialIP = init.InitialIP
// TODO(#1292): add a proper deadline here
err = ra.validateContacts(context.TODO(), reg.Contact)
err = ra.validateContacts(ctx, reg.Contact)
if err != nil {
return
}
// Store the authorization object, then return it
reg, err = ra.SA.NewRegistration(reg)
reg, err = ra.SA.NewRegistration(ctx, reg)
if err != nil {
// InternalServerError since the user-data was validated before being
// passed to the SA.
@ -296,10 +296,10 @@ func (ra *RegistrationAuthorityImpl) validateContacts(ctx context.Context, conta
return nil
}
func (ra *RegistrationAuthorityImpl) checkPendingAuthorizationLimit(regID int64) error {
func (ra *RegistrationAuthorityImpl) checkPendingAuthorizationLimit(ctx context.Context, regID int64) error {
limit := ra.rlPolicies.PendingAuthorizationsPerAccount
if limit.Enabled() {
count, err := ra.SA.CountPendingAuthorizations(regID)
count, err := ra.SA.CountPendingAuthorizations(ctx, regID)
if err != nil {
return err
}
@ -318,8 +318,8 @@ func (ra *RegistrationAuthorityImpl) checkPendingAuthorizationLimit(regID int64)
// NewAuthorization constructs a new Authz from a request. Values (domains) in
// request.Identifier will be lowercased before storage.
func (ra *RegistrationAuthorityImpl) NewAuthorization(request core.Authorization, regID int64) (authz core.Authorization, err error) {
reg, err := ra.SA.GetRegistration(regID)
func (ra *RegistrationAuthorityImpl) NewAuthorization(ctx context.Context, request core.Authorization, regID int64) (authz core.Authorization, err error) {
reg, err := ra.SA.GetRegistration(ctx, regID)
if err != nil {
err = core.MalformedRequestError(fmt.Sprintf("Invalid registration ID: %d", regID))
return authz, err
@ -333,12 +333,12 @@ func (ra *RegistrationAuthorityImpl) NewAuthorization(request core.Authorization
return authz, err
}
if err = ra.checkPendingAuthorizationLimit(regID); err != nil {
if err = ra.checkPendingAuthorizationLimit(ctx, regID); err != nil {
return authz, err
}
if identifier.Type == core.IdentifierDNS {
isSafe, err := ra.dc.IsSafe(identifier.Value)
isSafe, err := ra.dc.IsSafe(ctx, identifier.Value)
if err != nil {
outErr := core.InternalServerError("unable to determine if domain was safe")
ra.log.Warning(fmt.Sprintf("%s: %s", string(outErr), err))
@ -365,7 +365,7 @@ func (ra *RegistrationAuthorityImpl) NewAuthorization(request core.Authorization
}
// Get a pending Auth first so we can get our ID back, then update with challenges
authz, err = ra.SA.NewPendingAuthorization(authz)
authz, err = ra.SA.NewPendingAuthorization(ctx, authz)
if err != nil {
// InternalServerError since the user-data was validated before being
// passed to the SA.
@ -464,13 +464,13 @@ func (ra *RegistrationAuthorityImpl) MatchesCSR(cert core.Certificate, csr *x509
// checkAuthorizations checks that each requested name has a valid authorization
// that won't expire before the certificate expires. Returns an error otherwise.
func (ra *RegistrationAuthorityImpl) checkAuthorizations(names []string, registration *core.Registration) error {
func (ra *RegistrationAuthorityImpl) checkAuthorizations(ctx context.Context, names []string, registration *core.Registration) error {
now := ra.clk.Now()
var badNames []string
for i := range names {
names[i] = strings.ToLower(names[i])
}
auths, err := ra.SA.GetValidAuthorizations(registration.ID, names, now)
auths, err := ra.SA.GetValidAuthorizations(ctx, registration.ID, names, now)
if err != nil {
return err
}
@ -494,7 +494,7 @@ func (ra *RegistrationAuthorityImpl) checkAuthorizations(names []string, registr
}
// NewCertificate requests the issuance of a certificate.
func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest, regID int64) (cert core.Certificate, err error) {
func (ra *RegistrationAuthorityImpl) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (cert core.Certificate, err error) {
emptyCert := core.Certificate{}
var logEventResult string
@ -520,7 +520,7 @@ func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest,
return emptyCert, err
}
registration, err := ra.SA.GetRegistration(regID)
registration, err := ra.SA.GetRegistration(ctx, regID)
if err != nil {
logEvent.Error = err.Error()
return emptyCert, err
@ -550,7 +550,7 @@ func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest,
return emptyCert, err
}
csrPreviousDenied, err := ra.SA.AlreadyDeniedCSR(names)
csrPreviousDenied, err := ra.SA.AlreadyDeniedCSR(ctx, names)
if err != nil {
logEvent.Error = err.Error()
return emptyCert, err
@ -569,13 +569,13 @@ func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest,
// Check rate limits before checking authorizations. If someone is unable to
// issue a cert due to rate limiting, we don't want to tell them to go get the
// necessary authorizations, only to later fail the rate limit check.
err = ra.checkLimits(names, registration.ID)
err = ra.checkLimits(ctx, names, registration.ID)
if err != nil {
logEvent.Error = err.Error()
return emptyCert, err
}
err = ra.checkAuthorizations(names, &registration)
err = ra.checkAuthorizations(ctx, names, &registration)
if err != nil {
logEvent.Error = err.Error()
return emptyCert, err
@ -585,7 +585,7 @@ func (ra *RegistrationAuthorityImpl) NewCertificate(req core.CertificateRequest,
logEvent.VerifiedFields = []string{"subject.commonName", "subjectAltName"}
// Create the certificate and log the result
if cert, err = ra.CA.IssueCertificate(*csr, regID); err != nil {
if cert, err = ra.CA.IssueCertificate(ctx, *csr, regID); err != nil {
logEvent.Error = err.Error()
return emptyCert, err
}
@ -642,14 +642,14 @@ func domainsForRateLimiting(names []string) ([]string, error) {
return domains, nil
}
func (ra *RegistrationAuthorityImpl) checkCertificatesPerNameLimit(names []string, limit cmd.RateLimitPolicy, regID int64) error {
func (ra *RegistrationAuthorityImpl) checkCertificatesPerNameLimit(ctx context.Context, names []string, limit cmd.RateLimitPolicy, regID int64) error {
names, err := domainsForRateLimiting(names)
if err != nil {
return err
}
now := ra.clk.Now()
windowBegin := limit.WindowBegin(now)
counts, err := ra.SA.CountCertificatesByNames(names, windowBegin, now)
counts, err := ra.SA.CountCertificatesByNames(ctx, names, windowBegin, now)
if err != nil {
return err
}
@ -668,7 +668,7 @@ func (ra *RegistrationAuthorityImpl) checkCertificatesPerNameLimit(names []strin
// check if there is already a existing certificate for
// the exact name set we are issuing for. If so bypass the
// the certificatesPerName limit.
exists, err := ra.SA.FQDNSetExists(names)
exists, err := ra.SA.FQDNSetExists(ctx, names)
if err != nil {
return err
}
@ -688,8 +688,8 @@ func (ra *RegistrationAuthorityImpl) checkCertificatesPerNameLimit(names []strin
return nil
}
func (ra *RegistrationAuthorityImpl) checkCertificatesPerFQDNSetLimit(names []string, limit cmd.RateLimitPolicy, regID int64) error {
count, err := ra.SA.CountFQDNSets(limit.Window.Duration, names)
func (ra *RegistrationAuthorityImpl) checkCertificatesPerFQDNSetLimit(ctx context.Context, names []string, limit cmd.RateLimitPolicy, regID int64) error {
count, err := ra.SA.CountFQDNSets(ctx, limit.Window.Duration, names)
if err != nil {
return err
}
@ -703,10 +703,10 @@ func (ra *RegistrationAuthorityImpl) checkCertificatesPerFQDNSetLimit(names []st
return nil
}
func (ra *RegistrationAuthorityImpl) checkLimits(names []string, regID int64) error {
func (ra *RegistrationAuthorityImpl) checkLimits(ctx context.Context, names []string, regID int64) error {
limits := ra.rlPolicies
if limits.TotalCertificates.Enabled() {
totalIssued, err := ra.getIssuanceCount()
totalIssued, err := ra.getIssuanceCount(ctx)
if err != nil {
return err
}
@ -719,13 +719,13 @@ func (ra *RegistrationAuthorityImpl) checkLimits(names []string, regID int64) er
ra.totalCertsStats.Inc("Pass", 1)
}
if limits.CertificatesPerName.Enabled() {
err := ra.checkCertificatesPerNameLimit(names, limits.CertificatesPerName, regID)
err := ra.checkCertificatesPerNameLimit(ctx, names, limits.CertificatesPerName, regID)
if err != nil {
return err
}
}
if limits.CertificatesPerFQDNSet.Enabled() {
err := ra.checkCertificatesPerFQDNSetLimit(names, limits.CertificatesPerFQDNSet, regID)
err := ra.checkCertificatesPerFQDNSetLimit(ctx, names, limits.CertificatesPerFQDNSet, regID)
if err != nil {
return err
}
@ -734,17 +734,16 @@ func (ra *RegistrationAuthorityImpl) checkLimits(names []string, regID int64) er
}
// UpdateRegistration updates an existing Registration with new values.
func (ra *RegistrationAuthorityImpl) UpdateRegistration(base core.Registration, update core.Registration) (reg core.Registration, err error) {
func (ra *RegistrationAuthorityImpl) UpdateRegistration(ctx context.Context, base core.Registration, update core.Registration) (reg core.Registration, err error) {
base.MergeUpdate(update)
// TODO(#1292): add a proper deadline here
err = ra.validateContacts(context.TODO(), base.Contact)
err = ra.validateContacts(ctx, base.Contact)
if err != nil {
return
}
reg = base
err = ra.SA.UpdateRegistration(base)
err = ra.SA.UpdateRegistration(ctx, base)
if err != nil {
// InternalServerError since the user-data was validated before being
// passed to the SA.
@ -756,7 +755,7 @@ func (ra *RegistrationAuthorityImpl) UpdateRegistration(base core.Registration,
}
// UpdateAuthorization updates an authorization with new values.
func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization, challengeIndex int, response core.Challenge) (authz core.Authorization, err error) {
func (ra *RegistrationAuthorityImpl) UpdateAuthorization(ctx context.Context, base core.Authorization, challengeIndex int, response core.Challenge) (authz core.Authorization, err error) {
// Refuse to update expired authorizations
if base.Expires == nil || base.Expires.Before(ra.clk.Now()) {
err = core.NotFoundError("Expired authorization")
@ -800,7 +799,7 @@ func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization
}
// Store the updated version
if err = ra.SA.UpdatePendingAuthorization(authz); err != nil {
if err = ra.SA.UpdatePendingAuthorization(ctx, authz); err != nil {
// This can pretty much only happen when the client corrupts the Challenge
// data.
err = core.MalformedRequestError("Challenge data was corrupted")
@ -809,7 +808,7 @@ func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization
ra.stats.Inc("RA.NewPendingAuthorizations", 1, 1.0)
// Look up the account key for this authorization
reg, err := ra.SA.GetRegistration(authz.RegistrationID)
reg, err := ra.SA.GetRegistration(ctx, authz.RegistrationID)
if err != nil {
err = core.InternalServerError(err.Error())
return
@ -824,13 +823,14 @@ func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization
// Dispatch to the VA for service
vaCtx := context.Background()
if !ra.useNewVARPC {
// TODO(#1167): remove
_ = ra.VA.UpdateValidations(authz, challengeIndex)
_ = ra.VA.UpdateValidations(vaCtx, authz, challengeIndex)
ra.stats.Inc("RA.UpdatedPendingAuthorizations", 1, 1.0)
} else {
go func() {
records, err := ra.VA.PerformValidation(authz.Identifier.Value, authz.Challenges[challengeIndex], authz)
records, err := ra.VA.PerformValidation(vaCtx, authz.Identifier.Value, authz.Challenges[challengeIndex], authz)
var prob *probs.ProblemDetails
if p, ok := err.(*probs.ProblemDetails); ok {
prob = p
@ -853,7 +853,7 @@ func (ra *RegistrationAuthorityImpl) UpdateAuthorization(base core.Authorization
}
authz.Challenges[challengeIndex] = *challenge
err = ra.OnValidationUpdate(authz)
err = ra.OnValidationUpdate(vaCtx, authz)
if err != nil {
ra.log.Err(fmt.Sprintf("Could not record updated validation: err=[%s] regID=[%d]", err, authz.RegistrationID))
}
@ -876,9 +876,9 @@ func revokeEvent(state, serial, cn string, names []string, revocationCode core.R
}
// RevokeCertificateWithReg terminates trust in the certificate provided.
func (ra *RegistrationAuthorityImpl) RevokeCertificateWithReg(cert x509.Certificate, revocationCode core.RevocationCode, regID int64) (err error) {
func (ra *RegistrationAuthorityImpl) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, revocationCode core.RevocationCode, regID int64) (err error) {
serialString := core.SerialToString(cert.SerialNumber)
err = ra.SA.MarkCertificateRevoked(serialString, revocationCode)
err = ra.SA.MarkCertificateRevoked(ctx, serialString, revocationCode)
state := "Failure"
defer func() {
@ -909,9 +909,9 @@ func (ra *RegistrationAuthorityImpl) RevokeCertificateWithReg(cert x509.Certific
// AdministrativelyRevokeCertificate terminates trust in the certificate provided and
// does not require the registration ID of the requester since this method is only
// called from the admin-revoker tool.
func (ra *RegistrationAuthorityImpl) AdministrativelyRevokeCertificate(cert x509.Certificate, revocationCode core.RevocationCode, user string) error {
func (ra *RegistrationAuthorityImpl) AdministrativelyRevokeCertificate(ctx context.Context, cert x509.Certificate, revocationCode core.RevocationCode, user string) error {
serialString := core.SerialToString(cert.SerialNumber)
err := ra.SA.MarkCertificateRevoked(serialString, revocationCode)
err := ra.SA.MarkCertificateRevoked(ctx, serialString, revocationCode)
state := "Failure"
defer func() {
@ -941,7 +941,7 @@ func (ra *RegistrationAuthorityImpl) AdministrativelyRevokeCertificate(cert x509
}
// OnValidationUpdate is called when a given Authorization is updated by the VA.
func (ra *RegistrationAuthorityImpl) OnValidationUpdate(authz core.Authorization) error {
func (ra *RegistrationAuthorityImpl) OnValidationUpdate(ctx context.Context, authz core.Authorization) error {
// Consider validation successful if any of the combinations
// specified in the authorization has been fulfilled
validated := map[int]bool{}
@ -973,7 +973,7 @@ func (ra *RegistrationAuthorityImpl) OnValidationUpdate(authz core.Authorization
}
// Finalize the authorization
err := ra.SA.FinalizeAuthorization(authz)
err := ra.SA.FinalizeAuthorization(ctx, authz)
if err != nil {
return err
}

View File

@ -41,19 +41,19 @@ type DummyValidationAuthority struct {
IsSafeDomainErr error
}
func (dva *DummyValidationAuthority) UpdateValidations(authz core.Authorization, index int) (err error) {
func (dva *DummyValidationAuthority) UpdateValidations(ctx context.Context, authz core.Authorization, index int) (err error) {
dva.Called = true
dva.Argument = authz
return
}
func (dva *DummyValidationAuthority) PerformValidation(domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
func (dva *DummyValidationAuthority) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
dva.Called = true
dva.Argument = authz
return dva.RecordsReturn, dva.ProblemReturn
}
func (dva *DummyValidationAuthority) IsSafeDomain(req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
func (dva *DummyValidationAuthority) IsSafeDomain(ctx context.Context, req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
if dva.IsSafeDomainErr != nil {
return nil, dva.IsSafeDomainErr
}
@ -153,6 +153,8 @@ var testKeyPolicy = core.KeyPolicy{
AllowECDSANISTP384: true,
}
var ctx = context.Background()
func initAuthorities(t *testing.T) (*DummyValidationAuthority, *sa.SQLStorageAuthority, *RegistrationAuthorityImpl, clock.FakeClock, func()) {
err := json.Unmarshal(AccountKeyJSONA, &AccountKeyA)
test.AssertNotError(t, err, "Failed to unmarshal public JWK")
@ -203,7 +205,7 @@ func initAuthorities(t *testing.T) (*DummyValidationAuthority, *sa.SQLStorageAut
block, _ := pem.Decode(CSRPEM)
ExampleCSR, _ = x509.ParseCertificateRequest(block.Bytes)
Registration, _ = ssa.NewRegistration(core.Registration{
Registration, _ = ssa.NewRegistration(ctx, core.Registration{
Key: AccountKeyA,
InitialIP: net.ParseIP("3.2.3.3"),
})
@ -328,7 +330,7 @@ func TestNewRegistration(t *testing.T) {
InitialIP: net.ParseIP("7.6.6.5"),
}
result, err := ra.NewRegistration(input)
result, err := ra.NewRegistration(ctx, input)
if err != nil {
t.Fatalf("could not create new registration: %s", err)
}
@ -339,7 +341,7 @@ func TestNewRegistration(t *testing.T) {
"Contact didn't match")
test.Assert(t, result.Agreement == "", "Agreement didn't default empty")
reg, err := sa.GetRegistration(result.ID)
reg, err := sa.GetRegistration(ctx, result.ID)
test.AssertNotError(t, err, "Failed to retrieve registration")
test.Assert(t, core.KeyDigestEquals(reg.Key, AccountKeyB), "Retrieved registration differed.")
}
@ -356,7 +358,7 @@ func TestNewRegistrationNoFieldOverwrite(t *testing.T) {
InitialIP: net.ParseIP("5.0.5.0"),
}
result, err := ra.NewRegistration(input)
result, err := ra.NewRegistration(ctx, input)
test.AssertNotError(t, err, "Could not create new registration")
test.Assert(t, result.ID != 23, "ID shouldn't be set by user")
@ -364,7 +366,7 @@ func TestNewRegistrationNoFieldOverwrite(t *testing.T) {
//test.Assert(t, result.Agreement != "I agreed", "Agreement shouldn't be set with invalid URL")
id := result.ID
result2, err := ra.UpdateRegistration(result, core.Registration{
result2, err := ra.UpdateRegistration(ctx, result, core.Registration{
ID: 33,
Key: ShortKey,
})
@ -382,21 +384,21 @@ func TestNewRegistrationBadKey(t *testing.T) {
Key: ShortKey,
}
_, err := ra.NewRegistration(input)
_, err := ra.NewRegistration(ctx, input)
test.AssertError(t, err, "Should have rejected authorization with short key")
}
func TestNewAuthorization(t *testing.T) {
_, sa, ra, _, cleanUp := initAuthorities(t)
defer cleanUp()
_, err := ra.NewAuthorization(AuthzRequest, 0)
_, err := ra.NewAuthorization(ctx, AuthzRequest, 0)
test.AssertError(t, err, "Authorization cannot have registrationID == 0")
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
// Verify that returned authz same as DB
dbAuthz, err := sa.GetAuthorization(authz.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authz.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authz, dbAuthz)
@ -425,11 +427,11 @@ func TestNewAuthorizationCapitalLetters(t *testing.T) {
Value: "NOT-example.COM",
},
}
authz, err := ra.NewAuthorization(authzReq, Registration.ID)
authz, err := ra.NewAuthorization(ctx, authzReq, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
test.AssertEquals(t, "not-example.com", authz.Identifier.Value)
dbAuthz, err := sa.GetAuthorization(authz.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authz.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authz, dbAuthz)
}
@ -444,7 +446,7 @@ func TestNewAuthorizationInvalidName(t *testing.T) {
Value: "127.0.0.1",
},
}
_, err := ra.NewAuthorization(authzReq, Registration.ID)
_, err := ra.NewAuthorization(ctx, authzReq, Registration.ID)
if err == nil {
t.Fatalf("NewAuthorization succeeded for 127.0.0.1, should have failed")
}
@ -458,16 +460,16 @@ func TestUpdateAuthorization(t *testing.T) {
defer cleanUp()
// We know this is OK because of TestNewAuthorization
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
response, err := makeResponse(authz.Challenges[ResponseIndex])
test.AssertNotError(t, err, "Unable to construct response to challenge")
authz, err = ra.UpdateAuthorization(authz, ResponseIndex, response)
authz, err = ra.UpdateAuthorization(ctx, authz, ResponseIndex, response)
test.AssertNotError(t, err, "UpdateAuthorization failed")
// Verify that returned authz same as DB
dbAuthz, err := sa.GetAuthorization(authz.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authz.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authz, dbAuthz)
@ -485,7 +487,7 @@ func TestUpdateAuthorizationExpired(t *testing.T) {
_, _, ra, fc, cleanUp := initAuthorities(t)
defer cleanUp()
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
expiry := fc.Now().Add(-2 * time.Hour)
@ -493,7 +495,7 @@ func TestUpdateAuthorizationExpired(t *testing.T) {
response, err := makeResponse(authz.Challenges[ResponseIndex])
authz, err = ra.UpdateAuthorization(authz, ResponseIndex, response)
authz, err = ra.UpdateAuthorization(ctx, authz, ResponseIndex, response)
test.AssertError(t, err, "Updated expired authorization")
}
@ -502,20 +504,20 @@ func TestUpdateAuthorizationReject(t *testing.T) {
defer cleanUp()
// We know this is OK because of TestNewAuthorization
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
// Change the account key
reg, err := sa.GetRegistration(authz.RegistrationID)
reg, err := sa.GetRegistration(ctx, authz.RegistrationID)
test.AssertNotError(t, err, "GetRegistration failed")
reg.Key = AccountKeyC // was AccountKeyA
err = sa.UpdateRegistration(reg)
err = sa.UpdateRegistration(ctx, reg)
test.AssertNotError(t, err, "UpdateRegistration failed")
// Verify that the RA rejected the authorization request
response, err := makeResponse(authz.Challenges[ResponseIndex])
test.AssertNotError(t, err, "Unable to construct response to challenge")
_, err = ra.UpdateAuthorization(authz, ResponseIndex, response)
_, err = ra.UpdateAuthorization(ctx, authz, ResponseIndex, response)
test.AssertEquals(t, err, core.UnauthorizedError("Challenge cannot be updated with a different key"))
t.Log("DONE TestUpdateAuthorizationReject")
@ -527,7 +529,7 @@ func TestUpdateAuthorizationNewRPC(t *testing.T) {
defer cleanUp()
// We know this is OK because of TestNewAuthorization
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
response, err := makeResponse(authz.Challenges[ResponseIndex])
@ -537,11 +539,11 @@ func TestUpdateAuthorizationNewRPC(t *testing.T) {
{Hostname: "example.com"}}
va.ProblemReturn = nil
authz, err = ra.UpdateAuthorization(authz, ResponseIndex, response)
authz, err = ra.UpdateAuthorization(ctx, authz, ResponseIndex, response)
test.AssertNotError(t, err, "UpdateAuthorization failed")
// Verify that returned authz same as DB
dbAuthz, err := sa.GetAuthorization(authz.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authz.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authz, dbAuthz)
@ -559,24 +561,24 @@ func TestUpdateAuthorizationNewRPC(t *testing.T) {
func TestOnValidationUpdateSuccess(t *testing.T) {
_, sa, ra, fclk, cleanUp := initAuthorities(t)
defer cleanUp()
authzUpdated, err := sa.NewPendingAuthorization(AuthzInitial)
authzUpdated, err := sa.NewPendingAuthorization(ctx, AuthzInitial)
test.AssertNotError(t, err, "Failed to create new pending authz")
expires := fclk.Now().Add(300 * 24 * time.Hour)
authzUpdated.Expires = &expires
err = sa.UpdatePendingAuthorization(authzUpdated)
err = sa.UpdatePendingAuthorization(ctx, authzUpdated)
test.AssertNotError(t, err, "Could not store test data")
// Simulate a successful simpleHTTP challenge
authzFromVA := authzUpdated
authzFromVA.Challenges[0].Status = core.StatusValid
err = ra.OnValidationUpdate(authzFromVA)
err = ra.OnValidationUpdate(ctx, authzFromVA)
test.AssertNotError(t, err, "Could not store test data")
// Verify that the Authz in the DB is the same except for Status->StatusValid
authzFromVA.Status = core.StatusValid
dbAuthz, err := sa.GetAuthorization(authzFromVA.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authzFromVA.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
t.Log("authz from VA: ", authzFromVA)
t.Log("authz from DB: ", dbAuthz)
@ -587,18 +589,18 @@ func TestOnValidationUpdateSuccess(t *testing.T) {
func TestOnValidationUpdateFailure(t *testing.T) {
_, sa, ra, fclk, cleanUp := initAuthorities(t)
defer cleanUp()
authzFromVA, _ := sa.NewPendingAuthorization(AuthzInitial)
authzFromVA, _ := sa.NewPendingAuthorization(ctx, AuthzInitial)
expires := fclk.Now().Add(300 * 24 * time.Hour)
authzFromVA.Expires = &expires
err := sa.UpdatePendingAuthorization(authzFromVA)
err := sa.UpdatePendingAuthorization(ctx, authzFromVA)
test.AssertNotError(t, err, "Could not store test data")
authzFromVA.Challenges[0].Status = core.StatusInvalid
err = ra.OnValidationUpdate(authzFromVA)
err = ra.OnValidationUpdate(ctx, authzFromVA)
test.AssertNotError(t, err, "unable to update validation")
authzFromVA.Status = core.StatusInvalid
dbAuthz, err := sa.GetAuthorization(authzFromVA.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authzFromVA.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authzFromVA, dbAuthz)
}
@ -607,7 +609,7 @@ func TestCertificateKeyNotEqualAccountKey(t *testing.T) {
_, sa, ra, _, cleanUp := initAuthorities(t)
defer cleanUp()
authz := core.Authorization{RegistrationID: 1}
authz, err := sa.NewPendingAuthorization(authz)
authz, err := sa.NewPendingAuthorization(ctx, authz)
test.AssertNotError(t, err, "Could not store test data")
authz.Identifier = core.AcmeIdentifier{
Type: core.IdentifierDNS,
@ -622,14 +624,14 @@ func TestCertificateKeyNotEqualAccountKey(t *testing.T) {
test.AssertNotError(t, err, "Failed to sign CSR")
parsedCSR, err := x509.ParseCertificateRequest(csrBytes)
test.AssertNotError(t, err, "Failed to parse CSR")
err = sa.FinalizeAuthorization(authz)
err = sa.FinalizeAuthorization(ctx, authz)
test.AssertNotError(t, err, "Could not store test data")
certRequest := core.CertificateRequest{
CSR: parsedCSR,
}
// Registration has key == AccountKeyA
_, err = ra.NewCertificate(certRequest, Registration.ID)
_, err = ra.NewCertificate(ctx, certRequest, Registration.ID)
test.AssertError(t, err, "Should have rejected cert with key = account key")
test.AssertEquals(t, err.Error(), "Certificate public key must be different than account key")
@ -640,9 +642,9 @@ func TestAuthorizationRequired(t *testing.T) {
_, sa, ra, _, cleanUp := initAuthorities(t)
defer cleanUp()
AuthzFinal.RegistrationID = 1
AuthzFinal, err := sa.NewPendingAuthorization(AuthzFinal)
AuthzFinal, err := sa.NewPendingAuthorization(ctx, AuthzFinal)
test.AssertNotError(t, err, "Could not store test data")
err = sa.FinalizeAuthorization(AuthzFinal)
err = sa.FinalizeAuthorization(ctx, AuthzFinal)
test.AssertNotError(t, err, "Could not store test data")
// ExampleCSR requests not-example.com and www.not-example.com,
@ -651,7 +653,7 @@ func TestAuthorizationRequired(t *testing.T) {
CSR: ExampleCSR,
}
_, err = ra.NewCertificate(certRequest, 1)
_, err = ra.NewCertificate(ctx, certRequest, 1)
test.Assert(t, err != nil, "Issued certificate with insufficient authorization")
t.Log("DONE TestAuthorizationRequired")
@ -661,17 +663,17 @@ func TestNewCertificate(t *testing.T) {
_, sa, ra, _, cleanUp := initAuthorities(t)
defer cleanUp()
AuthzFinal.RegistrationID = Registration.ID
AuthzFinal, err := sa.NewPendingAuthorization(AuthzFinal)
AuthzFinal, err := sa.NewPendingAuthorization(ctx, AuthzFinal)
test.AssertNotError(t, err, "Could not store test data")
err = sa.FinalizeAuthorization(AuthzFinal)
err = sa.FinalizeAuthorization(ctx, AuthzFinal)
test.AssertNotError(t, err, "Could not store test data")
// Inject another final authorization to cover www.not-example.com
authzFinalWWW := AuthzFinal
authzFinalWWW.Identifier.Value = "www.not-example.com"
authzFinalWWW, err = sa.NewPendingAuthorization(authzFinalWWW)
authzFinalWWW, err = sa.NewPendingAuthorization(ctx, authzFinalWWW)
test.AssertNotError(t, err, "Could not store test data")
err = sa.FinalizeAuthorization(authzFinalWWW)
err = sa.FinalizeAuthorization(ctx, authzFinalWWW)
test.AssertNotError(t, err, "Could not store test data")
// Check that we fail if the CSR signature is invalid
@ -680,7 +682,7 @@ func TestNewCertificate(t *testing.T) {
CSR: ExampleCSR,
}
_, err = ra.NewCertificate(certRequest, Registration.ID)
_, err = ra.NewCertificate(ctx, certRequest, Registration.ID)
ExampleCSR.Signature[0]--
test.AssertError(t, err, "Failed to check CSR signature")
@ -690,7 +692,7 @@ func TestNewCertificate(t *testing.T) {
CSR: ExampleCSR,
}
cert, err := ra.NewCertificate(certRequest, Registration.ID)
cert, err := ra.NewCertificate(ctx, certRequest, Registration.ID)
test.AssertNotError(t, err, "Failed to issue certificate")
_, err = x509.ParseCertificate(cert.DER)
@ -710,16 +712,16 @@ func TestTotalCertRateLimit(t *testing.T) {
fc.Add(24 * 90 * time.Hour)
AuthzFinal.RegistrationID = Registration.ID
AuthzFinal, err := sa.NewPendingAuthorization(AuthzFinal)
AuthzFinal, err := sa.NewPendingAuthorization(ctx, AuthzFinal)
test.AssertNotError(t, err, "Could not store test data")
err = sa.FinalizeAuthorization(AuthzFinal)
err = sa.FinalizeAuthorization(ctx, AuthzFinal)
// Inject another final authorization to cover www.not-example.com
authzFinalWWW := AuthzFinal
authzFinalWWW.Identifier.Value = "www.not-example.com"
authzFinalWWW, err = sa.NewPendingAuthorization(authzFinalWWW)
authzFinalWWW, err = sa.NewPendingAuthorization(ctx, authzFinalWWW)
test.AssertNotError(t, err, "Could not store test data")
err = sa.FinalizeAuthorization(authzFinalWWW)
err = sa.FinalizeAuthorization(ctx, authzFinalWWW)
test.AssertNotError(t, err, "Could not store test data")
ExampleCSR.Subject.CommonName = "www.NOT-example.com"
@ -730,14 +732,14 @@ func TestTotalCertRateLimit(t *testing.T) {
// TODO(jsha): Since we're using a real SA rather than a mock, we call
// NewCertificate twice and insert the first result into the SA. Instead we
// should mock out the SA and have it return the cert count that we want.
cert, err := ra.NewCertificate(certRequest, Registration.ID)
cert, err := ra.NewCertificate(ctx, certRequest, Registration.ID)
test.AssertNotError(t, err, "Failed to issue certificate")
_, err = sa.AddCertificate(cert.DER, Registration.ID)
_, err = sa.AddCertificate(ctx, cert.DER, Registration.ID)
test.AssertNotError(t, err, "Failed to store certificate")
fc.Add(time.Hour)
_, err = ra.NewCertificate(certRequest, Registration.ID)
_, err = ra.NewCertificate(ctx, certRequest, Registration.ID)
test.AssertError(t, err, "Total certificate rate limit failed")
}
@ -754,21 +756,21 @@ func TestAuthzRateLimiting(t *testing.T) {
fc.Add(24 * 90 * time.Hour)
// Should be able to create an authzRequest
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
fc.Add(time.Hour)
// Second one should trigger rate limit
_, err = ra.NewAuthorization(AuthzRequest, Registration.ID)
_, err = ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertError(t, err, "Pending Authorization rate limit failed.")
// Finalize pending authz
err = ra.OnValidationUpdate(authz)
err = ra.OnValidationUpdate(ctx, authz)
test.AssertNotError(t, err, "Could not store test data")
// Try to create a new authzRequest, should be fine now.
_, err = ra.NewAuthorization(AuthzRequest, Registration.ID)
_, err = ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
}
@ -808,7 +810,7 @@ type mockSAWithNameCounts struct {
clk clock.FakeClock
}
func (m mockSAWithNameCounts) CountCertificatesByNames(names []string, earliest, latest time.Time) (ret map[string]int, err error) {
func (m mockSAWithNameCounts) CountCertificatesByNames(ctx context.Context, names []string, earliest, latest time.Time) (ret map[string]int, err error) {
if latest != m.clk.Now() {
m.t.Error("incorrect latest")
}
@ -842,31 +844,31 @@ func TestCheckCertificatesPerNameLimit(t *testing.T) {
ra.SA = mockSA
// One base domain, below threshold
err := ra.checkCertificatesPerNameLimit([]string{"www.example.com", "example.com"}, rlp, 99)
err := ra.checkCertificatesPerNameLimit(ctx, []string{"www.example.com", "example.com"}, rlp, 99)
test.AssertNotError(t, err, "rate limited example.com incorrectly")
// One base domain, above threshold
mockSA.nameCounts["example.com"] = 10
err = ra.checkCertificatesPerNameLimit([]string{"www.example.com", "example.com"}, rlp, 99)
err = ra.checkCertificatesPerNameLimit(ctx, []string{"www.example.com", "example.com"}, rlp, 99)
test.AssertError(t, err, "incorrectly failed to rate limit example.com")
if _, ok := err.(core.RateLimitedError); !ok {
t.Errorf("Incorrect error type %#v", err)
}
// SA misbehaved and didn't send back a count for every input name
err = ra.checkCertificatesPerNameLimit([]string{"zombo.com", "www.example.com", "example.com"}, rlp, 99)
err = ra.checkCertificatesPerNameLimit(ctx, []string{"zombo.com", "www.example.com", "example.com"}, rlp, 99)
test.AssertError(t, err, "incorrectly failed to error on misbehaving SA")
// Two base domains, one above threshold but with an override.
mockSA.nameCounts["example.com"] = 0
mockSA.nameCounts["bigissuer.com"] = 50
err = ra.checkCertificatesPerNameLimit([]string{"www.example.com", "subdomain.bigissuer.com"}, rlp, 99)
err = ra.checkCertificatesPerNameLimit(ctx, []string{"www.example.com", "subdomain.bigissuer.com"}, rlp, 99)
test.AssertNotError(t, err, "incorrectly rate limited bigissuer")
// Two base domains, one above its override
mockSA.nameCounts["example.com"] = 0
mockSA.nameCounts["bigissuer.com"] = 100
err = ra.checkCertificatesPerNameLimit([]string{"www.example.com", "subdomain.bigissuer.com"}, rlp, 99)
err = ra.checkCertificatesPerNameLimit(ctx, []string{"www.example.com", "subdomain.bigissuer.com"}, rlp, 99)
test.AssertError(t, err, "incorrectly failed to rate limit bigissuer")
if _, ok := err.(core.RateLimitedError); !ok {
t.Errorf("Incorrect error type")
@ -874,7 +876,7 @@ func TestCheckCertificatesPerNameLimit(t *testing.T) {
// One base domain, above its override (which is below threshold)
mockSA.nameCounts["smallissuer.co.uk"] = 1
err = ra.checkCertificatesPerNameLimit([]string{"www.smallissuer.co.uk"}, rlp, 99)
err = ra.checkCertificatesPerNameLimit(ctx, []string{"www.smallissuer.co.uk"}, rlp, 99)
test.AssertError(t, err, "incorrectly failed to rate limit smallissuer")
if _, ok := err.(core.RateLimitedError); !ok {
t.Errorf("Incorrect error type %#v", err)

View File

@ -5,7 +5,10 @@
package ra
import "github.com/letsencrypt/boulder/core"
import (
"github.com/letsencrypt/boulder/core"
"golang.org/x/net/context"
)
// TODO(jmhodges): remove once VA is deployed and stable with IsSafeDomain
// replace with just a call to ra.VA.IsSafeDomain
@ -19,13 +22,13 @@ type DomainCheck struct {
// IsSafe returns true if the VA's IsSafeDomain RPC says the domain is safe or
// if DomainCheck is nil.
func (d *DomainCheck) IsSafe(domain string) (bool, error) {
func (d *DomainCheck) IsSafe(ctx context.Context, domain string) (bool, error) {
// This nil check allows us to not actually call
if d == nil {
return true, nil
}
resp, err := d.VA.IsSafeDomain(&core.IsSafeDomainRequest{Domain: domain})
resp, err := d.VA.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: domain})
if err != nil {
return false, err
}

View File

@ -19,7 +19,7 @@ func TestChecksVASafeDomain(t *testing.T) {
va.IsNotSafe = true
_, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
_, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
if err == nil {
t.Errorf("want UnauthorizedError, got nil")
} else if _, ok := err.(core.UnauthorizedError); !ok {
@ -32,7 +32,7 @@ func TestHandlesVASafeDomainError(t *testing.T) {
defer cleanUp()
va.IsSafeDomainErr = errors.New("welp")
_, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
_, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
if err == nil {
t.Errorf("want InternalServerError, got nil")
} else if _, ok := err.(core.InternalServerError); !ok {
@ -45,10 +45,10 @@ func TestAllowsNullSafeDomainCheck(t *testing.T) {
defer cleanUp()
ra.dc = nil
authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID)
authz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
test.AssertNotError(t, err, "NewAuthorization failed")
dbAuthz, err := sa.GetAuthorization(authz.ID)
dbAuthz, err := sa.GetAuthorization(ctx, authz.ID)
test.AssertNotError(t, err, "Could not fetch authorization from database")
assertAuthzEqual(t, authz, dbAuthz)
}

View File

@ -22,6 +22,8 @@ import (
"syscall"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/probs"
@ -103,7 +105,7 @@ func amqpSubscribe(ch amqpChannel, name, routingKey string) (<-chan amqp.Deliver
// DeliveryHandler is a function that will process an amqp.DeliveryHandler
type DeliveryHandler func(amqp.Delivery)
type messageHandler func([]byte) ([]byte, error)
type messageHandler func(context.Context, []byte) ([]byte, error)
// AmqpRPCServer listens on a specified queue within an AMQP channel.
// When messages arrive on that queue, it dispatches them based on type,
@ -343,6 +345,8 @@ func makeAmqpChannel(conf *cmd.AMQPConfig) (*amqp.Channel, error) {
}
func (rpc *AmqpRPCServer) processMessage(msg amqp.Delivery) {
ctx := context.TODO()
// XXX-JWS: jws.Verify(body)
cb, present := rpc.dispatchTable[msg.Type]
rpc.log.Debug(fmt.Sprintf(" [s<][%s][%s] received %s(%s) [%s]", rpc.serverQueue, msg.ReplyTo, msg.Type, safeDER(msg.Body), msg.CorrelationId))
@ -353,7 +357,7 @@ func (rpc *AmqpRPCServer) processMessage(msg amqp.Delivery) {
}
var response rpcResponse
var err error
response.ReturnVal, err = cb(msg.Body)
response.ReturnVal, err = cb(ctx, msg.Body)
response.Error = wrapError(err)
jsonResponse, err := json.Marshal(response)
if err != nil {

View File

@ -13,6 +13,8 @@ import (
"net"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/letsencrypt/boulder/cmd"
"github.com/letsencrypt/boulder/core"
@ -234,7 +236,7 @@ func errorCondition(method string, err error, obj interface{}) {
func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority) error {
log := blog.Get()
rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodNewRegistration, func(ctx context.Context, req []byte) (response []byte, err error) {
var rr registrationRequest
if err = json.Unmarshal(req, &rr); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -242,7 +244,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
reg, err := impl.NewRegistration(rr.Reg)
reg, err := impl.NewRegistration(ctx, rr.Reg)
if err != nil {
return
}
@ -256,7 +258,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
})
rpc.Handle(MethodNewAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodNewAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var ar authorizationRequest
if err = json.Unmarshal(req, &ar); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -264,7 +266,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
authz, err := impl.NewAuthorization(ar.Authz, ar.RegID)
authz, err := impl.NewAuthorization(ctx, ar.Authz, ar.RegID)
if err != nil {
return
}
@ -278,7 +280,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
})
rpc.Handle(MethodNewCertificate, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodNewCertificate, func(ctx context.Context, req []byte) (response []byte, err error) {
log.Info(fmt.Sprintf(" [.] Entering MethodNewCertificate"))
var cr certificateRequest
if err = json.Unmarshal(req, &cr); err != nil {
@ -288,7 +290,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
}
log.Info(fmt.Sprintf(" [.] No problem unmarshaling request"))
cert, err := impl.NewCertificate(cr.Req, cr.RegID)
cert, err := impl.NewCertificate(ctx, cr.Req, cr.RegID)
if err != nil {
return
}
@ -303,7 +305,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
})
rpc.Handle(MethodUpdateRegistration, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdateRegistration, func(ctx context.Context, req []byte) (response []byte, err error) {
var urReq updateRegistrationRequest
err = json.Unmarshal(req, &urReq)
if err != nil {
@ -312,7 +314,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
reg, err := impl.UpdateRegistration(urReq.Base, urReq.Update)
reg, err := impl.UpdateRegistration(ctx, urReq.Base, urReq.Update)
if err != nil {
return
}
@ -326,7 +328,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
})
rpc.Handle(MethodUpdateAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdateAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var uaReq updateAuthorizationRequest
err = json.Unmarshal(req, &uaReq)
if err != nil {
@ -335,7 +337,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
newAuthz, err := impl.UpdateAuthorization(uaReq.Authz, uaReq.Index, uaReq.Response)
newAuthz, err := impl.UpdateAuthorization(ctx, uaReq.Authz, uaReq.Index, uaReq.Response)
if err != nil {
return
}
@ -349,7 +351,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
})
rpc.Handle(MethodRevokeCertificateWithReg, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodRevokeCertificateWithReg, func(ctx context.Context, req []byte) (response []byte, err error) {
var revReq struct {
Cert []byte
Reason core.RevocationCode
@ -366,11 +368,11 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
err = impl.RevokeCertificateWithReg(*cert, revReq.Reason, revReq.RegID)
err = impl.RevokeCertificateWithReg(ctx, *cert, revReq.Reason, revReq.RegID)
return
})
rpc.Handle(MethodAdministrativelyRevokeCertificate, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodAdministrativelyRevokeCertificate, func(ctx context.Context, req []byte) (response []byte, err error) {
var revReq struct {
Cert []byte
Reason core.RevocationCode
@ -387,11 +389,11 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
err = impl.AdministrativelyRevokeCertificate(*cert, revReq.Reason, revReq.User)
err = impl.AdministrativelyRevokeCertificate(ctx, *cert, revReq.Reason, revReq.User)
return
})
rpc.Handle(MethodOnValidationUpdate, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodOnValidationUpdate, func(ctx context.Context, req []byte) (response []byte, err error) {
var authz core.Authorization
if err = json.Unmarshal(req, &authz); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -399,7 +401,7 @@ func NewRegistrationAuthorityServer(rpc Server, impl core.RegistrationAuthority)
return
}
err = impl.OnValidationUpdate(authz)
err = impl.OnValidationUpdate(ctx, authz)
return
})
@ -418,7 +420,7 @@ func NewRegistrationAuthorityClient(clientName string, amqpConf *cmd.AMQPConfig,
}
// NewRegistration sends a New Registration request
func (rac RegistrationAuthorityClient) NewRegistration(reg core.Registration) (newReg core.Registration, err error) {
func (rac RegistrationAuthorityClient) NewRegistration(ctx context.Context, reg core.Registration) (newReg core.Registration, err error) {
data, err := json.Marshal(registrationRequest{reg})
if err != nil {
return
@ -434,7 +436,7 @@ func (rac RegistrationAuthorityClient) NewRegistration(reg core.Registration) (n
}
// NewAuthorization sends a New Authorization request
func (rac RegistrationAuthorityClient) NewAuthorization(authz core.Authorization, regID int64) (newAuthz core.Authorization, err error) {
func (rac RegistrationAuthorityClient) NewAuthorization(ctx context.Context, authz core.Authorization, regID int64) (newAuthz core.Authorization, err error) {
data, err := json.Marshal(authorizationRequest{authz, regID})
if err != nil {
return
@ -450,7 +452,7 @@ func (rac RegistrationAuthorityClient) NewAuthorization(authz core.Authorization
}
// NewCertificate sends a New Certificate request
func (rac RegistrationAuthorityClient) NewCertificate(cr core.CertificateRequest, regID int64) (cert core.Certificate, err error) {
func (rac RegistrationAuthorityClient) NewCertificate(ctx context.Context, cr core.CertificateRequest, regID int64) (cert core.Certificate, err error) {
data, err := json.Marshal(certificateRequest{cr, regID})
if err != nil {
return
@ -466,7 +468,7 @@ func (rac RegistrationAuthorityClient) NewCertificate(cr core.CertificateRequest
}
// UpdateRegistration sends an Update Registration request
func (rac RegistrationAuthorityClient) UpdateRegistration(base core.Registration, update core.Registration) (newReg core.Registration, err error) {
func (rac RegistrationAuthorityClient) UpdateRegistration(ctx context.Context, base core.Registration, update core.Registration) (newReg core.Registration, err error) {
var urReq updateRegistrationRequest
urReq.Base = base
urReq.Update = update
@ -486,7 +488,7 @@ func (rac RegistrationAuthorityClient) UpdateRegistration(base core.Registration
}
// UpdateAuthorization sends an Update Authorization request
func (rac RegistrationAuthorityClient) UpdateAuthorization(authz core.Authorization, index int, response core.Challenge) (newAuthz core.Authorization, err error) {
func (rac RegistrationAuthorityClient) UpdateAuthorization(ctx context.Context, authz core.Authorization, index int, response core.Challenge) (newAuthz core.Authorization, err error) {
var uaReq updateAuthorizationRequest
uaReq.Authz = authz
uaReq.Index = index
@ -508,7 +510,7 @@ func (rac RegistrationAuthorityClient) UpdateAuthorization(authz core.Authorizat
// RevokeCertificateWithReg sends a Revoke Certificate request initiated by the
// WFE
func (rac RegistrationAuthorityClient) RevokeCertificateWithReg(cert x509.Certificate, reason core.RevocationCode, regID int64) (err error) {
func (rac RegistrationAuthorityClient) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, regID int64) (err error) {
var revReq struct {
Cert []byte
Reason core.RevocationCode
@ -527,7 +529,7 @@ func (rac RegistrationAuthorityClient) RevokeCertificateWithReg(cert x509.Certif
// AdministrativelyRevokeCertificate sends a Revoke Certificate request initiated by the
// admin-revoker
func (rac RegistrationAuthorityClient) AdministrativelyRevokeCertificate(cert x509.Certificate, reason core.RevocationCode, user string) (err error) {
func (rac RegistrationAuthorityClient) AdministrativelyRevokeCertificate(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, user string) (err error) {
var revReq struct {
Cert []byte
Reason core.RevocationCode
@ -545,7 +547,7 @@ func (rac RegistrationAuthorityClient) AdministrativelyRevokeCertificate(cert x5
}
// OnValidationUpdate senda a notice that a validation has updated
func (rac RegistrationAuthorityClient) OnValidationUpdate(authz core.Authorization) (err error) {
func (rac RegistrationAuthorityClient) OnValidationUpdate(ctx context.Context, authz core.Authorization) (err error) {
data, err := json.Marshal(authz)
if err != nil {
return
@ -560,7 +562,7 @@ func (rac RegistrationAuthorityClient) OnValidationUpdate(authz core.Authorizati
// ValidationAuthorityClient / Server
// -> UpdateValidations
func NewValidationAuthorityServer(rpc Server, impl core.ValidationAuthority) (err error) {
rpc.Handle(MethodUpdateValidations, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdateValidations, func(ctx context.Context, req []byte) (response []byte, err error) {
var vaReq validationRequest
if err = json.Unmarshal(req, &vaReq); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -568,10 +570,10 @@ func NewValidationAuthorityServer(rpc Server, impl core.ValidationAuthority) (er
return
}
return nil, impl.UpdateValidations(vaReq.Authz, vaReq.Index)
return nil, impl.UpdateValidations(ctx, vaReq.Authz, vaReq.Index)
})
rpc.Handle(MethodPerformValidation, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodPerformValidation, func(ctx context.Context, req []byte) (response []byte, err error) {
var vaReq performValidationRequest
if err = json.Unmarshal(req, &vaReq); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -579,7 +581,7 @@ func NewValidationAuthorityServer(rpc Server, impl core.ValidationAuthority) (er
return nil, err
}
records, err := impl.PerformValidation(vaReq.Domain, vaReq.Challenge, vaReq.Authz)
records, err := impl.PerformValidation(ctx, vaReq.Domain, vaReq.Challenge, vaReq.Authz)
// If the type of error was a ProblemDetails, we need to return
// both that and the records to the caller (so it can update
// the challenge / authz in the SA with the failing records).
@ -593,14 +595,14 @@ func NewValidationAuthorityServer(rpc Server, impl core.ValidationAuthority) (er
return json.Marshal(performValidationResponse{records, probs})
})
rpc.Handle(MethodIsSafeDomain, func(req []byte) ([]byte, error) {
rpc.Handle(MethodIsSafeDomain, func(ctx context.Context, req []byte) ([]byte, error) {
r := &core.IsSafeDomainRequest{}
if err := json.Unmarshal(req, r); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
improperMessage(MethodIsSafeDomain, err, req)
return nil, err
}
resp, err := impl.IsSafeDomain(r)
resp, err := impl.IsSafeDomain(ctx, r)
if err != nil {
return nil, err
}
@ -622,7 +624,7 @@ func NewValidationAuthorityClient(clientName string, amqpConf *cmd.AMQPConfig, s
}
// UpdateValidations sends an Update Validations request
func (vac ValidationAuthorityClient) UpdateValidations(authz core.Authorization, index int) error {
func (vac ValidationAuthorityClient) UpdateValidations(ctx context.Context, authz core.Authorization, index int) error {
vaReq := validationRequest{
Authz: authz,
Index: index,
@ -638,7 +640,7 @@ func (vac ValidationAuthorityClient) UpdateValidations(authz core.Authorization,
// PerformValidation has the VA revalidate the specified challenge and returns
// the updated Challenge object.
func (vac ValidationAuthorityClient) PerformValidation(domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
func (vac ValidationAuthorityClient) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
vaReq := performValidationRequest{
Domain: domain,
Challenge: challenge,
@ -662,7 +664,7 @@ func (vac ValidationAuthorityClient) PerformValidation(domain string, challenge
// IsSafeDomain returns true if the domain given is determined to be safe by an
// third-party safe browsing API.
func (vac ValidationAuthorityClient) IsSafeDomain(req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
func (vac ValidationAuthorityClient) IsSafeDomain(ctx context.Context, req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
data, err := json.Marshal(req)
if err != nil {
return nil, err
@ -681,8 +683,8 @@ func (vac ValidationAuthorityClient) IsSafeDomain(req *core.IsSafeDomainRequest)
// NewPublisherServer creates a new server that wraps a CT publisher
func NewPublisherServer(rpc Server, impl core.Publisher) (err error) {
rpc.Handle(MethodSubmitToCT, func(req []byte) (response []byte, err error) {
err = impl.SubmitToCT(req)
rpc.Handle(MethodSubmitToCT, func(ctx context.Context, req []byte) (response []byte, err error) {
err = impl.SubmitToCT(ctx, req)
return
})
@ -701,7 +703,7 @@ func NewPublisherClient(clientName string, amqpConf *cmd.AMQPConfig, stats stats
}
// SubmitToCT sends a request to submit a certifcate to CT logs
func (pub PublisherClient) SubmitToCT(der []byte) (err error) {
func (pub PublisherClient) SubmitToCT(ctx context.Context, der []byte) (err error) {
_, err = pub.rpc.DispatchSync(MethodSubmitToCT, der)
return
}
@ -711,7 +713,7 @@ func (pub PublisherClient) SubmitToCT(der []byte) (err error) {
// CertificateAuthorityClient / Server
// -> IssueCertificate
func NewCertificateAuthorityServer(rpc Server, impl core.CertificateAuthority) (err error) {
rpc.Handle(MethodIssueCertificate, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodIssueCertificate, func(ctx context.Context, req []byte) (response []byte, err error) {
var icReq issueCertificateRequest
err = json.Unmarshal(req, &icReq)
if err != nil {
@ -727,7 +729,7 @@ func NewCertificateAuthorityServer(rpc Server, impl core.CertificateAuthority) (
return
}
cert, err := impl.IssueCertificate(*csr, icReq.RegID)
cert, err := impl.IssueCertificate(ctx, *csr, icReq.RegID)
if err != nil {
return
}
@ -742,7 +744,7 @@ func NewCertificateAuthorityServer(rpc Server, impl core.CertificateAuthority) (
return
})
rpc.Handle(MethodGenerateOCSP, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGenerateOCSP, func(ctx context.Context, req []byte) (response []byte, err error) {
var xferObj core.OCSPSigningRequest
err = json.Unmarshal(req, &xferObj)
if err != nil {
@ -751,7 +753,7 @@ func NewCertificateAuthorityServer(rpc Server, impl core.CertificateAuthority) (
return
}
response, err = impl.GenerateOCSP(xferObj)
response, err = impl.GenerateOCSP(ctx, xferObj)
if err != nil {
return
}
@ -774,7 +776,7 @@ func NewCertificateAuthorityClient(clientName string, amqpConf *cmd.AMQPConfig,
}
// IssueCertificate sends a request to issue a certificate
func (cac CertificateAuthorityClient) IssueCertificate(csr x509.CertificateRequest, regID int64) (cert core.Certificate, err error) {
func (cac CertificateAuthorityClient) IssueCertificate(ctx context.Context, csr x509.CertificateRequest, regID int64) (cert core.Certificate, err error) {
var icReq issueCertificateRequest
icReq.Bytes = csr.Raw
icReq.RegID = regID
@ -793,7 +795,7 @@ func (cac CertificateAuthorityClient) IssueCertificate(csr x509.CertificateReque
}
// GenerateOCSP sends a request to generate an OCSP response
func (cac CertificateAuthorityClient) GenerateOCSP(signRequest core.OCSPSigningRequest) (resp []byte, err error) {
func (cac CertificateAuthorityClient) GenerateOCSP(ctx context.Context, signRequest core.OCSPSigningRequest) (resp []byte, err error) {
data, err := json.Marshal(signRequest)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
@ -814,7 +816,7 @@ func (cac CertificateAuthorityClient) GenerateOCSP(signRequest core.OCSPSigningR
// NewStorageAuthorityServer constructs an RPC server
func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
rpc.Handle(MethodUpdateRegistration, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdateRegistration, func(ctx context.Context, req []byte) (response []byte, err error) {
var reg core.Registration
if err = json.Unmarshal(req, &reg); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -822,11 +824,11 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
err = impl.UpdateRegistration(reg)
err = impl.UpdateRegistration(ctx, reg)
return
})
rpc.Handle(MethodGetRegistration, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGetRegistration, func(ctx context.Context, req []byte) (response []byte, err error) {
var grReq getRegistrationRequest
err = json.Unmarshal(req, &grReq)
if err != nil {
@ -835,7 +837,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
reg, err := impl.GetRegistration(grReq.ID)
reg, err := impl.GetRegistration(ctx, grReq.ID)
if err != nil {
return
}
@ -849,7 +851,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodGetRegistrationByKey, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGetRegistrationByKey, func(ctx context.Context, req []byte) (response []byte, err error) {
var jwk jose.JsonWebKey
if err = json.Unmarshal(req, &jwk); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -857,7 +859,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
reg, err := impl.GetRegistrationByKey(jwk)
reg, err := impl.GetRegistrationByKey(ctx, jwk)
if err != nil {
return
}
@ -871,8 +873,8 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodGetAuthorization, func(req []byte) (response []byte, err error) {
authz, err := impl.GetAuthorization(string(req))
rpc.Handle(MethodGetAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
authz, err := impl.GetAuthorization(ctx, string(req))
if err != nil {
return
}
@ -886,7 +888,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodGetLatestValidAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGetLatestValidAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var lvar latestValidAuthorizationRequest
if err = json.Unmarshal(req, &lvar); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -894,7 +896,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
authz, err := impl.GetLatestValidAuthorization(lvar.RegID, lvar.Identifier)
authz, err := impl.GetLatestValidAuthorization(ctx, lvar.RegID, lvar.Identifier)
if err != nil {
return
}
@ -908,7 +910,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodGetValidAuthorizations, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGetValidAuthorizations, func(ctx context.Context, req []byte) (response []byte, err error) {
var mreq getValidAuthorizationsRequest
if err = json.Unmarshal(req, &mreq); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -916,7 +918,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
auths, err := impl.GetValidAuthorizations(mreq.RegID, mreq.Names, mreq.Now)
auths, err := impl.GetValidAuthorizations(ctx, mreq.RegID, mreq.Names, mreq.Now)
if err != nil {
return
}
@ -930,7 +932,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodAddCertificate, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodAddCertificate, func(ctx context.Context, req []byte) (response []byte, err error) {
var acReq addCertificateRequest
err = json.Unmarshal(req, &acReq)
if err != nil {
@ -939,7 +941,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
id, err := impl.AddCertificate(acReq.Bytes, acReq.RegID)
id, err := impl.AddCertificate(ctx, acReq.Bytes, acReq.RegID)
if err != nil {
return
}
@ -947,7 +949,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodNewRegistration, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodNewRegistration, func(ctx context.Context, req []byte) (response []byte, err error) {
var registration core.Registration
err = json.Unmarshal(req, &registration)
if err != nil {
@ -956,7 +958,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
output, err := impl.NewRegistration(registration)
output, err := impl.NewRegistration(ctx, registration)
if err != nil {
return
}
@ -970,7 +972,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodNewPendingAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodNewPendingAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var authz core.Authorization
if err = json.Unmarshal(req, &authz); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -978,7 +980,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
output, err := impl.NewPendingAuthorization(authz)
output, err := impl.NewPendingAuthorization(ctx, authz)
if err != nil {
return
}
@ -992,7 +994,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodUpdatePendingAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdatePendingAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var authz core.Authorization
if err = json.Unmarshal(req, &authz); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -1000,11 +1002,11 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
err = impl.UpdatePendingAuthorization(authz)
err = impl.UpdatePendingAuthorization(ctx, authz)
return
})
rpc.Handle(MethodFinalizeAuthorization, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodFinalizeAuthorization, func(ctx context.Context, req []byte) (response []byte, err error) {
var authz core.Authorization
if err = json.Unmarshal(req, &authz); err != nil {
// AUDIT[ Improper Messages ] 0786b6f2-91ca-4f48-9883-842a19084c64
@ -1012,17 +1014,17 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
err = impl.FinalizeAuthorization(authz)
err = impl.FinalizeAuthorization(ctx, authz)
return
})
rpc.Handle(MethodRevokeAuthorizationsByDomain, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodRevokeAuthorizationsByDomain, func(ctx context.Context, req []byte) (response []byte, err error) {
var reqObj revokeAuthsRequest
err = json.Unmarshal(req, &reqObj)
if err != nil {
return
}
aRevoked, paRevoked, err := impl.RevokeAuthorizationsByDomain(reqObj.Ident)
aRevoked, paRevoked, err := impl.RevokeAuthorizationsByDomain(ctx, reqObj.Ident)
if err != nil {
return
}
@ -1031,8 +1033,8 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodGetCertificate, func(req []byte) (response []byte, err error) {
cert, err := impl.GetCertificate(string(req))
rpc.Handle(MethodGetCertificate, func(ctx context.Context, req []byte) (response []byte, err error) {
cert, err := impl.GetCertificate(ctx, string(req))
if err != nil {
return
}
@ -1047,8 +1049,8 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return jsonResponse, nil
})
rpc.Handle(MethodGetCertificateStatus, func(req []byte) (response []byte, err error) {
status, err := impl.GetCertificateStatus(string(req))
rpc.Handle(MethodGetCertificateStatus, func(ctx context.Context, req []byte) (response []byte, err error) {
status, err := impl.GetCertificateStatus(ctx, string(req))
if err != nil {
return
}
@ -1062,7 +1064,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodMarkCertificateRevoked, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodMarkCertificateRevoked, func(ctx context.Context, req []byte) (response []byte, err error) {
var mcrReq markCertificateRevokedRequest
if err = json.Unmarshal(req, &mcrReq); err != nil {
@ -1071,11 +1073,11 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
err = impl.MarkCertificateRevoked(mcrReq.Serial, mcrReq.ReasonCode)
err = impl.MarkCertificateRevoked(ctx, mcrReq.Serial, mcrReq.ReasonCode)
return
})
rpc.Handle(MethodUpdateOCSP, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodUpdateOCSP, func(ctx context.Context, req []byte) (response []byte, err error) {
var updateOCSPReq updateOCSPRequest
if err = json.Unmarshal(req, &updateOCSPReq); err != nil {
@ -1084,11 +1086,11 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
err = impl.UpdateOCSP(updateOCSPReq.Serial, updateOCSPReq.OCSPResponse)
err = impl.UpdateOCSP(ctx, updateOCSPReq.Serial, updateOCSPReq.OCSPResponse)
return
})
rpc.Handle(MethodAlreadyDeniedCSR, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodAlreadyDeniedCSR, func(ctx context.Context, req []byte) (response []byte, err error) {
var adcReq alreadyDeniedCSRReq
err = json.Unmarshal(req, &adcReq)
@ -1098,7 +1100,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
exists, err := impl.AlreadyDeniedCSR(adcReq.Names)
exists, err := impl.AlreadyDeniedCSR(ctx, adcReq.Names)
if err != nil {
return
}
@ -1111,63 +1113,63 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodCountCertificatesRange, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodCountCertificatesRange, func(ctx context.Context, req []byte) (response []byte, err error) {
var cReq countRequest
err = json.Unmarshal(req, &cReq)
if err != nil {
return
}
count, err := impl.CountCertificatesRange(cReq.Start, cReq.End)
count, err := impl.CountCertificatesRange(ctx, cReq.Start, cReq.End)
if err != nil {
return
}
return json.Marshal(count)
})
rpc.Handle(MethodCountCertificatesByNames, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodCountCertificatesByNames, func(ctx context.Context, req []byte) (response []byte, err error) {
var cReq countCertificatesByNamesRequest
err = json.Unmarshal(req, &cReq)
if err != nil {
return
}
counts, err := impl.CountCertificatesByNames(cReq.Names, cReq.Earliest, cReq.Latest)
counts, err := impl.CountCertificatesByNames(ctx, cReq.Names, cReq.Earliest, cReq.Latest)
if err != nil {
return
}
return json.Marshal(counts)
})
rpc.Handle(MethodCountRegistrationsByIP, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodCountRegistrationsByIP, func(ctx context.Context, req []byte) (response []byte, err error) {
var cReq countRegistrationsByIPRequest
err = json.Unmarshal(req, &cReq)
if err != nil {
return
}
count, err := impl.CountRegistrationsByIP(cReq.IP, cReq.Earliest, cReq.Latest)
count, err := impl.CountRegistrationsByIP(ctx, cReq.IP, cReq.Earliest, cReq.Latest)
if err != nil {
return
}
return json.Marshal(count)
})
rpc.Handle(MethodCountPendingAuthorizations, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodCountPendingAuthorizations, func(ctx context.Context, req []byte) (response []byte, err error) {
var cReq countPendingAuthorizationsRequest
err = json.Unmarshal(req, &cReq)
if err != nil {
return
}
count, err := impl.CountPendingAuthorizations(cReq.RegID)
count, err := impl.CountPendingAuthorizations(ctx, cReq.RegID)
if err != nil {
return
}
return json.Marshal(count)
})
rpc.Handle(MethodGetSCTReceipt, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodGetSCTReceipt, func(ctx context.Context, req []byte) (response []byte, err error) {
var gsctReq struct {
Serial string
LogID string
@ -1180,7 +1182,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
sct, err := impl.GetSCTReceipt(gsctReq.Serial, gsctReq.LogID)
sct, err := impl.GetSCTReceipt(ctx, gsctReq.Serial, gsctReq.LogID)
jsonResponse, err := json.Marshal(sct)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
@ -1191,7 +1193,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return jsonResponse, nil
})
rpc.Handle(MethodAddSCTReceipt, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodAddSCTReceipt, func(ctx context.Context, req []byte) (response []byte, err error) {
var sct core.SignedCertificateTimestamp
err = json.Unmarshal(req, &sct)
if err != nil {
@ -1200,10 +1202,10 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
}
return nil, impl.AddSCTReceipt(core.SignedCertificateTimestamp(sct))
return nil, impl.AddSCTReceipt(ctx, core.SignedCertificateTimestamp(sct))
})
rpc.Handle(MethodCountFQDNSets, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodCountFQDNSets, func(ctx context.Context, req []byte) (response []byte, err error) {
var r countFQDNsRequest
err = json.Unmarshal(req, &r)
if err != nil {
@ -1211,7 +1213,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
errorCondition(MethodCountFQDNSets, err, req)
return
}
count, err := impl.CountFQDNSets(r.Window, r.Names)
count, err := impl.CountFQDNSets(ctx, r.Window, r.Names)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
errorCondition(MethodCountFQDNSets, err, req)
@ -1228,7 +1230,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
return
})
rpc.Handle(MethodFQDNSetExists, func(req []byte) (response []byte, err error) {
rpc.Handle(MethodFQDNSetExists, func(ctx context.Context, req []byte) (response []byte, err error) {
var r fqdnSetExistsRequest
err = json.Unmarshal(req, &r)
if err != nil {
@ -1236,7 +1238,7 @@ func NewStorageAuthorityServer(rpc Server, impl core.StorageAuthority) error {
errorCondition(MethodFQDNSetExists, err, req)
return
}
exists, err := impl.FQDNSetExists(r.Names)
exists, err := impl.FQDNSetExists(ctx, r.Names)
if err != nil {
// AUDIT[ Error Conditions ] 9cc4d537-8534-4970-8665-4b382abe82f3
errorCondition(MethodFQDNSetExists, err, req)
@ -1267,7 +1269,7 @@ func NewStorageAuthorityClient(clientName string, amqpConf *cmd.AMQPConfig, stat
}
// GetRegistration sends a request to get a registration by ID
func (cac StorageAuthorityClient) GetRegistration(id int64) (reg core.Registration, err error) {
func (cac StorageAuthorityClient) GetRegistration(ctx context.Context, id int64) (reg core.Registration, err error) {
var grReq getRegistrationRequest
grReq.ID = id
@ -1286,7 +1288,7 @@ func (cac StorageAuthorityClient) GetRegistration(id int64) (reg core.Registrati
}
// GetRegistrationByKey sends a request to get a registration by JWK
func (cac StorageAuthorityClient) GetRegistrationByKey(key jose.JsonWebKey) (reg core.Registration, err error) {
func (cac StorageAuthorityClient) GetRegistrationByKey(ctx context.Context, key jose.JsonWebKey) (reg core.Registration, err error) {
jsonKey, err := key.MarshalJSON()
if err != nil {
return
@ -1302,7 +1304,7 @@ func (cac StorageAuthorityClient) GetRegistrationByKey(key jose.JsonWebKey) (reg
}
// GetAuthorization sends a request to get an Authorization by ID
func (cac StorageAuthorityClient) GetAuthorization(id string) (authz core.Authorization, err error) {
func (cac StorageAuthorityClient) GetAuthorization(ctx context.Context, id string) (authz core.Authorization, err error) {
jsonAuthz, err := cac.rpc.DispatchSync(MethodGetAuthorization, []byte(id))
if err != nil {
return
@ -1313,7 +1315,7 @@ func (cac StorageAuthorityClient) GetAuthorization(id string) (authz core.Author
}
// GetLatestValidAuthorization sends a request to get an Authorization by RegID, Identifier
func (cac StorageAuthorityClient) GetLatestValidAuthorization(registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
func (cac StorageAuthorityClient) GetLatestValidAuthorization(ctx context.Context, registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
var lvar latestValidAuthorizationRequest
lvar.RegID = registrationID
@ -1336,7 +1338,7 @@ func (cac StorageAuthorityClient) GetLatestValidAuthorization(registrationID int
// GetValidAuthorizations sends a request to get a batch of Authorizations by
// RegID and dnsName. The current time is also included in the request to
// assist filtering.
func (cac StorageAuthorityClient) GetValidAuthorizations(registrationID int64, names []string, now time.Time) (auths map[string]*core.Authorization, err error) {
func (cac StorageAuthorityClient) GetValidAuthorizations(ctx context.Context, registrationID int64, names []string, now time.Time) (auths map[string]*core.Authorization, err error) {
data, err := json.Marshal(getValidAuthorizationsRequest{
RegID: registrationID,
Names: names,
@ -1356,7 +1358,7 @@ func (cac StorageAuthorityClient) GetValidAuthorizations(registrationID int64, n
}
// GetCertificate sends a request to get a Certificate by ID
func (cac StorageAuthorityClient) GetCertificate(id string) (cert core.Certificate, err error) {
func (cac StorageAuthorityClient) GetCertificate(ctx context.Context, id string) (cert core.Certificate, err error) {
jsonCert, err := cac.rpc.DispatchSync(MethodGetCertificate, []byte(id))
if err != nil {
return
@ -1368,7 +1370,7 @@ func (cac StorageAuthorityClient) GetCertificate(id string) (cert core.Certifica
// GetCertificateStatus sends a request to obtain the current status of a
// certificate by ID
func (cac StorageAuthorityClient) GetCertificateStatus(id string) (status core.CertificateStatus, err error) {
func (cac StorageAuthorityClient) GetCertificateStatus(ctx context.Context, id string) (status core.CertificateStatus, err error) {
jsonStatus, err := cac.rpc.DispatchSync(MethodGetCertificateStatus, []byte(id))
if err != nil {
return
@ -1379,7 +1381,7 @@ func (cac StorageAuthorityClient) GetCertificateStatus(id string) (status core.C
}
// MarkCertificateRevoked sends a request to mark a certificate as revoked
func (cac StorageAuthorityClient) MarkCertificateRevoked(serial string, reasonCode core.RevocationCode) (err error) {
func (cac StorageAuthorityClient) MarkCertificateRevoked(ctx context.Context, serial string, reasonCode core.RevocationCode) (err error) {
var mcrReq markCertificateRevokedRequest
mcrReq.Serial = serial
@ -1395,7 +1397,7 @@ func (cac StorageAuthorityClient) MarkCertificateRevoked(serial string, reasonCo
}
// UpdateOCSP sends a request to store an updated OCSP response
func (cac StorageAuthorityClient) UpdateOCSP(serial string, ocspResponse []byte) (err error) {
func (cac StorageAuthorityClient) UpdateOCSP(ctx context.Context, serial string, ocspResponse []byte) (err error) {
var updateOCSPReq updateOCSPRequest
updateOCSPReq.Serial = serial
@ -1411,7 +1413,7 @@ func (cac StorageAuthorityClient) UpdateOCSP(serial string, ocspResponse []byte)
}
// UpdateRegistration sends a request to store an updated registration
func (cac StorageAuthorityClient) UpdateRegistration(reg core.Registration) (err error) {
func (cac StorageAuthorityClient) UpdateRegistration(ctx context.Context, reg core.Registration) (err error) {
jsonReg, err := json.Marshal(reg)
if err != nil {
return
@ -1422,7 +1424,7 @@ func (cac StorageAuthorityClient) UpdateRegistration(reg core.Registration) (err
}
// NewRegistration sends a request to store a new registration
func (cac StorageAuthorityClient) NewRegistration(reg core.Registration) (output core.Registration, err error) {
func (cac StorageAuthorityClient) NewRegistration(ctx context.Context, reg core.Registration) (output core.Registration, err error) {
jsonReg, err := json.Marshal(reg)
if err != nil {
err = errors.New("NewRegistration RPC failed")
@ -1441,7 +1443,7 @@ func (cac StorageAuthorityClient) NewRegistration(reg core.Registration) (output
}
// NewPendingAuthorization sends a request to store a pending authorization
func (cac StorageAuthorityClient) NewPendingAuthorization(authz core.Authorization) (output core.Authorization, err error) {
func (cac StorageAuthorityClient) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (output core.Authorization, err error) {
jsonAuthz, err := json.Marshal(authz)
if err != nil {
return
@ -1460,7 +1462,7 @@ func (cac StorageAuthorityClient) NewPendingAuthorization(authz core.Authorizati
// UpdatePendingAuthorization sends a request to update the data in a pending
// authorization
func (cac StorageAuthorityClient) UpdatePendingAuthorization(authz core.Authorization) (err error) {
func (cac StorageAuthorityClient) UpdatePendingAuthorization(ctx context.Context, authz core.Authorization) (err error) {
jsonAuthz, err := json.Marshal(authz)
if err != nil {
return
@ -1472,7 +1474,7 @@ func (cac StorageAuthorityClient) UpdatePendingAuthorization(authz core.Authoriz
// FinalizeAuthorization sends a request to finalize an authorization (convert
// from pending)
func (cac StorageAuthorityClient) FinalizeAuthorization(authz core.Authorization) (err error) {
func (cac StorageAuthorityClient) FinalizeAuthorization(ctx context.Context, authz core.Authorization) (err error) {
jsonAuthz, err := json.Marshal(authz)
if err != nil {
return
@ -1484,7 +1486,7 @@ func (cac StorageAuthorityClient) FinalizeAuthorization(authz core.Authorization
// RevokeAuthorizationsByDomain sends a request to revoke all pending or finalized authorizations
// for a single domain
func (cac StorageAuthorityClient) RevokeAuthorizationsByDomain(ident core.AcmeIdentifier) (aRevoked int64, paRevoked int64, err error) {
func (cac StorageAuthorityClient) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (aRevoked int64, paRevoked int64, err error) {
data, err := json.Marshal(revokeAuthsRequest{Ident: ident})
if err != nil {
return
@ -1504,7 +1506,7 @@ func (cac StorageAuthorityClient) RevokeAuthorizationsByDomain(ident core.AcmeId
}
// AddCertificate sends a request to record the issuance of a certificate
func (cac StorageAuthorityClient) AddCertificate(cert []byte, regID int64) (id string, err error) {
func (cac StorageAuthorityClient) AddCertificate(ctx context.Context, cert []byte, regID int64) (id string, err error) {
var acReq addCertificateRequest
acReq.Bytes = cert
acReq.RegID = regID
@ -1522,7 +1524,7 @@ func (cac StorageAuthorityClient) AddCertificate(cert []byte, regID int64) (id s
}
// AlreadyDeniedCSR sends a request to search for denied names
func (cac StorageAuthorityClient) AlreadyDeniedCSR(names []string) (exists bool, err error) {
func (cac StorageAuthorityClient) AlreadyDeniedCSR(ctx context.Context, names []string) (exists bool, err error) {
var adcReq alreadyDeniedCSRReq
adcReq.Names = names
@ -1547,7 +1549,7 @@ func (cac StorageAuthorityClient) AlreadyDeniedCSR(names []string) (exists bool,
// CountCertificatesRange sends a request to count the number of certificates
// issued in a certain time range
func (cac StorageAuthorityClient) CountCertificatesRange(start, end time.Time) (count int64, err error) {
func (cac StorageAuthorityClient) CountCertificatesRange(ctx context.Context, start, end time.Time) (count int64, err error) {
var cReq countRequest
cReq.Start, cReq.End = start, end
data, err := json.Marshal(cReq)
@ -1564,7 +1566,7 @@ func (cac StorageAuthorityClient) CountCertificatesRange(start, end time.Time) (
// CountCertificatesByNames calls CountCertificatesRange on the remote
// StorageAuthority.
func (cac StorageAuthorityClient) CountCertificatesByNames(names []string, earliest, latest time.Time) (counts map[string]int, err error) {
func (cac StorageAuthorityClient) CountCertificatesByNames(ctx context.Context, names []string, earliest, latest time.Time) (counts map[string]int, err error) {
var cReq countCertificatesByNamesRequest
cReq.Names, cReq.Earliest, cReq.Latest = names, earliest, latest
data, err := json.Marshal(cReq)
@ -1581,7 +1583,7 @@ func (cac StorageAuthorityClient) CountCertificatesByNames(names []string, earli
// CountRegistrationsByIP calls CountRegistrationsByIP on the remote
// StorageAuthority.
func (cac StorageAuthorityClient) CountRegistrationsByIP(ip net.IP, earliest, latest time.Time) (count int, err error) {
func (cac StorageAuthorityClient) CountRegistrationsByIP(ctx context.Context, ip net.IP, earliest, latest time.Time) (count int, err error) {
var cReq countRegistrationsByIPRequest
cReq.IP, cReq.Earliest, cReq.Latest = ip, earliest, latest
data, err := json.Marshal(cReq)
@ -1598,7 +1600,7 @@ func (cac StorageAuthorityClient) CountRegistrationsByIP(ip net.IP, earliest, la
// CountPendingAuthorizations calls CountPendingAuthorizations on the remote
// StorageAuthority.
func (cac StorageAuthorityClient) CountPendingAuthorizations(regID int64) (count int, err error) {
func (cac StorageAuthorityClient) CountPendingAuthorizations(ctx context.Context, regID int64) (count int, err error) {
var cReq countPendingAuthorizationsRequest
cReq.RegID = regID
data, err := json.Marshal(cReq)
@ -1615,7 +1617,7 @@ func (cac StorageAuthorityClient) CountPendingAuthorizations(regID int64) (count
// GetSCTReceipt retrieves an SCT according to the serial number of a certificate
// and the logID of the log to which it was submitted.
func (cac StorageAuthorityClient) GetSCTReceipt(serial string, logID string) (receipt core.SignedCertificateTimestamp, err error) {
func (cac StorageAuthorityClient) GetSCTReceipt(ctx context.Context, serial string, logID string) (receipt core.SignedCertificateTimestamp, err error) {
var gsctReq struct {
Serial string
LogID string
@ -1638,7 +1640,7 @@ func (cac StorageAuthorityClient) GetSCTReceipt(serial string, logID string) (re
}
// AddSCTReceipt adds a new SCT to the database.
func (cac StorageAuthorityClient) AddSCTReceipt(sct core.SignedCertificateTimestamp) (err error) {
func (cac StorageAuthorityClient) AddSCTReceipt(ctx context.Context, sct core.SignedCertificateTimestamp) (err error) {
data, err := json.Marshal(sct)
if err != nil {
return
@ -1649,7 +1651,7 @@ func (cac StorageAuthorityClient) AddSCTReceipt(sct core.SignedCertificateTimest
}
// CountFQDNSets reutrns the number of currently valid sets with hash |setHash|
func (cac StorageAuthorityClient) CountFQDNSets(window time.Duration, names []string) (int64, error) {
func (cac StorageAuthorityClient) CountFQDNSets(ctx context.Context, window time.Duration, names []string) (int64, error) {
data, err := json.Marshal(countFQDNsRequest{window, names})
if err != nil {
return 0, err
@ -1665,7 +1667,7 @@ func (cac StorageAuthorityClient) CountFQDNSets(window time.Duration, names []st
// FQDNSetExists returns a bool indicating whether the FQDN set |name|
// exists in the database
func (cac StorageAuthorityClient) FQDNSetExists(names []string) (bool, error) {
func (cac StorageAuthorityClient) FQDNSetExists(ctx context.Context, names []string) (bool, error) {
data, err := json.Marshal(fqdnSetExistsRequest{names})
if err != nil {
return false, err

View File

@ -9,6 +9,8 @@ import (
"encoding/json"
"testing"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/core"
blog "github.com/letsencrypt/boulder/log"
"github.com/letsencrypt/boulder/test"
@ -16,6 +18,7 @@ import (
)
var log = blog.UseMock()
var ctx = context.Background()
const JWK1JSON = `{
"kty": "RSA",
@ -70,7 +73,7 @@ func TestRANewRegistration(t *testing.T) {
Key: jwk,
}
_, err = client.NewRegistration(reg)
_, err = client.NewRegistration(ctx, reg)
test.AssertNotError(t, err, "Updated Registration")
test.Assert(t, len(mock.LastBody) > 0, "Didn't send Registration")
test.AssertEquals(t, "NewRegistration", mock.LastMethod)
@ -89,6 +92,6 @@ func TestGenerateOCSP(t *testing.T) {
}
mock.NextResp = []byte{}
_, err := client.GenerateOCSP(req)
_, err := client.GenerateOCSP(ctx, req)
test.AssertError(t, err, "Should have failed at signer")
}

View File

@ -7,6 +7,7 @@ package sa
import (
"fmt"
gorp "gopkg.in/gorp.v1"
)

View File

@ -6,6 +6,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
"github.com/letsencrypt/boulder/core"
jose "github.com/square/go-jose"
)
@ -43,7 +45,7 @@ func CreateWorkingRegistration(t *testing.T, sa core.StorageAdder) core.Registra
t.Fatalf("unable to parse contact link: %s", err)
}
contacts := []*core.AcmeURL{contact}
reg, err := sa.NewRegistration(core.Registration{
reg, err := sa.NewRegistration(context.Background(), core.Registration{
Key: GoodJWK(),
Contact: contacts,
InitialIP: net.ParseIP("88.77.66.11"),

View File

@ -18,6 +18,8 @@ import (
"strings"
"time"
"golang.org/x/net/context"
"github.com/jmhodges/clock"
jose "github.com/square/go-jose"
gorp "gopkg.in/gorp.v1"
@ -116,7 +118,7 @@ func updateChallenges(authID string, challenges []core.Challenge, tx *gorp.Trans
}
// GetRegistration obtains a Registration by ID
func (ssa *SQLStorageAuthority) GetRegistration(id int64) (core.Registration, error) {
func (ssa *SQLStorageAuthority) GetRegistration(ctx context.Context, id int64) (core.Registration, error) {
regObj, err := ssa.dbMap.Get(regModel{}, id)
if err != nil {
return core.Registration{}, err
@ -133,7 +135,7 @@ func (ssa *SQLStorageAuthority) GetRegistration(id int64) (core.Registration, er
}
// GetRegistrationByKey obtains a Registration by JWK
func (ssa *SQLStorageAuthority) GetRegistrationByKey(key jose.JsonWebKey) (core.Registration, error) {
func (ssa *SQLStorageAuthority) GetRegistrationByKey(ctx context.Context, key jose.JsonWebKey) (core.Registration, error) {
reg := &regModel{}
sha, err := core.KeyDigest(key.Key)
if err != nil {
@ -153,7 +155,7 @@ func (ssa *SQLStorageAuthority) GetRegistrationByKey(key jose.JsonWebKey) (core.
}
// GetAuthorization obtains an Authorization by ID
func (ssa *SQLStorageAuthority) GetAuthorization(id string) (authz core.Authorization, err error) {
func (ssa *SQLStorageAuthority) GetAuthorization(ctx context.Context, id string) (authz core.Authorization, err error) {
tx, err := ssa.dbMap.Begin()
if err != nil {
return
@ -208,7 +210,7 @@ func (ssa *SQLStorageAuthority) GetAuthorization(id string) (authz core.Authoriz
}
// GetLatestValidAuthorization gets the valid authorization with biggest expire date for a given domain and registrationId
func (ssa *SQLStorageAuthority) GetLatestValidAuthorization(registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
func (ssa *SQLStorageAuthority) GetLatestValidAuthorization(ctx context.Context, registrationID int64, identifier core.AcmeIdentifier) (authz core.Authorization, err error) {
ident, err := json.Marshal(identifier)
if err != nil {
return
@ -222,12 +224,12 @@ func (ssa *SQLStorageAuthority) GetLatestValidAuthorization(registrationID int64
return
}
return ssa.GetAuthorization(auth.ID)
return ssa.GetAuthorization(ctx, auth.ID)
}
// GetValidAuthorizations returns the latest authorization object for all
// domain names from the parameters that the account has authorizations for.
func (ssa *SQLStorageAuthority) GetValidAuthorizations(registrationID int64, names []string, now time.Time) (latest map[string]*core.Authorization, err error) {
func (ssa *SQLStorageAuthority) GetValidAuthorizations(ctx context.Context, registrationID int64, names []string, now time.Time) (latest map[string]*core.Authorization, err error) {
if len(names) == 0 {
return nil, errors.New("GetValidAuthorizations: no names received")
}
@ -320,7 +322,7 @@ func ipRange(ip net.IP) (net.IP, net.IP) {
// time range in an IP range. For IPv4 addresses, that range is limited to the
// single IP. For IPv6 addresses, that range is a /48, since it's not uncommon
// for one person to have a /48 to themselves.
func (ssa *SQLStorageAuthority) CountRegistrationsByIP(ip net.IP, earliest time.Time, latest time.Time) (int, error) {
func (ssa *SQLStorageAuthority) CountRegistrationsByIP(ctx context.Context, ip net.IP, earliest time.Time, latest time.Time) (int, error) {
var count int64
beginIP, endIP := ipRange(ip)
err := ssa.dbMap.SelectOne(
@ -359,7 +361,7 @@ func (t TooManyCertificatesError) Error() string {
// The highest count this function can return is 10,000. If there are more
// certificates than that matching one of the provided domain names, it will return
// TooManyCertificatesError.
func (ssa *SQLStorageAuthority) CountCertificatesByNames(domains []string, earliest, latest time.Time) (map[string]int, error) {
func (ssa *SQLStorageAuthority) CountCertificatesByNames(ctx context.Context, domains []string, earliest, latest time.Time) (map[string]int, error) {
ret := make(map[string]int, len(domains))
for _, domain := range domains {
currentCount, err := ssa.countCertificatesByName(domain, earliest, latest)
@ -413,7 +415,7 @@ func (ssa *SQLStorageAuthority) countCertificatesByName(domain string, earliest,
// GetCertificate takes a serial number and returns the corresponding
// certificate, or error if it does not exist.
func (ssa *SQLStorageAuthority) GetCertificate(serial string) (core.Certificate, error) {
func (ssa *SQLStorageAuthority) GetCertificate(ctx context.Context, serial string) (core.Certificate, error) {
if !core.ValidSerial(serial) {
err := fmt.Errorf("Invalid certificate serial %s", serial)
return core.Certificate{}, err
@ -439,7 +441,7 @@ func (ssa *SQLStorageAuthority) GetCertificate(serial string) (core.Certificate,
// GetCertificateStatus takes a hexadecimal string representing the full 128-bit serial
// number of a certificate and returns data about that certificate's current
// validity.
func (ssa *SQLStorageAuthority) GetCertificateStatus(serial string) (status core.CertificateStatus, err error) {
func (ssa *SQLStorageAuthority) GetCertificateStatus(ctx context.Context, serial string) (status core.CertificateStatus, err error) {
if !core.ValidSerial(serial) {
err := fmt.Errorf("Invalid certificate serial %s", serial)
return core.CertificateStatus{}, err
@ -454,7 +456,7 @@ func (ssa *SQLStorageAuthority) GetCertificateStatus(serial string) (status core
}
// NewRegistration stores a new Registration
func (ssa *SQLStorageAuthority) NewRegistration(reg core.Registration) (core.Registration, error) {
func (ssa *SQLStorageAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) {
rm, err := registrationToModel(&reg)
if err != nil {
return reg, err
@ -468,8 +470,8 @@ func (ssa *SQLStorageAuthority) NewRegistration(reg core.Registration) (core.Reg
}
// UpdateOCSP stores an updated OCSP response.
func (ssa *SQLStorageAuthority) UpdateOCSP(serial string, ocspResponse []byte) (err error) {
status, err := ssa.GetCertificateStatus(serial)
func (ssa *SQLStorageAuthority) UpdateOCSP(ctx context.Context, serial string, ocspResponse []byte) (err error) {
status, err := ssa.GetCertificateStatus(ctx, serial)
if err != nil {
return fmt.Errorf(
"Unable to update OCSP for certificate %s: cert status not found.", serial)
@ -483,13 +485,13 @@ func (ssa *SQLStorageAuthority) UpdateOCSP(serial string, ocspResponse []byte) (
// MarkCertificateRevoked stores the fact that a certificate is revoked, along
// with a timestamp and a reason.
func (ssa *SQLStorageAuthority) MarkCertificateRevoked(serial string, reasonCode core.RevocationCode) (err error) {
if _, err = ssa.GetCertificate(serial); err != nil {
func (ssa *SQLStorageAuthority) MarkCertificateRevoked(ctx context.Context, serial string, reasonCode core.RevocationCode) (err error) {
if _, err = ssa.GetCertificate(ctx, serial); err != nil {
return fmt.Errorf(
"Unable to mark certificate %s revoked: cert not found.", serial)
}
if _, err = ssa.GetCertificateStatus(serial); err != nil {
if _, err = ssa.GetCertificateStatus(ctx, serial); err != nil {
return fmt.Errorf(
"Unable to mark certificate %s revoked: cert status not found.", serial)
}
@ -531,7 +533,7 @@ func (ssa *SQLStorageAuthority) MarkCertificateRevoked(serial string, reasonCode
}
// UpdateRegistration stores an updated Registration
func (ssa *SQLStorageAuthority) UpdateRegistration(reg core.Registration) error {
func (ssa *SQLStorageAuthority) UpdateRegistration(ctx context.Context, reg core.Registration) error {
lookupResult, err := ssa.dbMap.Get(regModel{}, reg.ID)
if err != nil {
return err
@ -565,7 +567,7 @@ func (ssa *SQLStorageAuthority) UpdateRegistration(reg core.Registration) error
}
// NewPendingAuthorization stores a new Pending Authorization
func (ssa *SQLStorageAuthority) NewPendingAuthorization(authz core.Authorization) (output core.Authorization, err error) {
func (ssa *SQLStorageAuthority) NewPendingAuthorization(ctx context.Context, authz core.Authorization) (output core.Authorization, err error) {
tx, err := ssa.dbMap.Begin()
if err != nil {
return
@ -616,7 +618,7 @@ func (ssa *SQLStorageAuthority) NewPendingAuthorization(authz core.Authorization
}
// UpdatePendingAuthorization updates a Pending Authorization
func (ssa *SQLStorageAuthority) UpdatePendingAuthorization(authz core.Authorization) (err error) {
func (ssa *SQLStorageAuthority) UpdatePendingAuthorization(ctx context.Context, authz core.Authorization) (err error) {
tx, err := ssa.dbMap.Begin()
if err != nil {
return
@ -664,7 +666,7 @@ func (ssa *SQLStorageAuthority) UpdatePendingAuthorization(authz core.Authorizat
}
// FinalizeAuthorization converts a Pending Authorization to a final one
func (ssa *SQLStorageAuthority) FinalizeAuthorization(authz core.Authorization) (err error) {
func (ssa *SQLStorageAuthority) FinalizeAuthorization(ctx context.Context, authz core.Authorization) (err error) {
tx, err := ssa.dbMap.Begin()
if err != nil {
return
@ -714,7 +716,7 @@ func (ssa *SQLStorageAuthority) FinalizeAuthorization(authz core.Authorization)
// RevokeAuthorizationsByDomain invalidates all pending or finalized authorizations
// for a specific domain
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ident core.AcmeIdentifier) (int64, int64, error) {
func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ctx context.Context, ident core.AcmeIdentifier) (int64, int64, error) {
identifierJSON, err := json.Marshal(ident)
if err != nil {
return 0, 0, err
@ -749,7 +751,7 @@ func (ssa *SQLStorageAuthority) RevokeAuthorizationsByDomain(ident core.AcmeIden
}
// AddCertificate stores an issued certificate.
func (ssa *SQLStorageAuthority) AddCertificate(certDER []byte, regID int64) (digest string, err error) {
func (ssa *SQLStorageAuthority) AddCertificate(ctx context.Context, certDER []byte, regID int64) (digest string, err error) {
var parsedCertificate *x509.Certificate
parsedCertificate, err = x509.ParseCertificate(certDER)
if err != nil {
@ -818,7 +820,7 @@ func (ssa *SQLStorageAuthority) AddCertificate(certDER []byte, regID int64) (dig
}
// AlreadyDeniedCSR queries to find if the name list has already been denied.
func (ssa *SQLStorageAuthority) AlreadyDeniedCSR(names []string) (already bool, err error) {
func (ssa *SQLStorageAuthority) AlreadyDeniedCSR(ctx context.Context, names []string) (already bool, err error) {
sort.Strings(names)
var denied int64
@ -839,7 +841,7 @@ func (ssa *SQLStorageAuthority) AlreadyDeniedCSR(names []string) (already bool,
// CountCertificatesRange returns the number of certificates issued in a specific
// date range
func (ssa *SQLStorageAuthority) CountCertificatesRange(start, end time.Time) (count int64, err error) {
func (ssa *SQLStorageAuthority) CountCertificatesRange(ctx context.Context, start, end time.Time) (count int64, err error) {
err = ssa.dbMap.SelectOne(
&count,
`SELECT COUNT(1) FROM certificates
@ -855,7 +857,7 @@ func (ssa *SQLStorageAuthority) CountCertificatesRange(start, end time.Time) (co
// CountPendingAuthorizations returns the number of pending, unexpired
// authorizations for the give registration.
func (ssa *SQLStorageAuthority) CountPendingAuthorizations(regID int64) (count int, err error) {
func (ssa *SQLStorageAuthority) CountPendingAuthorizations(ctx context.Context, regID int64) (count int, err error) {
err = ssa.dbMap.SelectOne(&count,
`SELECT count(1) FROM pendingAuthorizations
WHERE registrationID = :regID AND
@ -876,7 +878,7 @@ func (e ErrNoReceipt) Error() string {
// GetSCTReceipt gets a specific SCT receipt for a given certificate serial and
// CT log ID
func (ssa *SQLStorageAuthority) GetSCTReceipt(serial string, logID string) (receipt core.SignedCertificateTimestamp, err error) {
func (ssa *SQLStorageAuthority) GetSCTReceipt(ctx context.Context, serial string, logID string) (receipt core.SignedCertificateTimestamp, err error) {
err = ssa.dbMap.SelectOne(
&receipt,
"SELECT * FROM sctReceipts WHERE certificateSerial = :serial AND logID = :logID",
@ -895,7 +897,7 @@ func (ssa *SQLStorageAuthority) GetSCTReceipt(serial string, logID string) (rece
}
// AddSCTReceipt adds a new SCT receipt to the (append-only) sctReceipts table
func (ssa *SQLStorageAuthority) AddSCTReceipt(sct core.SignedCertificateTimestamp) error {
func (ssa *SQLStorageAuthority) AddSCTReceipt(ctx context.Context, sct core.SignedCertificateTimestamp) error {
err := ssa.dbMap.Insert(&sct)
// For AddSCTReceipt, duplicates are explicitly OK, so don't return errors
// based on duplicates, especially because we currently retry all submissions
@ -943,7 +945,7 @@ func addIssuedNames(tx execable, cert *x509.Certificate) error {
// CountFQDNSets returns the number of sets with hash |setHash| within the window
// |window|
func (ssa *SQLStorageAuthority) CountFQDNSets(window time.Duration, names []string) (int64, error) {
func (ssa *SQLStorageAuthority) CountFQDNSets(ctx context.Context, window time.Duration, names []string) (int64, error) {
var count int64
err := ssa.dbMap.SelectOne(
&count,
@ -958,7 +960,7 @@ func (ssa *SQLStorageAuthority) CountFQDNSets(window time.Duration, names []stri
// FQDNSetExists returns a bool indicating if one or more FQDN sets |names|
// exists in the database
func (ssa *SQLStorageAuthority) FQDNSetExists(names []string) (bool, error) {
func (ssa *SQLStorageAuthority) FQDNSetExists(ctx context.Context, names []string) (bool, error) {
var count int64
err := ssa.dbMap.SelectOne(
&count,

View File

@ -23,6 +23,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
"github.com/jmhodges/clock"
jose "github.com/square/go-jose"
@ -34,6 +36,7 @@ import (
)
var log = blog.UseMock()
var ctx = context.Background()
// initSA constructs a SQLStorageAuthority and a clean up function
// that should be defer'ed to the end of the test.
@ -74,7 +77,7 @@ func TestAddRegistration(t *testing.T) {
t.Fatalf("unable to parse contact link: %s", err)
}
contacts := []*core.AcmeURL{contact}
reg, err := sa.NewRegistration(core.Registration{
reg, err := sa.NewRegistration(ctx, core.Registration{
Key: jwk,
Contact: contacts,
InitialIP: net.ParseIP("43.34.43.34"),
@ -85,10 +88,10 @@ func TestAddRegistration(t *testing.T) {
test.Assert(t, reg.ID != 0, "ID shouldn't be 0")
test.AssertDeepEquals(t, reg.Contact, contacts)
_, err = sa.GetRegistration(0)
_, err = sa.GetRegistration(ctx, 0)
test.AssertError(t, err, "Registration object for ID 0 was returned")
dbReg, err := sa.GetRegistration(reg.ID)
dbReg, err := sa.GetRegistration(ctx, reg.ID)
test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))
expectedReg := core.Registration{
@ -109,9 +112,9 @@ func TestAddRegistration(t *testing.T) {
InitialIP: net.ParseIP("72.72.72.72"),
Agreement: "yes",
}
err = sa.UpdateRegistration(newReg)
err = sa.UpdateRegistration(ctx, newReg)
test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))
dbReg, err = sa.GetRegistrationByKey(jwk)
dbReg, err = sa.GetRegistrationByKey(ctx, jwk)
test.AssertNotError(t, err, "Couldn't get registration by key")
test.AssertEquals(t, dbReg.ID, newReg.ID)
@ -120,7 +123,7 @@ func TestAddRegistration(t *testing.T) {
var anotherJWK jose.JsonWebKey
err = json.Unmarshal([]byte(anotherKey), &anotherJWK)
test.AssertNotError(t, err, "couldn't unmarshal anotherJWK")
_, err = sa.GetRegistrationByKey(anotherJWK)
_, err = sa.GetRegistrationByKey(ctx, anotherJWK)
test.AssertError(t, err, "Registration object for invalid key was returned")
}
@ -128,18 +131,18 @@ func TestNoSuchRegistrationErrors(t *testing.T) {
sa, _, cleanUp := initSA(t)
defer cleanUp()
_, err := sa.GetRegistration(100)
_, err := sa.GetRegistration(ctx, 100)
if _, ok := err.(core.NoSuchRegistrationError); !ok {
t.Errorf("GetRegistration: expected NoSuchRegistrationError, got %T type error (%s)", err, err)
}
jwk := satest.GoodJWK()
_, err = sa.GetRegistrationByKey(jwk)
_, err = sa.GetRegistrationByKey(ctx, jwk)
if _, ok := err.(core.NoSuchRegistrationError); !ok {
t.Errorf("GetRegistrationByKey: expected a NoSuchRegistrationError, got %T type error (%s)", err, err)
}
err = sa.UpdateRegistration(core.Registration{ID: 100, Key: jwk})
err = sa.UpdateRegistration(ctx, core.Registration{ID: 100, Key: jwk})
if _, ok := err.(core.NoSuchRegistrationError); !ok {
t.Errorf("UpdateRegistration: expected a NoSuchRegistrationError, got %T type error (%v)", err, err)
}
@ -156,14 +159,14 @@ func TestCountPendingAuthorizations(t *testing.T) {
Expires: &expires,
}
pendingAuthz, err := sa.NewPendingAuthorization(pendingAuthz)
pendingAuthz, err := sa.NewPendingAuthorization(ctx, pendingAuthz)
test.AssertNotError(t, err, "Couldn't create new pending authorization")
count, err := sa.CountPendingAuthorizations(reg.ID)
count, err := sa.CountPendingAuthorizations(ctx, reg.ID)
test.AssertNotError(t, err, "Couldn't count pending authorizations")
test.AssertEquals(t, count, 1)
fc.Add(2 * time.Hour)
count, err = sa.CountPendingAuthorizations(reg.ID)
count, err = sa.CountPendingAuthorizations(ctx, reg.ID)
test.AssertNotError(t, err, "Couldn't count pending authorizations")
test.AssertEquals(t, count, 0)
}
@ -175,11 +178,11 @@ func TestAddAuthorization(t *testing.T) {
reg := satest.CreateWorkingRegistration(t, sa)
PA := core.Authorization{RegistrationID: reg.ID}
PA, err := sa.NewPendingAuthorization(PA)
PA, err := sa.NewPendingAuthorization(ctx, PA)
test.AssertNotError(t, err, "Couldn't create new pending authorization")
test.Assert(t, PA.ID != "", "ID shouldn't be blank")
dbPa, err := sa.GetAuthorization(PA.ID)
dbPa, err := sa.GetAuthorization(ctx, PA.ID)
test.AssertNotError(t, err, "Couldn't get pending authorization with ID "+PA.ID)
test.AssertMarshaledEquals(t, PA, dbPa)
@ -192,14 +195,14 @@ func TestAddAuthorization(t *testing.T) {
exp := time.Now().AddDate(0, 0, 1)
identifier := core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "wut.com"}
newPa := core.Authorization{ID: PA.ID, Identifier: identifier, RegistrationID: reg.ID, Status: core.StatusPending, Expires: &exp, Combinations: combos}
err = sa.UpdatePendingAuthorization(newPa)
err = sa.UpdatePendingAuthorization(ctx, newPa)
test.AssertNotError(t, err, "Couldn't update pending authorization with ID "+PA.ID)
newPa.Status = core.StatusValid
err = sa.FinalizeAuthorization(newPa)
err = sa.FinalizeAuthorization(ctx, newPa)
test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+PA.ID)
dbPa, err = sa.GetAuthorization(PA.ID)
dbPa, err = sa.GetAuthorization(ctx, PA.ID)
test.AssertNotError(t, err, "Couldn't get authorization with ID "+PA.ID)
}
@ -210,7 +213,7 @@ func CreateDomainAuth(t *testing.T, domainName string, sa *SQLStorageAuthority)
func CreateDomainAuthWithRegID(t *testing.T, domainName string, sa *SQLStorageAuthority, regID int64) (authz core.Authorization) {
// create pending auth
authz, err := sa.NewPendingAuthorization(core.Authorization{RegistrationID: regID, Challenges: []core.Challenge{{}}})
authz, err := sa.NewPendingAuthorization(ctx, core.Authorization{RegistrationID: regID, Challenges: []core.Challenge{{}}})
if err != nil {
t.Fatalf("Couldn't create new pending authorization: %s", err)
}
@ -230,7 +233,7 @@ func CreateDomainAuthWithRegID(t *testing.T, domainName string, sa *SQLStorageAu
authz.Combinations = combos
// save updated auth
err = sa.UpdatePendingAuthorization(authz)
err = sa.UpdatePendingAuthorization(ctx, authz)
test.AssertNotError(t, err, "Couldn't update pending authorization with ID "+authz.ID)
return
@ -242,7 +245,7 @@ func TestGetLatestValidAuthorizationBasic(t *testing.T) {
defer cleanUp()
// attempt to get unauthorized domain
authz, err := sa.GetLatestValidAuthorization(0, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
authz, err := sa.GetLatestValidAuthorization(ctx, 0, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
test.AssertError(t, err, "Should not have found a valid auth for example.org")
reg := satest.CreateWorkingRegistration(t, sa)
@ -252,15 +255,15 @@ func TestGetLatestValidAuthorizationBasic(t *testing.T) {
// finalize auth
authz.Status = core.StatusValid
err = sa.FinalizeAuthorization(authz)
err = sa.FinalizeAuthorization(ctx, authz)
test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+authz.ID)
// attempt to get authorized domain with wrong RegID
authz, err = sa.GetLatestValidAuthorization(0, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
authz, err = sa.GetLatestValidAuthorization(ctx, 0, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
test.AssertError(t, err, "Should not have found a valid auth for example.org and regID 0")
// get authorized domain
authz, err = sa.GetLatestValidAuthorization(reg.ID, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
authz, err = sa.GetLatestValidAuthorization(ctx, reg.ID, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.org"})
test.AssertNotError(t, err, "Should have found a valid auth for example.org and regID 42")
test.AssertEquals(t, authz.Status, core.StatusValid)
test.AssertEquals(t, authz.Identifier.Type, core.IdentifierDNS)
@ -283,11 +286,11 @@ func TestGetLatestValidAuthorizationMultiple(t *testing.T) {
exp := time.Now().AddDate(0, 0, 10) // expire in 10 day
authz.Expires = &exp
authz.Status = core.StatusInvalid
err = sa.FinalizeAuthorization(authz)
err = sa.FinalizeAuthorization(ctx, authz)
test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+authz.ID)
// should not get the auth
authz, err = sa.GetLatestValidAuthorization(reg.ID, ident)
authz, err = sa.GetLatestValidAuthorization(ctx, reg.ID, ident)
test.AssertError(t, err, "Should not have found a valid auth for "+domain)
// create valid auth
@ -295,11 +298,11 @@ func TestGetLatestValidAuthorizationMultiple(t *testing.T) {
exp = time.Now().AddDate(0, 0, 1) // expire in 1 day
authz.Expires = &exp
authz.Status = core.StatusValid
err = sa.FinalizeAuthorization(authz)
err = sa.FinalizeAuthorization(ctx, authz)
test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+authz.ID)
// should get the valid auth even if it's expire date is lower than the invalid one
authz, err = sa.GetLatestValidAuthorization(reg.ID, ident)
authz, err = sa.GetLatestValidAuthorization(ctx, reg.ID, ident)
test.AssertNotError(t, err, "Should have found a valid auth for "+domain)
test.AssertEquals(t, authz.Status, core.StatusValid)
test.AssertEquals(t, authz.Identifier.Type, ident.Type)
@ -311,10 +314,10 @@ func TestGetLatestValidAuthorizationMultiple(t *testing.T) {
exp = time.Now().AddDate(0, 0, 2) // expire in 2 day
newAuthz.Expires = &exp
newAuthz.Status = core.StatusValid
err = sa.FinalizeAuthorization(newAuthz)
err = sa.FinalizeAuthorization(ctx, newAuthz)
test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+newAuthz.ID)
authz, err = sa.GetLatestValidAuthorization(reg.ID, ident)
authz, err = sa.GetLatestValidAuthorization(ctx, reg.ID, ident)
test.AssertNotError(t, err, "Should have found a valid auth for "+domain)
test.AssertEquals(t, authz.Status, core.StatusValid)
test.AssertEquals(t, authz.Identifier.Type, ident.Type)
@ -334,15 +337,15 @@ func TestAddCertificate(t *testing.T) {
certDER, err := ioutil.ReadFile("www.eff.org.der")
test.AssertNotError(t, err, "Couldn't read example cert DER")
digest, err := sa.AddCertificate(certDER, reg.ID)
digest, err := sa.AddCertificate(ctx, certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
test.AssertEquals(t, digest, "qWoItDZmR4P9eFbeYgXXP3SR4ApnkQj8x4LsB_ORKBo")
retrievedCert, err := sa.GetCertificate("000000000000000000000000000000021bd4")
retrievedCert, err := sa.GetCertificate(ctx, "000000000000000000000000000000021bd4")
test.AssertNotError(t, err, "Couldn't get www.eff.org.der by full serial")
test.AssertByteEquals(t, certDER, retrievedCert.DER)
certificateStatus, err := sa.GetCertificateStatus("000000000000000000000000000000021bd4")
certificateStatus, err := sa.GetCertificateStatus(ctx, "000000000000000000000000000000021bd4")
test.AssertNotError(t, err, "Couldn't get status for www.eff.org.der")
test.Assert(t, !certificateStatus.SubscriberApproved, "SubscriberApproved should be false")
test.Assert(t, certificateStatus.Status == core.OCSPStatusGood, "OCSP Status should be good")
@ -354,15 +357,15 @@ func TestAddCertificate(t *testing.T) {
test.AssertNotError(t, err, "Couldn't read example cert DER")
serial := "ffdd9b8a82126d96f61d378d5ba99a0474f0"
digest2, err := sa.AddCertificate(certDER2, reg.ID)
digest2, err := sa.AddCertificate(ctx, certDER2, reg.ID)
test.AssertNotError(t, err, "Couldn't add test-cert.der")
test.AssertEquals(t, digest2, "vrlPN5wIPME1D2PPsCy-fGnTWh8dMyyYQcXPRkjHAQI")
retrievedCert2, err := sa.GetCertificate(serial)
retrievedCert2, err := sa.GetCertificate(ctx, serial)
test.AssertNotError(t, err, "Couldn't get test-cert.der")
test.AssertByteEquals(t, certDER2, retrievedCert2.DER)
certificateStatus2, err := sa.GetCertificateStatus(serial)
certificateStatus2, err := sa.GetCertificateStatus(ctx, serial)
test.AssertNotError(t, err, "Couldn't get status for test-cert.der")
test.Assert(t, !certificateStatus2.SubscriberApproved, "SubscriberApproved should be false")
test.Assert(t, certificateStatus2.Status == core.OCSPStatusGood, "OCSP Status should be good")
@ -388,30 +391,30 @@ func TestCountCertificatesByNames(t *testing.T) {
tomorrow := clk.Now().Add(24 * time.Hour)
// Count for a name that doesn't have any certs
counts, err := sa.CountCertificatesByNames([]string{"example.com"}, yesterday, now)
counts, err := sa.CountCertificatesByNames(ctx, []string{"example.com"}, yesterday, now)
test.AssertNotError(t, err, "Error counting certs.")
test.AssertEquals(t, len(counts), 1)
test.AssertEquals(t, counts["example.com"], 0)
// Add the test cert and query for its names.
reg := satest.CreateWorkingRegistration(t, sa)
_, err = sa.AddCertificate(certDER, reg.ID)
_, err = sa.AddCertificate(ctx, certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add test-cert.der")
// Time range including now should find the cert
counts, err = sa.CountCertificatesByNames([]string{"example.com"}, yesterday, now)
counts, err = sa.CountCertificatesByNames(ctx, []string{"example.com"}, yesterday, now)
test.AssertEquals(t, len(counts), 1)
test.AssertEquals(t, counts["example.com"], 1)
// Time range between two days ago and yesterday should not.
counts, err = sa.CountCertificatesByNames([]string{"example.com"}, twoDaysAgo, yesterday)
counts, err = sa.CountCertificatesByNames(ctx, []string{"example.com"}, twoDaysAgo, yesterday)
test.AssertNotError(t, err, "Error counting certs.")
test.AssertEquals(t, len(counts), 1)
test.AssertEquals(t, counts["example.com"], 0)
// Time range between now and tomorrow also should not (time ranges are
// inclusive at the tail end, but not the beginning end).
counts, err = sa.CountCertificatesByNames([]string{"example.com"}, now, tomorrow)
counts, err = sa.CountCertificatesByNames(ctx, []string{"example.com"}, now, tomorrow)
test.AssertNotError(t, err, "Error counting certs.")
test.AssertEquals(t, len(counts), 1)
test.AssertEquals(t, counts["example.com"], 0)
@ -419,9 +422,9 @@ func TestCountCertificatesByNames(t *testing.T) {
// Add a second test cert (for example.co.bn) and query for multiple names.
certDER2, err := ioutil.ReadFile("test-cert2.der")
test.AssertNotError(t, err, "Couldn't read test-cert2.der")
_, err = sa.AddCertificate(certDER2, reg.ID)
_, err = sa.AddCertificate(ctx, certDER2, reg.ID)
test.AssertNotError(t, err, "Couldn't add test-cert2.der")
counts, err = sa.CountCertificatesByNames([]string{"example.com", "foo.com", "example.co.bn"}, yesterday, now.Add(10000*time.Hour))
counts, err = sa.CountCertificatesByNames(ctx, []string{"example.com", "foo.com", "example.co.bn"}, yesterday, now.Add(10000*time.Hour))
test.AssertNotError(t, err, "Error counting certs.")
test.AssertEquals(t, len(counts), 3)
test.AssertEquals(t, counts["foo.com"], 0)
@ -441,7 +444,7 @@ func TestDeniedCSR(t *testing.T) {
sa, _, cleanUp := initSA(t)
defer cleanUp()
exists, err := sa.AlreadyDeniedCSR(append(csr.DNSNames, csr.Subject.CommonName))
exists, err := sa.AlreadyDeniedCSR(ctx, append(csr.DNSNames, csr.Subject.CommonName))
test.AssertNotError(t, err, "AlreadyDeniedCSR failed")
test.Assert(t, !exists, "Found non-existent CSR")
}
@ -466,10 +469,10 @@ func TestAddSCTReceipt(t *testing.T) {
}
sa, _, cleanup := initSA(t)
defer cleanup()
err = sa.AddSCTReceipt(sct)
err = sa.AddSCTReceipt(ctx, sct)
test.AssertNotError(t, err, "Failed to add SCT receipt")
// Append only and unique on signature and across LogID and CertificateSerial
err = sa.AddSCTReceipt(sct)
err = sa.AddSCTReceipt(ctx, sct)
test.AssertNotError(t, err, "Incorrectly returned error on duplicate SCT receipt")
}
@ -485,10 +488,10 @@ func TestGetSCTReceipt(t *testing.T) {
}
sa, _, cleanup := initSA(t)
defer cleanup()
err = sa.AddSCTReceipt(sct)
err = sa.AddSCTReceipt(ctx, sct)
test.AssertNotError(t, err, "Failed to add SCT receipt")
sqlSCT, err := sa.GetSCTReceipt(sctCertSerial, sctLogID)
sqlSCT, err := sa.GetSCTReceipt(ctx, sctCertSerial, sctLogID)
test.AssertNotError(t, err, "Failed to get existing SCT receipt")
test.Assert(t, sqlSCT.SCTVersion == sct.SCTVersion, "Invalid SCT version")
test.Assert(t, sqlSCT.LogID == sct.LogID, "Invalid log ID")
@ -505,7 +508,7 @@ func TestUpdateOCSP(t *testing.T) {
// Add a cert to the DB to test with.
certDER, err := ioutil.ReadFile("www.eff.org.der")
test.AssertNotError(t, err, "Couldn't read example cert DER")
_, err = sa.AddCertificate(certDER, reg.ID)
_, err = sa.AddCertificate(ctx, certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
serial := "000000000000000000000000000000021bd4"
@ -519,7 +522,7 @@ func TestUpdateOCSP(t *testing.T) {
fc.Add(1 * time.Hour)
err = sa.UpdateOCSP(serial, []byte(ocspResponse))
err = sa.UpdateOCSP(ctx, serial, []byte(ocspResponse))
test.AssertNotError(t, err, "UpdateOCSP failed")
certificateStatusObj, err = sa.dbMap.Get(core.CertificateStatus{}, serial)
@ -539,7 +542,7 @@ func TestMarkCertificateRevoked(t *testing.T) {
// Add a cert to the DB to test with.
certDER, err := ioutil.ReadFile("www.eff.org.der")
test.AssertNotError(t, err, "Couldn't read example cert DER")
_, err = sa.AddCertificate(certDER, reg.ID)
_, err = sa.AddCertificate(ctx, certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
serial := "000000000000000000000000000000021bd4"
@ -552,7 +555,7 @@ func TestMarkCertificateRevoked(t *testing.T) {
fc.Add(1 * time.Hour)
code := core.RevocationCode(1)
err = sa.MarkCertificateRevoked(serial, code)
err = sa.MarkCertificateRevoked(ctx, serial, code)
test.AssertNotError(t, err, "MarkCertificateRevoked failed")
certificateStatusObj, err = sa.dbMap.Get(core.CertificateStatus{}, serial)
@ -572,7 +575,7 @@ func TestCountCertificates(t *testing.T) {
defer cleanUp()
fc.Add(time.Hour * 24)
now := fc.Now()
count, err := sa.CountCertificatesRange(now.Add(-24*time.Hour), now)
count, err := sa.CountCertificatesRange(ctx, now.Add(-24*time.Hour), now)
test.AssertNotError(t, err, "Couldn't get certificate count for the last 24hrs")
test.AssertEquals(t, count, int64(0))
@ -580,18 +583,18 @@ func TestCountCertificates(t *testing.T) {
// Add a cert to the DB to test with.
certDER, err := ioutil.ReadFile("www.eff.org.der")
test.AssertNotError(t, err, "Couldn't read example cert DER")
_, err = sa.AddCertificate(certDER, reg.ID)
_, err = sa.AddCertificate(ctx, certDER, reg.ID)
test.AssertNotError(t, err, "Couldn't add www.eff.org.der")
fc.Add(2 * time.Hour)
now = fc.Now()
count, err = sa.CountCertificatesRange(now.Add(-24*time.Hour), now)
count, err = sa.CountCertificatesRange(ctx, now.Add(-24*time.Hour), now)
test.AssertNotError(t, err, "Couldn't get certificate count for the last 24hrs")
test.AssertEquals(t, count, int64(1))
fc.Add(24 * time.Hour)
now = fc.Now()
count, err = sa.CountCertificatesRange(now.Add(-24*time.Hour), now)
count, err = sa.CountCertificatesRange(ctx, now.Add(-24*time.Hour), now)
test.AssertNotError(t, err, "Couldn't get certificate count for the last 24hrs")
test.AssertEquals(t, count, int64(0))
}
@ -605,19 +608,19 @@ func TestCountRegistrationsByIP(t *testing.T) {
Opaque: "foo@example.com",
})
_, err := sa.NewRegistration(core.Registration{
_, err := sa.NewRegistration(ctx, core.Registration{
Key: jose.JsonWebKey{Key: &rsa.PublicKey{N: big.NewInt(1), E: 1}},
Contact: []*core.AcmeURL{&contact},
InitialIP: net.ParseIP("43.34.43.34"),
})
test.AssertNotError(t, err, "Couldn't insert registration")
_, err = sa.NewRegistration(core.Registration{
_, err = sa.NewRegistration(ctx, core.Registration{
Key: jose.JsonWebKey{Key: &rsa.PublicKey{N: big.NewInt(2), E: 1}},
Contact: []*core.AcmeURL{&contact},
InitialIP: net.ParseIP("2001:cdba:1234:5678:9101:1121:3257:9652"),
})
test.AssertNotError(t, err, "Couldn't insert registration")
_, err = sa.NewRegistration(core.Registration{
_, err = sa.NewRegistration(ctx, core.Registration{
Key: jose.JsonWebKey{Key: &rsa.PublicKey{N: big.NewInt(3), E: 1}},
Contact: []*core.AcmeURL{&contact},
InitialIP: net.ParseIP("2001:cdba:1234:5678:9101:1121:3257:9653"),
@ -627,16 +630,16 @@ func TestCountRegistrationsByIP(t *testing.T) {
earliest := fc.Now().Add(-time.Hour * 24)
latest := fc.Now()
count, err := sa.CountRegistrationsByIP(net.ParseIP("1.1.1.1"), earliest, latest)
count, err := sa.CountRegistrationsByIP(ctx, net.ParseIP("1.1.1.1"), earliest, latest)
test.AssertNotError(t, err, "Failed to count registrations")
test.AssertEquals(t, count, 0)
count, err = sa.CountRegistrationsByIP(net.ParseIP("43.34.43.34"), earliest, latest)
count, err = sa.CountRegistrationsByIP(ctx, net.ParseIP("43.34.43.34"), earliest, latest)
test.AssertNotError(t, err, "Failed to count registrations")
test.AssertEquals(t, count, 1)
count, err = sa.CountRegistrationsByIP(net.ParseIP("2001:cdba:1234:5678:9101:1121:3257:9652"), earliest, latest)
count, err = sa.CountRegistrationsByIP(ctx, net.ParseIP("2001:cdba:1234:5678:9101:1121:3257:9652"), earliest, latest)
test.AssertNotError(t, err, "Failed to count registrations")
test.AssertEquals(t, count, 2)
count, err = sa.CountRegistrationsByIP(net.ParseIP("2001:cdba:1234:0000:0000:0000:0000:0000"), earliest, latest)
count, err = sa.CountRegistrationsByIP(ctx, net.ParseIP("2001:cdba:1234:0000:0000:0000:0000:0000"), earliest, latest)
test.AssertNotError(t, err, "Failed to count registrations")
test.AssertEquals(t, count, 2)
}
@ -650,18 +653,18 @@ func TestRevokeAuthorizationsByDomain(t *testing.T) {
PA2 := CreateDomainAuthWithRegID(t, "a.com", sa, reg.ID)
PA2.Status = core.StatusValid
err := sa.FinalizeAuthorization(PA2)
err := sa.FinalizeAuthorization(ctx, PA2)
test.AssertNotError(t, err, "Failed to finalize authorization")
ident := core.AcmeIdentifier{Value: "a.com", Type: core.IdentifierDNS}
ar, par, err := sa.RevokeAuthorizationsByDomain(ident)
ar, par, err := sa.RevokeAuthorizationsByDomain(ctx, ident)
test.AssertNotError(t, err, "Failed to revoke authorizations for a.com")
test.AssertEquals(t, ar, int64(1))
test.AssertEquals(t, par, int64(1))
PA, err := sa.GetAuthorization(PA1.ID)
PA, err := sa.GetAuthorization(ctx, PA1.ID)
test.AssertNotError(t, err, "Failed to retrieve pending authorization")
FA, err := sa.GetAuthorization(PA2.ID)
FA, err := sa.GetAuthorization(ctx, PA2.ID)
test.AssertNotError(t, err, "Failed to retrieve finalized authorization")
test.AssertEquals(t, PA.Status, core.StatusRevoked)
@ -683,12 +686,12 @@ func TestFQDNSets(t *testing.T) {
// only one valid
threeHours := time.Hour * 3
count, err := sa.CountFQDNSets(threeHours, names)
count, err := sa.CountFQDNSets(ctx, threeHours, names)
test.AssertNotError(t, err, "Failed to count name sets")
test.AssertEquals(t, count, int64(1))
// check hash isn't affected by changing name order/casing
count, err = sa.CountFQDNSets(threeHours, []string{"b.example.com", "A.example.COM"})
count, err = sa.CountFQDNSets(ctx, threeHours, []string{"b.example.com", "A.example.COM"})
test.AssertNotError(t, err, "Failed to count name sets")
test.AssertEquals(t, count, int64(1))
@ -700,7 +703,7 @@ func TestFQDNSets(t *testing.T) {
test.AssertNotError(t, tx.Commit(), "Failed to commit transaction")
// only two valid
count, err = sa.CountFQDNSets(threeHours, names)
count, err = sa.CountFQDNSets(ctx, threeHours, names)
test.AssertNotError(t, err, "Failed to count name sets")
test.AssertEquals(t, count, int64(2))
@ -718,7 +721,7 @@ func TestFQDNSets(t *testing.T) {
test.AssertNotError(t, tx.Commit(), "Failed to commit transaction")
// only two valid
count, err = sa.CountFQDNSets(threeHours, names)
count, err = sa.CountFQDNSets(ctx, threeHours, names)
test.AssertNotError(t, err, "Failed to count name sets")
test.AssertEquals(t, count, int64(2))
}
@ -728,7 +731,7 @@ func TestFQDNSetsExists(t *testing.T) {
defer cleanUp()
names := []string{"a.example.com", "B.example.com"}
exists, err := sa.FQDNSetExists(names)
exists, err := sa.FQDNSetExists(ctx, names)
test.AssertNotError(t, err, "Failed to check FQDN set existence")
test.Assert(t, !exists, "FQDN set shouldn't exist")
@ -740,7 +743,7 @@ func TestFQDNSetsExists(t *testing.T) {
test.AssertNotError(t, err, "Failed to add name set")
test.AssertNotError(t, tx.Commit(), "Failed to commit transaction")
exists, err = sa.FQDNSetExists(names)
exists, err = sa.FQDNSetExists(ctx, names)
test.AssertNotError(t, err, "Failed to check FQDN set existence")
test.Assert(t, exists, "FQDN set does exist")
}

View File

@ -12,6 +12,7 @@ package va
import (
"github.com/letsencrypt/boulder/core"
safebrowsing "github.com/letsencrypt/go-safe-browsing-api"
"golang.org/x/net/context"
)
// SafeBrowsing is an interface for an third-party safe browing API client.
@ -25,7 +26,7 @@ type SafeBrowsing interface {
// third-party safe browsing API. It's meant be called by the RA before pending
// authorization creation. If no third-party client was provided, it fails open
// and increments a Skips metric.
func (va *ValidationAuthorityImpl) IsSafeDomain(req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
func (va *ValidationAuthorityImpl) IsSafeDomain(ctx context.Context, req *core.IsSafeDomainRequest) (*core.IsSafeDomainResponse, error) {
va.stats.Inc("VA.IsSafeDomain.Requests", 1, 1.0)
if va.SafeBrowsing == nil {
va.stats.Inc("VA.IsSafeDomain.Skips", 1, 1.0)

View File

@ -36,25 +36,25 @@ func TestIsSafeDomain(t *testing.T) {
sbc.EXPECT().IsListed("outofdate.com").Return("", safebrowsing.ErrOutOfDateHashes)
va := NewValidationAuthorityImpl(&cmd.PortConfig{}, sbc, nil, stats, clock.NewFake())
resp, err := va.IsSafeDomain(&core.IsSafeDomainRequest{Domain: "good.com"})
resp, err := va.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: "good.com"})
if err != nil {
t.Errorf("good.com: want no error, got '%s'", err)
}
if !resp.IsSafe {
t.Errorf("good.com: want true, got %t", resp.IsSafe)
}
resp, err = va.IsSafeDomain(&core.IsSafeDomainRequest{Domain: "bad.com"})
resp, err = va.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: "bad.com"})
if err != nil {
t.Errorf("bad.com: want no error, got '%s'", err)
}
if resp.IsSafe {
t.Errorf("bad.com: want false, got %t", resp.IsSafe)
}
_, err = va.IsSafeDomain(&core.IsSafeDomainRequest{Domain: "errorful.com"})
_, err = va.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: "errorful.com"})
if err == nil {
t.Errorf("errorful.com: want error, got none")
}
resp, err = va.IsSafeDomain(&core.IsSafeDomainRequest{Domain: "outofdate.com"})
resp, err = va.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: "outofdate.com"})
if err != nil {
t.Errorf("outofdate.com: want no error, got '%s'", err)
}
@ -69,7 +69,7 @@ func TestAllowNilInIsSafeDomain(t *testing.T) {
// Be cool with a nil SafeBrowsing. This will happen in prod when we have
// flag mismatch between the VA and RA.
resp, err := va.IsSafeDomain(&core.IsSafeDomainRequest{Domain: "example.com"})
resp, err := va.IsSafeDomain(ctx, &core.IsSafeDomainRequest{Domain: "example.com"})
if err != nil {
t.Errorf("nil SafeBrowsing, unexpected error: %s", err)
} else if !resp.IsSafe {

View File

@ -575,7 +575,7 @@ func (va *ValidationAuthorityImpl) validate(ctx context.Context, authz core.Auth
va.log.Info(fmt.Sprintf("Validations: %+v", authz))
err := va.RA.OnValidationUpdate(authz)
err := va.RA.OnValidationUpdate(ctx, authz)
if err != nil {
va.log.Err(fmt.Sprintf("va: unable to communicate updated authz [%d] to RA: %q authz=[%#v]", authz.RegistrationID, err, authz))
}
@ -629,9 +629,9 @@ func (va *ValidationAuthorityImpl) validateChallenge(ctx context.Context, identi
// goroutines.
//
// TODO(#1167): remove this method
func (va *ValidationAuthorityImpl) UpdateValidations(authz core.Authorization, challengeIndex int) error {
func (va *ValidationAuthorityImpl) UpdateValidations(ctx context.Context, authz core.Authorization, challengeIndex int) error {
// TODO(#1292): add a proper deadline here
go va.validate(context.TODO(), authz, challengeIndex)
go va.validate(ctx, authz, challengeIndex)
return nil
}
@ -639,7 +639,7 @@ func (va *ValidationAuthorityImpl) UpdateValidations(authz core.Authorization, c
// updated Challenge.
//
// TODO(#1626): remove authz parameter
func (va *ValidationAuthorityImpl) PerformValidation(domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
func (va *ValidationAuthorityImpl) PerformValidation(ctx context.Context, domain string, challenge core.Challenge, authz core.Authorization) ([]core.ValidationRecord, error) {
logEvent := verificationRequestEvent{
ID: authz.ID,
Requester: authz.RegistrationID,
@ -648,7 +648,7 @@ func (va *ValidationAuthorityImpl) PerformValidation(domain string, challenge co
}
vStart := va.clk.Now()
records, prob := va.validateChallengeAndCAA(context.TODO(), core.AcmeIdentifier{Type: "dns", Value: domain}, challenge)
records, prob := va.validateChallengeAndCAA(ctx, core.AcmeIdentifier{Type: "dns", Value: domain}, challenge)
logEvent.ValidationRecords = records
resultStatus := core.StatusInvalid

View File

@ -68,6 +68,8 @@ var ident = core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "localhost"}
var log = blog.UseMock()
var ctx = context.Background()
// All paths that get assigned to tokens MUST be valid tokens
const expectedToken = "LoqXcYV8q5ONbJQxbmR7SCTNo3tiAXDfowyjxAjEuX0"
const pathWrongToken = "i6lNAC4lOOLYCl-A08VJt9z_tKYvVk63Dumo8icsBjQ"
@ -224,7 +226,7 @@ func TestHTTP(t *testing.T) {
va := NewValidationAuthorityImpl(&cmd.PortConfig{HTTPPort: badPort}, nil, nil, stats, clock.Default())
va.DNSResolver = &bdns.MockDNSResolver{}
_, prob := va.validateHTTP01(context.Background(), ident, chall)
_, prob := va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Server's down; expected refusal. Where did we connect?")
}
@ -235,7 +237,7 @@ func TestHTTP(t *testing.T) {
log.Clear()
t.Logf("Trying to validate: %+v\n", chall)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Errorf("Unexpected failure in HTTP validation: %s", prob)
}
@ -243,7 +245,7 @@ func TestHTTP(t *testing.T) {
log.Clear()
setChallengeToken(&chall, path404)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Should have found a 404 for the challenge.")
}
@ -254,7 +256,7 @@ func TestHTTP(t *testing.T) {
setChallengeToken(&chall, pathWrongToken)
// The "wrong token" will actually be the expectedToken. It's wrong
// because it doesn't match pathWrongToken.
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Should have found the wrong token value.")
}
@ -263,7 +265,7 @@ func TestHTTP(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathMoved)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Failed to follow 301 redirect")
}
@ -271,7 +273,7 @@ func TestHTTP(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathFound)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Failed to follow 302 redirect")
}
@ -279,13 +281,13 @@ func TestHTTP(t *testing.T) {
test.AssertEquals(t, len(log.GetAllMatching(`redirect from ".*/`+pathMoved+`" to ".*/`+pathValid+`"`)), 1)
ipIdentifier := core.AcmeIdentifier{Type: core.IdentifierType("ip"), Value: "127.0.0.1"}
_, prob = va.validateHTTP01(context.Background(), ipIdentifier, chall)
_, prob = va.validateHTTP01(ctx, ipIdentifier, chall)
if prob == nil {
t.Fatalf("IdentifierType IP shouldn't have worked.")
}
test.AssertEquals(t, prob.Type, probs.MalformedProblem)
_, prob = va.validateHTTP01(context.Background(), core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "always.invalid"}, chall)
_, prob = va.validateHTTP01(ctx, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "always.invalid"}, chall)
if prob == nil {
t.Fatalf("Domain name is invalid.")
}
@ -293,7 +295,7 @@ func TestHTTP(t *testing.T) {
setChallengeToken(&chall, pathWaitLong)
started := time.Now()
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
took := time.Since(started)
// Check that the HTTP connection times out after 5 seconds and doesn't block for 10 seconds
test.Assert(t, (took > (time.Second * 5)), "HTTP timed out before 5 seconds")
@ -318,7 +320,7 @@ func TestHTTPRedirectLookup(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathMoved)
_, prob := va.validateHTTP01(context.Background(), ident, chall)
_, prob := va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Unexpected failure in redirect (%s): %s", pathMoved, prob)
}
@ -327,7 +329,7 @@ func TestHTTPRedirectLookup(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathFound)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Unexpected failure in redirect (%s): %s", pathFound, prob)
}
@ -337,14 +339,14 @@ func TestHTTPRedirectLookup(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathReLookupInvalid)
_, err = va.validateHTTP01(context.Background(), ident, chall)
_, err = va.validateHTTP01(ctx, ident, chall)
test.AssertError(t, err, chall.Token)
test.AssertEquals(t, len(log.GetAllMatching(`Resolved addresses for localhost \[using 127.0.0.1\]: \[127.0.0.1\]`)), 1)
test.AssertEquals(t, len(log.GetAllMatching(`No IPv4 addresses found for invalid.invalid`)), 1)
log.Clear()
setChallengeToken(&chall, pathReLookup)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Unexpected error in redirect (%s): %s", pathReLookup, prob)
}
@ -354,7 +356,7 @@ func TestHTTPRedirectLookup(t *testing.T) {
log.Clear()
setChallengeToken(&chall, pathRedirectPort)
_, err = va.validateHTTP01(context.Background(), ident, chall)
_, err = va.validateHTTP01(ctx, ident, chall)
test.AssertError(t, err, chall.Token)
test.AssertEquals(t, len(log.GetAllMatching(`redirect from ".*/port-redirect" to ".*other.valid:8080/path"`)), 1)
test.AssertEquals(t, len(log.GetAllMatching(`Resolved addresses for localhost \[using 127.0.0.1\]: \[127.0.0.1\]`)), 1)
@ -374,7 +376,7 @@ func TestHTTPRedirectLoop(t *testing.T) {
va.DNSResolver = &bdns.MockDNSResolver{}
log.Clear()
_, prob := va.validateHTTP01(context.Background(), ident, chall)
_, prob := va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Challenge should have failed for %s", chall.Token)
}
@ -394,13 +396,13 @@ func TestHTTPRedirectUserAgent(t *testing.T) {
va.UserAgent = rejectUserAgent
setChallengeToken(&chall, pathMoved)
_, prob := va.validateHTTP01(context.Background(), ident, chall)
_, prob := va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Challenge with rejectUserAgent should have failed (%s).", pathMoved)
}
setChallengeToken(&chall, pathFound)
_, prob = va.validateHTTP01(context.Background(), ident, chall)
_, prob = va.validateHTTP01(ctx, ident, chall)
if prob == nil {
t.Fatalf("Challenge with rejectUserAgent should have failed (%s).", pathFound)
}
@ -435,14 +437,14 @@ func TestTLSSNI(t *testing.T) {
va.DNSResolver = &bdns.MockDNSResolver{}
log.Clear()
_, prob := va.validateTLSSNI01(context.Background(), ident, chall)
_, prob := va.validateTLSSNI01(ctx, ident, chall)
if prob != nil {
t.Fatalf("Unexpected failre in validateTLSSNI01: %s", prob)
}
test.AssertEquals(t, len(log.GetAllMatching(`Resolved addresses for localhost \[using 127.0.0.1\]: \[127.0.0.1\]`)), 1)
log.Clear()
_, prob = va.validateTLSSNI01(context.Background(), core.AcmeIdentifier{
_, prob = va.validateTLSSNI01(ctx, core.AcmeIdentifier{
Type: core.IdentifierType("ip"),
Value: net.JoinHostPort("127.0.0.1", fmt.Sprintf("%d", port)),
}, chall)
@ -452,7 +454,7 @@ func TestTLSSNI(t *testing.T) {
test.AssertEquals(t, prob.Type, probs.MalformedProblem)
log.Clear()
_, prob = va.validateTLSSNI01(context.Background(), core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "always.invalid"}, chall)
_, prob = va.validateTLSSNI01(ctx, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "always.invalid"}, chall)
if prob == nil {
t.Fatalf("Domain name was supposed to be invalid.")
}
@ -464,7 +466,7 @@ func TestTLSSNI(t *testing.T) {
log.Clear()
started := time.Now()
_, prob = va.validateTLSSNI01(context.Background(), ident, chall)
_, prob = va.validateTLSSNI01(ctx, ident, chall)
took := time.Since(started)
// Check that the HTTP connection times out after 5 seconds and doesn't block for 10 seconds
test.Assert(t, (took > (time.Second * 5)), "HTTP timed out before 5 seconds")
@ -477,7 +479,7 @@ func TestTLSSNI(t *testing.T) {
// Take down validation server and check that validation fails.
hs.Close()
_, err = va.validateTLSSNI01(context.Background(), ident, chall)
_, err = va.validateTLSSNI01(ctx, ident, chall)
if err == nil {
t.Fatalf("Server's down; expected refusal. Where did we connect?")
}
@ -505,7 +507,7 @@ func TestTLSError(t *testing.T) {
va := NewValidationAuthorityImpl(&cmd.PortConfig{TLSPort: port}, nil, nil, stats, clock.Default())
va.DNSResolver = &bdns.MockDNSResolver{}
_, prob := va.validateTLSSNI01(context.Background(), ident, chall)
_, prob := va.validateTLSSNI01(ctx, ident, chall)
if prob == nil {
t.Fatalf("TLS validation should have failed: What cert was used?")
}
@ -533,7 +535,7 @@ func TestValidateHTTP(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chall},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertEquals(t, core.StatusValid, mockRA.lastAuthz.Challenges[0].Status)
}
@ -585,7 +587,7 @@ func TestValidateTLSSNI01(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chall},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertEquals(t, core.StatusValid, mockRA.lastAuthz.Challenges[0].Status)
}
@ -607,7 +609,7 @@ func TestValidateTLSSNINotSane(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chall},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertEquals(t, core.StatusInvalid, mockRA.lastAuthz.Challenges[0].Status)
}
@ -631,7 +633,7 @@ func TestUpdateValidations(t *testing.T) {
}
started := time.Now()
err := va.UpdateValidations(authz, 0)
err := va.UpdateValidations(ctx, authz, 0)
if err != nil {
test.AssertNotError(t, err, "UpdateValidations failed")
}
@ -646,7 +648,7 @@ func TestCAATimeout(t *testing.T) {
va := NewValidationAuthorityImpl(&cmd.PortConfig{}, nil, nil, stats, clock.Default())
va.DNSResolver = &bdns.MockDNSResolver{}
va.IssuerDomain = "letsencrypt.org"
err := va.checkCAA(context.Background(), core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "caa-timeout.com"})
err := va.checkCAA(ctx, core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "caa-timeout.com"})
if err.Type != probs.ConnectionProblem {
t.Errorf("Expected timeout error type %s, got %s", probs.ConnectionProblem, err.Type)
}
@ -692,7 +694,7 @@ func TestCAAChecking(t *testing.T) {
va.DNSResolver = &bdns.MockDNSResolver{}
va.IssuerDomain = "letsencrypt.org"
for _, caaTest := range tests {
present, valid, err := va.checkCAARecords(context.Background(), core.AcmeIdentifier{Type: "dns", Value: caaTest.Domain})
present, valid, err := va.checkCAARecords(ctx, core.AcmeIdentifier{Type: "dns", Value: caaTest.Domain})
if err != nil {
t.Errorf("CheckCAARecords error for %s: %s", caaTest.Domain, err)
}
@ -704,22 +706,22 @@ func TestCAAChecking(t *testing.T) {
}
}
present, valid, err := va.checkCAARecords(context.Background(), core.AcmeIdentifier{Type: "dns", Value: "servfail.com"})
present, valid, err := va.checkCAARecords(ctx, core.AcmeIdentifier{Type: "dns", Value: "servfail.com"})
test.AssertError(t, err, "servfail.com")
test.Assert(t, !present, "Present should be false")
test.Assert(t, !valid, "Valid should be false")
_, _, err = va.checkCAARecords(context.Background(), core.AcmeIdentifier{Type: "dns", Value: "servfail.com"})
_, _, err = va.checkCAARecords(ctx, core.AcmeIdentifier{Type: "dns", Value: "servfail.com"})
if err == nil {
t.Errorf("Should have returned error on CAA lookup, but did not: %s", "servfail.com")
}
present, valid, err = va.checkCAARecords(context.Background(), core.AcmeIdentifier{Type: "dns", Value: "servfail.present.com"})
present, valid, err = va.checkCAARecords(ctx, core.AcmeIdentifier{Type: "dns", Value: "servfail.present.com"})
test.AssertError(t, err, "servfail.present.com")
test.Assert(t, !present, "Present should be false")
test.Assert(t, !valid, "Valid should be false")
_, _, err = va.checkCAARecords(context.Background(), core.AcmeIdentifier{Type: "dns", Value: "servfail.present.com"})
_, _, err = va.checkCAARecords(ctx, core.AcmeIdentifier{Type: "dns", Value: "servfail.present.com"})
if err == nil {
t.Errorf("Should have returned error on CAA lookup, but did not: %s", "servfail.present.com")
}
@ -740,7 +742,7 @@ func TestDNSValidationFailure(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chalDNS},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
t.Logf("Resulting Authz: %+v", authz)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
@ -770,7 +772,7 @@ func TestDNSValidationInvalid(t *testing.T) {
mockRA := &MockRegistrationAuthority{}
va.RA = mockRA
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
test.Assert(t, authz.Challenges[0].Status == core.StatusInvalid, "Should be invalid.")
@ -804,7 +806,7 @@ func TestDNSValidationNotSane(t *testing.T) {
}
for i := 0; i < len(authz.Challenges); i++ {
va.validate(context.Background(), authz, i)
va.validate(ctx, authz, i)
test.AssertEquals(t, authz.Challenges[i].Status, core.StatusInvalid)
test.AssertEquals(t, authz.Challenges[i].Error.Type, probs.MalformedProblem)
if !strings.Contains(authz.Challenges[i].Error.Error(), "Challenge failed sanity check.") {
@ -832,7 +834,7 @@ func TestDNSValidationServFail(t *testing.T) {
Identifier: badIdent,
Challenges: []core.Challenge{chalDNS},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
test.Assert(t, authz.Challenges[0].Status == core.StatusInvalid, "Should be invalid.")
@ -855,7 +857,7 @@ func TestDNSValidationNoServer(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chalDNS},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
test.Assert(t, authz.Challenges[0].Status == core.StatusInvalid, "Should be invalid.")
@ -886,7 +888,7 @@ func TestDNSValidationOK(t *testing.T) {
Identifier: goodIdent,
Challenges: []core.Challenge{chalDNS},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
test.Assert(t, authz.Challenges[0].Status == core.StatusValid, "Should be valid.")
@ -916,7 +918,7 @@ func TestDNSValidationNoAuthorityOK(t *testing.T) {
Identifier: goodIdent,
Challenges: []core.Challenge{chalDNS},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertNotNil(t, mockRA.lastAuthz, "Should have gotten an authorization")
test.Assert(t, authz.Challenges[0].Status == core.StatusValid, "Should be valid.")
@ -954,7 +956,7 @@ func TestDNSValidationLive(t *testing.T) {
Challenges: []core.Challenge{goodChalDNS},
}
va.validate(context.Background(), authzGood, 0)
va.validate(ctx, authzGood, 0)
if authzGood.Challenges[0].Status != core.StatusValid {
t.Logf("TestDNSValidationLive on Good did not succeed.")
@ -971,7 +973,7 @@ func TestDNSValidationLive(t *testing.T) {
Challenges: []core.Challenge{badChalDNS},
}
va.validate(context.Background(), authzBad, 0)
va.validate(ctx, authzBad, 0)
if authzBad.Challenges[0].Status != core.StatusInvalid {
t.Logf("TestDNSValidationLive on Bad did succeed inappropriately.")
}
@ -998,7 +1000,7 @@ func TestCAAFailure(t *testing.T) {
Identifier: ident,
Challenges: []core.Challenge{chall},
}
va.validate(context.Background(), authz, 0)
va.validate(ctx, authz, 0)
test.AssertEquals(t, core.StatusInvalid, mockRA.lastAuthz.Challenges[0].Status)
}
@ -1007,35 +1009,35 @@ type MockRegistrationAuthority struct {
lastAuthz *core.Authorization
}
func (ra *MockRegistrationAuthority) NewRegistration(reg core.Registration) (core.Registration, error) {
func (ra *MockRegistrationAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) {
return reg, nil
}
func (ra *MockRegistrationAuthority) NewAuthorization(authz core.Authorization, regID int64) (core.Authorization, error) {
func (ra *MockRegistrationAuthority) NewAuthorization(ctx context.Context, authz core.Authorization, regID int64) (core.Authorization, error) {
return authz, nil
}
func (ra *MockRegistrationAuthority) NewCertificate(req core.CertificateRequest, regID int64) (core.Certificate, error) {
func (ra *MockRegistrationAuthority) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) {
return core.Certificate{}, nil
}
func (ra *MockRegistrationAuthority) UpdateRegistration(reg core.Registration, updated core.Registration) (core.Registration, error) {
func (ra *MockRegistrationAuthority) UpdateRegistration(ctx context.Context, reg core.Registration, updated core.Registration) (core.Registration, error) {
return reg, nil
}
func (ra *MockRegistrationAuthority) UpdateAuthorization(authz core.Authorization, foo int, challenge core.Challenge) (core.Authorization, error) {
func (ra *MockRegistrationAuthority) UpdateAuthorization(ctx context.Context, authz core.Authorization, foo int, challenge core.Challenge) (core.Authorization, error) {
return authz, nil
}
func (ra *MockRegistrationAuthority) RevokeCertificateWithReg(cert x509.Certificate, reason core.RevocationCode, reg int64) error {
func (ra *MockRegistrationAuthority) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, reg int64) error {
return nil
}
func (ra *MockRegistrationAuthority) AdministrativelyRevokeCertificate(cert x509.Certificate, reason core.RevocationCode, user string) error {
func (ra *MockRegistrationAuthority) AdministrativelyRevokeCertificate(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, user string) error {
return nil
}
func (ra *MockRegistrationAuthority) OnValidationUpdate(authz core.Authorization) error {
func (ra *MockRegistrationAuthority) OnValidationUpdate(ctx context.Context, authz core.Authorization) error {
ra.lastAuthz = &authz
return nil
}

View File

@ -107,7 +107,7 @@ func CountLabel(s string) (labels int) {
// Split splits a name s into its label indexes.
// www.miek.nl. returns []int{0, 4, 9}, www.miek.nl also returns []int{0, 4, 9}.
// The root name (.) returns nil. Also see SplitDomainName.
// The root name (.) returns nil. Also see SplitDomainName.
// s must be a syntactically valid domain name.
func Split(s string) []int {
if s == "." {

View File

@ -6,6 +6,8 @@ import (
"net/http"
"time"
"golang.org/x/net/context"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
blog "github.com/letsencrypt/boulder/log"
@ -32,10 +34,11 @@ func (e *requestEvent) AddError(msg string, args ...interface{}) {
e.Errors = append(e.Errors, fmt.Sprintf(msg, args...))
}
type wfeHandlerFunc func(*requestEvent, http.ResponseWriter, *http.Request)
type wfeHandlerFunc func(context.Context, *requestEvent, http.ResponseWriter, *http.Request)
func (f wfeHandlerFunc) ServeHTTP(e *requestEvent, w http.ResponseWriter, r *http.Request) {
f(e, w, r)
ctx := context.TODO()
f(ctx, e, w, r)
}
type wfeHandler interface {

View File

@ -11,7 +11,7 @@ import (
func TestRejectsNone(t *testing.T) {
wfe, _ := setupWFE(t)
_, _, _, prob := wfe.verifyPOST(newRequestEvent(), makePostRequest(`
_, _, _, prob := wfe.verifyPOST(ctx, newRequestEvent(), makePostRequest(`
{
"header": {
"alg": "none",
@ -35,7 +35,7 @@ func TestRejectsNone(t *testing.T) {
func TestRejectsHS256(t *testing.T) {
wfe, _ := setupWFE(t)
_, _, _, prob := wfe.verifyPOST(newRequestEvent(), makePostRequest(`
_, _, _, prob := wfe.verifyPOST(ctx, newRequestEvent(), makePostRequest(`
{
"header": {
"alg": "HS256",

View File

@ -18,6 +18,8 @@ import (
"strings"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/core"
@ -87,6 +89,9 @@ type WebFrontEndImpl struct {
// CORS settings
AllowOrigins []string
// Maximum duration of a request
RequestTimeout time.Duration
// Graceful shutdown settings
ShutdownStopTimeout time.Duration
ShutdownKillTimeout time.Duration
@ -140,7 +145,7 @@ func (wfe *WebFrontEndImpl) HandleFunc(mux *http.ServeMux, pattern string, h wfe
mux.Handle(pattern, &topHandler{
log: wfe.log,
clk: clock.Default(),
wfe: wfeHandlerFunc(func(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
wfe: wfeHandlerFunc(func(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
// We do not propagate errors here, because (1) they should be
// transient, and (2) they fail closed.
nonce, err := wfe.nonceService.Nonce()
@ -169,8 +174,16 @@ func (wfe *WebFrontEndImpl) HandleFunc(mux *http.ServeMux, pattern string, h wfe
wfe.setCORSHeaders(response, request, "")
timeout := wfe.RequestTimeout
if timeout == 0 {
timeout = 5 * time.Minute
}
ctx, cancel := context.WithTimeout(ctx, timeout)
// TODO(riking): add request context using WithValue
// Call the wrapped handler.
h(logEvent, response, request)
h(ctx, logEvent, response, request)
cancel()
}),
})
}
@ -226,7 +239,7 @@ func (wfe *WebFrontEndImpl) Handler() (http.Handler, error) {
// Method implementations
// Index serves a simple identification page. It is not part of the ACME spec.
func (wfe *WebFrontEndImpl) Index(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Index(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
// http://golang.org/pkg/net/http/#example_ServeMux_Handle
// The "/" pattern matches everything, so we need to check
// that we're at the root here.
@ -266,7 +279,7 @@ func addCacheHeader(w http.ResponseWriter, age float64) {
// Directory is an HTTP request handler that simply provides the directory
// object stored in the WFE's DirectoryJSON member.
func (wfe *WebFrontEndImpl) Directory(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Directory(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "application/json")
response.Write(wfe.DirectoryJSON)
}
@ -293,7 +306,7 @@ const (
// the key itself. verifyPOST also appends its errors to requestEvent.Errors so
// code calling it does not need to if they immediately return a response to the
// user.
func (wfe *WebFrontEndImpl) verifyPOST(logEvent *requestEvent, request *http.Request, regCheck bool, resource core.AcmeResource) ([]byte, *jose.JsonWebKey, core.Registration, *probs.ProblemDetails) {
func (wfe *WebFrontEndImpl) verifyPOST(ctx context.Context, logEvent *requestEvent, request *http.Request, regCheck bool, resource core.AcmeResource) ([]byte, *jose.JsonWebKey, core.Registration, *probs.ProblemDetails) {
// TODO: We should return a pointer to a registration, which can be nil,
// rather the a registration value with a sentinel value.
// https://github.com/letsencrypt/boulder/issues/877
@ -353,7 +366,7 @@ func (wfe *WebFrontEndImpl) verifyPOST(logEvent *requestEvent, request *http.Req
}
var key *jose.JsonWebKey
reg, err = wfe.SA.GetRegistrationByKey(*submittedKey)
reg, err = wfe.SA.GetRegistrationByKey(ctx, *submittedKey)
// Special case: If no registration was found, but regCheck is false, use an
// empty registration and the submitted key. The caller is expected to do some
// validation on the returned key.
@ -476,16 +489,16 @@ func link(url, relation string) string {
}
// NewRegistration is used by clients to submit a new registration/account
func (wfe *WebFrontEndImpl) NewRegistration(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) NewRegistration(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, key, _, prob := wfe.verifyPOST(logEvent, request, false, core.ResourceNewReg)
body, key, _, prob := wfe.verifyPOST(ctx, logEvent, request, false, core.ResourceNewReg)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
return
}
if existingReg, err := wfe.SA.GetRegistrationByKey(*key); err == nil {
if existingReg, err := wfe.SA.GetRegistrationByKey(ctx, *key); err == nil {
response.Header().Set("Location", fmt.Sprintf("%s%d", wfe.RegBase, existingReg.ID))
// TODO(#595): check for missing registration err
wfe.sendError(response, logEvent, probs.Conflict("Registration key is already in use"), err)
@ -516,7 +529,7 @@ func (wfe *WebFrontEndImpl) NewRegistration(logEvent *requestEvent, response htt
}
}
reg, err := wfe.RA.NewRegistration(init)
reg, err := wfe.RA.NewRegistration(ctx, init)
if err != nil {
logEvent.AddError("unable to create new registration: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Error creating new registration"), err)
@ -549,8 +562,8 @@ func (wfe *WebFrontEndImpl) NewRegistration(logEvent *requestEvent, response htt
}
// NewAuthorization is used by clients to submit a new ID Authorization
func (wfe *WebFrontEndImpl) NewAuthorization(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, _, currReg, prob := wfe.verifyPOST(logEvent, request, true, core.ResourceNewAuthz)
func (wfe *WebFrontEndImpl) NewAuthorization(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceNewAuthz)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
@ -573,7 +586,7 @@ func (wfe *WebFrontEndImpl) NewAuthorization(logEvent *requestEvent, response ht
logEvent.Extra["Identifier"] = init.Identifier
// Create new authz and return
authz, err := wfe.RA.NewAuthorization(init, currReg.ID)
authz, err := wfe.RA.NewAuthorization(ctx, init, currReg.ID)
if err != nil {
logEvent.AddError("unable to create new authz: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Error creating new authz"), err)
@ -602,11 +615,11 @@ func (wfe *WebFrontEndImpl) NewAuthorization(logEvent *requestEvent, response ht
}
// RevokeCertificate is used by clients to request the revocation of a cert.
func (wfe *WebFrontEndImpl) RevokeCertificate(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) RevokeCertificate(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
// We don't ask verifyPOST to verify there is a corresponding registration,
// because anyone with the right private key can revoke a certificate.
body, requestKey, registration, prob := wfe.verifyPOST(logEvent, request, false, core.ResourceRevokeCert)
body, requestKey, registration, prob := wfe.verifyPOST(ctx, logEvent, request, false, core.ResourceRevokeCert)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
@ -631,7 +644,7 @@ func (wfe *WebFrontEndImpl) RevokeCertificate(logEvent *requestEvent, response h
serial := core.SerialToString(providedCert.SerialNumber)
logEvent.Extra["ProvidedCertificateSerial"] = serial
cert, err := wfe.SA.GetCertificate(serial)
cert, err := wfe.SA.GetCertificate(ctx, serial)
// TODO(#991): handle db errors better
if err != nil || !bytes.Equal(cert.DER, revokeRequest.CertificateDER) {
wfe.sendError(response, logEvent, probs.NotFound("No such certificate"), err)
@ -648,7 +661,7 @@ func (wfe *WebFrontEndImpl) RevokeCertificate(logEvent *requestEvent, response h
logEvent.Extra["RetrievedCertificateEmailAddresses"] = parsedCertificate.EmailAddresses
logEvent.Extra["RetrievedCertificateIPAddresses"] = parsedCertificate.IPAddresses
certStatus, err := wfe.SA.GetCertificateStatus(serial)
certStatus, err := wfe.SA.GetCertificateStatus(ctx, serial)
if err != nil {
logEvent.AddError("unable to get certificate status: %s", err)
// TODO(#991): handle db errors
@ -673,7 +686,7 @@ func (wfe *WebFrontEndImpl) RevokeCertificate(logEvent *requestEvent, response h
}
// Use revocation code 0, meaning "unspecified"
err = wfe.RA.RevokeCertificateWithReg(*parsedCertificate, 0, registration.ID)
err = wfe.RA.RevokeCertificateWithReg(ctx, *parsedCertificate, 0, registration.ID)
if err != nil {
logEvent.AddError("failed to revoke certificate: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Failed to revoke certificate"), err)
@ -698,8 +711,8 @@ func (wfe *WebFrontEndImpl) logCsr(request *http.Request, cr core.CertificateReq
// NewCertificate is used by clients to request the issuance of a cert for an
// authorized identifier.
func (wfe *WebFrontEndImpl) NewCertificate(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, _, reg, prob := wfe.verifyPOST(logEvent, request, true, core.ResourceNewCert)
func (wfe *WebFrontEndImpl) NewCertificate(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, _, reg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceNewCert)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
@ -741,7 +754,7 @@ func (wfe *WebFrontEndImpl) NewCertificate(logEvent *requestEvent, response http
// authorized for target site, they could cause issuance for that site by
// lying to the RA. We should probably pass a copy of the whole rquest to the
// RA for secondary validation.
cert, err := wfe.RA.NewCertificate(certificateRequest, reg.ID)
cert, err := wfe.RA.NewCertificate(ctx, certificateRequest, reg.ID)
if err != nil {
logEvent.AddError("unable to create new cert: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Error creating new cert"), err)
@ -775,6 +788,7 @@ func (wfe *WebFrontEndImpl) NewCertificate(logEvent *requestEvent, response http
// Challenge handles POST requests to challenge URLs. Such requests are clients'
// responses to the server's challenges.
func (wfe *WebFrontEndImpl) Challenge(
ctx context.Context,
logEvent *requestEvent,
response http.ResponseWriter,
request *http.Request) {
@ -800,7 +814,7 @@ func (wfe *WebFrontEndImpl) Challenge(
logEvent.Extra["AuthorizationID"] = authorizationID
logEvent.Extra["ChallengeID"] = challengeID
authz, err := wfe.SA.GetAuthorization(authorizationID)
authz, err := wfe.SA.GetAuthorization(ctx, authorizationID)
if err != nil {
// TODO(#1198): handle db errors etc
notFound()
@ -830,10 +844,10 @@ func (wfe *WebFrontEndImpl) Challenge(
switch request.Method {
case "GET", "HEAD":
wfe.getChallenge(response, request, authz, &challenge, logEvent)
wfe.getChallenge(ctx, response, request, authz, &challenge, logEvent)
case "POST":
wfe.postChallenge(response, request, authz, challengeIndex, logEvent)
wfe.postChallenge(ctx, response, request, authz, challengeIndex, logEvent)
}
}
@ -861,6 +875,7 @@ func (wfe *WebFrontEndImpl) prepAuthorizationForDisplay(authz *core.Authorizatio
}
func (wfe *WebFrontEndImpl) getChallenge(
ctx context.Context,
response http.ResponseWriter,
request *http.Request,
authz core.Authorization,
@ -891,12 +906,13 @@ func (wfe *WebFrontEndImpl) getChallenge(
}
func (wfe *WebFrontEndImpl) postChallenge(
ctx context.Context,
response http.ResponseWriter,
request *http.Request,
authz core.Authorization,
challengeIndex int,
logEvent *requestEvent) {
body, _, currReg, prob := wfe.verifyPOST(logEvent, request, true, core.ResourceChallenge)
body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceChallenge)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
@ -930,7 +946,7 @@ func (wfe *WebFrontEndImpl) postChallenge(
}
// Ask the RA to update this authorization
updatedAuthorization, err := wfe.RA.UpdateAuthorization(authz, challengeIndex, challengeUpdate)
updatedAuthorization, err := wfe.RA.UpdateAuthorization(ctx, authz, challengeIndex, challengeUpdate)
if err != nil {
logEvent.AddError("unable to update challenge: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Unable to update challenge"), err)
@ -961,9 +977,9 @@ func (wfe *WebFrontEndImpl) postChallenge(
}
// Registration is used by a client to submit an update to their registration.
func (wfe *WebFrontEndImpl) Registration(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Registration(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
body, _, currReg, prob := wfe.verifyPOST(logEvent, request, true, core.ResourceRegistration)
body, _, currReg, prob := wfe.verifyPOST(ctx, logEvent, request, true, core.ResourceRegistration)
if prob != nil {
// verifyPOST handles its own setting of logEvent.Errors
wfe.sendError(response, logEvent, prob, nil)
@ -1011,7 +1027,7 @@ func (wfe *WebFrontEndImpl) Registration(logEvent *requestEvent, response http.R
update.Key = currReg.Key
// Ask the RA to update this authorization.
updatedReg, err := wfe.RA.UpdateRegistration(currReg, update)
updatedReg, err := wfe.RA.UpdateRegistration(ctx, currReg, update)
if err != nil {
logEvent.AddError("unable to update registration: %s", err)
wfe.sendError(response, logEvent, core.ProblemDetailsForError(err, "Unable to update registration"), err)
@ -1036,10 +1052,10 @@ func (wfe *WebFrontEndImpl) Registration(logEvent *requestEvent, response http.R
// Authorization is used by clients to submit an update to one of their
// authorizations.
func (wfe *WebFrontEndImpl) Authorization(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Authorization(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
// Requests to this handler should have a path that leads to a known authz
id := parseIDFromPath(request.URL.Path)
authz, err := wfe.SA.GetAuthorization(id)
authz, err := wfe.SA.GetAuthorization(ctx, id)
if err != nil {
logEvent.AddError("No such authorization at id %s", id)
// TODO(#1199): handle db errors
@ -1082,7 +1098,7 @@ var allHex = regexp.MustCompile("^[0-9a-f]+$")
// Certificate is used by clients to request a copy of their current certificate, or to
// request a reissuance of the certificate.
func (wfe *WebFrontEndImpl) Certificate(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Certificate(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
path := request.URL.Path
// Certificate paths consist of the CertBase path, plus exactly sixteen hex
@ -1102,7 +1118,7 @@ func (wfe *WebFrontEndImpl) Certificate(logEvent *requestEvent, response http.Re
}
logEvent.Extra["RequestedSerial"] = serial
cert, err := wfe.SA.GetCertificate(serial)
cert, err := wfe.SA.GetCertificate(ctx, serial)
// TODO(#991): handle db errors
if err != nil {
logEvent.AddError("unable to get certificate by serial id %#v: %s", serial, err)
@ -1130,12 +1146,12 @@ func (wfe *WebFrontEndImpl) Certificate(logEvent *requestEvent, response http.Re
// Terms is used by the client to obtain the current Terms of Service /
// Subscriber Agreement to which the subscriber must agree.
func (wfe *WebFrontEndImpl) Terms(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Terms(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
http.Redirect(response, request, wfe.SubscriberAgreementURL, http.StatusFound)
}
// Issuer obtains the issuer certificate used by this instance of Boulder.
func (wfe *WebFrontEndImpl) Issuer(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) Issuer(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
addCacheHeader(response, wfe.IssuerCacheDuration.Seconds())
// TODO Content negotiation
@ -1148,7 +1164,7 @@ func (wfe *WebFrontEndImpl) Issuer(logEvent *requestEvent, response http.Respons
}
// BuildID tells the requestor what build we're running.
func (wfe *WebFrontEndImpl) BuildID(logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
func (wfe *WebFrontEndImpl) BuildID(ctx context.Context, logEvent *requestEvent, response http.ResponseWriter, request *http.Request) {
response.Header().Set("Content-Type", "text/plain")
response.WriteHeader(http.StatusOK)
detailsString := fmt.Sprintf("Boulder=(%s %s)", core.GetBuildID(), core.GetBuildTime())

View File

@ -24,6 +24,8 @@ import (
"testing"
"time"
"golang.org/x/net/context"
"github.com/cactus/go-statsd-client/statsd"
"github.com/jmhodges/clock"
"github.com/letsencrypt/boulder/probs"
@ -142,37 +144,37 @@ EeMZ9nWyIM6bktLrE11HnFOnKhAYsM5fZA==
type MockRegistrationAuthority struct{}
func (ra *MockRegistrationAuthority) NewRegistration(reg core.Registration) (core.Registration, error) {
func (ra *MockRegistrationAuthority) NewRegistration(ctx context.Context, reg core.Registration) (core.Registration, error) {
return reg, nil
}
func (ra *MockRegistrationAuthority) NewAuthorization(authz core.Authorization, regID int64) (core.Authorization, error) {
func (ra *MockRegistrationAuthority) NewAuthorization(ctx context.Context, authz core.Authorization, regID int64) (core.Authorization, error) {
authz.RegistrationID = regID
authz.ID = "bkrPh2u0JUf18-rVBZtOOWWb3GuIiliypL-hBM9Ak1Q"
return authz, nil
}
func (ra *MockRegistrationAuthority) NewCertificate(req core.CertificateRequest, regID int64) (core.Certificate, error) {
func (ra *MockRegistrationAuthority) NewCertificate(ctx context.Context, req core.CertificateRequest, regID int64) (core.Certificate, error) {
return core.Certificate{}, nil
}
func (ra *MockRegistrationAuthority) UpdateRegistration(reg core.Registration, updated core.Registration) (core.Registration, error) {
func (ra *MockRegistrationAuthority) UpdateRegistration(ctx context.Context, reg core.Registration, updated core.Registration) (core.Registration, error) {
return reg, nil
}
func (ra *MockRegistrationAuthority) UpdateAuthorization(authz core.Authorization, foo int, challenge core.Challenge) (core.Authorization, error) {
func (ra *MockRegistrationAuthority) UpdateAuthorization(ctx context.Context, authz core.Authorization, foo int, challenge core.Challenge) (core.Authorization, error) {
return authz, nil
}
func (ra *MockRegistrationAuthority) RevokeCertificateWithReg(cert x509.Certificate, reason core.RevocationCode, reg int64) error {
func (ra *MockRegistrationAuthority) RevokeCertificateWithReg(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, reg int64) error {
return nil
}
func (ra *MockRegistrationAuthority) AdministrativelyRevokeCertificate(cert x509.Certificate, reason core.RevocationCode, user string) error {
func (ra *MockRegistrationAuthority) AdministrativelyRevokeCertificate(ctx context.Context, cert x509.Certificate, reason core.RevocationCode, user string) error {
return nil
}
func (ra *MockRegistrationAuthority) OnValidationUpdate(authz core.Authorization) error {
func (ra *MockRegistrationAuthority) OnValidationUpdate(ctx context.Context, authz core.Authorization) error {
return nil
}
@ -209,6 +211,8 @@ var testKeyPolicy = core.KeyPolicy{
AllowECDSANISTP384: true,
}
var ctx = context.Background()
func setupWFE(t *testing.T) (WebFrontEndImpl, clock.FakeClock) {
fc := clock.NewFake()
stats, _ := statsd.NewNoopClient()
@ -284,7 +288,7 @@ func TestHandleFunc(t *testing.T) {
mux = http.NewServeMux()
rw = httptest.NewRecorder()
stubCalled = false
wfe.HandleFunc(mux, "/test", func(*requestEvent, http.ResponseWriter, *http.Request) {
wfe.HandleFunc(mux, "/test", func(context.Context, *requestEvent, http.ResponseWriter, *http.Request) {
stubCalled = true
}, allowed...)
req.URL = mustParseURL("/test")
@ -476,7 +480,7 @@ func TestIndexPOST(t *testing.T) {
wfe, _ := setupWFE(t)
responseWriter := httptest.NewRecorder()
url, _ := url.Parse("/")
wfe.Index(newRequestEvent(), responseWriter, &http.Request{
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "POST",
URL: url,
})
@ -487,7 +491,7 @@ func TestPOST404(t *testing.T) {
wfe, _ := setupWFE(t)
responseWriter := httptest.NewRecorder()
url, _ := url.Parse("/foobar")
wfe.Index(newRequestEvent(), responseWriter, &http.Request{
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "POST",
URL: url,
})
@ -501,7 +505,7 @@ func TestIndex(t *testing.T) {
responseWriter := httptest.NewRecorder()
url, _ := url.Parse("/")
wfe.Index(newRequestEvent(), responseWriter, &http.Request{
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "GET",
URL: url,
})
@ -514,7 +518,7 @@ func TestIndex(t *testing.T) {
responseWriter.Body.Reset()
responseWriter.Header().Del("Cache-Control")
url, _ = url.Parse("/foo")
wfe.Index(newRequestEvent(), responseWriter, &http.Request{
wfe.Index(ctx, newRequestEvent(), responseWriter, &http.Request{
URL: url,
})
//test.AssertEquals(t, responseWriter.Code, http.StatusNotFound)
@ -582,7 +586,7 @@ func TestIssueCertificate(t *testing.T) {
// POST, but no body.
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter, &http.Request{
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "POST",
Header: map[string][]string{
"Content-Length": {"0"},
@ -594,14 +598,14 @@ func TestIssueCertificate(t *testing.T) {
// POST, but body that isn't valid JWS
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter, makePostRequest("hi"))
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter, makePostRequest("hi"))
test.AssertEquals(t,
responseWriter.Body.String(),
`{"type":"urn:acme:error:malformed","detail":"Parse error reading JWS","status":400}`)
// POST, Properly JWS-signed, but payload is "foo", not base64-encoded JSON.
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, "foo", wfe.nonceService)))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -609,7 +613,7 @@ func TestIssueCertificate(t *testing.T) {
// Valid, signed JWS body, payload is '{}'
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(
signRequest(t, "{}", wfe.nonceService)))
test.AssertEquals(t,
@ -618,7 +622,7 @@ func TestIssueCertificate(t *testing.T) {
// Valid, signed JWS body, payload is '{"resource":"new-cert"}'
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, `{"resource":"new-cert"}`, wfe.nonceService)))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -629,7 +633,7 @@ func TestIssueCertificate(t *testing.T) {
// openssl req -outform der -new -nodes -key wfe/test/178.key -subj /CN=foo.com | \
// sed 's/foo.com/fob.com/' | b64url
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(),
wfe.NewCertificate(ctx, newRequestEvent(),
responseWriter,
makePostRequest(signRequest(t, `{
"resource":"new-cert",
@ -643,7 +647,7 @@ func TestIssueCertificate(t *testing.T) {
// openssl req -outform der -new -nodes -key wfe/test/178.key -subj /CN=meep.com | b64url
mockLog.Clear()
responseWriter.Body.Reset()
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, `{
"resource":"new-cert",
"csr": "MIICWDCCAUACAQAwEzERMA8GA1UEAwwIbWVlcC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCaqzue57mgXEoGTZZoVkkCZraebWgXI8irX2BgQB1A3iZa9onxGPMcWQMxhSuUisbEJi4UkMcVST12HX01rUwhj41UuBxJvI1w4wvdstssTAaa9c9tsQ5-UED2bFRL1MsyBdbmCF_-pu3i-ZIYqWgiKbjVBe3nlAVbo77zizwp3Y4Tp1_TBOwTAuFkHePmkNT63uPm9My_hNzsSm1o-Q519Cf7ry-JQmOVgz_jIgFVGFYJ17EV3KUIpUuDShuyCFATBQspgJSN2DoXRUlQjXXkNTj23OxxdT_cVLcLJjytyG6e5izME2R2aCkDBWIc1a4_sRJ0R396auPXG6KhJ7o_AgMBAAGgADANBgkqhkiG9w0BAQsFAAOCAQEALu046p76aKgvoAEHFINkMTgKokPXf9mZ4IZx_BKz-qs1MPMxVtPIrQDVweBH6tYT7Hfj2naLry6SpZ3vUNP_FYeTFWgW1V03LiqacX-QQgbEYtn99Dt3ScGyzb7EH833ztb3vDJ_-ha_CJplIrg-kHBBrlLFWXhh-I9K1qLRTNpbhZ18ooFde4Sbhkw9o9fKivGhx9aYr7ZbjRsNtKit_DsG1nwEXz53TMJ2vB9IQY29coJv_n5NFLkvBfzbG5faRNiFcimPYBO2jFdaA2mWzfxltLtwMF_dBwzTXDpMo3TVT9zEdV8YpsWqr63igqGDZVpKenlkqvRTeGJVayVuMA"
@ -656,7 +660,7 @@ func TestIssueCertificate(t *testing.T) {
mockLog.Clear()
responseWriter.Body.Reset()
// openssl req -outform der -new -nodes -key wfe/test/178.key -subj /CN=not-an-example.com | b64url
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, `{
"resource":"new-cert",
"csr": "MIICYjCCAUoCAQAwHTEbMBkGA1UEAwwSbm90LWFuLWV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmqs7nue5oFxKBk2WaFZJAma2nm1oFyPIq19gYEAdQN4mWvaJ8RjzHFkDMYUrlIrGxCYuFJDHFUk9dh19Na1MIY-NVLgcSbyNcOML3bLbLEwGmvXPbbEOflBA9mxUS9TLMgXW5ghf_qbt4vmSGKloIim41QXt55QFW6O-84s8Kd2OE6df0wTsEwLhZB3j5pDU-t7j5vTMv4Tc7EptaPkOdfQn-68viUJjlYM_4yIBVRhWCdexFdylCKVLg0obsghQEwULKYCUjdg6F0VJUI115DU49tzscXU_3FS3CyY8rchunuYszBNkdmgpAwViHNWuP7ESdEd_emrj1xuioSe6PwIDAQABoAAwDQYJKoZIhvcNAQELBQADggEBAE_T1nWU38XVYL28hNVSXU0rW5IBUKtbvr0qAkD4kda4HmQRTYkt-LNSuvxoZCC9lxijjgtJi-OJe_DCTdZZpYzewlVvcKToWSYHYQ6Wm1-fxxD_XzphvZOujpmBySchdiz7QSVWJmVZu34XD5RJbIcrmj_cjRt42J1hiTFjNMzQu9U6_HwIMmliDL-soFY2RTvvZf-dAFvOUQ-Wbxt97eM1PbbmxJNWRhbAmgEpe9PWDPTpqV5AK56VAa991cQ1P8ZVmPss5hvwGWhOtpnpTZVHN3toGNYFKqxWPboirqushQlfKiFqT9rpRgM3-mFjOHidGqsKEkTdmfSVlVEk3oo="
@ -694,7 +698,7 @@ func TestGetChallenge(t *testing.T) {
req, err := http.NewRequest(method, challengeURL, nil)
test.AssertNotError(t, err, "Could not make NewRequest")
wfe.Challenge(newRequestEvent(), resp, req)
wfe.Challenge(ctx, newRequestEvent(), resp, req)
test.AssertEquals(t,
resp.Code,
http.StatusAccepted)
@ -733,7 +737,7 @@ func TestChallenge(t *testing.T) {
test.AssertNotError(t, err, "Could not unmarshal testing key")
challengeURL := "/acme/challenge/valid/23"
wfe.Challenge(newRequestEvent(), responseWriter,
wfe.Challenge(ctx, newRequestEvent(), responseWriter,
makePostRequestWithPath(challengeURL,
signRequest(t, `{"resource":"challenge"}`, wfe.nonceService)))
@ -751,7 +755,7 @@ func TestChallenge(t *testing.T) {
// Expired challenges should be inaccessible
challengeURL = "/acme/challenge/expired/23"
responseWriter = httptest.NewRecorder()
wfe.Challenge(newRequestEvent(), responseWriter,
wfe.Challenge(ctx, newRequestEvent(), responseWriter,
makePostRequestWithPath(challengeURL,
signRequest(t, `{"resource":"challenge"}`, wfe.nonceService)))
test.AssertEquals(t, responseWriter.Code, http.StatusNotFound)
@ -772,7 +776,7 @@ func TestBadNonce(t *testing.T) {
responseWriter := httptest.NewRecorder()
result, err := signer.Sign([]byte(`{"resource":"new-reg","contact":["mailto:person@mail.com"],"agreement":"` + agreementURL + `"}`))
test.AssertNotError(t, err, "Failed to sign body")
wfe.NewRegistration(newRequestEvent(), responseWriter,
wfe.NewRegistration(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Body.String(), `{"type":"urn:acme:error:badNonce","detail":"JWS has no anti-replay nonce","status":400}`)
}
@ -792,7 +796,7 @@ func TestNewECDSARegistration(t *testing.T) {
responseWriter := httptest.NewRecorder()
result, err := signer.Sign([]byte(`{"resource":"new-reg","contact":["mailto:person@mail.com"],"agreement":"` + agreementURL + `"}`))
test.AssertNotError(t, err, "Failed to sign")
wfe.NewRegistration(newRequestEvent(), responseWriter, makePostRequest(result.FullSerialize()))
wfe.NewRegistration(ctx, newRequestEvent(), responseWriter, makePostRequest(result.FullSerialize()))
var reg core.Registration
err = json.Unmarshal([]byte(responseWriter.Body.String()), &reg)
@ -817,7 +821,7 @@ func TestNewECDSARegistration(t *testing.T) {
// POST, Valid JSON, Key already in use
result, err = signer.Sign([]byte(`{"resource":"new-reg","contact":["mailto:person@mail.com"],"agreement":"` + agreementURL + `"}`))
wfe.NewRegistration(newRequestEvent(), responseWriter, makePostRequest(result.FullSerialize()))
wfe.NewRegistration(ctx, newRequestEvent(), responseWriter, makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Body.String(), `{"type":"urn:acme:error:malformed","detail":"Registration key is already in use","status":409}`)
test.AssertEquals(t, responseWriter.Header().Get("Location"), "/acme/reg/3")
test.AssertEquals(t, responseWriter.Code, 409)
@ -911,7 +915,7 @@ func TestNewRegistration(t *testing.T) {
responseWriter := httptest.NewRecorder()
result, err := signer.Sign([]byte(`{"resource":"new-reg","contact":["mailto:person@mail.com"],"agreement":"` + agreementURL + `"}`))
wfe.NewRegistration(newRequestEvent(), responseWriter,
wfe.NewRegistration(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
var reg core.Registration
@ -946,7 +950,7 @@ func TestNewRegistration(t *testing.T) {
// POST, Valid JSON, Key already in use
result, err = signer.Sign([]byte(`{"resource":"new-reg","contact":["mailto:person@mail.com"],"agreement":"` + agreementURL + `"}`))
wfe.NewRegistration(newRequestEvent(), responseWriter,
wfe.NewRegistration(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -988,7 +992,7 @@ type mockSANoSuchRegistration struct {
core.StorageGetter
}
func (msa mockSANoSuchRegistration) GetRegistrationByKey(jwk jose.JsonWebKey) (core.Registration, error) {
func (msa mockSANoSuchRegistration) GetRegistrationByKey(ctx context.Context, jwk jose.JsonWebKey) (core.Registration, error) {
return core.Registration{}, core.NoSuchRegistrationError("reg not found")
}
@ -1013,7 +1017,7 @@ func TestRevokeCertificateCertKey(t *testing.T) {
signer.SetNonceSource(wfe.nonceService)
result, _ := signer.Sign(revokeRequestJSON)
wfe.RevokeCertificate(newRequestEvent(), responseWriter,
wfe.RevokeCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Code, 200)
test.AssertEquals(t, responseWriter.Body.String(), "")
@ -1036,7 +1040,7 @@ func TestRevokeCertificateAccountKey(t *testing.T) {
test.AssertNotError(t, err, "Failed to make signer")
accountKeySigner.SetNonceSource(wfe.nonceService)
result, _ := accountKeySigner.Sign(revokeRequestJSON)
wfe.RevokeCertificate(newRequestEvent(), responseWriter,
wfe.RevokeCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Code, 200)
test.AssertEquals(t, responseWriter.Body.String(), "")
@ -1057,7 +1061,7 @@ func TestRevokeCertificateWrongKey(t *testing.T) {
test.AssertNotError(t, err, "Unable to create revoke request")
result, _ := accountKeySigner2.Sign(revokeRequestJSON)
wfe.RevokeCertificate(newRequestEvent(), responseWriter,
wfe.RevokeCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Code, 403)
test.AssertEquals(t, responseWriter.Body.String(),
@ -1098,7 +1102,7 @@ func TestRevokeCertificateAlreadyRevoked(t *testing.T) {
responseWriter.Body.Reset()
signer.SetNonceSource(wfe.nonceService)
result, _ := signer.Sign(revokeRequestJSON)
wfe.RevokeCertificate(newRequestEvent(), responseWriter,
wfe.RevokeCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(result.FullSerialize()))
test.AssertEquals(t, responseWriter.Code, 409)
test.AssertEquals(t, responseWriter.Body.String(),
@ -1121,7 +1125,7 @@ func TestAuthorization(t *testing.T) {
// POST, but no body.
responseWriter.Body.Reset()
wfe.NewAuthorization(newRequestEvent(), responseWriter, &http.Request{
wfe.NewAuthorization(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "POST",
Header: map[string][]string{
"Content-Length": {"0"},
@ -1131,12 +1135,12 @@ func TestAuthorization(t *testing.T) {
// POST, but body that isn't valid JWS
responseWriter.Body.Reset()
wfe.NewAuthorization(newRequestEvent(), responseWriter, makePostRequest("hi"))
wfe.NewAuthorization(ctx, newRequestEvent(), responseWriter, makePostRequest("hi"))
test.AssertEquals(t, responseWriter.Body.String(), `{"type":"urn:acme:error:malformed","detail":"Parse error reading JWS","status":400}`)
// POST, Properly JWS-signed, but payload is "foo", not base64-encoded JSON.
responseWriter.Body.Reset()
wfe.NewAuthorization(newRequestEvent(), responseWriter,
wfe.NewAuthorization(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, "foo", wfe.nonceService)))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -1145,7 +1149,7 @@ func TestAuthorization(t *testing.T) {
// Same signed body, but payload modified by one byte, breaking signature.
// should fail JWS verification.
responseWriter.Body.Reset()
wfe.NewAuthorization(newRequestEvent(), responseWriter, makePostRequest(`
wfe.NewAuthorization(ctx, newRequestEvent(), responseWriter, makePostRequest(`
{
"header": {
"alg": "RS256",
@ -1164,7 +1168,7 @@ func TestAuthorization(t *testing.T) {
`{"type":"urn:acme:error:malformed","detail":"JWS verification error","status":400}`)
responseWriter.Body.Reset()
wfe.NewAuthorization(newRequestEvent(), responseWriter,
wfe.NewAuthorization(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, `{"resource":"new-authz","identifier":{"type":"dns","value":"test.com"}}`, wfe.nonceService)))
test.AssertEquals(
@ -1183,7 +1187,7 @@ func TestAuthorization(t *testing.T) {
// Expired authorizations should be inaccessible
authzURL := "/acme/authz/expired"
responseWriter = httptest.NewRecorder()
wfe.Authorization(newRequestEvent(), responseWriter, &http.Request{
wfe.Authorization(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "GET",
URL: mustParseURL(authzURL),
})
@ -1229,7 +1233,7 @@ func TestRegistration(t *testing.T) {
responseWriter.Body.Reset()
// Test POST invalid JSON
wfe.Registration(newRequestEvent(), responseWriter, makePostRequestWithPath("/2", "invalid"))
wfe.Registration(ctx, newRequestEvent(), responseWriter, makePostRequestWithPath("/2", "invalid"))
test.AssertEquals(t,
responseWriter.Body.String(),
`{"type":"urn:acme:error:malformed","detail":"Parse error reading JWS","status":400}`)
@ -1246,7 +1250,7 @@ func TestRegistration(t *testing.T) {
signer.SetNonceSource(wfe.nonceService)
result, err := signer.Sign([]byte(`{"resource":"reg","agreement":"` + agreementURL + `"}`))
test.AssertNotError(t, err, "Unable to sign")
wfe.Registration(newRequestEvent(), responseWriter,
wfe.Registration(ctx, newRequestEvent(), responseWriter,
makePostRequestWithPath("/2", result.FullSerialize()))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -1265,7 +1269,7 @@ func TestRegistration(t *testing.T) {
result, err = signer.Sign([]byte(`{"resource":"reg","agreement":"https://letsencrypt.org/im-bad"}`))
// Test POST valid JSON with registration up in the mock
wfe.Registration(newRequestEvent(), responseWriter,
wfe.Registration(ctx, newRequestEvent(), responseWriter,
makePostRequestWithPath("/1", result.FullSerialize()))
test.AssertEquals(t,
responseWriter.Body.String(),
@ -1275,7 +1279,7 @@ func TestRegistration(t *testing.T) {
// Test POST valid JSON with registration up in the mock (with correct agreement URL)
result, err = signer.Sign([]byte(`{"resource":"reg","agreement":"` + agreementURL + `"}`))
test.AssertNotError(t, err, "Couldn't sign")
wfe.Registration(newRequestEvent(), responseWriter,
wfe.Registration(ctx, newRequestEvent(), responseWriter,
makePostRequestWithPath("/1", result.FullSerialize()))
test.AssertNotContains(t, responseWriter.Body.String(), "urn:acme:error")
links := responseWriter.Header()["Link"]
@ -1290,7 +1294,7 @@ func TestTermsRedirect(t *testing.T) {
responseWriter := httptest.NewRecorder()
path, _ := url.Parse("/terms")
wfe.Terms(newRequestEvent(), responseWriter, &http.Request{
wfe.Terms(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "GET",
URL: path,
})
@ -1307,7 +1311,7 @@ func TestIssuer(t *testing.T) {
responseWriter := httptest.NewRecorder()
wfe.Issuer(newRequestEvent(), responseWriter, &http.Request{
wfe.Issuer(ctx, newRequestEvent(), responseWriter, &http.Request{
Method: "GET",
})
test.AssertEquals(t, responseWriter.Code, http.StatusOK)
@ -1396,7 +1400,7 @@ func TestLogCsrPem(t *testing.T) {
test.AssertNotError(t, err, "Unable to parse certificateRequest")
mockSA := mocks.NewStorageAuthority(fc)
reg, err := mockSA.GetRegistration(789)
reg, err := mockSA.GetRegistration(ctx, 789)
test.AssertNotError(t, err, "Unable to get registration")
req, err := http.NewRequest("GET", "http://[::1]/", nil)
@ -1414,7 +1418,7 @@ func TestLogCsrPem(t *testing.T) {
func TestLengthRequired(t *testing.T) {
wfe, _ := setupWFE(t)
_, _, _, prob := wfe.verifyPOST(newRequestEvent(), &http.Request{
_, _, _, prob := wfe.verifyPOST(ctx, newRequestEvent(), &http.Request{
Method: "POST",
URL: mustParseURL("/"),
}, false, "resource")
@ -1427,7 +1431,7 @@ type mockSADifferentStoredKey struct {
core.StorageGetter
}
func (sa mockSADifferentStoredKey) GetRegistrationByKey(jwk jose.JsonWebKey) (core.Registration, error) {
func (sa mockSADifferentStoredKey) GetRegistrationByKey(ctx context.Context, jwk jose.JsonWebKey) (core.Registration, error) {
keyJSON := []byte(test2KeyPublicJSON)
var parsedKey jose.JsonWebKey
err := parsedKey.UnmarshalJSON(keyJSON)
@ -1445,7 +1449,7 @@ func TestVerifyPOSTUsesStoredKey(t *testing.T) {
wfe.SA = &mockSADifferentStoredKey{mocks.NewStorageAuthority(fc)}
// signRequest signs with test1Key, but our special mock returns a
// registration with test2Key
_, _, _, err := wfe.verifyPOST(newRequestEvent(), makePostRequest(signRequest(t, `{"resource":"foo"}`, wfe.nonceService)), true, "foo")
_, _, _, err := wfe.verifyPOST(ctx, newRequestEvent(), makePostRequest(signRequest(t, `{"resource":"foo"}`, wfe.nonceService)), true, "foo")
test.AssertError(t, err, "No error returned when provided key differed from stored key.")
}
@ -1456,7 +1460,7 @@ func TestBadKeyCSR(t *testing.T) {
// CSR with a bad (512 bit RSA) key.
// openssl req -outform der -new -newkey rsa:512 -nodes -keyout foo.com.key
// -subj /CN=foo.com | base64 -w0 | sed -e 's,+,-,g' -e 's,/,_,g'
wfe.NewCertificate(newRequestEvent(), responseWriter,
wfe.NewCertificate(ctx, newRequestEvent(), responseWriter,
makePostRequest(signRequest(t, `{
"resource":"new-cert",
"csr": "MIHLMHcCAQAwEjEQMA4GA1UEAwwHZm9vLmNvbTBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDCZftp4x4owgjBnwOKfzihIPedT-BUmV2fuQPMqaUlc8yJUp13vcO5uxUlaBm8leM7Dj_sgTDP_JgykorlYo73AgMBAAGgADANBgkqhkiG9w0BAQsFAANBAEaQ2QBhweK-kp1ejQCedUhMit_wG-uTBtKnc3M82f6_fztLkhg1vWQ782nmhbEI5orXp6QtNHgJYnBpqA9Ut00"