autocert_test.go 34 KB

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