func TestValidateContacts(t *testing.T) { _, _, ra, _, cleanUp := initAuthorities(t) defer cleanUp() tel, _ := core.ParseAcmeURL("tel:") ansible, _ := core.ParseAcmeURL("ansible:earth.sol.milkyway.laniakea/letsencrypt") validEmail, _ := core.ParseAcmeURL("mailto:[email protected]") malformedEmail, _ := core.ParseAcmeURL("mailto:admin.com") err := ra.validateContacts([]*core.AcmeURL{}) test.AssertNotError(t, err, "No Contacts") err = ra.validateContacts([]*core.AcmeURL{tel, validEmail}) test.AssertError(t, err, "Too Many Contacts") err = ra.validateContacts([]*core.AcmeURL{tel}) test.AssertNotError(t, err, "Simple Telephone") err = ra.validateContacts([]*core.AcmeURL{validEmail}) test.AssertNotError(t, err, "Valid Email") err = ra.validateContacts([]*core.AcmeURL{malformedEmail}) test.AssertError(t, err, "Malformed Email") err = ra.validateContacts([]*core.AcmeURL{ansible}) test.AssertError(t, err, "Unknown scheme") }
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 TestAuditObject(t *testing.T) { t.Parallel() stats, _ := statsd.NewNoopClient(nil) audit, _ := Dial("", "", "tag", stats) // Test a simple object err := audit.AuditObject("Prefix", "String") test.AssertNotError(t, err, "Simple objects should be serializable") // Test a system object err = audit.AuditObject("Prefix", t) test.AssertNotError(t, err, "System objects should be serializable") // Test a complex object type validObj struct { A string B string } var valid = validObj{A: "B", B: "C"} err = audit.AuditObject("Prefix", valid) test.AssertNotError(t, err, "Complex objects should be serializable") type invalidObj struct { A chan string } var invalid = invalidObj{A: make(chan string)} err = audit.AuditObject("Prefix", invalid) test.AssertError(t, err, "Invalid objects should fail serialization") }
// Ensure we get only valid authorization with correct RegID func TestGetLatestValidAuthorizationBasic(t *testing.T) { sa, _, cleanUp := initSA(t) defer cleanUp() // attempt to get unauthorized domain authz, err := sa.GetLatestValidAuthorization(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) // authorize "example.org" authz = CreateDomainAuthWithRegID(t, "example.org", sa, reg.ID) // finalize auth authz.Status = core.StatusValid err = sa.FinalizeAuthorization(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"}) 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"}) 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) test.AssertEquals(t, authz.Identifier.Value, "example.org") test.AssertEquals(t, authz.RegistrationID, reg.ID) }
func TestMarkCertificateRevoked(t *testing.T) { sa, fc, cleanUp := initSA(t) defer cleanUp() reg := satest.CreateWorkingRegistration(t, sa) // 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) test.AssertNotError(t, err, "Couldn't add www.eff.org.der") serial := "000000000000000000000000000000021bd4" const ocspResponse = "this is a fake OCSP response" certificateStatusObj, err := sa.dbMap.Get(core.CertificateStatus{}, serial) beforeStatus := certificateStatusObj.(*core.CertificateStatus) test.AssertEquals(t, beforeStatus.Status, core.OCSPStatusGood) fc.Add(1 * time.Hour) code := core.RevocationCode(1) err = sa.MarkCertificateRevoked(serial, code) test.AssertNotError(t, err, "MarkCertificateRevoked failed") certificateStatusObj, err = sa.dbMap.Get(core.CertificateStatus{}, serial) afterStatus := certificateStatusObj.(*core.CertificateStatus) test.AssertNotError(t, err, "Failed to fetch certificate status") if code != afterStatus.RevokedReason { t.Errorf("RevokedReasons, expected %v, got %v", code, afterStatus.RevokedReason) } if !fc.Now().Equal(afterStatus.RevokedDate) { t.Errorf("RevokedData, expected %s, got %s", fc.Now(), afterStatus.RevokedDate) } }
func TestValidateHTTP(t *testing.T) { chall := core.HTTPChallenge01(accountKey) err := setChallengeToken(&chall, core.NewToken()) test.AssertNotError(t, err, "Failed to complete HTTP challenge") hs := httpSrv(t, chall.Token) port, err := getPort(hs) test.AssertNotError(t, err, "failed to get test server port") stats, _ := statsd.NewNoopClient() va := NewValidationAuthorityImpl(&PortConfig{HTTPPort: port}, nil, stats, clock.Default()) va.DNSResolver = &mocks.DNSResolver{} mockRA := &MockRegistrationAuthority{} va.RA = mockRA defer hs.Close() var authz = core.Authorization{ ID: core.NewToken(), RegistrationID: 1, Identifier: ident, Challenges: []core.Challenge{chall}, } va.validate(authz, 0) test.AssertEquals(t, core.StatusValid, mockRA.lastAuthz.Challenges[0].Status) }
func TestDeduplication(t *testing.T) { cadb, storageAuthority, caConfig := setup(t) ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile) test.AssertNotError(t, err, "Failed to create CA") ca.SA = storageAuthority ca.MaxKeySize = 4096 // Test that the CA collapses duplicate names csrDER, _ := hex.DecodeString(DupeNameCSRhex) csr, _ := x509.ParseCertificateRequest(csrDER) cert, err := ca.IssueCertificate(*csr, 1, FarFuture) test.AssertNotError(t, err, "Failed to gracefully handle a CSR with duplicate names") if err != nil { return } parsedCert, err := x509.ParseCertificate(cert.DER) test.AssertNotError(t, err, "Error parsing certificate produced by CA") if err != nil { return } correctName := "a.not-example.com" correctNames := len(parsedCert.DNSNames) == 1 && parsedCert.DNSNames[0] == correctName && parsedCert.Subject.CommonName == correctName test.Assert(t, correctNames, "Incorrect set of names in deduplicated certificate") }
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 TestAuthzMeta(t *testing.T) { authz := core.Authorization{ID: "asd", RegistrationID: 10} pb, err := authzMetaToPB(authz) test.AssertNotError(t, err, "authzMetaToPB failed") test.Assert(t, pb != nil, "return vapb.AuthzMeta is nill") test.Assert(t, pb.Id != nil, "Id field is nil") test.AssertEquals(t, *pb.Id, authz.ID) test.Assert(t, pb.RegID != nil, "RegistrationID field is nil") test.AssertEquals(t, *pb.RegID, authz.RegistrationID) recon, err := pbToAuthzMeta(pb) test.AssertNotError(t, err, "pbToAuthzMeta failed") test.AssertEquals(t, recon.ID, authz.ID) test.AssertEquals(t, recon.RegistrationID, authz.RegistrationID) _, err = pbToAuthzMeta(nil) test.AssertError(t, err, "pbToAuthzMeta did not fail") test.AssertEquals(t, err, ErrMissingParameters) _, err = pbToAuthzMeta(&vapb.AuthzMeta{}) test.AssertError(t, err, "pbToAuthzMeta did not fail") test.AssertEquals(t, err, ErrMissingParameters) empty := "" one := int64(1) _, err = pbToAuthzMeta(&vapb.AuthzMeta{Id: &empty}) test.AssertError(t, err, "pbToAuthzMeta did not fail") test.AssertEquals(t, err, ErrMissingParameters) _, err = pbToAuthzMeta(&vapb.AuthzMeta{RegID: &one}) test.AssertError(t, err, "pbToAuthzMeta did not fail") test.AssertEquals(t, err, ErrMissingParameters) }
func TestDNSServFail(t *testing.T) { obj := NewTestDNSResolverImpl(time.Second*10, []string{dnsLoopbackAddr}, testStats, clock.NewFake(), 1) bad := "servfail.com" _, _, err := obj.LookupTXT(context.Background(), bad) test.AssertError(t, err, "LookupTXT didn't return an error") _, err = obj.LookupHost(context.Background(), bad) test.AssertError(t, err, "LookupHost didn't return an error") // CAA lookup ignores validation failures from the resolver for now // and returns an empty list of CAA records. emptyCaa, err := obj.LookupCAA(context.Background(), bad) test.Assert(t, len(emptyCaa) == 0, "Query returned non-empty list of CAA records") test.AssertNotError(t, err, "LookupCAA returned an error") // When we turn on enforceCAASERVFAIL, such lookups should fail. obj.caaSERVFAILExceptions = map[string]bool{"servfailexception.example.com": true} emptyCaa, err = obj.LookupCAA(context.Background(), bad) test.Assert(t, len(emptyCaa) == 0, "Query returned non-empty list of CAA records") test.AssertError(t, err, "LookupCAA should have returned an error") // Unless they are on the exception list emptyCaa, err = obj.LookupCAA(context.Background(), "servfailexception.example.com") test.Assert(t, len(emptyCaa) == 0, "Query returned non-empty list of CAA records") test.AssertNotError(t, err, "LookupCAA for servfail exception returned an error") }
func TestBasicSuccessful(t *testing.T) { pub, leaf, k := setup(t) ctrl := gomock.NewController(t) defer ctrl.Finish() scope := mock_metrics.NewMockScope(ctrl) pub.stats = scope server := logSrv(leaf.Raw, k) defer server.Close() port, err := getPort(server) test.AssertNotError(t, err, "Failed to get test server port") addLog(t, pub, port, &k.PublicKey) statName := pub.ctLogs[0].statName log.Clear() scope.EXPECT().NewScope(statName).Return(scope) scope.EXPECT().Inc("Submits", int64(1)).Return(nil) scope.EXPECT().TimingDuration("SubmitLatency", gomock.Any()).Return(nil) 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() scope.EXPECT().NewScope(statName).Return(scope) scope.EXPECT().Inc("Submits", int64(1)).Return(nil) scope.EXPECT().TimingDuration("SubmitLatency", gomock.Any()).Return(nil) err = pub.SubmitToCT(ctx, leaf.Raw) test.AssertNotError(t, err, "Certificate submission failed") test.AssertEquals(t, len(log.GetAllMatching("Failed to.*")), 0) }
func TestOnValidationUpdateSuccess(t *testing.T) { _, sa, ra, fclk, cleanUp := initAuthorities(t) defer cleanUp() authzUpdated, err := sa.NewPendingAuthorization(AuthzInitial) test.AssertNotError(t, err, "Failed to create new pending authz") expires := fclk.Now().Add(300 * 24 * time.Hour) authzUpdated.Expires = &expires sa.UpdatePendingAuthorization(authzUpdated) // Simulate a successful simpleHTTP challenge authzFromVA := authzUpdated authzFromVA.Challenges[0].Status = core.StatusValid ra.OnValidationUpdate(authzFromVA) // Verify that the Authz in the DB is the same except for Status->StatusValid authzFromVA.Status = core.StatusValid dbAuthz, err := sa.GetAuthorization(authzFromVA.ID) test.AssertNotError(t, err, "Could not fetch authorization from database") t.Log("authz from VA: ", authzFromVA) t.Log("authz from DB: ", dbAuthz) assertAuthzEqual(t, authzFromVA, dbAuthz) }
func TestUpdateAuthorization(t *testing.T) { va, sa, ra, _, cleanUp := initAuthorities(t) defer cleanUp() // We know this is OK because of TestNewAuthorization authz, err := ra.NewAuthorization(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) test.AssertNotError(t, err, "UpdateAuthorization failed") // Verify that returned authz same as DB dbAuthz, err := sa.GetAuthorization(authz.ID) test.AssertNotError(t, err, "Could not fetch authorization from database") assertAuthzEqual(t, authz, dbAuthz) // Verify that the VA got the authz, and it's the same as the others test.Assert(t, va.Called, "Authorization was not passed to the VA") assertAuthzEqual(t, authz, va.Argument) // Verify that the responses are reflected test.Assert(t, len(va.Argument.Challenges) > 0, "Authz passed to VA has no challenges") t.Log("DONE TestUpdateAuthorization") }
func TestNewAuthorization(t *testing.T) { _, sa, ra, _, cleanUp := initAuthorities(t) defer cleanUp() _, err := ra.NewAuthorization(AuthzRequest, 0) test.AssertError(t, err, "Authorization cannot have registrationID == 0") authz, err := ra.NewAuthorization(AuthzRequest, Registration.ID) test.AssertNotError(t, err, "NewAuthorization failed") // Verify that returned authz same as DB dbAuthz, err := sa.GetAuthorization(authz.ID) test.AssertNotError(t, err, "Could not fetch authorization from database") assertAuthzEqual(t, authz, dbAuthz) // Verify that the returned authz has the right information test.Assert(t, authz.RegistrationID == Registration.ID, "Initial authz did not get the right registration ID") test.Assert(t, authz.Identifier == AuthzRequest.Identifier, "Initial authz had wrong identifier") test.Assert(t, authz.Status == core.StatusPending, "Initial authz not pending") // TODO Verify that challenges are correct test.Assert(t, len(authz.Challenges) == len(SupportedChallenges), "Incorrect number of challenges returned") test.Assert(t, SupportedChallenges[authz.Challenges[0].Type], fmt.Sprintf("Unsupported challenge: %s", authz.Challenges[0].Type)) test.Assert(t, SupportedChallenges[authz.Challenges[1].Type], fmt.Sprintf("Unsupported challenge: %s", authz.Challenges[1].Type)) test.Assert(t, authz.Challenges[0].IsSane(false), "Challenge 0 is not sane") test.Assert(t, authz.Challenges[1].IsSane(false), "Challenge 1 is not sane") t.Log("DONE TestNewAuthorization") }
func TestCertificateKeyNotEqualAccountKey(t *testing.T) { _, _, sa, ra, cleanUp := initAuthorities(t) defer cleanUp() authz := core.Authorization{} authz, _ = sa.NewPendingAuthorization(authz) authz.Identifier = core.AcmeIdentifier{ Type: core.IdentifierDNS, Value: "www.example.com", } csr := x509.CertificateRequest{ SignatureAlgorithm: x509.SHA256WithRSA, PublicKey: AccountKeyA.Key, DNSNames: []string{"www.example.com"}, } csrBytes, err := x509.CreateCertificateRequest(rand.Reader, &csr, AccountPrivateKey.Key) test.AssertNotError(t, err, "Failed to sign CSR") parsedCSR, err := x509.ParseCertificateRequest(csrBytes) test.AssertNotError(t, err, "Failed to parse CSR") sa.UpdatePendingAuthorization(authz) sa.FinalizeAuthorization(authz) certRequest := core.CertificateRequest{ CSR: parsedCSR, } // Registration id 1 has key == AccountKeyA _, err = ra.NewCertificate(certRequest, 1) 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") t.Log("DONE TestCertificateKeyNotEqualAccountKey") }
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) }
// TODO(https://github.com/letsencrypt/boulder/issues/894): Remove this method func TestSimpleHttpTLS(t *testing.T) { chall := core.Challenge{ Type: core.ChallengeTypeSimpleHTTP, Token: expectedToken, ValidationRecord: []core.ValidationRecord{}, AccountKey: accountKey, } hs := simpleSrv(t, expectedToken, true) defer hs.Close() port, err := getPort(hs) test.AssertNotError(t, err, "failed to get test server port") stats, _ := statsd.NewNoopClient() va := NewValidationAuthorityImpl(&PortConfig{HTTPSPort: port}, nil, stats, clock.Default()) va.DNSResolver = &mocks.DNSResolver{} log.Clear() finChall, err := va.validateSimpleHTTP(ident, chall) test.AssertEquals(t, finChall.Status, core.StatusValid) test.AssertNotError(t, err, "Error validating simpleHttp") logs := log.GetAllMatching(`^\[AUDIT\] Attempting to validate simpleHttp for `) test.AssertEquals(t, len(logs), 1) test.AssertEquals(t, logs[0].Priority, syslog.LOG_NOTICE) }
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) }
func TestRevoke(t *testing.T) { cadb, storageAuthority, caConfig := setup(t) ca, err := NewCertificateAuthorityImpl(cadb, caConfig, caCertFile) test.AssertNotError(t, err, "Failed to create CA") if err != nil { return } ca.SA = storageAuthority ca.MaxKeySize = 4096 csrDER, _ := hex.DecodeString(CNandSANCSRhex) csr, _ := x509.ParseCertificateRequest(csrDER) certObj, err := ca.IssueCertificate(*csr, 1, FarFuture) test.AssertNotError(t, err, "Failed to sign certificate") if err != nil { return } cert, err := x509.ParseCertificate(certObj.DER) test.AssertNotError(t, err, "Certificate failed to parse") serialString := core.SerialToString(cert.SerialNumber) err = ca.RevokeCertificate(serialString, 0) test.AssertNotError(t, err, "Revocation failed") status, err := storageAuthority.GetCertificateStatus(serialString) test.AssertNotError(t, err, "Failed to get cert status") test.AssertEquals(t, status.Status, core.OCSPStatusRevoked) test.Assert(t, time.Now().Sub(status.OCSPLastUpdated) > time.Second, fmt.Sprintf("OCSP LastUpdated was wrong: %v", status.OCSPLastUpdated)) }
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 TestAddAuthorization(t *testing.T) { sa, _, cleanUp := initSA(t) defer cleanUp() reg := satest.CreateWorkingRegistration(t, sa) PA := core.Authorization{RegistrationID: reg.ID} PA, err := sa.NewPendingAuthorization(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) test.AssertNotError(t, err, "Couldn't get pending authorization with ID "+PA.ID) test.AssertMarshaledEquals(t, PA, dbPa) expectedPa := core.Authorization{ID: PA.ID} test.AssertMarshaledEquals(t, dbPa.ID, expectedPa.ID) combos := make([][]int, 1) combos[0] = []int{0, 1} 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) test.AssertNotError(t, err, "Couldn't update pending authorization with ID "+PA.ID) newPa.Status = core.StatusValid err = sa.FinalizeAuthorization(newPa) test.AssertNotError(t, err, "Couldn't finalize pending authorization with ID "+PA.ID) dbPa, err = sa.GetAuthorization(PA.ID) test.AssertNotError(t, err, "Couldn't get authorization with ID "+PA.ID) }
func TestHTTPRedirectUserAgent(t *testing.T) { chall := core.HTTPChallenge01(accountKey) err := setChallengeToken(&chall, expectedToken) test.AssertNotError(t, err, "Failed to complete HTTP challenge") hs := httpSrv(t, expectedToken) defer hs.Close() port, err := getPort(hs) test.AssertNotError(t, err, "failed to get test server port") stats, _ := statsd.NewNoopClient() va := NewValidationAuthorityImpl(&PortConfig{HTTPPort: port}, nil, stats, clock.Default()) va.DNSResolver = &bdns.MockDNSResolver{} va.UserAgent = rejectUserAgent setChallengeToken(&chall, pathMoved) _, prob := va.validateHTTP01(context.Background(), 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) if prob == nil { t.Fatalf("Challenge with rejectUserAgent should have failed (%s).", pathFound) } }
func TestUpdateOCSP(t *testing.T) { sa, fc, cleanUp := initSA(t) defer cleanUp() reg := satest.CreateWorkingRegistration(t, sa) // 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) test.AssertNotError(t, err, "Couldn't add www.eff.org.der") serial := "000000000000000000000000000000021bd4" const ocspResponse = "this is a fake OCSP response" certificateStatusObj, err := sa.dbMap.Get(core.CertificateStatus{}, serial) if certificateStatusObj == nil { t.Fatalf("Failed to get certificate status for %s", serial) } beforeUpdate := certificateStatusObj.(*core.CertificateStatus) fc.Add(1 * time.Hour) err = sa.UpdateOCSP(serial, []byte(ocspResponse)) test.AssertNotError(t, err, "UpdateOCSP failed") certificateStatusObj, err = sa.dbMap.Get(core.CertificateStatus{}, serial) certificateStatus := certificateStatusObj.(*core.CertificateStatus) test.AssertNotError(t, err, "Failed to fetch certificate status") test.Assert(t, certificateStatus.OCSPLastUpdated.After(beforeUpdate.OCSPLastUpdated), fmt.Sprintf("UpdateOCSP did not take. before: %s; after: %s", beforeUpdate.OCSPLastUpdated, certificateStatus.OCSPLastUpdated)) test.AssertEquals(t, ocspResponse, string(certificateStatus.OCSPResponse)) }
func TestValidateContacts(t *testing.T) { tel, _ := core.ParseAcmeURL("tel:") ansible, _ := core.ParseAcmeURL("ansible:earth.sol.milkyway.laniakea/letsencrypt") validEmail, _ := core.ParseAcmeURL("mailto:[email protected]") invalidEmail, _ := core.ParseAcmeURL("mailto:[email protected]") malformedEmail, _ := core.ParseAcmeURL("mailto:admin.com") err := validateContacts([]*core.AcmeURL{}, &mocks.MockDNS{}) test.AssertNotError(t, err, "No Contacts") err = validateContacts([]*core.AcmeURL{tel}, &mocks.MockDNS{}) test.AssertNotError(t, err, "Simple Telephone") err = validateContacts([]*core.AcmeURL{validEmail}, &mocks.MockDNS{}) test.AssertNotError(t, err, "Valid Email") err = validateContacts([]*core.AcmeURL{invalidEmail}, &mocks.MockDNS{}) test.AssertError(t, err, "Invalid Email") err = validateContacts([]*core.AcmeURL{malformedEmail}, &mocks.MockDNS{}) test.AssertError(t, err, "Malformed Email") err = validateContacts([]*core.AcmeURL{ansible}, &mocks.MockDNS{}) test.AssertError(t, err, "Unknown scehme") }
func TestCountCertificates(t *testing.T) { sa, fc, cleanUp := initSA(t) defer cleanUp() fc.Add(time.Hour * 24) now := fc.Now() count, err := sa.CountCertificatesRange(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)) reg := satest.CreateWorkingRegistration(t, sa) // 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) 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) 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) test.AssertNotError(t, err, "Couldn't get certificate count for the last 24hrs") test.AssertEquals(t, count, int64(0)) }
func TestNewRegistrationNoFieldOverwrite(t *testing.T) { _, _, _, ra, cleanUp := initAuthorities(t) defer cleanUp() mailto, _ := core.ParseAcmeURL("mailto:[email protected]") input := core.Registration{ ID: 23, Key: AccountKeyC, Contact: []*core.AcmeURL{mailto}, Agreement: "I agreed", } result, err := ra.NewRegistration(input) test.AssertNotError(t, err, "Could not create new registration") test.Assert(t, result.ID != 23, "ID shouldn't be set by user") // TODO: Enable this test case once we validate terms agreement. //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{ ID: 33, Key: ShortKey, }) test.AssertNotError(t, err, "Could not update registration") test.Assert(t, result2.ID != 33, fmt.Sprintf("ID shouldn't be overwritten. expected %d, got %d", id, result2.ID)) test.Assert(t, !core.KeyDigestEquals(result2.Key, ShortKey), "Key shouldn't be overwritten") }
func TestRevokeAuthorizationsByDomain(t *testing.T) { sa, _, cleanUp := initSA(t) defer cleanUp() reg := satest.CreateWorkingRegistration(t, sa) PA1 := CreateDomainAuthWithRegID(t, "a.com", sa, reg.ID) PA2 := CreateDomainAuthWithRegID(t, "a.com", sa, reg.ID) PA2.Status = core.StatusValid err := sa.FinalizeAuthorization(PA2) test.AssertNotError(t, err, "Failed to finalize authorization") ident := core.AcmeIdentifier{Value: "a.com", Type: core.IdentifierDNS} ar, par, err := sa.RevokeAuthorizationsByDomain(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) test.AssertNotError(t, err, "Failed to retrieve pending authorization") FA, err := sa.GetAuthorization(PA2.ID) test.AssertNotError(t, err, "Failed to retrieve finalized authorization") test.AssertEquals(t, PA.Status, core.StatusRevoked) test.AssertEquals(t, FA.Status, core.StatusRevoked) }
func TestNewAuthorization(t *testing.T) { _, _, sa, ra, cleanUp := initAuthorities(t) defer cleanUp() _, err := ra.NewAuthorization(AuthzRequest, 0) test.AssertError(t, err, "Authorization cannot have registrationID == 0") authz, err := ra.NewAuthorization(AuthzRequest, 1) test.AssertNotError(t, err, "NewAuthorization failed") // Verify that returned authz same as DB dbAuthz, err := sa.GetAuthorization(authz.ID) test.AssertNotError(t, err, "Could not fetch authorization from database") assertAuthzEqual(t, authz, dbAuthz) // Verify that the returned authz has the right information test.Assert(t, authz.RegistrationID == 1, "Initial authz did not get the right registration ID") test.Assert(t, authz.Identifier == AuthzRequest.Identifier, "Initial authz had wrong identifier") test.Assert(t, authz.Status == core.StatusPending, "Initial authz not pending") // TODO Verify that challenges are correct test.Assert(t, len(authz.Challenges) == 3, "Incorrect number of challenges returned") test.Assert(t, authz.Challenges[0].Type == core.ChallengeTypeSimpleHTTP, "Challenge 0 not SimpleHTTP") test.Assert(t, authz.Challenges[1].Type == core.ChallengeTypeDVSNI, "Challenge 1 not DVSNI") test.Assert(t, authz.Challenges[2].Type == core.ChallengeTypeDNS, "Challenge 2 not DNS") t.Log("DONE TestNewAuthorization") }
func TestSingleton(t *testing.T) { t.Parallel() log1 := GetAuditLogger() test.AssertNotNil(t, log1, "Logger shouldn't be nil") log2 := GetAuditLogger() test.AssertEquals(t, log1, log2) writer, err := syslog.New(syslog.LOG_EMERG|syslog.LOG_KERN, "tag") test.AssertNotError(t, err, "Could not construct syslog object") stats, _ := statsd.NewNoopClient(nil) log3, err := NewAuditLogger(writer, stats) test.AssertNotError(t, err, "Could not construct audit logger") // Should not work err = SetAuditLogger(log3) test.AssertError(t, err, "Can't re-set") // Verify no change log4 := GetAuditLogger() // Verify that log4 != log3 test.AssertNotEquals(t, log4, log3) // Verify that log4 == log2 == log1 test.AssertEquals(t, log4, log2) test.AssertEquals(t, log4, log1) }
func TestDNSLookupHost(t *testing.T) { obj := NewTestDNSResolverImpl(time.Second*10, []string{dnsLoopbackAddr}, testStats, clock.NewFake(), 1) ip, err := obj.LookupHost(context.Background(), "servfail.com") t.Logf("servfail.com - IP: %s, Err: %s", ip, err) test.AssertError(t, err, "Server failure") test.Assert(t, len(ip) == 0, "Should not have IPs") ip, err = obj.LookupHost(context.Background(), "nonexistent.letsencrypt.org") t.Logf("nonexistent.letsencrypt.org - IP: %s, Err: %s", ip, err) test.AssertNotError(t, err, "Not an error to not exist") test.Assert(t, len(ip) == 0, "Should not have IPs") // Single IPv4 address ip, err = obj.LookupHost(context.Background(), "cps.letsencrypt.org") t.Logf("cps.letsencrypt.org - IP: %s, Err: %s", ip, err) test.AssertNotError(t, err, "Not an error to exist") test.Assert(t, len(ip) == 1, "Should have IP") ip, err = obj.LookupHost(context.Background(), "cps.letsencrypt.org") t.Logf("cps.letsencrypt.org - IP: %s, Err: %s", ip, err) test.AssertNotError(t, err, "Not an error to exist") test.Assert(t, len(ip) == 1, "Should have IP") // No IPv6 ip, err = obj.LookupHost(context.Background(), "v6.letsencrypt.org") t.Logf("v6.letsencrypt.org - IP: %s, Err: %s", ip, err) test.AssertNotError(t, err, "Not an error to exist") test.Assert(t, len(ip) == 0, "Should not have IPs") }