rfc8555_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. // Copyright 2019 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/x509"
  10. "crypto/x509/pkix"
  11. "encoding/json"
  12. "encoding/pem"
  13. "fmt"
  14. "io/ioutil"
  15. "math/big"
  16. "net/http"
  17. "net/http/httptest"
  18. "reflect"
  19. "sync"
  20. "testing"
  21. "time"
  22. )
  23. // While contents of this file is pertinent only to RFC8555,
  24. // it is complementary to the tests in the other _test.go files
  25. // many of which are valid for both pre- and RFC8555.
  26. // This will make it easier to clean up the tests once non-RFC compliant
  27. // code is removed.
  28. func TestRFC_Discover(t *testing.T) {
  29. const (
  30. nonce = "https://example.com/acme/new-nonce"
  31. reg = "https://example.com/acme/new-acct"
  32. order = "https://example.com/acme/new-order"
  33. authz = "https://example.com/acme/new-authz"
  34. revoke = "https://example.com/acme/revoke-cert"
  35. keychange = "https://example.com/acme/key-change"
  36. metaTerms = "https://example.com/acme/terms/2017-5-30"
  37. metaWebsite = "https://www.example.com/"
  38. metaCAA = "example.com"
  39. )
  40. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  41. w.Header().Set("Content-Type", "application/json")
  42. fmt.Fprintf(w, `{
  43. "newNonce": %q,
  44. "newAccount": %q,
  45. "newOrder": %q,
  46. "newAuthz": %q,
  47. "revokeCert": %q,
  48. "keyChange": %q,
  49. "meta": {
  50. "termsOfService": %q,
  51. "website": %q,
  52. "caaIdentities": [%q],
  53. "externalAccountRequired": true
  54. }
  55. }`, nonce, reg, order, authz, revoke, keychange, metaTerms, metaWebsite, metaCAA)
  56. }))
  57. defer ts.Close()
  58. c := Client{DirectoryURL: ts.URL}
  59. dir, err := c.Discover(context.Background())
  60. if err != nil {
  61. t.Fatal(err)
  62. }
  63. if dir.NonceURL != nonce {
  64. t.Errorf("dir.NonceURL = %q; want %q", dir.NonceURL, nonce)
  65. }
  66. if dir.RegURL != reg {
  67. t.Errorf("dir.RegURL = %q; want %q", dir.RegURL, reg)
  68. }
  69. if dir.OrderURL != order {
  70. t.Errorf("dir.OrderURL = %q; want %q", dir.OrderURL, order)
  71. }
  72. if dir.AuthzURL != authz {
  73. t.Errorf("dir.AuthzURL = %q; want %q", dir.AuthzURL, authz)
  74. }
  75. if dir.RevokeURL != revoke {
  76. t.Errorf("dir.RevokeURL = %q; want %q", dir.RevokeURL, revoke)
  77. }
  78. if dir.KeyChangeURL != keychange {
  79. t.Errorf("dir.KeyChangeURL = %q; want %q", dir.KeyChangeURL, keychange)
  80. }
  81. if dir.Terms != metaTerms {
  82. t.Errorf("dir.Terms = %q; want %q", dir.Terms, metaTerms)
  83. }
  84. if dir.Website != metaWebsite {
  85. t.Errorf("dir.Website = %q; want %q", dir.Website, metaWebsite)
  86. }
  87. if len(dir.CAA) == 0 || dir.CAA[0] != metaCAA {
  88. t.Errorf("dir.CAA = %q; want [%q]", dir.CAA, metaCAA)
  89. }
  90. if !dir.ExternalAccountRequired {
  91. t.Error("dir.Meta.ExternalAccountRequired is false")
  92. }
  93. }
  94. func TestRFC_popNonce(t *testing.T) {
  95. var count int
  96. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  97. // The Client uses only Directory.NonceURL when specified.
  98. // Expect no other URL paths.
  99. if r.URL.Path != "/new-nonce" {
  100. t.Errorf("r.URL.Path = %q; want /new-nonce", r.URL.Path)
  101. }
  102. if count > 0 {
  103. w.WriteHeader(http.StatusTooManyRequests)
  104. return
  105. }
  106. count++
  107. w.Header().Set("Replay-Nonce", "second")
  108. }))
  109. cl := &Client{
  110. DirectoryURL: ts.URL,
  111. dir: &Directory{NonceURL: ts.URL + "/new-nonce"},
  112. }
  113. cl.addNonce(http.Header{"Replay-Nonce": {"first"}})
  114. for i, nonce := range []string{"first", "second"} {
  115. v, err := cl.popNonce(context.Background(), "")
  116. if err != nil {
  117. t.Errorf("%d: cl.popNonce: %v", i, err)
  118. }
  119. if v != nonce {
  120. t.Errorf("%d: cl.popNonce = %q; want %q", i, v, nonce)
  121. }
  122. }
  123. // No more nonces and server replies with an error past first nonce fetch.
  124. // Expected to fail.
  125. if _, err := cl.popNonce(context.Background(), ""); err == nil {
  126. t.Error("last cl.popNonce returned nil error")
  127. }
  128. }
  129. func TestRFC_postKID(t *testing.T) {
  130. var ts *httptest.Server
  131. ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  132. switch r.URL.Path {
  133. case "/new-nonce":
  134. w.Header().Set("Replay-Nonce", "nonce")
  135. case "/new-account":
  136. w.Header().Set("Location", "/account-1")
  137. w.Write([]byte(`{"status":"valid"}`))
  138. case "/post":
  139. b, _ := ioutil.ReadAll(r.Body) // check err later in decodeJWSxxx
  140. head, err := decodeJWSHead(bytes.NewReader(b))
  141. if err != nil {
  142. t.Errorf("decodeJWSHead: %v", err)
  143. return
  144. }
  145. if head.KID != "/account-1" {
  146. t.Errorf("head.KID = %q; want /account-1", head.KID)
  147. }
  148. if len(head.JWK) != 0 {
  149. t.Errorf("head.JWK = %q; want zero map", head.JWK)
  150. }
  151. if v := ts.URL + "/post"; head.URL != v {
  152. t.Errorf("head.URL = %q; want %q", head.URL, v)
  153. }
  154. var payload struct{ Msg string }
  155. decodeJWSRequest(t, &payload, bytes.NewReader(b))
  156. if payload.Msg != "ping" {
  157. t.Errorf("payload.Msg = %q; want ping", payload.Msg)
  158. }
  159. w.Write([]byte("pong"))
  160. default:
  161. t.Errorf("unhandled %s %s", r.Method, r.URL)
  162. w.WriteHeader(http.StatusBadRequest)
  163. }
  164. }))
  165. defer ts.Close()
  166. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  167. defer cancel()
  168. cl := &Client{
  169. Key: testKey,
  170. DirectoryURL: ts.URL,
  171. dir: &Directory{
  172. NonceURL: ts.URL + "/new-nonce",
  173. RegURL: ts.URL + "/new-account",
  174. OrderURL: "/force-rfc-mode",
  175. },
  176. }
  177. req := json.RawMessage(`{"msg":"ping"}`)
  178. res, err := cl.post(ctx, nil /* use kid */, ts.URL+"/post", req, wantStatus(http.StatusOK))
  179. if err != nil {
  180. t.Fatal(err)
  181. }
  182. defer res.Body.Close()
  183. b, _ := ioutil.ReadAll(res.Body) // don't care about err - just checking b
  184. if string(b) != "pong" {
  185. t.Errorf("res.Body = %q; want pong", b)
  186. }
  187. }
  188. // acmeServer simulates a subset of RFC8555 compliant CA.
  189. //
  190. // TODO: We also have x/crypto/acme/autocert/acmetest and startACMEServerStub in autocert_test.go.
  191. // It feels like this acmeServer is a sweet spot between usefulness and added complexity.
  192. // Also, acmetest and startACMEServerStub were both written for draft-02, no RFC support.
  193. // The goal is to consolidate all into one ACME test server.
  194. type acmeServer struct {
  195. ts *httptest.Server
  196. handler map[string]http.HandlerFunc // keyed by r.URL.Path
  197. mu sync.Mutex
  198. nnonce int
  199. }
  200. func newACMEServer() *acmeServer {
  201. return &acmeServer{handler: make(map[string]http.HandlerFunc)}
  202. }
  203. func (s *acmeServer) handle(path string, f func(http.ResponseWriter, *http.Request)) {
  204. s.handler[path] = http.HandlerFunc(f)
  205. }
  206. func (s *acmeServer) start() {
  207. s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  208. w.Header().Set("Content-Type", "application/json")
  209. // Directory request.
  210. if r.URL.Path == "/" {
  211. fmt.Fprintf(w, `{
  212. "newNonce": %q,
  213. "newAccount": %q,
  214. "newOrder": %q,
  215. "newAuthz": %q,
  216. "revokeCert": %q,
  217. "meta": {"termsOfService": %q}
  218. }`,
  219. s.url("/acme/new-nonce"),
  220. s.url("/acme/new-account"),
  221. s.url("/acme/new-order"),
  222. s.url("/acme/new-authz"),
  223. s.url("/acme/revoke-cert"),
  224. s.url("/terms"),
  225. )
  226. return
  227. }
  228. // All other responses contain a nonce value unconditionally.
  229. w.Header().Set("Replay-Nonce", s.nonce())
  230. if r.URL.Path == "/acme/new-nonce" {
  231. return
  232. }
  233. h := s.handler[r.URL.Path]
  234. if h == nil {
  235. w.WriteHeader(http.StatusBadRequest)
  236. fmt.Fprintf(w, "Unhandled %s", r.URL.Path)
  237. return
  238. }
  239. h.ServeHTTP(w, r)
  240. }))
  241. }
  242. func (s *acmeServer) close() {
  243. s.ts.Close()
  244. }
  245. func (s *acmeServer) url(path string) string {
  246. return s.ts.URL + path
  247. }
  248. func (s *acmeServer) nonce() string {
  249. s.mu.Lock()
  250. defer s.mu.Unlock()
  251. s.nnonce++
  252. return fmt.Sprintf("nonce%d", s.nnonce)
  253. }
  254. func (s *acmeServer) error(w http.ResponseWriter, e *wireError) {
  255. w.WriteHeader(e.Status)
  256. json.NewEncoder(w).Encode(e)
  257. }
  258. func TestRFC_Register(t *testing.T) {
  259. const email = "mailto:user@example.org"
  260. s := newACMEServer()
  261. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  262. w.Header().Set("Location", s.url("/accounts/1"))
  263. w.WriteHeader(http.StatusCreated) // 201 means new account created
  264. fmt.Fprintf(w, `{
  265. "status": "valid",
  266. "contact": [%q],
  267. "orders": %q
  268. }`, email, s.url("/accounts/1/orders"))
  269. b, _ := ioutil.ReadAll(r.Body) // check err later in decodeJWSxxx
  270. head, err := decodeJWSHead(bytes.NewReader(b))
  271. if err != nil {
  272. t.Errorf("decodeJWSHead: %v", err)
  273. return
  274. }
  275. if len(head.JWK) == 0 {
  276. t.Error("head.JWK is empty")
  277. }
  278. var req struct{ Contact []string }
  279. decodeJWSRequest(t, &req, bytes.NewReader(b))
  280. if len(req.Contact) != 1 || req.Contact[0] != email {
  281. t.Errorf("req.Contact = %q; want [%q]", req.Contact, email)
  282. }
  283. })
  284. s.start()
  285. defer s.close()
  286. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  287. defer cancel()
  288. cl := &Client{
  289. Key: testKeyEC,
  290. DirectoryURL: s.url("/"),
  291. }
  292. var didPrompt bool
  293. a := &Account{Contact: []string{email}}
  294. acct, err := cl.Register(ctx, a, func(tos string) bool {
  295. didPrompt = true
  296. terms := s.url("/terms")
  297. if tos != terms {
  298. t.Errorf("tos = %q; want %q", tos, terms)
  299. }
  300. return true
  301. })
  302. if err != nil {
  303. t.Fatal(err)
  304. }
  305. okAccount := &Account{
  306. URI: s.url("/accounts/1"),
  307. Status: StatusValid,
  308. Contact: []string{email},
  309. OrdersURL: s.url("/accounts/1/orders"),
  310. }
  311. if !reflect.DeepEqual(acct, okAccount) {
  312. t.Errorf("acct = %+v; want %+v", acct, okAccount)
  313. }
  314. if !didPrompt {
  315. t.Error("tos prompt wasn't called")
  316. }
  317. if v := cl.accountKID(ctx); v != keyID(okAccount.URI) {
  318. t.Errorf("account kid = %q; want %q", v, okAccount.URI)
  319. }
  320. }
  321. func TestRFC_RegisterExisting(t *testing.T) {
  322. s := newACMEServer()
  323. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  324. w.Header().Set("Location", s.url("/accounts/1"))
  325. w.WriteHeader(http.StatusOK) // 200 means account already exists
  326. w.Write([]byte(`{"status": "valid"}`))
  327. })
  328. s.start()
  329. defer s.close()
  330. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  331. _, err := cl.Register(context.Background(), &Account{}, AcceptTOS)
  332. if err != ErrAccountAlreadyExists {
  333. t.Errorf("err = %v; want %v", err, ErrAccountAlreadyExists)
  334. }
  335. kid := keyID(s.url("/accounts/1"))
  336. if v := cl.accountKID(context.Background()); v != kid {
  337. t.Errorf("account kid = %q; want %q", v, kid)
  338. }
  339. }
  340. func TestRFC_UpdateReg(t *testing.T) {
  341. const email = "mailto:user@example.org"
  342. s := newACMEServer()
  343. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  344. w.Header().Set("Location", s.url("/accounts/1"))
  345. w.WriteHeader(http.StatusOK)
  346. w.Write([]byte(`{"status": "valid"}`))
  347. })
  348. var didUpdate bool
  349. s.handle("/accounts/1", func(w http.ResponseWriter, r *http.Request) {
  350. didUpdate = true
  351. w.Header().Set("Location", s.url("/accounts/1"))
  352. w.WriteHeader(http.StatusOK)
  353. w.Write([]byte(`{"status": "valid"}`))
  354. b, _ := ioutil.ReadAll(r.Body) // check err later in decodeJWSxxx
  355. head, err := decodeJWSHead(bytes.NewReader(b))
  356. if err != nil {
  357. t.Errorf("decodeJWSHead: %v", err)
  358. return
  359. }
  360. if len(head.JWK) != 0 {
  361. t.Error("head.JWK is non-zero")
  362. }
  363. kid := s.url("/accounts/1")
  364. if head.KID != kid {
  365. t.Errorf("head.KID = %q; want %q", head.KID, kid)
  366. }
  367. var req struct{ Contact []string }
  368. decodeJWSRequest(t, &req, bytes.NewReader(b))
  369. if len(req.Contact) != 1 || req.Contact[0] != email {
  370. t.Errorf("req.Contact = %q; want [%q]", req.Contact, email)
  371. }
  372. })
  373. s.start()
  374. defer s.close()
  375. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  376. _, err := cl.UpdateReg(context.Background(), &Account{Contact: []string{email}})
  377. if err != nil {
  378. t.Error(err)
  379. }
  380. if !didUpdate {
  381. t.Error("UpdateReg didn't update the account")
  382. }
  383. }
  384. func TestRFC_GetReg(t *testing.T) {
  385. s := newACMEServer()
  386. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  387. w.Header().Set("Location", s.url("/accounts/1"))
  388. w.WriteHeader(http.StatusOK)
  389. w.Write([]byte(`{"status": "valid"}`))
  390. head, err := decodeJWSHead(r.Body)
  391. if err != nil {
  392. t.Errorf("decodeJWSHead: %v", err)
  393. return
  394. }
  395. if len(head.JWK) == 0 {
  396. t.Error("head.JWK is empty")
  397. }
  398. })
  399. s.start()
  400. defer s.close()
  401. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  402. acct, err := cl.GetReg(context.Background(), "")
  403. if err != nil {
  404. t.Fatal(err)
  405. }
  406. okAccount := &Account{
  407. URI: s.url("/accounts/1"),
  408. Status: StatusValid,
  409. }
  410. if !reflect.DeepEqual(acct, okAccount) {
  411. t.Errorf("acct = %+v; want %+v", acct, okAccount)
  412. }
  413. }
  414. func TestRFC_GetRegNoAccount(t *testing.T) {
  415. s := newACMEServer()
  416. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  417. s.error(w, &wireError{
  418. Status: http.StatusBadRequest,
  419. Type: "urn:ietf:params:acme:error:accountDoesNotExist",
  420. })
  421. })
  422. s.start()
  423. defer s.close()
  424. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  425. if _, err := cl.GetReg(context.Background(), ""); err != ErrNoAccount {
  426. t.Errorf("err = %v; want %v", err, ErrNoAccount)
  427. }
  428. }
  429. func TestRFC_GetRegOtherError(t *testing.T) {
  430. s := newACMEServer()
  431. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  432. w.WriteHeader(http.StatusBadRequest)
  433. })
  434. s.start()
  435. defer s.close()
  436. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  437. if _, err := cl.GetReg(context.Background(), ""); err == nil || err == ErrNoAccount {
  438. t.Errorf("GetReg: %v; want any other non-nil err", err)
  439. }
  440. }
  441. func TestRFC_AuthorizeOrder(t *testing.T) {
  442. s := newACMEServer()
  443. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  444. w.Header().Set("Location", s.url("/accounts/1"))
  445. w.WriteHeader(http.StatusOK)
  446. w.Write([]byte(`{"status": "valid"}`))
  447. })
  448. s.handle("/acme/new-order", func(w http.ResponseWriter, r *http.Request) {
  449. w.Header().Set("Location", s.url("/orders/1"))
  450. w.WriteHeader(http.StatusCreated)
  451. fmt.Fprintf(w, `{
  452. "status": "pending",
  453. "expires": "2019-09-01T00:00:00Z",
  454. "notBefore": "2019-08-31T00:00:00Z",
  455. "notAfter": "2019-09-02T00:00:00Z",
  456. "identifiers": [{"type":"dns", "value":"example.org"}],
  457. "authorizations": [%q]
  458. }`, s.url("/authz/1"))
  459. })
  460. s.start()
  461. defer s.close()
  462. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  463. o, err := cl.AuthorizeOrder(context.Background(), DomainIDs("example.org"),
  464. WithOrderNotBefore(time.Date(2019, 8, 31, 0, 0, 0, 0, time.UTC)),
  465. WithOrderNotAfter(time.Date(2019, 9, 2, 0, 0, 0, 0, time.UTC)),
  466. )
  467. if err != nil {
  468. t.Fatal(err)
  469. }
  470. okOrder := &Order{
  471. URI: s.url("/orders/1"),
  472. Status: StatusPending,
  473. Expires: time.Date(2019, 9, 1, 0, 0, 0, 0, time.UTC),
  474. NotBefore: time.Date(2019, 8, 31, 0, 0, 0, 0, time.UTC),
  475. NotAfter: time.Date(2019, 9, 2, 0, 0, 0, 0, time.UTC),
  476. Identifiers: []AuthzID{AuthzID{Type: "dns", Value: "example.org"}},
  477. AuthzURLs: []string{s.url("/authz/1")},
  478. }
  479. if !reflect.DeepEqual(o, okOrder) {
  480. t.Errorf("AuthorizeOrder = %+v; want %+v", o, okOrder)
  481. }
  482. }
  483. func TestRFC_GetOrder(t *testing.T) {
  484. s := newACMEServer()
  485. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  486. w.Header().Set("Location", s.url("/accounts/1"))
  487. w.WriteHeader(http.StatusOK)
  488. w.Write([]byte(`{"status": "valid"}`))
  489. })
  490. s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
  491. w.Header().Set("Location", s.url("/orders/1"))
  492. w.WriteHeader(http.StatusOK)
  493. w.Write([]byte(`{
  494. "status": "invalid",
  495. "expires": "2019-09-01T00:00:00Z",
  496. "notBefore": "2019-08-31T00:00:00Z",
  497. "notAfter": "2019-09-02T00:00:00Z",
  498. "identifiers": [{"type":"dns", "value":"example.org"}],
  499. "authorizations": ["/authz/1"],
  500. "finalize": "/orders/1/fin",
  501. "certificate": "/orders/1/cert",
  502. "error": {"type": "badRequest"}
  503. }`))
  504. })
  505. s.start()
  506. defer s.close()
  507. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  508. o, err := cl.GetOrder(context.Background(), s.url("/orders/1"))
  509. if err != nil {
  510. t.Fatal(err)
  511. }
  512. okOrder := &Order{
  513. URI: s.url("/orders/1"),
  514. Status: StatusInvalid,
  515. Expires: time.Date(2019, 9, 1, 0, 0, 0, 0, time.UTC),
  516. NotBefore: time.Date(2019, 8, 31, 0, 0, 0, 0, time.UTC),
  517. NotAfter: time.Date(2019, 9, 2, 0, 0, 0, 0, time.UTC),
  518. Identifiers: []AuthzID{AuthzID{Type: "dns", Value: "example.org"}},
  519. AuthzURLs: []string{"/authz/1"},
  520. FinalizeURL: "/orders/1/fin",
  521. CertURL: "/orders/1/cert",
  522. Error: &Error{ProblemType: "badRequest"},
  523. }
  524. if !reflect.DeepEqual(o, okOrder) {
  525. t.Errorf("GetOrder = %+v\nwant %+v", o, okOrder)
  526. }
  527. }
  528. func TestRFC_WaitOrder(t *testing.T) {
  529. for _, st := range []string{StatusReady, StatusValid} {
  530. t.Run(st, func(t *testing.T) {
  531. testWaitOrderStatus(t, st)
  532. })
  533. }
  534. }
  535. func testWaitOrderStatus(t *testing.T, okStatus string) {
  536. s := newACMEServer()
  537. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  538. w.Header().Set("Location", s.url("/accounts/1"))
  539. w.WriteHeader(http.StatusOK)
  540. w.Write([]byte(`{"status": "valid"}`))
  541. })
  542. var count int
  543. s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
  544. w.Header().Set("Location", s.url("/orders/1"))
  545. w.WriteHeader(http.StatusOK)
  546. s := StatusPending
  547. if count > 0 {
  548. s = okStatus
  549. }
  550. fmt.Fprintf(w, `{"status": %q}`, s)
  551. count++
  552. })
  553. s.start()
  554. defer s.close()
  555. var order *Order
  556. var err error
  557. done := make(chan struct{})
  558. go func() {
  559. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  560. order, err = cl.WaitOrder(context.Background(), s.url("/orders/1"))
  561. close(done)
  562. }()
  563. select {
  564. case <-time.After(3 * time.Second):
  565. t.Fatal("WaitOrder took too long to return")
  566. case <-done:
  567. if err != nil {
  568. t.Fatalf("WaitOrder: %v", err)
  569. }
  570. if order.Status != okStatus {
  571. t.Errorf("order.Status = %q; want %q", order.Status, okStatus)
  572. }
  573. }
  574. }
  575. func TestRFC_WaitOrderError(t *testing.T) {
  576. s := newACMEServer()
  577. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  578. w.Header().Set("Location", s.url("/accounts/1"))
  579. w.WriteHeader(http.StatusOK)
  580. w.Write([]byte(`{"status": "valid"}`))
  581. })
  582. var count int
  583. s.handle("/orders/1", func(w http.ResponseWriter, r *http.Request) {
  584. w.Header().Set("Location", s.url("/orders/1"))
  585. w.WriteHeader(http.StatusOK)
  586. s := StatusPending
  587. if count > 0 {
  588. s = StatusInvalid
  589. }
  590. fmt.Fprintf(w, `{"status": %q}`, s)
  591. count++
  592. })
  593. s.start()
  594. defer s.close()
  595. var err error
  596. done := make(chan struct{})
  597. go func() {
  598. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  599. _, err = cl.WaitOrder(context.Background(), s.url("/orders/1"))
  600. close(done)
  601. }()
  602. select {
  603. case <-time.After(3 * time.Second):
  604. t.Fatal("WaitOrder took too long to return")
  605. case <-done:
  606. if err == nil {
  607. t.Fatal("WaitOrder returned nil error")
  608. }
  609. e, ok := err.(*OrderError)
  610. if !ok {
  611. t.Fatalf("err = %v (%T); want OrderError", err, err)
  612. }
  613. if e.OrderURL != s.url("/orders/1") {
  614. t.Errorf("e.OrderURL = %q; want %q", e.OrderURL, s.url("/orders/1"))
  615. }
  616. if e.Status != StatusInvalid {
  617. t.Errorf("e.Status = %q; want %q", e.Status, StatusInvalid)
  618. }
  619. }
  620. }
  621. func TestRFC_CreateOrderCert(t *testing.T) {
  622. q := &x509.CertificateRequest{
  623. Subject: pkix.Name{CommonName: "example.org"},
  624. }
  625. csr, err := x509.CreateCertificateRequest(rand.Reader, q, testKeyEC)
  626. if err != nil {
  627. t.Fatal(err)
  628. }
  629. tmpl := &x509.Certificate{SerialNumber: big.NewInt(1)}
  630. leaf, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &testKeyEC.PublicKey, testKeyEC)
  631. if err != nil {
  632. t.Fatal(err)
  633. }
  634. s := newACMEServer()
  635. s.handle("/acme/new-account", func(w http.ResponseWriter, r *http.Request) {
  636. w.Header().Set("Location", s.url("/accounts/1"))
  637. w.Write([]byte(`{"status": "valid"}`))
  638. })
  639. var count int
  640. s.handle("/pleaseissue", func(w http.ResponseWriter, r *http.Request) {
  641. w.Header().Set("Location", s.url("/pleaseissue"))
  642. st := StatusProcessing
  643. if count > 0 {
  644. st = StatusValid
  645. }
  646. fmt.Fprintf(w, `{"status":%q, "certificate":%q}`, st, s.url("/crt"))
  647. count++
  648. })
  649. s.handle("/crt", func(w http.ResponseWriter, r *http.Request) {
  650. w.Header().Set("Content-Type", "application/pem-certificate-chain")
  651. pem.Encode(w, &pem.Block{Type: "CERTIFICATE", Bytes: leaf})
  652. })
  653. s.start()
  654. defer s.close()
  655. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
  656. defer cancel()
  657. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  658. cert, curl, err := cl.CreateOrderCert(ctx, s.url("/pleaseissue"), csr, true)
  659. if err != nil {
  660. t.Fatalf("CreateOrderCert: %v", err)
  661. }
  662. if _, err := x509.ParseCertificate(cert[0]); err != nil {
  663. t.Errorf("ParseCertificate: %v", err)
  664. }
  665. if !reflect.DeepEqual(cert[0], leaf) {
  666. t.Errorf("cert and leaf bytes don't match")
  667. }
  668. if u := s.url("/crt"); curl != u {
  669. t.Errorf("curl = %q; want %q", curl, u)
  670. }
  671. }
  672. func TestRFC_AlreadyRevokedCert(t *testing.T) {
  673. s := newACMEServer()
  674. s.handle("/acme/revoke-cert", func(w http.ResponseWriter, r *http.Request) {
  675. s.error(w, &wireError{
  676. Status: http.StatusBadRequest,
  677. Type: "urn:ietf:params:acme:error:alreadyRevoked",
  678. })
  679. })
  680. s.start()
  681. defer s.close()
  682. cl := &Client{Key: testKeyEC, DirectoryURL: s.url("/")}
  683. err := cl.RevokeCert(context.Background(), testKeyEC, []byte{0}, CRLReasonUnspecified)
  684. if err != nil {
  685. t.Fatalf("RevokeCert: %v", err)
  686. }
  687. }