Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

1314 рядки
36 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. "context"
  8. "crypto/rand"
  9. "crypto/rsa"
  10. "crypto/tls"
  11. "crypto/x509"
  12. "crypto/x509/pkix"
  13. "encoding/base64"
  14. "encoding/hex"
  15. "encoding/json"
  16. "fmt"
  17. "math/big"
  18. "net/http"
  19. "net/http/httptest"
  20. "reflect"
  21. "sort"
  22. "strings"
  23. "testing"
  24. "time"
  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.Token)
  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.Token)
  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.Token)
  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.Token)
  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. t.Run("wait loop", func(t *testing.T) {
  444. var count int
  445. authz, err := runWaitAuthorization(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
  446. count++
  447. w.Header().Set("Retry-After", "0")
  448. if count > 1 {
  449. fmt.Fprintf(w, `{"status":"valid"}`)
  450. return
  451. }
  452. fmt.Fprintf(w, `{"status":"pending"}`)
  453. })
  454. if err != nil {
  455. t.Fatalf("non-nil error: %v", err)
  456. }
  457. if authz == nil {
  458. t.Fatal("authz is nil")
  459. }
  460. })
  461. t.Run("invalid status", func(t *testing.T) {
  462. _, err := runWaitAuthorization(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
  463. fmt.Fprintf(w, `{"status":"invalid"}`)
  464. })
  465. if _, ok := err.(*AuthorizationError); !ok {
  466. t.Errorf("err is %v (%T); want non-nil *AuthorizationError", err, err)
  467. }
  468. })
  469. t.Run("non-retriable error", func(t *testing.T) {
  470. const code = http.StatusBadRequest
  471. _, err := runWaitAuthorization(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
  472. w.WriteHeader(code)
  473. })
  474. res, ok := err.(*Error)
  475. if !ok {
  476. t.Fatalf("err is %v (%T); want a non-nil *Error", err, err)
  477. }
  478. if res.StatusCode != code {
  479. t.Errorf("res.StatusCode = %d; want %d", res.StatusCode, code)
  480. }
  481. })
  482. for _, code := range []int{http.StatusTooManyRequests, http.StatusInternalServerError} {
  483. t.Run(fmt.Sprintf("retriable %d error", code), func(t *testing.T) {
  484. var count int
  485. authz, err := runWaitAuthorization(context.Background(), t, func(w http.ResponseWriter, r *http.Request) {
  486. count++
  487. w.Header().Set("Retry-After", "0")
  488. if count > 1 {
  489. fmt.Fprintf(w, `{"status":"valid"}`)
  490. return
  491. }
  492. w.WriteHeader(code)
  493. })
  494. if err != nil {
  495. t.Fatalf("non-nil error: %v", err)
  496. }
  497. if authz == nil {
  498. t.Fatal("authz is nil")
  499. }
  500. })
  501. }
  502. t.Run("context cancel", func(t *testing.T) {
  503. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
  504. defer cancel()
  505. _, err := runWaitAuthorization(ctx, t, func(w http.ResponseWriter, r *http.Request) {
  506. w.Header().Set("Retry-After", "60")
  507. fmt.Fprintf(w, `{"status":"pending"}`)
  508. })
  509. if err == nil {
  510. t.Error("err is nil")
  511. }
  512. })
  513. }
  514. func runWaitAuthorization(ctx context.Context, t *testing.T, h http.HandlerFunc) (*Authorization, error) {
  515. t.Helper()
  516. ts := httptest.NewServer(h)
  517. defer ts.Close()
  518. type res struct {
  519. authz *Authorization
  520. err error
  521. }
  522. ch := make(chan res, 1)
  523. go func() {
  524. var client Client
  525. a, err := client.WaitAuthorization(ctx, ts.URL)
  526. ch <- res{a, err}
  527. }()
  528. select {
  529. case <-time.After(3 * time.Second):
  530. t.Fatal("WaitAuthorization took too long to return")
  531. case v := <-ch:
  532. return v.authz, v.err
  533. }
  534. panic("runWaitAuthorization: out of select")
  535. }
  536. func TestRevokeAuthorization(t *testing.T) {
  537. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  538. if r.Method == "HEAD" {
  539. w.Header().Set("Replay-Nonce", "nonce")
  540. return
  541. }
  542. switch r.URL.Path {
  543. case "/1":
  544. var req struct {
  545. Resource string
  546. Status string
  547. Delete bool
  548. }
  549. decodeJWSRequest(t, &req, r)
  550. if req.Resource != "authz" {
  551. t.Errorf("req.Resource = %q; want authz", req.Resource)
  552. }
  553. if req.Status != "deactivated" {
  554. t.Errorf("req.Status = %q; want deactivated", req.Status)
  555. }
  556. if !req.Delete {
  557. t.Errorf("req.Delete is false")
  558. }
  559. case "/2":
  560. w.WriteHeader(http.StatusBadRequest)
  561. }
  562. }))
  563. defer ts.Close()
  564. client := &Client{Key: testKey}
  565. ctx := context.Background()
  566. if err := client.RevokeAuthorization(ctx, ts.URL+"/1"); err != nil {
  567. t.Errorf("err = %v", err)
  568. }
  569. if client.RevokeAuthorization(ctx, ts.URL+"/2") == nil {
  570. t.Error("nil error")
  571. }
  572. }
  573. func TestPollChallenge(t *testing.T) {
  574. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  575. if r.Method != "GET" {
  576. t.Errorf("r.Method = %q; want GET", r.Method)
  577. }
  578. w.WriteHeader(http.StatusOK)
  579. fmt.Fprintf(w, `{
  580. "type":"http-01",
  581. "status":"pending",
  582. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  583. "token":"token1"}`)
  584. }))
  585. defer ts.Close()
  586. cl := Client{Key: testKeyEC}
  587. chall, err := cl.GetChallenge(context.Background(), ts.URL)
  588. if err != nil {
  589. t.Fatal(err)
  590. }
  591. if chall.Status != "pending" {
  592. t.Errorf("Status = %q; want pending", chall.Status)
  593. }
  594. if chall.Type != "http-01" {
  595. t.Errorf("c.Type = %q; want http-01", chall.Type)
  596. }
  597. if chall.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  598. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", chall.URI)
  599. }
  600. if chall.Token != "token1" {
  601. t.Errorf("c.Token = %q; want token1", chall.Token)
  602. }
  603. }
  604. func TestAcceptChallenge(t *testing.T) {
  605. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  606. if r.Method == "HEAD" {
  607. w.Header().Set("Replay-Nonce", "test-nonce")
  608. return
  609. }
  610. if r.Method != "POST" {
  611. t.Errorf("r.Method = %q; want POST", r.Method)
  612. }
  613. var j struct {
  614. Resource string
  615. Type string
  616. Auth string `json:"keyAuthorization"`
  617. }
  618. decodeJWSRequest(t, &j, r)
  619. // Test request
  620. if j.Resource != "challenge" {
  621. t.Errorf(`resource = %q; want "challenge"`, j.Resource)
  622. }
  623. if j.Type != "http-01" {
  624. t.Errorf(`type = %q; want "http-01"`, j.Type)
  625. }
  626. keyAuth := "token1." + testKeyECThumbprint
  627. if j.Auth != keyAuth {
  628. t.Errorf(`keyAuthorization = %q; want %q`, j.Auth, keyAuth)
  629. }
  630. // Respond to request
  631. w.WriteHeader(http.StatusAccepted)
  632. fmt.Fprintf(w, `{
  633. "type":"http-01",
  634. "status":"pending",
  635. "uri":"https://ca.tld/acme/challenge/publickey/id1",
  636. "token":"token1",
  637. "keyAuthorization":%q
  638. }`, keyAuth)
  639. }))
  640. defer ts.Close()
  641. cl := Client{Key: testKeyEC}
  642. c, err := cl.Accept(context.Background(), &Challenge{
  643. URI: ts.URL,
  644. Token: "token1",
  645. Type: "http-01",
  646. })
  647. if err != nil {
  648. t.Fatal(err)
  649. }
  650. if c.Type != "http-01" {
  651. t.Errorf("c.Type = %q; want http-01", c.Type)
  652. }
  653. if c.URI != "https://ca.tld/acme/challenge/publickey/id1" {
  654. t.Errorf("c.URI = %q; want https://ca.tld/acme/challenge/publickey/id1", c.URI)
  655. }
  656. if c.Token != "token1" {
  657. t.Errorf("c.Token = %q; want token1", c.Token)
  658. }
  659. }
  660. func TestNewCert(t *testing.T) {
  661. notBefore := time.Now()
  662. notAfter := notBefore.AddDate(0, 2, 0)
  663. timeNow = func() time.Time { return notBefore }
  664. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  665. if r.Method == "HEAD" {
  666. w.Header().Set("Replay-Nonce", "test-nonce")
  667. return
  668. }
  669. if r.Method != "POST" {
  670. t.Errorf("r.Method = %q; want POST", r.Method)
  671. }
  672. var j struct {
  673. Resource string `json:"resource"`
  674. CSR string `json:"csr"`
  675. NotBefore string `json:"notBefore,omitempty"`
  676. NotAfter string `json:"notAfter,omitempty"`
  677. }
  678. decodeJWSRequest(t, &j, r)
  679. // Test request
  680. if j.Resource != "new-cert" {
  681. t.Errorf(`resource = %q; want "new-cert"`, j.Resource)
  682. }
  683. if j.NotBefore != notBefore.Format(time.RFC3339) {
  684. t.Errorf(`notBefore = %q; wanted %q`, j.NotBefore, notBefore.Format(time.RFC3339))
  685. }
  686. if j.NotAfter != notAfter.Format(time.RFC3339) {
  687. t.Errorf(`notAfter = %q; wanted %q`, j.NotAfter, notAfter.Format(time.RFC3339))
  688. }
  689. // Respond to request
  690. template := x509.Certificate{
  691. SerialNumber: big.NewInt(int64(1)),
  692. Subject: pkix.Name{
  693. Organization: []string{"goacme"},
  694. },
  695. NotBefore: notBefore,
  696. NotAfter: notAfter,
  697. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  698. ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
  699. BasicConstraintsValid: true,
  700. }
  701. sampleCert, err := x509.CreateCertificate(rand.Reader, &template, &template, &testKeyEC.PublicKey, testKeyEC)
  702. if err != nil {
  703. t.Fatalf("Error creating certificate: %v", err)
  704. }
  705. w.Header().Set("Location", "https://ca.tld/acme/cert/1")
  706. w.WriteHeader(http.StatusCreated)
  707. w.Write(sampleCert)
  708. }))
  709. defer ts.Close()
  710. csr := x509.CertificateRequest{
  711. Version: 0,
  712. Subject: pkix.Name{
  713. CommonName: "example.com",
  714. Organization: []string{"goacme"},
  715. },
  716. }
  717. csrb, err := x509.CreateCertificateRequest(rand.Reader, &csr, testKeyEC)
  718. if err != nil {
  719. t.Fatal(err)
  720. }
  721. c := Client{Key: testKeyEC, dir: &Directory{CertURL: ts.URL}}
  722. cert, certURL, err := c.CreateCert(context.Background(), csrb, notAfter.Sub(notBefore), false)
  723. if err != nil {
  724. t.Fatal(err)
  725. }
  726. if cert == nil {
  727. t.Errorf("cert is nil")
  728. }
  729. if certURL != "https://ca.tld/acme/cert/1" {
  730. t.Errorf("certURL = %q; want https://ca.tld/acme/cert/1", certURL)
  731. }
  732. }
  733. func TestFetchCert(t *testing.T) {
  734. var count byte
  735. var ts *httptest.Server
  736. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  737. count++
  738. if count < 3 {
  739. up := fmt.Sprintf("<%s>;rel=up", ts.URL)
  740. w.Header().Set("Link", up)
  741. }
  742. w.Write([]byte{count})
  743. }))
  744. defer ts.Close()
  745. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  746. if err != nil {
  747. t.Fatalf("FetchCert: %v", err)
  748. }
  749. cert := [][]byte{{1}, {2}, {3}}
  750. if !reflect.DeepEqual(res, cert) {
  751. t.Errorf("res = %v; want %v", res, cert)
  752. }
  753. }
  754. func TestFetchCertRetry(t *testing.T) {
  755. var count int
  756. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  757. if count < 1 {
  758. w.Header().Set("Retry-After", "0")
  759. w.WriteHeader(http.StatusTooManyRequests)
  760. count++
  761. return
  762. }
  763. w.Write([]byte{1})
  764. }))
  765. defer ts.Close()
  766. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  767. if err != nil {
  768. t.Fatalf("FetchCert: %v", err)
  769. }
  770. cert := [][]byte{{1}}
  771. if !reflect.DeepEqual(res, cert) {
  772. t.Errorf("res = %v; want %v", res, cert)
  773. }
  774. }
  775. func TestFetchCertCancel(t *testing.T) {
  776. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  777. w.Header().Set("Retry-After", "0")
  778. w.WriteHeader(http.StatusAccepted)
  779. }))
  780. defer ts.Close()
  781. ctx, cancel := context.WithCancel(context.Background())
  782. done := make(chan struct{})
  783. var err error
  784. go func() {
  785. _, err = (&Client{}).FetchCert(ctx, ts.URL, false)
  786. close(done)
  787. }()
  788. cancel()
  789. <-done
  790. if err != context.Canceled {
  791. t.Errorf("err = %v; want %v", err, context.Canceled)
  792. }
  793. }
  794. func TestFetchCertDepth(t *testing.T) {
  795. var count byte
  796. var ts *httptest.Server
  797. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  798. count++
  799. if count > maxChainLen+1 {
  800. t.Errorf("count = %d; want at most %d", count, maxChainLen+1)
  801. w.WriteHeader(http.StatusInternalServerError)
  802. }
  803. w.Header().Set("Link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  804. w.Write([]byte{count})
  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 TestFetchCertBreadth(t *testing.T) {
  813. var ts *httptest.Server
  814. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  815. for i := 0; i < maxChainLen+1; i++ {
  816. w.Header().Add("Link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  817. }
  818. w.Write([]byte{1})
  819. }))
  820. defer ts.Close()
  821. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  822. if err == nil {
  823. t.Errorf("err is nil")
  824. }
  825. }
  826. func TestFetchCertSize(t *testing.T) {
  827. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  828. b := bytes.Repeat([]byte{1}, maxCertSize+1)
  829. w.Write(b)
  830. }))
  831. defer ts.Close()
  832. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  833. if err == nil {
  834. t.Errorf("err is nil")
  835. }
  836. }
  837. func TestRevokeCert(t *testing.T) {
  838. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  839. if r.Method == "HEAD" {
  840. w.Header().Set("Replay-Nonce", "nonce")
  841. return
  842. }
  843. var req struct {
  844. Resource string
  845. Certificate string
  846. Reason int
  847. }
  848. decodeJWSRequest(t, &req, r)
  849. if req.Resource != "revoke-cert" {
  850. t.Errorf("req.Resource = %q; want revoke-cert", req.Resource)
  851. }
  852. if req.Reason != 1 {
  853. t.Errorf("req.Reason = %d; want 1", req.Reason)
  854. }
  855. // echo -n cert | base64 | tr -d '=' | tr '/+' '_-'
  856. cert := "Y2VydA"
  857. if req.Certificate != cert {
  858. t.Errorf("req.Certificate = %q; want %q", req.Certificate, cert)
  859. }
  860. }))
  861. defer ts.Close()
  862. client := &Client{
  863. Key: testKeyEC,
  864. dir: &Directory{RevokeURL: ts.URL},
  865. }
  866. ctx := context.Background()
  867. if err := client.RevokeCert(ctx, nil, []byte("cert"), CRLReasonKeyCompromise); err != nil {
  868. t.Fatal(err)
  869. }
  870. }
  871. func TestNonce_add(t *testing.T) {
  872. var c Client
  873. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  874. c.addNonce(http.Header{"Replay-Nonce": {}})
  875. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  876. nonces := map[string]struct{}{"nonce": {}}
  877. if !reflect.DeepEqual(c.nonces, nonces) {
  878. t.Errorf("c.nonces = %q; want %q", c.nonces, nonces)
  879. }
  880. }
  881. func TestNonce_addMax(t *testing.T) {
  882. c := &Client{nonces: make(map[string]struct{})}
  883. for i := 0; i < maxNonces; i++ {
  884. c.nonces[fmt.Sprintf("%d", i)] = struct{}{}
  885. }
  886. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  887. if n := len(c.nonces); n != maxNonces {
  888. t.Errorf("len(c.nonces) = %d; want %d", n, maxNonces)
  889. }
  890. }
  891. func TestNonce_fetch(t *testing.T) {
  892. tests := []struct {
  893. code int
  894. nonce string
  895. }{
  896. {http.StatusOK, "nonce1"},
  897. {http.StatusBadRequest, "nonce2"},
  898. {http.StatusOK, ""},
  899. }
  900. var i int
  901. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  902. if r.Method != "HEAD" {
  903. t.Errorf("%d: r.Method = %q; want HEAD", i, r.Method)
  904. }
  905. w.Header().Set("Replay-Nonce", tests[i].nonce)
  906. w.WriteHeader(tests[i].code)
  907. }))
  908. defer ts.Close()
  909. for ; i < len(tests); i++ {
  910. test := tests[i]
  911. c := &Client{}
  912. n, err := c.fetchNonce(context.Background(), ts.URL)
  913. if n != test.nonce {
  914. t.Errorf("%d: n=%q; want %q", i, n, test.nonce)
  915. }
  916. switch {
  917. case err == nil && test.nonce == "":
  918. t.Errorf("%d: n=%q, err=%v; want non-nil error", i, n, err)
  919. case err != nil && test.nonce != "":
  920. t.Errorf("%d: n=%q, err=%v; want %q", i, n, err, test.nonce)
  921. }
  922. }
  923. }
  924. func TestNonce_fetchError(t *testing.T) {
  925. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  926. w.WriteHeader(http.StatusTooManyRequests)
  927. }))
  928. defer ts.Close()
  929. c := &Client{}
  930. _, err := c.fetchNonce(context.Background(), ts.URL)
  931. e, ok := err.(*Error)
  932. if !ok {
  933. t.Fatalf("err is %T; want *Error", err)
  934. }
  935. if e.StatusCode != http.StatusTooManyRequests {
  936. t.Errorf("e.StatusCode = %d; want %d", e.StatusCode, http.StatusTooManyRequests)
  937. }
  938. }
  939. func TestNonce_postJWS(t *testing.T) {
  940. var count int
  941. seen := make(map[string]bool)
  942. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  943. count++
  944. w.Header().Set("Replay-Nonce", fmt.Sprintf("nonce%d", count))
  945. if r.Method == "HEAD" {
  946. // We expect the client do a HEAD request
  947. // but only to fetch the first nonce.
  948. return
  949. }
  950. // Make client.Authorize happy; we're not testing its result.
  951. defer func() {
  952. w.WriteHeader(http.StatusCreated)
  953. w.Write([]byte(`{"status":"valid"}`))
  954. }()
  955. head, err := decodeJWSHead(r)
  956. if err != nil {
  957. t.Errorf("decodeJWSHead: %v", err)
  958. return
  959. }
  960. if head.Nonce == "" {
  961. t.Error("head.Nonce is empty")
  962. return
  963. }
  964. if seen[head.Nonce] {
  965. t.Errorf("nonce is already used: %q", head.Nonce)
  966. }
  967. seen[head.Nonce] = true
  968. }))
  969. defer ts.Close()
  970. client := Client{Key: testKey, dir: &Directory{AuthzURL: ts.URL}}
  971. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  972. t.Errorf("client.Authorize 1: %v", err)
  973. }
  974. // The second call should not generate another extra HEAD request.
  975. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  976. t.Errorf("client.Authorize 2: %v", err)
  977. }
  978. if count != 3 {
  979. t.Errorf("total requests count: %d; want 3", count)
  980. }
  981. if n := len(client.nonces); n != 1 {
  982. t.Errorf("len(client.nonces) = %d; want 1", n)
  983. }
  984. for k := range seen {
  985. if _, exist := client.nonces[k]; exist {
  986. t.Errorf("used nonce %q in client.nonces", k)
  987. }
  988. }
  989. }
  990. func TestLinkHeader(t *testing.T) {
  991. h := http.Header{"Link": {
  992. `<https://example.com/acme/new-authz>;rel="next"`,
  993. `<https://example.com/acme/recover-reg>; rel=recover`,
  994. `<https://example.com/acme/terms>; foo=bar; rel="terms-of-service"`,
  995. `<dup>;rel="next"`,
  996. }}
  997. tests := []struct {
  998. rel string
  999. out []string
  1000. }{
  1001. {"next", []string{"https://example.com/acme/new-authz", "dup"}},
  1002. {"recover", []string{"https://example.com/acme/recover-reg"}},
  1003. {"terms-of-service", []string{"https://example.com/acme/terms"}},
  1004. {"empty", nil},
  1005. }
  1006. for i, test := range tests {
  1007. if v := linkHeader(h, test.rel); !reflect.DeepEqual(v, test.out) {
  1008. t.Errorf("%d: linkHeader(%q): %v; want %v", i, test.rel, v, test.out)
  1009. }
  1010. }
  1011. }
  1012. func TestTLSSNI01ChallengeCert(t *testing.T) {
  1013. const (
  1014. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1015. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1016. san = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.acme.invalid"
  1017. )
  1018. client := &Client{Key: testKeyEC}
  1019. tlscert, name, err := client.TLSSNI01ChallengeCert(token)
  1020. if err != nil {
  1021. t.Fatal(err)
  1022. }
  1023. if n := len(tlscert.Certificate); n != 1 {
  1024. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1025. }
  1026. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1027. if err != nil {
  1028. t.Fatal(err)
  1029. }
  1030. if len(cert.DNSNames) != 1 || cert.DNSNames[0] != san {
  1031. t.Fatalf("cert.DNSNames = %v; want %q", cert.DNSNames, san)
  1032. }
  1033. if cert.DNSNames[0] != name {
  1034. t.Errorf("cert.DNSNames[0] != name: %q vs %q", cert.DNSNames[0], name)
  1035. }
  1036. if cn := cert.Subject.CommonName; cn != san {
  1037. t.Errorf("cert.Subject.CommonName = %q; want %q", cn, san)
  1038. }
  1039. }
  1040. func TestTLSSNI02ChallengeCert(t *testing.T) {
  1041. const (
  1042. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1043. // echo -n evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA | shasum -a 256
  1044. sanA = "7ea0aaa69214e71e02cebb18bb867736.09b730209baabf60e43d4999979ff139.token.acme.invalid"
  1045. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1046. sanB = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.ka.acme.invalid"
  1047. )
  1048. client := &Client{Key: testKeyEC}
  1049. tlscert, name, err := client.TLSSNI02ChallengeCert(token)
  1050. if err != nil {
  1051. t.Fatal(err)
  1052. }
  1053. if n := len(tlscert.Certificate); n != 1 {
  1054. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1055. }
  1056. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1057. if err != nil {
  1058. t.Fatal(err)
  1059. }
  1060. names := []string{sanA, sanB}
  1061. if !reflect.DeepEqual(cert.DNSNames, names) {
  1062. t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
  1063. }
  1064. sort.Strings(cert.DNSNames)
  1065. i := sort.SearchStrings(cert.DNSNames, name)
  1066. if i >= len(cert.DNSNames) || cert.DNSNames[i] != name {
  1067. t.Errorf("%v doesn't have %q", cert.DNSNames, name)
  1068. }
  1069. if cn := cert.Subject.CommonName; cn != sanA {
  1070. t.Errorf("CommonName = %q; want %q", cn, sanA)
  1071. }
  1072. }
  1073. func TestTLSALPN01ChallengeCert(t *testing.T) {
  1074. const (
  1075. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1076. keyAuth = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA." + testKeyECThumbprint
  1077. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1078. h = "0420dbbd5eefe7b4d06eb9d1d9f5acb4c7cda27d320e4b30332f0b6cb441734ad7b0"
  1079. domain = "example.com"
  1080. )
  1081. extValue, err := hex.DecodeString(h)
  1082. if err != nil {
  1083. t.Fatal(err)
  1084. }
  1085. client := &Client{Key: testKeyEC}
  1086. tlscert, err := client.TLSALPN01ChallengeCert(token, domain)
  1087. if err != nil {
  1088. t.Fatal(err)
  1089. }
  1090. if n := len(tlscert.Certificate); n != 1 {
  1091. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1092. }
  1093. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1094. if err != nil {
  1095. t.Fatal(err)
  1096. }
  1097. names := []string{domain}
  1098. if !reflect.DeepEqual(cert.DNSNames, names) {
  1099. t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
  1100. }
  1101. if cn := cert.Subject.CommonName; cn != domain {
  1102. t.Errorf("CommonName = %q; want %q", cn, domain)
  1103. }
  1104. acmeExts := []pkix.Extension{}
  1105. for _, ext := range cert.Extensions {
  1106. if idPeACMEIdentifierV1.Equal(ext.Id) {
  1107. acmeExts = append(acmeExts, ext)
  1108. }
  1109. }
  1110. if len(acmeExts) != 1 {
  1111. t.Errorf("acmeExts = %v; want exactly one", acmeExts)
  1112. }
  1113. if !acmeExts[0].Critical {
  1114. t.Errorf("acmeExt.Critical = %v; want true", acmeExts[0].Critical)
  1115. }
  1116. if bytes.Compare(acmeExts[0].Value, extValue) != 0 {
  1117. t.Errorf("acmeExt.Value = %v; want %v", acmeExts[0].Value, extValue)
  1118. }
  1119. }
  1120. func TestTLSChallengeCertOpt(t *testing.T) {
  1121. key, err := rsa.GenerateKey(rand.Reader, 512)
  1122. if err != nil {
  1123. t.Fatal(err)
  1124. }
  1125. tmpl := &x509.Certificate{
  1126. SerialNumber: big.NewInt(2),
  1127. Subject: pkix.Name{Organization: []string{"Test"}},
  1128. DNSNames: []string{"should-be-overwritten"},
  1129. }
  1130. opts := []CertOption{WithKey(key), WithTemplate(tmpl)}
  1131. client := &Client{Key: testKeyEC}
  1132. cert1, _, err := client.TLSSNI01ChallengeCert("token", opts...)
  1133. if err != nil {
  1134. t.Fatal(err)
  1135. }
  1136. cert2, _, err := client.TLSSNI02ChallengeCert("token", opts...)
  1137. if err != nil {
  1138. t.Fatal(err)
  1139. }
  1140. for i, tlscert := range []tls.Certificate{cert1, cert2} {
  1141. // verify generated cert private key
  1142. tlskey, ok := tlscert.PrivateKey.(*rsa.PrivateKey)
  1143. if !ok {
  1144. t.Errorf("%d: tlscert.PrivateKey is %T; want *rsa.PrivateKey", i, tlscert.PrivateKey)
  1145. continue
  1146. }
  1147. if tlskey.D.Cmp(key.D) != 0 {
  1148. t.Errorf("%d: tlskey.D = %v; want %v", i, tlskey.D, key.D)
  1149. }
  1150. // verify generated cert public key
  1151. x509Cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1152. if err != nil {
  1153. t.Errorf("%d: %v", i, err)
  1154. continue
  1155. }
  1156. tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey)
  1157. if !ok {
  1158. t.Errorf("%d: x509Cert.PublicKey is %T; want *rsa.PublicKey", i, x509Cert.PublicKey)
  1159. continue
  1160. }
  1161. if tlspub.N.Cmp(key.N) != 0 {
  1162. t.Errorf("%d: tlspub.N = %v; want %v", i, tlspub.N, key.N)
  1163. }
  1164. // verify template option
  1165. sn := big.NewInt(2)
  1166. if x509Cert.SerialNumber.Cmp(sn) != 0 {
  1167. t.Errorf("%d: SerialNumber = %v; want %v", i, x509Cert.SerialNumber, sn)
  1168. }
  1169. org := []string{"Test"}
  1170. if !reflect.DeepEqual(x509Cert.Subject.Organization, org) {
  1171. t.Errorf("%d: Subject.Organization = %+v; want %+v", i, x509Cert.Subject.Organization, org)
  1172. }
  1173. for _, v := range x509Cert.DNSNames {
  1174. if !strings.HasSuffix(v, ".acme.invalid") {
  1175. t.Errorf("%d: invalid DNSNames element: %q", i, v)
  1176. }
  1177. }
  1178. }
  1179. }
  1180. func TestHTTP01Challenge(t *testing.T) {
  1181. const (
  1182. token = "xxx"
  1183. // thumbprint is precomputed for testKeyEC in jws_test.go
  1184. value = token + "." + testKeyECThumbprint
  1185. urlpath = "/.well-known/acme-challenge/" + token
  1186. )
  1187. client := &Client{Key: testKeyEC}
  1188. val, err := client.HTTP01ChallengeResponse(token)
  1189. if err != nil {
  1190. t.Fatal(err)
  1191. }
  1192. if val != value {
  1193. t.Errorf("val = %q; want %q", val, value)
  1194. }
  1195. if path := client.HTTP01ChallengePath(token); path != urlpath {
  1196. t.Errorf("path = %q; want %q", path, urlpath)
  1197. }
  1198. }
  1199. func TestDNS01ChallengeRecord(t *testing.T) {
  1200. // echo -n xxx.<testKeyECThumbprint> | \
  1201. // openssl dgst -binary -sha256 | \
  1202. // base64 | tr -d '=' | tr '/+' '_-'
  1203. const value = "8DERMexQ5VcdJ_prpPiA0mVdp7imgbCgjsG4SqqNMIo"
  1204. client := &Client{Key: testKeyEC}
  1205. val, err := client.DNS01ChallengeRecord("xxx")
  1206. if err != nil {
  1207. t.Fatal(err)
  1208. }
  1209. if val != value {
  1210. t.Errorf("val = %q; want %q", val, value)
  1211. }
  1212. }