acme_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "reflect"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/go-chi/chi/v5"
  14. "google.golang.org/protobuf/encoding/protojson"
  15. "google.golang.org/protobuf/proto"
  16. "google.golang.org/protobuf/types/known/timestamppb"
  17. "github.com/smallstep/linkedca"
  18. "github.com/smallstep/assert"
  19. "github.com/smallstep/certificates/acme"
  20. "github.com/smallstep/certificates/authority/admin"
  21. )
  22. func readProtoJSON(r io.ReadCloser, m proto.Message) error {
  23. defer r.Close()
  24. data, err := io.ReadAll(r)
  25. if err != nil {
  26. return err
  27. }
  28. return protojson.Unmarshal(data, m)
  29. }
  30. func mockMustAuthority(t *testing.T, a adminAuthority) {
  31. t.Helper()
  32. fn := mustAuthority
  33. t.Cleanup(func() {
  34. mustAuthority = fn
  35. })
  36. mustAuthority = func(ctx context.Context) adminAuthority {
  37. return a
  38. }
  39. }
  40. func TestHandler_requireEABEnabled(t *testing.T) {
  41. type test struct {
  42. ctx context.Context
  43. next http.HandlerFunc
  44. err *admin.Error
  45. statusCode int
  46. }
  47. var tests = map[string]func(t *testing.T) test{
  48. "fail/prov.GetDetails": func(t *testing.T) test {
  49. prov := &linkedca.Provisioner{
  50. Id: "provID",
  51. Name: "provName",
  52. }
  53. ctx := linkedca.NewContextWithProvisioner(context.Background(), prov)
  54. err := admin.NewErrorISE("error getting ACME details for provisioner 'provName'")
  55. err.Message = "error getting ACME details for provisioner 'provName'"
  56. return test{
  57. ctx: ctx,
  58. err: err,
  59. statusCode: 500,
  60. }
  61. },
  62. "fail/prov.GetDetails.GetACME": func(t *testing.T) test {
  63. prov := &linkedca.Provisioner{
  64. Id: "provID",
  65. Name: "provName",
  66. Details: &linkedca.ProvisionerDetails{},
  67. }
  68. ctx := linkedca.NewContextWithProvisioner(context.Background(), prov)
  69. err := admin.NewErrorISE("error getting ACME details for provisioner 'provName'")
  70. err.Message = "error getting ACME details for provisioner 'provName'"
  71. return test{
  72. ctx: ctx,
  73. err: err,
  74. statusCode: 500,
  75. }
  76. },
  77. "ok/eab-disabled": func(t *testing.T) test {
  78. prov := &linkedca.Provisioner{
  79. Id: "provID",
  80. Name: "provName",
  81. Details: &linkedca.ProvisionerDetails{
  82. Data: &linkedca.ProvisionerDetails_ACME{
  83. ACME: &linkedca.ACMEProvisioner{
  84. RequireEab: false,
  85. },
  86. },
  87. },
  88. }
  89. ctx := linkedca.NewContextWithProvisioner(context.Background(), prov)
  90. err := admin.NewError(admin.ErrorBadRequestType, "ACME EAB not enabled for provisioner provName")
  91. err.Message = "ACME EAB not enabled for provisioner 'provName'"
  92. return test{
  93. ctx: ctx,
  94. err: err,
  95. statusCode: 400,
  96. }
  97. },
  98. "ok/eab-enabled": func(t *testing.T) test {
  99. prov := &linkedca.Provisioner{
  100. Id: "provID",
  101. Name: "provName",
  102. Details: &linkedca.ProvisionerDetails{
  103. Data: &linkedca.ProvisionerDetails_ACME{
  104. ACME: &linkedca.ACMEProvisioner{
  105. RequireEab: true,
  106. },
  107. },
  108. },
  109. }
  110. ctx := linkedca.NewContextWithProvisioner(context.Background(), prov)
  111. return test{
  112. ctx: ctx,
  113. next: func(w http.ResponseWriter, r *http.Request) {
  114. w.Write(nil) // mock response with status 200
  115. },
  116. statusCode: 200,
  117. }
  118. },
  119. }
  120. for name, prep := range tests {
  121. tc := prep(t)
  122. t.Run(name, func(t *testing.T) {
  123. req := httptest.NewRequest("GET", "/foo", http.NoBody).WithContext(tc.ctx)
  124. w := httptest.NewRecorder()
  125. requireEABEnabled(tc.next)(w, req)
  126. res := w.Result()
  127. assert.Equals(t, tc.statusCode, res.StatusCode)
  128. body, err := io.ReadAll(res.Body)
  129. res.Body.Close()
  130. assert.FatalError(t, err)
  131. if res.StatusCode >= 400 {
  132. err := admin.Error{}
  133. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &err))
  134. assert.Equals(t, tc.err.Type, err.Type)
  135. assert.Equals(t, tc.err.Message, err.Message)
  136. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  137. assert.Equals(t, tc.err.Detail, err.Detail)
  138. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  139. return
  140. }
  141. })
  142. }
  143. }
  144. func TestCreateExternalAccountKeyRequest_Validate(t *testing.T) {
  145. type fields struct {
  146. Reference string
  147. }
  148. tests := []struct {
  149. name string
  150. fields fields
  151. wantErr bool
  152. }{
  153. {
  154. name: "fail/reference-too-long",
  155. fields: fields{
  156. Reference: strings.Repeat("A", 257),
  157. },
  158. wantErr: true,
  159. },
  160. {
  161. name: "ok/empty-reference",
  162. fields: fields{
  163. Reference: "",
  164. },
  165. wantErr: false,
  166. },
  167. {
  168. name: "ok",
  169. fields: fields{
  170. Reference: "my-eab-reference",
  171. },
  172. wantErr: false,
  173. },
  174. }
  175. for _, tt := range tests {
  176. t.Run(tt.name, func(t *testing.T) {
  177. r := &CreateExternalAccountKeyRequest{
  178. Reference: tt.fields.Reference,
  179. }
  180. if err := r.Validate(); (err != nil) != tt.wantErr {
  181. t.Errorf("CreateExternalAccountKeyRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
  182. }
  183. })
  184. }
  185. }
  186. func TestHandler_CreateExternalAccountKey(t *testing.T) {
  187. type test struct {
  188. ctx context.Context
  189. statusCode int
  190. err *admin.Error
  191. }
  192. var tests = map[string]func(t *testing.T) test{
  193. "ok": func(t *testing.T) test {
  194. chiCtx := chi.NewRouteContext()
  195. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  196. return test{
  197. ctx: ctx,
  198. statusCode: 501,
  199. err: &admin.Error{
  200. Type: admin.ErrorNotImplementedType.String(),
  201. Status: http.StatusNotImplemented,
  202. Message: "this functionality is currently only available in Certificate Manager: https://u.step.sm/cm",
  203. Detail: "not implemented",
  204. },
  205. }
  206. },
  207. }
  208. for name, prep := range tests {
  209. tc := prep(t)
  210. t.Run(name, func(t *testing.T) {
  211. req := httptest.NewRequest("POST", "/foo", http.NoBody) // chi routing is prepared in test setup
  212. req = req.WithContext(tc.ctx)
  213. w := httptest.NewRecorder()
  214. acmeResponder := NewACMEAdminResponder()
  215. acmeResponder.CreateExternalAccountKey(w, req)
  216. res := w.Result()
  217. assert.Equals(t, tc.statusCode, res.StatusCode)
  218. body, err := io.ReadAll(res.Body)
  219. res.Body.Close()
  220. assert.FatalError(t, err)
  221. adminErr := admin.Error{}
  222. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  223. assert.Equals(t, tc.err.Type, adminErr.Type)
  224. assert.Equals(t, tc.err.Message, adminErr.Message)
  225. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  226. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  227. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  228. })
  229. }
  230. }
  231. func TestHandler_DeleteExternalAccountKey(t *testing.T) {
  232. type test struct {
  233. ctx context.Context
  234. statusCode int
  235. err *admin.Error
  236. }
  237. var tests = map[string]func(t *testing.T) test{
  238. "ok": func(t *testing.T) test {
  239. chiCtx := chi.NewRouteContext()
  240. chiCtx.URLParams.Add("provisionerName", "provName")
  241. chiCtx.URLParams.Add("id", "keyID")
  242. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  243. return test{
  244. ctx: ctx,
  245. statusCode: 501,
  246. err: &admin.Error{
  247. Type: admin.ErrorNotImplementedType.String(),
  248. Status: http.StatusNotImplemented,
  249. Message: "this functionality is currently only available in Certificate Manager: https://u.step.sm/cm",
  250. Detail: "not implemented",
  251. },
  252. }
  253. },
  254. }
  255. for name, prep := range tests {
  256. tc := prep(t)
  257. t.Run(name, func(t *testing.T) {
  258. req := httptest.NewRequest("DELETE", "/foo", http.NoBody) // chi routing is prepared in test setup
  259. req = req.WithContext(tc.ctx)
  260. w := httptest.NewRecorder()
  261. acmeResponder := NewACMEAdminResponder()
  262. acmeResponder.DeleteExternalAccountKey(w, req)
  263. res := w.Result()
  264. assert.Equals(t, tc.statusCode, res.StatusCode)
  265. body, err := io.ReadAll(res.Body)
  266. res.Body.Close()
  267. assert.FatalError(t, err)
  268. adminErr := admin.Error{}
  269. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  270. assert.Equals(t, tc.err.Type, adminErr.Type)
  271. assert.Equals(t, tc.err.Message, adminErr.Message)
  272. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  273. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  274. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  275. })
  276. }
  277. }
  278. func TestHandler_GetExternalAccountKeys(t *testing.T) {
  279. type test struct {
  280. ctx context.Context
  281. statusCode int
  282. req *http.Request
  283. err *admin.Error
  284. }
  285. var tests = map[string]func(t *testing.T) test{
  286. "ok": func(t *testing.T) test {
  287. chiCtx := chi.NewRouteContext()
  288. chiCtx.URLParams.Add("provisionerName", "provName")
  289. req := httptest.NewRequest("GET", "/foo", http.NoBody)
  290. ctx := context.WithValue(context.Background(), chi.RouteCtxKey, chiCtx)
  291. return test{
  292. ctx: ctx,
  293. statusCode: 501,
  294. req: req,
  295. err: &admin.Error{
  296. Type: admin.ErrorNotImplementedType.String(),
  297. Status: http.StatusNotImplemented,
  298. Message: "this functionality is currently only available in Certificate Manager: https://u.step.sm/cm",
  299. Detail: "not implemented",
  300. },
  301. }
  302. },
  303. }
  304. for name, prep := range tests {
  305. tc := prep(t)
  306. t.Run(name, func(t *testing.T) {
  307. req := tc.req.WithContext(tc.ctx)
  308. w := httptest.NewRecorder()
  309. acmeResponder := NewACMEAdminResponder()
  310. acmeResponder.GetExternalAccountKeys(w, req)
  311. res := w.Result()
  312. assert.Equals(t, tc.statusCode, res.StatusCode)
  313. body, err := io.ReadAll(res.Body)
  314. res.Body.Close()
  315. assert.FatalError(t, err)
  316. adminErr := admin.Error{}
  317. assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &adminErr))
  318. assert.Equals(t, tc.err.Type, adminErr.Type)
  319. assert.Equals(t, tc.err.Message, adminErr.Message)
  320. assert.Equals(t, tc.err.StatusCode(), res.StatusCode)
  321. assert.Equals(t, tc.err.Detail, adminErr.Detail)
  322. assert.Equals(t, []string{"application/json"}, res.Header["Content-Type"])
  323. })
  324. }
  325. }
  326. func Test_eakToLinked(t *testing.T) {
  327. tests := []struct {
  328. name string
  329. k *acme.ExternalAccountKey
  330. want *linkedca.EABKey
  331. }{
  332. {
  333. name: "no-key",
  334. k: nil,
  335. want: nil,
  336. },
  337. {
  338. name: "no-policy",
  339. k: &acme.ExternalAccountKey{
  340. ID: "keyID",
  341. ProvisionerID: "provID",
  342. Reference: "ref",
  343. AccountID: "accID",
  344. HmacKey: []byte{1, 3, 3, 7},
  345. CreatedAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour),
  346. BoundAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC),
  347. Policy: nil,
  348. },
  349. want: &linkedca.EABKey{
  350. Id: "keyID",
  351. Provisioner: "provID",
  352. HmacKey: []byte{1, 3, 3, 7},
  353. Reference: "ref",
  354. Account: "accID",
  355. CreatedAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour)),
  356. BoundAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC)),
  357. Policy: nil,
  358. },
  359. },
  360. {
  361. name: "with-policy",
  362. k: &acme.ExternalAccountKey{
  363. ID: "keyID",
  364. ProvisionerID: "provID",
  365. Reference: "ref",
  366. AccountID: "accID",
  367. HmacKey: []byte{1, 3, 3, 7},
  368. CreatedAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour),
  369. BoundAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC),
  370. Policy: &acme.Policy{
  371. X509: acme.X509Policy{
  372. Allowed: acme.PolicyNames{
  373. DNSNames: []string{"*.local"},
  374. IPRanges: []string{"10.0.0.0/24"},
  375. },
  376. Denied: acme.PolicyNames{
  377. DNSNames: []string{"badhost.local"},
  378. IPRanges: []string{"10.0.0.30"},
  379. },
  380. },
  381. },
  382. },
  383. want: &linkedca.EABKey{
  384. Id: "keyID",
  385. Provisioner: "provID",
  386. HmacKey: []byte{1, 3, 3, 7},
  387. Reference: "ref",
  388. Account: "accID",
  389. CreatedAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour)),
  390. BoundAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC)),
  391. Policy: &linkedca.Policy{
  392. X509: &linkedca.X509Policy{
  393. Allow: &linkedca.X509Names{
  394. Dns: []string{"*.local"},
  395. Ips: []string{"10.0.0.0/24"},
  396. },
  397. Deny: &linkedca.X509Names{
  398. Dns: []string{"badhost.local"},
  399. Ips: []string{"10.0.0.30"},
  400. },
  401. },
  402. },
  403. },
  404. },
  405. }
  406. for _, tt := range tests {
  407. t.Run(tt.name, func(t *testing.T) {
  408. if got := eakToLinked(tt.k); !reflect.DeepEqual(got, tt.want) {
  409. t.Errorf("eakToLinked() = %v, want %v", got, tt.want)
  410. }
  411. })
  412. }
  413. }
  414. func Test_linkedEAKToCertificates(t *testing.T) {
  415. tests := []struct {
  416. name string
  417. k *linkedca.EABKey
  418. want *acme.ExternalAccountKey
  419. }{
  420. {
  421. name: "no-key",
  422. k: nil,
  423. want: nil,
  424. },
  425. {
  426. name: "no-policy",
  427. k: &linkedca.EABKey{
  428. Id: "keyID",
  429. Provisioner: "provID",
  430. HmacKey: []byte{1, 3, 3, 7},
  431. Reference: "ref",
  432. Account: "accID",
  433. CreatedAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour)),
  434. BoundAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC)),
  435. Policy: nil,
  436. },
  437. want: &acme.ExternalAccountKey{
  438. ID: "keyID",
  439. ProvisionerID: "provID",
  440. Reference: "ref",
  441. AccountID: "accID",
  442. HmacKey: []byte{1, 3, 3, 7},
  443. CreatedAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour),
  444. BoundAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC),
  445. Policy: nil,
  446. },
  447. },
  448. {
  449. name: "no-x509-policy",
  450. k: &linkedca.EABKey{
  451. Id: "keyID",
  452. Provisioner: "provID",
  453. HmacKey: []byte{1, 3, 3, 7},
  454. Reference: "ref",
  455. Account: "accID",
  456. CreatedAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour)),
  457. BoundAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC)),
  458. Policy: &linkedca.Policy{},
  459. },
  460. want: &acme.ExternalAccountKey{
  461. ID: "keyID",
  462. ProvisionerID: "provID",
  463. Reference: "ref",
  464. AccountID: "accID",
  465. HmacKey: []byte{1, 3, 3, 7},
  466. CreatedAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour),
  467. BoundAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC),
  468. Policy: &acme.Policy{},
  469. },
  470. },
  471. {
  472. name: "with-x509-policy",
  473. k: &linkedca.EABKey{
  474. Id: "keyID",
  475. Provisioner: "provID",
  476. HmacKey: []byte{1, 3, 3, 7},
  477. Reference: "ref",
  478. Account: "accID",
  479. CreatedAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour)),
  480. BoundAt: timestamppb.New(time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC)),
  481. Policy: &linkedca.Policy{
  482. X509: &linkedca.X509Policy{
  483. Allow: &linkedca.X509Names{
  484. Dns: []string{"*.local"},
  485. Ips: []string{"10.0.0.0/24"},
  486. },
  487. Deny: &linkedca.X509Names{
  488. Dns: []string{"badhost.local"},
  489. Ips: []string{"10.0.0.30"},
  490. },
  491. AllowWildcardNames: true,
  492. },
  493. },
  494. },
  495. want: &acme.ExternalAccountKey{
  496. ID: "keyID",
  497. ProvisionerID: "provID",
  498. Reference: "ref",
  499. AccountID: "accID",
  500. HmacKey: []byte{1, 3, 3, 7},
  501. CreatedAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC).Add(-1 * time.Hour),
  502. BoundAt: time.Date(2022, 04, 12, 9, 30, 30, 0, time.UTC),
  503. Policy: &acme.Policy{
  504. X509: acme.X509Policy{
  505. Allowed: acme.PolicyNames{
  506. DNSNames: []string{"*.local"},
  507. IPRanges: []string{"10.0.0.0/24"},
  508. },
  509. Denied: acme.PolicyNames{
  510. DNSNames: []string{"badhost.local"},
  511. IPRanges: []string{"10.0.0.30"},
  512. },
  513. AllowWildcardNames: true,
  514. },
  515. },
  516. },
  517. },
  518. }
  519. for _, tt := range tests {
  520. t.Run(tt.name, func(t *testing.T) {
  521. if got := linkedEAKToCertificates(tt.k); !reflect.DeepEqual(got, tt.want) {
  522. t.Errorf("linkedEAKToCertificates() = %v, want %v", got, tt.want)
  523. }
  524. })
  525. }
  526. }