acme_test.go 36 KB

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