acme_test.go 35 KB

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