autocert_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package autocert
  5. import (
  6. "bytes"
  7. "context"
  8. "crypto"
  9. "crypto/ecdsa"
  10. "crypto/elliptic"
  11. "crypto/rand"
  12. "crypto/rsa"
  13. "crypto/tls"
  14. "crypto/x509"
  15. "crypto/x509/pkix"
  16. "encoding/asn1"
  17. "encoding/base64"
  18. "encoding/json"
  19. "fmt"
  20. "html/template"
  21. "io"
  22. "io/ioutil"
  23. "math/big"
  24. "net/http"
  25. "net/http/httptest"
  26. "reflect"
  27. "strings"
  28. "sync"
  29. "testing"
  30. "time"
  31. "golang.org/x/crypto/acme"
  32. "golang.org/x/crypto/acme/autocert/internal/acmetest"
  33. )
  34. var (
  35. exampleDomain = "example.org"
  36. exampleCertKey = certKey{domain: exampleDomain}
  37. exampleCertKeyRSA = certKey{domain: exampleDomain, isRSA: true}
  38. )
  39. var discoTmpl = template.Must(template.New("disco").Parse(`{
  40. "new-reg": "{{.}}/new-reg",
  41. "new-authz": "{{.}}/new-authz",
  42. "new-cert": "{{.}}/new-cert"
  43. }`))
  44. var authzTmpl = template.Must(template.New("authz").Parse(`{
  45. "status": "pending",
  46. "challenges": [
  47. {
  48. "uri": "{{.}}/challenge/tls-alpn-01",
  49. "type": "tls-alpn-01",
  50. "token": "token-alpn"
  51. },
  52. {
  53. "uri": "{{.}}/challenge/dns-01",
  54. "type": "dns-01",
  55. "token": "token-dns-01"
  56. },
  57. {
  58. "uri": "{{.}}/challenge/http-01",
  59. "type": "http-01",
  60. "token": "token-http-01"
  61. }
  62. ]
  63. }`))
  64. type memCache struct {
  65. t *testing.T
  66. mu sync.Mutex
  67. keyData map[string][]byte
  68. }
  69. func (m *memCache) Get(ctx context.Context, key string) ([]byte, error) {
  70. m.mu.Lock()
  71. defer m.mu.Unlock()
  72. v, ok := m.keyData[key]
  73. if !ok {
  74. return nil, ErrCacheMiss
  75. }
  76. return v, nil
  77. }
  78. // filenameSafe returns whether all characters in s are printable ASCII
  79. // and safe to use in a filename on most filesystems.
  80. func filenameSafe(s string) bool {
  81. for _, c := range s {
  82. if c < 0x20 || c > 0x7E {
  83. return false
  84. }
  85. switch c {
  86. case '\\', '/', ':', '*', '?', '"', '<', '>', '|':
  87. return false
  88. }
  89. }
  90. return true
  91. }
  92. func (m *memCache) Put(ctx context.Context, key string, data []byte) error {
  93. if !filenameSafe(key) {
  94. m.t.Errorf("invalid characters in cache key %q", key)
  95. }
  96. m.mu.Lock()
  97. defer m.mu.Unlock()
  98. m.keyData[key] = data
  99. return nil
  100. }
  101. func (m *memCache) Delete(ctx context.Context, key string) error {
  102. m.mu.Lock()
  103. defer m.mu.Unlock()
  104. delete(m.keyData, key)
  105. return nil
  106. }
  107. func newMemCache(t *testing.T) *memCache {
  108. return &memCache{
  109. t: t,
  110. keyData: make(map[string][]byte),
  111. }
  112. }
  113. func (m *memCache) numCerts() int {
  114. m.mu.Lock()
  115. defer m.mu.Unlock()
  116. res := 0
  117. for key := range m.keyData {
  118. if strings.HasSuffix(key, "+token") ||
  119. strings.HasSuffix(key, "+key") ||
  120. strings.HasSuffix(key, "+http-01") {
  121. continue
  122. }
  123. res++
  124. }
  125. return res
  126. }
  127. func dummyCert(pub interface{}, san ...string) ([]byte, error) {
  128. return dateDummyCert(pub, time.Now(), time.Now().Add(90*24*time.Hour), san...)
  129. }
  130. func dateDummyCert(pub interface{}, start, end time.Time, san ...string) ([]byte, error) {
  131. // use EC key to run faster on 386
  132. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  133. if err != nil {
  134. return nil, err
  135. }
  136. t := &x509.Certificate{
  137. SerialNumber: big.NewInt(1),
  138. NotBefore: start,
  139. NotAfter: end,
  140. BasicConstraintsValid: true,
  141. KeyUsage: x509.KeyUsageKeyEncipherment,
  142. DNSNames: san,
  143. }
  144. if pub == nil {
  145. pub = &key.PublicKey
  146. }
  147. return x509.CreateCertificate(rand.Reader, t, t, pub, key)
  148. }
  149. func decodePayload(v interface{}, r io.Reader) error {
  150. var req struct{ Payload string }
  151. if err := json.NewDecoder(r).Decode(&req); err != nil {
  152. return err
  153. }
  154. payload, err := base64.RawURLEncoding.DecodeString(req.Payload)
  155. if err != nil {
  156. return err
  157. }
  158. return json.Unmarshal(payload, v)
  159. }
  160. type algorithmSupport int
  161. const (
  162. algRSA algorithmSupport = iota
  163. algECDSA
  164. )
  165. func clientHelloInfo(sni string, alg algorithmSupport) *tls.ClientHelloInfo {
  166. hello := &tls.ClientHelloInfo{
  167. ServerName: sni,
  168. CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305},
  169. }
  170. if alg == algECDSA {
  171. hello.CipherSuites = append(hello.CipherSuites, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305)
  172. }
  173. return hello
  174. }
  175. // tokenCertFn returns a function suitable for startACMEServerStub.
  176. // The returned function simulates a TLS hello request from a CA
  177. // during validation of a tls-alpn-01 challenge.
  178. func tokenCertFn(man *Manager, alg algorithmSupport) getCertificateFunc {
  179. return func(sni string) (*tls.Certificate, error) {
  180. hello := clientHelloInfo(sni, alg)
  181. hello.SupportedProtos = []string{acme.ALPNProto}
  182. return man.GetCertificate(hello)
  183. }
  184. }
  185. func TestGetCertificate(t *testing.T) {
  186. man := &Manager{Prompt: AcceptTOS}
  187. defer man.stopRenew()
  188. hello := clientHelloInfo("example.org", algECDSA)
  189. testGetCertificate(t, man, "example.org", hello)
  190. }
  191. func TestGetCertificate_trailingDot(t *testing.T) {
  192. man := &Manager{Prompt: AcceptTOS}
  193. defer man.stopRenew()
  194. hello := clientHelloInfo("example.org.", algECDSA)
  195. testGetCertificate(t, man, "example.org", hello)
  196. }
  197. func TestGetCertificate_unicodeIDN(t *testing.T) {
  198. man := &Manager{Prompt: AcceptTOS}
  199. defer man.stopRenew()
  200. hello := clientHelloInfo("σσσ.com", algECDSA)
  201. testGetCertificate(t, man, "xn--4xaaa.com", hello)
  202. hello = clientHelloInfo("σςΣ.com", algECDSA)
  203. testGetCertificate(t, man, "xn--4xaaa.com", hello)
  204. }
  205. func TestGetCertificate_mixedcase(t *testing.T) {
  206. man := &Manager{Prompt: AcceptTOS}
  207. defer man.stopRenew()
  208. hello := clientHelloInfo("example.org", algECDSA)
  209. testGetCertificate(t, man, "example.org", hello)
  210. hello = clientHelloInfo("EXAMPLE.ORG", algECDSA)
  211. testGetCertificate(t, man, "example.org", hello)
  212. }
  213. func TestGetCertificate_ForceRSA(t *testing.T) {
  214. man := &Manager{
  215. Prompt: AcceptTOS,
  216. Cache: newMemCache(t),
  217. ForceRSA: true,
  218. }
  219. defer man.stopRenew()
  220. hello := clientHelloInfo(exampleDomain, algECDSA)
  221. testGetCertificate(t, man, exampleDomain, hello)
  222. // ForceRSA was deprecated and is now ignored.
  223. cert, err := man.cacheGet(context.Background(), exampleCertKey)
  224. if err != nil {
  225. t.Fatalf("man.cacheGet: %v", err)
  226. }
  227. if _, ok := cert.PrivateKey.(*ecdsa.PrivateKey); !ok {
  228. t.Errorf("cert.PrivateKey is %T; want *ecdsa.PrivateKey", cert.PrivateKey)
  229. }
  230. }
  231. func TestGetCertificate_nilPrompt(t *testing.T) {
  232. man := &Manager{}
  233. defer man.stopRenew()
  234. url, finish := startACMEServerStub(t, tokenCertFn(man, algECDSA), "example.org")
  235. defer finish()
  236. man.Client = &acme.Client{DirectoryURL: url}
  237. hello := clientHelloInfo("example.org", algECDSA)
  238. if _, err := man.GetCertificate(hello); err == nil {
  239. t.Error("got certificate for example.org; wanted error")
  240. }
  241. }
  242. func TestGetCertificate_expiredCache(t *testing.T) {
  243. // Make an expired cert and cache it.
  244. pk, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  245. if err != nil {
  246. t.Fatal(err)
  247. }
  248. tmpl := &x509.Certificate{
  249. SerialNumber: big.NewInt(1),
  250. Subject: pkix.Name{CommonName: exampleDomain},
  251. NotAfter: time.Now(),
  252. }
  253. pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &pk.PublicKey, pk)
  254. if err != nil {
  255. t.Fatal(err)
  256. }
  257. tlscert := &tls.Certificate{
  258. Certificate: [][]byte{pub},
  259. PrivateKey: pk,
  260. }
  261. man := &Manager{Prompt: AcceptTOS, Cache: newMemCache(t)}
  262. defer man.stopRenew()
  263. if err := man.cachePut(context.Background(), exampleCertKey, tlscert); err != nil {
  264. t.Fatalf("man.cachePut: %v", err)
  265. }
  266. // The expired cached cert should trigger a new cert issuance
  267. // and return without an error.
  268. hello := clientHelloInfo(exampleDomain, algECDSA)
  269. testGetCertificate(t, man, exampleDomain, hello)
  270. }
  271. func TestGetCertificate_failedAttempt(t *testing.T) {
  272. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  273. w.WriteHeader(http.StatusBadRequest)
  274. }))
  275. defer ts.Close()
  276. d := createCertRetryAfter
  277. f := testDidRemoveState
  278. defer func() {
  279. createCertRetryAfter = d
  280. testDidRemoveState = f
  281. }()
  282. createCertRetryAfter = 0
  283. done := make(chan struct{})
  284. testDidRemoveState = func(ck certKey) {
  285. if ck != exampleCertKey {
  286. t.Errorf("testDidRemoveState: domain = %v; want %v", ck, exampleCertKey)
  287. }
  288. close(done)
  289. }
  290. man := &Manager{
  291. Prompt: AcceptTOS,
  292. Client: &acme.Client{
  293. DirectoryURL: ts.URL,
  294. },
  295. }
  296. defer man.stopRenew()
  297. hello := clientHelloInfo(exampleDomain, algECDSA)
  298. if _, err := man.GetCertificate(hello); err == nil {
  299. t.Error("GetCertificate: err is nil")
  300. }
  301. select {
  302. case <-time.After(5 * time.Second):
  303. t.Errorf("took too long to remove the %q state", exampleCertKey)
  304. case <-done:
  305. man.stateMu.Lock()
  306. defer man.stateMu.Unlock()
  307. if v, exist := man.state[exampleCertKey]; exist {
  308. t.Errorf("state exists for %v: %+v", exampleCertKey, v)
  309. }
  310. }
  311. }
  312. // testGetCertificate_tokenCache tests the fallback of token certificate fetches
  313. // to cache when Manager.certTokens misses.
  314. // algorithmSupport refers to the CA when verifying the certificate token.
  315. func testGetCertificate_tokenCache(t *testing.T, tokenAlg algorithmSupport) {
  316. man1 := &Manager{
  317. Cache: newMemCache(t),
  318. Prompt: AcceptTOS,
  319. }
  320. defer man1.stopRenew()
  321. man2 := &Manager{
  322. Cache: man1.Cache,
  323. Prompt: AcceptTOS,
  324. }
  325. defer man2.stopRenew()
  326. // Send the verification request to a different Manager from the one that
  327. // initiated the authorization, when they share caches.
  328. url, finish := startACMEServerStub(t, tokenCertFn(man2, tokenAlg), "example.org")
  329. defer finish()
  330. man1.Client = &acme.Client{DirectoryURL: url}
  331. man2.Client = &acme.Client{DirectoryURL: url}
  332. hello := clientHelloInfo("example.org", algECDSA)
  333. if _, err := man1.GetCertificate(hello); err != nil {
  334. t.Error(err)
  335. }
  336. if _, err := man2.GetCertificate(hello); err != nil {
  337. t.Error(err)
  338. }
  339. }
  340. func TestGetCertificate_tokenCache(t *testing.T) {
  341. t.Run("ecdsaSupport=true", func(t *testing.T) {
  342. testGetCertificate_tokenCache(t, algECDSA)
  343. })
  344. t.Run("ecdsaSupport=false", func(t *testing.T) {
  345. testGetCertificate_tokenCache(t, algRSA)
  346. })
  347. }
  348. func TestGetCertificate_ecdsaVsRSA(t *testing.T) {
  349. cache := newMemCache(t)
  350. man := &Manager{Prompt: AcceptTOS, Cache: cache}
  351. defer man.stopRenew()
  352. url, finish := startACMEServerStub(t, tokenCertFn(man, algECDSA), "example.org")
  353. defer finish()
  354. man.Client = &acme.Client{DirectoryURL: url}
  355. cert, err := man.GetCertificate(clientHelloInfo("example.org", algECDSA))
  356. if err != nil {
  357. t.Fatal(err)
  358. }
  359. if _, ok := cert.Leaf.PublicKey.(*ecdsa.PublicKey); !ok {
  360. t.Error("an ECDSA client was served a non-ECDSA certificate")
  361. }
  362. cert, err = man.GetCertificate(clientHelloInfo("example.org", algRSA))
  363. if err != nil {
  364. t.Fatal(err)
  365. }
  366. if _, ok := cert.Leaf.PublicKey.(*rsa.PublicKey); !ok {
  367. t.Error("a RSA client was served a non-RSA certificate")
  368. }
  369. if _, err := man.GetCertificate(clientHelloInfo("example.org", algECDSA)); err != nil {
  370. t.Error(err)
  371. }
  372. if _, err := man.GetCertificate(clientHelloInfo("example.org", algRSA)); err != nil {
  373. t.Error(err)
  374. }
  375. if numCerts := cache.numCerts(); numCerts != 2 {
  376. t.Errorf("found %d certificates in cache; want %d", numCerts, 2)
  377. }
  378. }
  379. func TestGetCertificate_wrongCacheKeyType(t *testing.T) {
  380. cache := newMemCache(t)
  381. man := &Manager{Prompt: AcceptTOS, Cache: cache}
  382. defer man.stopRenew()
  383. url, finish := startACMEServerStub(t, tokenCertFn(man, algECDSA), exampleDomain)
  384. defer finish()
  385. man.Client = &acme.Client{DirectoryURL: url}
  386. // Make an RSA cert and cache it without suffix.
  387. pk, err := rsa.GenerateKey(rand.Reader, 512)
  388. if err != nil {
  389. t.Fatal(err)
  390. }
  391. tmpl := &x509.Certificate{
  392. SerialNumber: big.NewInt(1),
  393. Subject: pkix.Name{CommonName: exampleDomain},
  394. NotAfter: time.Now().Add(90 * 24 * time.Hour),
  395. }
  396. pub, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &pk.PublicKey, pk)
  397. if err != nil {
  398. t.Fatal(err)
  399. }
  400. rsaCert := &tls.Certificate{
  401. Certificate: [][]byte{pub},
  402. PrivateKey: pk,
  403. }
  404. if err := man.cachePut(context.Background(), exampleCertKey, rsaCert); err != nil {
  405. t.Fatalf("man.cachePut: %v", err)
  406. }
  407. // The RSA cached cert should be silently ignored and replaced.
  408. cert, err := man.GetCertificate(clientHelloInfo(exampleDomain, algECDSA))
  409. if err != nil {
  410. t.Fatal(err)
  411. }
  412. if _, ok := cert.Leaf.PublicKey.(*ecdsa.PublicKey); !ok {
  413. t.Error("an ECDSA client was served a non-ECDSA certificate")
  414. }
  415. if numCerts := cache.numCerts(); numCerts != 1 {
  416. t.Errorf("found %d certificates in cache; want %d", numCerts, 1)
  417. }
  418. }
  419. type getCertificateFunc func(domain string) (*tls.Certificate, error)
  420. // startACMEServerStub runs an ACME server
  421. // The domain argument is the expected domain name of a certificate request.
  422. // TODO: Drop this in favour of x/crypto/acme/autocert/internal/acmetest.
  423. func startACMEServerStub(t *testing.T, tokenCert getCertificateFunc, domain string) (url string, finish func()) {
  424. verifyTokenCert := func() {
  425. tlscert, err := tokenCert(domain)
  426. if err != nil {
  427. t.Errorf("verifyTokenCert: tokenCert(%q): %v", domain, err)
  428. return
  429. }
  430. crt, err := x509.ParseCertificate(tlscert.Certificate[0])
  431. if err != nil {
  432. t.Errorf("verifyTokenCert: x509.ParseCertificate: %v", err)
  433. }
  434. if err := crt.VerifyHostname(domain); err != nil {
  435. t.Errorf("verifyTokenCert: %v", err)
  436. }
  437. // TODO: Update OID to the latest value 1.3.6.1.5.5.7.1.31
  438. // See https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-5.1
  439. oid := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
  440. for _, x := range crt.Extensions {
  441. if x.Id.Equal(oid) {
  442. // No need to check the extension value here.
  443. // This is done in acme package tests.
  444. return
  445. }
  446. }
  447. t.Error("verifyTokenCert: no id-pe-acmeIdentifier extension found")
  448. }
  449. // ACME CA server stub
  450. var ca *httptest.Server
  451. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  452. w.Header().Set("Replay-Nonce", "nonce")
  453. if r.Method == "HEAD" {
  454. // a nonce request
  455. return
  456. }
  457. switch r.URL.Path {
  458. // discovery
  459. case "/":
  460. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  461. t.Errorf("discoTmpl: %v", err)
  462. }
  463. // client key registration
  464. case "/new-reg":
  465. w.Write([]byte("{}"))
  466. // domain authorization
  467. case "/new-authz":
  468. w.Header().Set("Location", ca.URL+"/authz/1")
  469. w.WriteHeader(http.StatusCreated)
  470. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  471. t.Errorf("authzTmpl: %v", err)
  472. }
  473. // accept tls-alpn-01 challenge
  474. case "/challenge/tls-alpn-01":
  475. verifyTokenCert()
  476. w.Write([]byte("{}"))
  477. // authorization status
  478. case "/authz/1":
  479. w.Write([]byte(`{"status": "valid"}`))
  480. // cert request
  481. case "/new-cert":
  482. var req struct {
  483. CSR string `json:"csr"`
  484. }
  485. decodePayload(&req, r.Body)
  486. b, _ := base64.RawURLEncoding.DecodeString(req.CSR)
  487. csr, err := x509.ParseCertificateRequest(b)
  488. if err != nil {
  489. t.Errorf("new-cert: CSR: %v", err)
  490. }
  491. if csr.Subject.CommonName != domain {
  492. t.Errorf("CommonName in CSR = %q; want %q", csr.Subject.CommonName, domain)
  493. }
  494. der, err := dummyCert(csr.PublicKey, domain)
  495. if err != nil {
  496. t.Errorf("new-cert: dummyCert: %v", err)
  497. }
  498. chainUp := fmt.Sprintf("<%s/ca-cert>; rel=up", ca.URL)
  499. w.Header().Set("Link", chainUp)
  500. w.WriteHeader(http.StatusCreated)
  501. w.Write(der)
  502. // CA chain cert
  503. case "/ca-cert":
  504. der, err := dummyCert(nil, "ca")
  505. if err != nil {
  506. t.Errorf("ca-cert: dummyCert: %v", err)
  507. }
  508. w.Write(der)
  509. default:
  510. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  511. }
  512. }))
  513. finish = func() {
  514. ca.Close()
  515. // make sure token cert was removed
  516. cancel := make(chan struct{})
  517. done := make(chan struct{})
  518. go func() {
  519. defer close(done)
  520. tick := time.NewTicker(100 * time.Millisecond)
  521. defer tick.Stop()
  522. for {
  523. if _, err := tokenCert(domain); err != nil {
  524. return
  525. }
  526. select {
  527. case <-tick.C:
  528. case <-cancel:
  529. return
  530. }
  531. }
  532. }()
  533. select {
  534. case <-done:
  535. case <-time.After(5 * time.Second):
  536. close(cancel)
  537. t.Error("token cert was not removed")
  538. <-done
  539. }
  540. }
  541. return ca.URL, finish
  542. }
  543. // tests man.GetCertificate flow using the provided hello argument.
  544. // The domain argument is the expected domain name of a certificate request.
  545. func testGetCertificate(t *testing.T, man *Manager, domain string, hello *tls.ClientHelloInfo) {
  546. url, finish := startACMEServerStub(t, tokenCertFn(man, algECDSA), domain)
  547. defer finish()
  548. man.Client = &acme.Client{DirectoryURL: url}
  549. // simulate tls.Config.GetCertificate
  550. var tlscert *tls.Certificate
  551. var err error
  552. done := make(chan struct{})
  553. go func() {
  554. tlscert, err = man.GetCertificate(hello)
  555. close(done)
  556. }()
  557. select {
  558. case <-time.After(time.Minute):
  559. t.Fatal("man.GetCertificate took too long to return")
  560. case <-done:
  561. }
  562. if err != nil {
  563. t.Fatalf("man.GetCertificate: %v", err)
  564. }
  565. // verify the tlscert is the same we responded with from the CA stub
  566. if len(tlscert.Certificate) == 0 {
  567. t.Fatal("len(tlscert.Certificate) is 0")
  568. }
  569. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  570. if err != nil {
  571. t.Fatalf("x509.ParseCertificate: %v", err)
  572. }
  573. if len(cert.DNSNames) == 0 || cert.DNSNames[0] != domain {
  574. t.Errorf("cert.DNSNames = %v; want %q", cert.DNSNames, domain)
  575. }
  576. }
  577. func TestVerifyHTTP01(t *testing.T) {
  578. var (
  579. http01 http.Handler
  580. authzCount int // num. of created authorizations
  581. didAcceptHTTP01 bool
  582. )
  583. verifyHTTPToken := func() {
  584. r := httptest.NewRequest("GET", "/.well-known/acme-challenge/token-http-01", nil)
  585. w := httptest.NewRecorder()
  586. http01.ServeHTTP(w, r)
  587. if w.Code != http.StatusOK {
  588. t.Errorf("http token: w.Code = %d; want %d", w.Code, http.StatusOK)
  589. }
  590. if v := w.Body.String(); !strings.HasPrefix(v, "token-http-01.") {
  591. t.Errorf("http token value = %q; want 'token-http-01.' prefix", v)
  592. }
  593. }
  594. // ACME CA server stub, only the needed bits.
  595. // TODO: Replace this with x/crypto/acme/autocert/internal/acmetest.
  596. var ca *httptest.Server
  597. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  598. w.Header().Set("Replay-Nonce", "nonce")
  599. if r.Method == "HEAD" {
  600. // a nonce request
  601. return
  602. }
  603. switch r.URL.Path {
  604. // Discovery.
  605. case "/":
  606. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  607. t.Errorf("discoTmpl: %v", err)
  608. }
  609. // Client key registration.
  610. case "/new-reg":
  611. w.Write([]byte("{}"))
  612. // New domain authorization.
  613. case "/new-authz":
  614. authzCount++
  615. w.Header().Set("Location", fmt.Sprintf("%s/authz/%d", ca.URL, authzCount))
  616. w.WriteHeader(http.StatusCreated)
  617. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  618. t.Errorf("authzTmpl: %v", err)
  619. }
  620. // Reject tls-alpn-01.
  621. case "/challenge/tls-alpn-01":
  622. http.Error(w, "won't accept tls-sni-01", http.StatusBadRequest)
  623. // Should not accept dns-01.
  624. case "/challenge/dns-01":
  625. t.Errorf("dns-01 challenge was accepted")
  626. http.Error(w, "won't accept dns-01", http.StatusBadRequest)
  627. // Accept http-01.
  628. case "/challenge/http-01":
  629. didAcceptHTTP01 = true
  630. verifyHTTPToken()
  631. w.Write([]byte("{}"))
  632. // Authorization statuses.
  633. case "/authz/1": // tls-alpn-01
  634. w.Write([]byte(`{"status": "invalid"}`))
  635. case "/authz/2": // http-01
  636. w.Write([]byte(`{"status": "valid"}`))
  637. default:
  638. http.NotFound(w, r)
  639. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  640. }
  641. }))
  642. defer ca.Close()
  643. m := &Manager{
  644. Client: &acme.Client{
  645. DirectoryURL: ca.URL,
  646. },
  647. }
  648. http01 = m.HTTPHandler(nil)
  649. ctx := context.Background()
  650. client, err := m.acmeClient(ctx)
  651. if err != nil {
  652. t.Fatalf("m.acmeClient: %v", err)
  653. }
  654. if err := m.verify(ctx, client, "example.org"); err != nil {
  655. t.Errorf("m.verify: %v", err)
  656. }
  657. // Only tls-alpn-01 and http-01 must be accepted.
  658. // The dns-01 challenge is unsupported.
  659. if authzCount != 2 {
  660. t.Errorf("authzCount = %d; want 2", authzCount)
  661. }
  662. if !didAcceptHTTP01 {
  663. t.Error("did not accept http-01 challenge")
  664. }
  665. }
  666. func TestRevokeFailedAuthz(t *testing.T) {
  667. // Prefill authorization URIs expected to be revoked.
  668. // The challenges are selected in a specific order,
  669. // each tried within a newly created authorization.
  670. // This means each authorization URI corresponds to a different challenge type.
  671. revokedAuthz := map[string]bool{
  672. "/authz/0": false, // tls-alpn-01
  673. "/authz/1": false, // http-01
  674. "/authz/2": false, // no viable challenge, but authz is created
  675. }
  676. var authzCount int // num. of created authorizations
  677. var revokeCount int // num. of revoked authorizations
  678. done := make(chan struct{}) // closed when revokeCount is 3
  679. // ACME CA server stub, only the needed bits.
  680. // TODO: Replace this with x/crypto/acme/autocert/internal/acmetest.
  681. var ca *httptest.Server
  682. ca = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  683. w.Header().Set("Replay-Nonce", "nonce")
  684. if r.Method == "HEAD" {
  685. // a nonce request
  686. return
  687. }
  688. switch r.URL.Path {
  689. // Discovery.
  690. case "/":
  691. if err := discoTmpl.Execute(w, ca.URL); err != nil {
  692. t.Errorf("discoTmpl: %v", err)
  693. }
  694. // Client key registration.
  695. case "/new-reg":
  696. w.Write([]byte("{}"))
  697. // New domain authorization.
  698. case "/new-authz":
  699. w.Header().Set("Location", fmt.Sprintf("%s/authz/%d", ca.URL, authzCount))
  700. w.WriteHeader(http.StatusCreated)
  701. if err := authzTmpl.Execute(w, ca.URL); err != nil {
  702. t.Errorf("authzTmpl: %v", err)
  703. }
  704. authzCount++
  705. // tls-alpn-01 challenge "accept" request.
  706. case "/challenge/tls-alpn-01":
  707. // Refuse.
  708. http.Error(w, "won't accept tls-alpn-01 challenge", http.StatusBadRequest)
  709. // http-01 challenge "accept" request.
  710. case "/challenge/http-01":
  711. // Refuse.
  712. w.WriteHeader(http.StatusBadRequest)
  713. w.Write([]byte(`{"status":"invalid"}`))
  714. // Authorization requests.
  715. case "/authz/0", "/authz/1", "/authz/2":
  716. // Revocation requests.
  717. if r.Method == "POST" {
  718. var req struct{ Status string }
  719. if err := decodePayload(&req, r.Body); err != nil {
  720. t.Errorf("%s: decodePayload: %v", r.URL, err)
  721. }
  722. switch req.Status {
  723. case "deactivated":
  724. revokedAuthz[r.URL.Path] = true
  725. revokeCount++
  726. if revokeCount >= 3 {
  727. // Last authorization is revoked.
  728. defer close(done)
  729. }
  730. default:
  731. t.Errorf("%s: req.Status = %q; want 'deactivated'", r.URL, req.Status)
  732. }
  733. w.Write([]byte(`{"status": "invalid"}`))
  734. return
  735. }
  736. // Authorization status requests.
  737. w.Write([]byte(`{"status":"pending"}`))
  738. default:
  739. http.NotFound(w, r)
  740. t.Errorf("unrecognized r.URL.Path: %s", r.URL.Path)
  741. }
  742. }))
  743. defer ca.Close()
  744. m := &Manager{
  745. Client: &acme.Client{DirectoryURL: ca.URL},
  746. }
  747. m.HTTPHandler(nil) // enable http-01 challenge type
  748. // Should fail and revoke 3 authorizations.
  749. // The first 2 are tls-alpn-01 and http-01 challenges.
  750. // The third time an authorization is created but no viable challenge is found.
  751. // See revokedAuthz above for more explanation.
  752. if _, err := m.createCert(context.Background(), exampleCertKey); err == nil {
  753. t.Errorf("m.createCert returned nil error")
  754. }
  755. select {
  756. case <-time.After(3 * time.Second):
  757. t.Error("revocations took too long")
  758. case <-done:
  759. // revokeCount is at least 3.
  760. }
  761. for uri, ok := range revokedAuthz {
  762. if !ok {
  763. t.Errorf("%q authorization was not revoked", uri)
  764. }
  765. }
  766. }
  767. func TestHTTPHandlerDefaultFallback(t *testing.T) {
  768. tt := []struct {
  769. method, url string
  770. wantCode int
  771. wantLocation string
  772. }{
  773. {"GET", "http://example.org", 302, "https://example.org/"},
  774. {"GET", "http://example.org/foo", 302, "https://example.org/foo"},
  775. {"GET", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
  776. {"GET", "http://example.org/?a=b", 302, "https://example.org/?a=b"},
  777. {"GET", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
  778. {"GET", "http://example.org:80/foo?a=b", 302, "https://example.org:443/foo?a=b"},
  779. {"GET", "http://example.org:80/foo%20bar", 302, "https://example.org:443/foo%20bar"},
  780. {"GET", "http://[2602:d1:xxxx::c60a]:1234", 302, "https://[2602:d1:xxxx::c60a]:443/"},
  781. {"GET", "http://[2602:d1:xxxx::c60a]", 302, "https://[2602:d1:xxxx::c60a]/"},
  782. {"GET", "http://[2602:d1:xxxx::c60a]/foo?a=b", 302, "https://[2602:d1:xxxx::c60a]/foo?a=b"},
  783. {"HEAD", "http://example.org", 302, "https://example.org/"},
  784. {"HEAD", "http://example.org/foo", 302, "https://example.org/foo"},
  785. {"HEAD", "http://example.org/foo/bar/", 302, "https://example.org/foo/bar/"},
  786. {"HEAD", "http://example.org/?a=b", 302, "https://example.org/?a=b"},
  787. {"HEAD", "http://example.org/foo?a=b", 302, "https://example.org/foo?a=b"},
  788. {"POST", "http://example.org", 400, ""},
  789. {"PUT", "http://example.org", 400, ""},
  790. {"GET", "http://example.org/.well-known/acme-challenge/x", 404, ""},
  791. }
  792. var m Manager
  793. h := m.HTTPHandler(nil)
  794. for i, test := range tt {
  795. r := httptest.NewRequest(test.method, test.url, nil)
  796. w := httptest.NewRecorder()
  797. h.ServeHTTP(w, r)
  798. if w.Code != test.wantCode {
  799. t.Errorf("%d: w.Code = %d; want %d", i, w.Code, test.wantCode)
  800. t.Errorf("%d: body: %s", i, w.Body.Bytes())
  801. }
  802. if v := w.Header().Get("Location"); v != test.wantLocation {
  803. t.Errorf("%d: Location = %q; want %q", i, v, test.wantLocation)
  804. }
  805. }
  806. }
  807. func TestAccountKeyCache(t *testing.T) {
  808. m := Manager{Cache: newMemCache(t)}
  809. ctx := context.Background()
  810. k1, err := m.accountKey(ctx)
  811. if err != nil {
  812. t.Fatal(err)
  813. }
  814. k2, err := m.accountKey(ctx)
  815. if err != nil {
  816. t.Fatal(err)
  817. }
  818. if !reflect.DeepEqual(k1, k2) {
  819. t.Errorf("account keys don't match: k1 = %#v; k2 = %#v", k1, k2)
  820. }
  821. }
  822. func TestCache(t *testing.T) {
  823. ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  824. if err != nil {
  825. t.Fatal(err)
  826. }
  827. cert, err := dummyCert(ecdsaKey.Public(), exampleDomain)
  828. if err != nil {
  829. t.Fatal(err)
  830. }
  831. ecdsaCert := &tls.Certificate{
  832. Certificate: [][]byte{cert},
  833. PrivateKey: ecdsaKey,
  834. }
  835. rsaKey, err := rsa.GenerateKey(rand.Reader, 512)
  836. if err != nil {
  837. t.Fatal(err)
  838. }
  839. cert, err = dummyCert(rsaKey.Public(), exampleDomain)
  840. if err != nil {
  841. t.Fatal(err)
  842. }
  843. rsaCert := &tls.Certificate{
  844. Certificate: [][]byte{cert},
  845. PrivateKey: rsaKey,
  846. }
  847. man := &Manager{Cache: newMemCache(t)}
  848. defer man.stopRenew()
  849. ctx := context.Background()
  850. if err := man.cachePut(ctx, exampleCertKey, ecdsaCert); err != nil {
  851. t.Fatalf("man.cachePut: %v", err)
  852. }
  853. if err := man.cachePut(ctx, exampleCertKeyRSA, rsaCert); err != nil {
  854. t.Fatalf("man.cachePut: %v", err)
  855. }
  856. res, err := man.cacheGet(ctx, exampleCertKey)
  857. if err != nil {
  858. t.Fatalf("man.cacheGet: %v", err)
  859. }
  860. if res == nil || !bytes.Equal(res.Certificate[0], ecdsaCert.Certificate[0]) {
  861. t.Errorf("man.cacheGet = %+v; want %+v", res, ecdsaCert)
  862. }
  863. res, err = man.cacheGet(ctx, exampleCertKeyRSA)
  864. if err != nil {
  865. t.Fatalf("man.cacheGet: %v", err)
  866. }
  867. if res == nil || !bytes.Equal(res.Certificate[0], rsaCert.Certificate[0]) {
  868. t.Errorf("man.cacheGet = %+v; want %+v", res, rsaCert)
  869. }
  870. }
  871. func TestHostWhitelist(t *testing.T) {
  872. policy := HostWhitelist("example.com", "EXAMPLE.ORG", "*.example.net", "σςΣ.com")
  873. tt := []struct {
  874. host string
  875. allow bool
  876. }{
  877. {"example.com", true},
  878. {"example.org", true},
  879. {"xn--4xaaa.com", true},
  880. {"one.example.com", false},
  881. {"two.example.org", false},
  882. {"three.example.net", false},
  883. {"dummy", false},
  884. }
  885. for i, test := range tt {
  886. err := policy(nil, test.host)
  887. if err != nil && test.allow {
  888. t.Errorf("%d: policy(%q): %v; want nil", i, test.host, err)
  889. }
  890. if err == nil && !test.allow {
  891. t.Errorf("%d: policy(%q): nil; want an error", i, test.host)
  892. }
  893. }
  894. }
  895. func TestValidCert(t *testing.T) {
  896. key1, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  897. if err != nil {
  898. t.Fatal(err)
  899. }
  900. key2, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  901. if err != nil {
  902. t.Fatal(err)
  903. }
  904. key3, err := rsa.GenerateKey(rand.Reader, 512)
  905. if err != nil {
  906. t.Fatal(err)
  907. }
  908. cert1, err := dummyCert(key1.Public(), "example.org")
  909. if err != nil {
  910. t.Fatal(err)
  911. }
  912. cert2, err := dummyCert(key2.Public(), "example.org")
  913. if err != nil {
  914. t.Fatal(err)
  915. }
  916. cert3, err := dummyCert(key3.Public(), "example.org")
  917. if err != nil {
  918. t.Fatal(err)
  919. }
  920. now := time.Now()
  921. early, err := dateDummyCert(key1.Public(), now.Add(time.Hour), now.Add(2*time.Hour), "example.org")
  922. if err != nil {
  923. t.Fatal(err)
  924. }
  925. expired, err := dateDummyCert(key1.Public(), now.Add(-2*time.Hour), now.Add(-time.Hour), "example.org")
  926. if err != nil {
  927. t.Fatal(err)
  928. }
  929. tt := []struct {
  930. ck certKey
  931. key crypto.Signer
  932. cert [][]byte
  933. ok bool
  934. }{
  935. {certKey{domain: "example.org"}, key1, [][]byte{cert1}, true},
  936. {certKey{domain: "example.org", isRSA: true}, key3, [][]byte{cert3}, true},
  937. {certKey{domain: "example.org"}, key1, [][]byte{cert1, cert2, cert3}, true},
  938. {certKey{domain: "example.org"}, key1, [][]byte{cert1, {1}}, false},
  939. {certKey{domain: "example.org"}, key1, [][]byte{{1}}, false},
  940. {certKey{domain: "example.org"}, key1, [][]byte{cert2}, false},
  941. {certKey{domain: "example.org"}, key2, [][]byte{cert1}, false},
  942. {certKey{domain: "example.org"}, key1, [][]byte{cert3}, false},
  943. {certKey{domain: "example.org"}, key3, [][]byte{cert1}, false},
  944. {certKey{domain: "example.net"}, key1, [][]byte{cert1}, false},
  945. {certKey{domain: "example.org"}, key1, [][]byte{early}, false},
  946. {certKey{domain: "example.org"}, key1, [][]byte{expired}, false},
  947. {certKey{domain: "example.org", isRSA: true}, key1, [][]byte{cert1}, false},
  948. {certKey{domain: "example.org"}, key3, [][]byte{cert3}, false},
  949. }
  950. for i, test := range tt {
  951. leaf, err := validCert(test.ck, test.cert, test.key, now)
  952. if err != nil && test.ok {
  953. t.Errorf("%d: err = %v", i, err)
  954. }
  955. if err == nil && !test.ok {
  956. t.Errorf("%d: err is nil", i)
  957. }
  958. if err == nil && test.ok && leaf == nil {
  959. t.Errorf("%d: leaf is nil", i)
  960. }
  961. }
  962. }
  963. type cacheGetFunc func(ctx context.Context, key string) ([]byte, error)
  964. func (f cacheGetFunc) Get(ctx context.Context, key string) ([]byte, error) {
  965. return f(ctx, key)
  966. }
  967. func (f cacheGetFunc) Put(ctx context.Context, key string, data []byte) error {
  968. return fmt.Errorf("unsupported Put of %q = %q", key, data)
  969. }
  970. func (f cacheGetFunc) Delete(ctx context.Context, key string) error {
  971. return fmt.Errorf("unsupported Delete of %q", key)
  972. }
  973. func TestManagerGetCertificateBogusSNI(t *testing.T) {
  974. m := Manager{
  975. Prompt: AcceptTOS,
  976. Cache: cacheGetFunc(func(ctx context.Context, key string) ([]byte, error) {
  977. return nil, fmt.Errorf("cache.Get of %s", key)
  978. }),
  979. }
  980. tests := []struct {
  981. name string
  982. wantErr string
  983. }{
  984. {"foo.com", "cache.Get of foo.com"},
  985. {"foo.com.", "cache.Get of foo.com"},
  986. {`a\b.com`, "acme/autocert: server name contains invalid character"},
  987. {`a/b.com`, "acme/autocert: server name contains invalid character"},
  988. {"", "acme/autocert: missing server name"},
  989. {"foo", "acme/autocert: server name component count invalid"},
  990. {".foo", "acme/autocert: server name component count invalid"},
  991. {"foo.", "acme/autocert: server name component count invalid"},
  992. {"fo.o", "cache.Get of fo.o"},
  993. }
  994. for _, tt := range tests {
  995. _, err := m.GetCertificate(clientHelloInfo(tt.name, algECDSA))
  996. got := fmt.Sprint(err)
  997. if got != tt.wantErr {
  998. t.Errorf("GetCertificate(SNI = %q) = %q; want %q", tt.name, got, tt.wantErr)
  999. }
  1000. }
  1001. }
  1002. func TestCertRequest(t *testing.T) {
  1003. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1004. if err != nil {
  1005. t.Fatal(err)
  1006. }
  1007. // An extension from RFC7633. Any will do.
  1008. ext := pkix.Extension{
  1009. Id: asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1},
  1010. Value: []byte("dummy"),
  1011. }
  1012. b, err := certRequest(key, "example.org", []pkix.Extension{ext}, "san.example.org")
  1013. if err != nil {
  1014. t.Fatalf("certRequest: %v", err)
  1015. }
  1016. r, err := x509.ParseCertificateRequest(b)
  1017. if err != nil {
  1018. t.Fatalf("ParseCertificateRequest: %v", err)
  1019. }
  1020. var found bool
  1021. for _, v := range r.Extensions {
  1022. if v.Id.Equal(ext.Id) {
  1023. found = true
  1024. break
  1025. }
  1026. }
  1027. if !found {
  1028. t.Errorf("want %v in Extensions: %v", ext, r.Extensions)
  1029. }
  1030. }
  1031. func TestSupportsECDSA(t *testing.T) {
  1032. tests := []struct {
  1033. CipherSuites []uint16
  1034. SignatureSchemes []tls.SignatureScheme
  1035. SupportedCurves []tls.CurveID
  1036. ecdsaOk bool
  1037. }{
  1038. {[]uint16{
  1039. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1040. }, nil, nil, false},
  1041. {[]uint16{
  1042. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1043. }, nil, nil, true},
  1044. // SignatureSchemes limits, not extends, CipherSuites
  1045. {[]uint16{
  1046. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
  1047. }, []tls.SignatureScheme{
  1048. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1049. }, nil, false},
  1050. {[]uint16{
  1051. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1052. }, []tls.SignatureScheme{
  1053. tls.PKCS1WithSHA256,
  1054. }, nil, false},
  1055. {[]uint16{
  1056. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1057. }, []tls.SignatureScheme{
  1058. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1059. }, nil, true},
  1060. {[]uint16{
  1061. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1062. }, []tls.SignatureScheme{
  1063. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1064. }, []tls.CurveID{
  1065. tls.CurveP521,
  1066. }, false},
  1067. {[]uint16{
  1068. tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  1069. }, []tls.SignatureScheme{
  1070. tls.PKCS1WithSHA256, tls.ECDSAWithP256AndSHA256,
  1071. }, []tls.CurveID{
  1072. tls.CurveP256,
  1073. tls.CurveP521,
  1074. }, true},
  1075. }
  1076. for i, tt := range tests {
  1077. result := supportsECDSA(&tls.ClientHelloInfo{
  1078. CipherSuites: tt.CipherSuites,
  1079. SignatureSchemes: tt.SignatureSchemes,
  1080. SupportedCurves: tt.SupportedCurves,
  1081. })
  1082. if result != tt.ecdsaOk {
  1083. t.Errorf("%d: supportsECDSA = %v; want %v", i, result, tt.ecdsaOk)
  1084. }
  1085. }
  1086. }
  1087. // TODO: add same end-to-end for http-01 challenge type.
  1088. func TestEndToEnd(t *testing.T) {
  1089. const domain = "example.org"
  1090. // ACME CA server
  1091. ca := acmetest.NewCAServer([]string{"tls-alpn-01"}, []string{domain})
  1092. defer ca.Close()
  1093. // User dummy server.
  1094. m := &Manager{
  1095. Prompt: AcceptTOS,
  1096. Client: &acme.Client{DirectoryURL: ca.URL},
  1097. }
  1098. us := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1099. w.Write([]byte("OK"))
  1100. }))
  1101. us.TLS = &tls.Config{
  1102. NextProtos: []string{"http/1.1", acme.ALPNProto},
  1103. GetCertificate: func(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  1104. cert, err := m.GetCertificate(hello)
  1105. if err != nil {
  1106. t.Errorf("m.GetCertificate: %v", err)
  1107. }
  1108. return cert, err
  1109. },
  1110. }
  1111. us.StartTLS()
  1112. defer us.Close()
  1113. // In TLS-ALPN challenge verification, CA connects to the domain:443 in question.
  1114. // Because the domain won't resolve in tests, we need to tell the CA
  1115. // where to dial to instead.
  1116. ca.Resolve(domain, strings.TrimPrefix(us.URL, "https://"))
  1117. // A client visiting user dummy server.
  1118. tr := &http.Transport{
  1119. TLSClientConfig: &tls.Config{
  1120. RootCAs: ca.Roots,
  1121. ServerName: domain,
  1122. },
  1123. }
  1124. client := &http.Client{Transport: tr}
  1125. res, err := client.Get(us.URL)
  1126. if err != nil {
  1127. t.Fatal(err)
  1128. }
  1129. defer res.Body.Close()
  1130. b, err := ioutil.ReadAll(res.Body)
  1131. if err != nil {
  1132. t.Fatal(err)
  1133. }
  1134. if v := string(b); v != "OK" {
  1135. t.Errorf("user server response: %q; want 'OK'", v)
  1136. }
  1137. }