acme_test.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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}
  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
  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}
  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. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  801. if err != nil {
  802. t.Fatalf("FetchCert: %v", err)
  803. }
  804. cert := [][]byte{{1}, {2}, {3}}
  805. if !reflect.DeepEqual(res, cert) {
  806. t.Errorf("res = %v; want %v", res, cert)
  807. }
  808. }
  809. func TestFetchCertRetry(t *testing.T) {
  810. var count int
  811. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  812. if count < 1 {
  813. w.Header().Set("Retry-After", "0")
  814. w.WriteHeader(http.StatusTooManyRequests)
  815. count++
  816. return
  817. }
  818. w.Write([]byte{1})
  819. }))
  820. defer ts.Close()
  821. res, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  822. if err != nil {
  823. t.Fatalf("FetchCert: %v", err)
  824. }
  825. cert := [][]byte{{1}}
  826. if !reflect.DeepEqual(res, cert) {
  827. t.Errorf("res = %v; want %v", res, cert)
  828. }
  829. }
  830. func TestFetchCertCancel(t *testing.T) {
  831. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  832. w.Header().Set("Retry-After", "0")
  833. w.WriteHeader(http.StatusAccepted)
  834. }))
  835. defer ts.Close()
  836. ctx, cancel := context.WithCancel(context.Background())
  837. done := make(chan struct{})
  838. var err error
  839. go func() {
  840. _, err = (&Client{}).FetchCert(ctx, ts.URL, false)
  841. close(done)
  842. }()
  843. cancel()
  844. <-done
  845. if err != context.Canceled {
  846. t.Errorf("err = %v; want %v", err, context.Canceled)
  847. }
  848. }
  849. func TestFetchCertDepth(t *testing.T) {
  850. var count byte
  851. var ts *httptest.Server
  852. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  853. count++
  854. if count > maxChainLen+1 {
  855. t.Errorf("count = %d; want at most %d", count, maxChainLen+1)
  856. w.WriteHeader(http.StatusInternalServerError)
  857. }
  858. w.Header().Set("Link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  859. w.Write([]byte{count})
  860. }))
  861. defer ts.Close()
  862. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  863. if err == nil {
  864. t.Errorf("err is nil")
  865. }
  866. }
  867. func TestFetchCertBreadth(t *testing.T) {
  868. var ts *httptest.Server
  869. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  870. for i := 0; i < maxChainLen+1; i++ {
  871. w.Header().Add("Link", fmt.Sprintf("<%s>;rel=up", ts.URL))
  872. }
  873. w.Write([]byte{1})
  874. }))
  875. defer ts.Close()
  876. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, true)
  877. if err == nil {
  878. t.Errorf("err is nil")
  879. }
  880. }
  881. func TestFetchCertSize(t *testing.T) {
  882. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  883. b := bytes.Repeat([]byte{1}, maxCertSize+1)
  884. w.Write(b)
  885. }))
  886. defer ts.Close()
  887. _, err := (&Client{}).FetchCert(context.Background(), ts.URL, false)
  888. if err == nil {
  889. t.Errorf("err is nil")
  890. }
  891. }
  892. func TestRevokeCert(t *testing.T) {
  893. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  894. if r.Method == "HEAD" {
  895. w.Header().Set("Replay-Nonce", "nonce")
  896. return
  897. }
  898. var req struct {
  899. Resource string
  900. Certificate string
  901. Reason int
  902. }
  903. decodeJWSRequest(t, &req, r.Body)
  904. if req.Resource != "revoke-cert" {
  905. t.Errorf("req.Resource = %q; want revoke-cert", req.Resource)
  906. }
  907. if req.Reason != 1 {
  908. t.Errorf("req.Reason = %d; want 1", req.Reason)
  909. }
  910. // echo -n cert | base64 | tr -d '=' | tr '/+' '_-'
  911. cert := "Y2VydA"
  912. if req.Certificate != cert {
  913. t.Errorf("req.Certificate = %q; want %q", req.Certificate, cert)
  914. }
  915. }))
  916. defer ts.Close()
  917. client := &Client{
  918. Key: testKeyEC,
  919. dir: &Directory{RevokeURL: ts.URL},
  920. }
  921. ctx := context.Background()
  922. if err := client.RevokeCert(ctx, nil, []byte("cert"), CRLReasonKeyCompromise); err != nil {
  923. t.Fatal(err)
  924. }
  925. }
  926. func TestNonce_add(t *testing.T) {
  927. var c Client
  928. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  929. c.addNonce(http.Header{"Replay-Nonce": {}})
  930. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  931. nonces := map[string]struct{}{"nonce": {}}
  932. if !reflect.DeepEqual(c.nonces, nonces) {
  933. t.Errorf("c.nonces = %q; want %q", c.nonces, nonces)
  934. }
  935. }
  936. func TestNonce_addMax(t *testing.T) {
  937. c := &Client{nonces: make(map[string]struct{})}
  938. for i := 0; i < maxNonces; i++ {
  939. c.nonces[fmt.Sprintf("%d", i)] = struct{}{}
  940. }
  941. c.addNonce(http.Header{"Replay-Nonce": {"nonce"}})
  942. if n := len(c.nonces); n != maxNonces {
  943. t.Errorf("len(c.nonces) = %d; want %d", n, maxNonces)
  944. }
  945. }
  946. func TestNonce_fetch(t *testing.T) {
  947. tests := []struct {
  948. code int
  949. nonce string
  950. }{
  951. {http.StatusOK, "nonce1"},
  952. {http.StatusBadRequest, "nonce2"},
  953. {http.StatusOK, ""},
  954. }
  955. var i int
  956. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  957. if r.Method != "HEAD" {
  958. t.Errorf("%d: r.Method = %q; want HEAD", i, r.Method)
  959. }
  960. w.Header().Set("Replay-Nonce", tests[i].nonce)
  961. w.WriteHeader(tests[i].code)
  962. }))
  963. defer ts.Close()
  964. for ; i < len(tests); i++ {
  965. test := tests[i]
  966. c := &Client{}
  967. n, err := c.fetchNonce(context.Background(), ts.URL)
  968. if n != test.nonce {
  969. t.Errorf("%d: n=%q; want %q", i, n, test.nonce)
  970. }
  971. switch {
  972. case err == nil && test.nonce == "":
  973. t.Errorf("%d: n=%q, err=%v; want non-nil error", i, n, err)
  974. case err != nil && test.nonce != "":
  975. t.Errorf("%d: n=%q, err=%v; want %q", i, n, err, test.nonce)
  976. }
  977. }
  978. }
  979. func TestNonce_fetchError(t *testing.T) {
  980. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  981. w.WriteHeader(http.StatusTooManyRequests)
  982. }))
  983. defer ts.Close()
  984. c := &Client{}
  985. _, err := c.fetchNonce(context.Background(), ts.URL)
  986. e, ok := err.(*Error)
  987. if !ok {
  988. t.Fatalf("err is %T; want *Error", err)
  989. }
  990. if e.StatusCode != http.StatusTooManyRequests {
  991. t.Errorf("e.StatusCode = %d; want %d", e.StatusCode, http.StatusTooManyRequests)
  992. }
  993. }
  994. func TestNonce_popWhenEmpty(t *testing.T) {
  995. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  996. if r.Method != "HEAD" {
  997. t.Errorf("r.Method = %q; want HEAD", r.Method)
  998. }
  999. switch r.URL.Path {
  1000. case "/dir-with-nonce":
  1001. w.Header().Set("Replay-Nonce", "dirnonce")
  1002. case "/new-nonce":
  1003. w.Header().Set("Replay-Nonce", "newnonce")
  1004. case "/dir-no-nonce", "/empty":
  1005. // No nonce in the header.
  1006. default:
  1007. t.Errorf("Unknown URL: %s", r.URL)
  1008. }
  1009. }))
  1010. defer ts.Close()
  1011. ctx := context.Background()
  1012. tt := []struct {
  1013. dirURL, popURL, nonce string
  1014. wantOK bool
  1015. }{
  1016. {ts.URL + "/dir-with-nonce", ts.URL + "/new-nonce", "dirnonce", true},
  1017. {ts.URL + "/dir-no-nonce", ts.URL + "/new-nonce", "newnonce", true},
  1018. {ts.URL + "/dir-no-nonce", ts.URL + "/empty", "", false},
  1019. }
  1020. for _, test := range tt {
  1021. t.Run(fmt.Sprintf("nonce:%s wantOK:%v", test.nonce, test.wantOK), func(t *testing.T) {
  1022. c := Client{DirectoryURL: test.dirURL}
  1023. v, err := c.popNonce(ctx, test.popURL)
  1024. if !test.wantOK {
  1025. if err == nil {
  1026. t.Fatalf("c.popNonce(%q) returned nil error", test.popURL)
  1027. }
  1028. return
  1029. }
  1030. if err != nil {
  1031. t.Fatalf("c.popNonce(%q): %v", test.popURL, err)
  1032. }
  1033. if v != test.nonce {
  1034. t.Errorf("c.popNonce(%q) = %q; want %q", test.popURL, v, test.nonce)
  1035. }
  1036. })
  1037. }
  1038. }
  1039. func TestNonce_postJWS(t *testing.T) {
  1040. var count int
  1041. seen := make(map[string]bool)
  1042. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  1043. count++
  1044. w.Header().Set("Replay-Nonce", fmt.Sprintf("nonce%d", count))
  1045. if r.Method == "HEAD" {
  1046. // We expect the client do a HEAD request
  1047. // but only to fetch the first nonce.
  1048. return
  1049. }
  1050. // Make client.Authorize happy; we're not testing its result.
  1051. defer func() {
  1052. w.WriteHeader(http.StatusCreated)
  1053. w.Write([]byte(`{"status":"valid"}`))
  1054. }()
  1055. head, err := decodeJWSHead(r.Body)
  1056. if err != nil {
  1057. t.Errorf("decodeJWSHead: %v", err)
  1058. return
  1059. }
  1060. if head.Nonce == "" {
  1061. t.Error("head.Nonce is empty")
  1062. return
  1063. }
  1064. if seen[head.Nonce] {
  1065. t.Errorf("nonce is already used: %q", head.Nonce)
  1066. }
  1067. seen[head.Nonce] = true
  1068. }))
  1069. defer ts.Close()
  1070. client := Client{
  1071. Key: testKey,
  1072. DirectoryURL: ts.URL, // nonces are fetched from here first
  1073. dir: &Directory{AuthzURL: ts.URL},
  1074. }
  1075. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  1076. t.Errorf("client.Authorize 1: %v", err)
  1077. }
  1078. // The second call should not generate another extra HEAD request.
  1079. if _, err := client.Authorize(context.Background(), "example.com"); err != nil {
  1080. t.Errorf("client.Authorize 2: %v", err)
  1081. }
  1082. if count != 3 {
  1083. t.Errorf("total requests count: %d; want 3", count)
  1084. }
  1085. if n := len(client.nonces); n != 1 {
  1086. t.Errorf("len(client.nonces) = %d; want 1", n)
  1087. }
  1088. for k := range seen {
  1089. if _, exist := client.nonces[k]; exist {
  1090. t.Errorf("used nonce %q in client.nonces", k)
  1091. }
  1092. }
  1093. }
  1094. func TestLinkHeader(t *testing.T) {
  1095. h := http.Header{"Link": {
  1096. `<https://example.com/acme/new-authz>;rel="next"`,
  1097. `<https://example.com/acme/recover-reg>; rel=recover`,
  1098. `<https://example.com/acme/terms>; foo=bar; rel="terms-of-service"`,
  1099. `<dup>;rel="next"`,
  1100. }}
  1101. tests := []struct {
  1102. rel string
  1103. out []string
  1104. }{
  1105. {"next", []string{"https://example.com/acme/new-authz", "dup"}},
  1106. {"recover", []string{"https://example.com/acme/recover-reg"}},
  1107. {"terms-of-service", []string{"https://example.com/acme/terms"}},
  1108. {"empty", nil},
  1109. }
  1110. for i, test := range tests {
  1111. if v := linkHeader(h, test.rel); !reflect.DeepEqual(v, test.out) {
  1112. t.Errorf("%d: linkHeader(%q): %v; want %v", i, test.rel, v, test.out)
  1113. }
  1114. }
  1115. }
  1116. func TestTLSSNI01ChallengeCert(t *testing.T) {
  1117. const (
  1118. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1119. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1120. san = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.acme.invalid"
  1121. )
  1122. client := &Client{Key: testKeyEC}
  1123. tlscert, name, err := client.TLSSNI01ChallengeCert(token)
  1124. if err != nil {
  1125. t.Fatal(err)
  1126. }
  1127. if n := len(tlscert.Certificate); n != 1 {
  1128. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1129. }
  1130. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1131. if err != nil {
  1132. t.Fatal(err)
  1133. }
  1134. if len(cert.DNSNames) != 1 || cert.DNSNames[0] != san {
  1135. t.Fatalf("cert.DNSNames = %v; want %q", cert.DNSNames, san)
  1136. }
  1137. if cert.DNSNames[0] != name {
  1138. t.Errorf("cert.DNSNames[0] != name: %q vs %q", cert.DNSNames[0], name)
  1139. }
  1140. if cn := cert.Subject.CommonName; cn != san {
  1141. t.Errorf("cert.Subject.CommonName = %q; want %q", cn, san)
  1142. }
  1143. }
  1144. func TestTLSSNI02ChallengeCert(t *testing.T) {
  1145. const (
  1146. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1147. // echo -n evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA | shasum -a 256
  1148. sanA = "7ea0aaa69214e71e02cebb18bb867736.09b730209baabf60e43d4999979ff139.token.acme.invalid"
  1149. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1150. sanB = "dbbd5eefe7b4d06eb9d1d9f5acb4c7cd.a27d320e4b30332f0b6cb441734ad7b0.ka.acme.invalid"
  1151. )
  1152. client := &Client{Key: testKeyEC}
  1153. tlscert, name, err := client.TLSSNI02ChallengeCert(token)
  1154. if err != nil {
  1155. t.Fatal(err)
  1156. }
  1157. if n := len(tlscert.Certificate); n != 1 {
  1158. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1159. }
  1160. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1161. if err != nil {
  1162. t.Fatal(err)
  1163. }
  1164. names := []string{sanA, sanB}
  1165. if !reflect.DeepEqual(cert.DNSNames, names) {
  1166. t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
  1167. }
  1168. sort.Strings(cert.DNSNames)
  1169. i := sort.SearchStrings(cert.DNSNames, name)
  1170. if i >= len(cert.DNSNames) || cert.DNSNames[i] != name {
  1171. t.Errorf("%v doesn't have %q", cert.DNSNames, name)
  1172. }
  1173. if cn := cert.Subject.CommonName; cn != sanA {
  1174. t.Errorf("CommonName = %q; want %q", cn, sanA)
  1175. }
  1176. }
  1177. func TestTLSALPN01ChallengeCert(t *testing.T) {
  1178. const (
  1179. token = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA"
  1180. keyAuth = "evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ-PCt92wr-oA." + testKeyECThumbprint
  1181. // echo -n <token.testKeyECThumbprint> | shasum -a 256
  1182. h = "0420dbbd5eefe7b4d06eb9d1d9f5acb4c7cda27d320e4b30332f0b6cb441734ad7b0"
  1183. domain = "example.com"
  1184. )
  1185. extValue, err := hex.DecodeString(h)
  1186. if err != nil {
  1187. t.Fatal(err)
  1188. }
  1189. client := &Client{Key: testKeyEC}
  1190. tlscert, err := client.TLSALPN01ChallengeCert(token, domain)
  1191. if err != nil {
  1192. t.Fatal(err)
  1193. }
  1194. if n := len(tlscert.Certificate); n != 1 {
  1195. t.Fatalf("len(tlscert.Certificate) = %d; want 1", n)
  1196. }
  1197. cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1198. if err != nil {
  1199. t.Fatal(err)
  1200. }
  1201. names := []string{domain}
  1202. if !reflect.DeepEqual(cert.DNSNames, names) {
  1203. t.Fatalf("cert.DNSNames = %v;\nwant %v", cert.DNSNames, names)
  1204. }
  1205. if cn := cert.Subject.CommonName; cn != domain {
  1206. t.Errorf("CommonName = %q; want %q", cn, domain)
  1207. }
  1208. acmeExts := []pkix.Extension{}
  1209. for _, ext := range cert.Extensions {
  1210. if idPeACMEIdentifierV1.Equal(ext.Id) {
  1211. acmeExts = append(acmeExts, ext)
  1212. }
  1213. }
  1214. if len(acmeExts) != 1 {
  1215. t.Errorf("acmeExts = %v; want exactly one", acmeExts)
  1216. }
  1217. if !acmeExts[0].Critical {
  1218. t.Errorf("acmeExt.Critical = %v; want true", acmeExts[0].Critical)
  1219. }
  1220. if bytes.Compare(acmeExts[0].Value, extValue) != 0 {
  1221. t.Errorf("acmeExt.Value = %v; want %v", acmeExts[0].Value, extValue)
  1222. }
  1223. }
  1224. func TestTLSChallengeCertOpt(t *testing.T) {
  1225. key, err := rsa.GenerateKey(rand.Reader, 512)
  1226. if err != nil {
  1227. t.Fatal(err)
  1228. }
  1229. tmpl := &x509.Certificate{
  1230. SerialNumber: big.NewInt(2),
  1231. Subject: pkix.Name{Organization: []string{"Test"}},
  1232. DNSNames: []string{"should-be-overwritten"},
  1233. }
  1234. opts := []CertOption{WithKey(key), WithTemplate(tmpl)}
  1235. client := &Client{Key: testKeyEC}
  1236. cert1, _, err := client.TLSSNI01ChallengeCert("token", opts...)
  1237. if err != nil {
  1238. t.Fatal(err)
  1239. }
  1240. cert2, _, err := client.TLSSNI02ChallengeCert("token", opts...)
  1241. if err != nil {
  1242. t.Fatal(err)
  1243. }
  1244. for i, tlscert := range []tls.Certificate{cert1, cert2} {
  1245. // verify generated cert private key
  1246. tlskey, ok := tlscert.PrivateKey.(*rsa.PrivateKey)
  1247. if !ok {
  1248. t.Errorf("%d: tlscert.PrivateKey is %T; want *rsa.PrivateKey", i, tlscert.PrivateKey)
  1249. continue
  1250. }
  1251. if tlskey.D.Cmp(key.D) != 0 {
  1252. t.Errorf("%d: tlskey.D = %v; want %v", i, tlskey.D, key.D)
  1253. }
  1254. // verify generated cert public key
  1255. x509Cert, err := x509.ParseCertificate(tlscert.Certificate[0])
  1256. if err != nil {
  1257. t.Errorf("%d: %v", i, err)
  1258. continue
  1259. }
  1260. tlspub, ok := x509Cert.PublicKey.(*rsa.PublicKey)
  1261. if !ok {
  1262. t.Errorf("%d: x509Cert.PublicKey is %T; want *rsa.PublicKey", i, x509Cert.PublicKey)
  1263. continue
  1264. }
  1265. if tlspub.N.Cmp(key.N) != 0 {
  1266. t.Errorf("%d: tlspub.N = %v; want %v", i, tlspub.N, key.N)
  1267. }
  1268. // verify template option
  1269. sn := big.NewInt(2)
  1270. if x509Cert.SerialNumber.Cmp(sn) != 0 {
  1271. t.Errorf("%d: SerialNumber = %v; want %v", i, x509Cert.SerialNumber, sn)
  1272. }
  1273. org := []string{"Test"}
  1274. if !reflect.DeepEqual(x509Cert.Subject.Organization, org) {
  1275. t.Errorf("%d: Subject.Organization = %+v; want %+v", i, x509Cert.Subject.Organization, org)
  1276. }
  1277. for _, v := range x509Cert.DNSNames {
  1278. if !strings.HasSuffix(v, ".acme.invalid") {
  1279. t.Errorf("%d: invalid DNSNames element: %q", i, v)
  1280. }
  1281. }
  1282. }
  1283. }
  1284. func TestHTTP01Challenge(t *testing.T) {
  1285. const (
  1286. token = "xxx"
  1287. // thumbprint is precomputed for testKeyEC in jws_test.go
  1288. value = token + "." + testKeyECThumbprint
  1289. urlpath = "/.well-known/acme-challenge/" + token
  1290. )
  1291. client := &Client{Key: testKeyEC}
  1292. val, err := client.HTTP01ChallengeResponse(token)
  1293. if err != nil {
  1294. t.Fatal(err)
  1295. }
  1296. if val != value {
  1297. t.Errorf("val = %q; want %q", val, value)
  1298. }
  1299. if path := client.HTTP01ChallengePath(token); path != urlpath {
  1300. t.Errorf("path = %q; want %q", path, urlpath)
  1301. }
  1302. }
  1303. func TestDNS01ChallengeRecord(t *testing.T) {
  1304. // echo -n xxx.<testKeyECThumbprint> | \
  1305. // openssl dgst -binary -sha256 | \
  1306. // base64 | tr -d '=' | tr '/+' '_-'
  1307. const value = "8DERMexQ5VcdJ_prpPiA0mVdp7imgbCgjsG4SqqNMIo"
  1308. client := &Client{Key: testKeyEC}
  1309. val, err := client.DNS01ChallengeRecord("xxx")
  1310. if err != nil {
  1311. t.Fatal(err)
  1312. }
  1313. if val != value {
  1314. t.Errorf("val = %q; want %q", val, value)
  1315. }
  1316. }