You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

1305 lines
35 KiB

  1. // Copyright 2015 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 acme
  5. import (
  6. "bytes"
  7. "crypto/rand"
  8. "crypto/rsa"
  9. "crypto/tls"
  10. "crypto/x509"
  11. "crypto/x509/pkix"
  12. "encoding/base64"
  13. "encoding/json"
  14. "fmt"
  15. "io/ioutil"
  16. "math/big"
  17. "net/http"
  18. "net/http/httptest"
  19. "reflect"
  20. "sort"
  21. "strings"
  22. "testing"
  23. "time"
  24. "golang.org/x/net/context"
  25. )
  26. // Decodes a JWS-encoded request and unmarshals the decoded JSON into a provided
  27. // interface.
  28. func decodeJWSRequest(t *testing.T, v interface{}, r *http.Request) {
  29. // Decode request
  30. var req struct{ Payload string }
  31. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  32. t.Fatal(err)
  33. }
  34. payload, err := base64.RawURLEncoding.DecodeString(req.Payload)
  35. if err != nil {
  36. t.Fatal(err)
  37. }
  38. err = json.Unmarshal(payload, v)
  39. if err != nil {
  40. t.Fatal(err)
  41. }
  42. }
  43. type jwsHead struct {
  44. Alg string
  45. Nonce string
  46. JWK map[string]string `json:"jwk"`
  47. }
  48. func decodeJWSHead(r *http.Request) (*jwsHead, error) {
  49. var req struct{ Protected string }
  50. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  51. return nil, err
  52. }
  53. b, err := base64.RawURLEncoding.DecodeString(req.Protected)
  54. if err != nil {
  55. return nil, err
  56. }
  57. var head jwsHead
  58. if err := json.Unmarshal(b, &head); err != nil {
  59. return nil, err
  60. }
  61. return &head, nil
  62. }
  63. func TestDiscover(t *testing.T) {
  64. const (
  65. reg = "https://example.com/acme/new-reg"
  66. authz = "https://example.com/acme/new-authz"
  67. cert = "https://example.com/acme/new-cert"
  68. revoke = "https://example.com/acme/revoke-cert"
  69. )
  70. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  71. w.Header().Set("content-type", "application/json")
  72. fmt.Fprintf(w, `{
  73. "new-reg": %q,
  74. "new-authz": %q,
  75. "new-cert": %q,
  76. "revoke-cert": %q
  77. }`, reg, authz, cert, revoke)
  78. }))
  79. defer ts.Close()
  80. c := Client{DirectoryURL: ts.URL}
  81. dir, err := c.Discover(context.Background())
  82. if err != nil {
  83. t.Fatal(err)
  84. }
  85. if dir.RegURL != reg {
  86. t.Errorf("dir.RegURL = %q; want %q", dir.RegURL, reg)
  87. }
  88. if dir.AuthzURL != authz {
  89. t.Errorf("dir.AuthzURL = %q; want %q", dir.AuthzURL, authz)
  90. }
  91. if dir.CertURL != cert {
  92. t.Errorf("dir.CertURL = %q; want %q", dir.CertURL, cert)
  93. }
  94. if dir.RevokeURL != revoke {
  95. t.Errorf("dir.RevokeURL = %q; want %q", dir.RevokeURL, revoke)
  96. }
  97. }
  98. func TestRegister(t *testing.T) {
  99. contacts := []string{"mailto:admin@example.com"}
  100. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  101. if r.Method == "HEAD" {
  102. w.Header().Set("replay-nonce", "test-nonce")
  103. return
  104. }
  105. if r.Method != "POST" {
  106. t.Errorf("r.Method = %q; want POST", r.Method)
  107. }
  108. var j struct {
  109. Resource string
  110. Contact []string
  111. Agreement string
  112. }
  113. decodeJWSRequest(t, &j, r)
  114. // Test request
  115. if j.Resource != "new-reg" {
  116. t.Errorf("j.Resource = %q; want new-reg", j.Resource)
  117. }
  118. if !reflect.DeepEqual(j.Contact, contacts) {
  119. t.Errorf("j.Contact = %v; want %v", j.Contact, contacts)
  120. }
  121. w.Header().Set("Location", "https://ca.tld/acme/reg/1")
  122. w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`)
  123. w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`)
  124. w.Header().Add("Link", `<https://ca.tld/acme/terms>;rel="terms-of-service"`)
  125. w.WriteHeader(http.StatusCreated)
  126. b, _ := json.Marshal(contacts)
  127. fmt.Fprintf(w, `{"contact": %s}`, b)
  128. }))
  129. defer ts.Close()
  130. prompt := func(url string) bool {
  131. const terms = "https://ca.tld/acme/terms"
  132. if url != terms {
  133. t.Errorf("prompt url = %q; want %q", url, terms)
  134. }
  135. return false
  136. }
  137. c := Client{Key: testKeyEC, dir: &Directory{RegURL: ts.URL}}
  138. a := &Account{Contact: contacts}
  139. var err error
  140. if a, err = c.Register(context.Background(), a, prompt); err != nil {
  141. t.Fatal(err)
  142. }
  143. if a.URI != "https://ca.tld/acme/reg/1" {
  144. t.Errorf("a.URI = %q; want https://ca.tld/acme/reg/1", a.URI)
  145. }
  146. if a.Authz != "https://ca.tld/acme/new-authz" {
  147. t.Errorf("a.Authz = %q; want https://ca.tld/acme/new-authz", a.Authz)
  148. }
  149. if a.CurrentTerms != "https://ca.tld/acme/terms" {
  150. t.Errorf("a.CurrentTerms = %q; want https://ca.tld/acme/terms", a.CurrentTerms)
  151. }
  152. if !reflect.DeepEqual(a.Contact, contacts) {
  153. t.Errorf("a.Contact = %v; want %v", a.Contact, contacts)
  154. }
  155. }
  156. func TestUpdateReg(t *testing.T) {
  157. const terms = "https://ca.tld/acme/terms"
  158. contacts := []string{"mailto:admin@example.com"}
  159. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  160. if r.Method == "HEAD" {
  161. w.Header().Set("replay-nonce", "test-nonce")
  162. return
  163. }
  164. if r.Method != "POST" {
  165. t.Errorf("r.Method = %q; want POST", r.Method)
  166. }
  167. var j struct {
  168. Resource string
  169. Contact []string
  170. Agreement string
  171. }
  172. decodeJWSRequest(t, &j, r)
  173. // Test request
  174. if j.Resource != "reg" {
  175. t.Errorf("j.Resource = %q; want reg", j.Resource)
  176. }
  177. if j.Agreement != terms {
  178. t.Errorf("j.Agreement = %q; want %q", j.Agreement, terms)
  179. }
  180. if !reflect.DeepEqual(j.Contact, contacts) {
  181. t.Errorf("j.Contact = %v; want %v", j.Contact, contacts)
  182. }
  183. w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`)
  184. w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`)
  185. w.Header().Add("Link", fmt.Sprintf(`<%s>;rel="terms-of-service"`, terms))
  186. w.WriteHeader(http.StatusOK)
  187. b, _ := json.Marshal(contacts)
  188. fmt.Fprintf(w, `{"contact":%s, "agreement":%q}`, b, terms)
  189. }))
  190. defer ts.Close()
  191. c := Client{Key: testKeyEC}
  192. a := &Account{URI: ts.URL, Contact: contacts, AgreedTerms: terms}
  193. var err error
  194. if a, err = c.UpdateReg(context.Background(), a); err != nil {
  195. t.Fatal(err)
  196. }
  197. if a.Authz != "https://ca.tld/acme/new-authz" {
  198. t.Errorf("a.Authz = %q; want https://ca.tld/acme/new-authz", a.Authz)
  199. }
  200. if a.AgreedTerms != terms {
  201. t.Errorf("a.AgreedTerms = %q; want %q", a.AgreedTerms, terms)
  202. }
  203. if a.CurrentTerms != terms {
  204. t.Errorf("a.CurrentTerms = %q; want %q", a.CurrentTerms, terms)
  205. }
  206. if a.URI != ts.URL {
  207. t.Errorf("a.URI = %q; want %q", a.URI, ts.URL)
  208. }
  209. }
  210. func TestGetReg(t *testing.T) {
  211. const terms = "https://ca.tld/acme/terms"
  212. const newTerms = "https://ca.tld/acme/new-terms"
  213. contacts := []string{"mailto:admin@example.com"}
  214. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  215. if r.Method == "HEAD" {
  216. w.Header().Set("replay-nonce", "test-nonce")
  217. return
  218. }
  219. if r.Method != "POST" {
  220. t.Errorf("r.Method = %q; want POST", r.Method)
  221. }
  222. var j struct {
  223. Resource string
  224. Contact []string
  225. Agreement string
  226. }
  227. decodeJWSRequest(t, &j, r)
  228. // Test request
  229. if j.Resource != "reg" {
  230. t.Errorf("j.Resource = %q; want reg", j.Resource)
  231. }
  232. if len(j.Contact) != 0 {
  233. t.Errorf("j.Contact = %v", j.Contact)
  234. }
  235. if j.Agreement != "" {
  236. t.Errorf("j.Agreement = %q", j.Agreement)
  237. }
  238. w.Header().Set("Link", `<https://ca.tld/acme/new-authz>;rel="next"`)
  239. w.Header().Add("Link", `<https://ca.tld/acme/recover-reg>;rel="recover"`)
  240. w.Header().Add("Link", fmt.Sprintf(`<%s>;rel="terms-of-service"`, newTerms))
  241. w.WriteHeader(http.StatusOK)
  242. b, _ := json.Marshal(contacts)
  243. fmt.Fprintf(w, `{"contact":%s, "agreement":%q}`, b, terms)
  244. }))
  245. defer ts.Close()
  246. c := Client{Key: testKeyEC}
  247. a, err := c.GetReg(context.Background(), ts.URL)
  248. if err != nil {
  249. t.Fatal(err)
  250. }
  251. if a.Authz != "https://ca.tld/acme/new-authz" {
  252. t.Errorf("a.AuthzURL = %q; want https://ca.tld/acme/new-authz", a.Authz)
  253. }
  254. if a.AgreedTerms != terms {
  255. t.Errorf("a.AgreedTerms = %q; want %q", a.AgreedTerms, terms)
  256. }
  257. if a.CurrentTerms != newTerms {
  258. t.Errorf("a.CurrentTerms = %q; want %q", a.CurrentTerms, newTerms)
  259. }
  260. if a.URI != ts.URL {
  261. t.Errorf("a.URI = %q; want %q", a.URI, ts.URL)
  262. }
  263. }
  264. func TestAuthorize(t *testing.T) {
  265. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  266. if r.Method == "HEAD" {
  267. w.Header().Set("replay-nonce", "test-nonce")
  268. return
  269. }
  270. if r.Method != "POST" {
  271. t.Errorf("r.Method = %q; want POST", r.Method)
  272. }
  273. var j struct {
  274. Resource string
  275. Identifier struct {
  276. Type string
  277. Value string
  278. }
  279. }
  280. decodeJWSRequest(t, &j, r)
  281. // Test request
  282. if j.Resource != "new-authz" {
  283. t.Errorf("j.Resource = %q; want new-authz", j.Resource)
  284. }
  285. if j.Identifier.Type != "dns" {
  286. t.Errorf("j.Identifier.Type = %q; want dns", j.Identifier.Type)
  287. }
  288. if j.Identifier.Value != "example.com" {
  289. t.Errorf("j.Identifier.Value = %q; want example.com", j.Identifier.Value)
  290. }
  291. w.Header().Set("Location", "https://ca.tld/acme/auth/1")
  292. w.WriteHeader(http.StatusCreated)
  293. fmt.Fprintf(w, `{
  294. "identifier": {"type":"dns","value":"example.com"},
  295. "status":"pending",
  296. "challenges":[
  297. {
  298. "type":"http-01",
  299. "status":"pending",
  300. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  301. "token":"token1"
  302. },
  303. {
  304. "type":"tls-sni-01",
  305. "status":"pending",
  306. "uri":"https://ca.tld/acme/challenge/publickey/id2",
  307. "token":"token2"
  308. }
  309. ],
  310. "combinations":[[0],[1]]}`)
  311. }))
  312. defer ts.Close()
  313. cl := Client{Key: testKeyEC, dir: &Directory{AuthzURL: ts.URL}}
  314. auth, err := cl.Authorize(context.Background(), "example.com")
  315. if err != nil {
  316. t.Fatal(err)
  317. }
  318. if auth.URI != "https://ca.tld/acme/auth/1" {
  319. t.Errorf("URI = %q; want https://ca.tld/acme/auth/1", auth.URI)
  320. }
  321. if auth.Status != "pending" {
  322. t.Errorf("Status = %q; want pending", auth.Status)
  323. }
  324. if auth.Identifier.Type != "dns" {
  325. t.Errorf("Identifier.Type = %q; want dns", auth.Identifier.Type)
  326. }
  327. if auth.Identifier.Value != "example.com" {
  328. t.Errorf("Identifier.Value = %q; want example.com", auth.Identifier.Value)
  329. }
  330. if n := len(auth.Challenges); n != 2 {
  331. t.Fatalf("len(auth.Challenges) = %d; want 2", n)
  332. }
  333. c := auth.Challenges[0]
  334. if c.Type != "http-01" {
  335. t.Errorf("c.Type = %q; want http-01", c.Type)
  336. }
  337. if c.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  338. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI)
  339. }
  340. if c.Token != "token1" {
  341. t.Errorf("c.Token = %q; want token1", c.Type)
  342. }
  343. c = auth.Challenges[1]
  344. if c.Type != "tls-sni-01" {
  345. t.Errorf("c.Type = %q; want tls-sni-01", c.Type)
  346. }
  347. if c.URI != "https://ca.tld/acme/challenge/publickey/id2" {
  348. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id2", c.URI)
  349. }
  350. if c.Token != "token2" {
  351. t.Errorf("c.Token = %q; want token2", c.Type)
  352. }
  353. combs := [][]int{{0}, {1}}
  354. if !reflect.DeepEqual(auth.Combinations, combs) {
  355. t.Errorf("auth.Combinations: %+v\nwant: %+v\n", auth.Combinations, combs)
  356. }
  357. }
  358. func TestAuthorizeValid(t *testing.T) {
  359. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  360. if r.Method == "HEAD" {
  361. w.Header().Set("replay-nonce", "nonce")
  362. return
  363. }
  364. w.WriteHeader(http.StatusCreated)
  365. w.Write([]byte(`{"status":"valid"}`))
  366. }))
  367. defer ts.Close()
  368. client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}}
  369. _, err := client.Authorize(context.Background(), "example.com")
  370. if err != nil {
  371. t.Errorf("err = %v", err)
  372. }
  373. }
  374. func TestGetAuthorization(t *testing.T) {
  375. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  376. if r.Method != "GET" {
  377. t.Errorf("r.Method = %q; want GET", r.Method)
  378. }
  379. w.WriteHeader(http.StatusOK)
  380. fmt.Fprintf(w, `{
  381. "identifier": {"type":"dns","value":"example.com"},
  382. "status":"pending",
  383. "challenges":[
  384. {
  385. "type":"http-01",
  386. "status":"pending",
  387. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  388. "token":"token1"
  389. },
  390. {
  391. "type":"tls-sni-01",
  392. "status":"pending",
  393. "uri":"https://ca.tld/acme/challenge/publickey/id2",
  394. "token":"token2"
  395. }
  396. ],
  397. "combinations":[[0],[1]]}`)
  398. }))
  399. defer ts.Close()
  400. cl := Client{Key: testKeyEC}
  401. auth, err := cl.GetAuthorization(context.Background(), ts.URL)
  402. if err != nil {
  403. t.Fatal(err)
  404. }
  405. if auth.Status != "pending" {
  406. t.Errorf("Status = %q; want pending", auth.Status)
  407. }
  408. if auth.Identifier.Type != "dns" {
  409. t.Errorf("Identifier.Type = %q; want dns", auth.Identifier.Type)
  410. }
  411. if auth.Identifier.Value != "example.com" {
  412. t.Errorf("Identifier.Value = %q; want example.com", auth.Identifier.Value)
  413. }
  414. if n := len(auth.Challenges); n != 2 {
  415. t.Fatalf("len(set.Challenges) = %d; want 2", n)
  416. }
  417. c := auth.Challenges[0]
  418. if c.Type != "http-01" {
  419. t.Errorf("c.Type = %q; want http-01", c.Type)
  420. }
  421. if c.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  422. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI)
  423. }
  424. if c.Token != "token1" {
  425. t.Errorf("c.Token = %q; want token1", c.Type)
  426. }
  427. c = auth.Challenges[1]
  428. if c.Type != "tls-sni-01" {
  429. t.Errorf("c.Type = %q; want tls-sni-01", c.Type)
  430. }
  431. if c.URI != "https://ca.tld/acme/challenge/publickey/id2" {
  432. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id2", c.URI)
  433. }
  434. if c.Token != "token2" {
  435. t.Errorf("c.Token = %q; want token2", c.Type)
  436. }
  437. combs := [][]int{{0}, {1}}
  438. if !reflect.DeepEqual(auth.Combinations, combs) {
  439. t.Errorf("auth.Combinations: %+v\nwant: %+v\n", auth.Combinations, combs)
  440. }
  441. }
  442. func TestWaitAuthorization(t *testing.T) {
  443. var count int
  444. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  445. count++
  446. w.Header().Set("retry-after", "0")
  447. if count > 1 {
  448. fmt.Fprintf(w, `{"status":"valid"}`)
  449. return
  450. }
  451. fmt.Fprintf(w, `{"status":"pending"}`)
  452. }))
  453. defer ts.Close()
  454. type res struct {
  455. authz *Authorization
  456. err error
  457. }
  458. done := make(chan res)
  459. defer close(done)
  460. go func() {
  461. var client Client
  462. a, err := client.WaitAuthorization(context.Background(), ts.URL)
  463. done <- res{a, err}
  464. }()
  465. select {
  466. case <-time.After(5 * time.Second):
  467. t.Fatal("WaitAuthz took too long to return")
  468. case res := <-done:
  469. if res.err != nil {
  470. t.Fatalf("res.err = %v", res.err)
  471. }
  472. if res.authz == nil {
  473. t.Fatal("res.authz is nil")
  474. }
  475. }
  476. }
  477. func TestWaitAuthorizationInvalid(t *testing.T) {
  478. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  479. fmt.Fprintf(w, `{"status":"invalid"}`)
  480. }))
  481. defer ts.Close()
  482. res := make(chan error)
  483. defer close(res)
  484. go func() {
  485. var client Client
  486. _, err := client.WaitAuthorization(context.Background(), ts.URL)
  487. res <- err
  488. }()
  489. select {
  490. case <-time.After(3 * time.Second):
  491. t.Fatal("WaitAuthz took too long to return")
  492. case err := <-res:
  493. if err == nil {
  494. t.Error("err is nil")
  495. }
  496. }
  497. }
  498. func TestWaitAuthorizationCancel(t *testing.T) {
  499. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  500. w.Header().Set("retry-after", "60")
  501. fmt.Fprintf(w, `{"status":"pending"}`)
  502. }))
  503. defer ts.Close()
  504. res := make(chan error)
  505. defer close(res)
  506. go func() {
  507. var client Client
  508. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  509. defer cancel()
  510. _, err := client.WaitAuthorization(ctx, ts.URL)
  511. res <- err
  512. }()
  513. select {
  514. case <-time.After(time.Second):
  515. t.Fatal("WaitAuthz took too long to return")
  516. case err := <-res:
  517. if err == nil {
  518. t.Error("err is nil")
  519. }
  520. }
  521. }
  522. func TestRevokeAuthorization(t *testing.T) {
  523. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  524. if r.Method == "HEAD" {
  525. w.Header().Set("replay-nonce", "nonce")
  526. return
  527. }
  528. switch r.URL.Path {
  529. case "/1":
  530. var req struct {
  531. Resource string
  532. Status string
  533. Delete bool
  534. }
  535. decodeJWSRequest(t, &req, r)
  536. if req.Resource != "authz" {
  537. t.Errorf("req.Resource = %q; want authz", req.Resource)
  538. }
  539. if req.Status != "deactivated" {
  540. t.Errorf("req.Status = %q; want deactivated", req.Status)
  541. }
  542. if !req.Delete {
  543. t.Errorf("req.Delete is false")
  544. }
  545. case "/2":
  546. w.WriteHeader(http.StatusInternalServerError)
  547. }
  548. }))
  549. defer ts.Close()
  550. client := &Client{Key: testKey}
  551. ctx := context.Background()
  552. if err := client.RevokeAuthorization(ctx, ts.URL+"/1"); err != nil {
  553. t.Errorf("err = %v", err)
  554. }
  555. if client.RevokeAuthorization(ctx, ts.URL+"/2") == nil {
  556. t.Error("nil error")
  557. }
  558. }
  559. func TestPollChallenge(t *testing.T) {
  560. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  561. if r.Method != "GET" {
  562. t.Errorf("r.Method = %q; want GET", r.Method)
  563. }
  564. w.WriteHeader(http.StatusOK)
  565. fmt.Fprintf(w, `{
  566. "type":"http-01",
  567. "status":"pending",
  568. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  569. "token":"token1"}`)
  570. }))
  571. defer ts.Close()
  572. cl := Client{Key: testKeyEC}
  573. chall, err := cl.GetChallenge(context.Background(), ts.URL)
  574. if err != nil {
  575. t.Fatal(err)
  576. }
  577. if chall.Status != "pending" {
  578. t.Errorf("Status = %q; want pending", chall.Status)
  579. }
  580. if chall.Type != "http-01" {
  581. t.Errorf("c.Type = %q; want http-01", chall.Type)
  582. }
  583. if chall.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  584. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", chall.URI)
  585. }
  586. if chall.Token != "token1" {
  587. t.Errorf("c.Token = %q; want token1", chall.Type)
  588. }
  589. }
  590. func TestAcceptChallenge(t *testing.T) {
  591. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  592. if r.Method == "HEAD" {
  593. w.Header().Set("replay-nonce", "test-nonce")
  594. return
  595. }
  596. if r.Method != "POST" {
  597. t.Errorf("r.Method = %q; want POST", r.Method)
  598. }
  599. var j struct {
  600. Resource string
  601. Type string
  602. Auth string `json:"keyAuthorization"`
  603. }
  604. decodeJWSRequest(t, &j, r)
  605. // Test request
  606. if j.Resource != "challenge" {
  607. t.Errorf(`resource = %q; want "challenge"`, j.Resource)
  608. }
  609. if j.Type != "http-01" {
  610. t.Errorf(`type = %q; want "http-01"`, j.Type)
  611. }
  612. keyAuth := "token1." + testKeyECThumbprint
  613. if j.Auth != keyAuth {
  614. t.Errorf(`keyAuthorization = %q; want %q`, j.Auth, keyAuth)
  615. }
  616. // Respond to request
  617. w.WriteHeader(http.StatusAccepted)
  618. fmt.Fprintf(w, `{
  619. "type":"http-01",
  620. "status":"pending",
  621. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  622. "token":"token1",
  623. "keyAuthorization":%q
  624. }`, keyAuth)
  625. }))
  626. defer ts.Close()
  627. cl := Client{Key: testKeyEC}
  628. c, err := cl.Accept(context.Background(), &Challenge{
  629. URI: ts.URL,
  630. Token: "token1",
  631. Type: "http-01",
  632. })
  633. if err != nil {
  634. t.Fatal(err)
  635. }
  636. if c.Type != "http-01" {
  637. t.Errorf("c.Type = %q; want http-01", c.Type)
  638. }
  639. if c.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  640. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI)
  641. }
  642. if c.Token != "token1" {
  643. t.Errorf("c.Token = %q; want token1", c.Type)
  644. }
  645. }
  646. func TestNewCert(t *testing.T) {
  647. notBefore := time.Now()
  648. notAfter := notBefore.AddDate(0, 2, 0)
  649. timeNow = func() time.Time { return notBefore }
  650. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  651. if r.Method == "HEAD" {
  652. w.Header().Set("replay-nonce", "test-nonce")
  653. return
  654. }
  655. if r.Method != "POST" {
  656. t.Errorf("r.Method = %q; want POST", r.Method)
  657. }
  658. var j struct {
  659. Resource string `json:"resource"`
  660. CSR string `json:"csr"`
  661. NotBefore string `json:"notBefore,omitempty"`
  662. NotAfter string `json:"notAfter,omitempty"`
  663. }
  664. decodeJWSRequest(t, &j, r)
  665. // Test request
  666. if j.Resource != "new-cert" {
  667. t.Errorf(`resource = %q; want "new-cert"`, j.Resource)
  668. }
  669. if j.NotBefore != notBefore.Format(time.RFC3339) {
  670. t.Errorf(`notBefore = %q; wanted %q`, j.NotBefore, notBefore.Format(time.RFC3339))
  671. }
  672. if j.NotAfter != notAfter.Format(time.RFC3339) {
  673. t.Errorf(`notAfter = %q; wanted %q`, j.NotAfter, notAfter.Format(time.RFC3339))
  674. }
  675. // Respond to request
  676. template := x509.Certificate{
  677. SerialNumber: big.NewInt(int64(1)),
  678. Subject: pkix.Name{
  679. Organization: []string{"goacme"},
  680. },
  681. NotBefore: notBefore,
  682. NotAfter: notAfter,
  683. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  684. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  685. BasicConstraintsValid: true,
  686. }
  687. sampleCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &testKeyEC.PublicKey, testKeyEC)
  688. if err != nil {
  689. t.Fatalf("Error creating certificate: %v", err)
  690. }
  691. w.Header().Set("Location", "https://ca.tld/acme/cert/1")
  692. w.WriteHeader(http.StatusCreated)
  693. w.Write(sampleCert)
  694. }))
  695. defer ts.Close()
  696. csr := x509.CertificateRequest{
  697. Version: 0,
  698. Subject: pkix.Name{
  699. CommonName: "example.com",
  700. Organization: []string{"goacme"},
  701. },
  702. }
  703. csrb, err := x509.CreateCertificateRequest(rand.Reader, &csr, testKeyEC)
  704. if err != nil {
  705. t.Fatal(err)
  706. }
  707. c := Client{Key: testKeyEC, dir: &Directory{CertURL: ts.URL}}
  708. cert, certURL, err := c.CreateCert(context.Background(), csrb, notAfter.Sub(notBefore), false)
  709. if err != nil {
  710. t.Fatal(err)
  711. }
  712. if cert == nil {
  713. t.Errorf("cert is nil")
  714. }
  715. if certURL != "https://ca.tld/acme/cert/1" {
  716. t.Errorf("certURL = %q; want https://ca.tld/acme/cert/1", certURL)
  717. }
  718. }
  719. func TestFetchCert(t *testing.T) {
  720. var count byte
  721. var ts *httptest.Server
  722. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  723. count++
  724. if count < 3 {
  725. up := fmt.Sprintf("<%s>;rel=up", ts.URL)
  726. w.Header().Set("link", up)
  727. }
  728. w.Write([]byte{count})
  729. }))
  730. defer ts.Close()
  731. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  732. if err != nil {
  733. t.Fatalf("FetchCert: %v", err)
  734. }
  735. cert := [][]byte{{1}, {2}, {3}}
  736. if !reflect.DeepEqual(res, cert) {
  737. t.Errorf("res = %v; want %v", res, cert)
  738. }
  739. }
  740. func TestFetchCertRetry(t *testing.T) {
  741. var count int
  742. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  743. if count < 1 {
  744. w.Header().Set("retry-after", "0")
  745. w.WriteHeader(http.StatusAccepted)
  746. count++
  747. return
  748. }
  749. w.Write([]byte{1})
  750. }))
  751. defer ts.Close()
  752. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  753. if err != nil {
  754. t.Fatalf("FetchCert: %v", err)
  755. }
  756. cert := [][]byte{{1}}
  757. if !reflect.DeepEqual(res, cert) {
  758. t.Errorf("res = %v; want %v", res, cert)
  759. }
  760. }
  761. func TestFetchCertCancel(t *testing.T) {
  762. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  763. w.Header().Set("retry-after", "0")
  764. w.WriteHeader(http.StatusAccepted)
  765. }))
  766. defer ts.Close()
  767. ctx, cancel := context.WithCancel(context.Background())
  768. done := make(chan struct{})
  769. var err error
  770. go func() {
  771. _, err = (&Client{}).FetchCert(ctx, ts.URL, false)
  772. close(done)
  773. }()
  774. cancel()
  775. <-done
  776. if err != context.Canceled {
  777. t.Errorf("err = %v; want %v", err, context.Canceled)
  778. }
  779. }
  780. func TestFetchCertDepth(t *testing.T) {
  781. var count byte
  782. var ts *httptest.Server
  783. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  784. count++
  785. if count > maxChainLen+1 {
  786. t.Errorf("count = %d; want at most %d", count, maxChainLen+1)
  787. w.WriteHeader(http.StatusInternalServerError)
  788. }
  789. w.Header().Set("link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  790. w.Write([]byte{count})
  791. }))
  792. defer ts.Close()
  793. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  794. if err == nil {
  795. t.Errorf("err is nil")
  796. }
  797. }
  798. func TestFetchCertBreadth(t *testing.T) {
  799. var ts *httptest.Server
  800. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  801. for i := 0; i < maxChainLen+1; i++ {
  802. w.Header().Add("link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  803. }
  804. w.Write([]byte{1})
  805. }))
  806. defer ts.Close()
  807. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  808. if err == nil {
  809. t.Errorf("err is nil")
  810. }
  811. }
  812. func TestFetchCertSize(t *testing.T) {
  813. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  814. b := bytes.Repeat([]byte{1}, maxCertSize+1)
  815. w.Write(b)
  816. }))
  817. defer ts.Close()
  818. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  819. if err == nil {
  820. t.Errorf("err is nil")
  821. }
  822. }
  823. func TestRevokeCert(t *testing.T) {
  824. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  825. if r.Method == "HEAD" {
  826. w.Header().Set("replay-nonce", "nonce")
  827. return
  828. }
  829. var req struct {
  830. Resource string
  831. Certificate string
  832. Reason int
  833. }
  834. decodeJWSRequest(t, &req, r)
  835. if req.Resource != "revoke-cert" {
  836. t.Errorf("req.Resource = %q; want revoke-cert", req.Resource)
  837. }
  838. if req.Reason != 1 {
  839. t.Errorf("req.Reason = %d; want 1", req.Reason)
  840. }
  841. // echo -n cert | base64 | tr -d '=' | tr '/+' '_-'
  842. cert := "Y2VydA"
  843. if req.Certificate != cert {
  844. t.Errorf("req.Certificate = %q; want %q", req.Certificate, cert)
  845. }
  846. }))
  847. defer ts.Close()
  848. client := &Client{
  849. Key: testKeyEC,
  850. dir: &Directory{RevokeURL: ts.URL},
  851. }
  852. ctx := context.Background()
  853. if err := client.RevokeCert(ctx, nil, []byte("cert"), CRLReasonKeyCompromise); err != nil {
  854. t.Fatal(err)
  855. }
  856. }
  857. func TestNonce_add(t *testing.T) {
  858. var c Client
  859. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  860. c.addNonce(http.Header{"Replay-Nonce": {}})
  861. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  862. nonces := map[string]struct{}{"nonce": struct{}{}}
  863. if !reflect.DeepEqual(c.nonces, nonces) {
  864. t.Errorf("c.nonces = %q; want %q", c.nonces, nonces)
  865. }
  866. }
  867. func TestNonce_addMax(t *testing.T) {
  868. c := &Client{nonces: make(map[string]struct{})}
  869. for i := 0; i < maxNonces; i++ {
  870. c.nonces[fmt.Sprintf("%d", i)] = struct{}{}
  871. }
  872. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  873. if n := len(c.nonces); n != maxNonces {
  874. t.Errorf("len(c.nonces) = %d; want %d", n, maxNonces)
  875. }
  876. }
  877. func TestNonce_fetch(t *testing.T) {
  878. tests := []struct {
  879. code int
  880. nonce string
  881. }{
  882. {http.StatusOK, "nonce1"},
  883. {http.StatusBadRequest, "nonce2"},
  884. {http.StatusOK, ""},
  885. }
  886. var i int
  887. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  888. if r.Method != "HEAD" {
  889. t.Errorf("%d: r.Method = %q; want HEAD", i, r.Method)
  890. }
  891. w.Header().Set("replay-nonce", tests[i].nonce)
  892. w.WriteHeader(tests[i].code)
  893. }))
  894. defer ts.Close()
  895. for ; i < len(tests); i++ {
  896. test := tests[i]
  897. n, err := fetchNonce(context.Background(), http.DefaultClient, ts.URL)
  898. if n != test.nonce {
  899. t.Errorf("%d: n=%q; want %q", i, n, test.nonce)
  900. }
  901. switch {
  902. case err == nil && test.nonce == "":
  903. t.Errorf("%d: n=%q, err=%v; want non-nil error", i, n, err)
  904. case err != nil && test.nonce != "":
  905. t.Errorf("%d: n=%q, err=%v; want %q", i, n, err, test.nonce)
  906. }
  907. }
  908. }
  909. func TestNonce_fetchError(t *testing.T) {
  910. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  911. w.WriteHeader(http.StatusTooManyRequests)
  912. }))
  913. defer ts.Close()
  914. _, err := fetchNonce(context.Background(), http.DefaultClient, ts.URL)
  915. e, ok := err.(*Error)
  916. if !ok {
  917. t.Fatalf("err is %T; want *Error", err)
  918. }
  919. if e.StatusCode != http.StatusTooManyRequests {
  920. t.Errorf("e.StatusCode = %d; want %d", e.StatusCode, http.StatusTooManyRequests)
  921. }
  922. }
  923. func TestNonce_postJWS(t *testing.T) {
  924. var count int
  925. seen := make(map[string]bool)
  926. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  927. count++
  928. w.Header().Set("replay-nonce", fmt.Sprintf("nonce%d", count))
  929. if r.Method == "HEAD" {
  930. // We expect the client do a HEAD request
  931. // but only to fetch the first nonce.
  932. return
  933. }
  934. // Make client.Authorize happy; we're not testing its result.
  935. defer func() {
  936. w.WriteHeader(http.StatusCreated)
  937. w.Write([]byte(`{"status":"valid"}`))
  938. }()
  939. head, err := decodeJWSHead(r)
  940. if err != nil {
  941. t.Errorf("decodeJWSHead: %v", err)
  942. return
  943. }
  944. if head.Nonce == "" {
  945. t.Error("head.Nonce is empty")
  946. return
  947. }
  948. if seen[head.Nonce] {
  949. t.Errorf("nonce is already used: %q", head.Nonce)
  950. }
  951. seen[head.Nonce] = true
  952. }))
  953. defer ts.Close()
  954. client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}}
  955. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  956. t.Errorf("client.Authorize 1: %v", err)
  957. }
  958. // The second call should not generate another extra HEAD request.
  959. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  960. t.Errorf("client.Authorize 2: %v", err)
  961. }
  962. if count != 3 {
  963. t.Errorf("total requests count: %d; want 3", count)
  964. }
  965. if n := len(client.nonces); n != 1 {
  966. t.Errorf("len(client.nonces) = %d; want 1", n)
  967. }
  968. for k := range seen {
  969. if _, exist := client.nonces[k]; exist {
  970. t.Errorf("used nonce %q in client.nonces", k)
  971. }
  972. }
  973. }
  974. func TestLinkHeader(t *testing.T) {
  975. h := http.Header{"Link": {
  976. `<https://example.com/acme/new-authz>;rel="next"`,
  977. `<https://example.com/acme/recover-reg>; rel=recover`,
  978. `<https://example.com/acme/terms>; foo=bar; rel="terms-of-service"`,
  979. `<dup>;rel="next"`,
  980. }}
  981. tests := []struct {
  982. rel string
  983. out []string
  984. }{
  985. {"next", []string{"https://example.com/acme/new-authz", "dup"}},
  986. {"recover", []string{"https://example.com/acme/recover-reg"}},
  987. {"terms-of-service", []string{"https://example.com/acme/terms"}},
  988. {"empty", nil},
  989. }
  990. for i, test := range tests {
  991. if v := linkHeader(h, test.rel); !reflect.DeepEqual(v, test.out) {
  992. t.Errorf("%d: linkHeader(%q): %v; want %v", i, test.rel, v, test.out)
  993. }
  994. }
  995. }
  996. func TestErrorResponse(t *testing.T) {
  997. s := `{
  998. "status": 400,
  999. "type": "urn:acme:error:xxx",
  1000. "detail": "text"
  1001. }`
  1002. res := &http.Response{
  1003. StatusCode: 400,
  1004. Status: "400 Bad Request",
  1005. Body: ioutil.NopCloser(strings.NewReader(s)),
  1006. Header: http.Header{"X-Foo": {"bar"}},
  1007. }
  1008. err := responseError(res)
  1009. v, ok := err.(*Error)
  1010. if !ok {
  1011. t.Fatalf("err = %+v (%T); want *Error type", err, err)
  1012. }
  1013. if v.StatusCode != 400 {
  1014. t.Errorf("v.StatusCode = %v; want 400", v.StatusCode)
  1015. }
  1016. if v.ProblemType != "urn:acme:error:xxx" {
  1017. t.Errorf("v.ProblemType = %q; want urn:acme:error:xxx", v.ProblemType)
  1018. }
  1019. if v.Detail != "text" {
  1020. t.Errorf("v.Detail = %q; want text", v.Detail)
  1021. }
  1022. if !reflect.DeepEqual(v.Header, res.Header) {
  1023. t.Errorf("v.Header = %+v; want %+v", v.Header, res.Header)
  1024. }
  1025. }
  1026. func TestTLSSNI01ChallengeCert(t *testing.T) {
  1027. const (
  1028. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1029. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1030. san = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.acme.invalid"
  1031. )
  1032. client := &Client{Key: testKeyEC}
  1033. tlscert, name, err := client.TLSSNI01ChallengeCert(token)
  1034. if err != nil {
  1035. t.Fatal(err)
  1036. }
  1037. if n := len(tlscert.Certificate); n != 1 {
  1038. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1039. }
  1040. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1041. if err != nil {
  1042. t.Fatal(err)
  1043. }
  1044. if len(cert.DNSNames) != 1 || cert.DNSNames[0] != san {
  1045. t.Fatalf("cert.DNSNames = %v; want %q", cert.DNSNames, san)
  1046. }
  1047. if cert.DNSNames[0] != name {
  1048. t.Errorf("cert.DNSNames[0] != name: %q vs %q", cert.DNSNames[0], name)
  1049. }
  1050. }
  1051. func TestTLSSNI02ChallengeCert(t *testing.T) {
  1052. const (
  1053. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1054. // echo -n evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA | shasum -a 256
  1055. sanA = "7ea0aaa69214e71e02cebb18bb867736.09b730209baabf60e43d4999979ff139.token.acme.invalid"
  1056. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1057. sanB = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.ka.acme.invalid"
  1058. )
  1059. client := &Client{Key: testKeyEC}
  1060. tlscert, name, err := client.TLSSNI02ChallengeCert(token)
  1061. if err != nil {
  1062. t.Fatal(err)
  1063. }
  1064. if n := len(tlscert.Certificate); n != 1 {
  1065. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1066. }
  1067. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1068. if err != nil {
  1069. t.Fatal(err)
  1070. }
  1071. names := []string{sanA, sanB}
  1072. if !reflect.DeepEqual(cert.DNSNames, names) {
  1073. t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
  1074. }
  1075. sort.Strings(cert.DNSNames)
  1076. i := sort.SearchStrings(cert.DNSNames, name)
  1077. if i >= len(cert.DNSNames) || cert.DNSNames[i] != name {
  1078. t.Errorf("%v doesn't have %q", cert.DNSNames, name)
  1079. }
  1080. }
  1081. func TestTLSChallengeCertOpt(t *testing.T) {
  1082. key, err := rsa.GenerateKey(rand.Reader, 512)
  1083. if err != nil {
  1084. t.Fatal(err)
  1085. }
  1086. tmpl := &x509.Certificate{
  1087. SerialNumber: big.NewInt(2),
  1088. Subject: pkix.Name{Organization: []string{"Test"}},
  1089. DNSNames: []string{"should-be-overwritten"},
  1090. }
  1091. opts := []CertOption{WithKey(key), WithTemplate(tmpl)}
  1092. client := &Client{Key: testKeyEC}
  1093. cert1, _, err := client.TLSSNI01ChallengeCert("token", opts...)
  1094. if err != nil {
  1095. t.Fatal(err)
  1096. }
  1097. cert2, _, err := client.TLSSNI02ChallengeCert("token", opts...)
  1098. if err != nil {
  1099. t.Fatal(err)
  1100. }
  1101. for i, tlscert := range []tls.Certificate{cert1, cert2} {
  1102. // verify generated cert private key
  1103. tlskey, ok := tlscert.PrivateKey.(*rsa.PrivateKey)
  1104. if !ok {
  1105. t.Errorf("%d: tlscert.PrivateKey is %T; want *rsa.PrivateKey", i, tlscert.PrivateKey)
  1106. continue
  1107. }
  1108. if tlskey.D.Cmp(key.D) != 0 {
  1109. t.Errorf("%d: tlskey.D = %v; want %v", i, tlskey.D, key.D)
  1110. }
  1111. // verify generated cert public key
  1112. x509Cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1113. if err != nil {
  1114. t.Errorf("%d: %v", i, err)
  1115. continue
  1116. }
  1117. tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey)
  1118. if !ok {
  1119. t.Errorf("%d: x509Cert.PublicKey is %T; want *rsa.PublicKey", i, x509Cert.PublicKey)
  1120. continue
  1121. }
  1122. if tlspub.N.Cmp(key.N) != 0 {
  1123. t.Errorf("%d: tlspub.N = %v; want %v", i, tlspub.N, key.N)
  1124. }
  1125. // verify template option
  1126. sn := big.NewInt(2)
  1127. if x509Cert.SerialNumber.Cmp(sn) != 0 {
  1128. t.Errorf("%d: SerialNumber = %v; want %v", i, x509Cert.SerialNumber, sn)
  1129. }
  1130. org := []string{"Test"}
  1131. if !reflect.DeepEqual(x509Cert.Subject.Organization, org) {
  1132. t.Errorf("%d: Subject.Organization = %+v; want %+v", i, x509Cert.Subject.Organization, org)
  1133. }
  1134. for _, v := range x509Cert.DNSNames {
  1135. if !strings.HasSuffix(v, ".acme.invalid") {
  1136. t.Errorf("%d: invalid DNSNames element: %q", i, v)
  1137. }
  1138. }
  1139. }
  1140. }
  1141. func TestHTTP01Challenge(t *testing.T) {
  1142. const (
  1143. token = "xxx"
  1144. // thumbprint is precomputed for testKeyEC in jws_test.go
  1145. value = token + "." + testKeyECThumbprint
  1146. urlpath = "/.well-known/acme-challenge/" + token
  1147. )
  1148. client := &Client{Key: testKeyEC}
  1149. val, err := client.HTTP01ChallengeResponse(token)
  1150. if err != nil {
  1151. t.Fatal(err)
  1152. }
  1153. if val != value {
  1154. t.Errorf("val = %q; want %q", val, value)
  1155. }
  1156. if path := client.HTTP01ChallengePath(token); path != urlpath {
  1157. t.Errorf("path = %q; want %q", path, urlpath)
  1158. }
  1159. }
  1160. func TestDNS01ChallengeRecord(t *testing.T) {
  1161. // echo -n xxx.<testKeyECThumbprint> | \
  1162. // openssl dgst -binary -sha256 | \
  1163. // base64 | tr -d '=' | tr '/+' '_-'
  1164. const value = "8DERMexQ5VcdJ_prpPiA0mVdp7imgbCgjsG4SqqNMIo"
  1165. client := &Client{Key: testKeyEC}
  1166. val, err := client.DNS01ChallengeRecord("xxx")
  1167. if err != nil {
  1168. t.Fatal(err)
  1169. }
  1170. if val != value {
  1171. t.Errorf("val = %q; want %q", val, value)
  1172. }
  1173. }
  1174. func TestBackoff(t *testing.T) {
  1175. tt := []struct{ min, max time.Duration }{
  1176. {time.Second, 2 * time.Second},
  1177. {2 * time.Second, 3 * time.Second},
  1178. {4 * time.Second, 5 * time.Second},
  1179. {8 * time.Second, 9 * time.Second},
  1180. }
  1181. for i, test := range tt {
  1182. d := backoff(i, time.Minute)
  1183. if d < test.min || test.max < d {
  1184. t.Errorf("%d: d = %v; want between %v and %v", i, d, test.min, test.max)
  1185. }
  1186. }
  1187. min, max := time.Second, 2*time.Second
  1188. if d := backoff(-1, time.Minute); d < min || max < d {
  1189. t.Errorf("d = %v; want between %v and %v", d, min, max)
  1190. }
  1191. bound := 10 * time.Second
  1192. if d := backoff(100, bound); d != bound {
  1193. t.Errorf("d = %v; want %v", d, bound)
  1194. }
  1195. }