acme_test.go 39 KB

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