func TestValidationResult(t *testing.T) {
	ip := net.ParseIP("1.1.1.1")
	vrA := core.ValidationRecord{
		Hostname:          "hostA",
		Port:              "2020",
		AddressesResolved: []net.IP{ip},
		AddressUsed:       ip,
		URL:               "urlA",
		Authorities:       []string{"authA"},
	}
	vrB := core.ValidationRecord{
		Hostname:          "hostB",
		Port:              "2020",
		AddressesResolved: []net.IP{ip},
		AddressUsed:       ip,
		URL:               "urlB",
		Authorities:       []string{"authB"},
	}
	result := []core.ValidationRecord{vrA, vrB}
	prob := &probs.ProblemDetails{Type: probs.TLSProblem, Detail: "asd", HTTPStatus: 200}

	pb, err := validationResultToPB(result, prob)
	test.AssertNotError(t, err, "validationResultToPB failed")
	test.Assert(t, pb != nil, "Returned vapb.ValidationResult is nil")

	reconResult, reconProb, err := pbToValidationResult(pb)
	test.AssertNotError(t, err, "pbToValidationResult failed")
	test.AssertDeepEquals(t, reconResult, result)
	test.AssertDeepEquals(t, reconProb, prob)
}
func TestPerformValidationReq(t *testing.T) {
	var jwk jose.JsonWebKey
	err := json.Unmarshal([]byte(JWK1JSON), &jwk)
	test.AssertNotError(t, err, "Failed to unmarshal test key")
	domain := "example.com"
	chall := core.Challenge{
		AccountKey: &jwk,
		ID:         10,
		Type:       core.ChallengeTypeDNS01,
		Status:     core.StatusPending,
		Token:      "asd",
		ProvidedKeyAuthorization: "keyauth",
	}
	authz := core.Authorization{ID: "asd", RegistrationID: 10}

	pb, err := argsToPerformValidationRequest(domain, chall, authz)
	test.AssertNotError(t, err, "argsToPerformValidationRequest failed")
	test.Assert(t, pb != nil, "Return vapb.PerformValidationRequest is nil")

	reconDomain, reconChall, reconAuthz, err := performValidationReqToArgs(pb)
	test.AssertNotError(t, err, "performValidationReqToArgs failed")
	test.AssertEquals(t, reconDomain, domain)
	test.AssertDeepEquals(t, reconChall, chall)
	test.AssertDeepEquals(t, reconAuthz, authz)
}
func TestProblemDetails(t *testing.T) {
	pb, err := problemDetailsToPB(nil)
	test.AssertNotEquals(t, err, "problemDetailToPB failed")
	test.Assert(t, pb == nil, "Returned corepb.ProblemDetails is not nil")

	prob := &probs.ProblemDetails{Type: probs.TLSProblem, Detail: "asd", HTTPStatus: 200}
	pb, err = problemDetailsToPB(prob)
	test.AssertNotError(t, err, "problemDetailToPB failed")
	test.Assert(t, pb != nil, "return corepb.ProblemDetails is nill")
	test.AssertDeepEquals(t, *pb.ProblemType, string(prob.Type))
	test.AssertEquals(t, *pb.Detail, prob.Detail)
	test.AssertEquals(t, int(*pb.HttpStatus), prob.HTTPStatus)

	recon, err := pbToProblemDetails(pb)
	test.AssertNotError(t, err, "pbToProblemDetails failed")
	test.AssertDeepEquals(t, recon, prob)

	recon, err = pbToProblemDetails(nil)
	test.AssertNotError(t, err, "pbToProblemDetails failed")
	test.Assert(t, recon == nil, "Returned core.PRoblemDetails is not nil")
	_, err = pbToProblemDetails(&corepb.ProblemDetails{})
	test.AssertError(t, err, "pbToProblemDetails did not fail")
	test.AssertEquals(t, err, ErrMissingParameters)
	empty := ""
	_, err = pbToProblemDetails(&corepb.ProblemDetails{ProblemType: &empty})
	test.AssertError(t, err, "pbToProblemDetails did not fail")
	test.AssertEquals(t, err, ErrMissingParameters)
	_, err = pbToProblemDetails(&corepb.ProblemDetails{Detail: &empty})
	test.AssertError(t, err, "pbToProblemDetails did not fail")
	test.AssertEquals(t, err, ErrMissingParameters)
}
Beispiel #4
0
func TestChallengesFor(t *testing.T) {
	pa := paImpl(t)

	var accountKey *jose.JsonWebKey
	err := json.Unmarshal([]byte(accountKeyJSON), &accountKey)
	if err != nil {
		t.Errorf("Error unmarshaling JWK: %v", err)
	}

	challenges, combinations := pa.ChallengesFor(core.AcmeIdentifier{}, accountKey)

	test.Assert(t, len(challenges) == len(enabledChallenges), "Wrong number of challenges returned")
	test.Assert(t, len(combinations) == len(enabledChallenges), "Wrong number of combinations returned")

	seenChalls := make(map[string]bool)
	// Expected only if the pseudo-RNG is seeded with 99.
	expectedCombos := [][]int{{1}, {2}, {0}}
	for _, challenge := range challenges {
		test.Assert(t, !seenChalls[challenge.Type], "should not already have seen this type")
		seenChalls[challenge.Type] = true

		test.Assert(t, enabledChallenges[challenge.Type], "Unsupported challenge returned")
	}
	test.AssertEquals(t, len(seenChalls), len(enabledChallenges))
	test.AssertDeepEquals(t, expectedCombos, combinations)
}
func TestVAChallenge(t *testing.T) {
	var jwk jose.JsonWebKey
	err := json.Unmarshal([]byte(JWK1JSON), &jwk)
	test.AssertNotError(t, err, "Failed to unmarshal test key")
	chall := core.Challenge{
		AccountKey: &jwk,
		ID:         10,
		Type:       core.ChallengeTypeDNS01,
		Status:     core.StatusPending,
		Token:      "asd",
		ProvidedKeyAuthorization: "keyauth",
	}

	pb, err := vaChallengeToPB(chall)
	test.AssertNotError(t, err, "vaChallengeToPB failed")
	test.Assert(t, pb != nil, "Returned corepb.Challenge is nil")

	recon, err := pbToVAChallenge(pb)
	test.AssertNotError(t, err, "pbToVAChallenge failed")
	test.AssertDeepEquals(t, recon, chall)

	_, err = pbToVAChallenge(nil)
	test.AssertError(t, err, "pbToVAChallenge did not fail")
	test.AssertEquals(t, err, ErrMissingParameters)
	_, err = pbToVAChallenge(&corepb.Challenge{})
	test.AssertError(t, err, "pbToVAChallenge did not fail")
	test.AssertEquals(t, err, ErrMissingParameters)
}
func TestAuthz(t *testing.T) {
	exp := time.Now().AddDate(0, 0, 1)
	identifier := core.AcmeIdentifier{Type: core.IdentifierDNS, Value: "example.com"}
	combos := make([][]int, 1)
	combos[0] = []int{0, 1}
	challA := core.Challenge{
		ID:     10,
		Type:   core.ChallengeTypeDNS01,
		Status: core.StatusPending,
		Token:  "asd",
		ProvidedKeyAuthorization: "keyauth",
	}
	challB := core.Challenge{
		ID:     11,
		Type:   core.ChallengeTypeDNS01,
		Status: core.StatusPending,
		Token:  "asd2",
		ProvidedKeyAuthorization: "keyauth4",
	}
	inAuthz := core.Authorization{
		ID:             "1",
		Identifier:     identifier,
		RegistrationID: 5,
		Status:         core.StatusPending,
		Expires:        &exp,
		Challenges:     []core.Challenge{challA, challB},
		Combinations:   combos,
	}

	pbAuthz, err := authzToPB(inAuthz)
	test.AssertNotError(t, err, "authzToPB failed")
	outAuthz, err := pbToAuthz(pbAuthz)
	test.AssertNotError(t, err, "pbToAuthz failed")
	test.AssertDeepEquals(t, inAuthz, outAuthz)
}
func TestCapitalizedLetters(t *testing.T) {
	testCtx := setup(t)
	testCtx.caConfig.MaxNames = 3
	ca, err := NewCertificateAuthorityImpl(
		testCtx.caConfig,
		testCtx.fc,
		testCtx.stats,
		testCtx.issuers,
		testCtx.keyPolicy)
	ca.Publisher = &mocks.Publisher{}
	ca.PA = testCtx.pa
	ca.SA = &mockSA{}

	csr, _ := x509.ParseCertificateRequest(CapitalizedCSR)
	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)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")
	test.AssertEquals(t, "capitalizedletters.com", parsedCert.Subject.CommonName)
	sort.Strings(parsedCert.DNSNames)
	expected := []string{"capitalizedletters.com", "evenmorecaps.com", "morecaps.com"}
	test.AssertDeepEquals(t, expected, parsedCert.DNSNames)
	t.Logf("subject serial number %#v", parsedCert.Subject.SerialNumber)
}
func TestProblemDetailsFromError(t *testing.T) {
	testCases := []struct {
		err        error
		statusCode int
		problem    probs.ProblemType
	}{
		{InternalServerError("foo"), 500, probs.ServerInternalProblem},
		{NotSupportedError("foo"), 501, probs.ServerInternalProblem},
		{MalformedRequestError("foo"), 400, probs.MalformedProblem},
		{UnauthorizedError("foo"), 403, probs.UnauthorizedProblem},
		{NotFoundError("foo"), 404, probs.MalformedProblem},
		{SignatureValidationError("foo"), 400, probs.MalformedProblem},
		{RateLimitedError("foo"), 429, probs.RateLimitedProblem},
		{LengthRequiredError("foo"), 411, probs.MalformedProblem},
		{BadNonceError("foo"), 400, probs.BadNonceProblem},
	}
	for _, c := range testCases {
		p := ProblemDetailsForError(c.err, "k")
		if p.HTTPStatus != c.statusCode {
			t.Errorf("Incorrect status code for %s. Expected %d, got %d", reflect.TypeOf(c.err).Name(), c.statusCode, p.HTTPStatus)
		}
		if probs.ProblemType(p.Type) != c.problem {
			t.Errorf("Expected problem urn %#v, got %#v", c.problem, p.Type)
		}
	}

	expected := &probs.ProblemDetails{
		Type:       probs.MalformedProblem,
		HTTPStatus: 200,
		Detail:     "gotcha",
	}
	p := ProblemDetailsForError(expected, "k")
	test.AssertDeepEquals(t, expected, p)
}
func TestAddRegistration(t *testing.T) {
	sa, clk, cleanUp := initSA(t)
	defer cleanUp()

	jwk := satest.GoodJWK()

	contact, err := core.ParseAcmeURL("mailto:[email protected]")
	if err != nil {
		t.Fatalf("unable to parse contact link: %s", err)
	}
	contacts := []*core.AcmeURL{contact}
	reg, err := sa.NewRegistration(core.Registration{
		Key:       jwk,
		Contact:   contacts,
		InitialIP: net.ParseIP("43.34.43.34"),
	})
	if err != nil {
		t.Fatalf("Couldn't create new registration: %s", err)
	}
	test.Assert(t, reg.ID != 0, "ID shouldn't be 0")
	test.AssertDeepEquals(t, reg.Contact, contacts)

	_, err = sa.GetRegistration(0)
	test.AssertError(t, err, "Registration object for ID 0 was returned")

	dbReg, err := sa.GetRegistration(reg.ID)
	test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))

	expectedReg := core.Registration{
		ID:        reg.ID,
		Key:       jwk,
		InitialIP: net.ParseIP("43.34.43.34"),
		CreatedAt: clk.Now(),
	}
	test.AssertEquals(t, dbReg.ID, expectedReg.ID)
	test.Assert(t, core.KeyDigestEquals(dbReg.Key, expectedReg.Key), "Stored key != expected")

	u, _ := core.ParseAcmeURL("test.com")

	newReg := core.Registration{
		ID:        reg.ID,
		Key:       jwk,
		Contact:   []*core.AcmeURL{u},
		InitialIP: net.ParseIP("72.72.72.72"),
		Agreement: "yes",
	}
	err = sa.UpdateRegistration(newReg)
	test.AssertNotError(t, err, fmt.Sprintf("Couldn't get registration with ID %v", reg.ID))
	dbReg, err = sa.GetRegistrationByKey(jwk)
	test.AssertNotError(t, err, "Couldn't get registration by key")

	test.AssertEquals(t, dbReg.ID, newReg.ID)
	test.AssertEquals(t, dbReg.Agreement, newReg.Agreement)

	var anotherJWK jose.JsonWebKey
	err = json.Unmarshal([]byte(anotherKey), &anotherJWK)
	test.AssertNotError(t, err, "couldn't unmarshal anotherJWK")
	_, err = sa.GetRegistrationByKey(anotherJWK)
	test.AssertError(t, err, "Registration object for invalid key was returned")
}
func TestRegistration(t *testing.T) {
	contacts := []string{"email"}
	var key jose.JsonWebKey
	err := json.Unmarshal([]byte(`
		{
			"e": "AQAB",
			"kty": "RSA",
			"n": "tSwgy3ORGvc7YJI9B2qqkelZRUC6F1S5NwXFvM4w5-M0TsxbFsH5UH6adigV0jzsDJ5imAechcSoOhAh9POceCbPN1sTNwLpNbOLiQQ7RD5mY_pSUHWXNmS9R4NZ3t2fQAzPeW7jOfF0LKuJRGkekx6tXP1uSnNibgpJULNc4208dgBaCHo3mvaE2HV2GmVl1yxwWX5QZZkGQGjNDZYnjFfa2DKVvFs0QbAk21ROm594kAxlRlMMrvqlf24Eq4ERO0ptzpZgm_3j_e4hGRD39gJS7kAzK-j2cacFQ5Qi2Y6wZI2p-FCq_wiYsfEAIkATPBiLKl_6d_Jfcvs_impcXQ"
		}
	`), &key)
	test.AssertNotError(t, err, "Could not unmarshal testing key")
	inReg := core.Registration{
		ID:        1,
		Key:       &key,
		Contact:   &contacts,
		Agreement: "yup",
		InitialIP: net.ParseIP("1.1.1.1"),
		CreatedAt: time.Now(),
		Status:    core.StatusValid,
	}
	pbReg, err := registrationToPB(inReg)
	test.AssertNotError(t, err, "registrationToPB failed")
	outReg, err := pbToRegistration(pbReg)
	test.AssertNotError(t, err, "pbToRegistration failed")
	test.AssertDeepEquals(t, inReg, outReg)

	inReg.Contact = nil
	pbReg, err = registrationToPB(inReg)
	test.AssertNotError(t, err, "registrationToPB failed")
	pbReg.Contact = []string{}
	outReg, err = pbToRegistration(pbReg)
	test.AssertNotError(t, err, "pbToRegistration failed")
	test.AssertDeepEquals(t, inReg, outReg)

	var empty []string
	inReg.Contact = &empty
	pbReg, err = registrationToPB(inReg)
	test.AssertNotError(t, err, "registrationToPB failed")
	outReg, err = pbToRegistration(pbReg)
	test.AssertNotError(t, err, "pbToRegistration failed")
	test.Assert(t, *outReg.Contact != nil, "Empty slice was converted to a nil slice")
}
func TestJWK(t *testing.T) {
	var jwk jose.JsonWebKey
	err := json.Unmarshal([]byte(JWK1JSON), &jwk)
	test.AssertNotError(t, err, "Failed to unmarshal test key")

	str, err := jwkToString(&jwk)
	test.AssertNotError(t, err, "jwkToString failed")
	test.AssertEquals(t, str, JWK1JSON)

	recon, err := stringToJWK(str)
	test.AssertNotError(t, err, "stringToJWK failed")
	test.AssertDeepEquals(t, recon.Key, jwk.Key)
}
func TestCert(t *testing.T) {
	now := time.Now()
	cert := core.Certificate{
		RegistrationID: 1,
		Serial:         "serial",
		Digest:         "digest",
		DER:            []byte{255},
		Issued:         now,
		Expires:        now.Add(time.Hour),
	}

	certPB := certToPB(cert)
	outCert := pbToCert(certPB)

	test.AssertDeepEquals(t, cert, outCert)
}
func TestSCT(t *testing.T) {
	sct := core.SignedCertificateTimestamp{
		ID:                10,
		SCTVersion:        1,
		LogID:             "logid",
		Timestamp:         100,
		Extensions:        []byte{255},
		Signature:         []byte{1},
		CertificateSerial: "serial",
	}

	sctPB := sctToPB(sct)
	outSCT := pbToSCT(sctPB)

	test.AssertDeepEquals(t, sct, outSCT)
}
func TestNormalizeCSR(t *testing.T) {
	cases := []struct {
		csr           *x509.CertificateRequest
		forceCN       bool
		expectedCN    string
		expectedNames []string
	}{
		{
			&x509.CertificateRequest{DNSNames: []string{"a.com"}},
			true,
			"a.com",
			[]string{"a.com"},
		},
		{
			&x509.CertificateRequest{Subject: pkix.Name{CommonName: "A.com"}, DNSNames: []string{"a.com"}},
			true,
			"a.com",
			[]string{"a.com"},
		},
		{
			&x509.CertificateRequest{DNSNames: []string{"a.com"}},
			false,
			"",
			[]string{"a.com"},
		},
		{
			&x509.CertificateRequest{DNSNames: []string{"a.com", "a.com"}},
			false,
			"",
			[]string{"a.com"},
		},
		{
			&x509.CertificateRequest{Subject: pkix.Name{CommonName: "A.com"}, DNSNames: []string{"B.com"}},
			false,
			"a.com",
			[]string{"a.com", "b.com"},
		},
	}
	for _, c := range cases {
		normalizeCSR(c.csr, c.forceCN)
		test.AssertEquals(t, c.expectedCN, c.csr.Subject.CommonName)
		test.AssertDeepEquals(t, c.expectedNames, c.expectedNames)
	}
}
func TestValidationRecord(t *testing.T) {
	ip := net.ParseIP("1.1.1.1")
	vr := core.ValidationRecord{
		Hostname:          "host",
		Port:              "2020",
		AddressesResolved: []net.IP{ip},
		AddressUsed:       ip,
		URL:               "url",
		Authorities:       []string{"auth"},
	}

	pb, err := validationRecordToPB(vr)
	test.AssertNotError(t, err, "validationRecordToPB failed")
	test.Assert(t, pb != nil, "Return core.ValidationRecord is nil")

	recon, err := pbToValidationRecord(pb)
	test.AssertNotError(t, err, "pbToValidationRecord failed")
	test.AssertDeepEquals(t, recon, vr)
}
Beispiel #16
0
func TestChallengesFor(t *testing.T) {
	pa := paImpl(t)

	challenges, combinations := pa.ChallengesFor(core.AcmeIdentifier{})

	test.Assert(t, len(challenges) == len(enabledChallenges), "Wrong number of challenges returned")
	test.Assert(t, len(combinations) == len(enabledChallenges), "Wrong number of combinations returned")

	seenChalls := make(map[string]bool)
	// Expected only if the pseudo-RNG is seeded with 99.
	expectedCombos := [][]int{{1}, {2}, {0}}
	for _, challenge := range challenges {
		test.Assert(t, !seenChalls[challenge.Type], "should not already have seen this type")
		seenChalls[challenge.Type] = true

		test.Assert(t, enabledChallenges[challenge.Type], "Unsupported challenge returned")
	}
	test.AssertEquals(t, len(seenChalls), len(enabledChallenges))
	test.AssertDeepEquals(t, expectedCombos, combinations)
}
func TestCapitalizedLetters(t *testing.T) {
	ctx := setup(t)
	defer ctx.cleanUp()
	ctx.caConfig.MaxNames = 3
	ca, err := NewCertificateAuthorityImpl(ctx.caConfig, ctx.fc, ctx.stats, caCert, caKey, ctx.keyPolicy)
	ca.Publisher = &mocks.Publisher{}
	ca.PA = ctx.pa
	ca.SA = ctx.sa

	csr, _ := x509.ParseCertificateRequest(CapitalizedCSR)
	cert, err := ca.IssueCertificate(*csr, ctx.reg.ID)
	test.AssertNotError(t, err, "Failed to gracefully handle a CSR with capitalized names")

	parsedCert, err := x509.ParseCertificate(cert.DER)
	test.AssertNotError(t, err, "Error parsing certificate produced by CA")
	test.AssertEquals(t, "capitalizedletters.com", parsedCert.Subject.CommonName)
	sort.Strings(parsedCert.DNSNames)
	expected := []string{"capitalizedletters.com", "evenmorecaps.com", "morecaps.com"}
	test.AssertDeepEquals(t, expected, parsedCert.DNSNames)
}
Beispiel #18
0
func TestAllowNoCN(t *testing.T) {
	testCtx := setup(t)
	ca, err := NewCertificateAuthorityImpl(
		testCtx.caConfig,
		testCtx.fc,
		testCtx.stats,
		testCtx.issuers,
		testCtx.keyPolicy,
		testCtx.logger)
	test.AssertNotError(t, err, "Couldn't create new CA")
	ca.forceCNFromSAN = false
	ca.Publisher = &mocks.Publisher{}
	ca.PA = testCtx.pa
	ca.SA = &mockSA{}

	csr, err := x509.ParseCertificateRequest(NoCNCSR)
	test.AssertNotError(t, err, "Couldn't parse CSR")
	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))
	if cert.Subject.CommonName != "" {
		t.Errorf("want no CommonName, got %#v", cert.Subject.CommonName)
	}
	serial := core.SerialToString(cert.SerialNumber)
	if cert.Subject.SerialNumber != serial {
		t.Errorf("SerialNumber: want %#v, got %#v", serial, cert.Subject.SerialNumber)
	}

	expected := []string{}
	for _, name := range csr.DNSNames {
		expected = append(expected, name)
	}
	sort.Strings(expected)
	actual := []string{}
	for _, name := range cert.DNSNames {
		actual = append(actual, name)
	}
	sort.Strings(actual)
	test.AssertDeepEquals(t, actual, expected)
}
func TestLoadPolicies(t *testing.T) {
	policy := New()

	policyContent, readErr := ioutil.ReadFile("../test/rate-limit-policies.yml")
	test.AssertNotError(t, readErr, "Failed to load rate-limit-policies.yml")

	// Test that loading a good policy from YAML doesn't error
	err := policy.LoadPolicies(policyContent)
	test.AssertNotError(t, err, "Failed to parse rate-limit-policies.yml")

	// Test that the TotalCertificates section parsed correctly
	totalCerts := policy.TotalCertificates()
	test.AssertEquals(t, totalCerts.Threshold, 100000)
	test.AssertEquals(t, len(totalCerts.Overrides), 0)
	test.AssertEquals(t, len(totalCerts.RegistrationOverrides), 0)

	// Test that the CertificatesPerName section parsed correctly
	certsPerName := policy.CertificatesPerName()
	test.AssertEquals(t, certsPerName.Threshold, 2)
	test.AssertDeepEquals(t, certsPerName.Overrides, map[string]int{
		"ratelimit.me":          1,
		"le.wtf":                10000,
		"le1.wtf":               10000,
		"le2.wtf":               10000,
		"le3.wtf":               10000,
		"nginx.wtf":             10000,
		"good-caa-reserved.com": 10000,
		"bad-caa-reserved.com":  10000,
		"ecdsa.le.wtf":          10000,
		"must-staple.le.wtf":    10000,
	})
	test.AssertDeepEquals(t, certsPerName.RegistrationOverrides, map[int64]int{
		101: 1000,
	})

	// Test that the RegistrationsPerIP section parsed correctly
	regsPerIP := policy.RegistrationsPerIP()
	test.AssertEquals(t, regsPerIP.Threshold, 10000)
	test.AssertDeepEquals(t, regsPerIP.Overrides, map[string]int{
		"127.0.0.1": 1000000,
	})
	test.AssertEquals(t, len(regsPerIP.RegistrationOverrides), 0)

	// Test that the PendingAuthorizationsPerAccount section parsed correctly
	pendingAuthsPerAcct := policy.PendingAuthorizationsPerAccount()
	test.AssertEquals(t, pendingAuthsPerAcct.Threshold, 3)
	test.AssertEquals(t, len(pendingAuthsPerAcct.Overrides), 0)
	test.AssertEquals(t, len(pendingAuthsPerAcct.RegistrationOverrides), 0)

	// Test that the CertificatesPerFQDN section parsed correctly
	certsPerFQDN := policy.CertificatesPerFQDNSet()
	test.AssertEquals(t, certsPerFQDN.Threshold, 5)
	test.AssertDeepEquals(t, certsPerFQDN.Overrides, map[string]int{
		"le.wtf":                10000,
		"le1.wtf":               10000,
		"le2.wtf":               10000,
		"le3.wtf":               10000,
		"le.wtf,le1.wtf":        10000,
		"good-caa-reserved.com": 10000,
		"nginx.wtf":             10000,
		"ecdsa.le.wtf":          10000,
		"must-staple.le.wtf":    10000,
	})
	test.AssertEquals(t, len(certsPerFQDN.RegistrationOverrides), 0)

	// Test that loading invalid YAML generates an error
	err = policy.LoadPolicies([]byte("err"))
	test.AssertError(t, err, "Failed to generate error loading invalid yaml policy file")
	// Re-check a field of policy to make sure a LoadPolicies error doesn't
	// corrupt the existing policies
	test.AssertDeepEquals(t, policy.RegistrationsPerIP().Overrides, map[string]int{
		"127.0.0.1": 1000000,
	})

	// Test that the RateLimitConfig accessors do not panic when there has been no
	// `LoadPolicy` call, and instead return empty RateLimitPolicy objects with default
	// values.
	emptyPolicy := New()
	test.AssertEquals(t, emptyPolicy.TotalCertificates().Threshold, 0)
	test.AssertEquals(t, emptyPolicy.CertificatesPerName().Threshold, 0)
	test.AssertEquals(t, emptyPolicy.RegistrationsPerIP().Threshold, 0)
	test.AssertEquals(t, emptyPolicy.RegistrationsPerIP().Threshold, 0)
	test.AssertEquals(t, emptyPolicy.PendingAuthorizationsPerAccount().Threshold, 0)
	test.AssertEquals(t, emptyPolicy.CertificatesPerFQDNSet().Threshold, 0)
}
func TestVerifyCSR(t *testing.T) {
	private, err := rsa.GenerateKey(rand.Reader, 2048)
	test.AssertNotError(t, err, "error generating test key")
	signedReqBytes, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{PublicKey: private.PublicKey, SignatureAlgorithm: x509.SHA256WithRSA}, private)
	test.AssertNotError(t, err, "error generating test CSR")
	signedReq, err := x509.ParseCertificateRequest(signedReqBytes)
	test.AssertNotError(t, err, "error parsing test CSR")
	brokenSignedReq := new(x509.CertificateRequest)
	*brokenSignedReq = *signedReq
	brokenSignedReq.Signature = []byte{1, 1, 1, 1}
	signedReqWithHosts := new(x509.CertificateRequest)
	*signedReqWithHosts = *signedReq
	signedReqWithHosts.DNSNames = []string{"a.com", "b.com"}
	signedReqWithLongCN := new(x509.CertificateRequest)
	*signedReqWithLongCN = *signedReq
	signedReqWithLongCN.Subject.CommonName = strings.Repeat("a", maxCNLength+1)
	signedReqWithBadName := new(x509.CertificateRequest)
	*signedReqWithBadName = *signedReq
	signedReqWithBadName.DNSNames = []string{"bad-name.com"}

	cases := []struct {
		csr           *x509.CertificateRequest
		maxNames      int
		keyPolicy     *goodkey.KeyPolicy
		pa            core.PolicyAuthority
		regID         int64
		expectedError error
	}{
		{
			&x509.CertificateRequest{},
			0,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("invalid public key in CSR"),
		},
		{
			&x509.CertificateRequest{PublicKey: private.PublicKey},
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("signature algorithm not supported"),
		},
		{
			brokenSignedReq,
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("invalid signature on CSR"),
		},
		{
			signedReq,
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("at least one DNS name is required"),
		},
		{
			signedReqWithLongCN,
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("CN was longer than 64 bytes"),
		},
		{
			signedReqWithHosts,
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("CSR contains more than 1 DNS names"),
		},
		{
			signedReqWithBadName,
			1,
			testingPolicy,
			&mockPA{},
			0,
			errors.New("policy forbids issuing for: bad-name.com"),
		},
	}

	for _, c := range cases {
		err := VerifyCSR(c.csr, c.maxNames, c.keyPolicy, c.pa, false, c.regID)
		test.AssertDeepEquals(t, c.expectedError, err)
	}
}
func TestUniqueLowerNames(t *testing.T) {
	u := UniqueLowerNames([]string{"foobar.com", "fooBAR.com", "baz.com", "foobar.com", "bar.com", "bar.com", "a.com"})
	sort.Strings(u)
	test.AssertDeepEquals(t, []string{"a.com", "bar.com", "baz.com", "foobar.com"}, u)
}