acme_test.go 31 KB

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