예제 #1
0
func TestFindContacts(t *testing.T) {
	testCtx := setup(t)
	defer testCtx.cleanUp()

	// Add some test registrations
	testCtx.addRegistrations(t)

	// Run findContacts - since no certificates have been added corresponding to
	// the above registrations, no contacts should be found.
	contacts, err := testCtx.c.findContacts()
	test.AssertNotError(t, err, "findContacts() produced error")
	test.AssertEquals(t, len(contacts), 0)

	// Now add some certificates
	testCtx.addCertificates(t)

	// Run findContacts - since there are two registrations with unexpired certs
	// we should get exactly two contacts back for RegA and RegC. RegB should
	// *not* be present since their certificate has already expired. Similarly,
	// RegD should *not* be present since its only contact is a "tel:" prefixed
	// ACMEUrl. Since the results are sorted, RegC should be first.
	contacts, err = testCtx.c.findContacts()
	test.AssertNotError(t, err, "findContacts() produced error")
	test.AssertEquals(t, len(contacts), 2)
	test.AssertEquals(t, contacts[0], emailCRaw)
	test.AssertEquals(t, contacts[1], emailARaw)
}
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 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)
}
예제 #4
0
func TestCustomConstraint(t *testing.T) {
	setUp(t)
	defer func() {
		constraintMap = map[string]*Constraint{}
	}()
	constraint := &Constraint{
		Name: "accounts_balance_check",
		GetError: func(e *pq.Error) *Error {
			return &Error{
				Message:  "Cannot write a negative balance",
				Severity: e.Severity,
				Table:    e.Table,
				Detail:   e.Detail,
				Code:     string(e.Code),
			}
		},
	}
	RegisterConstraint(constraint)
	_, err := db.Exec("INSERT INTO accounts (id, email, balance) VALUES ($1, $2, -1)", uuid, email)
	dberr := GetError(err)
	switch e := dberr.(type) {
	case *Error:
		test.AssertEquals(t, e.Error(), "Cannot write a negative balance")
		test.AssertEquals(t, e.Table, "accounts")
	default:
		t.Fail()
	}
}
예제 #5
0
// 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 TestCAAChecking(t *testing.T) {
	type CAATest struct {
		Domain  string
		Present bool
		Valid   bool
	}
	tests := []CAATest{
		// Reserved
		CAATest{"reserved.com", true, false},
		// Critical
		CAATest{"critical.com", true, false},
		CAATest{"nx.critical.com", true, false},
		CAATest{"cname-critical.com", true, false},
		CAATest{"nx.cname-critical.com", true, false},
		// Good (absent)
		CAATest{"absent.com", false, true},
		CAATest{"cname-absent.com", false, true},
		CAATest{"nx.cname-absent.com", false, true},
		CAATest{"cname-nx.com", false, true},
		CAATest{"example.co.uk", false, true},
		// Good (present)
		CAATest{"present.com", true, true},
		CAATest{"cname-present.com", true, true},
		CAATest{"cname2-present.com", true, true},
		CAATest{"nx.cname2-present.com", true, true},
		CAATest{"dname-present.com", true, true},
		CAATest{"dname2cname.com", true, true},
		// CNAME to critical
	}

	va := NewValidationAuthorityImpl(true)
	va.DNSResolver = &mocks.MockDNS{}
	va.IssuerDomain = "letsencrypt.org"
	for _, caaTest := range tests {
		present, valid, err := va.CheckCAARecords(core.AcmeIdentifier{Type: "dns", Value: caaTest.Domain})
		test.AssertNotError(t, err, caaTest.Domain)
		fmt.Println(caaTest.Domain, caaTest.Present == present, caaTest.Valid == valid)
		test.AssertEquals(t, caaTest.Present, present)
		test.AssertEquals(t, caaTest.Valid, valid)
	}

	present, valid, err := va.CheckCAARecords(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")

	for _, name := range []string{
		"www.caa-loop.com",
		"a.cname-loop.com",
		"a.dname-loop.com",
		"cname-servfail.com",
		"cname2servfail.com",
		"dname-servfail.com",
		"cname-and-dname.com",
		"servfail.com",
	} {
		_, _, err = va.CheckCAARecords(core.AcmeIdentifier{Type: "dns", Value: name})
		test.AssertError(t, err, name)
	}
}
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 TestLoadAndDumpRules(t *testing.T) {
	p, cleanup := padbImpl(t)
	defer cleanup()

	load := RuleSet{
		Blacklist: []BlacklistRule{
			BlacklistRule{
				Host: "bad.com",
			},
		},
		Whitelist: []WhitelistRule{
			WhitelistRule{
				Host: "good.bad.com",
			},
		},
	}
	err := p.LoadRules(load)
	test.AssertNotError(t, err, "Couldn't load rules")

	dumped, err := p.DumpRules()
	test.AssertNotError(t, err, "Couldn't dump rules")
	test.AssertEquals(t, len(dumped.Blacklist), 1)
	test.AssertEquals(t, len(dumped.Whitelist), 1)

	test.AssertEquals(t, dumped.Whitelist[0], load.Whitelist[0])
	test.AssertEquals(t, dumped.Blacklist[0], load.Blacklist[0])
}
예제 #9
0
func TestValidateHTTPResponseDocument(t *testing.T) {
	chall := core.HTTPChallenge01(accountKey)
	setChallengeToken(&chall, core.NewToken())

	hs := httpSrv(t, `a.StartOfLine.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.PastTruncationPoint.aaaaaaaaaaaaaaaaaaaa`)
	port, err := getPort(hs)
	test.AssertNotError(t, err, "failed to get test server port")
	stats, _ := statsd.NewNoopClient()
	va := NewValidationAuthorityImpl(&cmd.PortConfig{HTTPPort: port}, nil, nil, stats, clock.Default())
	va.DNSResolver = &bdns.MockDNSResolver{}
	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(ctx, authz, 0)

	test.AssertEquals(t, core.StatusInvalid, mockRA.lastAuthz.Challenges[0].Status)
	test.Assert(t, len(log.GetAllMatching("StartOfLine")) > 1, "Beginning of response body not logged")
	test.Assert(t, len(log.GetAllMatching("…")) > 1, "Ellipsis not logged")
	test.AssertEquals(t, len(log.GetAllMatching("PastTruncationPoint")), 0) // End of response body was logged

}
func TestStaticResolver(t *testing.T) {
	names := []string{"test:443"}
	sr := newStaticResolver(names)
	watcher, err := sr.Resolve("")
	test.AssertNotError(t, err, "staticResolver.Resolve failed")

	// Make sure doing this doesn't break anything (since it does nothing)
	watcher.Close()

	updates, err := watcher.Next()
	test.AssertNotError(t, err, "staticwatcher.Next failed")
	test.AssertEquals(t, len(names), len(updates))
	test.AssertEquals(t, updates[0].Addr, "test:443")
	test.AssertEquals(t, updates[0].Op, naming.Add)
	test.AssertEquals(t, updates[0].Metadata, nil)

	returned := make(chan struct{}, 1)
	go func() {
		_, err = watcher.Next()
		test.AssertNotError(t, err, "watcher.Next failed")
		returned <- struct{}{}
	}()
	select {
	case <-returned:
		t.Fatal("staticWatcher.Next returned something after the first call")
	case <-time.After(time.Millisecond * 500):
	}
}
예제 #11
0
func TestMessageContent(t *testing.T) {
	// Create a mailer with fixed content
	const (
		testDestination = "*****@*****.**"
		testSubject     = "Test Subject"
	)
	testBody, err := ioutil.ReadFile("testdata/test_msg_body.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_body.txt")
	mc := &mocks.Mailer{}
	m := &mailer{
		mailer:        mc,
		subject:       testSubject,
		destinations:  []string{testDestination},
		emailTemplate: string(testBody),
		checkpoint:    interval{start: 0, end: 1},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer, one message should have been created with the content
	// expected
	err = m.run()
	test.AssertNotError(t, err, "error calling mailer run()")
	test.AssertEquals(t, len(mc.Messages), 1)
	test.AssertEquals(t, mocks.MailerMessage{
		To:      testDestination,
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
}
예제 #12
0
func TestIndex(t *testing.T) {
	wfe := setupWFE(t)
	wfe.IndexCacheDuration = time.Second * 10

	responseWriter := httptest.NewRecorder()

	url, _ := url.Parse("/")
	wfe.Index(responseWriter, &http.Request{
		Method: "GET",
		URL:    url,
	})
	test.AssertEquals(t, responseWriter.Code, http.StatusOK)
	test.AssertNotEquals(t, responseWriter.Body.String(), "404 page not found\n")
	test.Assert(t, strings.Contains(responseWriter.Body.String(), wfe.NewReg),
		"new-reg not found")
	test.AssertEquals(t, responseWriter.Header().Get("Cache-Control"), "public, max-age=10")

	responseWriter.Body.Reset()
	responseWriter.Header().Del("Cache-Control")
	url, _ = url.Parse("/foo")
	wfe.Index(responseWriter, &http.Request{
		URL: url,
	})
	//test.AssertEquals(t, responseWriter.Code, http.StatusNotFound)
	test.AssertEquals(t, responseWriter.Body.String(), "404 page not found\n")
	test.AssertEquals(t, responseWriter.Header().Get("Cache-Control"), "")
}
예제 #13
0
func TestParseLine(t *testing.T) {
	fc := clock.NewFake()
	fc.Set(time.Date(2015, 3, 4, 5, 0, 0, 0, time.UTC))
	sa := &mockSA{}

	found, added := parseLogLine(sa, log, "")
	test.AssertEquals(t, found, false)
	test.AssertEquals(t, added, false)

	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: cert=[] err=[AMQP-RPC timeout], regID=[1337]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)

	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: cert=[deadbeef] err=[AMQP-RPC timeout], regID=[]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)

	log.Clear()
	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: cert=[3082045b30820343a003020102021300ffa0160630d618b2eb5c0510824b14274856300d06092a864886f70d01010b0500301f311d301b06035504030c146861707079206861636b65722066616b65204341301e170d3135313030333035323130305a170d3136303130313035323130305a3018311630140603550403130d6578616d706c652e636f2e626e30820122300d06092a864886f70d01010105000382010f003082010a02820101009ea3f1d21fade5596e36a6a77095a94758e4b72466b7444ada4f7c4cf6fde9b1d470b93b65c1fdd896917f248ccae49b57c80dc21c64b010699432130d059d2d8392346e8a179c7c947835549c64a7a5680c518faf0a5cbea48e684fca6304775c8fa9239c34f1d5cb2d063b098bd1c17183c7521efc884641b2f0b41402ac87c7076848d4347cef59dd5a9c174ad25467db933c95ef48c578ba762f527b21666a198fb5e1fe2d8299b4dceb1791e96ad075e3ecb057c776d764fad8f0829d43c32ddf985a3a36fade6966cec89468721a1ec47ab38eac8da4514060ded51d283a787b7c69971bda01f49f76baa41b1f9b4348aa4279e0fa55645d6616441f0d0203010001a382019530820191300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff04023000301d0603551d0e04160414369d0c100452b9eb3ffe7ae852e9e839a3ae5adb301f0603551d23041830168014fb784f12f96015832c9f177f3419b32e36ea4189306a06082b06010505070101045e305c302606082b06010505073001861a687474703a2f2f6c6f63616c686f73743a343030322f6f637370303206082b060105050730028626687474703a2f2f6c6f63616c686f73743a343030302f61636d652f6973737565722d6365727430180603551d110411300f820d6578616d706c652e636f2e626e30270603551d1f0420301e301ca01aa0188616687474703a2f2f6578616d706c652e636f6d2f63726c30630603551d20045c305a300a060667810c0102013000304c06032a03043045302206082b060105050702011616687474703a2f2f6578616d706c652e636f6d2f637073301f06082b0601050507020230130c11446f20576861742054686f752057696c74300d06092a864886f70d01010b05000382010100bbb4b994971cafa2e56e2258db46d88bfb361d8bfcd75521c03174e471eaa9f3ff2e719059bb57cc064079496d8550577c127baa84a18e792ddd36bf4f7b874b6d40d1d14288c15d38e4d6be25eb7805b1c3756b3735702eb4585d1886bc8af2c14086d3ce506e55184913c83aaaa8dfe6160bd035e42cda6d97697ed3ee3124c9bf9620a9fe6602191c1b746533c1d4a30023bbe902cb4aa661901177ed924eb836c94cc062dd0ce439c4ece9ee1dfe0499a42cbbcb2ea7243c59f4df4fdd7058229bacf9a640632dbd776b21633137b2df1c41f0765a66f448777aeec7ed4c0cdeb9d8a2356ff813820a287e11d52efde1aa543b4ef2ee992a7a9d5ccf7da4] err=[AMQP-RPC timeout], regID=[1001]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, true)
	checkNoErrors(t)

	log.Clear()
	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: cert=[3082045b30820343a003020102021300ffa0160630d618b2eb5c0510824b14274856300d06092a864886f70d01010b0500301f311d301b06035504030c146861707079206861636b65722066616b65204341301e170d3135313030333035323130305a170d3136303130313035323130305a3018311630140603550403130d6578616d706c652e636f2e626e30820122300d06092a864886f70d01010105000382010f003082010a02820101009ea3f1d21fade5596e36a6a77095a94758e4b72466b7444ada4f7c4cf6fde9b1d470b93b65c1fdd896917f248ccae49b57c80dc21c64b010699432130d059d2d8392346e8a179c7c947835549c64a7a5680c518faf0a5cbea48e684fca6304775c8fa9239c34f1d5cb2d063b098bd1c17183c7521efc884641b2f0b41402ac87c7076848d4347cef59dd5a9c174ad25467db933c95ef48c578ba762f527b21666a198fb5e1fe2d8299b4dceb1791e96ad075e3ecb057c776d764fad8f0829d43c32ddf985a3a36fade6966cec89468721a1ec47ab38eac8da4514060ded51d283a787b7c69971bda01f49f76baa41b1f9b4348aa4279e0fa55645d6616441f0d0203010001a382019530820191300e0603551d0f0101ff0404030205a0301d0603551d250416301406082b0601050507030106082b06010505070302300c0603551d130101ff04023000301d0603551d0e04160414369d0c100452b9eb3ffe7ae852e9e839a3ae5adb301f0603551d23041830168014fb784f12f96015832c9f177f3419b32e36ea4189306a06082b06010505070101045e305c302606082b06010505073001861a687474703a2f2f6c6f63616c686f73743a343030322f6f637370303206082b060105050730028626687474703a2f2f6c6f63616c686f73743a343030302f61636d652f6973737565722d6365727430180603551d110411300f820d6578616d706c652e636f2e626e30270603551d1f0420301e301ca01aa0188616687474703a2f2f6578616d706c652e636f6d2f63726c30630603551d20045c305a300a060667810c0102013000304c06032a03043045302206082b060105050702011616687474703a2f2f6578616d706c652e636f6d2f637073301f06082b0601050507020230130c11446f20576861742054686f752057696c74300d06092a864886f70d01010b05000382010100bbb4b994971cafa2e56e2258db46d88bfb361d8bfcd75521c03174e471eaa9f3ff2e719059bb57cc064079496d8550577c127baa84a18e792ddd36bf4f7b874b6d40d1d14288c15d38e4d6be25eb7805b1c3756b3735702eb4585d1886bc8af2c14086d3ce506e55184913c83aaaa8dfe6160bd035e42cda6d97697ed3ee3124c9bf9620a9fe6602191c1b746533c1d4a30023bbe902cb4aa661901177ed924eb836c94cc062dd0ce439c4ece9ee1dfe0499a42cbbcb2ea7243c59f4df4fdd7058229bacf9a640632dbd776b21633137b2df1c41f0765a66f448777aeec7ed4c0cdeb9d8a2356ff813820a287e11d52efde1aa543b4ef2ee992a7a9d5ccf7da4] err=[AMQP-RPC timeout], regID=[1001]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)
	checkNoErrors(t)
}
예제 #14
0
func TestChallenge(t *testing.T) {
	wfe := NewWebFrontEndImpl()
	wfe.RA = &MockRegistrationAuthority{}
	wfe.SA = &MockSA{}
	wfe.HandlePaths()
	responseWriter := httptest.NewRecorder()

	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")

	challengeURL, _ := url.Parse("/acme/authz/asdf?challenge=foo")
	authz := core.Authorization{
		ID: "asdf",
		Identifier: core.AcmeIdentifier{
			Type:  "dns",
			Value: "letsencrypt.org",
		},
		Challenges: []core.Challenge{
			core.Challenge{
				Type: "dns",
				URI:  core.AcmeURL(*challengeURL),
			},
		},
		RegistrationID: 1,
	}

	wfe.Challenge(authz, responseWriter, &http.Request{
		Method: "POST",
		URL:    challengeURL,
		Body: makeBody(`
			{
					"header": {
							"alg": "RS256",
							"jwk": {
									"e": "AQAB",
									"kty": "RSA",
									"n": "tSwgy3ORGvc7YJI9B2qqkelZRUC6F1S5NwXFvM4w5-M0TsxbFsH5UH6adigV0jzsDJ5imAechcSoOhAh9POceCbPN1sTNwLpNbOLiQQ7RD5mY_pSUHWXNmS9R4NZ3t2fQAzPeW7jOfF0LKuJRGkekx6tXP1uSnNibgpJULNc4208dgBaCHo3mvaE2HV2GmVl1yxwWX5QZZkGQGjNDZYnjFfa2DKVvFs0QbAk21ROm594kAxlRlMMrvqlf24Eq4ERO0ptzpZgm_3j_e4hGRD39gJS7kAzK-j2cacFQ5Qi2Y6wZI2p-FCq_wiYsfEAIkATPBiLKl_6d_Jfcvs_impcXQ"
							}
					},
					"payload": "e30K",
					"signature": "JXYA_pin91Bc5oz5I6dqCNNWDrBaYTB31EnWorrj4JEFRaidafC9mpLDLLA9jR9kX_Vy2bA5b6pPpXVKm0w146a0L551OdL8JrrLka9q6LypQdDLLQa76XD03hSBOFcC-Oo5FLPa3WRWS1fQ37hYAoLxtS3isWXMIq_4Onx5bq8bwKyu-3E3fRb_lzIZ8hTIWwcblCTOfufUe6AoK4m6MfBjz0NGhyyk4lEZZw6Sttm2VuZo3xmWoRTJEyJG5AOJ6fkNJ9iQQ1kVhMr0ZZ7NVCaOZAnxrwv2sCjY6R3f4HuEVe1yzT75Mq2IuXq-tadGyFujvUxF6BWHCulbEnss7g"
			}
		`),
	})

	test.AssertEquals(
		t, responseWriter.Header().Get("Location"),
		"/acme/authz/asdf?challenge=foo")
	test.AssertEquals(
		t, responseWriter.Header().Get("Link"),
		"</acme/authz/asdf>;rel=\"up\"")
	test.AssertEquals(
		t, responseWriter.Body.String(),
		"{\"type\":\"dns\",\"uri\":\"/acme/authz/asdf?challenge=foo\"}")
}
예제 #15
0
func TestCheckCAAFallback(t *testing.T) {
	testSrv := httptest.NewServer(http.HandlerFunc(mocks.GPDNSHandler))
	defer testSrv.Close()

	stats := mocks.NewStatter()
	scope := metrics.NewStatsdScope(stats, "VA")
	logger := blog.NewMock()
	caaDR, err := cdr.New(metrics.NewNoopScope(), time.Second, 1, nil, blog.NewMock())
	test.AssertNotError(t, err, "Failed to create CAADistributedResolver")
	caaDR.URI = testSrv.URL
	caaDR.Clients["1.1.1.1"] = new(http.Client)
	va := NewValidationAuthorityImpl(
		&cmd.PortConfig{},
		nil,
		caaDR,
		&bdns.MockDNSResolver{},
		"user agent 1.0",
		"ca.com",
		scope,
		clock.Default(),
		logger)

	prob := va.checkCAA(ctx, core.AcmeIdentifier{Value: "bad-local-resolver.com", Type: "dns"})
	test.Assert(t, prob == nil, fmt.Sprintf("returned ProblemDetails was non-nil: %#v", prob))

	va.caaDR = nil
	prob = va.checkCAA(ctx, core.AcmeIdentifier{Value: "bad-local-resolver.com", Type: "dns"})
	test.Assert(t, prob != nil, "returned ProblemDetails was nil")
	test.AssertEquals(t, prob.Type, probs.ConnectionProblem)
	test.AssertEquals(t, prob.Detail, "server failure at resolver")
}
예제 #16
0
func TestDNSValidationNotSane(t *testing.T) {
	stats, _ := statsd.NewNoopClient()
	va := NewValidationAuthorityImpl(&cmd.PortConfig{}, nil, nil, stats, clock.Default())
	va.DNSResolver = &bdns.MockDNSResolver{}
	mockRA := &MockRegistrationAuthority{}
	va.RA = mockRA

	chal0 := core.DNSChallenge01(accountKey)
	chal0.Token = ""

	chal1 := core.DNSChallenge01(accountKey)
	chal1.Token = "yfCBb-bRTLz8Wd1C0lTUQK3qlKj3-t2tYGwx5Hj7r_"

	chal2 := core.DNSChallenge01(accountKey)
	chal2.ProvidedKeyAuthorization = ""

	chal3 := core.DNSChallenge01(accountKey)
	chal3.ProvidedKeyAuthorization = "a.a"

	var authz = core.Authorization{
		ID:             core.NewToken(),
		RegistrationID: 1,
		Identifier:     ident,
		Challenges:     []core.Challenge{chal0, chal1, chal2, chal3},
	}

	for i := 0; i < len(authz.Challenges); 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.") {
			t.Errorf("Got wrong error: %s", authz.Challenges[i].Error)
		}
	}
}
예제 #17
0
func TestParseLine(t *testing.T) {
	fc := clock.NewFake()
	fc.Set(time.Date(2015, 3, 4, 5, 0, 0, 0, time.UTC))
	sa := &mockSA{}

	found, added := parseLogLine(sa, log, "")
	test.AssertEquals(t, found, false)
	test.AssertEquals(t, added, false)

	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: b64der=[] err=[AMQP-RPC timeout], regID=[1337]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)

	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: b64der=[deadbeef] err=[AMQP-RPC timeout], regID=[]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)

	log.Clear()
	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: b64der=[MIIEWzCCA0OgAwIBAgITAP+gFgYw1hiy61wFEIJLFCdIVjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQDDBRoYXBweSBoYWNrZXIgZmFrZSBDQTAeFw0xNTEwMDMwNTIxMDBaFw0xNjAxMDEwNTIxMDBaMBgxFjAUBgNVBAMTDWV4YW1wbGUuY28uYm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCeo/HSH63lWW42pqdwlalHWOS3JGa3REraT3xM9v3psdRwuTtlwf3YlpF/JIzK5JtXyA3CHGSwEGmUMhMNBZ0tg5I0booXnHyUeDVUnGSnpWgMUY+vCly+pI5oT8pjBHdcj6kjnDTx1cstBjsJi9HBcYPHUh78iEZBsvC0FAKsh8cHaEjUNHzvWd1anBdK0lRn25M8le9IxXi6di9SeyFmahmPteH+LYKZtNzrF5HpatB14+ywV8d212T62PCCnUPDLd+YWjo2+t5pZs7IlGhyGh7EerOOrI2kUUBg3tUdKDp4e3xplxvaAfSfdrqkGx+bQ0iqQnng+lVkXWYWRB8NAgMBAAGjggGVMIIBkTAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFDadDBAEUrnrP/566FLp6DmjrlrbMB8GA1UdIwQYMBaAFPt4TxL5YBWDLJ8XfzQZsy426kGJMGoGCCsGAQUFBwEBBF4wXDAmBggrBgEFBQcwAYYaaHR0cDovL2xvY2FsaG9zdDo0MDAyL29jc3AwMgYIKwYBBQUHMAKGJmh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC9hY21lL2lzc3Vlci1jZXJ0MBgGA1UdEQQRMA+CDWV4YW1wbGUuY28uYm4wJwYDVR0fBCAwHjAcoBqgGIYWaHR0cDovL2V4YW1wbGUuY29tL2NybDBjBgNVHSAEXDBaMAoGBmeBDAECATAAMEwGAyoDBDBFMCIGCCsGAQUFBwIBFhZodHRwOi8vZXhhbXBsZS5jb20vY3BzMB8GCCsGAQUFBwICMBMMEURvIFdoYXQgVGhvdSBXaWx0MA0GCSqGSIb3DQEBCwUAA4IBAQC7tLmUlxyvouVuIljbRtiL+zYdi/zXVSHAMXTkceqp8/8ucZBZu1fMBkB5SW2FUFd8EnuqhKGOeS3dNr9Pe4dLbUDR0UKIwV045Na+Jet4BbHDdWs3NXAutFhdGIa8ivLBQIbTzlBuVRhJE8g6qqjf5hYL0DXkLNptl2l+0+4xJMm/liCp/mYCGRwbdGUzwdSjACO76QLLSqZhkBF37ZJOuDbJTMBi3QzkOcTs6e4d/gSZpCy7yy6nJDxZ9N9P3XBYIpus+aZAYy29d2shYzE3st8cQfB2Wmb0SHd67sftTAzeudiiNW/4E4IKKH4R1S794apUO07y7pkqep1cz32k] err=[AMQP-RPC timeout], regID=[1001]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, true)
	checkNoErrors(t)

	log.Clear()
	found, added = parseLogLine(sa, log, "0000-00-00T00:00:00+00:00 hostname boulder-ca[pid]: [AUDIT] Failed RPC to store at SA, orphaning certificate: b64der=[MIIEWzCCA0OgAwIBAgITAP+gFgYw1hiy61wFEIJLFCdIVjANBgkqhkiG9w0BAQsFADAfMR0wGwYDVQQDDBRoYXBweSBoYWNrZXIgZmFrZSBDQTAeFw0xNTEwMDMwNTIxMDBaFw0xNjAxMDEwNTIxMDBaMBgxFjAUBgNVBAMTDWV4YW1wbGUuY28uYm4wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCeo/HSH63lWW42pqdwlalHWOS3JGa3REraT3xM9v3psdRwuTtlwf3YlpF/JIzK5JtXyA3CHGSwEGmUMhMNBZ0tg5I0booXnHyUeDVUnGSnpWgMUY+vCly+pI5oT8pjBHdcj6kjnDTx1cstBjsJi9HBcYPHUh78iEZBsvC0FAKsh8cHaEjUNHzvWd1anBdK0lRn25M8le9IxXi6di9SeyFmahmPteH+LYKZtNzrF5HpatB14+ywV8d212T62PCCnUPDLd+YWjo2+t5pZs7IlGhyGh7EerOOrI2kUUBg3tUdKDp4e3xplxvaAfSfdrqkGx+bQ0iqQnng+lVkXWYWRB8NAgMBAAGjggGVMIIBkTAOBgNVHQ8BAf8EBAMCBaAwHQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMAwGA1UdEwEB/wQCMAAwHQYDVR0OBBYEFDadDBAEUrnrP/566FLp6DmjrlrbMB8GA1UdIwQYMBaAFPt4TxL5YBWDLJ8XfzQZsy426kGJMGoGCCsGAQUFBwEBBF4wXDAmBggrBgEFBQcwAYYaaHR0cDovL2xvY2FsaG9zdDo0MDAyL29jc3AwMgYIKwYBBQUHMAKGJmh0dHA6Ly9sb2NhbGhvc3Q6NDAwMC9hY21lL2lzc3Vlci1jZXJ0MBgGA1UdEQQRMA+CDWV4YW1wbGUuY28uYm4wJwYDVR0fBCAwHjAcoBqgGIYWaHR0cDovL2V4YW1wbGUuY29tL2NybDBjBgNVHSAEXDBaMAoGBmeBDAECATAAMEwGAyoDBDBFMCIGCCsGAQUFBwIBFhZodHRwOi8vZXhhbXBsZS5jb20vY3BzMB8GCCsGAQUFBwICMBMMEURvIFdoYXQgVGhvdSBXaWx0MA0GCSqGSIb3DQEBCwUAA4IBAQC7tLmUlxyvouVuIljbRtiL+zYdi/zXVSHAMXTkceqp8/8ucZBZu1fMBkB5SW2FUFd8EnuqhKGOeS3dNr9Pe4dLbUDR0UKIwV045Na+Jet4BbHDdWs3NXAutFhdGIa8ivLBQIbTzlBuVRhJE8g6qqjf5hYL0DXkLNptl2l+0+4xJMm/liCp/mYCGRwbdGUzwdSjACO76QLLSqZhkBF37ZJOuDbJTMBi3QzkOcTs6e4d/gSZpCy7yy6nJDxZ9N9P3XBYIpus+aZAYy29d2shYzE3st8cQfB2Wmb0SHd67sftTAzeudiiNW/4E4IKKH4R1S794apUO07y7pkqep1cz32k] err=[AMQP-RPC timeout], regID=[1001]")
	test.AssertEquals(t, found, true)
	test.AssertEquals(t, added, false)
	checkNoErrors(t)
}
예제 #18
0
func TestMysqlLogger(t *testing.T) {
	log := blog.UseMock()
	mLog := mysqlLogger{log}

	testCases := []struct {
		args     []interface{}
		expected string
	}{
		{
			[]interface{}{nil},
			`ERR: [AUDIT] [mysql] <nil>`,
		},
		{
			[]interface{}{""},
			`ERR: [AUDIT] [mysql] `,
		},
		{
			[]interface{}{"Sup ", 12345, " Sup sup"},
			`ERR: [AUDIT] [mysql] Sup 12345 Sup sup`,
		},
	}

	for _, tc := range testCases {
		// mysqlLogger proxies blog.AuditLogger to provide a Print() method
		mLog.Print(tc.args...)
		logged := log.GetAll()
		// Calling Print should produce the expected output
		test.AssertEquals(t, len(logged), 1)
		test.AssertEquals(t, logged[0], tc.expected)
		log.Clear()
	}
}
예제 #19
0
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)
}
예제 #20
0
func TestCfsslLogger(t *testing.T) {
	log := blog.UseMock()
	cLog := cfsslLogger{log}

	testCases := []struct {
		msg, expected string
	}{
		{
			"",
			"ERR: [AUDIT] ",
		},
		{
			"Test",
			"ERR: [AUDIT] Test",
		},
	}

	for _, tc := range testCases {
		// cfsslLogger proxies blog.AuditLogger to provide Crit() and Emerg()
		// methods that are expected by CFSSL's logger
		cLog.Crit(tc.msg)
		cLog.Emerg(tc.msg)
		logged := log.GetAll()
		// Calling Crit and Emerg should produce two AuditErr outputs matching the
		// testCase expected output
		test.AssertEquals(t, len(logged), 2)
		test.AssertEquals(t, logged[0], tc.expected)
		test.AssertEquals(t, logged[1], tc.expected)
		log.Clear()
	}
}
예제 #21
0
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)
}
예제 #22
0
func TestReuseAuthorization(t *testing.T) {
	_, sa, ra, _, cleanUp := initAuthorities(t)
	defer cleanUp()

	// Turn on AuthZ Reuse
	ra.reuseValidAuthz = true

	// Create one finalized authorization
	finalAuthz := AuthzInitial
	finalAuthz.Status = "valid"
	exp := ra.clk.Now().Add(365 * 24 * time.Hour)
	finalAuthz.Expires = &exp
	finalAuthz.Challenges[0].Status = "valid"
	finalAuthz.RegistrationID = Registration.ID
	finalAuthz, err := sa.NewPendingAuthorization(ctx, finalAuthz)
	test.AssertNotError(t, err, "Could not store test pending authorization")
	err = sa.FinalizeAuthorization(ctx, finalAuthz)
	test.AssertNotError(t, err, "Could not finalize test pending authorization")

	// Now create another authorization for the same Reg.ID/domain
	secondAuthz, err := ra.NewAuthorization(ctx, AuthzRequest, Registration.ID)
	test.AssertNotError(t, err, "NewAuthorization for secondAuthz failed")

	// The first authz should be reused as the second and thus have the same ID
	test.AssertEquals(t, finalAuthz.ID, secondAuthz.ID)

	// The second authz shouldn't be pending, it should be valid (that's why it
	// was reused)
	test.AssertEquals(t, secondAuthz.Status, core.StatusValid)

	// It should have one http challenge already marked valid
	httpIndex := ResponseIndex
	httpChallenge := secondAuthz.Challenges[httpIndex]
	test.AssertEquals(t, httpChallenge.Type, core.ChallengeTypeHTTP01)
	test.AssertEquals(t, httpChallenge.Status, core.StatusValid)

	// It should have one SNI challenge that is pending
	sniIndex := httpIndex + 1
	sniChallenge := secondAuthz.Challenges[sniIndex]
	test.AssertEquals(t, sniChallenge.Type, core.ChallengeTypeTLSSNI01)
	test.AssertEquals(t, sniChallenge.Status, core.StatusPending)

	// Sending an update to this authz for an already valid challenge should do
	// nothing (but produce no error), since it is already a valid authz
	response, err := makeResponse(httpChallenge)
	test.AssertNotError(t, err, "Unable to construct response to secondAuthz http challenge")
	secondAuthz, err = ra.UpdateAuthorization(ctx, secondAuthz, httpIndex, response)
	test.AssertNotError(t, err, "UpdateAuthorization on secondAuthz http failed")
	test.AssertEquals(t, finalAuthz.ID, secondAuthz.ID)
	test.AssertEquals(t, secondAuthz.Status, core.StatusValid)

	// Similarly, sending an update to this authz for a pending challenge should do
	// nothing (but produce no error), since the overall authz is already valid
	response, err = makeResponse(sniChallenge)
	test.AssertNotError(t, err, "Unable to construct response to secondAuthz sni challenge")
	secondAuthz, err = ra.UpdateAuthorization(ctx, secondAuthz, sniIndex, response)
	test.AssertNotError(t, err, "UpdateAuthorization on secondAuthz sni failed")
	test.AssertEquals(t, finalAuthz.ID, secondAuthz.ID)
	test.AssertEquals(t, secondAuthz.Status, core.StatusValid)
}
예제 #23
0
func TestDNSValidationNotSane(t *testing.T) {
	stats, _ := statsd.NewNoopClient()
	va := NewValidationAuthorityImpl(&PortConfig{}, nil, stats, clock.Default())
	va.DNSResolver = &mocks.DNSResolver{}
	mockRA := &MockRegistrationAuthority{}
	va.RA = mockRA

	chal0 := core.DNSChallenge01(accountKey)
	chal0.Token = ""

	chal1 := core.DNSChallenge01(accountKey)
	chal1.Token = "yfCBb-bRTLz8Wd1C0lTUQK3qlKj3-t2tYGwx5Hj7r_"

	chal2 := core.DNSChallenge01(accountKey)
	chal2.TLS = new(bool)
	*chal2.TLS = true

	var authz = core.Authorization{
		ID:             core.NewToken(),
		RegistrationID: 1,
		Identifier:     ident,
		Challenges:     []core.Challenge{chal0, chal1, chal2},
	}

	for i := 0; i < len(authz.Challenges); i++ {
		va.validate(authz, i)
		test.AssertEquals(t, authz.Challenges[i].Status, core.StatusInvalid)
		test.AssertEquals(t, authz.Challenges[i].Error.Type, core.MalformedProblem)
	}
}
예제 #24
0
func TestCountPendingAuthorizations(t *testing.T) {
	sa, fc, cleanUp := initSA(t)
	defer cleanUp()

	reg := satest.CreateWorkingRegistration(t, sa)
	expires := fc.Now().Add(time.Hour)
	pendingAuthz := core.Authorization{
		RegistrationID: reg.ID,
		Expires:        &expires,
	}

	pendingAuthz, err := sa.NewPendingAuthorization(ctx, pendingAuthz)
	test.AssertNotError(t, err, "Couldn't create new pending authorization")
	count, err := sa.CountPendingAuthorizations(ctx, reg.ID)
	test.AssertNotError(t, err, "Couldn't count pending authorizations")
	test.AssertEquals(t, count, 0)

	pendingAuthz.Status = core.StatusPending
	pendingAuthz, err = sa.NewPendingAuthorization(ctx, pendingAuthz)
	test.AssertNotError(t, err, "Couldn't create new pending authorization")
	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(ctx, reg.ID)
	test.AssertNotError(t, err, "Couldn't count pending authorizations")
	test.AssertEquals(t, count, 0)
}
// 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)
}
예제 #26
0
func TestGenerateOCSPResponses(t *testing.T) {
	updater, sa, _, fc, cleanUp := setup(t)
	defer cleanUp()

	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)
	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)
	test.AssertNotError(t, err, "Couldn't add test-cert-b.pem")

	earliest := fc.Now().Add(-time.Hour)
	certs, err := updater.findStaleOCSPResponses(earliest, 10)
	test.AssertNotError(t, err, "Couldn't find stale responses")
	test.AssertEquals(t, len(certs), 2)

	updater.generateOCSPResponses(certs)

	certs, err = updater.findStaleOCSPResponses(earliest, 10)
	test.AssertNotError(t, err, "Failed to find stale responses")
	test.AssertEquals(t, len(certs), 0)
}
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")
}
예제 #28
0
func TestFindStaleOCSPResponses(t *testing.T) {
	updater, sa, _, fc, cleanUp := setup(t)
	defer cleanUp()

	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)
	test.AssertNotError(t, err, "Couldn't add www.eff.org.der")

	earliest := fc.Now().Add(-time.Hour)
	certs, err := updater.findStaleOCSPResponses(earliest, 10)
	test.AssertNotError(t, err, "Couldn't find certificate")
	test.AssertEquals(t, len(certs), 1)

	status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
	test.AssertNotError(t, err, "Couldn't get the core.Certificate from the database")

	meta, err := updater.generateResponse(status)
	test.AssertNotError(t, err, "Couldn't generate OCSP response")
	err = updater.storeResponse(meta)
	test.AssertNotError(t, err, "Couldn't store OCSP response")

	certs, err = updater.findStaleOCSPResponses(earliest, 10)
	test.AssertNotError(t, err, "Failed to find stale responses")
	test.AssertEquals(t, len(certs), 0)
}
예제 #29
0
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)
}
예제 #30
0
func TestStoreResponseGuard(t *testing.T) {
	updater, sa, _, _, cleanUp := setup(t)
	defer cleanUp()

	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)
	test.AssertNotError(t, err, "Couldn't add www.eff.org.der")

	status, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
	test.AssertNotError(t, err, "Failed to get certificate status")

	status.OCSPResponse = []byte{0}
	err = updater.storeResponse(&status, core.OCSPStatusRevoked)
	test.AssertNotError(t, err, "Failed to update certificate status")

	unchangedStatus, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
	test.AssertNotError(t, err, "Failed to get certificate status")
	test.AssertEquals(t, len(unchangedStatus.OCSPResponse), 0)

	err = updater.storeResponse(&status, core.OCSPStatusGood)
	test.AssertNotError(t, err, "Failed to updated certificate status")

	changedStatus, err := sa.GetCertificateStatus(core.SerialToString(parsedCert.SerialNumber))
	test.AssertNotError(t, err, "Failed to get certificate status")
	test.AssertEquals(t, len(changedStatus.OCSPResponse), 1)
}