4
0
Эх сурвалжийг харах

Merge branch 'master' into certificate-transparency

Mariano Cano 7 жил өмнө
parent
commit
afb3c7cd08
100 өөрчлөгдсөн 24758 нэмэгдсэн , 1800 устгасан
  1. 1 0
      .VERSION
  2. 1 0
      .gitattributes
  3. 0 28
      .github/ISSUE_TEMPLATE/autocert_bug.md
  4. 0 11
      .github/ISSUE_TEMPLATE/autocert_enhancement.md
  5. 11 0
      .github/ISSUE_TEMPLATE/enhancement.md
  6. 5 0
      .gitignore
  7. 70 0
      .golangci.yml
  8. 1 1
      .travis.yml
  9. 7 0
      .version.sh
  10. 112 273
      Gopkg.lock
  11. 11 16
      Gopkg.toml
  12. 51 62
      Makefile
  13. 250 436
      README.md
  14. 214 0
      acme/account.go
  15. 844 0
      acme/account_test.go
  16. 213 0
      acme/api/account.go
  17. 790 0
      acme/api/account_test.go
  18. 214 0
      acme/api/handler.go
  19. 771 0
      acme/api/handler_test.go
  20. 377 0
      acme/api/middleware.go
  21. 1550 0
      acme/api/middleware_test.go
  22. 164 0
      acme/api/order.go
  23. 757 0
      acme/api/order_test.go
  24. 263 0
      acme/authority.go
  25. 1474 0
      acme/authority_test.go
  26. 337 0
      acme/authz.go
  27. 809 0
      acme/authz_test.go
  28. 89 0
      acme/certificate.go
  29. 253 0
      acme/certificate_test.go
  30. 445 0
      acme/challenge.go
  31. 1093 0
      acme/challenge_test.go
  32. 76 0
      acme/common.go
  33. 120 0
      acme/directory.go
  34. 60 0
      acme/directory_test.go
  35. 439 0
      acme/errors.go
  36. 73 0
      acme/nonce.go
  37. 163 0
      acme/nonce_test.go
  38. 342 0
      acme/order.go
  39. 1129 0
      acme/order_test.go
  40. 113 23
      api/api.go
  41. 279 46
      api/api_test.go
  42. 13 1
      api/errors.go
  43. 103 0
      api/revoke.go
  44. 233 0
      api/revoke_test.go
  45. 159 0
      api/ssh.go
  46. 320 0
      api/ssh_test.go
  47. 33 0
      api/utils.go
  48. 91 45
      authority/authority.go
  49. 48 18
      authority/authority_test.go
  50. 136 147
      authority/authorize.go
  51. 479 131
      authority/authorize_test.go
  52. 0 115
      authority/claims.go
  53. 0 132
      authority/claims_test.go
  54. 62 15
      authority/config.go
  55. 22 10
      authority/config_test.go
  56. 66 0
      authority/db_test.go
  57. 26 2
      authority/error.go
  58. 0 144
      authority/provisioner.go
  59. 85 0
      authority/provisioner/acme.go
  60. 184 0
      authority/provisioner/acme_test.go
  61. 478 0
      authority/provisioner/aws.go
  62. 510 0
      authority/provisioner/aws_test.go
  63. 342 0
      authority/provisioner/azure.go
  64. 472 0
      authority/provisioner/azure_test.go
  65. 192 0
      authority/provisioner/claims.go
  66. 261 0
      authority/provisioner/collection.go
  67. 399 0
      authority/provisioner/collection_test.go
  68. 63 0
      authority/provisioner/duration.go
  69. 111 0
      authority/provisioner/duration_test.go
  70. 390 0
      authority/provisioner/gcp.go
  71. 500 0
      authority/provisioner/gcp_test.go
  72. 218 0
      authority/provisioner/jwk.go
  73. 540 0
      authority/provisioner/jwk_test.go
  74. 147 0
      authority/provisioner/keystore.go
  75. 192 0
      authority/provisioner/keystore_test.go
  76. 34 0
      authority/provisioner/method.go
  77. 44 0
      authority/provisioner/noop.go
  78. 29 0
      authority/provisioner/noop_test.go
  79. 374 0
      authority/provisioner/oidc.go
  80. 540 0
      authority/provisioner/oidc_test.go
  81. 295 0
      authority/provisioner/provisioner.go
  82. 54 0
      authority/provisioner/provisioner_test.go
  83. 297 0
      authority/provisioner/sign_options.go
  84. 275 0
      authority/provisioner/sign_options_test.go
  85. 380 0
      authority/provisioner/sign_ssh_options.go
  86. 192 0
      authority/provisioner/sign_ssh_options_test.go
  87. 125 0
      authority/provisioner/ssh_test.go
  88. 7 0
      authority/provisioner/testdata/ecdsa.csr
  89. 8 0
      authority/provisioner/testdata/ecdsa.key
  90. 6 0
      authority/provisioner/testdata/ed25519.csr
  91. 6 0
      authority/provisioner/testdata/ed25519.key
  92. 11 0
      authority/provisioner/testdata/root_ca.crt
  93. 16 0
      authority/provisioner/testdata/rsa.csr
  94. 30 0
      authority/provisioner/testdata/rsa.key
  95. 10 0
      authority/provisioner/testdata/short-rsa.csr
  96. 146 0
      authority/provisioner/timeduration.go
  97. 268 0
      authority/provisioner/timeduration_test.go
  98. 744 0
      authority/provisioner/utils_test.go
  99. 0 55
      authority/provisioner_test.go
  100. 21 89
      authority/provisioners.go

+ 1 - 0
.VERSION

@@ -0,0 +1 @@
+$Format:%d$

+ 1 - 0
.gitattributes

@@ -0,0 +1 @@
+.VERSION export-subst

+ 0 - 28
.github/ISSUE_TEMPLATE/autocert_bug.md

@@ -1,28 +0,0 @@
----
-name: Autocert Bug
-about: Report a bug you found in autocert
-labels: area/autocert bug
----
-
-### Subject of the issue
-Describe your issue here
-
-### Environment
-* Kubernetes version:
-* Cloud provider or hardware configuration:
-* OS (e.g., from /etc/os-release):
-* Kernel (e.g., `uname -a`):
-* Install tools:
-* Other:
-
-### Steps to reproduce
-Tell us how to reproduce this issue
-
-### Expected behaviour
-Tell us what should happen
-
-### Actual behaviour
-Tell us what happens instead
-
-### Additional context
-Add any other context about the problem here

+ 0 - 11
.github/ISSUE_TEMPLATE/autocert_enhancement.md

@@ -1,11 +0,0 @@
----
-name: Autocert Enhancement
-about: Suggest an enhancement to autocert
-labels: area/autocert enhancement
----
-
-### What would you like to be added
-
-
-### Why this is needed
-

+ 11 - 0
.github/ISSUE_TEMPLATE/enhancement.md

@@ -0,0 +1,11 @@
+---
+name: Certificates Enhancement
+about: Suggest an enhancement to step certificates
+labels: area/cert-management enhancement
+---
+
+### What would you like to be added
+
+
+### Why this is needed
+

+ 5 - 0
.gitignore

@@ -18,3 +18,8 @@
 coverage.txt
 vendor
 output
+
+# Ignore modules until switch from gopkg
+go.mod
+go.sum
+

+ 70 - 0
.golangci.yml

@@ -0,0 +1,70 @@
+linters-settings:
+  govet:
+    check-shadowing: true
+    settings:
+      printf:
+        funcs:
+          - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
+          - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
+          - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
+          - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
+  golint:
+    min-confidence: 0
+  gocyclo:
+    min-complexity: 10
+  maligned:
+    suggest-new: true
+  dupl:
+    threshold: 100
+  goconst:
+    min-len: 2
+    min-occurrences: 2
+  depguard:
+    list-type: blacklist
+    packages:
+      # logging is allowed only by logutils.Log, logrus
+      # is allowed to use only in logutils package
+      - github.com/sirupsen/logrus
+  misspell:
+    locale: US
+  lll:
+    line-length: 140
+  goimports:
+    local-prefixes: github.com/golangci/golangci-lint
+  gocritic:
+    enabled-tags:
+      - performance
+      - style
+      - experimental
+    disabled-checks:
+      - wrapperFunc
+      - dupImport # https://github.com/go-critic/go-critic/issues/845
+
+linters:
+  disable-all: true
+  enable:
+    - gofmt
+    - golint
+    - vet
+    - misspell
+    - ineffassign
+    - deadcode
+    - staticcheck
+    - unused
+
+run:
+  skip-dirs:
+    - pkg
+
+issues:
+  exclude:
+    - can't lint
+    - declaration of "err" shadows declaration at line
+    - should have a package comment, unless it's in another file for this package
+    - error strings should not be capitalized or end with punctuation or a newline
+# golangci.com configuration
+# https://github.com/golangci/golangci/wiki/Configuration
+service:
+  golangci-lint-version: 1.18.x # use the fixed version to not introduce new linters unexpectedly
+  prepare:
+    - echo "here I can run custom commands, but no preparation needed for this repo"

+ 1 - 1
.travis.yml

@@ -1,6 +1,6 @@
 language: go
 go:
-- 1.11.x
+- 1.13.x
 addons:
   apt:
     packages:

+ 7 - 0
.version.sh

@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+read -r firstline < .VERSION
+last_half="${firstline##*tag: }"
+if [[ ${last_half::1} == "v" ]]; then
+    version_string="${last_half%%[,)]*}"
+fi
+echo "${version_string:-v0.0.0}"

+ 112 - 273
Gopkg.lock

@@ -1,20 +1,13 @@
 # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
 
 
-[[projects]]
-  digest = "1:304cb78c285eaf02ab529ad02a257cad9b4845022915e6c82f87860ac53222d8"
-  name = "github.com/alecthomas/gometalinter"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "bae2f1293d092fd8167939d5108d1b025eaef9de"
-
 [[projects]]
   branch = "master"
-  digest = "1:c198fdc381e898e8fb62b8eb62758195091c313ad18e52a3067366e1dda2fb3c"
-  name = "github.com/alecthomas/units"
+  digest = "1:6716c9fe6333591128e72848f246fc01dc72240e1e64185d8b4e124e7280b35d"
+  name = "github.com/AndreasBriese/bbloom"
   packages = ["."]
   pruneopts = "UT"
-  revision = "2efee857e7cfd4f3d0138cc3cbb1b4966962b93a"
+  revision = "e2d15f34fcf99d5dbb871c820ec73f710fca9815"
 
 [[projects]]
   branch = "master"
@@ -25,23 +18,27 @@
   revision = "2972be24d48e78746da79ba8e24e8b488c9880de"
 
 [[projects]]
-  digest = "1:848ef40f818e59905140552cc49ff3dc1a15f955e4b56d1c5c2cc4b54dbadf0c"
-  name = "github.com/client9/misspell"
+  digest = "1:21ac9938fb1098b3a7b0dd909fb30878d33231177fac11a2821114eb9c1088ff"
+  name = "github.com/dgraph-io/badger"
   packages = [
     ".",
-    "cmd/misspell",
+    "options",
+    "protos",
+    "skl",
+    "table",
+    "y",
   ]
   pruneopts = "UT"
-  revision = "b90dc15cfd220ecf8bbc9043ecb928cef381f011"
-  version = "v0.3.4"
+  revision = "391b6d3b93e6014fe8c2971fcc0c1266e47dbbd9"
+  version = "v1.5.3"
 
 [[projects]]
-  digest = "1:2cd7915ab26ede7d95b8749e6b1f933f1c6d5398030684e6505940a10f31cfda"
-  name = "github.com/ghodss/yaml"
+  branch = "master"
+  digest = "1:6e8109ce247a59ab1eeb5330166c12735f6590de99c9647b6162d11518d32c9a"
+  name = "github.com/dgryski/go-farm"
   packages = ["."]
   pruneopts = "UT"
-  revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
-  version = "v1.0.0"
+  revision = "6a90982ecee230ff6cba02d5bd386acc030be9d3"
 
 [[projects]]
   branch = "master"
@@ -52,38 +49,22 @@
   revision = "0ebf7795c516423a110473652e9ba3a59a504863"
 
 [[projects]]
-  digest = "1:b402bb9a24d108a9405a6f34675091b036c8b056aac843bf6ef2389a65c5cf48"
-  name = "github.com/gogo/protobuf"
-  packages = [
-    "proto",
-    "sortkeys",
-  ]
-  pruneopts = "UT"
-  revision = "4cbf7e384e768b4e01799441fdf2a706a5635ae7"
-  version = "v1.2.0"
-
-[[projects]]
-  branch = "travis-1.9"
-  digest = "1:e8f5d9c09a7209c740e769713376abda388c41b777ba8e9ed52767e21acf379f"
-  name = "github.com/golang/lint"
-  packages = [
-    ".",
-    "golint",
-  ]
+  digest = "1:ec6f9bf5e274c833c911923c9193867f3f18788c461f76f05f62bb1510e0ae65"
+  name = "github.com/go-sql-driver/mysql"
+  packages = ["."]
   pruneopts = "UT"
-  revision = "883fe33ffc4344bad1ecd881f61afd5ec5d80e0a"
+  revision = "72cd26f257d44c1114970e19afddcd812016007e"
+  version = "v1.4.1"
 
 [[projects]]
+<<<<<<< HEAD
   branch = "master"
   digest = "1:239c4c7fd2159585454003d9be7207167970194216193a8a210b8d29576f19c9"
+=======
+  digest = "1:97df918963298c287643883209a2c3f642e6593379f97ab400c2a2e219ab647d"
+>>>>>>> master
   name = "github.com/golang/protobuf"
-  packages = [
-    "proto",
-    "ptypes",
-    "ptypes/any",
-    "ptypes/duration",
-    "ptypes/timestamp",
-  ]
+  packages = ["proto"]
   pruneopts = "UT"
   revision = "c823c79ea1570fb5ff454033735a8e68575d1d0f"
 
@@ -104,38 +85,6 @@
   pruneopts = "UT"
   revision = "b5e3a70217c2a317c27b3c852126d0f8f29fef2b"
 
-[[projects]]
-  branch = "master"
-  digest = "1:3ee90c0d94da31b442dde97c99635aaafec68d0b8a3c12ee2075c6bdabeec6bb"
-  name = "github.com/google/gofuzz"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1"
-
-[[projects]]
-  branch = "master"
-  digest = "1:750e747d0aad97b79f4a4e00034bae415c2ea793fd9e61438d966ee9c79579bf"
-  name = "github.com/google/shlex"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "6f45313302b9c56850fc17f99e40caebce98c716"
-
-[[projects]]
-  branch = "master"
-  digest = "1:824d147914b40e56e9e1eebd602bc6bb9761989d52fd8e4a498428467980eb17"
-  name = "github.com/gordonklaus/ineffassign"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "1003c8bd00dc2869cb5ca5282e6ce33834fed514"
-
-[[projects]]
-  digest = "1:3e551bbb3a7c0ab2a2bf4660e7fcad16db089fdcfbb44b0199e62838038623ea"
-  name = "github.com/json-iterator/go"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "1624edc4454b8682399def8740d46db5e4362ba4"
-  version = "v1.1.5"
-
 [[projects]]
   branch = "master"
   digest = "1:e51f40f0c19b39c1825eadd07d5c0a98a2ad5942b166d9fc4f54750ce9a04810"
@@ -164,7 +113,7 @@
   revision = "2d01aacdc34a083dca635ba869909f5fc0cd4f41"
 
 [[projects]]
-  digest = "1:2a2a76072bd413b3484a0b5bb2fbb078b0b7dd8950e9276c900e14dce2354679"
+  digest = "1:2d2bc0f23cca6b59cec3fbece9abc102bdb19f548dd58d7667e57699074a2c76"
   name = "github.com/manifoldco/promptui"
   packages = [
     ".",
@@ -172,8 +121,8 @@
     "screenbuf",
   ]
   pruneopts = "UT"
-  revision = "20f2a94120aa14a334121a6de66616a7fa89a5cd"
-  version = "v0.3.2"
+  revision = "157c96fb638a14d268b305cf2012582431fcc410"
+  version = "v0.3.1"
 
 [[projects]]
   digest = "1:c658e84ad3916da105a761660dcaeb01e63416c8ec7bc62256a9b411a05fcd67"
@@ -192,20 +141,26 @@
   version = "v0.0.4"
 
 [[projects]]
-  digest = "1:33422d238f147d247752996a26574ac48dcf472976eda7f5134015f06bf16563"
-  name = "github.com/modern-go/concurrent"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94"
-  version = "1.0.3"
-
-[[projects]]
-  digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855"
-  name = "github.com/modern-go/reflect2"
-  packages = ["."]
+  branch = "master"
+  digest = "1:ae08d850ba158ea3ba4a7bb90f8372608172d8920644e5a6693b940a1f4e5d01"
+  name = "github.com/mmcloughlin/avo"
+  packages = [
+    "attr",
+    "build",
+    "buildtags",
+    "gotypes",
+    "internal/prnt",
+    "internal/stack",
+    "ir",
+    "operand",
+    "pass",
+    "printer",
+    "reg",
+    "src",
+    "x86",
+  ]
   pruneopts = "UT"
-  revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd"
-  version = "1.0.1"
+  revision = "2e7d06bc7ada2979f17ccf8ebf486dba23b84fc7"
 
 [[projects]]
   digest = "1:266d082179f3a29a4bdcf1dcc49d4a304f5c7107e65bd22d1fecacf45f1ac348"
@@ -224,33 +179,12 @@
   version = "v1.11.0"
 
 [[projects]]
-  digest = "1:07140002dbf37da92090f731b46fa47be4820b82fe5c14a035203b0e813d0ec2"
-  name = "github.com/nicksnyder/go-i18n"
-  packages = [
-    "i18n",
-    "i18n/bundle",
-    "i18n/language",
-    "i18n/translation",
-  ]
-  pruneopts = "UT"
-  revision = "0dc1626d56435e9d605a29875701721c54bc9bbd"
-  version = "v1.10.0"
-
-[[projects]]
-  digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e"
-  name = "github.com/pelletier/go-toml"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194"
-  version = "v1.2.0"
-
-[[projects]]
-  digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747"
+  digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b"
   name = "github.com/pkg/errors"
   packages = ["."]
   pruneopts = "UT"
-  revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
-  version = "v0.8.0"
+  revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4"
+  version = "v0.8.1"
 
 [[projects]]
   digest = "1:2e76a73cb51f42d63a2a1a85b3dc5731fd4faf6821b434bd0ef2c099186031d6"
@@ -293,11 +227,17 @@
   revision = "de77670473b5492f5d0bce155b5c01534c2d13f7"
 
 [[projects]]
+<<<<<<< HEAD
   branch = "certificate-transparency"
   digest = "1:ed4ae9e597c66929a567de027512ee77a632ed8c4471e53c82c82c6658c4eb90"
+=======
+  branch = "master"
+  digest = "1:c26dc5debe7fa23c636a116c336aa033f8d7be0d3464d7b363f4b3355dcccf4f"
+>>>>>>> master
   name = "github.com/smallstep/cli"
   packages = [
     "command",
+    "command/version",
     "config",
     "crypto/keys",
     "crypto/pemutil",
@@ -315,15 +255,25 @@
     "utils",
   ]
   pruneopts = "UT"
+<<<<<<< HEAD
   revision = "6cb4285dba37a5d03e1f4be41fc897b071181a70"
+=======
+  revision = "eeecaac062cb548ee2ab7c7563bc3c2f2160f019"
+>>>>>>> master
 
 [[projects]]
   branch = "master"
-  digest = "1:ba52e5a5fb800ce55108b7a5f181bb809aab71c16736051312b0aa969f82ad39"
-  name = "github.com/tsenart/deadcode"
-  packages = ["."]
+  digest = "1:7d03323edb817ca94efaee5489cde6acd06ceeaca9e6eee106d2d6a90deca997"
+  name = "github.com/smallstep/nosql"
+  packages = [
+    ".",
+    "badger",
+    "bolt",
+    "database",
+    "mysql",
+  ]
   pruneopts = "UT"
-  revision = "210d2dc333e90c7e3eedf4f2242507a8e83ed4ab"
+  revision = "f80b3f432de0662f07ebd58fe52b0a119fe5dcd9"
 
 [[projects]]
   branch = "master"
@@ -333,16 +283,30 @@
   pruneopts = "UT"
   revision = "b67dcf995b6a7b7f14fad5fcb7cc5441b05e814b"
 
+[[projects]]
+  digest = "1:5f7414cf41466d4b4dd7ec52b2cd3e481e08cfd11e7e24fef730c0e483e88bb1"
+  name = "go.etcd.io/bbolt"
+  packages = ["."]
+  pruneopts = "UT"
+  revision = "63597a96ec0ad9e6d43c3fc81e809909e0237461"
+  version = "v1.3.2"
+
 [[projects]]
   branch = "master"
-  digest = "1:a068d4e48e0f2e172903d25b6e066815fa8efd4b01102aec4c741f02a9650c03"
+  digest = "1:afc49fe39c8c591fc2c8ddc73adc4c69e67125dde6c58e24c91b3b0cf78602be"
   name = "golang.org/x/crypto"
   packages = [
     "cryptobyte",
     "cryptobyte/asn1",
+    "curve25519",
     "ed25519",
     "ed25519/internal/edwards25519",
+    "internal/chacha20",
+    "internal/subtle",
+    "ocsp",
     "pbkdf2",
+    "poly1305",
+    "ssh",
     "ssh/terminal",
   ]
   pruneopts = "UT"
@@ -403,82 +367,32 @@
 
 [[projects]]
   branch = "master"
-  digest = "1:384310e8a567edf6d5406d93318f9460c2d8db1a07ff5b6fece95b224343e7f1"
+  digest = "1:6b4a1c844969280f4d3e36ef4b0762e3522e701c015f688b68ef91c2ea6b5ac7"
   name = "golang.org/x/tools"
   packages = [
     "go/ast/astutil",
     "go/gcexportdata",
+    "go/internal/cgo",
     "go/internal/gcimporter",
+    "go/packages",
     "go/types/typeutil",
+    "internal/fastwalk",
+    "internal/gopathwalk",
+    "internal/semver",
   ]
   pruneopts = "UT"
   revision = "3a10b9bf0a52df7e992a8c3eb712a86d3c896c75"
 
 [[projects]]
-  branch = "master"
-  digest = "1:077c1c599507b3b3e9156d17d36e1e61928ee9b53a5b420f10f28ebd4a0b275c"
-  name = "google.golang.org/genproto"
-  packages = ["googleapis/rpc/status"]
-  pruneopts = "UT"
-  revision = "4b09977fb92221987e99d190c8f88f2c92727a29"
-
-[[projects]]
-  digest = "1:9ab5a33d8cb5c120602a34d2e985ce17956a4e8c2edce7e6961568f95e40c09a"
-  name = "google.golang.org/grpc"
-  packages = [
-    ".",
-    "balancer",
-    "balancer/base",
-    "balancer/roundrobin",
-    "binarylog/grpc_binarylog_v1",
-    "codes",
-    "connectivity",
-    "credentials",
-    "credentials/internal",
-    "encoding",
-    "encoding/proto",
-    "grpclog",
-    "internal",
-    "internal/backoff",
-    "internal/binarylog",
-    "internal/channelz",
-    "internal/envconfig",
-    "internal/grpcrand",
-    "internal/grpcsync",
-    "internal/syscall",
-    "internal/transport",
-    "keepalive",
-    "metadata",
-    "naming",
-    "peer",
-    "resolver",
-    "resolver/dns",
-    "resolver/passthrough",
-    "stats",
-    "status",
-    "tap",
-  ]
-  pruneopts = "UT"
-  revision = "a02b0774206b209466313a0b525d2c738fe407eb"
-  version = "v1.18.0"
-
-[[projects]]
-  digest = "1:39efb07a0d773dc09785b237ada4e10b5f28646eb6505d97bc18f8d2ff439362"
-  name = "gopkg.in/alecthomas/kingpin.v3-unstable"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "63abe20a23e29e80bbef8089bd3dee3ac25e5306"
-
-[[projects]]
-  digest = "1:2d1fbdc6777e5408cabeb02bf336305e724b925ff4546ded0fa8715a7267922a"
-  name = "gopkg.in/inf.v0"
-  packages = ["."]
+  digest = "1:c25289f43ac4a68d88b02245742347c94f1e108c534dda442188015ff80669b3"
+  name = "google.golang.org/appengine"
+  packages = ["cloudsql"]
   pruneopts = "UT"
-  revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf"
-  version = "v0.9.1"
+  revision = "54a98f90d1c46b7731eb8fb305d2a321c30ef610"
+  version = "v1.5.0"
 
 [[projects]]
-  digest = "1:7fbe10f3790dc4e6296c7c844c5a9b35513e5521c29c47e10ba99cd2956a2719"
+  digest = "1:9593bab40e981b1f90b7e07faeab0d09b75fe338880d08880f986a9d3283c53f"
   name = "gopkg.in/square/go-jose.v2"
   packages = [
     ".",
@@ -487,91 +401,15 @@
     "jwt",
   ]
   pruneopts = "UT"
-  revision = "ef984e69dd356202fd4e4910d4d9c24468bdf0b8"
-  version = "v2.1.9"
-
-[[projects]]
-  digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202"
-  name = "gopkg.in/yaml.v2"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
-  version = "v2.2.1"
-
-[[projects]]
-  branch = "master"
-  digest = "1:767b6c0b2c1d9487ee50cb8df1d0fdebf06ac0b19b723f6489d388e7b47c962d"
-  name = "k8s.io/api"
-  packages = [
-    "admission/v1beta1",
-    "authentication/v1",
-    "core/v1",
-  ]
-  pruneopts = "UT"
-  revision = "de494049e22a9ccf748c5bbda7492f42f344d0cd"
-
-[[projects]]
-  branch = "master"
-  digest = "1:5eb353533eaebdfec2392210ab218a389965ba5d4dc02b4aef87b9549e5d0f84"
-  name = "k8s.io/apimachinery"
-  packages = [
-    "pkg/api/resource",
-    "pkg/apis/meta/v1",
-    "pkg/apis/meta/v1/unstructured",
-    "pkg/conversion",
-    "pkg/conversion/queryparams",
-    "pkg/fields",
-    "pkg/labels",
-    "pkg/runtime",
-    "pkg/runtime/schema",
-    "pkg/runtime/serializer",
-    "pkg/runtime/serializer/json",
-    "pkg/runtime/serializer/protobuf",
-    "pkg/runtime/serializer/recognizer",
-    "pkg/runtime/serializer/versioning",
-    "pkg/selection",
-    "pkg/types",
-    "pkg/util/errors",
-    "pkg/util/framer",
-    "pkg/util/intstr",
-    "pkg/util/json",
-    "pkg/util/naming",
-    "pkg/util/net",
-    "pkg/util/runtime",
-    "pkg/util/sets",
-    "pkg/util/validation",
-    "pkg/util/validation/field",
-    "pkg/util/yaml",
-    "pkg/watch",
-    "third_party/forked/golang/reflect",
-  ]
-  pruneopts = "UT"
-  revision = "4b3b852955ebe47857fcf134b531b23dd8f3e793"
-
-[[projects]]
-  digest = "1:72fd56341405f53c745377e0ebc4abeff87f1a048e0eea6568a20212650f5a82"
-  name = "k8s.io/klog"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "71442cd4037d612096940ceb0f3fec3f7fff66e0"
-  version = "v0.2.0"
-
-[[projects]]
-  digest = "1:7719608fe0b52a4ece56c2dde37bedd95b938677d1ab0f84b8a7852e4c59f849"
-  name = "sigs.k8s.io/yaml"
-  packages = ["."]
-  pruneopts = "UT"
-  revision = "fd68e9863619f6ec2fdd8625fe1f02e7c877e480"
-  version = "v1.1.0"
+  revision = "730df5f748271903322feb182be83b43ebbbe27d"
+  version = "v2.3.1"
 
 [solve-meta]
   analyzer-name = "dep"
   analyzer-version = 1
   input-imports = [
-    "github.com/alecthomas/gometalinter",
-    "github.com/client9/misspell/cmd/misspell",
-    "github.com/ghodss/yaml",
     "github.com/go-chi/chi",
+<<<<<<< HEAD
     "github.com/golang/lint/golint",
     "github.com/golang/protobuf/proto",
     "github.com/google/certificate-transparency-go",
@@ -580,11 +418,15 @@
     "github.com/google/certificate-transparency-go/tls",
     "github.com/google/certificate-transparency-go/x509",
     "github.com/gordonklaus/ineffassign",
+=======
+>>>>>>> master
     "github.com/newrelic/go-agent",
     "github.com/pkg/errors",
     "github.com/rs/xid",
     "github.com/sirupsen/logrus",
     "github.com/smallstep/assert",
+    "github.com/smallstep/cli/command",
+    "github.com/smallstep/cli/command/version",
     "github.com/smallstep/cli/config",
     "github.com/smallstep/cli/crypto/keys",
     "github.com/smallstep/cli/crypto/pemutil",
@@ -596,21 +438,18 @@
     "github.com/smallstep/cli/pkg/x509",
     "github.com/smallstep/cli/token",
     "github.com/smallstep/cli/token/provision",
+    "github.com/smallstep/cli/ui",
     "github.com/smallstep/cli/usage",
-    "github.com/tsenart/deadcode",
+    "github.com/smallstep/cli/utils",
+    "github.com/smallstep/nosql",
+    "github.com/smallstep/nosql/database",
     "github.com/urfave/cli",
-    "golang.org/x/net/context",
+    "golang.org/x/crypto/ed25519",
+    "golang.org/x/crypto/ocsp",
+    "golang.org/x/crypto/ssh",
     "golang.org/x/net/http2",
-    "google.golang.org/grpc",
-    "google.golang.org/grpc/credentials",
-    "google.golang.org/grpc/peer",
     "gopkg.in/square/go-jose.v2",
     "gopkg.in/square/go-jose.v2/jwt",
-    "k8s.io/api/admission/v1beta1",
-    "k8s.io/api/core/v1",
-    "k8s.io/apimachinery/pkg/apis/meta/v1",
-    "k8s.io/apimachinery/pkg/runtime",
-    "k8s.io/apimachinery/pkg/runtime/serializer",
   ]
   solver-name = "gps-cdcl"
   solver-version = 1

+ 11 - 16
Gopkg.toml

@@ -23,19 +23,6 @@
 #   non-go = false
 #   go-tests = true
 #   unused-packages = true
-
-required = [
-  "github.com/alecthomas/gometalinter",
-  "github.com/golang/lint/golint",
-  "github.com/client9/misspell/cmd/misspell",
-  "github.com/gordonklaus/ineffassign",
-  "github.com/tsenart/deadcode",
-]
-
-[[constraint]]
-  name = "github.com/alecthomas/gometalinter"
-  revision = "bae2f1293d092fd8167939d5108d1b025eaef9de"
-
 [[override]]
   name = "gopkg.in/alecthomas/kingpin.v3-unstable"
   revision = "63abe20a23e29e80bbef8089bd3dee3ac25e5306"
@@ -48,9 +35,9 @@ required = [
   branch = "certificate-transparency"
   name = "github.com/smallstep/cli"
 
-[prune]
-  go-tests = true
-  unused-packages = true
+[[constraint]]
+  branch = "master"
+  name = "github.com/smallstep/nosql"
 
 [[constraint]]
   name = "github.com/newrelic/go-agent"
@@ -62,6 +49,7 @@ required = [
 
 [[constraint]]
   name = "gopkg.in/square/go-jose.v2"
+<<<<<<< HEAD
   version = "2.1.9"
 
 [[constraint]]
@@ -71,3 +59,10 @@ required = [
 [[override]]
   branch = "master"
   name = "github.com/golang/protobuf"
+=======
+  version = "2.3.1"
+
+[prune]
+  go-tests = true
+  unused-packages = true
+>>>>>>> master

+ 51 - 62
Makefile

@@ -8,10 +8,7 @@ SRC=$(shell find . -type f -name '*.go' -not -path "./vendor/*")
 GOOS_OVERRIDE ?=
 OUTPUT_ROOT=output/
 
-# Set shell to bash for `echo -e`
-SHELL := /bin/bash
-
-all: build lint test
+all: build test lint
 
 .PHONY: all
 
@@ -22,25 +19,18 @@ all: build lint test
 bootstra%:
 	$Q which dep || go get github.com/golang/dep/cmd/dep
 	$Q dep ensure
+	$Q GO111MODULE=on go get github.com/golangci/golangci-lint/cmd/golangci-lint@v1.18.0
+
 
 vendor: Gopkg.lock
 	$Q dep ensure
 
-BOOTSTRAP=\
-	github.com/golang/lint/golint \
-	github.com/client9/misspell/cmd/misspell \
-	github.com/gordonklaus/ineffassign \
-	github.com/tsenart/deadcode \
-	github.com/alecthomas/gometalinter
-
 define VENDOR_BIN_TMPL
 vendor/bin/$(notdir $(1)): vendor
 	$Q go build -o $$@ ./vendor/$(1)
 VENDOR_BINS += vendor/bin/$(notdir $(1))
 endef
 
-$(foreach pkg,$(BOOTSTRAP),$(eval $(call VENDOR_BIN_TMPL,$(pkg))))
-
 .PHONY: bootstra% vendor
 
 #################################################
@@ -49,11 +39,19 @@ $(foreach pkg,$(BOOTSTRAP),$(eval $(call VENDOR_BIN_TMPL,$(pkg))))
 
 # Version flags to embed in the binaries
 VERSION ?= $(shell [ -d .git ] && git describe --tags --always --dirty="-dev")
+# If we are not in an active git dir then try reading the version from .VERSION.
+# .VERSION contains a slug populated by `git archive`.
+VERSION := $(or $(VERSION),$(shell ./.version.sh .VERSION))
 VERSION := $(shell echo $(VERSION) | sed 's/^v//')
+NOT_RC  := $(shell echo $(VERSION) | grep -v -e -rc)
 
 # If TRAVIS_TAG is set then we know this ref has been tagged.
 ifdef TRAVIS_TAG
-	PUSHTYPE=release
+	ifeq ($(NOT_RC),)
+		PUSHTYPE=release-candidate
+	else
+		PUSHTYPE=release
+	endif
 else
 	PUSHTYPE=master
 endif
@@ -96,16 +94,7 @@ generate:
 test:
 	$Q $(GOFLAGS) go test -short -coverprofile=coverage.out ./...
 
-vtest:
-	$(Q)for d in $$(go list ./... | grep -v vendor); do \
-    echo -e "TESTS FOR: for \033[0;35m$$d\033[0m"; \
-    $(GOFLAGS) go test -v -bench=. -run=. -short -coverprofile=coverage.out $$d; \
-	out=$$?; \
-	if [[ $$out -ne 0 ]]; then ret=$$out; fi;\
-    rm -f profile.coverage.out; \
-	done; exit $$ret;
-
-.PHONY: test vtest
+.PHONY: test
 
 integrate: integration
 
@@ -118,26 +107,13 @@ integration: bin/$(BINNAME)
 # Linting
 #########################################
 
-LINTERS=\
-	gofmt \
-	golint \
-	vet \
-	misspell \
-	ineffassign \
-	deadcode
-
-$(patsubst %,%-bin,$(filter-out gofmt vet,$(LINTERS))): %-bin: vendor/bin/%
-gofmt-bin vet-bin:
-
-$(LINTERS): %: vendor/bin/gometalinter %-bin vendor
-	$Q PATH=`pwd`/vendor/bin:$$PATH gometalinter --tests --disable-all --vendor \
-	     --deadline=5m -s data -s pkg --enable $@ ./...
 fmt:
 	$Q gofmt -l -w $(SRC)
 
-lint: $(LINTERS)
+lint:
+	$Q LOG_LEVEL=error golangci-lint run
 
-.PHONY: $(LINTERS) lint fmt
+.PHONY: lint fmt
 
 #########################################
 # Install
@@ -153,6 +129,19 @@ uninstall:
 
 .PHONY: install uninstall
 
+#########################################
+# Clean
+#########################################
+
+clean:
+	@echo "You will need to run 'make bootstrap' or 'dep ensure' directly to re-download any dependencies."
+	$Q rm -rf vendor
+ifneq ($(BINNAME),"")
+	$Q rm -f bin/$(BINNAME)
+endif
+
+.PHONY: clean
+
 #########################################
 # Building Docker Image
 #
@@ -198,24 +187,30 @@ docker-tag:
 docker-push-tag: docker-tag
 	$(call DOCKER_PUSH,step-ca,$(VERSION))
 
+docker-push-tag-latest:
+	$(call DOCKER_PUSH,step-ca,latest)
+
 # Rely on DOCKER_USERNAME and DOCKER_PASSWORD being set inside the CI or
 # equivalent environment
 docker-login:
 	$Q docker login -u="$(DOCKER_USERNAME)" -p="$(DOCKER_PASSWORD)"
 
-.PHONY: docker-login docker-tag docker-push-tag
+.PHONY: docker-login docker-tag docker-push-tag docker-push-tag-latest
 
 #################################################
 # Targets for pushing the docker images
 #################################################
 
-# For all builds on the master branch, we actually build the container
+# For all builds we build the docker container
 docker-master: docker
 
-# For all builds on the master branch with an rc tag
-docker-release: docker-master docker-login docker-push-tag
+# For all builds with a release candidate tag
+docker-release-candidate: docker-master docker-login docker-push-tag
 
-.PHONY: docker-master docker-release
+# For all builds with a release tag
+docker-release: docker-release-candidate docker-push-tag-latest
+
+.PHONY: docker-master docker-release-candidate docker-release
 
 #########################################
 # Debian
@@ -276,16 +271,20 @@ bundle-darwin: binary-darwin
 .PHONY: binary-linux binary-darwin bundle-linux bundle-darwin
 
 #################################################
-# Targets for creating OS specific artifacts
+# Targets for creating OS specific artifacts and archives
 #################################################
 
 artifacts-linux-tag: bundle-linux debian
 
 artifacts-darwin-tag: bundle-darwin
 
-artifacts-tag: artifacts-linux-tag artifacts-darwin-tag
+artifacts-archive-tag:
+	$Q mkdir -p $(RELEASE)
+	$Q git archive v$(VERSION) | gzip > $(RELEASE)/step-certificates_$(VERSION).tar.gz
+
+artifacts-tag: artifacts-linux-tag artifacts-darwin-tag artifacts-archive-tag
 
-.PHONY: artifacts-linux-tag artifacts-darwin-tag artifacts-tag
+.PHONY: artifacts-linux-tag artifacts-darwin-tag artifacts-archive-tag artifacts-tag
 
 #################################################
 # Targets for creating step artifacts
@@ -294,23 +293,13 @@ artifacts-tag: artifacts-linux-tag artifacts-darwin-tag
 # For all builds that are not tagged
 artifacts-master:
 
+# For all builds with a release-candidate (-rc) tag
+artifacts-release-candidate: artifacts-tag
+
 # For all builds with a release tag
 artifacts-release: artifacts-tag
 
 # This command is called by travis directly *after* a successful build
 artifacts: artifacts-$(PUSHTYPE) docker-$(PUSHTYPE)
 
-.PHONY: artifacts-master artifacts-release artifacts
-
-#########################################
-# Clean
-#########################################
-
-clean:
-	@echo "You will need to run 'make bootstrap' or 'dep ensure' directly to re-download any dependencies."
-	$Q rm -rf vendor
-ifneq ($(BINNAME),"")
-	$Q rm -f bin/$(BINNAME)
-endif
-
-.PHONY: clean
+.PHONY: artifacts-master artifacts-release-candidate artifacts-release artifacts

+ 250 - 436
README.md

@@ -1,532 +1,355 @@
 # Step Certificates
 
-An online certificate authority and related tools for secure automated
-certificate management, so you can use TLS everywhere.
+An online certificate authority and related tools for secure automated certificate management, so you can use TLS everywhere.
 
-For more information and docs see [the Step website](https://smallstep.com/cli/)
-and the [blog post](https://smallstep.com/blog/step-certificates.html)
-announcing Step Certificate Authority.
+This repository is for `step-ca`, a certificate authority that exposes an API for automated certificate management. It also contains a [golang SDK](https://github.com/smallstep/certificates/tree/master/examples#basic-client-usage) for interacting with `step-ca` programatically. However, you'll probably want to use the [`step` command-line tool](https://github.com/smallstep/cli) to operate `step-ca` and get certificates, instead of using this low-level SDK directly.
 
-![Animated terminal showing step certificates in practice](https://github.com/smallstep/certificates/raw/master/images/step-ca.gif)
+**Questions? Find us [on gitter](https://gitter.im/smallstep/community).**
 
-## Why?
+[Website](https://smallstep.com) |
+[Documentation](#documentation) |
+[Installation Guide](#installation-guide) |
+[Getting Started](./docs/GETTING_STARTED.md) |
+[Contribution Guide](./docs/CONTRIBUTING.md)
 
-Managing your own *public key infrastructure* (PKI) can be tedious and error
-prone. Good security hygiene is hard. Setting up simple PKI is out of reach for
-many small teams, and following best practices like proper certificate revocation
-and rolling is challenging even for experts.
-
-Amongst numerous use cases, proper PKI makes it easy to use mTLS (mutual TLS) to improve security and to make it possible to connect services across the public internet. Unlike VPNs & SDNs, deploying and scaling mTLS is pretty easy. You're (hopefully) already using TLS, and your existing tools and standard libraries will provide most of what you need. If you know how to operate DNS and reverse proxies, you know how to operate mTLS infrastructure.
-
-![Connect it all with mTLS](https://raw.githubusercontent.com/smallstep/certificates/master/images/connect-with-mtls-2.png)
-
-There's just one problem: **you need certificates issued by your own certificate authority (CA)**. Building and operating a CA, issuing certificates, and making sure they're renewed before they expire is tricky. This project provides the infratructure, automations, and workflows you'll need.
-
-
-This project is part of smallstep's broader security architecture, which makes
-it much easier to implement good security practices early, and incrementally
-improve them as your system matures.
-
-> ## 🆕 Autocert
-> <a href="autocert/README.md"><img width="50%" src="https://raw.githubusercontent.com/smallstep/certificates/autocert/autocert/autocert-logo.png"></a>
->
-> If you're using Kubernetes, make sure you [check out autocert](autocert/README.md): a kubernetes add-on that builds on `step certificates` to automatically injects TLS/HTTPS certificates into your containers.
-
-### Table of Contents
-
-- [Installing](#installing)
-- [Documentation](#documentation)
-- [Terminology](#terminology)
-- [Getting Started](#getting-started)
-- [Commonly Asked Questions](docs/common-questions.md)
-- [Recommended Defaults](docs/recommendations.md)
-- [How To Create A New Release](docs/distribution.md)
-- [Versioning](#versioning)
-- [LICENSE](./LICENSE)
-- [CHANGELOG](./CHANGELOG.md)
-
-
-## Installing
-
-These instructions will install an OS specific version of the `step` binary on
-your local machine.
-
-### Mac OS
-
-Install `step` via [Homebrew](https://brew.sh/):
-
-```
-brew install smallstep/smallstep/step
-```
-
-### Linux
-
-Download the latest Debian package from [releases](https://github.com/smallstep/certificates/releases):
-
-```
-wget https://github.com/smallstep/certificates/releases/download/X.Y.Z/step-certificates_X.Y.Z_amd64.deb
-```
-
-Install the Debian package:
-
-```
-sudo dpkg -i step-certificates_X.Y.Z_amd64.deb
-```
-
-## Documentation
-
-Documentation can be found in three places:
-
-1. On the command line with `step ca help xxx` where `xxx` is the subcommand you are interested in. Ex: `step help ca provisioners list`
-
-2. On the web at https://smallstep.com/docs/certificates
-
-3. In your browser with `step ca help --http :8080` and visiting http://localhost:8080
-
-## Terminology
-
-### PKI - Public Key Infrastructure
-
-A set of roles, policies, and procedures needed to create, manage, distribute,
-use, store, and revoke digital certificates and manage public-key encryption.
-The purpose of a PKI is to facilitate the secure electronic transfer of
-information for a range of network activities.
-
-### Provisioners
-
-Provisioners are people or code that are registered with the CA and authorized
-to issue "provisioning tokens". Provisioning tokens are single use tokens that
-can be used to authenticate with the CA and get a certificate.
-
-## Getting Started
-
-Demonstrates setting up your own PKI and certificate authority using `step ca`
-and getting certificates using the `step` command line tool and SDK.
-
-![Animated terminal showing step ca init in practice](https://smallstep.com/images/blog/2018-12-04-unfurl.gif)
-
-### Prerequisites
-
-1. [Step CLI](https://github.com/smallstep/cli/blob/master/README.md#installing)
-
-2. [Step CA](#installing)
-
-### Initializing PKI and configuring the Certificate Authority
-
-To initialize a PKI and configure the Step Certificate Authority run:
-
-```
-step ca init
-```
-
-You'll be asked for a name for your PKI. This name will appear in your CA
-certificates. It doesn't really matter what you choose. The name of your
-organization or your project will suffice.
-
-If you run:
-
-```
-tree $(step path)
-```
-
-You should see:
-
-```
-.
-├── certs
-│   ├── intermediate_ca.crt
-│   └── root_ca.crt
-├── config
-│   ├── ca.json
-│   └── defaults.json
-└── secrets
-    ├── intermediate_ca_key
-    └── root_ca_key
-```
-
-The files created include:
-
-* `root_ca.crt` and `root_ca_key`: the root certificate and private key for
-  your PKI
-* `intermediate_ca.crt` and `intermediate_ca_key`: the intermediate certificate
-  and private key that will be used to sign leaf certificates
-* `ca.json`: the configuration file necessary for running the Step CA.
-* `defaults.json`: file containing default parameters for the `step` CA cli
-interface. You can override these values with the appropriate flags or
-environment variables.
-
-All of the files endinging in `_key` are password protected using the password
-you chose during PKI initialization. We advise you to change these passwords
-(using the `step crypto change-pass` utility) if you plan to run your CA in a
-non-development environment.
+[![GitHub release](https://img.shields.io/github/release/smallstep/certificates.svg)](https://github.com/smallstep/certificates/releases)
+[![Join the chat at https://gitter.im/smallstep/community](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/smallstep/community)
+[![CA Image](https://images.microbadger.com/badges/image/smallstep/step-ca.svg)](https://microbadger.com/images/smallstep/step-ca)
+[![Go Report Card](https://goreportcard.com/badge/github.com/smallstep/certificates)](https://goreportcard.com/report/github.com/smallstep/certificates)
+[![Build Status](https://travis-ci.com/smallstep/certificates.svg?branch=master)](https://travis-ci.com/smallstep/certificates)
+[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
+[![CLA assistant](https://cla-assistant.io/readme/badge/smallstep/certificates)](https://cla-assistant.io/smallstep/certificates)
 
-### What's Inside `ca.json`?
+[![GitHub stars](https://img.shields.io/github/stars/smallstep/certificates.svg?style=social)](https://github.com/smallstep/certificates/stargazers)
+[![Twitter followers](https://img.shields.io/twitter/follow/smallsteplabs.svg?label=Follow&style=social)](https://twitter.com/intent/follow?screen_name=smallsteplabs)
 
-`ca.json` is responsible for configuring communication, authorization, and
-default new certificate values for the Step CA. Below is a short list of
-definitions and descriptions of available configuration attributes.
+![Animated terminal showing step certificates in practice](https://github.com/smallstep/certificates/raw/master/docs/images/step-ca-2-legged.gif)
 
-* `root`: location of the root certificate on the filesystem. The root certificate
-is used to mutually authenticate all api clients of the CA.
+## Features
 
-* `crt`: location of the intermediate certificate on the filesystem. The
-intermediate certificate is returned alongside each new certificate,
-allowing the client to complete the certificate chain.
+It's super easy to get started and to operate `step-ca` thanks to [streamlined initialization](https://github.com/smallstep/certificates#lets-get-started) and [safe, sane defaults](https://github.com/smallstep/certificates/blob/master/docs/defaults.md). **Get started in 15 minutes.**
 
-* `key`: location of the intermediate private key on the filesystem. The
-intermediate key signs all new certificates generated by the CA.
+### A private certificate authority you run yourself
 
-* `password`: optionally store the password for decrypting the intermediate private
-key (this should be the same password you chose during PKI initialization). If
-the value is not stored in configuration then you will be prompted for it when
-starting the CA.
+- Issue client and server certificates to VMs, containers, devices, and people using internal hostnames and emails
+- [RFC5280](https://tools.ietf.org/html/rfc5280) and [CA/Browser Forum](https://cabforum.org/baseline-requirements-documents/) compliant certificates that work **for TLS and HTTPS**
+- Choose key types (RSA, ECDSA, EdDSA) & lifetimes to suit your needs
+- [Short-lived certificates](https://smallstep.com/blog/passive-revocation.html) with **fully automated** enrollment, renewal, and revocation
+- Fast, stable, and capable of high availability deployment using [root federation](https://smallstep.com/blog/step-v0.8.3-federation-root-rotation.html) and/or multiple intermediaries
+- Operate as an online intermediate for an existing root CA
+- [Pluggable database backends](https://github.com/smallstep/certificates/blob/master/docs/database.md) for persistence
+- [Helm charts](https://hub.helm.sh/charts/smallstep/step-certificates), [autocert](https://github.com/smallstep/autocert), and [cert-manager integration](https://github.com/smallstep/step-issuer) for kubernetes
 
-* `address`: e.g. `127.0.0.1:8080` - address and port on which the CA will bind
-and respond to requests.
+### Lots of (automatable) ways to get certificates
 
-* `dnsNames`: comma separated list of DNS Name(s) for the CA.
+- [Single sign-on](https://smallstep.com/blog/easily-curl-services-secured-by-https-tls.html) using Okta, GSuite, Active Directory, or any other OAuth OIDC identity provider
+- [Instance identity documents](https://smallstep.com/blog/embarrassingly-easy-certificates-on-aws-azure-gcp/) for VMs on AWS, GCP, and Azure
+- [Single-use short-lived tokens](https://smallstep.com/docs/design-doc.html#jwk-provisioner) issued by your CD tool — Puppet, Chef, Ansible, Terraform, etc.
+- Use an existing certificate from another CA (e.g., using a device certificate like [Twilio's Trust OnBoard](https://www.twilio.com/wireless/trust-onboard)) *coming soon*
 
-* `logger`: the default logging format for the CA is `text`. The other options
-is `json`.
+### [Your own private ACME Server](https://smallstep.com/blog/private-acme-server/)
+- Issue certificates using ACMEv2 ([RFC8555](https://tools.ietf.org/html/rfc8555)), **the protocol used by Let's Encrypt**
+- Great for [using ACME in development & pre-production](https://smallstep.com/blog/private-acme-server/#local-development-pre-production)
+- Supports the `http-01` and `dns-01` ACME challenge types
+- Works with any compliant ACME client including [certbot](https://smallstep.com/blog/private-acme-server/#certbot-uploads-acme-certbot-png-certbot-example), [acme.sh](https://smallstep.com/blog/private-acme-server/#acme-sh-uploads-acme-acme-sh-png-acme-sh-example), [Caddy](https://smallstep.com/blog/private-acme-server/#caddy-uploads-acme-caddy-png-caddy-example), and [traefik](https://smallstep.com/blog/private-acme-server/#traefik-uploads-acme-traefik-png-traefik-example)
+- Get certificates programmatically (e.g., in [Go](https://smallstep.com/blog/private-acme-server/#golang-uploads-acme-golang-png-go-example), [Python](https://smallstep.com/blog/private-acme-server/#python-uploads-acme-python-png-python-example), [Node.js](https://smallstep.com/blog/private-acme-server/#node-js-uploads-acme-node-js-png-node-js-example))
 
-* `tls`: settings for negotiating communication with the CA; includes acceptable
-ciphersuites, min/max TLS version, etc.
+### [SSH Certificates](https://smallstep.com/blog/use-ssh-certificates/)
 
-* `authority`: controls the request authorization and signature processes.
+- Use [certificate authentication for SSH](https://smallstep.com/blog/use-ssh-certificates/): connect SSH to SSO, improve security, and eliminate warnings & errors
+- Issue SSH user certificates using OAuth OIDC
+- Issue SSH host certificates to cloud VMs using instance identity documents
 
-    - `template`: default ASN1DN values for new certificates.
+### Easy certificate management and automation via [`step` CLI](https://github.com/smallstep/cli) [integration](https://smallstep.com/docs/cli/ca/)
 
-    - `claims`: default validation for requested attributes in the certificate request.
-    Can be overriden by similar claims objects defined by individual provisioners.
+- Generate key pairs where they're needed so private keys are never transmitted across the network
+- [Authenticate and obtain a certificate](https://smallstep.com/docs/cli/ca/certificate/) using any enrollment mechanism supported by `step-ca`
+- Securely [distribute root certificates](https://smallstep.com/docs/cli/ca/root/) and [bootstrap](https://smallstep.com/docs/cli/ca/bootstrap/) PKI relying parties
+- [Renew](https://smallstep.com/docs/cli/ca/renew/) and [revoke](https://smallstep.com/docs/cli/ca/revoke/) certificates issued by `step-ca`
+- [Install root certificates](https://smallstep.com/docs/cli/certificate/install/) so your CA is trusted by default (issue development certificates **that [work in browsers](https://smallstep.com/blog/step-v0-8-6-valid-HTTPS-certificates-for-dev-pre-prod.html)**)
+- [Inspect](https://smallstep.com/docs/cli/certificate/inspect/) and [lint](https://smallstep.com/docs/cli/certificate/lint/) certificates
 
-        * `minTLSCertDuration`: do not allow certificates with a duration less
-        than this value.
+## Motivation
 
-        * `maxTLSCertDuration`: do not allow certificates with a duration greater
-        than this value.
+Managing your own *public key infrastructure* (PKI) can be tedious and error
+prone. Good security hygiene is hard. Setting up simple PKI is out of reach for
+many small teams, and following best practices like proper certificate
+revocation and rolling is challenging even for experts.
+
+Amongst numerous use cases, proper PKI makes it easy to use mTLS (mutual TLS)
+to improve security and to make it possible to connect services across the
+public internet. Unlike VPNs & SDNs, deploying and scaling mTLS is pretty
+easy. You're (hopefully) already using TLS, and your existing tools and
+standard libraries will provide most of what you need. If you know how to
+operate DNS and reverse proxies, you know how to operate mTLS
+infrastructure.
 
-        * `defaultTLSCertDuration`: if no certificate validity period is specified,
-        use this value.
+![Connect it all with
+mTLS](https://raw.githubusercontent.com/smallstep/certificates/master/docs/images/connect-with-mtls-2.png)
 
-        * `disableIssuedAtCheck`: disable a check verifying that provisioning
-        tokens must be issued after the CA has booted. This is one prevention
-        against token reuse. The default value is `false`. Do not change this
-        unless you know what you are doing.
+There's just one problem: **you need certificates issued by your own
+certificate authority (CA)**. Building and operating a CA, issuing
+certificates, and making sure they're renewed before they expire is tricky.
+This project provides the infrastructure, automations, and workflows you'll
+need.
 
-    - `provisioners`: list of provisioners. Each provisioner has a `name`,
-    associated public/private keys, and an optional `claims` attribute that will
-    override any values set in the global `claims` directly underneath `authority`.
+`step certificates` is part of smallstep's broader security architecture, which
+makes it much easier to implement good security practices early, and
+incrementally improve them as your system matures.
 
+For more information and [docs](https://smallstep.com/docs) see [the smallstep
+website](https://smallstep.com/certificates) and the [blog
+post](https://smallstep.com/blog/step-certificates.html) announcing this project.
 
-`step ca init` will generate one provisioner. New provisioners can be added by
-running `step ca provisioner add`.
+## Installation Guide
 
-### Running the CA
+These instructions will install an OS specific version of the `step-ca` binary on
+your local machine.
 
-To start the CA run:
+While `step` is not required to run `step-ca`, it will make your life easier so you'll probably want to [install it](https://github.com/smallstep/cli#installation-guide) too.
 
-```
-export STEPPATH=$(step path)
-step-ca $STEPPATH/config/ca.json
-```
+### Mac OS
 
-### Configure Your Environment
+Install `step`  and `step-ca` together via [Homebrew](https://brew.sh/):
 
-**Note**: Configuring your environment is only necessary for remote servers
-(not the server on which the `step ca init` command was originally run).
+<pre><code><b>$ brew install step</b>
 
-Many of the cli utilities under `step ca [sub-command]` interface directly with
-a running instance of the Step CA. The CA exposes an HTTP API and clients are
-required to connect using HTTP over TLS (aka HTTPS). As part of bootstraping the
-Step CA, a certificate was generated using the root of trust that was
-created when you initilialized your PKI. In order to properly validate this
-certificate clients need access to the public root of trust, aka the public
-root certificate. If you are using the Step CLI on the same host where you
-initialized your PKI (the `root_ca.crt` is stored on disk locally), then you
-can continue to setting up a `default.json`, otherwise we will show you
-how to easily download your root certificate in the following step.
+# Test installation ...
+<b>$ step certificate inspect https://smallstep.com</b>
+Certificate:
+    Data:
+        Version: 3 (0x2)
+        Serial Number: 326381749415081530968054238478851085504954 (0x3bf265673332db2d0c70e48a163fb7d11ba)
+    Signature Algorithm: SHA256-RSA
+        Issuer: C=US,O=Let's Encrypt,CN=Let's Encrypt Authority X3
+...</code></pre>
 
-#### Download the Root Certificate
+> Note: If you have installed `step` previously through the `smallstep/smallstep`
+> tap you will need to run the following commands before installing:
+> 
+> ```
+> $ brew untap smallstep/smallstep
+> $ brew uninstall step
+> ```
 
-The next few steps are a guide for downloading the root certificate of your PKI
-from a running instance of the CA. First we'll define two servers:
+### Linux
 
-* **remote server**: This is the server where the Step CA is running. This may
-also be the server where you initialized your PKI, but for security reasons
-you may have done that offline.
+#### Debian
 
-* **local server**: This is the server that wants access to the `step ca [sub-command]`
+1. [Optional] Install `step`.
 
-* **ca-url**: This is the url at which the CA is listening for requests. This
-should be a combination of the DNS name and port entered during PKI initialization.
-In the examples below we will use `https://ca.smallstep.com:8080`.
+    Download the latest Debian package from
+    [`step` releases](https://github.com/smallstep/cli/releases):
 
-1. Get the Fingerprint.
+    ```
+    $ wget https://github.com/smallstep/cli/releases/download/X.Y.Z/step_X.Y.Z_amd64.deb
+    ```
 
-    From the **remote server**:
+    Install the Debian package:
 
     ```
-    $ FP=$(step certificate fingerprint $(step path)/certs/root_ca.crt)
+    $ sudo dpkg -i step_X.Y.Z_amd64.deb
     ```
 
-2. Bootstrap your environment.
+2. Install `step-ca`.
 
-    From the **local server**:
+    Download the latest Debian package from [releases](https://github.com/smallstep/certificates/releases):
 
     ```
-    $ step ca bootstrap --fingerprint $FP --ca-url "https://ca.smallstep.com:8080"
-    $ cat $(step path)/config/defaults.json
+    $ wget https://github.com/smallstep/certificates/releases/download/X.Y.Z/step-certificates_X.Y.Z_amd64.deb
     ```
 
-3. Test.
+    Install the Debian package:
 
     ```
-    * step ca health
+    $ sudo dpkg -i step-certificates_X.Y.Z_amd64.deb
     ```
 
-#### Setting up Environment Defaults
-This is optional, but we recommend you populate a `defaults.json` file with a
-few variables that will make your command line experience much more pleasant.
+#### Arch Linux
 
-You can do this manually or with the step command `step ca bootstrap`:
+We are using the [Arch User Repository](https://aur.archlinux.org) to distribute
+`step` binaries for Arch Linux.
 
-```
-$ step ca bootstrap \
-  --ca-url https://ca.smallstep.com:8080 \
-  --fingerprint 0d7d3834cf187726cf331c40a31aa7ef6b29ba4df601416c9788f6ee01058cf3
-# Let's see what we got...
-$ cat $STEPPATH/config/defaults.json
-{
-  "ca-url": "https://ca.smallstep.com:8080",
-  "fingerprint": "628cfc85090ca65bb246d224f1217445be155cfc6167db4ed8f1b0e3de1447c5",
-  "root": "/Users/<you>/src/github.com/smallstep/step/.step/certs/root_ca.crt"
-}
-# Test it out
-$ step ca health
-```
+* [Optional] The `step` binary tarball can be found [here](https://aur.archlinux.org/packages/step-cli-bin/).
+* The `step-ca` binary tarball can be found [here](https://aur.archlinux.org/packages/step-ca-bin/).
 
-* **ca-url** is the DNS name and port that you used when initializing the CA.
+You can use [pacman](https://www.archlinux.org/pacman/) to install the packages.
 
-* **root** is the path to the root certificate on the file system.
+### Kubernetes
 
-* **fingerprint** is the root certificate fingerprint (SHA256).
+We publish [helm charts](https://hub.helm.sh/charts/smallstep/step-certificates) for easy installation on kubernetes:
 
-You can always override these values with command-line flags or environment
-variables.
+```
+helm install step-certificates
+```
 
-To manage the CA provisioners you can also add the property **ca-config** with
-the path to the CA configuration file, with that property you won't need to add
-it in commands like `step ca provisioners [add|remove]`.
-**Note**: to manage provisioners you must be on the host on which the CA is
-running. You need direct access to the `ca.json` file.
+> <a href="https://github.com/smallstep/autocert"><img width="25%" src="https://raw.githubusercontent.com/smallstep/autocert/master/autocert-logo.png"></a>
+>
+> If you're using Kubernetes, make sure you [check out
+> autocert](https://github.com/smallstep/autocert): a kubernetes add-on that builds on `step
+> certificates` to automatically inject TLS/HTTPS certificates into your containers.
 
-### Hot Reload
+### Test
 
-It is important that the CA be able to handle configuration changes with no downtime.
-Our CA has a built in `reload` function allowing it to:
+<pre><code><b>$ step version</b>
+Smallstep CLI/0.10.0 (darwin/amd64)
+Release Date: 2019-04-30 19:01 UTC
 
-1. Finish processing existing connections while blocking new ones.
-2. Parse the configuration file and re-initialize the API.
-3. Begin accepting blocked and new connections.
+<b>$ step-ca version</b>
+Smallstep CA/0.10.0 (darwin/amd64)
+Release Date: 2019-04-30 19:02 UTC</code></pre>
 
-`reload` is triggered by sending a SIGHUP to the PID (see `man kill`
-for your OS) of the Step CA process. A few important details to note when using `reload`:
+## Quickstart
 
-* The location of the modified configuration must be in the same location as it
-was in the original invocation of `step-ca`. So, if the original command was
+In the following guide we'll run a simple `hello` server that requires clients
+to connect over an authorized and encrypted channel using HTTPS. `step-ca`
+will issue certificates to our server, allowing it to authenticate and encrypt
+communication. Let's get started!
 
-```
-$ step-ca ./.step/config/ca.json
-```
+### Prerequisites
 
-then, upon `reload`, the Step CA will read it's new configuration from the same
-configuration file.
+* [`step`](#installation-guide)
+* [golang](https://golang.org/doc/install)
 
-* Step CA requires the password to decrypt the intermediate certificate, again,
-upon `reload`. You can automate this in one of two ways:
+### Let's get started!
 
-    * Use the `--password-file` flag in the original invocation.
-    * Use the top level `password` attribute in the `ca.json` configuration file.
+#### 1. Run `step ca init` to create your CA's keys & certificates and configure `step-ca`:
 
-### Let's issue a certificate!
+<pre><code><b>$ step ca init</b>
+✔ What would you like to name your new PKI? (e.g. Smallstep): <b>Example Inc.</b>
+✔ What DNS names or IP addresses would you like to add to your new CA? (e.g. ca.smallstep.com[,1.1.1.1,etc.]): <b>localhost</b>
+✔ What address will your new CA listen at? (e.g. :443): <b>127.0.0.1:8080</b>
+✔ What would you like to name the first provisioner for your new CA? (e.g. you@smallstep.com): <b>bob@example.com</b>
+✔ What do you want your password to be? [leave empty and we'll generate one]: <b>abc123</b>
 
-There are two steps to issuing a certificate at the command line:
+Generating root certificate...
+all done!
 
-1. Generate a provisioning token using your provisioning credentials.
-2. Generate a CSR and exchange it, along with the provisioning token, for a certificate.
+Generating intermediate certificate...
+all done!
 
-If you would like to generate a certificate from the command line, the Step CLI
-provides a single command that will prompt you to select and decrypt an
-authorized provisioner and then request a new certificate.
+✔ Root certificate: /Users/bob/src/github.com/smallstep/step/.step/certs/root_ca.crt
+✔ Root private key: /Users/bob/src/github.com/smallstep/step/.step/secrets/root_ca_key
+✔ Root fingerprint: 702a094e239c9eec6f0dcd0a5f65e595bf7ed6614012825c5fe3d1ae1b2fd6ee
+✔ Intermediate certificate: /Users/bob/src/github.com/smallstep/step/.step/certs/intermediate_ca.crt
+✔ Intermediate private key: /Users/bob/src/github.com/smallstep/step/.step/secrets/intermediate_ca_key
+✔ Default configuration: /Users/bob/src/github.com/smallstep/step/.step/config/defaults.json
+✔ Certificate Authority configuration: /Users/bob/src/github.com/smallstep/step/.step/config/ca.json
 
-```
-$ step ca certificate "foo.example.com" foo.crt foo.key
-```
+Your PKI is ready to go. To generate certificates for individual services see 'step help ca'.</code></pre>
 
-If you would like to generate certificates on demand from an automated
-configuration management solution (no user input) you would split the above flow
-into two commands.
+This command will:
 
-```
-$ TOKEN=$(step ca token foo.example.com \
-    --kid 4vn46fbZT68Uxfs9LBwHkTvrjEvxQqx-W8nnE-qDjts \
-    --ca-url https://ca.example.com \
-    --root /path/to/root_ca.crt  --password-file /path/to/provisioner/password)
+- Generate [password protected](https://github.com/smallstep/certificates/blob/master/docs/GETTING_STARTED.md#passwords)  private keys for your CA to sign certificates
+- Generate a root and [intermediate signing certificate](https://security.stackexchange.com/questions/128779/why-is-it-more-secure-to-use-intermediate-ca-certificates) for your CA
+- Create a JSON configuration file for `step-ca` (see [getting started](./docs/GETTING_STARTED.md) for details)
 
-$ step ca certificate "foo.example.com" foo.crt foo.key --token "$TOKEN"
-```
-
-You can take a closer look at the contents of the certificate using `step certificate inspect`:
+You can find these artifacts in `$STEPPATH` (or `~/.step` by default).
 
-```
-$ step certificate inspect foo.crt
-```
+#### 2. Start `step-ca`:
 
-### List|Add|Remove Provisioners
+You'll be prompted for your password from the previous step, to decrypt the CA's private signing key:
 
-The Step CA configuration is initialized with one provisioner; one entity
-that is authorized by the CA to generate provisioning tokens for new certificates.
-We encourage you to have many provisioners - ideally one for each entity in your
-infrastructure.
+<pre><code><b>$ step-ca $(step path)/config/ca.json</b>
+Please enter the password to decrypt /Users/bob/src/github.com/smallstep/step/.step/secrets/intermediate_ca_key: <b>abc123</b>
+2019/02/18 13:28:58 Serving HTTPS on 127.0.0.1:8080 ...</code></pre>
 
-**Why should I be using multiple provisioners?**
-
-* Each certificate generated by the Step CA contains the ID of the provisioner
-that issued the *provisioning token* authorizing the creation of the cert. This
-ID is stored in the X.509 ExtraExtensions of the certificate under
-`OID: 1.3.6.1.4.1.37476.9000.64.1` and can be inspected by running `step
-certificate inspect foo.crt`. These IDs can and should be used to debug and
-gather information about the origin of a certificate. If every member of your
-ops team and the configuration management tools all use the same provisioner
-to authorize new certificates you lose valuable visibility into the workings
-of your PKI.
-* Each provisioner should require a **unique** password to decrypt it's private key
--- we can generate unique passwords for you but we can't force you to use them.
-If you only have one provisioner then every entity in the infrastructure will
-need access to that one password. Jim from your dev ops team should not be using
-the same provisioner/password combo to authorize certificates for debugging as
-Chef is for your CICD - no matter how trustworthy Jim says he is.
-
-Let's begin by listing the existing provisioners:
+#### 3. Copy our `hello world` golang server.
 
 ```
-$ bin/step ca provisioner list
-```
+$ cat > srv.go <<EOF
+package main
 
-Now let's add a provisioner for Jim.
+import (
+    "net/http"
+    "log"
+)
 
-```
-$ bin/step ca provisioner add jim@smallstep.com --create
+func HiHandler(w http.ResponseWriter, req *http.Request) {
+    w.Header().Set("Content-Type", "text/plain")
+    w.Write([]byte("Hello, world!\n"))
+}
+
+func main() {
+    http.HandleFunc("/hi", HiHandler)
+    err := http.ListenAndServeTLS(":8443", "srv.crt", "srv.key", nil)
+    if err != nil {
+        log.Fatal(err)
+    }
+}
+EOF
 ```
 
-**NOTE**: This change will not affect the Step CA until a `reload` is forced by
-sending a SIGHUP signal to the process.
+#### 4. Get an identity for your server from the Step CA.
 
-List the provisioners again and you will see that nothing has changed.
+<pre><code><b>$ step ca certificate localhost srv.crt srv.key</b>
+✔ Key ID: rQxROEr7Kx9TNjSQBTETtsu3GKmuW9zm02dMXZ8GUEk (bob@example.com)
+✔ Please enter the password to decrypt the provisioner key: abc123
+✔ CA: https://localhost:8080/1.0/sign
+✔ Certificate: srv.crt
+✔ Private Key: srv.key
 
-```
-$ bin/step ca provisioner list
-```
+<b>$ step certificate inspect --bundle srv.crt</b>
+Certificate:
+    Data:
+        Version: 3 (0x2)
+        Serial Number: 140439335711218707689123407681832384336 (0x69a7a1d7f6f22f68059d2d9088307750)
+    Signature Algorithm: ECDSA-SHA256
+        Issuer: CN=Example Inc. Intermediate CA
+        Validity
+            Not Before: Feb 18 21:32:35 2019 UTC
+            Not After : Feb 19 21:32:35 2019 UTC
+        Subject: CN=localhost
+...
+Certificate:
+    Data:
+        Version: 3 (0x2)
+        Serial Number: 207035091234452090159026162349261226844 (0x9bc18217bd560cf07db23178ed90835c)
+    Signature Algorithm: ECDSA-SHA256
+        Issuer: CN=Example Inc. Root CA
+        Validity
+            Not Before: Feb 18 21:27:21 2019 UTC
+            Not After : Feb 15 21:27:21 2029 UTC
+        Subject: CN=Example Inc. Intermediate CA
+...</code></pre>
 
-Now let's `reload` the CA. You will need to re-enter your intermediate
-password unless it's in your `ca.json` or your are using `--password-file`.
+Note that `step` and `step-ca` handle details like [certificate bundling](https://smallstep.com/blog/everything-pki.html#intermediates-chains-and-bundling) for you.
 
-```
-$ ps aux | grep step-ca   # to get the PID
-$ kill -1 <pid>
-```
+#### 5. Run the simple server.
 
-Once the CA is running again, list the provisioners, again.
+<pre><code><b>$ go run srv.go &</b></code></pre>
 
-```
-$ bin/step ca provisioner list
-```
+#### 6. Get the root certificate from the Step CA.
 
-Boom! Magic.
-Now suppose Jim forgets his password ('come on Jim!'), and he'd like to remove
-his old provisioner. Get the `kid` (Key ID) of Jim's provisioner by listing
-the provisioners and finding the appropriate one. Then run:
+In a new Terminal window:
 
-```
-$ bin/step ca provisioner remove jim@smallstep.com --kid <kid>
-```
+<pre><code><b>$ step ca root root.crt</b>
+The root certificate has been saved in root.crt.</code></pre>
 
-Then `reload` the CA and verify that Jim's provisioner is no longer returned
-in the provisioner list.
+#### 7. Make an authenticated, encrypted curl request to your server using HTTP over TLS.
 
-We can also remove all of Jim's provisioners, supposing Jim forgot all the passwords
-('really Jim?'), by running the following:
+<pre><code><b>$ curl --cacert root.crt https://localhost:8443/hi</b>
+Hello, world!</code></pre>
 
-```
-$ bin/step ca provisioner remove jim@smallstep.com --all
-```
-
-The same entity may have multiple provisioners for authorizing different
-types of certs. Each of these provisioners must have unique keys.
+*All Done!*
 
-## Notes on Securing the Step CA and your PKI.
+Check out the [Getting Started](./docs/GETTING_STARTED.md) guide for more examples
+and best practices on running Step CA in production.
 
-In this section we recommend a few best practices when it comes to
-running, deploying, and managing your own online CA and PKI. Security is a moving
-target and we expect out recommendations to change and evolve as well.
+## Documentation
 
-### Initializing your PKI
+Documentation can be found in a handful of different places:
 
-When you initialize your PKI two private keys are generated; one intermediate
-private key and one root private key. It is very important that these private keys
-are kept secret. The root private key should be moved around as little as possible,
-preferably not all - meaning it never leaves the server on which it was created.
+1. The [docs](./docs/README.md) sub-repo has an index of documentation and tutorials.
 
-### Passwords
+2. On the command line with `step ca help xxx` where `xxx` is the subcommand
+you are interested in. Ex: `step help ca provisioners list`.
 
-When you intialize your PKI (`step ca init`) the root and intermediate
-private keys will be encrypted with the same password. We recommend that you
-change the password with which the intermediate was encrypted at your earliest
-convenience.
+3. On the web at https://smallstep.com/docs/certificates.
 
-```
-$ step crypto change-pass $STEPPATH/secrets/intermediate_ca_key
-```
+4. On your browser by running `step help --http=:8080 ca` from the command line
+and visiting http://localhost:8080.
 
-Once you've changed the intermediate private key password you should never have
-to use the root private key password again.
-
-We encourage users to always use a password manager to generate random passwords
-or let Step CLI generate passwords for you.
-
-The next important matter is how your passwords are stored. We recommend using a
-[password manager](https://en.wikipedia.org/wiki/List_of_password_managers).
-There are many to choose from and the choice will depend on the risk & security
-profile of your organization.
-
-In addition to using a password manager to store all passwords (private key,
-provisioner, etc.) we recommend using a threshold cryptography algorithm like
-[Shamir's Secret Sharing](https://en.wikipedia.org/wiki/Shamir's_Secret_Sharing)
-to divide the root private key across a handful of trusted parties.
-
-### Provisioners
-
-When you intialize your PKI (`step ca init`) a default provisioner will be created
-and it's private key will be encrypted using the same password used to encrypt
-the root private key. Before deploying the Step CA you should remove this
-provisioner and add new ones that are encrypted with new, secure, random passwords.
-See the section on [managing provisioners](#listaddremove-provisioners).
-
-### Deploying
-
-* Refrain from entering passwords for private keys or provisioners on the command line.
-Use the `--password-file` flag whenever possible.
-* Run the Step CA as a new user and make sure that the config files, private keys,
-and passwords used by the CA are stored in such a way that only this new user
-has permissions to read and write them.
-* Use short lived certificates. Our default validity period for new certificates
-is 24 hours. You can configure this value in the `ca.json` file. Shorter is
-better - less time to form an attack.
-* Short lived certificates are **not** a replacement for CRL and OCSP. CRL and OCSP
-are features that we plan to implement, but are not yet available. In the mean
-time short lived certificates are a decent alternative.
-* Keep your hosts secure by enforcing AuthN and AuthZ for every connection. SSH
-access is a big one.
 
 ## The Future
 
@@ -538,16 +361,7 @@ help solve problems in this space.
 * Tell us what features you'd like to see - open issues or hit us on
 [Twitter](https://twitter.com/smallsteplabs).
 
-## Versioning
-
-We use [SemVer](http://semver.org/) for versioning. For the versions available,
-see the [tags on this repository](https://github.com/smallstep/cli).
-
-## License
+## Further Reading
 
-This project is licensed under the Apache 2.0 License - see the
-[LICENSE](./LICENSE) file for details
-
-### Individual Contributor License
-
-[![CLA assistant](https://cla-assistant.io/readme/badge/smallstep/certificates)](https://cla-assistant.io/smallstep/certificates)
+Check out the [Getting Started](https://smallstep.com/docs/getting-started/) guide for more examples
+and best practices on running Step CA in production.

+ 214 - 0
acme/account.go

@@ -0,0 +1,214 @@
+package acme
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+)
+
+// Account is a subset of the internal account type containing only those
+// attributes required for responses in the ACME protocol.
+type Account struct {
+	Contact []string         `json:"contact,omitempty"`
+	Status  string           `json:"status"`
+	Orders  string           `json:"orders"`
+	ID      string           `json:"-"`
+	Key     *jose.JSONWebKey `json:"-"`
+}
+
+// ToLog enables response logging.
+func (a *Account) ToLog() (interface{}, error) {
+	b, err := json.Marshal(a)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling account for logging"))
+	}
+	return string(b), nil
+}
+
+// GetID returns the account ID.
+func (a *Account) GetID() string {
+	return a.ID
+}
+
+// GetKey returns the JWK associated with the account.
+func (a *Account) GetKey() *jose.JSONWebKey {
+	return a.Key
+}
+
+// IsValid returns true if the Account is valid.
+func (a *Account) IsValid() bool {
+	return a.Status == StatusValid
+}
+
+// AccountOptions are the options needed to create a new ACME account.
+type AccountOptions struct {
+	Key     *jose.JSONWebKey
+	Contact []string
+}
+
+// account represents an ACME account.
+type account struct {
+	ID          string           `json:"id"`
+	Created     time.Time        `json:"created"`
+	Deactivated time.Time        `json:"deactivated"`
+	Key         *jose.JSONWebKey `json:"key"`
+	Contact     []string         `json:"contact,omitempty"`
+	Status      string           `json:"status"`
+}
+
+// newAccount returns a new acme account type.
+func newAccount(db nosql.DB, ops AccountOptions) (*account, error) {
+	id, err := randID()
+	if err != nil {
+		return nil, err
+	}
+
+	a := &account{
+		ID:      id,
+		Key:     ops.Key,
+		Contact: ops.Contact,
+		Status:  "valid",
+		Created: clock.Now(),
+	}
+	return a, a.saveNew(db)
+}
+
+// toACME converts the internal Account type into the public acmeAccount
+// type for presentation in the ACME protocol.
+func (a *account) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Account, error) {
+	return &Account{
+		Status:  a.Status,
+		Contact: a.Contact,
+		Orders:  dir.getLink(OrdersByAccountLink, URLSafeProvisionerName(p), true, a.ID),
+		Key:     a.Key,
+		ID:      a.ID,
+	}, nil
+}
+
+// save writes the Account to the DB.
+// If the account is new then the necessary indices will be created.
+// Else, the account in the DB will be updated.
+func (a *account) saveNew(db nosql.DB) error {
+	kid, err := keyToID(a.Key)
+	if err != nil {
+		return err
+	}
+	kidB := []byte(kid)
+
+	// Set the jwkID -> acme account ID index
+	_, swapped, err := db.CmpAndSwap(accountByKeyIDTable, kidB, nil, []byte(a.ID))
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrap(err, "error setting key-id to account-id index"))
+	case !swapped:
+		return ServerInternalErr(errors.Errorf("key-id to account-id index already exists"))
+	default:
+		if err = a.save(db, nil); err != nil {
+			db.Del(accountByKeyIDTable, kidB)
+			return err
+		}
+		return nil
+	}
+}
+
+func (a *account) save(db nosql.DB, old *account) error {
+	var (
+		err  error
+		oldB []byte
+	)
+	if old == nil {
+		oldB = nil
+	} else {
+		if oldB, err = json.Marshal(old); err != nil {
+			return ServerInternalErr(errors.Wrap(err, "error marshaling old acme order"))
+		}
+	}
+
+	b, err := json.Marshal(*a)
+	if err != nil {
+		return errors.Wrap(err, "error marshaling new account object")
+	}
+	// Set the Account
+	_, swapped, err := db.CmpAndSwap(accountTable, []byte(a.ID), oldB, b)
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrap(err, "error storing account"))
+	case !swapped:
+		return ServerInternalErr(errors.New("error storing account; " +
+			"value has changed since last read"))
+	default:
+		return nil
+	}
+}
+
+// update updates the acme account object stored in the database if,
+// and only if, the account has not changed since the last read.
+func (a *account) update(db nosql.DB, contact []string) (*account, error) {
+	b := *a
+	b.Contact = contact
+	if err := b.save(db, a); err != nil {
+		return nil, err
+	}
+	return &b, nil
+}
+
+// deactivate deactivates the acme account.
+func (a *account) deactivate(db nosql.DB) (*account, error) {
+	b := *a
+	b.Status = StatusDeactivated
+	b.Deactivated = clock.Now()
+	if err := b.save(db, a); err != nil {
+		return nil, err
+	}
+	return &b, nil
+}
+
+// getAccountByID retrieves the account with the given ID.
+func getAccountByID(db nosql.DB, id string) (*account, error) {
+	ab, err := db.Get(accountTable, []byte(id))
+	if err != nil {
+		if nosql.IsErrNotFound(err) {
+			return nil, MalformedErr(errors.Wrapf(err, "account %s not found", id))
+		}
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading account %s", id))
+	}
+
+	a := new(account)
+	if err = json.Unmarshal(ab, a); err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling account"))
+	}
+	return a, nil
+}
+
+// getAccountByKeyID retrieves Id associated with the given Kid.
+func getAccountByKeyID(db nosql.DB, kid string) (*account, error) {
+	id, err := db.Get(accountByKeyIDTable, []byte(kid))
+	if err != nil {
+		if nosql.IsErrNotFound(err) {
+			return nil, MalformedErr(errors.Wrapf(err, "account with key id %s not found", kid))
+		}
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading key-account index"))
+	}
+	return getAccountByID(db, string(id))
+}
+
+// getOrderIDsByAccount retrieves a list of Order IDs that were created by the
+// account.
+func getOrderIDsByAccount(db nosql.DB, id string) ([]string, error) {
+	b, err := db.Get(ordersByAccountIDTable, []byte(id))
+	if err != nil {
+		if nosql.IsErrNotFound(err) {
+			return []string{}, nil
+		}
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading orderIDs for account %s", id))
+	}
+	var orderIDs []string
+	if err := json.Unmarshal(b, &orderIDs); err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error unmarshaling orderIDs for account %s", id))
+	}
+	return orderIDs, nil
+}

+ 844 - 0
acme/account_test.go

@@ -0,0 +1,844 @@
+package acme
+
+import (
+	"encoding/json"
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+var (
+	defaultDisableRenewal   = false
+	globalProvisionerClaims = provisioner.Claims{
+		MinTLSDur:      &provisioner.Duration{Duration: 5 * time.Minute},
+		MaxTLSDur:      &provisioner.Duration{Duration: 24 * time.Hour},
+		DefaultTLSDur:  &provisioner.Duration{Duration: 24 * time.Hour},
+		DisableRenewal: &defaultDisableRenewal,
+	}
+)
+
+func newProv() provisioner.Interface {
+	// Initialize provisioners
+	p := &provisioner.ACME{
+		Type: "ACME",
+		Name: "test@acme-provisioner.com",
+	}
+	if err := p.Init(provisioner.Config{Claims: globalProvisionerClaims}); err != nil {
+		fmt.Printf("%v", err)
+	}
+	return p
+}
+
+func newAcc() (*account, error) {
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	if err != nil {
+		return nil, err
+	}
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return nil, true, nil
+		},
+	}
+	return newAccount(mockdb, AccountOptions{
+		Key: jwk, Contact: []string{"foo", "bar"},
+	})
+}
+
+func TestGetAccountByID(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		acc *account
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/not-found": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				id:  acc.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("account %s not found: not found", acc.ID)),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				id:  acc.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error loading account %s: force", acc.ID)),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				id:  acc.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						return nil, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error unmarshaling account: unexpected end of JSON input")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				id:  acc.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						return b, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acc, err := getAccountByID(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.acc.ID, acc.ID)
+					assert.Equals(t, tc.acc.Status, acc.Status)
+					assert.Equals(t, tc.acc.Created, acc.Created)
+					assert.Equals(t, tc.acc.Deactivated, acc.Deactivated)
+					assert.Equals(t, tc.acc.Contact, acc.Contact)
+					assert.Equals(t, tc.acc.Key.KeyID, acc.Key.KeyID)
+				}
+			}
+		})
+	}
+}
+
+func TestGetAccountByKeyID(t *testing.T) {
+	type test struct {
+		kid string
+		db  nosql.DB
+		acc *account
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/kid-not-found": func(t *testing.T) test {
+			return test{
+				kid: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("account with key id foo not found: not found")),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			return test{
+				kid: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading key-account index: force")),
+			}
+		},
+		"fail/getAccount-error": func(t *testing.T) test {
+			count := 0
+			return test{
+				kid: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						if count == 0 {
+							assert.Equals(t, bucket, accountByKeyIDTable)
+							assert.Equals(t, key, []byte("foo"))
+							count++
+							return []byte("bar"), nil
+						}
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading account bar: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			count := 0
+			return test{
+				kid: acc.Key.KeyID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						var ret []byte
+						switch count {
+						case 0:
+							assert.Equals(t, bucket, accountByKeyIDTable)
+							assert.Equals(t, key, []byte(acc.Key.KeyID))
+							ret = []byte(acc.ID)
+						case 1:
+							assert.Equals(t, bucket, accountTable)
+							assert.Equals(t, key, []byte(acc.ID))
+							ret = b
+						}
+						count++
+						return ret, nil
+					},
+				},
+				acc: acc,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acc, err := getAccountByKeyID(tc.db, tc.kid); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.acc.ID, acc.ID)
+					assert.Equals(t, tc.acc.Status, acc.Status)
+					assert.Equals(t, tc.acc.Created, acc.Created)
+					assert.Equals(t, tc.acc.Deactivated, acc.Deactivated)
+					assert.Equals(t, tc.acc.Contact, acc.Contact)
+					assert.Equals(t, tc.acc.Key.KeyID, acc.Key.KeyID)
+				}
+			}
+		})
+	}
+}
+
+func TestGetAccountIDsByAccount(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		res []string
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok/not-found": func(t *testing.T) test {
+			return test{
+				id: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				res: []string{},
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			return test{
+				id: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading orderIDs for account foo: force")),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			return test{
+				id: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte("foo"))
+						return nil, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error unmarshaling orderIDs for account foo: unexpected end of JSON input")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			oids := []string{"foo", "bar", "baz"}
+			b, err := json.Marshal(oids)
+			assert.FatalError(t, err)
+			return test{
+				id: "foo",
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte("foo"))
+						return b, nil
+					},
+				},
+				res: oids,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if oids, err := getOrderIDsByAccount(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.res, oids)
+				}
+			}
+		})
+	}
+}
+
+func TestAccountToACME(t *testing.T) {
+	dir := newDirectory("ca.smallstep.com", "acme")
+	prov := newProv()
+
+	type test struct {
+		acc *account
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{acc: acc}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			acmeAccount, err := tc.acc.toACME(nil, dir, prov)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, acmeAccount.ID, tc.acc.ID)
+					assert.Equals(t, acmeAccount.Status, tc.acc.Status)
+					assert.Equals(t, acmeAccount.Contact, tc.acc.Contact)
+					assert.Equals(t, acmeAccount.Key.KeyID, tc.acc.Key.KeyID)
+					assert.Equals(t, acmeAccount.Orders,
+						fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s/orders", URLSafeProvisionerName(prov), tc.acc.ID))
+				}
+			}
+		})
+	}
+}
+
+func TestAccountSave(t *testing.T) {
+	type test struct {
+		acc, old *account
+		db       nosql.DB
+		err      *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/old-nil/swap-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+		"fail/old-nil/swap-false": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return []byte("foo"), false, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing account; value has changed since last read")),
+			}
+		},
+		"ok/old-nil": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, nil)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, []byte(acc.ID), key)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/old-not-nil": func(t *testing.T) test {
+			oldAcc, err := newAcc()
+			assert.FatalError(t, err)
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+
+			oldb, err := json.Marshal(oldAcc)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				old: oldAcc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, b)
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, []byte(acc.ID), key)
+						return []byte("foo"), true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.acc.save(tc.db, tc.old); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestAccountSaveNew(t *testing.T) {
+	type test struct {
+		acc *account
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/keyToID-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			acc.Key.Key = "foo"
+			return test{
+				acc: acc,
+				err: ServerInternalErr(errors.New("error generating jwk thumbprint: square/go-jose: unknown key type 'string'")),
+			}
+		},
+		"fail/swap-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			kid, err := keyToID(acc.Key)
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountByKeyIDTable)
+						assert.Equals(t, key, []byte(kid))
+						assert.Equals(t, old, nil)
+						assert.Equals(t, newval, []byte(acc.ID))
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error setting key-id to account-id index: force")),
+			}
+		},
+		"fail/swap-false": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			kid, err := keyToID(acc.Key)
+			assert.FatalError(t, err)
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountByKeyIDTable)
+						assert.Equals(t, key, []byte(kid))
+						assert.Equals(t, old, nil)
+						assert.Equals(t, newval, []byte(acc.ID))
+						return nil, false, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("key-id to account-id index already exists")),
+			}
+		},
+		"fail/save-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			kid, err := keyToID(acc.Key)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			count := 0
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 0 {
+							assert.Equals(t, bucket, accountByKeyIDTable)
+							assert.Equals(t, key, []byte(kid))
+							assert.Equals(t, old, nil)
+							assert.Equals(t, newval, []byte(acc.ID))
+							count++
+							return nil, true, nil
+						}
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, nil)
+						assert.Equals(t, newval, b)
+						return nil, false, errors.New("force")
+					},
+					MDel: func(bucket, key []byte) error {
+						assert.Equals(t, bucket, accountByKeyIDTable)
+						assert.Equals(t, key, []byte(kid))
+						return nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			kid, err := keyToID(acc.Key)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			count := 0
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 0 {
+							assert.Equals(t, bucket, accountByKeyIDTable)
+							assert.Equals(t, key, []byte(kid))
+							assert.Equals(t, old, nil)
+							assert.Equals(t, newval, []byte(acc.ID))
+							count++
+							return nil, true, nil
+						}
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, nil)
+						assert.Equals(t, newval, b)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.acc.saveNew(tc.db); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestAccountUpdate(t *testing.T) {
+	type test struct {
+		acc     *account
+		contact []string
+		db      nosql.DB
+		res     []byte
+		err     *Error
+	}
+	contact := []string{"foo", "bar"}
+	tests := map[string]func(t *testing.T) test{
+		"fail/save-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			_acc := *acc
+			clone := &_acc
+			clone.Contact = contact
+			b, err := json.Marshal(clone)
+			assert.FatalError(t, err)
+			return test{
+				acc:     acc,
+				contact: contact,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, b)
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			_acc := *acc
+			clone := &_acc
+			clone.Contact = contact
+			b, err := json.Marshal(clone)
+			assert.FatalError(t, err)
+			return test{
+				acc:     acc,
+				contact: contact,
+				res:     b,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, b)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			acc, err := tc.acc.update(tc.db, tc.contact)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					b, err := json.Marshal(acc)
+					assert.FatalError(t, err)
+					assert.Equals(t, b, tc.res)
+				}
+			}
+		})
+	}
+}
+
+func TestAccountDeactivate(t *testing.T) {
+	type test struct {
+		acc *account
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/save-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, oldb)
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			return test{
+				acc: acc,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						assert.Equals(t, old, oldb)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			acc, err := tc.acc.deactivate(tc.db)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, acc.ID, tc.acc.ID)
+					assert.Equals(t, acc.Contact, tc.acc.Contact)
+					assert.Equals(t, acc.Status, StatusDeactivated)
+					assert.Equals(t, acc.Key.KeyID, tc.acc.Key.KeyID)
+					assert.Equals(t, acc.Created, tc.acc.Created)
+
+					assert.True(t, acc.Deactivated.Before(time.Now().Add(time.Minute)))
+					assert.True(t, acc.Deactivated.After(time.Now().Add(-time.Minute)))
+				}
+			}
+		})
+	}
+}
+
+func TestNewAccount(t *testing.T) {
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	assert.FatalError(t, err)
+	kid, err := keyToID(jwk)
+	assert.FatalError(t, err)
+	ops := AccountOptions{
+		Key:     jwk,
+		Contact: []string{"foo", "bar"},
+	}
+	type test struct {
+		ops AccountOptions
+		db  nosql.DB
+		err *Error
+		id  *string
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/store-error": func(t *testing.T) test {
+			return test{
+				ops: ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error setting key-id to account-id index: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var _id string
+			id := &_id
+			count := 0
+			return test{
+				ops: ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						switch count {
+						case 0:
+							assert.Equals(t, bucket, accountByKeyIDTable)
+							assert.Equals(t, key, []byte(kid))
+						case 1:
+							assert.Equals(t, bucket, accountTable)
+							*id = string(key)
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				id: id,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			acc, err := newAccount(tc.db, tc.ops)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, acc.ID, *tc.id)
+					assert.Equals(t, acc.Status, StatusValid)
+					assert.Equals(t, acc.Contact, ops.Contact)
+					assert.Equals(t, acc.Key.KeyID, ops.Key.KeyID)
+
+					assert.True(t, acc.Deactivated.IsZero())
+
+					assert.True(t, acc.Created.Before(time.Now().UTC().Add(time.Minute)))
+					assert.True(t, acc.Created.After(time.Now().UTC().Add(-1*time.Minute)))
+				}
+			}
+		})
+	}
+}

+ 213 - 0
acme/api/account.go

@@ -0,0 +1,213 @@
+package api
+
+import (
+	"encoding/json"
+	"net/http"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/api"
+	"github.com/smallstep/certificates/logging"
+)
+
+// NewAccountRequest represents the payload for a new account request.
+type NewAccountRequest struct {
+	Contact              []string `json:"contact"`
+	OnlyReturnExisting   bool     `json:"onlyReturnExisting"`
+	TermsOfServiceAgreed bool     `json:"termsOfServiceAgreed"`
+}
+
+func validateContacts(cs []string) error {
+	for _, c := range cs {
+		if len(c) == 0 {
+			return acme.MalformedErr(errors.New("contact cannot be empty string"))
+		}
+	}
+	return nil
+}
+
+// Validate validates a new-account request body.
+func (n *NewAccountRequest) Validate() error {
+	if n.OnlyReturnExisting && len(n.Contact) > 0 {
+		return acme.MalformedErr(errors.New("incompatible input; onlyReturnExisting must be alone"))
+	}
+	return validateContacts(n.Contact)
+}
+
+// UpdateAccountRequest represents an update-account request.
+type UpdateAccountRequest struct {
+	Contact []string `json:"contact"`
+	Status  string   `json:"status"`
+}
+
+// IsDeactivateRequest returns true if the update request is a deactivation
+// request, false otherwise.
+func (u *UpdateAccountRequest) IsDeactivateRequest() bool {
+	return u.Status == acme.StatusDeactivated
+}
+
+// Validate validates a update-account request body.
+func (u *UpdateAccountRequest) Validate() error {
+	switch {
+	case len(u.Status) > 0 && len(u.Contact) > 0:
+		return acme.MalformedErr(errors.New("incompatible input; contact and " +
+			"status updates are mutually exclusive"))
+	case len(u.Contact) > 0:
+		if err := validateContacts(u.Contact); err != nil {
+			return err
+		}
+		return nil
+	case len(u.Status) > 0:
+		if u.Status != acme.StatusDeactivated {
+			return acme.MalformedErr(errors.Errorf("cannot update account "+
+				"status to %s, only deactivated", u.Status))
+		}
+		return nil
+	default:
+		return acme.MalformedErr(errors.Errorf("empty update request"))
+	}
+}
+
+// NewAccount is the handler resource for creating new ACME accounts.
+func (h *Handler) NewAccount(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	payload, err := payloadFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	var nar NewAccountRequest
+	if err := json.Unmarshal(payload.value, &nar); err != nil {
+		api.WriteError(w, acme.MalformedErr(errors.Wrap(err,
+			"failed to unmarshal new-account request payload")))
+		return
+	}
+	if err := nar.Validate(); err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	httpStatus := http.StatusCreated
+	acc, err := accountFromContext(r)
+	if err != nil {
+		acmeErr, ok := err.(*acme.Error)
+		if !ok || acmeErr.Status != http.StatusNotFound {
+			// Something went wrong ...
+			api.WriteError(w, err)
+			return
+		}
+
+		// Account does not exist //
+		if nar.OnlyReturnExisting {
+			api.WriteError(w, acme.AccountDoesNotExistErr(nil))
+			return
+		}
+		jwk, err := jwkFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+
+		if acc, err = h.Auth.NewAccount(prov, acme.AccountOptions{
+			Key:     jwk,
+			Contact: nar.Contact,
+		}); err != nil {
+			api.WriteError(w, err)
+			return
+		}
+	} else {
+		// Account exists //
+		httpStatus = http.StatusOK
+	}
+
+	w.Header().Set("Location", h.Auth.GetLink(acme.AccountLink,
+		acme.URLSafeProvisionerName(prov), true, acc.GetID()))
+	api.JSONStatus(w, acc, httpStatus)
+	return
+}
+
+// GetUpdateAccount is the api for updating an ACME account.
+func (h *Handler) GetUpdateAccount(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	payload, err := payloadFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	if !payload.isPostAsGet {
+		var uar UpdateAccountRequest
+		if err := json.Unmarshal(payload.value, &uar); err != nil {
+			api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "failed to unmarshal new-account request payload")))
+			return
+		}
+		if err := uar.Validate(); err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		var err error
+		if uar.IsDeactivateRequest() {
+			acc, err = h.Auth.DeactivateAccount(prov, acc.GetID())
+		} else {
+			acc, err = h.Auth.UpdateAccount(prov, acc.GetID(), uar.Contact)
+		}
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+	}
+	w.Header().Set("Location", h.Auth.GetLink(acme.AccountLink, acme.URLSafeProvisionerName(prov), true, acc.GetID()))
+	api.JSON(w, acc)
+	return
+}
+
+func logOrdersByAccount(w http.ResponseWriter, oids []string) {
+	if rl, ok := w.(logging.ResponseLogger); ok {
+		m := map[string]interface{}{
+			"orders": oids,
+		}
+		rl.WithFields(m)
+	}
+}
+
+// GetOrdersByAccount ACME api for retrieving the list of order urls belonging to an account.
+func (h *Handler) GetOrdersByAccount(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	accID := chi.URLParam(r, "accID")
+	if acc.ID != accID {
+		api.WriteError(w, acme.UnauthorizedErr(errors.New("account ID does not match url param")))
+		return
+	}
+	orders, err := h.Auth.GetOrdersByAccount(prov, acc.GetID())
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	api.JSON(w, orders)
+	logOrdersByAccount(w, orders)
+	return
+}

+ 790 - 0
acme/api/account_test.go

@@ -0,0 +1,790 @@
+package api
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+)
+
+var (
+	defaultDisableRenewal   = false
+	globalProvisionerClaims = provisioner.Claims{
+		MinTLSDur:      &provisioner.Duration{Duration: 5 * time.Minute},
+		MaxTLSDur:      &provisioner.Duration{Duration: 24 * time.Hour},
+		DefaultTLSDur:  &provisioner.Duration{Duration: 24 * time.Hour},
+		DisableRenewal: &defaultDisableRenewal,
+	}
+)
+
+func newProv() provisioner.Interface {
+	// Initialize provisioners
+	p := &provisioner.ACME{
+		Type: "ACME",
+		Name: "test@acme-provisioner.com",
+	}
+	if err := p.Init(provisioner.Config{Claims: globalProvisionerClaims}); err != nil {
+		fmt.Printf("%v", err)
+	}
+	return p
+}
+
+func TestNewAccountRequestValidate(t *testing.T) {
+	type test struct {
+		nar *NewAccountRequest
+		err *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/incompatible-input": func(t *testing.T) test {
+			return test{
+				nar: &NewAccountRequest{
+					OnlyReturnExisting: true,
+					Contact:            []string{"foo", "bar"},
+				},
+				err: acme.MalformedErr(errors.Errorf("incompatible input; onlyReturnExisting must be alone")),
+			}
+		},
+		"fail/bad-contact": func(t *testing.T) test {
+			return test{
+				nar: &NewAccountRequest{
+					Contact: []string{"foo", ""},
+				},
+				err: acme.MalformedErr(errors.Errorf("contact cannot be empty string")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				nar: &NewAccountRequest{
+					Contact: []string{"foo", "bar"},
+				},
+			}
+		},
+		"ok/onlyReturnExisting": func(t *testing.T) test {
+			return test{
+				nar: &NewAccountRequest{
+					OnlyReturnExisting: true,
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			if err := tc.nar.Validate(); err != nil {
+				if assert.NotNil(t, err) {
+					ae, ok := err.(*acme.Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestUpdateAccountRequestValidate(t *testing.T) {
+	type test struct {
+		uar *UpdateAccountRequest
+		err *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/incompatible-input": func(t *testing.T) test {
+			return test{
+				uar: &UpdateAccountRequest{
+					Contact: []string{"foo", "bar"},
+					Status:  "foo",
+				},
+				err: acme.MalformedErr(errors.Errorf("incompatible input; " +
+					"contact and status updates are mutually exclusive")),
+			}
+		},
+		"fail/bad-contact": func(t *testing.T) test {
+			return test{
+				uar: &UpdateAccountRequest{
+					Contact: []string{"foo", ""},
+				},
+				err: acme.MalformedErr(errors.Errorf("contact cannot be empty string")),
+			}
+		},
+		"fail/bad-status": func(t *testing.T) test {
+			return test{
+				uar: &UpdateAccountRequest{
+					Status: "foo",
+				},
+				err: acme.MalformedErr(errors.Errorf("cannot update account " +
+					"status to foo, only deactivated")),
+			}
+		},
+		"ok/contact": func(t *testing.T) test {
+			return test{
+				uar: &UpdateAccountRequest{
+					Contact: []string{"foo", "bar"},
+				},
+			}
+		},
+		"ok/status": func(t *testing.T) test {
+			return test{
+				uar: &UpdateAccountRequest{
+					Status: "deactivated",
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			if err := tc.uar.Validate(); err != nil {
+				if assert.NotNil(t, err) {
+					ae, ok := err.(*acme.Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestHandlerGetOrdersByAccount(t *testing.T) {
+	oids := []string{
+		"https://ca.smallstep.com/acme/order/foo",
+		"https://ca.smallstep.com/acme/order/bar",
+	}
+	accID := "account-id"
+	prov := newProv()
+
+	// Request with chi context
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("accID", accID)
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/account/%s/orders", accID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.Errorf("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.Errorf("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/account-id-mismatch": func(t *testing.T) test {
+			acc := &acme.Account{ID: "foo"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 401,
+				problem:    acme.UnauthorizedErr(errors.New("account ID does not match url param")),
+			}
+		},
+		"fail/getOrdersByAccount-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: accID}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.ServerInternalErr(errors.New("force")),
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: accID}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					getOrdersByAccount: func(p provisioner.Interface, id string) ([]string, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, id, acc.ID)
+						return oids, nil
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetOrdersByAccount(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(oids)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerNewAccount(t *testing.T) {
+	accID := "accountID"
+	acc := acme.Account{
+		ID:     accID,
+		Status: "valid",
+		Orders: fmt.Sprintf("https://ca.smallstep.com/acme/account/%s/orders", accID),
+	}
+	prov := newProv()
+
+	url := "https://ca.smallstep.com/acme/new-account"
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-payload": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/unmarshal-payload-error": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("failed to unmarshal new-account request payload: unexpected end of JSON input")),
+			}
+		},
+		"fail/malformed-payload-error": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				Contact: []string{"foo", ""},
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("contact cannot be empty string")),
+			}
+		},
+		"fail/no-existing-account": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				OnlyReturnExisting: true,
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/no-jwk": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.Errorf("jwk expected in request context")),
+			}
+		},
+		"fail/nil-jwk": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, jwkContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.Errorf("jwk expected in request context")),
+			}
+		},
+		"fail/NewAccount-error": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, jwkContextKey, jwk)
+			return test{
+				auth: &mockAcmeAuthority{
+					newAccount: func(p provisioner.Interface, ops acme.AccountOptions) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, ops.Contact, nar.Contact)
+						assert.Equals(t, ops.Key, jwk)
+						return nil, acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok/new-account": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, jwkContextKey, jwk)
+			return test{
+				auth: &mockAcmeAuthority{
+					newAccount: func(p provisioner.Interface, ops acme.AccountOptions) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, ops.Contact, nar.Contact)
+						assert.Equals(t, ops.Key, jwk)
+						return &acc, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{accID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+							acme.URLSafeProvisionerName(prov), accID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 201,
+			}
+		},
+		"ok/return-existing": func(t *testing.T) test {
+			nar := &NewAccountRequest{
+				OnlyReturnExisting: true,
+			}
+			b, err := json.Marshal(nar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			return test{
+				auth: &mockAcmeAuthority{
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{accID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+							acme.URLSafeProvisionerName(prov), accID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.NewAccount(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(acc)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"],
+					[]string{fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+						acme.URLSafeProvisionerName(prov), accID)})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerGetUpdateAccount(t *testing.T) {
+	accID := "accountID"
+	acc := acme.Account{
+		ID:     accID,
+		Status: "valid",
+		Orders: fmt.Sprintf("https://ca.smallstep.com/acme/account/%s/orders", accID),
+	}
+	prov := newProv()
+
+	// Request with chi context
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/account/%s", accID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/no-payload": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/unmarshal-payload-error": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("failed to unmarshal new-account request payload: unexpected end of JSON input")),
+			}
+		},
+		"fail/malformed-payload-error": func(t *testing.T) test {
+			uar := &UpdateAccountRequest{
+				Contact: []string{"foo", ""},
+			}
+			b, err := json.Marshal(uar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("contact cannot be empty string")),
+			}
+		},
+		"fail/Deactivate-error": func(t *testing.T) test {
+			uar := &UpdateAccountRequest{
+				Status: "deactivated",
+			}
+			b, err := json.Marshal(uar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					deactivateAccount: func(p provisioner.Interface, id string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, id, accID)
+						return nil, acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"fail/UpdateAccount-error": func(t *testing.T) test {
+			uar := &UpdateAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(uar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					updateAccount: func(p provisioner.Interface, id string, contacts []string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, id, accID)
+						assert.Equals(t, contacts, uar.Contact)
+						return nil, acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok/deactivate": func(t *testing.T) test {
+			uar := &UpdateAccountRequest{
+				Status: "deactivated",
+			}
+			b, err := json.Marshal(uar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					deactivateAccount: func(p provisioner.Interface, id string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, id, accID)
+						return &acc, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{accID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+							acme.URLSafeProvisionerName(prov), accID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+		"ok/new-account": func(t *testing.T) test {
+			uar := &UpdateAccountRequest{
+				Contact: []string{"foo", "bar"},
+			}
+			b, err := json.Marshal(uar)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					updateAccount: func(p provisioner.Interface, id string, contacts []string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, id, accID)
+						assert.Equals(t, contacts, uar.Contact)
+						return &acc, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{accID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+							acme.URLSafeProvisionerName(prov), accID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+		"ok/post-as-get": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, &acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isPostAsGet: true})
+			return test{
+				auth: &mockAcmeAuthority{
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{accID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+							acme.URLSafeProvisionerName(prov), accID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetUpdateAccount(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(acc)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"],
+					[]string{fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/%s",
+						acme.URLSafeProvisionerName(prov), accID)})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}

+ 214 - 0
acme/api/handler.go

@@ -0,0 +1,214 @@
+package api
+
+import (
+	"fmt"
+	"net/http"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/api"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+)
+
+func link(url, typ string) string {
+	return fmt.Sprintf("<%s>;rel=\"%s\"", url, typ)
+}
+
+type contextKey string
+
+const (
+	accContextKey         = contextKey("acc")
+	jwsContextKey         = contextKey("jws")
+	jwkContextKey         = contextKey("jwk")
+	payloadContextKey     = contextKey("payload")
+	provisionerContextKey = contextKey("provisioner")
+)
+
+type payloadInfo struct {
+	value       []byte
+	isPostAsGet bool
+	isEmptyJSON bool
+}
+
+func accountFromContext(r *http.Request) (*acme.Account, error) {
+	val, ok := r.Context().Value(accContextKey).(*acme.Account)
+	if !ok || val == nil {
+		return nil, acme.AccountDoesNotExistErr(nil)
+	}
+	return val, nil
+}
+func jwkFromContext(r *http.Request) (*jose.JSONWebKey, error) {
+	val, ok := r.Context().Value(jwkContextKey).(*jose.JSONWebKey)
+	if !ok || val == nil {
+		return nil, acme.ServerInternalErr(errors.Errorf("jwk expected in request context"))
+	}
+	return val, nil
+}
+func jwsFromContext(r *http.Request) (*jose.JSONWebSignature, error) {
+	val, ok := r.Context().Value(jwsContextKey).(*jose.JSONWebSignature)
+	if !ok || val == nil {
+		return nil, acme.ServerInternalErr(errors.Errorf("jws expected in request context"))
+	}
+	return val, nil
+}
+func payloadFromContext(r *http.Request) (*payloadInfo, error) {
+	val, ok := r.Context().Value(payloadContextKey).(*payloadInfo)
+	if !ok || val == nil {
+		return nil, acme.ServerInternalErr(errors.Errorf("payload expected in request context"))
+	}
+	return val, nil
+}
+func provisionerFromContext(r *http.Request) (provisioner.Interface, error) {
+	val, ok := r.Context().Value(provisionerContextKey).(provisioner.Interface)
+	if !ok || val == nil {
+		return nil, acme.ServerInternalErr(errors.Errorf("provisioner expected in request context"))
+	}
+	return val, nil
+}
+
+// New returns a new ACME API router.
+func New(acmeAuth acme.Interface) api.RouterHandler {
+	return &Handler{acmeAuth}
+}
+
+// Handler is the ACME request handler.
+type Handler struct {
+	Auth acme.Interface
+}
+
+// Route traffic and implement the Router interface.
+func (h *Handler) Route(r api.Router) {
+	getLink := h.Auth.GetLink
+	// Standard ACME API
+	r.MethodFunc("GET", getLink(acme.NewNonceLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetNonce)))
+	r.MethodFunc("HEAD", getLink(acme.NewNonceLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetNonce)))
+	r.MethodFunc("GET", getLink(acme.DirectoryLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetDirectory)))
+	r.MethodFunc("HEAD", getLink(acme.DirectoryLink, "{provisionerID}", false), h.lookupProvisioner(h.addNonce(h.GetDirectory)))
+
+	extractPayloadByJWK := func(next nextHTTP) nextHTTP {
+		return h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.extractJWK(h.verifyAndExtractJWSPayload(next))))))))
+	}
+	extractPayloadByKid := func(next nextHTTP) nextHTTP {
+		return h.lookupProvisioner(h.addNonce(h.addDirLink(h.verifyContentType(h.parseJWS(h.validateJWS(h.lookupJWK(h.verifyAndExtractJWSPayload(next))))))))
+	}
+
+	r.MethodFunc("POST", getLink(acme.NewAccountLink, "{provisionerID}", false), extractPayloadByJWK(h.NewAccount))
+	r.MethodFunc("POST", getLink(acme.AccountLink, "{provisionerID}", false, "{accID}"), extractPayloadByKid(h.GetUpdateAccount))
+	r.MethodFunc("POST", getLink(acme.NewOrderLink, "{provisionerID}", false), extractPayloadByKid(h.NewOrder))
+	r.MethodFunc("POST", getLink(acme.OrderLink, "{provisionerID}", false, "{ordID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrder)))
+	r.MethodFunc("POST", getLink(acme.OrdersByAccountLink, "{provisionerID}", false, "{accID}"), extractPayloadByKid(h.isPostAsGet(h.GetOrdersByAccount)))
+	r.MethodFunc("POST", getLink(acme.FinalizeLink, "{provisionerID}", false, "{ordID}"), extractPayloadByKid(h.FinalizeOrder))
+	r.MethodFunc("POST", getLink(acme.AuthzLink, "{provisionerID}", false, "{authzID}"), extractPayloadByKid(h.isPostAsGet(h.GetAuthz)))
+	r.MethodFunc("POST", getLink(acme.ChallengeLink, "{provisionerID}", false, "{chID}"), extractPayloadByKid(h.GetChallenge))
+	r.MethodFunc("POST", getLink(acme.CertificateLink, "{provisionerID}", false, "{certID}"), extractPayloadByKid(h.isPostAsGet(h.GetCertificate)))
+}
+
+// GetNonce just sets the right header since a Nonce is added to each response
+// by middleware by default.
+func (h *Handler) GetNonce(w http.ResponseWriter, r *http.Request) {
+	if r.Method == "HEAD" {
+		w.WriteHeader(http.StatusOK)
+	} else {
+		w.WriteHeader(http.StatusNoContent)
+	}
+	return
+}
+
+// GetDirectory is the ACME resource for returning a directory configuration
+// for client configuration.
+func (h *Handler) GetDirectory(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	dir := h.Auth.GetDirectory(prov)
+	api.JSON(w, dir)
+	return
+}
+
+// GetAuthz ACME api for retrieving an Authz.
+func (h *Handler) GetAuthz(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	authz, err := h.Auth.GetAuthz(prov, acc.GetID(), chi.URLParam(r, "authzID"))
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	w.Header().Set("Location", h.Auth.GetLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, authz.GetID()))
+	api.JSON(w, authz)
+	return
+}
+
+// GetChallenge ACME api for retrieving a Challenge.
+func (h *Handler) GetChallenge(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	// Just verify that the payload was set, since we're not strictly adhering
+	// to ACME V2 spec for reasons specified below.
+	_, err = payloadFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	// NOTE: We should be checking that the request is either a POST-as-GET, or
+	// that the payload is an empty JSON block ({}). However, older ACME clients
+	// still send a vestigial body (rather than an empty JSON block) and
+	// strict enforcement would render these clients broken. For the time being
+	// we'll just ignore the body.
+	var (
+		ch   *acme.Challenge
+		chID = chi.URLParam(r, "chID")
+	)
+	ch, err = h.Auth.ValidateChallenge(prov, acc.GetID(), chID, acc.GetKey())
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	getLink := h.Auth.GetLink
+	w.Header().Add("Link", link(getLink(acme.AuthzLink, acme.URLSafeProvisionerName(prov), true, ch.GetAuthzID()), "up"))
+	w.Header().Set("Location", getLink(acme.ChallengeLink, acme.URLSafeProvisionerName(prov), true, ch.GetID()))
+	api.JSON(w, ch)
+	return
+}
+
+// GetCertificate ACME api for retrieving a Certificate.
+func (h *Handler) GetCertificate(w http.ResponseWriter, r *http.Request) {
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	certID := chi.URLParam(r, "certID")
+	certBytes, err := h.Auth.GetCertificate(acc.GetID(), certID)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	w.Header().Set("Content-Type", "application/pem-certificate-chain; charset=utf-8")
+	w.Write(certBytes)
+	return
+}

+ 771 - 0
acme/api/handler_test.go

@@ -0,0 +1,771 @@
+package api
+
+import (
+	"bytes"
+	"context"
+	"crypto/x509"
+	"encoding/json"
+	"encoding/pem"
+	"fmt"
+	"io/ioutil"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/crypto/pemutil"
+	"github.com/smallstep/cli/jose"
+)
+
+type mockAcmeAuthority struct {
+	deactivateAccount   func(provisioner.Interface, string) (*acme.Account, error)
+	finalizeOrder       func(p provisioner.Interface, accID string, id string, csr *x509.CertificateRequest) (*acme.Order, error)
+	getAccount          func(p provisioner.Interface, id string) (*acme.Account, error)
+	getAccountByKey     func(provisioner.Interface, *jose.JSONWebKey) (*acme.Account, error)
+	getAuthz            func(p provisioner.Interface, accID string, id string) (*acme.Authz, error)
+	getCertificate      func(accID string, id string) ([]byte, error)
+	getChallenge        func(p provisioner.Interface, accID string, id string) (*acme.Challenge, error)
+	getDirectory        func(provisioner.Interface) *acme.Directory
+	getLink             func(acme.Link, string, bool, ...string) string
+	getOrder            func(p provisioner.Interface, accID string, id string) (*acme.Order, error)
+	getOrdersByAccount  func(p provisioner.Interface, id string) ([]string, error)
+	loadProvisionerByID func(string) (provisioner.Interface, error)
+	newAccount          func(provisioner.Interface, acme.AccountOptions) (*acme.Account, error)
+	newNonce            func() (string, error)
+	newOrder            func(provisioner.Interface, acme.OrderOptions) (*acme.Order, error)
+	updateAccount       func(provisioner.Interface, string, []string) (*acme.Account, error)
+	useNonce            func(string) error
+	validateChallenge   func(p provisioner.Interface, accID string, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error)
+	ret1                interface{}
+	err                 error
+}
+
+func (m *mockAcmeAuthority) DeactivateAccount(p provisioner.Interface, id string) (*acme.Account, error) {
+	if m.deactivateAccount != nil {
+		return m.deactivateAccount(p, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Account), m.err
+}
+
+func (m *mockAcmeAuthority) FinalizeOrder(p provisioner.Interface, accID, id string, csr *x509.CertificateRequest) (*acme.Order, error) {
+	if m.finalizeOrder != nil {
+		return m.finalizeOrder(p, accID, id, csr)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Order), m.err
+}
+
+func (m *mockAcmeAuthority) GetAccount(p provisioner.Interface, id string) (*acme.Account, error) {
+	if m.getAccount != nil {
+		return m.getAccount(p, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Account), m.err
+}
+
+func (m *mockAcmeAuthority) GetAccountByKey(p provisioner.Interface, jwk *jose.JSONWebKey) (*acme.Account, error) {
+	if m.getAccountByKey != nil {
+		return m.getAccountByKey(p, jwk)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Account), m.err
+}
+
+func (m *mockAcmeAuthority) GetAuthz(p provisioner.Interface, accID, id string) (*acme.Authz, error) {
+	if m.getAuthz != nil {
+		return m.getAuthz(p, accID, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Authz), m.err
+}
+
+func (m *mockAcmeAuthority) GetCertificate(accID, id string) ([]byte, error) {
+	if m.getCertificate != nil {
+		return m.getCertificate(accID, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.([]byte), m.err
+}
+
+func (m *mockAcmeAuthority) GetChallenge(p provisioner.Interface, accID, id string) (*acme.Challenge, error) {
+	if m.getChallenge != nil {
+		return m.getChallenge(p, accID, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Challenge), m.err
+}
+
+func (m *mockAcmeAuthority) GetDirectory(p provisioner.Interface) *acme.Directory {
+	if m.getDirectory != nil {
+		return m.getDirectory(p)
+	}
+	return m.ret1.(*acme.Directory)
+}
+
+func (m *mockAcmeAuthority) GetLink(typ acme.Link, provID string, abs bool, in ...string) string {
+	if m.getLink != nil {
+		return m.getLink(typ, provID, abs, in...)
+	}
+	return m.ret1.(string)
+}
+
+func (m *mockAcmeAuthority) GetOrder(p provisioner.Interface, accID, id string) (*acme.Order, error) {
+	if m.getOrder != nil {
+		return m.getOrder(p, accID, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Order), m.err
+}
+
+func (m *mockAcmeAuthority) GetOrdersByAccount(p provisioner.Interface, id string) ([]string, error) {
+	if m.getOrdersByAccount != nil {
+		return m.getOrdersByAccount(p, id)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.([]string), m.err
+}
+
+func (m *mockAcmeAuthority) LoadProvisionerByID(provID string) (provisioner.Interface, error) {
+	if m.loadProvisionerByID != nil {
+		return m.loadProvisionerByID(provID)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(provisioner.Interface), m.err
+}
+
+func (m *mockAcmeAuthority) NewAccount(p provisioner.Interface, ops acme.AccountOptions) (*acme.Account, error) {
+	if m.newAccount != nil {
+		return m.newAccount(p, ops)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Account), m.err
+}
+
+func (m *mockAcmeAuthority) NewNonce() (string, error) {
+	if m.newNonce != nil {
+		return m.newNonce()
+	} else if m.err != nil {
+		return "", m.err
+	}
+	return m.ret1.(string), m.err
+}
+
+func (m *mockAcmeAuthority) NewOrder(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
+	if m.newOrder != nil {
+		return m.newOrder(p, ops)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Order), m.err
+}
+
+func (m *mockAcmeAuthority) UpdateAccount(p provisioner.Interface, id string, contact []string) (*acme.Account, error) {
+	if m.updateAccount != nil {
+		return m.updateAccount(p, id, contact)
+	} else if m.err != nil {
+		return nil, m.err
+	}
+	return m.ret1.(*acme.Account), m.err
+}
+
+func (m *mockAcmeAuthority) UseNonce(nonce string) error {
+	if m.useNonce != nil {
+		return m.useNonce(nonce)
+	}
+	return m.err
+}
+
+func (m *mockAcmeAuthority) ValidateChallenge(p provisioner.Interface, accID string, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error) {
+	switch {
+	case m.validateChallenge != nil:
+		return m.validateChallenge(p, accID, id, jwk)
+	case m.err != nil:
+		return nil, m.err
+	default:
+		return m.ret1.(*acme.Challenge), m.err
+	}
+}
+
+func TestHandlerGetNonce(t *testing.T) {
+	tests := []struct {
+		name       string
+		statusCode int
+	}{
+		{"GET", 204},
+		{"HEAD", 200},
+	}
+
+	// Request with chi context
+	req := httptest.NewRequest("GET", "http://ca.smallstep.com/nonce", nil)
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			h := New(nil).(*Handler)
+			w := httptest.NewRecorder()
+			req.Method = tt.name
+			h.GetNonce(w, req)
+			res := w.Result()
+
+			if res.StatusCode != tt.statusCode {
+				t.Errorf("Handler.GetNonce StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
+			}
+		})
+	}
+}
+
+func TestHandlerGetDirectory(t *testing.T) {
+	auth := acme.NewAuthority(nil, "ca.smallstep.com", "acme", nil)
+	prov := newProv()
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/directory", acme.URLSafeProvisionerName(prov))
+
+	expDir := acme.Directory{
+		NewNonce:   fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-nonce", acme.URLSafeProvisionerName(prov)),
+		NewAccount: fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-account", acme.URLSafeProvisionerName(prov)),
+		NewOrder:   fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-order", acme.URLSafeProvisionerName(prov)),
+		RevokeCert: fmt.Sprintf("https://ca.smallstep.com/acme/%s/revoke-cert", acme.URLSafeProvisionerName(prov)),
+		KeyChange:  fmt.Sprintf("https://ca.smallstep.com/acme/%s/key-change", acme.URLSafeProvisionerName(prov)),
+	}
+
+	type test struct {
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetDirectory(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				var dir acme.Directory
+				json.Unmarshal(bytes.TrimSpace(body), &dir)
+				assert.Equals(t, dir, expDir)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerGetAuthz(t *testing.T) {
+	expiry := time.Now().UTC().Add(6 * time.Hour)
+	az := acme.Authz{
+		ID: "authzID",
+		Identifier: acme.Identifier{
+			Type:  "dns",
+			Value: "example.com",
+		},
+		Status:   "pending",
+		Expires:  expiry.Format(time.RFC3339),
+		Wildcard: false,
+		Challenges: []*acme.Challenge{
+			{
+				Type:    "http-01",
+				Status:  "pending",
+				Token:   "tok2",
+				URL:     "https://ca.smallstep.com/acme/challenge/chHTTPID",
+				ID:      "chHTTP01ID",
+				AuthzID: "authzID",
+			},
+			{
+				Type:    "dns-01",
+				Status:  "pending",
+				Token:   "tok2",
+				URL:     "https://ca.smallstep.com/acme/challenge/chDNSID",
+				ID:      "chDNSID",
+				AuthzID: "authzID",
+			},
+		},
+	}
+	prov := newProv()
+
+	// Request with chi context
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("authzID", az.ID)
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/challenge/%s",
+		acme.URLSafeProvisionerName(prov), az.ID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/getAuthz-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.ServerInternalErr(errors.New("force")),
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					getAuthz: func(p provisioner.Interface, accID, id string) (*acme.Authz, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, az.ID)
+						return &az, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.Equals(t, typ, acme.AuthzLink)
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{az.ID})
+						return url
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetAuthz(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				//var gotAz acme.Authz
+				//assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &gotAz))
+				expB, err := json.Marshal(az)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"], []string{url})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerGetCertificate(t *testing.T) {
+	leaf, err := pemutil.ReadCertificate("../../authority/testdata/certs/foo.crt")
+	assert.FatalError(t, err)
+	inter, err := pemutil.ReadCertificate("../../authority/testdata/certs/intermediate_ca.crt")
+	assert.FatalError(t, err)
+	root, err := pemutil.ReadCertificate("../../authority/testdata/certs/root_ca.crt")
+	assert.FatalError(t, err)
+
+	certBytes := append(pem.EncodeToMemory(&pem.Block{
+		Type:  "CERTIFICATE",
+		Bytes: leaf.Raw,
+	}), pem.EncodeToMemory(&pem.Block{
+		Type:  "CERTIFICATE",
+		Bytes: inter.Raw,
+	})...)
+	certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{
+		Type:  "CERTIFICATE",
+		Bytes: root.Raw,
+	})...)
+	certID := "certID"
+
+	prov := newProv()
+	// Request with chi context
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("certID", certID)
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/certificate/%s",
+		acme.URLSafeProvisionerName(prov), certID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), accContextKey, nil)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/getCertificate-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.ServerInternalErr(errors.New("force")),
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					getCertificate: func(accID, id string) ([]byte, error) {
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, certID)
+						return certBytes, nil
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetCertificate(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), bytes.TrimSpace(certBytes))
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/pem-certificate-chain; charset=utf-8"})
+			}
+		})
+	}
+}
+
+func ch() acme.Challenge {
+	return acme.Challenge{
+		Type:    "http-01",
+		Status:  "pending",
+		Token:   "tok2",
+		URL:     "https://ca.smallstep.com/acme/challenge/chID",
+		ID:      "chID",
+		AuthzID: "authzID",
+	}
+}
+
+func TestHandlerGetChallenge(t *testing.T) {
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("chID", "chID")
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/challenge/%s", "chID")
+	prov := newProv()
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		ch         acme.Challenge
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/no-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/validate-challenge-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.UnauthorizedErr(nil),
+				},
+				ctx:        ctx,
+				statusCode: 401,
+				problem:    acme.UnauthorizedErr(nil),
+			}
+		},
+		"fail/get-challenge-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isPostAsGet: true})
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.UnauthorizedErr(nil),
+				},
+				ctx:        ctx,
+				statusCode: 401,
+				problem:    acme.UnauthorizedErr(nil),
+			}
+		},
+		"ok/validate-challenge": func(t *testing.T) test {
+			key, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			acc := &acme.Account{ID: "accID", Key: key}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{isEmptyJSON: true})
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			ch := ch()
+			ch.Status = "valid"
+			ch.Validated = time.Now().UTC().Format(time.RFC3339)
+			count := 0
+			return test{
+				auth: &mockAcmeAuthority{
+					validateChallenge: func(p provisioner.Interface, accID, id string, jwk *jose.JSONWebKey) (*acme.Challenge, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, ch.ID)
+						assert.Equals(t, jwk.KeyID, key.KeyID)
+						return &ch, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						var ret string
+						switch count {
+						case 0:
+							assert.Equals(t, typ, acme.AuthzLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.True(t, abs)
+							assert.Equals(t, in, []string{ch.AuthzID})
+							ret = fmt.Sprintf("https://ca.smallstep.com/acme/authz/%s", ch.AuthzID)
+						case 1:
+							assert.Equals(t, typ, acme.ChallengeLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.True(t, abs)
+							assert.Equals(t, in, []string{ch.ID})
+							ret = url
+						}
+						count++
+						return ret
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+				ch:         ch,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetChallenge(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(tc.ch)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<https://ca.smallstep.com/acme/authz/%s>;rel=\"up\"", tc.ch.AuthzID)})
+				assert.Equals(t, res.Header["Location"], []string{url})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}

+ 377 - 0
acme/api/middleware.go

@@ -0,0 +1,377 @@
+package api
+
+import (
+	"context"
+	"crypto/rsa"
+	"io/ioutil"
+	"net/http"
+	"net/url"
+	"strings"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/api"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/logging"
+	"github.com/smallstep/cli/crypto/keys"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+)
+
+type nextHTTP = func(http.ResponseWriter, *http.Request)
+
+func logNonce(w http.ResponseWriter, nonce string) {
+	if rl, ok := w.(logging.ResponseLogger); ok {
+		m := map[string]interface{}{
+			"nonce": nonce,
+		}
+		rl.WithFields(m)
+	}
+}
+
+// addNonce is a middleware that adds a nonce to the response header.
+func (h *Handler) addNonce(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		nonce, err := h.Auth.NewNonce()
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		w.Header().Set("Replay-Nonce", nonce)
+		w.Header().Set("Cache-Control", "no-store")
+		logNonce(w, nonce)
+		next(w, r)
+		return
+	}
+}
+
+// addDirLink is a middleware that adds a 'Link' response reader with the
+// directory index url.
+func (h *Handler) addDirLink(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		prov, err := provisionerFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		w.Header().Add("Link", link(h.Auth.GetLink(acme.DirectoryLink, acme.URLSafeProvisionerName(prov), true), "index"))
+		next(w, r)
+		return
+	}
+}
+
+// verifyContentType is a middleware that verifies that content type is
+// application/jose+json.
+func (h *Handler) verifyContentType(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		prov, err := provisionerFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		ct := r.Header.Get("Content-Type")
+		var expected []string
+		if strings.Contains(r.URL.Path, h.Auth.GetLink(acme.CertificateLink, acme.URLSafeProvisionerName(prov), false, "")) {
+			// GET /certificate requests allow a greater range of content types.
+			expected = []string{"application/jose+json", "application/pkix-cert", "application/pkcs7-mime"}
+		} else {
+			// By default every request should have content-type applictaion/jose+json.
+			expected = []string{"application/jose+json"}
+		}
+		for _, e := range expected {
+			if ct == e {
+				next(w, r)
+				return
+			}
+		}
+		api.WriteError(w, acme.MalformedErr(errors.Errorf(
+			"expected content-type to be in %s, but got %s", expected, ct)))
+		return
+	}
+}
+
+// parseJWS is a middleware that parses a request body into a JSONWebSignature struct.
+func (h *Handler) parseJWS(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		body, err := ioutil.ReadAll(r.Body)
+		if err != nil {
+			api.WriteError(w, acme.ServerInternalErr(errors.Wrap(err, "failed to read request body")))
+			return
+		}
+		jws, err := jose.ParseJWS(string(body))
+		if err != nil {
+			api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "failed to parse JWS from request body")))
+			return
+		}
+		ctx := context.WithValue(r.Context(), jwsContextKey, jws)
+		next(w, r.WithContext(ctx))
+		return
+	}
+}
+
+// validateJWS checks the request body for to verify that it meets ACME
+// requirements for a JWS.
+//
+// The JWS MUST NOT have multiple signatures
+// The JWS Unencoded Payload Option [RFC7797] MUST NOT be used
+// The JWS Unprotected Header [RFC7515] MUST NOT be used
+// The JWS Payload MUST NOT be detached
+// The JWS Protected Header MUST include the following fields:
+//   * “alg” (Algorithm)
+//     * This field MUST NOT contain “none” or a Message Authentication Code
+//       (MAC) algorithm (e.g. one in which the algorithm registry description
+//       mentions MAC/HMAC).
+//   * “nonce” (defined in Section 6.5)
+//   * “url” (defined in Section 6.4)
+//   * Either “jwk” (JSON Web Key) or “kid” (Key ID) as specified below<Paste>
+func (h *Handler) validateJWS(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		jws, err := jwsFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		if len(jws.Signatures) == 0 {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("request body does not contain a signature")))
+			return
+		}
+		if len(jws.Signatures) > 1 {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("request body contains more than one signature")))
+			return
+		}
+
+		sig := jws.Signatures[0]
+		uh := sig.Unprotected
+		if len(uh.KeyID) > 0 ||
+			uh.JSONWebKey != nil ||
+			len(uh.Algorithm) > 0 ||
+			len(uh.Nonce) > 0 ||
+			len(uh.ExtraHeaders) > 0 {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("unprotected header must not be used")))
+			return
+		}
+		hdr := sig.Protected
+		switch hdr.Algorithm {
+		case jose.RS256, jose.RS384, jose.RS512:
+			if hdr.JSONWebKey != nil {
+				switch k := hdr.JSONWebKey.Key.(type) {
+				case *rsa.PublicKey:
+					if k.Size() < keys.MinRSAKeyBytes {
+						api.WriteError(w, acme.MalformedErr(errors.Errorf("rsa "+
+							"keys must be at least %d bits (%d bytes) in size",
+							8*keys.MinRSAKeyBytes, keys.MinRSAKeyBytes)))
+						return
+					}
+				default:
+					api.WriteError(w, acme.MalformedErr(errors.Errorf("jws key type and algorithm do not match")))
+					return
+				}
+			}
+		case jose.ES256, jose.ES384, jose.ES512, jose.EdDSA:
+			// we good
+		default:
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("unsuitable algorithm: %s", hdr.Algorithm)))
+			return
+		}
+
+		// Check the validity/freshness of the Nonce.
+		if err := h.Auth.UseNonce(hdr.Nonce); err != nil {
+			api.WriteError(w, err)
+			return
+		}
+
+		// Check that the JWS url matches the requested url.
+		jwsURL, ok := hdr.ExtraHeaders["url"].(string)
+		if !ok {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("jws missing url protected header")))
+			return
+		}
+		reqURL := &url.URL{Scheme: "https", Host: r.Host, Path: r.URL.Path}
+		if jwsURL != reqURL.String() {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("url header in JWS (%s) does not match request url (%s)", jwsURL, reqURL)))
+			return
+		}
+
+		if hdr.JSONWebKey != nil && len(hdr.KeyID) > 0 {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk and kid are mutually exclusive")))
+			return
+		}
+		if hdr.JSONWebKey == nil && len(hdr.KeyID) == 0 {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("either jwk or kid must be defined in jws protected header")))
+			return
+		}
+		next(w, r)
+		return
+	}
+}
+
+// extractJWK is a middleware that extracts the JWK from the JWS and saves it
+// in the context. Make sure to parse and validate the JWS before running this
+// middleware.
+func (h *Handler) extractJWK(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		ctx := r.Context()
+		prov, err := provisionerFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		jws, err := jwsFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		jwk := jws.Signatures[0].Protected.JSONWebKey
+		if jwk == nil {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("jwk expected in protected header")))
+			return
+		}
+		if !jwk.Valid() {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("invalid jwk in protected header")))
+			return
+		}
+		ctx = context.WithValue(ctx, jwkContextKey, jwk)
+		acc, err := h.Auth.GetAccountByKey(prov, jwk)
+		switch {
+		case nosql.IsErrNotFound(err):
+			// For NewAccount requests ...
+			break
+		case err != nil:
+			api.WriteError(w, err)
+			return
+		default:
+			if !acc.IsValid() {
+				api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
+				return
+			}
+			ctx = context.WithValue(ctx, accContextKey, acc)
+		}
+		next(w, r.WithContext(ctx))
+		return
+	}
+}
+
+// lookupProvisioner loads the provisioner associated with the request.
+// Responsds 404 if the provisioner does not exist.
+func (h *Handler) lookupProvisioner(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		ctx := r.Context()
+
+		name := chi.URLParam(r, "provisionerID")
+		provID, err := url.PathUnescape(name)
+		if err != nil {
+			api.WriteError(w, acme.ServerInternalErr(errors.Wrapf(err, "error url unescaping provisioner id '%s'", name)))
+			return
+		}
+		p, err := h.Auth.LoadProvisionerByID("acme/" + provID)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		if p.GetType() != provisioner.TypeACME {
+			api.WriteError(w, acme.AccountDoesNotExistErr(errors.New("provisioner must be of type ACME")))
+			return
+		}
+		ctx = context.WithValue(ctx, provisionerContextKey, p)
+		next(w, r.WithContext(ctx))
+		return
+	}
+}
+
+// lookupJWK loads the JWK associated with the acme account referenced by the
+// kid parameter of the signed payload.
+// Make sure to parse and validate the JWS before running this middleware.
+func (h *Handler) lookupJWK(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		ctx := r.Context()
+		prov, err := provisionerFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		jws, err := jwsFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+
+		kidPrefix := h.Auth.GetLink(acme.AccountLink, acme.URLSafeProvisionerName(prov), true, "")
+		kid := jws.Signatures[0].Protected.KeyID
+		if !strings.HasPrefix(kid, kidPrefix) {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("kid does not have "+
+				"required prefix; expected %s, but got %s", kidPrefix, kid)))
+			return
+		}
+
+		accID := strings.TrimPrefix(kid, kidPrefix)
+		acc, err := h.Auth.GetAccount(prov, accID)
+		switch {
+		case nosql.IsErrNotFound(err):
+			api.WriteError(w, acme.AccountDoesNotExistErr(nil))
+			return
+		case err != nil:
+			api.WriteError(w, err)
+			return
+		default:
+			if !acc.IsValid() {
+				api.WriteError(w, acme.UnauthorizedErr(errors.New("account is not active")))
+				return
+			}
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, jwkContextKey, acc.Key)
+			next(w, r.WithContext(ctx))
+			return
+		}
+	}
+}
+
+// verifyAndExtractJWSPayload extracts the JWK from the JWS and saves it in the context.
+// Make sure to parse and validate the JWS before running this middleware.
+func (h *Handler) verifyAndExtractJWSPayload(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		jws, err := jwsFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		jwk, err := jwkFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		if len(jwk.Algorithm) != 0 && jwk.Algorithm != jws.Signatures[0].Protected.Algorithm {
+			api.WriteError(w, acme.MalformedErr(errors.New("verifier and signature algorithm do not match")))
+			return
+		}
+		payload, err := jws.Verify(jwk)
+		if err != nil {
+			api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "error verifying jws")))
+			return
+		}
+		ctx := context.WithValue(r.Context(), payloadContextKey, &payloadInfo{
+			value:       payload,
+			isPostAsGet: string(payload) == "",
+			isEmptyJSON: string(payload) == "{}",
+		})
+		next(w, r.WithContext(ctx))
+		return
+	}
+}
+
+// isPostAsGet asserts that the request is a PostAsGet (empty JWS payload).
+func (h *Handler) isPostAsGet(next nextHTTP) nextHTTP {
+	return func(w http.ResponseWriter, r *http.Request) {
+		payload, err := payloadFromContext(r)
+		if err != nil {
+			api.WriteError(w, err)
+			return
+		}
+		if !payload.isPostAsGet {
+			api.WriteError(w, acme.MalformedErr(errors.Errorf("expected POST-as-GET")))
+			return
+		}
+		next(w, r)
+		return
+	}
+}

+ 1550 - 0
acme/api/middleware_test.go

@@ -0,0 +1,1550 @@
+package api
+
+import (
+	"bytes"
+	"context"
+	"crypto"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io"
+	"io/ioutil"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql/database"
+)
+
+var testBody = []byte("foo")
+
+func testNext(w http.ResponseWriter, r *http.Request) {
+	w.Write(testBody)
+	return
+}
+
+func TestHandlerAddNonce(t *testing.T) {
+	url := "https://ca.smallstep.com/acme/new-nonce"
+	type test struct {
+		auth       acme.Interface
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/AddNonce-error": func(t *testing.T) test {
+			return test{
+				auth: &mockAcmeAuthority{
+					newNonce: func() (string, error) {
+						return "", acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				auth: &mockAcmeAuthority{
+					newNonce: func() (string, error) {
+						return "bar", nil
+					},
+				},
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			w := httptest.NewRecorder()
+			h.addNonce(testNext)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, res.Header["Replay-Nonce"], []string{"bar"})
+				assert.Equals(t, res.Header["Cache-Control"], []string{"no-store"})
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerAddDirLink(t *testing.T) {
+	url := "https://ca.smallstep.com/acme/new-nonce"
+	prov := newProv()
+	type test struct {
+		auth       acme.Interface
+		link       string
+		statusCode int
+		ctx        context.Context
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			link := "https://ca.smallstep.com/acme/directory"
+			return test{
+				auth: &mockAcmeAuthority{
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						return link
+					},
+				},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				link:       link,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.addDirLink(testNext)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, res.Header["Link"], []string{fmt.Sprintf("<%s>;rel=\"index\"", tc.link)})
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerVerifyContentType(t *testing.T) {
+	prov := newProv()
+	url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/certificate/abc123",
+		acme.URLSafeProvisionerName(prov))
+	type test struct {
+		h           Handler
+		ctx         context.Context
+		contentType string
+		problem     *acme.Error
+		statusCode  int
+		url         string
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				h:          Handler{Auth: &mockAcmeAuthority{}},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				h:          Handler{Auth: &mockAcmeAuthority{}},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/general-bad-content-type": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				url: fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-account",
+					acme.URLSafeProvisionerName(prov)),
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "foo",
+				statusCode:  400,
+				problem:     acme.MalformedErr(errors.New("expected content-type to be in [application/jose+json], but got foo")),
+			}
+		},
+		"fail/certificate-bad-content-type": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "foo",
+				statusCode:  400,
+				problem:     acme.MalformedErr(errors.New("expected content-type to be in [application/jose+json application/pkix-cert application/pkcs7-mime], but got foo")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "application/jose+json",
+				statusCode:  200,
+			}
+		},
+		"ok/certificate/pkix-cert": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "application/pkix-cert",
+				statusCode:  200,
+			}
+		},
+		"ok/certificate/jose+json": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "application/jose+json",
+				statusCode:  200,
+			}
+		},
+		"ok/certificate/pkcs7-mime": func(t *testing.T) test {
+			return test{
+				h: Handler{
+					Auth: &mockAcmeAuthority{
+						getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+							assert.Equals(t, typ, acme.CertificateLink)
+							assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+							assert.Equals(t, abs, false)
+							assert.Equals(t, in, []string{""})
+							return "/certificate/"
+						},
+					},
+				},
+				ctx:         context.WithValue(context.Background(), provisionerContextKey, prov),
+				contentType: "application/pkcs7-mime",
+				statusCode:  200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			_url := url
+			if tc.url != "" {
+				_url = tc.url
+			}
+			req := httptest.NewRequest("GET", _url, nil)
+			req = req.WithContext(tc.ctx)
+			req.Header.Add("Content-Type", tc.contentType)
+			w := httptest.NewRecorder()
+			tc.h.verifyContentType(testNext)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerIsPostAsGet(t *testing.T) {
+	url := "https://ca.smallstep.com/acme/new-account"
+	type test struct {
+		ctx        context.Context
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-payload": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), payloadContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/not-post-as-get": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), payloadContextKey, &payloadInfo{}),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("expected POST-as-GET")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), payloadContextKey, &payloadInfo{isPostAsGet: true}),
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(nil).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.isPostAsGet(testNext)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+type errReader int
+
+func (errReader) Read(p []byte) (n int, err error) {
+	return 0, errors.New("force")
+}
+func (errReader) Close() error {
+	return nil
+}
+
+func TestHandlerParseJWS(t *testing.T) {
+	url := "https://ca.smallstep.com/acme/new-account"
+	type test struct {
+		next       nextHTTP
+		body       io.Reader
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/read-body-error": func(t *testing.T) test {
+			return test{
+				body:       errReader(0),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("failed to read request body: force")),
+			}
+		},
+		"fail/parse-jws-error": func(t *testing.T) test {
+			return test{
+				body:       strings.NewReader("foo"),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("failed to parse JWS from request body: square/go-jose: compact JWS format must have three parts")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			signer, err := jose.NewSigner(jose.SigningKey{
+				Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+				Key:       jwk.Key,
+			}, new(jose.SignerOptions))
+			assert.FatalError(t, err)
+			signed, err := signer.Sign([]byte("baz"))
+			assert.FatalError(t, err)
+			expRaw, err := signed.CompactSerialize()
+			assert.FatalError(t, err)
+
+			return test{
+				body: strings.NewReader(expRaw),
+				next: func(w http.ResponseWriter, r *http.Request) {
+					jws, err := jwsFromContext(r)
+					assert.FatalError(t, err)
+					gotRaw, err := jws.CompactSerialize()
+					assert.FatalError(t, err)
+					assert.Equals(t, gotRaw, expRaw)
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(nil).(*Handler)
+			req := httptest.NewRequest("GET", url, tc.body)
+			w := httptest.NewRecorder()
+			h.parseJWS(tc.next)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerVerifyAndExtractJWSPayload(t *testing.T) {
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	assert.FatalError(t, err)
+	_pub := jwk.Public()
+	pub := &_pub
+	so := new(jose.SignerOptions)
+	so.WithHeader("alg", jose.SignatureAlgorithm(jwk.Algorithm))
+	signer, err := jose.NewSigner(jose.SigningKey{
+		Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+		Key:       jwk.Key,
+	}, so)
+	assert.FatalError(t, err)
+	jws, err := signer.Sign([]byte("baz"))
+	assert.FatalError(t, err)
+	raw, err := jws.CompactSerialize()
+	assert.FatalError(t, err)
+	parsedJWS, err := jose.ParseJWS(raw)
+	assert.FatalError(t, err)
+	url := "https://ca.smallstep.com/acme/account/1234"
+	type test struct {
+		ctx        context.Context
+		next       func(http.ResponseWriter, *http.Request)
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/nil-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/no-jwk": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jwk expected in request context")),
+			}
+		},
+		"fail/nil-jwk": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
+			return test{
+				ctx:        context.WithValue(ctx, jwkContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jwk expected in request context")),
+			}
+		},
+		"fail/verify-jws-failure": func(t *testing.T) test {
+			_jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			_pub := _jwk.Public()
+			ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
+			ctx = context.WithValue(ctx, jwkContextKey, &_pub)
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("error verifying jws: square/go-jose: error in cryptographic primitive")),
+			}
+		},
+		"fail/algorithm-mismatch": func(t *testing.T) test {
+			_pub := *pub
+			clone := &_pub
+			clone.Algorithm = jose.HS256
+			ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
+			ctx = context.WithValue(ctx, jwkContextKey, clone)
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("verifier and signature algorithm do not match")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
+			ctx = context.WithValue(ctx, jwkContextKey, pub)
+			return test{
+				ctx:        ctx,
+				statusCode: 200,
+				next: func(w http.ResponseWriter, r *http.Request) {
+					p, err := payloadFromContext(r)
+					assert.FatalError(t, err)
+					if assert.NotNil(t, p) {
+						assert.Equals(t, p.value, []byte("baz"))
+						assert.False(t, p.isPostAsGet)
+						assert.False(t, p.isEmptyJSON)
+					}
+					w.Write(testBody)
+				},
+			}
+		},
+		"ok/empty-algorithm-in-jwk": func(t *testing.T) test {
+			_pub := *pub
+			clone := &_pub
+			clone.Algorithm = ""
+			ctx := context.WithValue(context.Background(), jwsContextKey, parsedJWS)
+			ctx = context.WithValue(ctx, jwkContextKey, pub)
+			return test{
+				ctx:        ctx,
+				statusCode: 200,
+				next: func(w http.ResponseWriter, r *http.Request) {
+					p, err := payloadFromContext(r)
+					assert.FatalError(t, err)
+					if assert.NotNil(t, p) {
+						assert.Equals(t, p.value, []byte("baz"))
+						assert.False(t, p.isPostAsGet)
+						assert.False(t, p.isEmptyJSON)
+					}
+					w.Write(testBody)
+				},
+			}
+		},
+		"ok/post-as-get": func(t *testing.T) test {
+			_jws, err := signer.Sign([]byte(""))
+			assert.FatalError(t, err)
+			_raw, err := _jws.CompactSerialize()
+			assert.FatalError(t, err)
+			_parsed, err := jose.ParseJWS(_raw)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
+			ctx = context.WithValue(ctx, jwkContextKey, pub)
+			return test{
+				ctx:        ctx,
+				statusCode: 200,
+				next: func(w http.ResponseWriter, r *http.Request) {
+					p, err := payloadFromContext(r)
+					assert.FatalError(t, err)
+					if assert.NotNil(t, p) {
+						assert.Equals(t, p.value, []byte{})
+						assert.True(t, p.isPostAsGet)
+						assert.False(t, p.isEmptyJSON)
+					}
+					w.Write(testBody)
+				},
+			}
+		},
+		"ok/empty-json": func(t *testing.T) test {
+			_jws, err := signer.Sign([]byte("{}"))
+			assert.FatalError(t, err)
+			_raw, err := _jws.CompactSerialize()
+			assert.FatalError(t, err)
+			_parsed, err := jose.ParseJWS(_raw)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), jwsContextKey, _parsed)
+			ctx = context.WithValue(ctx, jwkContextKey, pub)
+			return test{
+				ctx:        ctx,
+				statusCode: 200,
+				next: func(w http.ResponseWriter, r *http.Request) {
+					p, err := payloadFromContext(r)
+					assert.FatalError(t, err)
+					if assert.NotNil(t, p) {
+						assert.Equals(t, p.value, []byte("{}"))
+						assert.False(t, p.isPostAsGet)
+						assert.True(t, p.isEmptyJSON)
+					}
+					w.Write(testBody)
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(nil).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.verifyAndExtractJWSPayload(tc.next)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerLookupJWK(t *testing.T) {
+	prov := newProv()
+	url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
+		acme.URLSafeProvisionerName(prov))
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	assert.FatalError(t, err)
+	accID := "account-id"
+	prefix := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/",
+		acme.URLSafeProvisionerName(prov))
+	so := new(jose.SignerOptions)
+	so.WithHeader("kid", fmt.Sprintf("%s%s", prefix, accID))
+	signer, err := jose.NewSigner(jose.SigningKey{
+		Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+		Key:       jwk.Key,
+	}, so)
+	assert.FatalError(t, err)
+	jws, err := signer.Sign([]byte("baz"))
+	assert.FatalError(t, err)
+	raw, err := jws.CompactSerialize()
+	assert.FatalError(t, err)
+	parsedJWS, err := jose.ParseJWS(raw)
+	assert.FatalError(t, err)
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		next       func(http.ResponseWriter, *http.Request)
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/nil-jws": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/no-kid": func(t *testing.T) test {
+			_signer, err := jose.NewSigner(jose.SigningKey{
+				Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+				Key:       jwk.Key,
+			}, new(jose.SignerOptions))
+			assert.FatalError(t, err)
+			_jws, err := _signer.Sign([]byte("baz"))
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, _jws)
+			return test{
+				auth: &mockAcmeAuthority{
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return prefix
+					},
+				},
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("kid does not have required prefix; expected %s, but got ", prefix)),
+			}
+		},
+		"fail/bad-kid-prefix": func(t *testing.T) test {
+			_so := new(jose.SignerOptions)
+			_so.WithHeader("kid", "foo")
+			_signer, err := jose.NewSigner(jose.SigningKey{
+				Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+				Key:       jwk.Key,
+			}, _so)
+			assert.FatalError(t, err)
+			_jws, err := _signer.Sign([]byte("baz"))
+			assert.FatalError(t, err)
+			_raw, err := _jws.CompactSerialize()
+			assert.FatalError(t, err)
+			_parsed, err := jose.ParseJWS(_raw)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, _parsed)
+			return test{
+				auth: &mockAcmeAuthority{
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/", acme.URLSafeProvisionerName(prov))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("kid does not have required prefix; expected %s, but got foo", prefix)),
+			}
+		},
+		"fail/account-not-found": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				auth: &mockAcmeAuthority{
+					getAccount: func(p provisioner.Interface, _accID string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, accID)
+						return nil, database.ErrNotFound
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/", acme.URLSafeProvisionerName(prov))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/GetAccount-error": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				auth: &mockAcmeAuthority{
+					getAccount: func(p provisioner.Interface, _accID string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, accID)
+						return nil, acme.ServerInternalErr(errors.New("force"))
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/", acme.URLSafeProvisionerName(prov))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"fail/account-not-valid": func(t *testing.T) test {
+			acc := &acme.Account{Status: "deactivated"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				auth: &mockAcmeAuthority{
+					getAccount: func(p provisioner.Interface, _accID string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, accID)
+						return acc, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/", acme.URLSafeProvisionerName(prov))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 401,
+				problem:    acme.UnauthorizedErr(errors.New("account is not active")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{Status: "valid", Key: jwk}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				auth: &mockAcmeAuthority{
+					getAccount: func(p provisioner.Interface, _accID string) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, accID)
+						return acc, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.AccountLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{""})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/", acme.URLSafeProvisionerName(prov))
+					},
+				},
+				ctx: ctx,
+				next: func(w http.ResponseWriter, r *http.Request) {
+					_acc, err := accountFromContext(r)
+					assert.FatalError(t, err)
+					assert.Equals(t, _acc, acc)
+					_jwk, err := jwkFromContext(r)
+					assert.FatalError(t, err)
+					assert.Equals(t, _jwk, jwk)
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.lookupJWK(tc.next)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerExtractJWK(t *testing.T) {
+	prov := newProv()
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	assert.FatalError(t, err)
+	kid, err := jwk.Thumbprint(crypto.SHA256)
+	assert.FatalError(t, err)
+	pub := jwk.Public()
+	pub.KeyID = base64.RawURLEncoding.EncodeToString(kid)
+
+	so := new(jose.SignerOptions)
+	so.WithHeader("jwk", pub)
+	signer, err := jose.NewSigner(jose.SigningKey{
+		Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
+		Key:       jwk.Key,
+	}, so)
+	assert.FatalError(t, err)
+	jws, err := signer.Sign([]byte("baz"))
+	assert.FatalError(t, err)
+	raw, err := jws.CompactSerialize()
+	assert.FatalError(t, err)
+	parsedJWS, err := jose.ParseJWS(raw)
+	assert.FatalError(t, err)
+	url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234",
+		acme.URLSafeProvisionerName(prov))
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		next       func(http.ResponseWriter, *http.Request)
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/nil-jws": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/nil-jwk": func(t *testing.T) test {
+			_jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							JSONWebKey: nil,
+						},
+					},
+				},
+			}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, _jws)
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("jwk expected in protected header")),
+			}
+		},
+		"fail/invalid-jwk": func(t *testing.T) test {
+			_jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							JSONWebKey: &jose.JSONWebKey{Key: "foo"},
+						},
+					},
+				},
+			}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, _jws)
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("invalid jwk in protected header")),
+			}
+		},
+		"fail/GetAccountByKey-error": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				ctx: ctx,
+				auth: &mockAcmeAuthority{
+					getAccountByKey: func(p provisioner.Interface, jwk *jose.JSONWebKey) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, jwk.KeyID, pub.KeyID)
+						return nil, acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"fail/account-not-valid": func(t *testing.T) test {
+			acc := &acme.Account{Status: "deactivated"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				ctx: ctx,
+				auth: &mockAcmeAuthority{
+					getAccountByKey: func(p provisioner.Interface, jwk *jose.JSONWebKey) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, jwk.KeyID, pub.KeyID)
+						return acc, nil
+					},
+				},
+				statusCode: 401,
+				problem:    acme.UnauthorizedErr(errors.New("account is not active")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{Status: "valid"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				ctx: ctx,
+				auth: &mockAcmeAuthority{
+					getAccountByKey: func(p provisioner.Interface, jwk *jose.JSONWebKey) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, jwk.KeyID, pub.KeyID)
+						return acc, nil
+					},
+				},
+				next: func(w http.ResponseWriter, r *http.Request) {
+					_acc, err := accountFromContext(r)
+					assert.FatalError(t, err)
+					assert.Equals(t, _acc, acc)
+					_jwk, err := jwkFromContext(r)
+					assert.FatalError(t, err)
+					assert.Equals(t, _jwk.KeyID, pub.KeyID)
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+		"ok/no-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, jwsContextKey, parsedJWS)
+			return test{
+				ctx: ctx,
+				auth: &mockAcmeAuthority{
+					getAccountByKey: func(p provisioner.Interface, jwk *jose.JSONWebKey) (*acme.Account, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, jwk.KeyID, pub.KeyID)
+						return nil, database.ErrNotFound
+					},
+				},
+				next: func(w http.ResponseWriter, r *http.Request) {
+					_acc, err := accountFromContext(r)
+					assert.NotNil(t, err)
+					assert.Nil(t, _acc)
+					_jwk, err := jwkFromContext(r)
+					assert.FatalError(t, err)
+					assert.Equals(t, _jwk.KeyID, pub.KeyID)
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.extractJWK(tc.next)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}
+
+func TestHandlerValidateJWS(t *testing.T) {
+	url := "https://ca.smallstep.com/acme/account/1234"
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		next       func(http.ResponseWriter, *http.Request)
+		problem    *acme.Error
+		statusCode int
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/nil-jws": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("jws expected in request context")),
+			}
+		},
+		"fail/no-signature": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, &jose.JSONWebSignature{}),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("request body does not contain a signature")),
+			}
+		},
+		"fail/more-than-one-signature": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{},
+					{},
+				},
+			}
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("request body contains more than one signature")),
+			}
+		},
+		"fail/unprotected-header-not-empty": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{Unprotected: jose.Header{Nonce: "abc"}},
+				},
+			}
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("unprotected header must not be used")),
+			}
+		},
+		"fail/unsuitable-algorithm-none": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{Protected: jose.Header{Algorithm: "none"}},
+				},
+			}
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("unsuitable algorithm: none")),
+			}
+		},
+		"fail/unsuitable-algorithm-mac": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{Protected: jose.Header{Algorithm: jose.HS256}},
+				},
+			}
+			return test{
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("unsuitable algorithm: %s", jose.HS256)),
+			}
+		},
+		"fail/rsa-key-&-alg-mismatch": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			pub := jwk.Public()
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm:  jose.RS256,
+							JSONWebKey: &pub,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("jws key type and algorithm do not match")),
+			}
+		},
+		"fail/rsa-key-too-small": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 1024)
+			assert.FatalError(t, err)
+			pub := jwk.Public()
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm:  jose.RS256,
+							JSONWebKey: &pub,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("rsa keys must be at least 2048 bits (256 bytes) in size")),
+			}
+		},
+		"fail/UseNonce-error": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{Protected: jose.Header{Algorithm: jose.ES256}},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return acme.ServerInternalErr(errors.New("force"))
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"fail/no-url-header": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{Protected: jose.Header{Algorithm: jose.ES256}},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("jws missing url protected header")),
+			}
+		},
+		"fail/url-mismatch": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm: jose.ES256,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": "foo",
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("url header in JWS (foo) does not match request url (%s)", url)),
+			}
+		},
+		"fail/both-jwk-kid": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			pub := jwk.Public()
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm:  jose.ES256,
+							KeyID:      "bar",
+							JSONWebKey: &pub,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("jwk and kid are mutually exclusive")),
+			}
+		},
+		"fail/no-jwk-kid": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm: jose.ES256,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx:        context.WithValue(context.Background(), jwsContextKey, jws),
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.Errorf("either jwk or kid must be defined in jws protected header")),
+			}
+		},
+		"ok/kid": func(t *testing.T) test {
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm: jose.ES256,
+							KeyID:     "bar",
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx: context.WithValue(context.Background(), jwsContextKey, jws),
+				next: func(w http.ResponseWriter, r *http.Request) {
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+		"ok/jwk/ecdsa": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			pub := jwk.Public()
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm:  jose.ES256,
+							JSONWebKey: &pub,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx: context.WithValue(context.Background(), jwsContextKey, jws),
+				next: func(w http.ResponseWriter, r *http.Request) {
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+		"ok/jwk/rsa": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("RSA", "", "", "sig", "", 2048)
+			assert.FatalError(t, err)
+			pub := jwk.Public()
+			jws := &jose.JSONWebSignature{
+				Signatures: []jose.Signature{
+					{
+						Protected: jose.Header{
+							Algorithm:  jose.RS256,
+							JSONWebKey: &pub,
+							ExtraHeaders: map[jose.HeaderKey]interface{}{
+								"url": url,
+							},
+						},
+					},
+				},
+			}
+			return test{
+				auth: &mockAcmeAuthority{
+					useNonce: func(n string) error {
+						return nil
+					},
+				},
+				ctx: context.WithValue(context.Background(), jwsContextKey, jws),
+				next: func(w http.ResponseWriter, r *http.Request) {
+					w.Write(testBody)
+					return
+				},
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.validateJWS(tc.next)(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				assert.Equals(t, bytes.TrimSpace(body), testBody)
+			}
+		})
+	}
+}

+ 164 - 0
acme/api/order.go

@@ -0,0 +1,164 @@
+package api
+
+import (
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/json"
+	"net/http"
+	"time"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/api"
+)
+
+// NewOrderRequest represents the body for a NewOrder request.
+type NewOrderRequest struct {
+	Identifiers []acme.Identifier `json:"identifiers"`
+	NotBefore   time.Time         `json:"notBefore,omitempty"`
+	NotAfter    time.Time         `json:"notAfter,omitempty"`
+}
+
+// Validate validates a new-order request body.
+func (n *NewOrderRequest) Validate() error {
+	if len(n.Identifiers) == 0 {
+		return acme.MalformedErr(errors.Errorf("identifiers list cannot be empty"))
+	}
+	for _, id := range n.Identifiers {
+		if id.Type != "dns" {
+			return acme.MalformedErr(errors.Errorf("identifier type unsupported: %s", id.Type))
+		}
+	}
+	return nil
+}
+
+// FinalizeRequest captures the body for a Finalize order request.
+type FinalizeRequest struct {
+	CSR string `json:"csr"`
+	csr *x509.CertificateRequest
+}
+
+// Validate validates a finalize request body.
+func (f *FinalizeRequest) Validate() error {
+	var err error
+	csrBytes, err := base64.RawURLEncoding.DecodeString(f.CSR)
+	if err != nil {
+		return acme.MalformedErr(errors.Wrap(err, "error base64url decoding csr"))
+	}
+	f.csr, err = x509.ParseCertificateRequest(csrBytes)
+	if err != nil {
+		return acme.MalformedErr(errors.Wrap(err, "unable to parse csr"))
+	}
+	if err = f.csr.CheckSignature(); err != nil {
+		return acme.MalformedErr(errors.Wrap(err, "csr failed signature check"))
+	}
+	return nil
+}
+
+// NewOrder ACME api for creating a new order.
+func (h *Handler) NewOrder(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	payload, err := payloadFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	var nor NewOrderRequest
+	if err := json.Unmarshal(payload.value, &nor); err != nil {
+		api.WriteError(w, acme.MalformedErr(errors.Wrap(err,
+			"failed to unmarshal new-order request payload")))
+		return
+	}
+	if err := nor.Validate(); err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	o, err := h.Auth.NewOrder(prov, acme.OrderOptions{
+		AccountID:   acc.GetID(),
+		Identifiers: nor.Identifiers,
+		NotBefore:   nor.NotBefore,
+		NotAfter:    nor.NotAfter,
+	})
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	w.Header().Set("Location", h.Auth.GetLink(acme.OrderLink, acme.URLSafeProvisionerName(prov), true, o.GetID()))
+	api.JSONStatus(w, o, http.StatusCreated)
+	return
+}
+
+// GetOrder ACME api for retrieving an order.
+func (h *Handler) GetOrder(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	oid := chi.URLParam(r, "ordID")
+	o, err := h.Auth.GetOrder(prov, acc.GetID(), oid)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	w.Header().Set("Location", h.Auth.GetLink(acme.OrderLink, acme.URLSafeProvisionerName(prov), true, o.GetID()))
+	api.JSON(w, o)
+	return
+}
+
+// FinalizeOrder attemptst to finalize an order and create a certificate.
+func (h *Handler) FinalizeOrder(w http.ResponseWriter, r *http.Request) {
+	prov, err := provisionerFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	acc, err := accountFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	payload, err := payloadFromContext(r)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+	var fr FinalizeRequest
+	if err := json.Unmarshal(payload.value, &fr); err != nil {
+		api.WriteError(w, acme.MalformedErr(errors.Wrap(err, "failed to unmarshal finalize-order request payload")))
+		return
+	}
+	if err := fr.Validate(); err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	oid := chi.URLParam(r, "ordID")
+	o, err := h.Auth.FinalizeOrder(prov, acc.GetID(), oid, fr.csr)
+	if err != nil {
+		api.WriteError(w, err)
+		return
+	}
+
+	w.Header().Set("Location", h.Auth.GetLink(acme.OrderLink, acme.URLSafeProvisionerName(prov), true, o.ID))
+	api.JSON(w, o)
+	return
+}

+ 757 - 0
acme/api/order_test.go

@@ -0,0 +1,757 @@
+package api
+
+import (
+	"bytes"
+	"context"
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/acme"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/crypto/pemutil"
+)
+
+func TestNewOrderRequestValidate(t *testing.T) {
+	type test struct {
+		nor      *NewOrderRequest
+		nbf, naf time.Time
+		err      *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-identifiers": func(t *testing.T) test {
+			return test{
+				nor: &NewOrderRequest{},
+				err: acme.MalformedErr(errors.Errorf("identifiers list cannot be empty")),
+			}
+		},
+		"fail/bad-identifier": func(t *testing.T) test {
+			return test{
+				nor: &NewOrderRequest{
+					Identifiers: []acme.Identifier{
+						{Type: "dns", Value: "example.com"},
+						{Type: "foo", Value: "bar.com"},
+					},
+				},
+				err: acme.MalformedErr(errors.Errorf("identifier type unsupported: foo")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			nbf := time.Now().UTC().Add(time.Minute)
+			naf := time.Now().UTC().Add(5 * time.Minute)
+			return test{
+				nor: &NewOrderRequest{
+					Identifiers: []acme.Identifier{
+						{Type: "dns", Value: "example.com"},
+						{Type: "dns", Value: "bar.com"},
+					},
+					NotAfter:  naf,
+					NotBefore: nbf,
+				},
+				nbf: nbf,
+				naf: naf,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			if err := tc.nor.Validate(); err != nil {
+				if assert.NotNil(t, err) {
+					ae, ok := err.(*acme.Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					if tc.nbf.IsZero() {
+						assert.True(t, tc.nor.NotBefore.Before(time.Now().Add(time.Minute)))
+						assert.True(t, tc.nor.NotBefore.After(time.Now().Add(-time.Minute)))
+					} else {
+						assert.Equals(t, tc.nor.NotBefore, tc.nbf)
+					}
+					if tc.naf.IsZero() {
+						assert.True(t, tc.nor.NotAfter.Before(time.Now().Add(24*time.Hour)))
+						assert.True(t, tc.nor.NotAfter.After(time.Now().Add(24*time.Hour-time.Minute)))
+					} else {
+						assert.Equals(t, tc.nor.NotAfter, tc.naf)
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestFinalizeRequestValidate(t *testing.T) {
+	_csr, err := pemutil.Read("../../authority/testdata/certs/foo.csr")
+	assert.FatalError(t, err)
+	csr, ok := _csr.(*x509.CertificateRequest)
+	assert.Fatal(t, ok)
+	type test struct {
+		fr  *FinalizeRequest
+		err *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/parse-csr-error": func(t *testing.T) test {
+			return test{
+				fr:  &FinalizeRequest{},
+				err: acme.MalformedErr(errors.Errorf("unable to parse csr: asn1: syntax error: sequence truncated")),
+			}
+		},
+		"fail/invalid-csr-signature": func(t *testing.T) test {
+			b, err := pemutil.Read("../../authority/testdata/certs/badsig.csr")
+			assert.FatalError(t, err)
+			c, ok := b.(*x509.CertificateRequest)
+			assert.Fatal(t, ok)
+			return test{
+				fr: &FinalizeRequest{
+					CSR: base64.RawURLEncoding.EncodeToString(c.Raw),
+				},
+				err: acme.MalformedErr(errors.Errorf("csr failed signature check: x509: ECDSA verification failure")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			return test{
+				fr: &FinalizeRequest{
+					CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			if err := tc.fr.Validate(); err != nil {
+				if assert.NotNil(t, err) {
+					ae, ok := err.(*acme.Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.fr.csr.Raw, csr.Raw)
+				}
+			}
+		})
+	}
+}
+
+func TestHandlerGetOrder(t *testing.T) {
+	expiry := time.Now().UTC().Add(6 * time.Hour)
+	nbf := time.Now().UTC()
+	naf := time.Now().UTC().Add(24 * time.Hour)
+	o := acme.Order{
+		ID:        "orderID",
+		Expires:   expiry.Format(time.RFC3339),
+		NotBefore: nbf.Format(time.RFC3339),
+		NotAfter:  naf.Format(time.RFC3339),
+		Identifiers: []acme.Identifier{
+			{
+				Type:  "dns",
+				Value: "example.com",
+			},
+			{
+				Type:  "dns",
+				Value: "*.smallstep.com",
+			},
+		},
+		Status:         "pending",
+		Authorizations: []string{"foo", "bar"},
+	}
+
+	// Request with chi context
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("ordID", o.ID)
+	prov := newProv()
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/order/%s",
+		acme.URLSafeProvisionerName(prov), o.ID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/getOrder-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					err: acme.ServerInternalErr(errors.New("force")),
+				},
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					getOrder: func(p provisioner.Interface, accID, id string) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, o.ID)
+						return &o, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.OrderLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{o.ID})
+						return url
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.GetOrder(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(o)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"], []string{url})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerNewOrder(t *testing.T) {
+	expiry := time.Now().UTC().Add(6 * time.Hour)
+	nbf := time.Now().UTC().Add(5 * time.Hour)
+	naf := nbf.Add(17 * time.Hour)
+	o := acme.Order{
+		ID:        "orderID",
+		Expires:   expiry.Format(time.RFC3339),
+		NotBefore: nbf.Format(time.RFC3339),
+		NotAfter:  naf.Format(time.RFC3339),
+		Identifiers: []acme.Identifier{
+			{Type: "dns", Value: "example.com"},
+			{Type: "dns", Value: "bar.com"},
+		},
+		Status:         "pending",
+		Authorizations: []string{"foo", "bar"},
+	}
+
+	prov := newProv()
+	url := fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-order",
+		acme.URLSafeProvisionerName(prov))
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/no-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/unmarshal-payload-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("failed to unmarshal new-order request payload: unexpected end of JSON input")),
+			}
+		},
+		"fail/malformed-payload-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &NewOrderRequest{}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("identifiers list cannot be empty")),
+			}
+		},
+		"fail/NewOrder-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &NewOrderRequest{
+				Identifiers: []acme.Identifier{
+					{Type: "dns", Value: "example.com"},
+					{Type: "dns", Value: "bar.com"},
+				},
+			}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, ops.AccountID, acc.ID)
+						assert.Equals(t, ops.Identifiers, nor.Identifiers)
+						return nil, acme.MalformedErr(errors.New("force"))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &NewOrderRequest{
+				Identifiers: []acme.Identifier{
+					{Type: "dns", Value: "example.com"},
+					{Type: "dns", Value: "bar.com"},
+				},
+				NotBefore: nbf,
+				NotAfter:  naf,
+			}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, ops.AccountID, acc.ID)
+						assert.Equals(t, ops.Identifiers, nor.Identifiers)
+						assert.Equals(t, ops.NotBefore, nbf)
+						assert.Equals(t, ops.NotAfter, naf)
+						return &o, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.OrderLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{o.ID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 201,
+			}
+		},
+		"ok/default-naf-nbf": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &NewOrderRequest{
+				Identifiers: []acme.Identifier{
+					{Type: "dns", Value: "example.com"},
+					{Type: "dns", Value: "bar.com"},
+				},
+			}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				auth: &mockAcmeAuthority{
+					newOrder: func(p provisioner.Interface, ops acme.OrderOptions) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, ops.AccountID, acc.ID)
+						assert.Equals(t, ops.Identifiers, nor.Identifiers)
+
+						assert.True(t, ops.NotBefore.IsZero())
+						assert.True(t, ops.NotAfter.IsZero())
+						return &o, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.OrderLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{o.ID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 201,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.NewOrder(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(o)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"],
+					[]string{fmt.Sprintf("https://ca.smallstep.com/acme/order/%s", o.ID)})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}
+
+func TestHandlerFinalizeOrder(t *testing.T) {
+	expiry := time.Now().UTC().Add(6 * time.Hour)
+	nbf := time.Now().UTC().Add(5 * time.Hour)
+	naf := nbf.Add(17 * time.Hour)
+	o := acme.Order{
+		ID:        "orderID",
+		Expires:   expiry.Format(time.RFC3339),
+		NotBefore: nbf.Format(time.RFC3339),
+		NotAfter:  naf.Format(time.RFC3339),
+		Identifiers: []acme.Identifier{
+			{Type: "dns", Value: "example.com"},
+			{Type: "dns", Value: "bar.com"},
+		},
+		Status:         "valid",
+		Authorizations: []string{"foo", "bar"},
+		Certificate:    "https://ca.smallstep.com/acme/certificate/certID",
+	}
+	_csr, err := pemutil.Read("../../authority/testdata/certs/foo.csr")
+	assert.FatalError(t, err)
+	csr, ok := _csr.(*x509.CertificateRequest)
+	assert.Fatal(t, ok)
+
+	// Request with chi context
+	chiCtx := chi.NewRouteContext()
+	chiCtx.URLParams.Add("ordID", o.ID)
+	prov := newProv()
+	url := fmt.Sprintf("http://ca.smallstep.com/acme/%s/order/%s/finalize",
+		acme.URLSafeProvisionerName(prov), o.ID)
+
+	type test struct {
+		auth       acme.Interface
+		ctx        context.Context
+		statusCode int
+		problem    *acme.Error
+	}
+	var tests = map[string]func(t *testing.T) test{
+		"fail/no-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.Background(),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/nil-provisioner": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, nil),
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("provisioner expected in request context")),
+			}
+		},
+		"fail/no-account": func(t *testing.T) test {
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        context.WithValue(context.Background(), provisionerContextKey, prov),
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/nil-account": func(t *testing.T) test {
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, nil)
+			return test{
+				auth:       &mockAcmeAuthority{},
+				ctx:        ctx,
+				statusCode: 404,
+				problem:    acme.AccountDoesNotExistErr(nil),
+			}
+		},
+		"fail/no-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/nil-payload": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, nil)
+			return test{
+				ctx:        ctx,
+				statusCode: 500,
+				problem:    acme.ServerInternalErr(errors.New("payload expected in request context")),
+			}
+		},
+		"fail/unmarshal-payload-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("failed to unmarshal finalize-order request payload: unexpected end of JSON input")),
+			}
+		},
+		"fail/malformed-payload-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			fr := &FinalizeRequest{}
+			b, err := json.Marshal(fr)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			return test{
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("unable to parse csr: asn1: syntax error: sequence truncated")),
+			}
+		},
+		"fail/FinalizeOrder-error": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &FinalizeRequest{
+				CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
+			}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					finalizeOrder: func(p provisioner.Interface, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, o.ID)
+						assert.Equals(t, incsr.Raw, csr.Raw)
+						return nil, acme.MalformedErr(errors.New("force"))
+					},
+				},
+				ctx:        ctx,
+				statusCode: 400,
+				problem:    acme.MalformedErr(errors.New("force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc := &acme.Account{ID: "accID"}
+			nor := &FinalizeRequest{
+				CSR: base64.RawURLEncoding.EncodeToString(csr.Raw),
+			}
+			b, err := json.Marshal(nor)
+			assert.FatalError(t, err)
+			ctx := context.WithValue(context.Background(), provisionerContextKey, prov)
+			ctx = context.WithValue(ctx, accContextKey, acc)
+			ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
+			ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
+			return test{
+				auth: &mockAcmeAuthority{
+					finalizeOrder: func(p provisioner.Interface, accID, id string, incsr *x509.CertificateRequest) (*acme.Order, error) {
+						assert.Equals(t, p, prov)
+						assert.Equals(t, accID, acc.ID)
+						assert.Equals(t, id, o.ID)
+						assert.Equals(t, incsr.Raw, csr.Raw)
+						return &o, nil
+					},
+					getLink: func(typ acme.Link, provID string, abs bool, in ...string) string {
+						assert.Equals(t, typ, acme.OrderLink)
+						assert.Equals(t, provID, acme.URLSafeProvisionerName(prov))
+						assert.True(t, abs)
+						assert.Equals(t, in, []string{o.ID})
+						return fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s",
+							acme.URLSafeProvisionerName(prov), o.ID)
+					},
+				},
+				ctx:        ctx,
+				statusCode: 200,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*Handler)
+			req := httptest.NewRequest("GET", url, nil)
+			req = req.WithContext(tc.ctx)
+			w := httptest.NewRecorder()
+			h.FinalizeOrder(w, req)
+			res := w.Result()
+
+			assert.Equals(t, res.StatusCode, tc.statusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if res.StatusCode >= 400 && assert.NotNil(t, tc.problem) {
+				var ae acme.AError
+				assert.FatalError(t, json.Unmarshal(bytes.TrimSpace(body), &ae))
+				prob := tc.problem.ToACME()
+
+				assert.Equals(t, ae.Type, prob.Type)
+				assert.Equals(t, ae.Detail, prob.Detail)
+				assert.Equals(t, ae.Identifier, prob.Identifier)
+				assert.Equals(t, ae.Subproblems, prob.Subproblems)
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/problem+json"})
+			} else {
+				expB, err := json.Marshal(o)
+				assert.FatalError(t, err)
+				assert.Equals(t, bytes.TrimSpace(body), expB)
+				assert.Equals(t, res.Header["Location"],
+					[]string{fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s",
+						acme.URLSafeProvisionerName(prov), o.ID)})
+				assert.Equals(t, res.Header["Content-Type"], []string{"application/json"})
+			}
+		})
+	}
+}

+ 263 - 0
acme/authority.go

@@ -0,0 +1,263 @@
+package acme
+
+import (
+	"crypto"
+	"crypto/x509"
+	"encoding/base64"
+	"net"
+	"net/http"
+	"net/url"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+)
+
+// Interface is the acme authority interface.
+type Interface interface {
+	DeactivateAccount(provisioner.Interface, string) (*Account, error)
+	FinalizeOrder(provisioner.Interface, string, string, *x509.CertificateRequest) (*Order, error)
+	GetAccount(provisioner.Interface, string) (*Account, error)
+	GetAccountByKey(provisioner.Interface, *jose.JSONWebKey) (*Account, error)
+	GetAuthz(provisioner.Interface, string, string) (*Authz, error)
+	GetCertificate(string, string) ([]byte, error)
+	GetDirectory(provisioner.Interface) *Directory
+	GetLink(Link, string, bool, ...string) string
+	GetOrder(provisioner.Interface, string, string) (*Order, error)
+	GetOrdersByAccount(provisioner.Interface, string) ([]string, error)
+	LoadProvisionerByID(string) (provisioner.Interface, error)
+	NewAccount(provisioner.Interface, AccountOptions) (*Account, error)
+	NewNonce() (string, error)
+	NewOrder(provisioner.Interface, OrderOptions) (*Order, error)
+	UpdateAccount(provisioner.Interface, string, []string) (*Account, error)
+	UseNonce(string) error
+	ValidateChallenge(provisioner.Interface, string, string, *jose.JSONWebKey) (*Challenge, error)
+}
+
+// Authority is the layer that handles all ACME interactions.
+type Authority struct {
+	db       nosql.DB
+	dir      *directory
+	signAuth SignAuthority
+}
+
+// NewAuthority returns a new Authority that implements the ACME interface.
+func NewAuthority(db nosql.DB, dns, prefix string, signAuth SignAuthority) *Authority {
+	return &Authority{
+		db: db, dir: newDirectory(dns, prefix), signAuth: signAuth,
+	}
+}
+
+// GetLink returns the requested link from the directory.
+func (a *Authority) GetLink(typ Link, provID string, abs bool, inputs ...string) string {
+	return a.dir.getLink(typ, provID, abs, inputs...)
+}
+
+// GetDirectory returns the ACME directory object.
+func (a *Authority) GetDirectory(p provisioner.Interface) *Directory {
+	name := url.PathEscape(p.GetName())
+	return &Directory{
+		NewNonce:   a.dir.getLink(NewNonceLink, name, true),
+		NewAccount: a.dir.getLink(NewAccountLink, name, true),
+		NewOrder:   a.dir.getLink(NewOrderLink, name, true),
+		RevokeCert: a.dir.getLink(RevokeCertLink, name, true),
+		KeyChange:  a.dir.getLink(KeyChangeLink, name, true),
+	}
+}
+
+// LoadProvisionerByID calls out to the SignAuthority interface to load a
+// provisioner by ID.
+func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
+	return a.signAuth.LoadProvisionerByID(id)
+}
+
+// NewNonce generates, stores, and returns a new ACME nonce.
+func (a *Authority) NewNonce() (string, error) {
+	n, err := newNonce(a.db)
+	if err != nil {
+		return "", err
+	}
+	return n.ID, nil
+}
+
+// UseNonce consumes the given nonce if it is valid, returns error otherwise.
+func (a *Authority) UseNonce(nonce string) error {
+	return useNonce(a.db, nonce)
+}
+
+// NewAccount creates, stores, and returns a new ACME account.
+func (a *Authority) NewAccount(p provisioner.Interface, ao AccountOptions) (*Account, error) {
+	acc, err := newAccount(a.db, ao)
+	if err != nil {
+		return nil, err
+	}
+	return acc.toACME(a.db, a.dir, p)
+}
+
+// UpdateAccount updates an ACME account.
+func (a *Authority) UpdateAccount(p provisioner.Interface, id string, contact []string) (*Account, error) {
+	acc, err := getAccountByID(a.db, id)
+	if err != nil {
+		return nil, ServerInternalErr(err)
+	}
+	if acc, err = acc.update(a.db, contact); err != nil {
+		return nil, err
+	}
+	return acc.toACME(a.db, a.dir, p)
+}
+
+// GetAccount returns an ACME account.
+func (a *Authority) GetAccount(p provisioner.Interface, id string) (*Account, error) {
+	acc, err := getAccountByID(a.db, id)
+	if err != nil {
+		return nil, err
+	}
+	return acc.toACME(a.db, a.dir, p)
+}
+
+// DeactivateAccount deactivates an ACME account.
+func (a *Authority) DeactivateAccount(p provisioner.Interface, id string) (*Account, error) {
+	acc, err := getAccountByID(a.db, id)
+	if err != nil {
+		return nil, err
+	}
+	if acc, err = acc.deactivate(a.db); err != nil {
+		return nil, err
+	}
+	return acc.toACME(a.db, a.dir, p)
+}
+
+func keyToID(jwk *jose.JSONWebKey) (string, error) {
+	kid, err := jwk.Thumbprint(crypto.SHA256)
+	if err != nil {
+		return "", ServerInternalErr(errors.Wrap(err, "error generating jwk thumbprint"))
+	}
+	return base64.RawURLEncoding.EncodeToString(kid), nil
+}
+
+// GetAccountByKey returns the ACME associated with the jwk id.
+func (a *Authority) GetAccountByKey(p provisioner.Interface, jwk *jose.JSONWebKey) (*Account, error) {
+	kid, err := keyToID(jwk)
+	if err != nil {
+		return nil, err
+	}
+	acc, err := getAccountByKeyID(a.db, kid)
+	if err != nil {
+		return nil, err
+	}
+	return acc.toACME(a.db, a.dir, p)
+}
+
+// GetOrder returns an ACME order.
+func (a *Authority) GetOrder(p provisioner.Interface, accID, orderID string) (*Order, error) {
+	o, err := getOrder(a.db, orderID)
+	if err != nil {
+		return nil, err
+	}
+	if accID != o.AccountID {
+		return nil, UnauthorizedErr(errors.New("account does not own order"))
+	}
+	if o, err = o.updateStatus(a.db); err != nil {
+		return nil, err
+	}
+	return o.toACME(a.db, a.dir, p)
+}
+
+// GetOrdersByAccount returns the list of order urls owned by the account.
+func (a *Authority) GetOrdersByAccount(p provisioner.Interface, id string) ([]string, error) {
+	oids, err := getOrderIDsByAccount(a.db, id)
+	if err != nil {
+		return nil, err
+	}
+
+	var ret = []string{}
+	for _, oid := range oids {
+		o, err := getOrder(a.db, oid)
+		if err != nil {
+			return nil, ServerInternalErr(err)
+		}
+		if o.Status == StatusInvalid {
+			continue
+		}
+		ret = append(ret, a.dir.getLink(OrderLink, URLSafeProvisionerName(p), true, o.ID))
+	}
+	return ret, nil
+}
+
+// NewOrder generates, stores, and returns a new ACME order.
+func (a *Authority) NewOrder(p provisioner.Interface, ops OrderOptions) (*Order, error) {
+	order, err := newOrder(a.db, ops)
+	if err != nil {
+		return nil, Wrap(err, "error creating order")
+	}
+	return order.toACME(a.db, a.dir, p)
+}
+
+// FinalizeOrder attempts to finalize an order and generate a new certificate.
+func (a *Authority) FinalizeOrder(p provisioner.Interface, accID, orderID string, csr *x509.CertificateRequest) (*Order, error) {
+	o, err := getOrder(a.db, orderID)
+	if err != nil {
+		return nil, err
+	}
+	if accID != o.AccountID {
+		return nil, UnauthorizedErr(errors.New("account does not own order"))
+	}
+	o, err = o.finalize(a.db, csr, a.signAuth, p)
+	if err != nil {
+		return nil, Wrap(err, "error finalizing order")
+	}
+	return o.toACME(a.db, a.dir, p)
+}
+
+// GetAuthz retrieves and attempts to update the status on an ACME authz
+// before returning.
+func (a *Authority) GetAuthz(p provisioner.Interface, accID, authzID string) (*Authz, error) {
+	az, err := getAuthz(a.db, authzID)
+	if err != nil {
+		return nil, err
+	}
+	if accID != az.getAccountID() {
+		return nil, UnauthorizedErr(errors.New("account does not own authz"))
+	}
+	az, err = az.updateStatus(a.db)
+	if err != nil {
+		return nil, Wrap(err, "error updating authz status")
+	}
+	return az.toACME(a.db, a.dir, p)
+}
+
+// ValidateChallenge attempts to validate the challenge.
+func (a *Authority) ValidateChallenge(p provisioner.Interface, accID, chID string, jwk *jose.JSONWebKey) (*Challenge, error) {
+	ch, err := getChallenge(a.db, chID)
+	if err != nil {
+		return nil, err
+	}
+	if accID != ch.getAccountID() {
+		return nil, UnauthorizedErr(errors.New("account does not own challenge"))
+	}
+	client := http.Client{
+		Timeout: time.Duration(30 * time.Second),
+	}
+	ch, err = ch.validate(a.db, jwk, validateOptions{
+		httpGet:   client.Get,
+		lookupTxt: net.LookupTXT,
+	})
+	if err != nil {
+		return nil, Wrap(err, "error attempting challenge validation")
+	}
+	return ch.toACME(a.db, a.dir, p)
+}
+
+// GetCertificate retrieves the Certificate by ID.
+func (a *Authority) GetCertificate(accID, certID string) ([]byte, error) {
+	cert, err := getCert(a.db, certID)
+	if err != nil {
+		return nil, err
+	}
+	if accID != cert.AccountID {
+		return nil, UnauthorizedErr(errors.New("account does not own certificate"))
+	}
+	return cert.toACME(a.db, a.dir)
+}

+ 1474 - 0
acme/authority_test.go

@@ -0,0 +1,1474 @@
+package acme
+
+import (
+	"encoding/json"
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql/database"
+)
+
+func TestAuthorityGetLink(t *testing.T) {
+	auth := NewAuthority(nil, "ca.smallstep.com", "acme", nil)
+	provID := "acme-test-provisioner"
+	type test struct {
+		auth   *Authority
+		typ    Link
+		abs    bool
+		inputs []string
+		res    string
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok/new-account/abs": func(t *testing.T) test {
+			return test{
+				auth: auth,
+				typ:  NewAccountLink,
+				abs:  true,
+				res:  fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-account", provID),
+			}
+		},
+		"ok/new-account/no-abs": func(t *testing.T) test {
+			return test{
+				auth: auth,
+				typ:  NewAccountLink,
+				abs:  false,
+				res:  fmt.Sprintf("/%s/new-account", provID),
+			}
+		},
+		"ok/order/abs": func(t *testing.T) test {
+			return test{
+				auth:   auth,
+				typ:    OrderLink,
+				abs:    true,
+				inputs: []string{"foo"},
+				res:    fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/foo", provID),
+			}
+		},
+		"ok/order/no-abs": func(t *testing.T) test {
+			return test{
+				auth:   auth,
+				typ:    OrderLink,
+				abs:    false,
+				inputs: []string{"foo"},
+				res:    fmt.Sprintf("/%s/order/foo", provID),
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			link := tc.auth.GetLink(tc.typ, provID, tc.abs, tc.inputs...)
+			assert.Equals(t, tc.res, link)
+		})
+	}
+}
+
+func TestAuthorityGetDirectory(t *testing.T) {
+	auth := NewAuthority(nil, "ca.smallstep.com", "acme", nil)
+	prov := newProv()
+	acmeDir := auth.GetDirectory(prov)
+	assert.Equals(t, acmeDir.NewNonce, fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-nonce", URLSafeProvisionerName(prov)))
+	assert.Equals(t, acmeDir.NewAccount, fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-account", URLSafeProvisionerName(prov)))
+	assert.Equals(t, acmeDir.NewOrder, fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-order", URLSafeProvisionerName(prov)))
+	//assert.Equals(t, acmeDir.NewOrder, "httsp://ca.smallstep.com/acme/new-authz")
+	assert.Equals(t, acmeDir.RevokeCert, fmt.Sprintf("https://ca.smallstep.com/acme/%s/revoke-cert", URLSafeProvisionerName(prov)))
+	assert.Equals(t, acmeDir.KeyChange, fmt.Sprintf("https://ca.smallstep.com/acme/%s/key-change", URLSafeProvisionerName(prov)))
+}
+
+func TestAuthorityNewNonce(t *testing.T) {
+	type test struct {
+		auth *Authority
+		res  *string
+		err  *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/newNonce-error": func(t *testing.T) test {
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				res:  nil,
+				err:  ServerInternalErr(errors.New("error storing nonce: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var _res string
+			res := &_res
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					*res = string(key)
+					return nil, true, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				res:  res,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if nonce, err := tc.auth.NewNonce(); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, nonce, *tc.res)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityUseNonce(t *testing.T) {
+	type test struct {
+		auth *Authority
+		err  *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/newNonce-error": func(t *testing.T) test {
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MUpdate: func(tx *database.Tx) error {
+					return errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				err:  ServerInternalErr(errors.New("error deleting nonce foo: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MUpdate: func(tx *database.Tx) error {
+					return nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.auth.UseNonce("foo"); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestAuthorityNewAccount(t *testing.T) {
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	assert.FatalError(t, err)
+	ops := AccountOptions{
+		Key: jwk, Contact: []string{"foo", "bar"},
+	}
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		ops  AccountOptions
+		err  *Error
+		acc  **Account
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/newAccount-error": func(t *testing.T) test {
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				ops:  ops,
+				err:  ServerInternalErr(errors.New("error setting key-id to account-id index: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var (
+				_acmeacc = &Account{}
+				acmeacc  = &_acmeacc
+				count    = 0
+				dir      = newDirectory("ca.smallstep.com", "acme")
+			)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					if count == 1 {
+						var acc *account
+						assert.FatalError(t, json.Unmarshal(newval, &acc))
+						*acmeacc, err = acc.toACME(nil, dir, prov)
+						return nil, true, nil
+					}
+					count++
+					return nil, true, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				ops:  ops,
+				acc:  acmeacc,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAcc, err := tc.auth.NewAccount(prov, tc.ops); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAcc)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(*tc.acc)
+					assert.FatalError(t, err)
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetAccount(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		id   string
+		err  *Error
+		acc  *account
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getAccount-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, accountTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.Errorf("error loading account %s: force", id)),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   acc.ID,
+				acc:  acc,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAcc, err := tc.auth.GetAccount(prov, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAcc)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.acc.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetAccountByKey(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		jwk  *jose.JSONWebKey
+		err  *Error
+		acc  *account
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/generate-thumbprint-error": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			jwk.Key = "foo"
+			auth := NewAuthority(nil, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				jwk:  jwk,
+				err:  ServerInternalErr(errors.New("error generating jwk thumbprint: square/go-jose: unknown key type 'string'")),
+			}
+		},
+		"fail/getAccount-error": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			kid, err := keyToID(jwk)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, accountByKeyIDTable)
+					assert.Equals(t, key, []byte(kid))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				jwk:  jwk,
+				err:  ServerInternalErr(errors.New("error loading key-account index: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+			count := 0
+			kid, err := keyToID(acc.Key)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch {
+					case count == 0:
+						assert.Equals(t, bucket, accountByKeyIDTable)
+						assert.Equals(t, key, []byte(kid))
+						ret = []byte(acc.ID)
+					case count == 1:
+						assert.Equals(t, bucket, accountTable)
+						assert.Equals(t, key, []byte(acc.ID))
+						ret = b
+					}
+					count++
+					return ret, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				jwk:  acc.Key,
+				acc:  acc,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAcc, err := tc.auth.GetAccountByKey(prov, tc.jwk); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAcc)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.acc.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetOrder(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth      *Authority
+		id, accID string
+		err       *Error
+		o         *order
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getOrder-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.New("error loading order foo: force")),
+			}
+		},
+		"fail/order-not-owned-by-account": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: "foo",
+				err:   UnauthorizedErr(errors.New("account does not own order")),
+			}
+		},
+		"fail/updateStatus-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			i := 0
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					switch {
+					case i == 0:
+						i++
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(o.ID))
+						return b, nil
+					default:
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, key, []byte(o.Authorizations[0]))
+						return nil, ServerInternalErr(errors.New("force"))
+					}
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: o.AccountID,
+				err:   ServerInternalErr(errors.Errorf("error loading authz %s: force", o.Authorizations[0])),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = "valid"
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: o.AccountID,
+				o:     o,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeO, err := tc.auth.GetOrder(prov, tc.accID, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeO)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.o.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetCertificate(t *testing.T) {
+	type test struct {
+		auth      *Authority
+		id, accID string
+		err       *Error
+		cert      *certificate
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getCertificate-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, certTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.New("error loading certificate: force")),
+			}
+		},
+		"fail/certificate-not-owned-by-account": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(cert)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, certTable)
+					assert.Equals(t, key, []byte(cert.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    cert.ID,
+				accID: "foo",
+				err:   UnauthorizedErr(errors.New("account does not own certificate")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(cert)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, certTable)
+					assert.Equals(t, key, []byte(cert.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    cert.ID,
+				accID: cert.AccountID,
+				cert:  cert,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeCert, err := tc.auth.GetCertificate(tc.accID, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeCert)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.cert.toACME(nil, tc.auth.dir)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetAuthz(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth      *Authority
+		id, accID string
+		err       *Error
+		acmeAz    *Authz
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getAuthz-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, authzTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.Errorf("error loading authz %s: force", id)),
+			}
+		},
+		"fail/authz-not-owned-by-account": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, authzTable)
+					assert.Equals(t, key, []byte(az.getID()))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    az.getID(),
+				accID: "foo",
+				err:   UnauthorizedErr(errors.New("account does not own authz")),
+			}
+		},
+		"fail/update-status-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			count := 0
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, key, []byte(az.getID()))
+						ret = b
+					case 1:
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(az.getChallenges()[0]))
+						return nil, errors.New("force")
+					}
+					count++
+					return ret, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    az.getID(),
+				accID: az.getAccountID(),
+				err:   ServerInternalErr(errors.New("error updating authz status: error loading challenge")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var ch1B, ch2B = &[]byte{}, &[]byte{}
+			count := 0
+			mockdb := &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					switch count {
+					case 0:
+						*ch1B = newval
+					case 1:
+						*ch2B = newval
+					}
+					count++
+					return nil, true, nil
+				},
+			}
+			az, err := newAuthz(mockdb, "1234", Identifier{
+				Type: "dns", Value: "acme.example.com",
+			})
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Status = StatusValid
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+
+			ch1, err := unmarshalChallenge(*ch1B)
+			assert.FatalError(t, err)
+			ch2, err := unmarshalChallenge(*ch2B)
+			assert.FatalError(t, err)
+			count = 0
+			mockdb = &db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch1.getID()))
+						ret = *ch1B
+					case 1:
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch2.getID()))
+						ret = *ch2B
+					}
+					count++
+					return ret, nil
+				},
+			}
+			acmeAz, err := az.toACME(mockdb, newDirectory("ca.smallstep.com", "acme"), prov)
+			assert.FatalError(t, err)
+
+			count = 0
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, key, []byte(az.getID()))
+						ret = b
+					case 1:
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch1.getID()))
+						ret = *ch1B
+					case 2:
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch2.getID()))
+						ret = *ch2B
+					}
+					count++
+					return ret, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:   auth,
+				id:     az.getID(),
+				accID:  az.getAccountID(),
+				acmeAz: acmeAz,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAz, err := tc.auth.GetAuthz(prov, tc.accID, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAz)
+					assert.FatalError(t, err)
+
+					expb, err := json.Marshal(tc.acmeAz)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityNewOrder(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		ops  OrderOptions
+		err  *Error
+		o    **Order
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/newOrder-error": func(t *testing.T) test {
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				ops:  defaultOrderOps(),
+				err:  ServerInternalErr(errors.New("error creating order: error creating http challenge: error saving acme challenge: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var (
+				_acmeO = &Order{}
+				acmeO  = &_acmeO
+				count  = 0
+				dir    = newDirectory("ca.smallstep.com", "acme")
+				err    error
+				_accID string
+				accID  = &_accID
+			)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, challengeTable)
+					case 1:
+						assert.Equals(t, bucket, challengeTable)
+					case 2:
+						assert.Equals(t, bucket, authzTable)
+					case 3:
+						assert.Equals(t, bucket, challengeTable)
+					case 4:
+						assert.Equals(t, bucket, challengeTable)
+					case 5:
+						assert.Equals(t, bucket, authzTable)
+					case 6:
+						assert.Equals(t, bucket, orderTable)
+						var o order
+						assert.FatalError(t, json.Unmarshal(newval, &o))
+						*acmeO, err = o.toACME(nil, dir, prov)
+						assert.FatalError(t, err)
+						*accID = o.AccountID
+					case 7:
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, string(key), *accID)
+					}
+					count++
+					return nil, true, nil
+				},
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return nil, database.ErrNotFound
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				ops:  defaultOrderOps(),
+				o:    acmeO,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeO, err := tc.auth.NewOrder(prov, tc.ops); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeO)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(*tc.o)
+					assert.FatalError(t, err)
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityGetOrdersByAccount(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		id   string
+		err  *Error
+		res  []string
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getOrderIDsByAccount-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, ordersByAccountIDTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.New("error loading orderIDs for account foo: force")),
+			}
+		},
+		"fail/getOrder-error": func(t *testing.T) test {
+			var (
+				id    = "zap"
+				oids  = []string{"foo", "bar"}
+				count = 0
+				err   error
+			)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte(id))
+						ret, err = json.Marshal(oids)
+						assert.FatalError(t, err)
+					case 1:
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(oids[0]))
+						return nil, errors.New("force")
+					}
+					count++
+					return ret, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.New("error loading order foo: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var (
+				id    = "zap"
+				count = 0
+				err   error
+			)
+			foo, err := newO()
+			bar, err := newO()
+			baz, err := newO()
+			bar.Status = StatusInvalid
+
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					var ret []byte
+					switch count {
+					case 0:
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte(id))
+						ret, err = json.Marshal([]string{foo.ID, bar.ID, baz.ID})
+						assert.FatalError(t, err)
+					case 1:
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(foo.ID))
+						ret, err = json.Marshal(foo)
+						assert.FatalError(t, err)
+					case 2:
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(bar.ID))
+						ret, err = json.Marshal(bar)
+						assert.FatalError(t, err)
+					case 3:
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(baz.ID))
+						ret, err = json.Marshal(baz)
+						assert.FatalError(t, err)
+					}
+					count++
+					return ret, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				res: []string{
+					fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s", URLSafeProvisionerName(prov), foo.ID),
+					fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s", URLSafeProvisionerName(prov), baz.ID),
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if orderLinks, err := tc.auth.GetOrdersByAccount(prov, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.res, orderLinks)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityFinalizeOrder(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth      *Authority
+		id, accID string
+		err       *Error
+		o         *order
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getOrder-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.New("error loading order foo: force")),
+			}
+		},
+		"fail/order-not-owned-by-account": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: "foo",
+				err:   UnauthorizedErr(errors.New("account does not own order")),
+			}
+		},
+		"fail/finalize-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Expires = time.Now().Add(-time.Minute)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: o.AccountID,
+				err:   ServerInternalErr(errors.New("error finalizing order: error storing order: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusValid
+			o.Certificate = "certID"
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, orderTable)
+					assert.Equals(t, key, []byte(o.ID))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    o.ID,
+				accID: o.AccountID,
+				o:     o,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeO, err := tc.auth.FinalizeOrder(prov, tc.accID, tc.id, nil); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeO)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.o.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityValidateChallenge(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth      *Authority
+		id, accID string
+		err       *Error
+		ch        challenge
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getChallenge-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, challengeTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.Errorf("error loading challenge %s: force", id)),
+			}
+		},
+		"fail/challenge-not-owned-by-account": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, challengeTable)
+					assert.Equals(t, key, []byte(ch.getID()))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    ch.getID(),
+				accID: "foo",
+				err:   UnauthorizedErr(errors.New("account does not own challenge")),
+			}
+		},
+		"fail/validate-error": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, challengeTable)
+					assert.Equals(t, key, []byte(ch.getID()))
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					assert.Equals(t, bucket, challengeTable)
+					assert.Equals(t, key, []byte(ch.getID()))
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    ch.getID(),
+				accID: ch.getAccountID(),
+				err:   ServerInternalErr(errors.New("error attempting challenge validation: error saving acme challenge: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusValid
+			_ch.baseChallenge.Validated = clock.Now()
+			b, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, challengeTable)
+					assert.Equals(t, key, []byte(ch.getID()))
+					return b, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:  auth,
+				id:    ch.getID(),
+				accID: ch.getAccountID(),
+				ch:    ch,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeCh, err := tc.auth.ValidateChallenge(prov, tc.accID, tc.id, nil); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeCh)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.ch.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityUpdateAccount(t *testing.T) {
+	contact := []string{"baz", "zap"}
+	prov := newProv()
+	type test struct {
+		auth    *Authority
+		id      string
+		contact []string
+		acc     *account
+		err     *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getAccount-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, accountTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:    auth,
+				id:      id,
+				contact: contact,
+				err:     ServerInternalErr(errors.Errorf("error loading account %s: force", id)),
+			}
+		},
+		"fail/update-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:    auth,
+				id:      acc.ID,
+				contact: contact,
+				err:     ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			_acc := *acc
+			clone := &_acc
+			clone.Contact = contact
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					assert.Equals(t, bucket, accountTable)
+					assert.Equals(t, key, []byte(acc.ID))
+					return nil, true, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth:    auth,
+				id:      acc.ID,
+				contact: contact,
+				acc:     clone,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAcc, err := tc.auth.UpdateAccount(prov, tc.id, tc.contact); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAcc)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.acc.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}
+
+func TestAuthorityDeactivateAccount(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		auth *Authority
+		id   string
+		acc  *account
+		err  *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getAccount-error": func(t *testing.T) test {
+			id := "foo"
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					assert.Equals(t, bucket, accountTable)
+					assert.Equals(t, key, []byte(id))
+					return nil, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   id,
+				err:  ServerInternalErr(errors.Errorf("error loading account %s: force", id)),
+			}
+		},
+		"fail/deactivate-error": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   acc.ID,
+				err:  ServerInternalErr(errors.New("error storing account: force")),
+			}
+		},
+
+		"ok": func(t *testing.T) test {
+			acc, err := newAcc()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(acc)
+			assert.FatalError(t, err)
+
+			_acc := *acc
+			clone := &_acc
+			clone.Status = StatusDeactivated
+			clone.Deactivated = clock.Now()
+			auth := NewAuthority(&db.MockNoSQLDB{
+				MGet: func(bucket, key []byte) ([]byte, error) {
+					return b, nil
+				},
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					assert.Equals(t, bucket, accountTable)
+					assert.Equals(t, key, []byte(acc.ID))
+					return nil, true, nil
+				},
+			}, "ca.smallstep.com", "acme", nil)
+			return test{
+				auth: auth,
+				id:   acc.ID,
+				acc:  clone,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if acmeAcc, err := tc.auth.DeactivateAccount(prov, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					gotb, err := json.Marshal(acmeAcc)
+					assert.FatalError(t, err)
+
+					acmeExp, err := tc.acc.toACME(nil, tc.auth.dir, prov)
+					assert.FatalError(t, err)
+					expb, err := json.Marshal(acmeExp)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, expb, gotb)
+				}
+			}
+		})
+	}
+}

+ 337 - 0
acme/authz.go

@@ -0,0 +1,337 @@
+package acme
+
+import (
+	"encoding/json"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/nosql"
+)
+
+var defaultExpiryDuration = time.Hour * 24
+
+// Authz is a subset of the Authz type containing only those attributes
+// required for responses in the ACME protocol.
+type Authz struct {
+	Identifier Identifier   `json:"identifier"`
+	Status     string       `json:"status"`
+	Expires    string       `json:"expires"`
+	Challenges []*Challenge `json:"challenges"`
+	Wildcard   bool         `json:"wildcard"`
+	ID         string       `json:"-"`
+}
+
+// ToLog enables response logging.
+func (a *Authz) ToLog() (interface{}, error) {
+	b, err := json.Marshal(a)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling authz for logging"))
+	}
+	return string(b), nil
+}
+
+// GetID returns the Authz ID.
+func (a *Authz) GetID() string {
+	return a.ID
+}
+
+// authz is the interface that the various authz types must implement.
+type authz interface {
+	save(nosql.DB, authz) error
+	clone() *baseAuthz
+	getID() string
+	getAccountID() string
+	getType() string
+	getIdentifier() Identifier
+	getStatus() string
+	getExpiry() time.Time
+	getWildcard() bool
+	getChallenges() []string
+	getCreated() time.Time
+	updateStatus(db nosql.DB) (authz, error)
+	toACME(nosql.DB, *directory, provisioner.Interface) (*Authz, error)
+}
+
+// baseAuthz is the base authz type that others build from.
+type baseAuthz struct {
+	ID         string     `json:"id"`
+	AccountID  string     `json:"accountID"`
+	Identifier Identifier `json:"identifier"`
+	Status     string     `json:"status"`
+	Expires    time.Time  `json:"expires"`
+	Challenges []string   `json:"challenges"`
+	Wildcard   bool       `json:"wildcard"`
+	Created    time.Time  `json:"created"`
+	Error      *Error     `json:"error"`
+}
+
+func newBaseAuthz(accID string, identifier Identifier) (*baseAuthz, error) {
+	id, err := randID()
+	if err != nil {
+		return nil, err
+	}
+
+	now := clock.Now()
+	ba := &baseAuthz{
+		ID:         id,
+		AccountID:  accID,
+		Status:     StatusPending,
+		Created:    now,
+		Expires:    now.Add(defaultExpiryDuration),
+		Identifier: identifier,
+	}
+
+	if strings.HasPrefix(identifier.Value, "*.") {
+		ba.Wildcard = true
+		ba.Identifier = Identifier{
+			Value: strings.TrimPrefix(identifier.Value, "*."),
+			Type:  identifier.Type,
+		}
+	}
+
+	return ba, nil
+}
+
+// getID returns the ID of the authz.
+func (ba *baseAuthz) getID() string {
+	return ba.ID
+}
+
+// getAccountID returns the Account ID that created the authz.
+func (ba *baseAuthz) getAccountID() string {
+	return ba.AccountID
+}
+
+// getType returns the type of the authz.
+func (ba *baseAuthz) getType() string {
+	return ba.Identifier.Type
+}
+
+// getIdentifier returns the identifier for the authz.
+func (ba *baseAuthz) getIdentifier() Identifier {
+	return ba.Identifier
+}
+
+// getStatus returns the status of the authz.
+func (ba *baseAuthz) getStatus() string {
+	return ba.Status
+}
+
+// getWildcard returns true if the authz identifier has a '*', false otherwise.
+func (ba *baseAuthz) getWildcard() bool {
+	return ba.Wildcard
+}
+
+// getChallenges returns the authz challenge IDs.
+func (ba *baseAuthz) getChallenges() []string {
+	return ba.Challenges
+}
+
+// getExpiry returns the expiration time of the authz.
+func (ba *baseAuthz) getExpiry() time.Time {
+	return ba.Expires
+}
+
+// getCreated returns the created time of the authz.
+func (ba *baseAuthz) getCreated() time.Time {
+	return ba.Created
+}
+
+// toACME converts the internal Authz type into the public acmeAuthz type for
+// presentation in the ACME protocol.
+func (ba *baseAuthz) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Authz, error) {
+	var chs = make([]*Challenge, len(ba.Challenges))
+	for i, chID := range ba.Challenges {
+		ch, err := getChallenge(db, chID)
+		if err != nil {
+			return nil, err
+		}
+		chs[i], err = ch.toACME(db, dir, p)
+		if err != nil {
+			return nil, err
+		}
+	}
+	return &Authz{
+		Identifier: ba.Identifier,
+		Status:     ba.getStatus(),
+		Challenges: chs,
+		Wildcard:   ba.getWildcard(),
+		Expires:    ba.Expires.Format(time.RFC3339),
+		ID:         ba.ID,
+	}, nil
+}
+
+func (ba *baseAuthz) save(db nosql.DB, old authz) error {
+	var (
+		err        error
+		oldB, newB []byte
+	)
+	if old == nil {
+		oldB = nil
+	} else {
+		if oldB, err = json.Marshal(old); err != nil {
+			return ServerInternalErr(errors.Wrap(err, "error marshaling old authz"))
+		}
+	}
+	if newB, err = json.Marshal(ba); err != nil {
+		return ServerInternalErr(errors.Wrap(err, "error marshaling new authz"))
+	}
+	_, swapped, err := db.CmpAndSwap(authzTable, []byte(ba.ID), oldB, newB)
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrapf(err, "error storing authz"))
+	case !swapped:
+		return ServerInternalErr(errors.Errorf("error storing authz; " +
+			"value has changed since last read"))
+	default:
+		return nil
+	}
+}
+
+func (ba *baseAuthz) clone() *baseAuthz {
+	u := *ba
+	return &u
+}
+
+func (ba *baseAuthz) parent() authz {
+	return &dnsAuthz{ba}
+}
+
+// updateStatus attempts to update the status on a baseAuthz and stores the
+// updating object if necessary.
+func (ba *baseAuthz) updateStatus(db nosql.DB) (authz, error) {
+	newAuthz := ba.clone()
+
+	now := time.Now().UTC()
+	switch ba.Status {
+	case StatusInvalid:
+		return ba.parent(), nil
+	case StatusValid:
+		return ba.parent(), nil
+	case StatusPending:
+		// check expiry
+		if now.After(ba.Expires) {
+			newAuthz.Status = StatusInvalid
+			newAuthz.Error = MalformedErr(errors.New("authz has expired"))
+			break
+		}
+
+		var isValid = false
+		for _, chID := range ba.Challenges {
+			ch, err := getChallenge(db, chID)
+			if err != nil {
+				return ba, err
+			}
+			if ch.getStatus() == StatusValid {
+				isValid = true
+				break
+			}
+		}
+
+		if !isValid {
+			return ba.parent(), nil
+		}
+		newAuthz.Status = StatusValid
+		newAuthz.Error = nil
+	default:
+		return nil, ServerInternalErr(errors.Errorf("unrecognized authz status: %s", ba.Status))
+	}
+
+	if err := newAuthz.save(db, ba); err != nil {
+		return ba, err
+	}
+	return newAuthz.parent(), nil
+}
+
+// unmarshalAuthz unmarshals an authz type into the correct sub-type.
+func unmarshalAuthz(data []byte) (authz, error) {
+	var getType struct {
+		Identifier Identifier `json:"identifier"`
+	}
+	if err := json.Unmarshal(data, &getType); err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling authz type"))
+	}
+
+	switch getType.Identifier.Type {
+	case "dns":
+		var ba baseAuthz
+		if err := json.Unmarshal(data, &ba); err != nil {
+			return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling authz type into dnsAuthz"))
+		}
+		return &dnsAuthz{&ba}, nil
+	default:
+		return nil, ServerInternalErr(errors.Errorf("unexpected authz type %s",
+			getType.Identifier.Type))
+	}
+}
+
+// dnsAuthz represents a dns acme authorization.
+type dnsAuthz struct {
+	*baseAuthz
+}
+
+// newAuthz returns a new acme authorization object based on the identifier
+// type.
+func newAuthz(db nosql.DB, accID string, identifier Identifier) (a authz, err error) {
+	switch identifier.Type {
+	case "dns":
+		a, err = newDNSAuthz(db, accID, identifier)
+	default:
+		err = MalformedErr(errors.Errorf("unexpected authz type %s",
+			identifier.Type))
+	}
+	return
+}
+
+// newDNSAuthz returns a new dns acme authorization object.
+func newDNSAuthz(db nosql.DB, accID string, identifier Identifier) (authz, error) {
+	ba, err := newBaseAuthz(accID, identifier)
+	if err != nil {
+		return nil, err
+	}
+
+	ba.Challenges = []string{}
+	if !ba.Wildcard {
+		// http challenges are only permitted if the DNS is not a wildcard dns.
+		ch1, err := newHTTP01Challenge(db, ChallengeOptions{
+			AccountID:  accID,
+			AuthzID:    ba.ID,
+			Identifier: ba.Identifier})
+		if err != nil {
+			return nil, Wrap(err, "error creating http challenge")
+		}
+		ba.Challenges = append(ba.Challenges, ch1.getID())
+	}
+	ch2, err := newDNS01Challenge(db, ChallengeOptions{
+		AccountID:  accID,
+		AuthzID:    ba.ID,
+		Identifier: identifier})
+	if err != nil {
+		return nil, Wrap(err, "error creating dns challenge")
+	}
+	ba.Challenges = append(ba.Challenges, ch2.getID())
+
+	da := &dnsAuthz{ba}
+	if err := da.save(db, nil); err != nil {
+		return nil, err
+	}
+
+	return da, nil
+}
+
+// getAuthz retrieves and unmarshals an ACME authz type from the database.
+func getAuthz(db nosql.DB, id string) (authz, error) {
+	b, err := db.Get(authzTable, []byte(id))
+	if nosql.IsErrNotFound(err) {
+		return nil, MalformedErr(errors.Wrapf(err, "authz %s not found", id))
+	} else if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading authz %s", id))
+	}
+	az, err := unmarshalAuthz(b)
+	if err != nil {
+		return nil, err
+	}
+	return az, nil
+}

+ 809 - 0
acme/authz_test.go

@@ -0,0 +1,809 @@
+package acme
+
+import (
+	"encoding/json"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+func newAz() (authz, error) {
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return []byte("foo"), true, nil
+		},
+	}
+	return newAuthz(mockdb, "1234", Identifier{
+		Type: "dns", Value: "acme.example.com",
+	})
+}
+
+func TestGetAuthz(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		az  authz
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/not-found": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			return test{
+				az: az,
+				id: az.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("authz %s not found: not found", az.getID())),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			return test{
+				az: az,
+				id: az.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error loading authz %s: force", az.getID())),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Identifier.Type = "foo"
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				az: az,
+				id: az.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, key, []byte(az.getID()))
+						return b, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("unexpected authz type foo")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				az: az,
+				id: az.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, key, []byte(az.getID()))
+						return b, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if az, err := getAuthz(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.az.getID(), az.getID())
+					assert.Equals(t, tc.az.getAccountID(), az.getAccountID())
+					assert.Equals(t, tc.az.getStatus(), az.getStatus())
+					assert.Equals(t, tc.az.getIdentifier(), az.getIdentifier())
+					assert.Equals(t, tc.az.getCreated(), az.getCreated())
+					assert.Equals(t, tc.az.getExpiry(), az.getExpiry())
+					assert.Equals(t, tc.az.getChallenges(), az.getChallenges())
+				}
+			}
+		})
+	}
+}
+
+func TestAuthzClone(t *testing.T) {
+	az, err := newAz()
+	assert.FatalError(t, err)
+
+	clone := az.clone()
+
+	assert.Equals(t, clone.getID(), az.getID())
+	assert.Equals(t, clone.getAccountID(), az.getAccountID())
+	assert.Equals(t, clone.getStatus(), az.getStatus())
+	assert.Equals(t, clone.getIdentifier(), az.getIdentifier())
+	assert.Equals(t, clone.getExpiry(), az.getExpiry())
+	assert.Equals(t, clone.getCreated(), az.getCreated())
+	assert.Equals(t, clone.getChallenges(), az.getChallenges())
+
+	clone.Status = StatusValid
+
+	assert.NotEquals(t, clone.getStatus(), az.getStatus())
+}
+
+func TestNewAuthz(t *testing.T) {
+	iden := Identifier{
+		Type: "dns", Value: "acme.example.com",
+	}
+	accID := "1234"
+	type test struct {
+		iden   Identifier
+		db     nosql.DB
+		err    *Error
+		resChs *([]string)
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/unexpected-type": func(t *testing.T) test {
+			return test{
+				iden: Identifier{Type: "foo", Value: "acme.example.com"},
+				err:  MalformedErr(errors.New("unexpected authz type foo")),
+			}
+		},
+		"fail/new-http-chall-error": func(t *testing.T) test {
+			return test{
+				iden: iden,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error creating http challenge: error saving acme challenge: force")),
+			}
+		},
+		"fail/new-dns-chall-error": func(t *testing.T) test {
+			count := 0
+			return test{
+				iden: iden,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 1 {
+							return nil, false, errors.New("force")
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error creating dns challenge: error saving acme challenge: force")),
+			}
+		},
+		"fail/save-authz-error": func(t *testing.T) test {
+			count := 0
+			return test{
+				iden: iden,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 2 {
+							return nil, false, errors.New("force")
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing authz: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			chs := &([]string{})
+			count := 0
+			return test{
+				iden: iden,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 2 {
+							assert.Equals(t, bucket, authzTable)
+							assert.Equals(t, old, nil)
+
+							az, err := unmarshalAuthz(newval)
+							assert.FatalError(t, err)
+
+							assert.Equals(t, az.getID(), string(key))
+							assert.Equals(t, az.getAccountID(), accID)
+							assert.Equals(t, az.getStatus(), StatusPending)
+							assert.Equals(t, az.getIdentifier(), iden)
+							assert.Equals(t, az.getWildcard(), false)
+
+							*chs = az.getChallenges()
+
+							assert.True(t, az.getCreated().Before(time.Now().UTC().Add(time.Minute)))
+							assert.True(t, az.getCreated().After(time.Now().UTC().Add(-1*time.Minute)))
+
+							expiry := az.getCreated().Add(defaultExpiryDuration)
+							assert.True(t, az.getExpiry().Before(expiry.Add(time.Minute)))
+							assert.True(t, az.getExpiry().After(expiry.Add(-1*time.Minute)))
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				resChs: chs,
+			}
+		},
+		"ok/wildcard": func(t *testing.T) test {
+			chs := &([]string{})
+			count := 0
+			_iden := Identifier{Type: "dns", Value: "*.acme.example.com"}
+			return test{
+				iden: _iden,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 1 {
+							assert.Equals(t, bucket, authzTable)
+							assert.Equals(t, old, nil)
+
+							az, err := unmarshalAuthz(newval)
+							assert.FatalError(t, err)
+
+							assert.Equals(t, az.getID(), string(key))
+							assert.Equals(t, az.getAccountID(), accID)
+							assert.Equals(t, az.getStatus(), StatusPending)
+							assert.Equals(t, az.getIdentifier(), iden)
+							assert.Equals(t, az.getWildcard(), true)
+
+							*chs = az.getChallenges()
+							// Verify that we only have 1 challenge instead of 2.
+							assert.True(t, len(*chs) == 1)
+
+							assert.True(t, az.getCreated().Before(time.Now().UTC().Add(time.Minute)))
+							assert.True(t, az.getCreated().After(time.Now().UTC().Add(-1*time.Minute)))
+
+							expiry := az.getCreated().Add(defaultExpiryDuration)
+							assert.True(t, az.getExpiry().Before(expiry.Add(time.Minute)))
+							assert.True(t, az.getExpiry().After(expiry.Add(-1*time.Minute)))
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				resChs: chs,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			az, err := newAuthz(tc.db, accID, tc.iden)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, az.getAccountID(), accID)
+					assert.Equals(t, az.getType(), "dns")
+					assert.Equals(t, az.getStatus(), StatusPending)
+
+					assert.True(t, az.getCreated().Before(time.Now().UTC().Add(time.Minute)))
+					assert.True(t, az.getCreated().After(time.Now().UTC().Add(-1*time.Minute)))
+
+					expiry := az.getCreated().Add(defaultExpiryDuration)
+					assert.True(t, az.getExpiry().Before(expiry.Add(time.Minute)))
+					assert.True(t, az.getExpiry().After(expiry.Add(-1*time.Minute)))
+
+					assert.Equals(t, az.getChallenges(), *(tc.resChs))
+
+					if strings.HasPrefix(tc.iden.Value, "*.") {
+						assert.True(t, az.getWildcard())
+						assert.Equals(t, az.getIdentifier().Value, strings.TrimPrefix(tc.iden.Value, "*."))
+					} else {
+						assert.False(t, az.getWildcard())
+						assert.Equals(t, az.getIdentifier().Value, tc.iden.Value)
+					}
+
+					assert.True(t, az.getID() != "")
+				}
+			}
+		})
+	}
+}
+
+func TestAuthzToACME(t *testing.T) {
+	dir := newDirectory("ca.smallstep.com", "acme")
+
+	var (
+		ch1, ch2           challenge
+		ch1Bytes, ch2Bytes = &([]byte{}), &([]byte{})
+		err                error
+	)
+
+	count := 0
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			if count == 0 {
+				*ch1Bytes = newval
+				ch1, err = unmarshalChallenge(newval)
+				assert.FatalError(t, err)
+			} else if count == 1 {
+				*ch2Bytes = newval
+				ch2, err = unmarshalChallenge(newval)
+				assert.FatalError(t, err)
+			}
+			count++
+			return []byte("foo"), true, nil
+		},
+	}
+	iden := Identifier{
+		Type: "dns", Value: "acme.example.com",
+	}
+	az, err := newAuthz(mockdb, "1234", iden)
+	assert.FatalError(t, err)
+	prov := newProv()
+
+	type test struct {
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/getChallenge1-error": func(t *testing.T) test {
+			return test{
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading challenge")),
+			}
+		},
+		"fail/getChallenge2-error": func(t *testing.T) test {
+			count := 0
+			return test{
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						if count == 1 {
+							return nil, errors.New("force")
+						}
+						count++
+						return *ch1Bytes, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading challenge")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			count := 0
+			return test{
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						if count == 0 {
+							count++
+							return *ch1Bytes, nil
+						}
+						return *ch2Bytes, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			acmeAz, err := az.toACME(tc.db, dir, prov)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, acmeAz.ID, az.getID())
+					assert.Equals(t, acmeAz.Identifier, iden)
+					assert.Equals(t, acmeAz.Status, StatusPending)
+
+					acmeCh1, err := ch1.toACME(nil, dir, prov)
+					assert.FatalError(t, err)
+					acmeCh2, err := ch2.toACME(nil, dir, prov)
+					assert.FatalError(t, err)
+
+					assert.Equals(t, acmeAz.Challenges[0], acmeCh1)
+					assert.Equals(t, acmeAz.Challenges[1], acmeCh2)
+
+					expiry, err := time.Parse(time.RFC3339, acmeAz.Expires)
+					assert.FatalError(t, err)
+					assert.Equals(t, expiry.String(), az.getExpiry().String())
+				}
+			}
+		})
+	}
+}
+
+func TestAuthzSave(t *testing.T) {
+	type test struct {
+		az, old authz
+		db      nosql.DB
+		err     *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/old-nil/swap-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			return test{
+				az:  az,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing authz: force")),
+			}
+		},
+		"fail/old-nil/swap-false": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			return test{
+				az:  az,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return []byte("foo"), false, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing authz; value has changed since last read")),
+			}
+		},
+		"ok/old-nil": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				az:  az,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, nil)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, []byte(az.getID()), key)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/old-not-nil": func(t *testing.T) test {
+			oldAz, err := newAz()
+			assert.FatalError(t, err)
+			az, err := newAz()
+			assert.FatalError(t, err)
+
+			oldb, err := json.Marshal(oldAz)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				az:  az,
+				old: oldAz,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, authzTable)
+						assert.Equals(t, []byte(az.getID()), key)
+						return []byte("foo"), true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.az.save(tc.db, tc.old); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestAuthzUnmarshal(t *testing.T) {
+	type test struct {
+		az  authz
+		azb []byte
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/nil": func(t *testing.T) test {
+			return test{
+				azb: nil,
+				err: ServerInternalErr(errors.New("error unmarshaling authz type: unexpected end of JSON input")),
+			}
+		},
+		"fail/unexpected-type": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Identifier.Type = "foo"
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				azb: b,
+				err: ServerInternalErr(errors.New("unexpected authz type foo")),
+			}
+		},
+		"ok/dns": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(az)
+			assert.FatalError(t, err)
+			return test{
+				az:  az,
+				azb: b,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if az, err := unmarshalAuthz(tc.azb); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.az.getID(), az.getID())
+					assert.Equals(t, tc.az.getAccountID(), az.getAccountID())
+					assert.Equals(t, tc.az.getStatus(), az.getStatus())
+					assert.Equals(t, tc.az.getCreated(), az.getCreated())
+					assert.Equals(t, tc.az.getExpiry(), az.getExpiry())
+					assert.Equals(t, tc.az.getWildcard(), az.getWildcard())
+					assert.Equals(t, tc.az.getChallenges(), az.getChallenges())
+				}
+			}
+		})
+	}
+}
+
+func TestAuthzUpdateStatus(t *testing.T) {
+	type test struct {
+		az, res authz
+		err     *Error
+		db      nosql.DB
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/already-invalid": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Status = StatusInvalid
+			return test{
+				az:  az,
+				res: az,
+			}
+		},
+		"fail/already-valid": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Status = StatusValid
+			return test{
+				az:  az,
+				res: az,
+			}
+		},
+		"fail/unexpected-status": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Status = StatusReady
+			return test{
+				az:  az,
+				res: az,
+				err: ServerInternalErr(errors.New("unrecognized authz status: ready")),
+			}
+		},
+		"fail/save-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Expires = time.Now().UTC().Add(-time.Minute)
+			return test{
+				az:  az,
+				res: az,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing authz: force")),
+			}
+		},
+		"ok/expired": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Expires = time.Now().UTC().Add(-time.Minute)
+
+			clone := az.clone()
+			clone.Error = MalformedErr(errors.New("authz has expired"))
+			clone.Status = StatusInvalid
+			return test{
+				az:  az,
+				res: clone.parent(),
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"fail/get-challenge-error": func(t *testing.T) test {
+			az, err := newAz()
+			assert.FatalError(t, err)
+
+			return test{
+				az:  az,
+				res: az,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading challenge")),
+			}
+		},
+		"ok/valid": func(t *testing.T) test {
+			var (
+				ch2      challenge
+				ch1Bytes = &([]byte{})
+				err      error
+			)
+
+			count := 0
+			mockdb := &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					if count == 0 {
+						*ch1Bytes = newval
+					} else if count == 1 {
+						ch2, err = unmarshalChallenge(newval)
+						assert.FatalError(t, err)
+					}
+					count++
+					return nil, true, nil
+				},
+			}
+			iden := Identifier{
+				Type: "dns", Value: "acme.example.com",
+			}
+			az, err := newAuthz(mockdb, "1234", iden)
+			assert.FatalError(t, err)
+			_az, ok := az.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az.baseAuthz.Error = MalformedErr(nil)
+
+			_ch, ok := ch2.(*dns01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusValid
+			chb, err := json.Marshal(ch2)
+
+			clone := az.clone()
+			clone.Status = StatusValid
+			clone.Error = nil
+
+			count = 0
+			return test{
+				az:  az,
+				res: clone.parent(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						if count == 0 {
+							count++
+							return *ch1Bytes, nil
+						}
+						count++
+						return chb, nil
+					},
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/still-pending": func(t *testing.T) test {
+			var ch1Bytes, ch2Bytes = &([]byte{}), &([]byte{})
+
+			count := 0
+			mockdb := &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					if count == 0 {
+						*ch1Bytes = newval
+					} else if count == 1 {
+						*ch2Bytes = newval
+					}
+					count++
+					return nil, true, nil
+				},
+			}
+			iden := Identifier{
+				Type: "dns", Value: "acme.example.com",
+			}
+			az, err := newAuthz(mockdb, "1234", iden)
+			assert.FatalError(t, err)
+
+			count = 0
+			return test{
+				az:  az,
+				res: az,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						if count == 0 {
+							count++
+							return *ch1Bytes, nil
+						}
+						count++
+						return *ch2Bytes, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			az, err := tc.az.updateStatus(tc.db)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					expB, err := json.Marshal(tc.res)
+					assert.FatalError(t, err)
+					b, err := json.Marshal(az)
+					assert.FatalError(t, err)
+					assert.Equals(t, expB, b)
+				}
+			}
+		})
+	}
+}

+ 89 - 0
acme/certificate.go

@@ -0,0 +1,89 @@
+package acme
+
+import (
+	"crypto/x509"
+	"encoding/json"
+	"encoding/pem"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/nosql"
+)
+
+type certificate struct {
+	ID            string    `json:"id"`
+	Created       time.Time `json:"created"`
+	AccountID     string    `json:"accountID"`
+	OrderID       string    `json:"orderID"`
+	Leaf          []byte    `json:"leaf"`
+	Intermediates []byte    `json:"intermediates"`
+}
+
+// CertOptions options with which to create and store a cert object.
+type CertOptions struct {
+	AccountID     string
+	OrderID       string
+	Leaf          *x509.Certificate
+	Intermediates []*x509.Certificate
+}
+
+func newCert(db nosql.DB, ops CertOptions) (*certificate, error) {
+	id, err := randID()
+	if err != nil {
+		return nil, err
+	}
+
+	leaf := pem.EncodeToMemory(&pem.Block{
+		Type:  "CERTIFICATE",
+		Bytes: ops.Leaf.Raw,
+	})
+	var intermediates []byte
+	for _, cert := range ops.Intermediates {
+		intermediates = append(intermediates, pem.EncodeToMemory(&pem.Block{
+			Type:  "CERTIFICATE",
+			Bytes: cert.Raw,
+		})...)
+	}
+
+	cert := &certificate{
+		ID:            id,
+		AccountID:     ops.AccountID,
+		OrderID:       ops.OrderID,
+		Leaf:          leaf,
+		Intermediates: intermediates,
+		Created:       time.Now().UTC(),
+	}
+	certB, err := json.Marshal(cert)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling certificate"))
+	}
+
+	_, swapped, err := db.CmpAndSwap(certTable, []byte(id), nil, certB)
+	switch {
+	case err != nil:
+		return nil, ServerInternalErr(errors.Wrap(err, "error storing certificate"))
+	case !swapped:
+		return nil, ServerInternalErr(errors.New("error storing certificate; " +
+			"value has changed since last read"))
+	default:
+		return cert, nil
+	}
+}
+
+func (c *certificate) toACME(db nosql.DB, dir *directory) ([]byte, error) {
+	return append(c.Leaf, c.Intermediates...), nil
+}
+
+func getCert(db nosql.DB, id string) (*certificate, error) {
+	b, err := db.Get(certTable, []byte(id))
+	if nosql.IsErrNotFound(err) {
+		return nil, MalformedErr(errors.Wrapf(err, "certificate %s not found", id))
+	} else if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error loading certificate"))
+	}
+	var cert certificate
+	if err := json.Unmarshal(b, &cert); err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling certificate"))
+	}
+	return &cert, nil
+}

+ 253 - 0
acme/certificate_test.go

@@ -0,0 +1,253 @@
+package acme
+
+import (
+	"crypto/x509"
+	"encoding/json"
+	"encoding/pem"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/cli/crypto/pemutil"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+func defaultCertOps() (*CertOptions, error) {
+	crt, err := pemutil.ReadCertificate("../authority/testdata/certs/foo.crt")
+	if err != nil {
+		return nil, err
+	}
+	inter, err := pemutil.ReadCertificate("../authority/testdata/certs/intermediate_ca.crt")
+	if err != nil {
+		return nil, err
+	}
+	root, err := pemutil.ReadCertificate("../authority/testdata/certs/root_ca.crt")
+	if err != nil {
+		return nil, err
+	}
+	return &CertOptions{
+		AccountID:     "accID",
+		OrderID:       "ordID",
+		Leaf:          crt,
+		Intermediates: []*x509.Certificate{inter, root},
+	}, nil
+}
+
+func newcert() (*certificate, error) {
+	ops, err := defaultCertOps()
+	if err != nil {
+		return nil, err
+	}
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return nil, true, nil
+		},
+	}
+	return newCert(mockdb, *ops)
+}
+
+func TestNewCert(t *testing.T) {
+	type test struct {
+		db  nosql.DB
+		ops CertOptions
+		err *Error
+		id  *string
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/cmpAndSwap-error": func(t *testing.T) test {
+			ops, err := defaultCertOps()
+			assert.FatalError(t, err)
+			return test{
+				ops: *ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, old, nil)
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing certificate: force")),
+			}
+		},
+		"fail/cmpAndSwap-false": func(t *testing.T) test {
+			ops, err := defaultCertOps()
+			assert.FatalError(t, err)
+			return test{
+				ops: *ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, old, nil)
+						return nil, false, nil
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing certificate; value has changed since last read")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			ops, err := defaultCertOps()
+			assert.FatalError(t, err)
+			var _id string
+			id := &_id
+			return test{
+				ops: *ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, old, nil)
+						*id = string(key)
+						return nil, true, nil
+					},
+				},
+				id: id,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if cert, err := newCert(tc.db, tc.ops); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, cert.ID, *tc.id)
+					assert.Equals(t, cert.AccountID, tc.ops.AccountID)
+					assert.Equals(t, cert.OrderID, tc.ops.OrderID)
+
+					leaf := pem.EncodeToMemory(&pem.Block{
+						Type:  "CERTIFICATE",
+						Bytes: tc.ops.Leaf.Raw,
+					})
+					var intermediates []byte
+					for _, cert := range tc.ops.Intermediates {
+						intermediates = append(intermediates, pem.EncodeToMemory(&pem.Block{
+							Type:  "CERTIFICATE",
+							Bytes: cert.Raw,
+						})...)
+					}
+					assert.Equals(t, cert.Leaf, leaf)
+					assert.Equals(t, cert.Intermediates, intermediates)
+
+					assert.True(t, cert.Created.Before(time.Now().Add(time.Minute)))
+					assert.True(t, cert.Created.After(time.Now().Add(-time.Minute)))
+				}
+			}
+		})
+	}
+}
+
+func TestGetCert(t *testing.T) {
+	type test struct {
+		id   string
+		db   nosql.DB
+		cert *certificate
+		err  *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/not-found": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			return test{
+				cert: cert,
+				id:   cert.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, key, []byte(cert.ID))
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("certificate %s not found: not found", cert.ID)),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			return test{
+				cert: cert,
+				id:   cert.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, key, []byte(cert.ID))
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading certificate: force")),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			return test{
+				cert: cert,
+				id:   cert.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, key, []byte(cert.ID))
+						return nil, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error unmarshaling certificate: unexpected end of JSON input")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			cert, err := newcert()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(cert)
+			assert.FatalError(t, err)
+			return test{
+				cert: cert,
+				id:   cert.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, certTable)
+						assert.Equals(t, key, []byte(cert.ID))
+						return b, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if cert, err := getCert(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.cert.ID, cert.ID)
+					assert.Equals(t, tc.cert.AccountID, cert.AccountID)
+					assert.Equals(t, tc.cert.OrderID, cert.OrderID)
+					assert.Equals(t, tc.cert.Created, cert.Created)
+					assert.Equals(t, tc.cert.Leaf, cert.Leaf)
+					assert.Equals(t, tc.cert.Intermediates, cert.Intermediates)
+				}
+			}
+		})
+	}
+}
+
+func TestCertificateToACME(t *testing.T) {
+	cert, err := newcert()
+	assert.FatalError(t, err)
+	acmeCert, err := cert.toACME(nil, nil)
+	assert.FatalError(t, err)
+	assert.Equals(t, append(cert.Leaf, cert.Intermediates...), acmeCert)
+}

+ 445 - 0
acme/challenge.go

@@ -0,0 +1,445 @@
+package acme
+
+import (
+	"crypto"
+	"crypto/sha256"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+)
+
+// Challenge is a subset of the challenge type containing only those attributes
+// required for responses in the ACME protocol.
+type Challenge struct {
+	Type      string  `json:"type"`
+	Status    string  `json:"status"`
+	Token     string  `json:"token"`
+	Validated string  `json:"validated,omitempty"`
+	URL       string  `json:"url"`
+	Error     *AError `json:"error,omitempty"`
+	ID        string  `json:"-"`
+	AuthzID   string  `json:"-"`
+}
+
+// ToLog enables response logging.
+func (c *Challenge) ToLog() (interface{}, error) {
+	b, err := json.Marshal(c)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling challenge for logging"))
+	}
+	return string(b), nil
+}
+
+// GetID returns the Challenge ID.
+func (c *Challenge) GetID() string {
+	return c.ID
+}
+
+// GetAuthzID returns the parent Authz ID that owns the Challenge.
+func (c *Challenge) GetAuthzID() string {
+	return c.AuthzID
+}
+
+type httpGetter func(string) (*http.Response, error)
+type lookupTxt func(string) ([]string, error)
+
+type validateOptions struct {
+	httpGet   httpGetter
+	lookupTxt lookupTxt
+}
+
+// challenge is the interface ACME challenege types must implement.
+type challenge interface {
+	save(db nosql.DB, swap challenge) error
+	validate(nosql.DB, *jose.JSONWebKey, validateOptions) (challenge, error)
+	getType() string
+	getError() *AError
+	getValue() string
+	getStatus() string
+	getID() string
+	getAuthzID() string
+	getToken() string
+	clone() *baseChallenge
+	getAccountID() string
+	getValidated() time.Time
+	getCreated() time.Time
+	toACME(nosql.DB, *directory, provisioner.Interface) (*Challenge, error)
+}
+
+// ChallengeOptions is the type used to created a new Challenge.
+type ChallengeOptions struct {
+	AccountID  string
+	AuthzID    string
+	Identifier Identifier
+}
+
+// baseChallenge is the base Challenge type that others build from.
+type baseChallenge struct {
+	ID        string    `json:"id"`
+	AccountID string    `json:"accountID"`
+	AuthzID   string    `json:"authzID"`
+	Type      string    `json:"type"`
+	Status    string    `json:"status"`
+	Token     string    `json:"token"`
+	Value     string    `json:"value"`
+	Validated time.Time `json:"validated"`
+	Created   time.Time `json:"created"`
+	Error     *AError   `json:"error"`
+}
+
+func newBaseChallenge(accountID, authzID string) (*baseChallenge, error) {
+	id, err := randID()
+	if err != nil {
+		return nil, Wrap(err, "error generating random id for ACME challenge")
+	}
+	token, err := randID()
+	if err != nil {
+		return nil, Wrap(err, "error generating token for ACME challenge")
+	}
+
+	return &baseChallenge{
+		ID:        id,
+		AccountID: accountID,
+		AuthzID:   authzID,
+		Status:    StatusPending,
+		Token:     token,
+		Created:   clock.Now(),
+	}, nil
+}
+
+// getID returns the id of the baseChallenge.
+func (bc *baseChallenge) getID() string {
+	return bc.ID
+}
+
+// getAuthzID returns the authz ID of the baseChallenge.
+func (bc *baseChallenge) getAuthzID() string {
+	return bc.AuthzID
+}
+
+// getAccountID returns the account id of the baseChallenge.
+func (bc *baseChallenge) getAccountID() string {
+	return bc.AccountID
+}
+
+// getType returns the type of the baseChallenge.
+func (bc *baseChallenge) getType() string {
+	return bc.Type
+}
+
+// getValue returns the type of the baseChallenge.
+func (bc *baseChallenge) getValue() string {
+	return bc.Value
+}
+
+// getStatus returns the status of the baseChallenge.
+func (bc *baseChallenge) getStatus() string {
+	return bc.Status
+}
+
+// getToken returns the token of the baseChallenge.
+func (bc *baseChallenge) getToken() string {
+	return bc.Token
+}
+
+// getValidated returns the validated time of the baseChallenge.
+func (bc *baseChallenge) getValidated() time.Time {
+	return bc.Validated
+}
+
+// getCreated returns the created time of the baseChallenge.
+func (bc *baseChallenge) getCreated() time.Time {
+	return bc.Created
+}
+
+// getCreated returns the created time of the baseChallenge.
+func (bc *baseChallenge) getError() *AError {
+	return bc.Error
+}
+
+// toACME converts the internal Challenge type into the public acmeChallenge
+// type for presentation in the ACME protocol.
+func (bc *baseChallenge) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Challenge, error) {
+	ac := &Challenge{
+		Type:    bc.getType(),
+		Status:  bc.getStatus(),
+		Token:   bc.getToken(),
+		URL:     dir.getLink(ChallengeLink, URLSafeProvisionerName(p), true, bc.getID()),
+		ID:      bc.getID(),
+		AuthzID: bc.getAuthzID(),
+	}
+	if !bc.Validated.IsZero() {
+		ac.Validated = bc.Validated.Format(time.RFC3339)
+	}
+	if bc.Error != nil {
+		ac.Error = bc.Error
+	}
+	return ac, nil
+}
+
+// save writes the challenge to disk. For new challenges 'old' should be nil,
+// otherwise 'old' should be a pointer to the acme challenge as it was at the
+// start of the request. This method will fail if the value currently found
+// in the bucket/row does not match the value of 'old'.
+func (bc *baseChallenge) save(db nosql.DB, old challenge) error {
+	newB, err := json.Marshal(bc)
+	if err != nil {
+		return ServerInternalErr(errors.Wrap(err,
+			"error marshaling new acme challenge"))
+	}
+	var oldB []byte
+	if old == nil {
+		oldB = nil
+	} else {
+		oldB, err = json.Marshal(old)
+		if err != nil {
+			return ServerInternalErr(errors.Wrap(err,
+				"error marshaling old acme challenge"))
+		}
+	}
+
+	_, swapped, err := db.CmpAndSwap(challengeTable, []byte(bc.ID), oldB, newB)
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrap(err, "error saving acme challenge"))
+	case !swapped:
+		return ServerInternalErr(errors.New("error saving acme challenge; " +
+			"acme challenge has changed since last read"))
+	default:
+		return nil
+	}
+}
+
+func (bc *baseChallenge) clone() *baseChallenge {
+	u := *bc
+	return &u
+}
+
+func (bc *baseChallenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
+	return nil, ServerInternalErr(errors.New("unimplemented"))
+}
+
+func (bc *baseChallenge) storeError(db nosql.DB, err *Error) error {
+	clone := bc.clone()
+	clone.Error = err.ToACME()
+	return clone.save(db, bc)
+}
+
+// unmarshalChallenge unmarshals a challenge type into the correct sub-type.
+func unmarshalChallenge(data []byte) (challenge, error) {
+	var getType struct {
+		Type string `json:"type"`
+	}
+	if err := json.Unmarshal(data, &getType); err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
+	}
+
+	switch getType.Type {
+	case "dns-01":
+		var bc baseChallenge
+		if err := json.Unmarshal(data, &bc); err != nil {
+			return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
+				"challenge type into dns01Challenge"))
+		}
+		return &dns01Challenge{&bc}, nil
+	case "http-01":
+		var bc baseChallenge
+		if err := json.Unmarshal(data, &bc); err != nil {
+			return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
+				"challenge type into http01Challenge"))
+		}
+		return &http01Challenge{&bc}, nil
+	default:
+		return nil, ServerInternalErr(errors.Errorf("unexpected challenge type %s", getType.Type))
+	}
+}
+
+// http01Challenge represents an http-01 acme challenge.
+type http01Challenge struct {
+	*baseChallenge
+}
+
+// newHTTP01Challenge returns a new acme http-01 challenge.
+func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
+	bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
+	if err != nil {
+		return nil, err
+	}
+	bc.Type = "http-01"
+	bc.Value = ops.Identifier.Value
+
+	hc := &http01Challenge{bc}
+	if err := hc.save(db, nil); err != nil {
+		return nil, err
+	}
+	return hc, nil
+}
+
+// Validate attempts to validate the challenge. If the challenge has been
+// satisfactorily validated, the 'status' and 'validated' attributes are
+// updated.
+func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
+	// If already valid or invalid then return without performing validation.
+	if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
+		return hc, nil
+	}
+	url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
+
+	resp, err := vo.httpGet(url)
+	if err != nil {
+		if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
+			"error doing http GET for url %s", url))); err != nil {
+			return nil, err
+		}
+		return hc, nil
+	}
+	if resp.StatusCode >= 400 {
+		if err = hc.storeError(db,
+			ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
+				url, resp.StatusCode))); err != nil {
+			return nil, err
+		}
+		return hc, nil
+	}
+	defer resp.Body.Close()
+
+	body, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
+			"response body for url %s", url))
+	}
+	keyAuth := strings.Trim(string(body), "\r\n")
+
+	expected, err := KeyAuthorization(hc.Token, jwk)
+	if err != nil {
+		return nil, err
+	}
+	if keyAuth != expected {
+		if err = hc.storeError(db,
+			RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
+				"expected %s, but got %s", expected, keyAuth))); err != nil {
+			return nil, err
+		}
+		return hc, nil
+	}
+
+	// Update and store the challenge.
+	upd := &http01Challenge{hc.baseChallenge.clone()}
+	upd.Status = StatusValid
+	upd.Error = nil
+	upd.Validated = clock.Now()
+
+	if err := upd.save(db, hc); err != nil {
+		return nil, err
+	}
+	return upd, nil
+}
+
+// dns01Challenge represents an dns-01 acme challenge.
+type dns01Challenge struct {
+	*baseChallenge
+}
+
+// newDNS01Challenge returns a new acme dns-01 challenge.
+func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
+	bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
+	if err != nil {
+		return nil, err
+	}
+	bc.Type = "dns-01"
+	bc.Value = ops.Identifier.Value
+
+	dc := &dns01Challenge{bc}
+	if err := dc.save(db, nil); err != nil {
+		return nil, err
+	}
+	return dc, nil
+}
+
+// KeyAuthorization creates the ACME key authorization value from a token
+// and a jwk.
+func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
+	thumbprint, err := jwk.Thumbprint(crypto.SHA256)
+	if err != nil {
+		return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
+	}
+	encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
+	return fmt.Sprintf("%s.%s", token, encPrint), nil
+}
+
+// validate attempts to validate the challenge. If the challenge has been
+// satisfactorily validated, the 'status' and 'validated' attributes are
+// updated.
+func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
+	// If already valid or invalid then return without performing validation.
+	if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
+		return dc, nil
+	}
+
+	txtRecords, err := vo.lookupTxt("_acme-challenge." + dc.Value)
+	if err != nil {
+		if err = dc.storeError(db,
+			DNSErr(errors.Wrapf(err, "error looking up TXT "+
+				"records for domain %s", dc.Value))); err != nil {
+			return nil, err
+		}
+		return dc, nil
+	}
+
+	expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
+	if err != nil {
+		return nil, err
+	}
+	h := sha256.Sum256([]byte(expectedKeyAuth))
+	expected := base64.RawURLEncoding.EncodeToString(h[:])
+	var found bool
+	for _, r := range txtRecords {
+		if r == expected {
+			found = true
+			break
+		}
+	}
+	if !found {
+		if err = dc.storeError(db,
+			RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
+				"does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
+			return nil, err
+		}
+		return dc, nil
+	}
+
+	// Update and store the challenge.
+	upd := &dns01Challenge{dc.baseChallenge.clone()}
+	upd.Status = StatusValid
+	upd.Error = nil
+	upd.Validated = time.Now().UTC()
+
+	if err := upd.save(db, dc); err != nil {
+		return nil, err
+	}
+	return upd, nil
+}
+
+// getChallenge retrieves and unmarshals an ACME challenge type from the database.
+func getChallenge(db nosql.DB, id string) (challenge, error) {
+	b, err := db.Get(challengeTable, []byte(id))
+	if nosql.IsErrNotFound(err) {
+		return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
+	} else if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
+	}
+	ch, err := unmarshalChallenge(b)
+	if err != nil {
+		return nil, err
+	}
+	return ch, nil
+}

+ 1093 - 0
acme/challenge_test.go

@@ -0,0 +1,1093 @@
+package acme
+
+import (
+	"bytes"
+	"crypto"
+	"crypto/sha256"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/cli/jose"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+var testOps = ChallengeOptions{
+	AccountID: "accID",
+	AuthzID:   "authzID",
+	Identifier: Identifier{
+		Type:  "", // will get set correctly depending on the "new.." method.
+		Value: "zap.internal",
+	},
+}
+
+func newDNSCh() (challenge, error) {
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return []byte("foo"), true, nil
+		},
+	}
+	return newDNS01Challenge(mockdb, testOps)
+}
+
+func newHTTPCh() (challenge, error) {
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return []byte("foo"), true, nil
+		},
+	}
+	return newHTTP01Challenge(mockdb, testOps)
+}
+
+func TestNewHTTP01Challenge(t *testing.T) {
+	ops := ChallengeOptions{
+		AccountID: "accID",
+		AuthzID:   "authzID",
+		Identifier: Identifier{
+			Type:  "http",
+			Value: "zap.internal",
+		},
+	}
+	type test struct {
+		ops ChallengeOptions
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]test{
+		"fail/store-error": {
+			ops: ops,
+			db: &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			},
+			err: ServerInternalErr(errors.New("error saving acme challenge: force")),
+		},
+		"ok": {
+			ops: ops,
+			db: &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return []byte("foo"), true, nil
+				},
+			},
+		},
+	}
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			ch, err := newHTTP01Challenge(tc.db, tc.ops)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, ch.getAccountID(), ops.AccountID)
+					assert.Equals(t, ch.getAuthzID(), ops.AuthzID)
+					assert.Equals(t, ch.getType(), "http-01")
+					assert.Equals(t, ch.getValue(), "zap.internal")
+					assert.Equals(t, ch.getStatus(), StatusPending)
+
+					assert.True(t, ch.getValidated().IsZero())
+					assert.True(t, ch.getCreated().Before(time.Now().UTC().Add(time.Minute)))
+					assert.True(t, ch.getCreated().After(time.Now().UTC().Add(-1*time.Minute)))
+
+					assert.True(t, ch.getID() != "")
+					assert.True(t, ch.getToken() != "")
+				}
+			}
+		})
+	}
+}
+
+func TestNewDNS01Challenge(t *testing.T) {
+	ops := ChallengeOptions{
+		AccountID: "accID",
+		AuthzID:   "authzID",
+		Identifier: Identifier{
+			Type:  "dns",
+			Value: "zap.internal",
+		},
+	}
+	type test struct {
+		ops ChallengeOptions
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]test{
+		"fail/store-error": {
+			ops: ops,
+			db: &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return nil, false, errors.New("force")
+				},
+			},
+			err: ServerInternalErr(errors.New("error saving acme challenge: force")),
+		},
+		"ok": {
+			ops: ops,
+			db: &db.MockNoSQLDB{
+				MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+					return []byte("foo"), true, nil
+				},
+			},
+		},
+	}
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			ch, err := newDNS01Challenge(tc.db, tc.ops)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, ch.getAccountID(), ops.AccountID)
+					assert.Equals(t, ch.getAuthzID(), ops.AuthzID)
+					assert.Equals(t, ch.getType(), "dns-01")
+					assert.Equals(t, ch.getValue(), "zap.internal")
+					assert.Equals(t, ch.getStatus(), StatusPending)
+
+					assert.True(t, ch.getValidated().IsZero())
+					assert.True(t, ch.getCreated().Before(time.Now().UTC().Add(time.Minute)))
+					assert.True(t, ch.getCreated().After(time.Now().UTC().Add(-1*time.Minute)))
+
+					assert.True(t, ch.getID() != "")
+					assert.True(t, ch.getToken() != "")
+				}
+			}
+		})
+	}
+}
+
+func TestChallengeToACME(t *testing.T) {
+	dir := newDirectory("ca.smallstep.com", "acme")
+
+	httpCh, err := newHTTPCh()
+	assert.FatalError(t, err)
+	_httpCh, ok := httpCh.(*http01Challenge)
+	assert.Fatal(t, ok)
+	_httpCh.baseChallenge.Validated = clock.Now()
+
+	dnsCh, err := newDNSCh()
+	assert.FatalError(t, err)
+	prov := newProv()
+	tests := map[string]challenge{
+		"dns":  dnsCh,
+		"http": httpCh,
+	}
+	for name, ch := range tests {
+		t.Run(name, func(t *testing.T) {
+			ach, err := ch.toACME(nil, dir, prov)
+			assert.FatalError(t, err)
+
+			assert.Equals(t, ach.Type, ch.getType())
+			assert.Equals(t, ach.Status, ch.getStatus())
+			assert.Equals(t, ach.Token, ch.getToken())
+			assert.Equals(t, ach.URL,
+				fmt.Sprintf("https://ca.smallstep.com/acme/%s/challenge/%s",
+					URLSafeProvisionerName(prov), ch.getID()))
+			assert.Equals(t, ach.ID, ch.getID())
+			assert.Equals(t, ach.AuthzID, ch.getAuthzID())
+
+			if ach.Type == "http-01" {
+				v, err := time.Parse(time.RFC3339, ach.Validated)
+				assert.FatalError(t, err)
+				assert.Equals(t, v.String(), _httpCh.baseChallenge.Validated.String())
+			} else {
+				assert.Equals(t, ach.Validated, "")
+			}
+		})
+	}
+}
+
+func TestChallengeSave(t *testing.T) {
+	type test struct {
+		ch  challenge
+		old challenge
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/old-nil/swap-error": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error saving acme challenge: force")),
+			}
+		},
+		"fail/old-nil/swap-false": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return []byte("foo"), false, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error saving acme challenge; acme challenge has changed since last read")),
+			}
+		},
+		"ok/old-nil": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(httpCh)
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, nil)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, []byte(httpCh.getID()), key)
+						return []byte("foo"), true, nil
+					},
+				},
+			}
+		},
+		"ok/old-not-nil": func(t *testing.T) test {
+			oldHTTPCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+
+			oldb, err := json.Marshal(oldHTTPCh)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(httpCh)
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				old: oldHTTPCh,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, []byte(httpCh.getID()), key)
+						return []byte("foo"), true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.ch.save(tc.db, tc.old); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestChallengeClone(t *testing.T) {
+	ch, err := newHTTPCh()
+	assert.FatalError(t, err)
+
+	clone := ch.clone()
+
+	assert.Equals(t, clone.getID(), ch.getID())
+	assert.Equals(t, clone.getAccountID(), ch.getAccountID())
+	assert.Equals(t, clone.getAuthzID(), ch.getAuthzID())
+	assert.Equals(t, clone.getStatus(), ch.getStatus())
+	assert.Equals(t, clone.getToken(), ch.getToken())
+	assert.Equals(t, clone.getCreated(), ch.getCreated())
+	assert.Equals(t, clone.getValidated(), ch.getValidated())
+
+	clone.Status = StatusValid
+
+	assert.NotEquals(t, clone.getStatus(), ch.getStatus())
+}
+
+func TestChallengeUnmarshal(t *testing.T) {
+	type test struct {
+		ch  challenge
+		chb []byte
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/nil": func(t *testing.T) test {
+			return test{
+				chb: nil,
+				err: ServerInternalErr(errors.New("error unmarshaling challenge type: unexpected end of JSON input")),
+			}
+		},
+		"fail/unexpected-type": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_httpCh, ok := httpCh.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_httpCh.baseChallenge.Type = "foo"
+			b, err := json.Marshal(httpCh)
+			assert.FatalError(t, err)
+			return test{
+				chb: b,
+				err: ServerInternalErr(errors.New("unexpected challenge type foo")),
+			}
+		},
+		"ok/dns": func(t *testing.T) test {
+			dnsCh, err := newDNSCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(dnsCh)
+			assert.FatalError(t, err)
+			return test{
+				ch:  dnsCh,
+				chb: b,
+			}
+		},
+		"ok/http": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(httpCh)
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				chb: b,
+			}
+		},
+		"ok/err": func(t *testing.T) test {
+			httpCh, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_httpCh, ok := httpCh.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_httpCh.baseChallenge.Error = ServerInternalErr(errors.New("force")).ToACME()
+			b, err := json.Marshal(httpCh)
+			assert.FatalError(t, err)
+			return test{
+				ch:  httpCh,
+				chb: b,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if ch, err := unmarshalChallenge(tc.chb); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.ch.getID(), ch.getID())
+					assert.Equals(t, tc.ch.getAccountID(), ch.getAccountID())
+					assert.Equals(t, tc.ch.getAuthzID(), ch.getAuthzID())
+					assert.Equals(t, tc.ch.getStatus(), ch.getStatus())
+					assert.Equals(t, tc.ch.getToken(), ch.getToken())
+					assert.Equals(t, tc.ch.getCreated(), ch.getCreated())
+					assert.Equals(t, tc.ch.getValidated(), ch.getValidated())
+				}
+			}
+		})
+	}
+}
+func TestGetChallenge(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		ch  challenge
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/not-found": func(t *testing.T) test {
+			dnsCh, err := newDNSCh()
+			assert.FatalError(t, err)
+			return test{
+				ch: dnsCh,
+				id: dnsCh.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("challenge %s not found: not found", dnsCh.getID())),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			dnsCh, err := newDNSCh()
+			assert.FatalError(t, err)
+			return test{
+				ch: dnsCh,
+				id: dnsCh.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error loading challenge %s: force", dnsCh.getID())),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			dnsCh, err := newDNSCh()
+			assert.FatalError(t, err)
+			_dnsCh, ok := dnsCh.(*dns01Challenge)
+			assert.Fatal(t, ok)
+			_dnsCh.baseChallenge.Type = "foo"
+			b, err := json.Marshal(dnsCh)
+			assert.FatalError(t, err)
+			return test{
+				ch: dnsCh,
+				id: dnsCh.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(dnsCh.getID()))
+						return b, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("unexpected challenge type foo")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			dnsCh, err := newDNSCh()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(dnsCh)
+			assert.FatalError(t, err)
+			return test{
+				ch: dnsCh,
+				id: dnsCh.getID(),
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(dnsCh.getID()))
+						return b, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if ch, err := getChallenge(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.ch.getID(), ch.getID())
+					assert.Equals(t, tc.ch.getAccountID(), ch.getAccountID())
+					assert.Equals(t, tc.ch.getAuthzID(), ch.getAuthzID())
+					assert.Equals(t, tc.ch.getStatus(), ch.getStatus())
+					assert.Equals(t, tc.ch.getToken(), ch.getToken())
+					assert.Equals(t, tc.ch.getCreated(), ch.getCreated())
+					assert.Equals(t, tc.ch.getValidated(), ch.getValidated())
+				}
+			}
+		})
+	}
+}
+
+func TestKeyAuthorization(t *testing.T) {
+	type test struct {
+		token string
+		jwk   *jose.JSONWebKey
+		exp   string
+		err   *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/jwk-thumbprint-error": func(t *testing.T) test {
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			jwk.Key = "foo"
+			return test{
+				token: "1234",
+				jwk:   jwk,
+				err:   ServerInternalErr(errors.Errorf("error generating JWK thumbprint: square/go-jose: unknown key type 'string'")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			token := "1234"
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			thumbprint, err := jwk.Thumbprint(crypto.SHA256)
+			assert.FatalError(t, err)
+			encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
+			return test{
+				token: token,
+				jwk:   jwk,
+				exp:   fmt.Sprintf("%s.%s", token, encPrint),
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if ka, err := KeyAuthorization(tc.token, tc.jwk); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.exp, ka)
+				}
+			}
+		})
+	}
+}
+
+type errReader int
+
+func (errReader) Read(p []byte) (n int, err error) {
+	return 0, errors.New("force")
+}
+func (errReader) Close() error {
+	return nil
+}
+
+func TestHTTP01Validate(t *testing.T) {
+	type test struct {
+		vo  validateOptions
+		ch  challenge
+		res challenge
+		jwk *jose.JSONWebKey
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok/status-already-valid": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusValid
+			return test{
+				ch:  ch,
+				res: ch,
+			}
+		},
+		"ok/status-already-invalid": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusInvalid
+			return test{
+				ch:  ch,
+				res: ch,
+			}
+		},
+		"ok/http-get-error": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			expErr := ConnectionErr(errors.Errorf("error doing http GET for url "+
+				"http://zap.internal/.well-known/acme-challenge/%s: force", ch.getToken()))
+			baseClone := ch.clone()
+			baseClone.Error = expErr.ToACME()
+			newCh := &http01Challenge{baseClone}
+			newb, err := json.Marshal(newCh)
+			assert.FatalError(t, err)
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return nil, errors.New("force")
+					},
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, newb)
+						return nil, true, nil
+					},
+				},
+				res: ch,
+			}
+		},
+		"ok/http-get->=400": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			expErr := ConnectionErr(errors.Errorf("error doing http GET for url "+
+				"http://zap.internal/.well-known/acme-challenge/%s with status code 400", ch.getToken()))
+			baseClone := ch.clone()
+			baseClone.Error = expErr.ToACME()
+			newCh := &http01Challenge{baseClone}
+			newb, err := json.Marshal(newCh)
+			assert.FatalError(t, err)
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							StatusCode: http.StatusBadRequest,
+						}, nil
+					},
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, newb)
+						return nil, true, nil
+					},
+				},
+				res: ch,
+			}
+		},
+		"fail/read-body": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			jwk.Key = "foo"
+
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							Body: errReader(0),
+						}, nil
+					},
+				},
+				jwk: jwk,
+				err: ServerInternalErr(errors.Errorf("error reading response "+
+					"body for url http://zap.internal/.well-known/acme-challenge/%s: force",
+					ch.getToken())),
+			}
+		},
+		"fail/key-authorization-gen-error": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			jwk.Key = "foo"
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							Body: ioutil.NopCloser(bytes.NewBufferString("foo")),
+						}, nil
+					},
+				},
+				jwk: jwk,
+				err: ServerInternalErr(errors.New("error generating JWK thumbprint: square/go-jose: unknown key type 'string'")),
+			}
+		},
+		"ok/key-auth-mismatch": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+
+			expErr := RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
+				"expected %s, but got foo", expKeyAuth))
+			baseClone := ch.clone()
+			baseClone.Error = expErr.ToACME()
+			newCh := &http01Challenge{baseClone}
+			newb, err := json.Marshal(newCh)
+			assert.FatalError(t, err)
+
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							Body: ioutil.NopCloser(bytes.NewBufferString("foo")),
+						}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, newb)
+						return nil, true, nil
+					},
+				},
+				res: ch,
+			}
+		},
+		"fail/save-error": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							Body: ioutil.NopCloser(bytes.NewBufferString(expKeyAuth)),
+						}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error saving acme challenge: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			ch, err := newHTTPCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*http01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Error = MalformedErr(nil).ToACME()
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+
+			baseClone := ch.clone()
+			baseClone.Status = StatusValid
+			baseClone.Error = nil
+			newCh := &http01Challenge{baseClone}
+
+			return test{
+				ch:  ch,
+				res: newCh,
+				vo: validateOptions{
+					httpGet: func(url string) (*http.Response, error) {
+						return &http.Response{
+							Body: ioutil.NopCloser(bytes.NewBufferString(expKeyAuth)),
+						}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+
+						httpCh, err := unmarshalChallenge(newval)
+						assert.FatalError(t, err)
+						assert.Equals(t, httpCh.getStatus(), StatusValid)
+						assert.True(t, httpCh.getValidated().Before(time.Now().UTC().Add(time.Minute)))
+						assert.True(t, httpCh.getValidated().After(time.Now().UTC().Add(-1*time.Second)))
+
+						baseClone.Validated = httpCh.getValidated()
+
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if ch, err := tc.ch.validate(tc.db, tc.jwk, tc.vo); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.res.getID(), ch.getID())
+					assert.Equals(t, tc.res.getAccountID(), ch.getAccountID())
+					assert.Equals(t, tc.res.getAuthzID(), ch.getAuthzID())
+					assert.Equals(t, tc.res.getStatus(), ch.getStatus())
+					assert.Equals(t, tc.res.getToken(), ch.getToken())
+					assert.Equals(t, tc.res.getCreated(), ch.getCreated())
+					assert.Equals(t, tc.res.getValidated(), ch.getValidated())
+					assert.Equals(t, tc.res.getError(), ch.getError())
+				}
+			}
+		})
+	}
+}
+
+func TestDNS01Validate(t *testing.T) {
+	type test struct {
+		vo  validateOptions
+		ch  challenge
+		res challenge
+		jwk *jose.JSONWebKey
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok/status-already-valid": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*dns01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusValid
+			return test{
+				ch:  ch,
+				res: ch,
+			}
+		},
+		"ok/status-already-invalid": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*dns01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Status = StatusInvalid
+			return test{
+				ch:  ch,
+				res: ch,
+			}
+		},
+		"ok/lookup-txt-error": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			expErr := DNSErr(errors.Errorf("error looking up TXT records for "+
+				"domain %s: force", ch.getValue()))
+			baseClone := ch.clone()
+			baseClone.Error = expErr.ToACME()
+			newCh := &dns01Challenge{baseClone}
+			newb, err := json.Marshal(newCh)
+			assert.FatalError(t, err)
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					lookupTxt: func(url string) ([]string, error) {
+						return nil, errors.New("force")
+					},
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, newb)
+						return nil, true, nil
+					},
+				},
+				res: ch,
+			}
+		},
+		"fail/key-authorization-gen-error": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+			jwk.Key = "foo"
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					lookupTxt: func(url string) ([]string, error) {
+						return []string{"foo", "bar"}, nil
+					},
+				},
+				jwk: jwk,
+				err: ServerInternalErr(errors.New("error generating JWK thumbprint: square/go-jose: unknown key type 'string'")),
+			}
+		},
+		"ok/key-auth-mismatch": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+
+			expErr := RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
+				"expected %s, but got %s", expKeyAuth, []string{"foo", "bar"}))
+			baseClone := ch.clone()
+			baseClone.Error = expErr.ToACME()
+			newCh := &http01Challenge{baseClone}
+			newb, err := json.Marshal(newCh)
+			assert.FatalError(t, err)
+
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					lookupTxt: func(url string) ([]string, error) {
+						return []string{"foo", "bar"}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, newb)
+						return nil, true, nil
+					},
+				},
+				res: ch,
+			}
+		},
+		"fail/save-error": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+			h := sha256.Sum256([]byte(expKeyAuth))
+			expected := base64.RawURLEncoding.EncodeToString(h[:])
+			return test{
+				ch: ch,
+				vo: validateOptions{
+					lookupTxt: func(url string) ([]string, error) {
+						return []string{"foo", expected}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error saving acme challenge: force")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			ch, err := newDNSCh()
+			assert.FatalError(t, err)
+			_ch, ok := ch.(*dns01Challenge)
+			assert.Fatal(t, ok)
+			_ch.baseChallenge.Error = MalformedErr(nil).ToACME()
+			oldb, err := json.Marshal(ch)
+			assert.FatalError(t, err)
+
+			jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+			assert.FatalError(t, err)
+
+			expKeyAuth, err := KeyAuthorization(ch.getToken(), jwk)
+			assert.FatalError(t, err)
+			h := sha256.Sum256([]byte(expKeyAuth))
+			expected := base64.RawURLEncoding.EncodeToString(h[:])
+
+			baseClone := ch.clone()
+			baseClone.Status = StatusValid
+			baseClone.Error = nil
+			newCh := &dns01Challenge{baseClone}
+
+			return test{
+				ch:  ch,
+				res: newCh,
+				vo: validateOptions{
+					lookupTxt: func(url string) ([]string, error) {
+						return []string{"foo", expected}, nil
+					},
+				},
+				jwk: jwk,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, challengeTable)
+						assert.Equals(t, key, []byte(ch.getID()))
+						assert.Equals(t, old, oldb)
+
+						dnsCh, err := unmarshalChallenge(newval)
+						assert.FatalError(t, err)
+						assert.Equals(t, dnsCh.getStatus(), StatusValid)
+						assert.True(t, dnsCh.getValidated().Before(time.Now().UTC()))
+						assert.True(t, dnsCh.getValidated().After(time.Now().UTC().Add(-1*time.Second)))
+
+						baseClone.Validated = dnsCh.getValidated()
+
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if ch, err := tc.ch.validate(tc.db, tc.jwk, tc.vo); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.res.getID(), ch.getID())
+					assert.Equals(t, tc.res.getAccountID(), ch.getAccountID())
+					assert.Equals(t, tc.res.getAuthzID(), ch.getAuthzID())
+					assert.Equals(t, tc.res.getStatus(), ch.getStatus())
+					assert.Equals(t, tc.res.getToken(), ch.getToken())
+					assert.Equals(t, tc.res.getCreated(), ch.getCreated())
+					assert.Equals(t, tc.res.getValidated(), ch.getValidated())
+					assert.Equals(t, tc.res.getError(), ch.getError())
+				}
+			}
+		})
+	}
+}

+ 76 - 0
acme/common.go

@@ -0,0 +1,76 @@
+package acme
+
+import (
+	"crypto/x509"
+	"net/url"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/crypto/randutil"
+)
+
+// SignAuthority is the interface implemented by a CA authority.
+type SignAuthority interface {
+	Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
+	LoadProvisionerByID(string) (provisioner.Interface, error)
+}
+
+// Identifier encodes the type that an order pertains to.
+type Identifier struct {
+	Type  string `json:"type"`
+	Value string `json:"value"`
+}
+
+var (
+	accountTable           = []byte("acme-accounts")
+	accountByKeyIDTable    = []byte("acme-keyID-accountID-index")
+	authzTable             = []byte("acme-authzs")
+	challengeTable         = []byte("acme-challenges")
+	nonceTable             = []byte("nonce-table")
+	orderTable             = []byte("acme-orders")
+	ordersByAccountIDTable = []byte("acme-account-orders-index")
+	certTable              = []byte("acme-certs")
+)
+
+var (
+	// StatusValid -- valid
+	StatusValid = "valid"
+	// StatusInvalid -- invalid
+	StatusInvalid = "invalid"
+	// StatusPending -- pending; e.g. an Order that is not ready to be finalized.
+	StatusPending = "pending"
+	// StatusDeactivated -- deactivated; e.g. for an Account that is not longer valid.
+	StatusDeactivated = "deactivated"
+	// StatusReady -- ready; e.g. for an Order that is ready to be finalized.
+	StatusReady = "ready"
+	//statusExpired     = "expired"
+	//statusActive      = "active"
+	//statusProcessing  = "processing"
+)
+
+var idLen = 32
+
+func randID() (val string, err error) {
+	val, err = randutil.Alphanumeric(idLen)
+	if err != nil {
+		return "", ServerInternalErr(errors.Wrap(err, "error generating random alphanumeric ID"))
+	}
+	return val, nil
+}
+
+// Clock that returns time in UTC rounded to seconds.
+type Clock int
+
+// Now returns the UTC time rounded to seconds.
+func (c *Clock) Now() time.Time {
+	return time.Now().UTC().Round(time.Second)
+}
+
+var clock = new(Clock)
+
+// URLSafeProvisionerName returns a path escaped version of the ACME provisioner
+// ID that is safe to use in URL paths.
+func URLSafeProvisionerName(p provisioner.Interface) string {
+	return url.PathEscape(p.GetName())
+}

+ 120 - 0
acme/directory.go

@@ -0,0 +1,120 @@
+package acme
+
+import (
+	"encoding/json"
+	"fmt"
+
+	"github.com/pkg/errors"
+)
+
+// Directory represents an ACME directory for configuring clients.
+type Directory struct {
+	NewNonce   string `json:"newNonce,omitempty"`
+	NewAccount string `json:"newAccount,omitempty"`
+	NewOrder   string `json:"newOrder,omitempty"`
+	NewAuthz   string `json:"newAuthz,omitempty"`
+	RevokeCert string `json:"revokeCert,omitempty"`
+	KeyChange  string `json:"keyChange,omitempty"`
+}
+
+// ToLog enables response logging for the Directory type.
+func (d *Directory) ToLog() (interface{}, error) {
+	b, err := json.Marshal(d)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling directory for logging"))
+	}
+	return string(b), nil
+}
+
+type directory struct {
+	prefix, dns string
+}
+
+// newDirectory returns a new Directory type.
+func newDirectory(dns, prefix string) *directory {
+	return &directory{prefix: prefix, dns: dns}
+}
+
+// Link captures the link type.
+type Link int
+
+const (
+	// NewNonceLink new-nonce
+	NewNonceLink Link = iota
+	// NewAccountLink new-account
+	NewAccountLink
+	// AccountLink account
+	AccountLink
+	// OrderLink order
+	OrderLink
+	// NewOrderLink new-order
+	NewOrderLink
+	// OrdersByAccountLink list of orders owned by account
+	OrdersByAccountLink
+	// FinalizeLink finalize order
+	FinalizeLink
+	// NewAuthzLink authz
+	NewAuthzLink
+	// AuthzLink new-authz
+	AuthzLink
+	// ChallengeLink challenge
+	ChallengeLink
+	// CertificateLink certificate
+	CertificateLink
+	// DirectoryLink directory
+	DirectoryLink
+	// RevokeCertLink revoke certificate
+	RevokeCertLink
+	// KeyChangeLink key rollover
+	KeyChangeLink
+)
+
+func (l Link) String() string {
+	switch l {
+	case NewNonceLink:
+		return "new-nonce"
+	case NewAccountLink:
+		return "new-account"
+	case AccountLink:
+		return "account"
+	case NewOrderLink:
+		return "new-order"
+	case OrderLink:
+		return "order"
+	case NewAuthzLink:
+		return "new-authz"
+	case AuthzLink:
+		return "authz"
+	case ChallengeLink:
+		return "challenge"
+	case CertificateLink:
+		return "certificate"
+	case DirectoryLink:
+		return "directory"
+	case RevokeCertLink:
+		return "revoke-cert"
+	case KeyChangeLink:
+		return "key-change"
+	default:
+		return "unexpected"
+	}
+}
+
+// getLink returns an absolute or partial path to the given resource.
+func (d *directory) getLink(typ Link, provisionerName string, abs bool, inputs ...string) string {
+	var link string
+	switch typ {
+	case NewNonceLink, NewAccountLink, NewOrderLink, NewAuthzLink, DirectoryLink, KeyChangeLink, RevokeCertLink:
+		link = fmt.Sprintf("/%s/%s", provisionerName, typ.String())
+	case AccountLink, OrderLink, AuthzLink, ChallengeLink, CertificateLink:
+		link = fmt.Sprintf("/%s/%s/%s", provisionerName, typ.String(), inputs[0])
+	case OrdersByAccountLink:
+		link = fmt.Sprintf("/%s/%s/%s/orders", provisionerName, AccountLink.String(), inputs[0])
+	case FinalizeLink:
+		link = fmt.Sprintf("/%s/%s/%s/finalize", provisionerName, OrderLink.String(), inputs[0])
+	}
+	if abs {
+		return fmt.Sprintf("https://%s/%s%s", d.dns, d.prefix, link)
+	}
+	return link
+}

+ 60 - 0
acme/directory_test.go

@@ -0,0 +1,60 @@
+package acme
+
+import (
+	"fmt"
+	"testing"
+
+	"github.com/smallstep/assert"
+)
+
+func TestDirectoryGetLink(t *testing.T) {
+	dns := "ca.smallstep.com"
+	prefix := "acme"
+	dir := newDirectory(dns, prefix)
+	id := "1234"
+
+	prov := newProv()
+	provID := URLSafeProvisionerName(prov)
+
+	assert.Equals(t, dir.getLink(NewNonceLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-nonce", provID))
+	assert.Equals(t, dir.getLink(NewNonceLink, provID, false), fmt.Sprintf("/%s/new-nonce", provID))
+
+	assert.Equals(t, dir.getLink(NewAccountLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-account", provID))
+	assert.Equals(t, dir.getLink(NewAccountLink, provID, false), fmt.Sprintf("/%s/new-account", provID))
+
+	assert.Equals(t, dir.getLink(AccountLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234", provID))
+	assert.Equals(t, dir.getLink(AccountLink, provID, false, id), fmt.Sprintf("/%s/account/1234", provID))
+
+	assert.Equals(t, dir.getLink(NewOrderLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-order", provID))
+	assert.Equals(t, dir.getLink(NewOrderLink, provID, false), fmt.Sprintf("/%s/new-order", provID))
+
+	assert.Equals(t, dir.getLink(OrderLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/1234", provID))
+	assert.Equals(t, dir.getLink(OrderLink, provID, false, id), fmt.Sprintf("/%s/order/1234", provID))
+
+	assert.Equals(t, dir.getLink(OrdersByAccountLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/account/1234/orders", provID))
+	assert.Equals(t, dir.getLink(OrdersByAccountLink, provID, false, id), fmt.Sprintf("/%s/account/1234/orders", provID))
+
+	assert.Equals(t, dir.getLink(FinalizeLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/1234/finalize", provID))
+	assert.Equals(t, dir.getLink(FinalizeLink, provID, false, id), fmt.Sprintf("/%s/order/1234/finalize", provID))
+
+	assert.Equals(t, dir.getLink(NewAuthzLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/new-authz", provID))
+	assert.Equals(t, dir.getLink(NewAuthzLink, provID, false), fmt.Sprintf("/%s/new-authz", provID))
+
+	assert.Equals(t, dir.getLink(AuthzLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/authz/1234", provID))
+	assert.Equals(t, dir.getLink(AuthzLink, provID, false, id), fmt.Sprintf("/%s/authz/1234", provID))
+
+	assert.Equals(t, dir.getLink(DirectoryLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/directory", provID))
+	assert.Equals(t, dir.getLink(DirectoryLink, provID, false), fmt.Sprintf("/%s/directory", provID))
+
+	assert.Equals(t, dir.getLink(RevokeCertLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/revoke-cert", provID))
+	assert.Equals(t, dir.getLink(RevokeCertLink, provID, false), fmt.Sprintf("/%s/revoke-cert", provID))
+
+	assert.Equals(t, dir.getLink(KeyChangeLink, provID, true), fmt.Sprintf("https://ca.smallstep.com/acme/%s/key-change", provID))
+	assert.Equals(t, dir.getLink(KeyChangeLink, provID, false), fmt.Sprintf("/%s/key-change", provID))
+
+	assert.Equals(t, dir.getLink(ChallengeLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/challenge/1234", provID))
+	assert.Equals(t, dir.getLink(ChallengeLink, provID, false, id), fmt.Sprintf("/%s/challenge/1234", provID))
+
+	assert.Equals(t, dir.getLink(CertificateLink, provID, true, id), fmt.Sprintf("https://ca.smallstep.com/acme/%s/certificate/1234", provID))
+	assert.Equals(t, dir.getLink(CertificateLink, provID, false, id), fmt.Sprintf("/%s/certificate/1234", provID))
+}

+ 439 - 0
acme/errors.go

@@ -0,0 +1,439 @@
+package acme
+
+import (
+	"github.com/pkg/errors"
+)
+
+// AccountDoesNotExistErr returns a new acme error.
+func AccountDoesNotExistErr(err error) *Error {
+	return &Error{
+		Type:   accountDoesNotExistErr,
+		Detail: "Account does not exist",
+		Status: 404,
+		Err:    err,
+	}
+}
+
+// AlreadyRevokedErr returns a new acme error.
+func AlreadyRevokedErr(err error) *Error {
+	return &Error{
+		Type:   alreadyRevokedErr,
+		Detail: "Certificate already revoked",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// BadCSRErr returns a new acme error.
+func BadCSRErr(err error) *Error {
+	return &Error{
+		Type:   badCSRErr,
+		Detail: "The CSR is unacceptable",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// BadNonceErr returns a new acme error.
+func BadNonceErr(err error) *Error {
+	return &Error{
+		Type:   badNonceErr,
+		Detail: "Unacceptable anti-replay nonce",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// BadPublicKeyErr returns a new acme error.
+func BadPublicKeyErr(err error) *Error {
+	return &Error{
+		Type:   badPublicKeyErr,
+		Detail: "The jws was signed by a public key the server does not support",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// BadRevocationReasonErr returns a new acme error.
+func BadRevocationReasonErr(err error) *Error {
+	return &Error{
+		Type:   badRevocationReasonErr,
+		Detail: "The revocation reason provided is not allowed by the server",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// BadSignatureAlgorithmErr returns a new acme error.
+func BadSignatureAlgorithmErr(err error) *Error {
+	return &Error{
+		Type:   badSignatureAlgorithmErr,
+		Detail: "The JWS was signed with an algorithm the server does not support",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// CaaErr returns a new acme error.
+func CaaErr(err error) *Error {
+	return &Error{
+		Type:   caaErr,
+		Detail: "Certification Authority Authorization (CAA) records forbid the CA from issuing a certificate",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// CompoundErr returns a new acme error.
+func CompoundErr(err error) *Error {
+	return &Error{
+		Type:   compoundErr,
+		Detail: "Specific error conditions are indicated in the “subproblems” array",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// ConnectionErr returns a new acme error.
+func ConnectionErr(err error) *Error {
+	return &Error{
+		Type:   connectionErr,
+		Detail: "The server could not connect to validation target",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// DNSErr returns a new acme error.
+func DNSErr(err error) *Error {
+	return &Error{
+		Type:   dnsErr,
+		Detail: "There was a problem with a DNS query during identifier validation",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// ExternalAccountRequiredErr returns a new acme error.
+func ExternalAccountRequiredErr(err error) *Error {
+	return &Error{
+		Type:   externalAccountRequiredErr,
+		Detail: "The request must include a value for the \"externalAccountBinding\" field",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// IncorrectResponseErr returns a new acme error.
+func IncorrectResponseErr(err error) *Error {
+	return &Error{
+		Type:   incorrectResponseErr,
+		Detail: "Response received didn't match the challenge's requirements",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// InvalidContactErr returns a new acme error.
+func InvalidContactErr(err error) *Error {
+	return &Error{
+		Type:   invalidContactErr,
+		Detail: "A contact URL for an account was invalid",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// MalformedErr returns a new acme error.
+func MalformedErr(err error) *Error {
+	return &Error{
+		Type:   malformedErr,
+		Detail: "The request message was malformed",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// OrderNotReadyErr returns a new acme error.
+func OrderNotReadyErr(err error) *Error {
+	return &Error{
+		Type:   orderNotReadyErr,
+		Detail: "The request attempted to finalize an order that is not ready to be finalized",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// RateLimitedErr returns a new acme error.
+func RateLimitedErr(err error) *Error {
+	return &Error{
+		Type:   rateLimitedErr,
+		Detail: "The request exceeds a rate limit",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// RejectedIdentifierErr returns a new acme error.
+func RejectedIdentifierErr(err error) *Error {
+	return &Error{
+		Type:   rejectedIdentifierErr,
+		Detail: "The server will not issue certificates for the identifier",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// ServerInternalErr returns a new acme error.
+func ServerInternalErr(err error) *Error {
+	return &Error{
+		Type:   serverInternalErr,
+		Detail: "The server experienced an internal error",
+		Status: 500,
+		Err:    err,
+	}
+}
+
+// TLSErr returns a new acme error.
+func TLSErr(err error) *Error {
+	return &Error{
+		Type:   tlsErr,
+		Detail: "The server received a TLS error during validation",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// UnauthorizedErr returns a new acme error.
+func UnauthorizedErr(err error) *Error {
+	return &Error{
+		Type:   unauthorizedErr,
+		Detail: "The client lacks sufficient authorization",
+		Status: 401,
+		Err:    err,
+	}
+}
+
+// UnsupportedContactErr returns a new acme error.
+func UnsupportedContactErr(err error) *Error {
+	return &Error{
+		Type:   unsupportedContactErr,
+		Detail: "A contact URL for an account used an unsupported protocol scheme",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// UnsupportedIdentifierErr returns a new acme error.
+func UnsupportedIdentifierErr(err error) *Error {
+	return &Error{
+		Type:   unsupportedIdentifierErr,
+		Detail: "An identifier is of an unsupported type",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// UserActionRequiredErr returns a new acme error.
+func UserActionRequiredErr(err error) *Error {
+	return &Error{
+		Type:   userActionRequiredErr,
+		Detail: "Visit the “instance” URL and take actions specified there",
+		Status: 400,
+		Err:    err,
+	}
+}
+
+// ProbType is the type of the ACME problem.
+type ProbType int
+
+const (
+	// The request specified an account that does not exist
+	accountDoesNotExistErr ProbType = iota
+	// The request specified a certificate to be revoked that has already been revoked
+	alreadyRevokedErr
+	// The CSR is unacceptable (e.g., due to a short key)
+	badCSRErr
+	// The client sent an unacceptable anti-replay nonce
+	badNonceErr
+	// The JWS was signed by a public key the server does not support
+	badPublicKeyErr
+	// The revocation reason provided is not allowed by the server
+	badRevocationReasonErr
+	// The JWS was signed with an algorithm the server does not support
+	badSignatureAlgorithmErr
+	// Certification Authority Authorization (CAA) records forbid the CA from issuing a certificate
+	caaErr
+	// Specific error conditions are indicated in the “subproblems” array.
+	compoundErr
+	// The server could not connect to validation target
+	connectionErr
+	// There was a problem with a DNS query during identifier validation
+	dnsErr
+	// The request must include a value for the “externalAccountBinding” field
+	externalAccountRequiredErr
+	// Response received didn’t match the challenge’s requirements
+	incorrectResponseErr
+	// A contact URL for an account was invalid
+	invalidContactErr
+	// The request message was malformed
+	malformedErr
+	// The request attempted to finalize an order that is not ready to be finalized
+	orderNotReadyErr
+	// The request exceeds a rate limit
+	rateLimitedErr
+	// The server will not issue certificates for the identifier
+	rejectedIdentifierErr
+	// The server experienced an internal error
+	serverInternalErr
+	// The server received a TLS error during validation
+	tlsErr
+	// The client lacks sufficient authorization
+	unauthorizedErr
+	// A contact URL for an account used an unsupported protocol scheme
+	unsupportedContactErr
+	// An identifier is of an unsupported type
+	unsupportedIdentifierErr
+	// Visit the “instance” URL and take actions specified there
+	userActionRequiredErr
+)
+
+// String returns the string representation of the acme problem type,
+// fulfilling the Stringer interface.
+func (ap ProbType) String() string {
+	switch ap {
+	case accountDoesNotExistErr:
+		return "accountDoesNotExist"
+	case alreadyRevokedErr:
+		return "alreadyRevoked"
+	case badCSRErr:
+		return "badCSR"
+	case badNonceErr:
+		return "badNonce"
+	case badPublicKeyErr:
+		return "badPublicKey"
+	case badRevocationReasonErr:
+		return "badRevocationReason"
+	case badSignatureAlgorithmErr:
+		return "badSignatureAlgorithm"
+	case caaErr:
+		return "caa"
+	case compoundErr:
+		return "compound"
+	case connectionErr:
+		return "connection"
+	case dnsErr:
+		return "dns"
+	case externalAccountRequiredErr:
+		return "externalAccountRequired"
+	case incorrectResponseErr:
+		return "incorrectResponse"
+	case invalidContactErr:
+		return "invalidContact"
+	case malformedErr:
+		return "malformed"
+	case orderNotReadyErr:
+		return "orderNotReady"
+	case rateLimitedErr:
+		return "rateLimited"
+	case rejectedIdentifierErr:
+		return "rejectedIdentifier"
+	case serverInternalErr:
+		return "serverInternal"
+	case tlsErr:
+		return "tls"
+	case unauthorizedErr:
+		return "unauthorized"
+	case unsupportedContactErr:
+		return "unsupportedContact"
+	case unsupportedIdentifierErr:
+		return "unsupportedIdentifier"
+	case userActionRequiredErr:
+		return "userActionRequired"
+	default:
+		return "unsupported type"
+	}
+}
+
+// Error is an ACME error type complete with problem document.
+type Error struct {
+	Type       ProbType
+	Detail     string
+	Err        error
+	Status     int
+	Sub        []*Error
+	Identifier *Identifier
+}
+
+// Wrap attempts to wrap the internal error.
+func Wrap(err error, wrap string) *Error {
+	switch e := err.(type) {
+	case nil:
+		return nil
+	case *Error:
+		if e.Err == nil {
+			e.Err = errors.New(wrap + "; " + e.Detail)
+		} else {
+			e.Err = errors.Wrap(e.Err, wrap)
+		}
+		return e
+	default:
+		return ServerInternalErr(errors.Wrap(err, wrap))
+	}
+}
+
+// Error implements the error interface.
+func (e *Error) Error() string {
+	if e.Err == nil {
+		return e.Detail
+	}
+	return e.Err.Error()
+}
+
+// Cause returns the internal error and implements the Causer interface.
+func (e *Error) Cause() error {
+	if e.Err == nil {
+		return errors.New(e.Detail)
+	}
+	return e.Err
+}
+
+// ToACME returns an acme representation of the problem type.
+func (e *Error) ToACME() *AError {
+	ae := &AError{
+		Type:   "urn:ietf:params:acme:error:" + e.Type.String(),
+		Detail: e.Error(),
+		Status: e.Status,
+	}
+	if e.Identifier != nil {
+		ae.Identifier = *e.Identifier
+	}
+	for _, p := range e.Sub {
+		ae.Subproblems = append(ae.Subproblems, p.ToACME())
+	}
+	return ae
+}
+
+// StatusCode returns the status code and implements the StatusCode interface.
+func (e *Error) StatusCode() int {
+	return e.Status
+}
+
+// AError is the error type as seen in acme request/responses.
+type AError struct {
+	Type        string        `json:"type"`
+	Detail      string        `json:"detail"`
+	Identifier  interface{}   `json:"identifier,omitempty"`
+	Subproblems []interface{} `json:"subproblems,omitempty"`
+	Status      int           `json:"-"`
+}
+
+// Error allows AError to implement the error interface.
+func (ae *AError) Error() string {
+	return ae.Detail
+}
+
+// StatusCode returns the status code and implements the StatusCode interface.
+func (ae *AError) StatusCode() int {
+	return ae.Status
+}

+ 73 - 0
acme/nonce.go

@@ -0,0 +1,73 @@
+package acme
+
+import (
+	"encoding/base64"
+	"encoding/json"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+// nonce contains nonce metadata used in the ACME protocol.
+type nonce struct {
+	ID      string
+	Created time.Time
+}
+
+// newNonce creates, stores, and returns an ACME replay-nonce.
+func newNonce(db nosql.DB) (*nonce, error) {
+	_id, err := randID()
+	if err != nil {
+		return nil, err
+	}
+
+	id := base64.RawURLEncoding.EncodeToString([]byte(_id))
+	n := &nonce{
+		ID:      id,
+		Created: clock.Now(),
+	}
+	b, err := json.Marshal(n)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling nonce"))
+	}
+	_, swapped, err := db.CmpAndSwap(nonceTable, []byte(id), nil, b)
+	switch {
+	case err != nil:
+		return nil, ServerInternalErr(errors.Wrap(err, "error storing nonce"))
+	case !swapped:
+		return nil, ServerInternalErr(errors.New("error storing nonce; " +
+			"value has changed since last read"))
+	default:
+		return n, nil
+	}
+}
+
+// useNonce verifies that the nonce is valid (by checking if it exists),
+// and if so, consumes the nonce resource by deleting it from the database.
+func useNonce(db nosql.DB, nonce string) error {
+	err := db.Update(&database.Tx{
+		Operations: []*database.TxEntry{
+			{
+				Bucket: nonceTable,
+				Key:    []byte(nonce),
+				Cmd:    database.Get,
+			},
+			{
+				Bucket: nonceTable,
+				Key:    []byte(nonce),
+				Cmd:    database.Delete,
+			},
+		},
+	})
+
+	switch {
+	case nosql.IsErrNotFound(err):
+		return BadNonceErr(nil)
+	case err != nil:
+		return ServerInternalErr(errors.Wrapf(err, "error deleting nonce %s", nonce))
+	default:
+		return nil
+	}
+}

+ 163 - 0
acme/nonce_test.go

@@ -0,0 +1,163 @@
+package acme
+
+import (
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+func TestNewNonce(t *testing.T) {
+	type test struct {
+		db  nosql.DB
+		err *Error
+		id  *string
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/cmpAndSwap-error": func(t *testing.T) test {
+			return test{
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, nonceTable)
+						assert.Equals(t, old, nil)
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing nonce: force")),
+			}
+		},
+		"fail/cmpAndSwap-false": func(t *testing.T) test {
+			return test{
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, nonceTable)
+						assert.Equals(t, old, nil)
+						return nil, false, nil
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing nonce; value has changed since last read")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			var _id string
+			id := &_id
+			return test{
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, bucket, nonceTable)
+						assert.Equals(t, old, nil)
+						*id = string(key)
+						return nil, true, nil
+					},
+				},
+				id: id,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if n, err := newNonce(tc.db); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, n.ID, *tc.id)
+
+					assert.True(t, n.Created.Before(time.Now().Add(time.Minute)))
+					assert.True(t, n.Created.After(time.Now().Add(-time.Minute)))
+				}
+			}
+		})
+	}
+}
+
+func TestUseNonce(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/update-not-found": func(t *testing.T) test {
+			id := "foo"
+			return test{
+				db: &db.MockNoSQLDB{
+					MUpdate: func(tx *database.Tx) error {
+						assert.Equals(t, tx.Operations[0].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[0].Key, []byte(id))
+						assert.Equals(t, tx.Operations[0].Cmd, database.Get)
+
+						assert.Equals(t, tx.Operations[1].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[1].Key, []byte(id))
+						assert.Equals(t, tx.Operations[1].Cmd, database.Delete)
+						return database.ErrNotFound
+					},
+				},
+				id:  id,
+				err: BadNonceErr(nil),
+			}
+		},
+		"fail/update-error": func(t *testing.T) test {
+			id := "foo"
+			return test{
+				db: &db.MockNoSQLDB{
+					MUpdate: func(tx *database.Tx) error {
+						assert.Equals(t, tx.Operations[0].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[0].Key, []byte(id))
+						assert.Equals(t, tx.Operations[0].Cmd, database.Get)
+
+						assert.Equals(t, tx.Operations[1].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[1].Key, []byte(id))
+						assert.Equals(t, tx.Operations[1].Cmd, database.Delete)
+						return errors.New("force")
+					},
+				},
+				id:  id,
+				err: ServerInternalErr(errors.Errorf("error deleting nonce %s: force", id)),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			id := "foo"
+			return test{
+				db: &db.MockNoSQLDB{
+					MUpdate: func(tx *database.Tx) error {
+						assert.Equals(t, tx.Operations[0].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[0].Key, []byte(id))
+						assert.Equals(t, tx.Operations[0].Cmd, database.Get)
+
+						assert.Equals(t, tx.Operations[1].Bucket, nonceTable)
+						assert.Equals(t, tx.Operations[1].Key, []byte(id))
+						assert.Equals(t, tx.Operations[1].Cmd, database.Delete)
+
+						return nil
+					},
+				},
+				id: id,
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := useNonce(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			}
+		})
+	}
+}

+ 342 - 0
acme/order.go

@@ -0,0 +1,342 @@
+package acme
+
+import (
+	"context"
+	"crypto/x509"
+	"encoding/json"
+	"reflect"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/nosql"
+)
+
+var defaultOrderExpiry = time.Hour * 24
+
+// Order contains order metadata for the ACME protocol order type.
+type Order struct {
+	Status         string       `json:"status"`
+	Expires        string       `json:"expires,omitempty"`
+	Identifiers    []Identifier `json:"identifiers"`
+	NotBefore      string       `json:"notBefore,omitempty"`
+	NotAfter       string       `json:"notAfter,omitempty"`
+	Error          interface{}  `json:"error,omitempty"`
+	Authorizations []string     `json:"authorizations"`
+	Finalize       string       `json:"finalize"`
+	Certificate    string       `json:"certificate,omitempty"`
+	ID             string       `json:"-"`
+}
+
+// ToLog enables response logging.
+func (o *Order) ToLog() (interface{}, error) {
+	b, err := json.Marshal(o)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error marshaling order for logging"))
+	}
+	return string(b), nil
+}
+
+// GetID returns the Order ID.
+func (o *Order) GetID() string {
+	return o.ID
+}
+
+// OrderOptions options with which to create a new Order.
+type OrderOptions struct {
+	AccountID   string       `json:"accID"`
+	Identifiers []Identifier `json:"identifiers"`
+	NotBefore   time.Time    `json:"notBefore"`
+	NotAfter    time.Time    `json:"notAfter"`
+}
+
+type order struct {
+	ID             string       `json:"id"`
+	AccountID      string       `json:"accountID"`
+	Created        time.Time    `json:"created"`
+	Expires        time.Time    `json:"expires,omitempty"`
+	Status         string       `json:"status"`
+	Identifiers    []Identifier `json:"identifiers"`
+	NotBefore      time.Time    `json:"notBefore,omitempty"`
+	NotAfter       time.Time    `json:"notAfter,omitempty"`
+	Error          *Error       `json:"error,omitempty"`
+	Authorizations []string     `json:"authorizations"`
+	Certificate    string       `json:"certificate,omitempty"`
+}
+
+// newOrder returns a new Order type.
+func newOrder(db nosql.DB, ops OrderOptions) (*order, error) {
+	id, err := randID()
+	if err != nil {
+		return nil, err
+	}
+
+	authzs := make([]string, len(ops.Identifiers))
+	for i, identifier := range ops.Identifiers {
+		az, err := newAuthz(db, ops.AccountID, identifier)
+		if err != nil {
+			return nil, err
+		}
+		authzs[i] = az.getID()
+	}
+
+	now := clock.Now()
+	o := &order{
+		ID:             id,
+		AccountID:      ops.AccountID,
+		Created:        now,
+		Status:         StatusPending,
+		Expires:        now.Add(defaultOrderExpiry),
+		Identifiers:    ops.Identifiers,
+		NotBefore:      ops.NotBefore,
+		NotAfter:       ops.NotAfter,
+		Authorizations: authzs,
+	}
+	if err := o.save(db, nil); err != nil {
+		return nil, err
+	}
+
+	// Update the "order IDs by account ID" index //
+	oids, err := getOrderIDsByAccount(db, ops.AccountID)
+	if err != nil {
+		return nil, err
+	}
+	newOids := append(oids, o.ID)
+	if err = orderIDs(newOids).save(db, oids, o.AccountID); err != nil {
+		db.Del(orderTable, []byte(o.ID))
+		return nil, err
+	}
+	return o, nil
+}
+
+type orderIDs []string
+
+func (oids orderIDs) save(db nosql.DB, old orderIDs, accID string) error {
+	var (
+		err  error
+		oldb []byte
+	)
+	if len(old) == 0 {
+		oldb = nil
+	} else {
+		oldb, err = json.Marshal(old)
+		if err != nil {
+			return ServerInternalErr(errors.Wrap(err, "error marshaling old order IDs slice"))
+		}
+	}
+	newb, err := json.Marshal(oids)
+	if err != nil {
+		return ServerInternalErr(errors.Wrap(err, "error marshaling new order IDs slice"))
+	}
+	_, swapped, err := db.CmpAndSwap(ordersByAccountIDTable, []byte(accID), oldb, newb)
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrapf(err, "error storing order IDs for account %s", accID))
+	case !swapped:
+		return ServerInternalErr(errors.Errorf("error storing order IDs "+
+			"for account %s; order IDs changed since last read", accID))
+	default:
+		return nil
+	}
+}
+
+func (o *order) save(db nosql.DB, old *order) error {
+	var (
+		err  error
+		oldB []byte
+	)
+	if old == nil {
+		oldB = nil
+	} else {
+		if oldB, err = json.Marshal(old); err != nil {
+			return ServerInternalErr(errors.Wrap(err, "error marshaling old acme order"))
+		}
+	}
+
+	newB, err := json.Marshal(o)
+	if err != nil {
+		return ServerInternalErr(errors.Wrap(err, "error marshaling new acme order"))
+	}
+
+	_, swapped, err := db.CmpAndSwap(orderTable, []byte(o.ID), oldB, newB)
+	switch {
+	case err != nil:
+		return ServerInternalErr(errors.Wrap(err, "error storing order"))
+	case !swapped:
+		return ServerInternalErr(errors.New("error storing order; " +
+			"value has changed since last read"))
+	default:
+		return nil
+	}
+}
+
+// updateStatus updates order status if necessary.
+func (o *order) updateStatus(db nosql.DB) (*order, error) {
+	_newOrder := *o
+	newOrder := &_newOrder
+
+	now := time.Now().UTC()
+	switch o.Status {
+	case StatusInvalid:
+		return o, nil
+	case StatusValid:
+		return o, nil
+	case StatusReady:
+		// check expiry
+		if now.After(o.Expires) {
+			newOrder.Status = StatusInvalid
+			newOrder.Error = MalformedErr(errors.New("order has expired"))
+			break
+		}
+		return o, nil
+	case StatusPending:
+		// check expiry
+		if now.After(o.Expires) {
+			newOrder.Status = StatusInvalid
+			newOrder.Error = MalformedErr(errors.New("order has expired"))
+			break
+		}
+
+		var count = map[string]int{
+			StatusValid:   0,
+			StatusInvalid: 0,
+			StatusPending: 0,
+		}
+		for _, azID := range o.Authorizations {
+			az, err := getAuthz(db, azID)
+			if err != nil {
+				return nil, err
+			}
+			if az, err = az.updateStatus(db); err != nil {
+				return nil, err
+			}
+			st := az.getStatus()
+			count[st]++
+		}
+		switch {
+		case count[StatusInvalid] > 0:
+			newOrder.Status = StatusInvalid
+		case count[StatusPending] > 0:
+			break
+		case count[StatusValid] == len(o.Authorizations):
+			newOrder.Status = StatusReady
+		default:
+			return nil, ServerInternalErr(errors.New("unexpected authz status"))
+		}
+	default:
+		return nil, ServerInternalErr(errors.Errorf("unrecognized order status: %s", o.Status))
+	}
+
+	if err := newOrder.save(db, o); err != nil {
+		return nil, err
+	}
+	return newOrder, nil
+}
+
+// finalize signs a certificate if the necessary conditions for Order completion
+// have been met.
+func (o *order) finalize(db nosql.DB, csr *x509.CertificateRequest, auth SignAuthority, p provisioner.Interface) (*order, error) {
+	var err error
+	if o, err = o.updateStatus(db); err != nil {
+		return nil, err
+	}
+	switch o.Status {
+	case StatusInvalid:
+		return nil, OrderNotReadyErr(errors.Errorf("order %s has been abandoned", o.ID))
+	case StatusValid:
+		return o, nil
+	case StatusPending:
+		return nil, OrderNotReadyErr(errors.Errorf("order %s is not ready", o.ID))
+	case StatusReady:
+		break
+	default:
+		return nil, ServerInternalErr(errors.Errorf("unexpected status %s for order %s", o.Status, o.ID))
+	}
+
+	// Validate identifier names against CSR alternative names //
+	csrNames := make(map[string]int)
+	for _, n := range csr.DNSNames {
+		csrNames[n] = 1
+	}
+	orderNames := make(map[string]int)
+	for _, n := range o.Identifiers {
+		orderNames[n.Value] = 1
+	}
+	if !reflect.DeepEqual(csrNames, orderNames) {
+		return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly"))
+	}
+
+	// Get authorizations from the ACME provisioner.
+	ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
+	signOps, err := p.AuthorizeSign(ctx, "")
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error retrieving authorization options from ACME provisioner"))
+	}
+
+	// Create and store a new certificate.
+	leaf, inter, err := auth.Sign(csr, provisioner.Options{
+		NotBefore: provisioner.NewTimeDuration(o.NotBefore),
+		NotAfter:  provisioner.NewTimeDuration(o.NotAfter),
+	}, signOps...)
+	if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error generating certificate for order %s", o.ID))
+	}
+
+	cert, err := newCert(db, CertOptions{
+		AccountID:     o.AccountID,
+		OrderID:       o.ID,
+		Leaf:          leaf,
+		Intermediates: []*x509.Certificate{inter},
+	})
+	if err != nil {
+		return nil, err
+	}
+
+	_newOrder := *o
+	newOrder := &_newOrder
+	newOrder.Certificate = cert.ID
+	newOrder.Status = StatusValid
+	if err := newOrder.save(db, o); err != nil {
+		return nil, err
+	}
+	return newOrder, nil
+}
+
+// getOrder retrieves and unmarshals an ACME Order type from the database.
+func getOrder(db nosql.DB, id string) (*order, error) {
+	b, err := db.Get(orderTable, []byte(id))
+	if nosql.IsErrNotFound(err) {
+		return nil, MalformedErr(errors.Wrapf(err, "order %s not found", id))
+	} else if err != nil {
+		return nil, ServerInternalErr(errors.Wrapf(err, "error loading order %s", id))
+	}
+	var o order
+	if err := json.Unmarshal(b, &o); err != nil {
+		return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling order"))
+	}
+	return &o, nil
+}
+
+// toACME converts the internal Order type into the public acmeOrder type for
+// presentation in the ACME protocol.
+func (o *order) toACME(db nosql.DB, dir *directory, p provisioner.Interface) (*Order, error) {
+	azs := make([]string, len(o.Authorizations))
+	for i, aid := range o.Authorizations {
+		azs[i] = dir.getLink(AuthzLink, URLSafeProvisionerName(p), true, aid)
+	}
+	ao := &Order{
+		Status:         o.Status,
+		Expires:        o.Expires.Format(time.RFC3339),
+		Identifiers:    o.Identifiers,
+		NotBefore:      o.NotBefore.Format(time.RFC3339),
+		NotAfter:       o.NotAfter.Format(time.RFC3339),
+		Authorizations: azs,
+		Finalize:       dir.getLink(FinalizeLink, URLSafeProvisionerName(p), true, o.ID),
+		ID:             o.ID,
+	}
+
+	if o.Certificate != "" {
+		ao.Certificate = dir.getLink(CertificateLink, URLSafeProvisionerName(p), true, o.Certificate)
+	}
+	return ao, nil
+}

+ 1129 - 0
acme/order_test.go

@@ -0,0 +1,1129 @@
+package acme
+
+import (
+	"context"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/json"
+	"fmt"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/db"
+	"github.com/smallstep/nosql"
+	"github.com/smallstep/nosql/database"
+)
+
+var certDuration = 6 * time.Hour
+
+func defaultOrderOps() OrderOptions {
+	return OrderOptions{
+		AccountID: "accID",
+		Identifiers: []Identifier{
+			{Type: "dns", Value: "acme.example.com"},
+			{Type: "dns", Value: "step.example.com"},
+		},
+		NotBefore: clock.Now(),
+		NotAfter:  clock.Now().Add(certDuration),
+	}
+}
+
+func newO() (*order, error) {
+	mockdb := &db.MockNoSQLDB{
+		MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+			return []byte("foo"), true, nil
+		},
+		MGet: func(bucket, key []byte) ([]byte, error) {
+			b, err := json.Marshal([]string{"1", "2"})
+			if err != nil {
+				return nil, err
+			}
+			return b, nil
+		},
+	}
+	return newOrder(mockdb, defaultOrderOps())
+}
+
+func TestGetOrder(t *testing.T) {
+	type test struct {
+		id  string
+		db  nosql.DB
+		o   *order
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/not-found": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:  o,
+				id: o.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, database.ErrNotFound
+					},
+				},
+				err: MalformedErr(errors.Errorf("order %s not found: not found", o.ID)),
+			}
+		},
+		"fail/db-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:  o,
+				id: o.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error loading order %s: force", o.ID)),
+			}
+		},
+		"fail/unmarshal-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:  o,
+				id: o.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(o.ID))
+						return nil, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error unmarshaling order: unexpected end of JSON input")),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			return test{
+				o:  o,
+				id: o.ID,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(o.ID))
+						return b, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if o, err := getOrder(tc.db, tc.id); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, tc.o.ID, o.ID)
+					assert.Equals(t, tc.o.AccountID, o.AccountID)
+					assert.Equals(t, tc.o.Status, o.Status)
+					assert.Equals(t, tc.o.Identifiers, o.Identifiers)
+					assert.Equals(t, tc.o.Created, o.Created)
+					assert.Equals(t, tc.o.Expires, o.Expires)
+					assert.Equals(t, tc.o.Authorizations, o.Authorizations)
+					assert.Equals(t, tc.o.NotBefore, o.NotBefore)
+					assert.Equals(t, tc.o.NotAfter, o.NotAfter)
+					assert.Equals(t, tc.o.Certificate, o.Certificate)
+					assert.Equals(t, tc.o.Error, o.Error)
+				}
+			}
+		})
+	}
+}
+
+func TestOrderToACME(t *testing.T) {
+	dir := newDirectory("ca.smallstep.com", "acme")
+	prov := newProv()
+
+	type test struct {
+		o   *order
+		err *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"ok/no-cert": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{o: o}
+		},
+		"ok/cert": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusValid
+			o.Certificate = "cert-id"
+			return test{o: o}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			acmeOrder, err := tc.o.toACME(nil, dir, prov)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, acmeOrder.ID, tc.o.ID)
+					assert.Equals(t, acmeOrder.Status, tc.o.Status)
+					assert.Equals(t, acmeOrder.Identifiers, tc.o.Identifiers)
+					assert.Equals(t, acmeOrder.Finalize, fmt.Sprintf("https://ca.smallstep.com/acme/%s/order/%s/finalize", URLSafeProvisionerName(prov), tc.o.ID))
+					if tc.o.Certificate != "" {
+						assert.Equals(t, acmeOrder.Certificate, fmt.Sprintf("https://ca.smallstep.com/acme/%s/certificate/%s", URLSafeProvisionerName(prov), tc.o.Certificate))
+					}
+
+					expiry, err := time.Parse(time.RFC3339, acmeOrder.Expires)
+					assert.FatalError(t, err)
+					assert.Equals(t, expiry.String(), tc.o.Expires.String())
+					nbf, err := time.Parse(time.RFC3339, acmeOrder.NotBefore)
+					assert.FatalError(t, err)
+					assert.Equals(t, nbf.String(), tc.o.NotBefore.String())
+					naf, err := time.Parse(time.RFC3339, acmeOrder.NotAfter)
+					assert.FatalError(t, err)
+					assert.Equals(t, naf.String(), tc.o.NotAfter.String())
+				}
+			}
+		})
+	}
+}
+
+func TestOrderSave(t *testing.T) {
+	type test struct {
+		o, old *order
+		db     nosql.DB
+		err    *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/old-nil/swap-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:   o,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing order: force")),
+			}
+		},
+		"fail/old-nil/swap-false": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:   o,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return []byte("foo"), false, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing order; value has changed since last read")),
+			}
+		},
+		"ok/old-nil": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			return test{
+				o:   o,
+				old: nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, nil)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, []byte(o.ID), key)
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/old-not-nil": func(t *testing.T) test {
+			oldo, err := newO()
+			assert.FatalError(t, err)
+			o, err := newO()
+			assert.FatalError(t, err)
+
+			oldb, err := json.Marshal(oldo)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(o)
+			assert.FatalError(t, err)
+			return test{
+				o:   o,
+				old: oldo,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, []byte(o.ID), key)
+						return []byte("foo"), true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.o.save(tc.db, tc.old); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestNewOrder(t *testing.T) {
+	type test struct {
+		ops    OrderOptions
+		db     nosql.DB
+		err    *Error
+		authzs *([]string)
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/unexpected-identifier-type": func(t *testing.T) test {
+			ops := defaultOrderOps()
+			ops.Identifiers[0].Type = "foo"
+			return test{
+				ops: ops,
+				err: MalformedErr(errors.New("unexpected authz type foo")),
+			}
+		},
+		"fail/save-order-error": func(t *testing.T) test {
+			count := 0
+			return test{
+				ops: defaultOrderOps(),
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count >= 6 {
+							return nil, false, errors.New("force")
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing order: force")),
+			}
+		},
+		"fail/get-orderIDs-error": func(t *testing.T) test {
+			count := 0
+			ops := defaultOrderOps()
+			return test{
+				ops: ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count >= 7 {
+							return nil, false, errors.New("force")
+						}
+						count++
+						return nil, true, nil
+					},
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error loading orderIDs for account %s: force", ops.AccountID)),
+			}
+		},
+		"fail/save-orderIDs-error": func(t *testing.T) test {
+			count := 0
+			oids := []string{"1", "2"}
+			oidsB, err := json.Marshal(oids)
+			assert.FatalError(t, err)
+			var (
+				_oid = ""
+				oid  = &_oid
+			)
+			ops := defaultOrderOps()
+			return test{
+				ops: ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count >= 7 {
+							assert.Equals(t, bucket, ordersByAccountIDTable)
+							assert.Equals(t, key, []byte(ops.AccountID))
+							return nil, false, errors.New("force")
+						} else if count == 6 {
+							*oid = string(key)
+						}
+						count++
+						return nil, true, nil
+					},
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return oidsB, nil
+					},
+					MDel: func(bucket, key []byte) error {
+						assert.Equals(t, bucket, orderTable)
+						assert.Equals(t, key, []byte(*oid))
+						return nil
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing order IDs for account %s: force", ops.AccountID)),
+			}
+		},
+		"ok": func(t *testing.T) test {
+			count := 0
+			oids := []string{"1", "2"}
+			oidsB, err := json.Marshal(oids)
+			assert.FatalError(t, err)
+			authzs := &([]string{})
+			var (
+				_oid = ""
+				oid  = &_oid
+			)
+			ops := defaultOrderOps()
+			return test{
+				ops: ops,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count >= 7 {
+							assert.Equals(t, bucket, ordersByAccountIDTable)
+							assert.Equals(t, key, []byte(ops.AccountID))
+							assert.Equals(t, old, oidsB)
+							newB, err := json.Marshal(append(oids, *oid))
+							assert.FatalError(t, err)
+							assert.Equals(t, newval, newB)
+						} else if count == 6 {
+							*oid = string(key)
+						} else if count == 5 {
+							*authzs = append(*authzs, string(key))
+						} else if count == 2 {
+							*authzs = []string{string(key)}
+						}
+						count++
+						return nil, true, nil
+					},
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return oidsB, nil
+					},
+				},
+				authzs: authzs,
+			}
+		},
+	}
+	for name, run := range tests {
+		tc := run(t)
+		t.Run(name, func(t *testing.T) {
+			o, err := newOrder(tc.db, tc.ops)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, o.AccountID, tc.ops.AccountID)
+					assert.Equals(t, o.Status, StatusPending)
+					assert.Equals(t, o.Identifiers, tc.ops.Identifiers)
+					assert.Equals(t, o.Error, nil)
+					assert.Equals(t, o.Certificate, "")
+					assert.Equals(t, o.Authorizations, *tc.authzs)
+
+					assert.True(t, o.Created.Before(time.Now().UTC().Add(time.Minute)))
+					assert.True(t, o.Created.After(time.Now().UTC().Add(-1*time.Minute)))
+
+					expiry := o.Created.Add(defaultExpiryDuration)
+					assert.True(t, o.Expires.Before(expiry.Add(time.Minute)))
+					assert.True(t, o.Expires.After(expiry.Add(-1*time.Minute)))
+
+					assert.Equals(t, o.NotBefore, tc.ops.NotBefore)
+					assert.Equals(t, o.NotAfter, tc.ops.NotAfter)
+				}
+			}
+		})
+	}
+}
+
+func TestOrderIDsSave(t *testing.T) {
+	accID := "acc-id"
+	newOids := func() orderIDs {
+		return []string{"1", "2"}
+	}
+	type test struct {
+		oids, old orderIDs
+		db        nosql.DB
+		err       *Error
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/old-nil/swap-error": func(t *testing.T) test {
+			return test{
+				oids: newOids(),
+				old:  nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing order IDs for account %s: force", accID)),
+			}
+		},
+		"fail/old-nil/swap-false": func(t *testing.T) test {
+			return test{
+				oids: newOids(),
+				old:  nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return []byte("foo"), false, nil
+					},
+				},
+				err: ServerInternalErr(errors.Errorf("error storing order IDs for account %s; order IDs changed since last read", accID)),
+			}
+		},
+		"ok/old-nil": func(t *testing.T) test {
+			oids := newOids()
+			b, err := json.Marshal(oids)
+			assert.FatalError(t, err)
+			return test{
+				oids: oids,
+				old:  nil,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, nil)
+						assert.Equals(t, b, newval)
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte(accID))
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/old-not-nil": func(t *testing.T) test {
+			oldOids := newOids()
+			oids := append(oldOids, "3")
+
+			oldb, err := json.Marshal(oldOids)
+			assert.FatalError(t, err)
+			b, err := json.Marshal(oids)
+			assert.FatalError(t, err)
+			return test{
+				oids: oids,
+				old:  oldOids,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						assert.Equals(t, old, oldb)
+						assert.Equals(t, newval, b)
+						assert.Equals(t, bucket, ordersByAccountIDTable)
+						assert.Equals(t, key, []byte(accID))
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			if err := tc.oids.save(tc.db, tc.old, accID); err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestOrderUpdateStatus(t *testing.T) {
+	type test struct {
+		o, res *order
+		err    *Error
+		db     nosql.DB
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/already-invalid": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusInvalid
+			return test{
+				o:   o,
+				res: o,
+			}
+		},
+		"fail/already-valid": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusValid
+			return test{
+				o:   o,
+				res: o,
+			}
+		},
+		"fail/unexpected-status": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusDeactivated
+			return test{
+				o:   o,
+				res: o,
+				err: ServerInternalErr(errors.New("unrecognized order status: deactivated")),
+			}
+		},
+		"fail/save-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Expires = time.Now().UTC().Add(-time.Minute)
+			return test{
+				o:   o,
+				res: o,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error storing order: force")),
+			}
+		},
+		"ok/expired": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Expires = time.Now().UTC().Add(-time.Minute)
+
+			_o := *o
+			clone := &_o
+			clone.Error = MalformedErr(errors.New("order has expired"))
+			clone.Status = StatusInvalid
+			return test{
+				o:   o,
+				res: clone,
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"fail/get-authz-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			return test{
+				o:   o,
+				res: o,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						return nil, errors.New("force")
+					},
+				},
+				err: ServerInternalErr(errors.New("error loading authz")),
+			}
+		},
+		"ok/still-pending": func(t *testing.T) test {
+			az1, err := newAz()
+			assert.FatalError(t, err)
+			az2, err := newAz()
+			assert.FatalError(t, err)
+
+			ch1, err := newHTTPCh()
+			assert.FatalError(t, err)
+			ch2, err := newDNSCh()
+			assert.FatalError(t, err)
+
+			ch1b, err := json.Marshal(ch1)
+			assert.FatalError(t, err)
+			ch2b, err := json.Marshal(ch2)
+			assert.FatalError(t, err)
+
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Authorizations = []string{az1.getID(), az2.getID()}
+
+			_az2, ok := az2.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az2.baseAuthz.Status = StatusValid
+
+			b1, err := json.Marshal(az1)
+			assert.FatalError(t, err)
+			b2, err := json.Marshal(az2)
+			assert.FatalError(t, err)
+
+			count := 0
+			return test{
+				o:   o,
+				res: o,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						var ret []byte
+						switch count {
+						case 0:
+							ret = b1
+						case 1:
+							ret = ch1b
+						case 2:
+							ret = ch2b
+						case 3:
+							ret = b2
+						default:
+							return nil, errors.New("unexpected count")
+						}
+						count++
+						return ret, nil
+					},
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/invalid": func(t *testing.T) test {
+			az1, err := newAz()
+			assert.FatalError(t, err)
+			az2, err := newAz()
+			assert.FatalError(t, err)
+
+			ch1, err := newHTTPCh()
+			assert.FatalError(t, err)
+			ch2, err := newDNSCh()
+			assert.FatalError(t, err)
+
+			ch1b, err := json.Marshal(ch1)
+			assert.FatalError(t, err)
+			ch2b, err := json.Marshal(ch2)
+			assert.FatalError(t, err)
+
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Authorizations = []string{az1.getID(), az2.getID()}
+
+			_az2, ok := az2.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az2.baseAuthz.Status = StatusInvalid
+
+			b1, err := json.Marshal(az1)
+			assert.FatalError(t, err)
+			b2, err := json.Marshal(az2)
+			assert.FatalError(t, err)
+
+			_o := *o
+			clone := &_o
+			clone.Status = StatusInvalid
+
+			count := 0
+			return test{
+				o:   o,
+				res: clone,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						var ret []byte
+						switch count {
+						case 0:
+							ret = b1
+						case 1:
+							ret = ch1b
+						case 2:
+							ret = ch2b
+						case 3:
+							ret = b2
+						default:
+							return nil, errors.New("unexpected count")
+						}
+						count++
+						return ret, nil
+					},
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			o, err := tc.o.updateStatus(tc.db)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					expB, err := json.Marshal(tc.res)
+					assert.FatalError(t, err)
+					b, err := json.Marshal(o)
+					assert.FatalError(t, err)
+					assert.Equals(t, expB, b)
+				}
+			}
+		})
+	}
+}
+
+type mockSignAuth struct {
+	sign                func(csr *x509.CertificateRequest, signOpts provisioner.Options, extraOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
+	loadProvisionerByID func(string) (provisioner.Interface, error)
+	ret1, ret2          interface{}
+	err                 error
+}
+
+func (m *mockSignAuth) Sign(csr *x509.CertificateRequest, signOpts provisioner.Options, extraOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error) {
+	if m.sign != nil {
+		return m.sign(csr, signOpts, extraOpts...)
+	} else if m.err != nil {
+		return nil, nil, m.err
+	}
+	return m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate), m.err
+}
+
+func (m *mockSignAuth) LoadProvisionerByID(id string) (provisioner.Interface, error) {
+	if m.loadProvisionerByID != nil {
+		return m.loadProvisionerByID(id)
+	}
+	return m.ret1.(provisioner.Interface), m.err
+}
+
+func TestOrderFinalize(t *testing.T) {
+	prov := newProv()
+	type test struct {
+		o, res *order
+		err    *Error
+		db     nosql.DB
+		csr    *x509.CertificateRequest
+		sa     SignAuthority
+		prov   provisioner.Interface
+	}
+	tests := map[string]func(t *testing.T) test{
+		"fail/already-invalid": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusInvalid
+			return test{
+				o:   o,
+				err: OrderNotReadyErr(errors.Errorf("order %s has been abandoned", o.ID)),
+			}
+		},
+		"ok/already-valid": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusValid
+			o.Certificate = "cert-id"
+			return test{
+				o:   o,
+				res: o,
+			}
+		},
+		"fail/still-pending": func(t *testing.T) test {
+			az1, err := newAz()
+			assert.FatalError(t, err)
+			az2, err := newAz()
+			assert.FatalError(t, err)
+
+			ch1, err := newHTTPCh()
+			assert.FatalError(t, err)
+			ch2, err := newDNSCh()
+			assert.FatalError(t, err)
+
+			ch1b, err := json.Marshal(ch1)
+			assert.FatalError(t, err)
+			ch2b, err := json.Marshal(ch2)
+			assert.FatalError(t, err)
+
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Authorizations = []string{az1.getID(), az2.getID()}
+
+			_az2, ok := az2.(*dnsAuthz)
+			assert.Fatal(t, ok)
+			_az2.baseAuthz.Status = StatusValid
+
+			b1, err := json.Marshal(az1)
+			assert.FatalError(t, err)
+			b2, err := json.Marshal(az2)
+			assert.FatalError(t, err)
+
+			count := 0
+			return test{
+				o:   o,
+				res: o,
+				db: &db.MockNoSQLDB{
+					MGet: func(bucket, key []byte) ([]byte, error) {
+						var ret []byte
+						switch count {
+						case 0:
+							ret = b1
+						case 1:
+							ret = ch1b
+						case 2:
+							ret = ch2b
+						case 3:
+							ret = b2
+						default:
+							return nil, errors.New("unexpected count")
+						}
+						count++
+						return ret, nil
+					},
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, true, nil
+					},
+				},
+				err: OrderNotReadyErr(errors.Errorf("order %s is not ready", o.ID)),
+			}
+		},
+		"fail/ready/csr-names-match-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "foo",
+				},
+				DNSNames: []string{"bar", "baz"},
+			}
+			return test{
+				o:   o,
+				csr: csr,
+				err: BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly")),
+			}
+		},
+		"fail/ready/csr-names-match-error-2": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "acme.example.com",
+				},
+				DNSNames: []string{"step.example.com"},
+			}
+			return test{
+				o:   o,
+				csr: csr,
+				err: BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly")),
+			}
+		},
+		"fail/ready/provisioner-auth-sign-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "foo",
+				},
+				DNSNames: []string{"step.example.com", "acme.example.com"},
+			}
+			return test{
+				o:   o,
+				csr: csr,
+				err: ServerInternalErr(errors.New("error retrieving authorization options from ACME provisioner: force")),
+				prov: &provisioner.MockProvisioner{
+					MauthorizeSign: func(ctx context.Context, token string) ([]provisioner.SignOption, error) {
+						return nil, errors.New("force")
+					},
+				},
+			}
+		},
+		"fail/ready/sign-cert-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "foo",
+				},
+				DNSNames: []string{"step.example.com", "acme.example.com"},
+			}
+			return test{
+				o:   o,
+				csr: csr,
+				err: ServerInternalErr(errors.Errorf("error generating certificate for order %s: force", o.ID)),
+				sa: &mockSignAuth{
+					err: errors.New("force"),
+				},
+			}
+		},
+		"fail/ready/store-cert-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "foo",
+				},
+				DNSNames: []string{"step.example.com", "acme.example.com"},
+			}
+			crt := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "acme.example.com",
+				},
+			}
+			inter := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "intermediate",
+				},
+			}
+			return test{
+				o:   o,
+				csr: csr,
+				err: ServerInternalErr(errors.Errorf("error storing certificate: force")),
+				sa: &mockSignAuth{
+					ret1: crt, ret2: inter,
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						return nil, false, errors.New("force")
+					},
+				},
+			}
+		},
+		"fail/ready/store-order-error": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "acme",
+				},
+				DNSNames: []string{"acme.example.com", "step.example.com"},
+			}
+			crt := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "acme.example.com",
+				},
+			}
+			inter := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "intermediate",
+				},
+			}
+			count := 0
+			return test{
+				o:   o,
+				csr: csr,
+				err: ServerInternalErr(errors.Errorf("error storing order: force")),
+				sa: &mockSignAuth{
+					ret1: crt, ret2: inter,
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 1 {
+							return nil, false, errors.New("force")
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+			}
+		},
+		"ok/ready/sign": func(t *testing.T) test {
+			o, err := newO()
+			assert.FatalError(t, err)
+			o.Status = StatusReady
+
+			csr := &x509.CertificateRequest{
+				Subject: pkix.Name{
+					CommonName: "foo",
+				},
+				DNSNames: []string{"acme.example.com", "step.example.com"},
+			}
+			crt := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "acme.example.com",
+				},
+			}
+			inter := &x509.Certificate{
+				Subject: pkix.Name{
+					CommonName: "intermediate",
+				},
+			}
+
+			_o := *o
+			clone := &_o
+			clone.Status = StatusValid
+
+			count := 0
+			return test{
+				o:   o,
+				res: clone,
+				csr: csr,
+				sa: &mockSignAuth{
+					sign: func(csr *x509.CertificateRequest, pops provisioner.Options, signOps ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error) {
+						assert.Equals(t, len(signOps), 4)
+						return crt, inter, nil
+					},
+				},
+				db: &db.MockNoSQLDB{
+					MCmpAndSwap: func(bucket, key, old, newval []byte) ([]byte, bool, error) {
+						if count == 0 {
+							clone.Certificate = string(key)
+						}
+						count++
+						return nil, true, nil
+					},
+				},
+			}
+		},
+	}
+	for name, run := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := run(t)
+			p := tc.prov
+			if p == nil {
+				p = prov
+			}
+			o, err := tc.o.finalize(tc.db, tc.csr, tc.sa, p)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					ae, ok := err.(*Error)
+					assert.True(t, ok)
+					assert.HasPrefix(t, ae.Error(), tc.err.Error())
+					assert.Equals(t, ae.StatusCode(), tc.err.StatusCode())
+					assert.Equals(t, ae.Type, tc.err.Type)
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					expB, err := json.Marshal(tc.res)
+					assert.FatalError(t, err)
+					b, err := json.Marshal(o)
+					assert.FatalError(t, err)
+					assert.Equals(t, expB, b)
+				}
+			}
+		})
+	}
+}

+ 113 - 23
api/api.go

@@ -1,10 +1,17 @@
 package api
 
 import (
+	"context"
+	"crypto/dsa"
+	"crypto/ecdsa"
+	"crypto/rsa"
 	"crypto/tls"
 	"crypto/x509"
+	"encoding/asn1"
+	"encoding/base64"
 	"encoding/json"
 	"encoding/pem"
+	"fmt"
 	"net/http"
 	"strconv"
 	"strings"
@@ -13,22 +20,44 @@ import (
 	"github.com/go-chi/chi"
 	"github.com/pkg/errors"
 	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/logging"
 	"github.com/smallstep/cli/crypto/tlsutil"
 )
 
 // Authority is the interface implemented by a CA authority.
 type Authority interface {
-	Authorize(ott string) ([]interface{}, error)
+	SSHAuthority
+	// context specifies the Authorize[Sign|Revoke|etc.] method.
+	Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error)
+	AuthorizeSign(ott string) ([]provisioner.SignOption, error)
 	GetTLSOptions() *tlsutil.TLSOptions
 	Root(shasum string) (*x509.Certificate, error)
-	Sign(cr *x509.CertificateRequest, signOpts authority.SignOptions, extraOpts ...interface{}) (*x509.Certificate, *x509.Certificate, error)
+	Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
 	Renew(peer *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
-	GetProvisioners(cursor string, limit int) ([]*authority.Provisioner, string, error)
+	LoadProvisionerByCertificate(*x509.Certificate) (provisioner.Interface, error)
+	LoadProvisionerByID(string) (provisioner.Interface, error)
+	GetProvisioners(cursor string, limit int) (provisioner.List, string, error)
+	Revoke(*authority.RevokeOptions) error
 	GetEncryptedKey(kid string) (string, error)
 	GetRoots() (federation []*x509.Certificate, err error)
 	GetFederation() ([]*x509.Certificate, error)
 }
 
+// TimeDuration is an alias of provisioner.TimeDuration
+type TimeDuration = provisioner.TimeDuration
+
+// NewTimeDuration returns a TimeDuration with the defined time.
+func NewTimeDuration(t time.Time) TimeDuration {
+	return provisioner.NewTimeDuration(t)
+}
+
+// ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
+// time.Duration string.
+func ParseTimeDuration(s string) (TimeDuration, error) {
+	return provisioner.ParseTimeDuration(s)
+}
+
 // Certificate wraps a *x509.Certificate and adds the json.Marshaler interface.
 type Certificate struct {
 	*x509.Certificate
@@ -147,18 +176,18 @@ type RootResponse struct {
 type SignRequest struct {
 	CsrPEM    CertificateRequest `json:"csr"`
 	OTT       string             `json:"ott"`
-	NotAfter  time.Time          `json:"notAfter"`
-	NotBefore time.Time          `json:"notBefore"`
+	NotAfter  TimeDuration       `json:"notAfter"`
+	NotBefore TimeDuration       `json:"notBefore"`
 }
 
 // ProvisionersResponse is the response object that returns the list of
 // provisioners.
 type ProvisionersResponse struct {
-	Provisioners []*authority.Provisioner `json:"provisioners"`
-	NextCursor   string                   `json:"nextCursor"`
+	Provisioners provisioner.List `json:"provisioners"`
+	NextCursor   string           `json:"nextCursor"`
 }
 
-// ProvisionerKeyResponse is the response object that returns the encryptoed key
+// ProvisionerKeyResponse is the response object that returns the encrypted key
 // of a provisioner.
 type ProvisionerKeyResponse struct {
 	Key string `json:"key"`
@@ -215,12 +244,15 @@ func (h *caHandler) Route(r Router) {
 	r.MethodFunc("GET", "/root/{sha}", h.Root)
 	r.MethodFunc("POST", "/sign", h.Sign)
 	r.MethodFunc("POST", "/renew", h.Renew)
+	r.MethodFunc("POST", "/revoke", h.Revoke)
 	r.MethodFunc("GET", "/provisioners", h.Provisioners)
 	r.MethodFunc("GET", "/provisioners/{kid}/encrypted-key", h.ProvisionerKey)
 	r.MethodFunc("GET", "/roots", h.Roots)
 	r.MethodFunc("GET", "/federation", h.Federation)
 	// For compatibility with old code:
 	r.MethodFunc("POST", "/re-sign", h.Renew)
+	// SSH CA
+	r.MethodFunc("POST", "/sign-ssh", h.SignSSH)
 }
 
 // Health is an HTTP handler that returns the status of the server.
@@ -252,34 +284,36 @@ func (h *caHandler) Sign(w http.ResponseWriter, r *http.Request) {
 		WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
 		return
 	}
+
+	logOtt(w, body.OTT)
 	if err := body.Validate(); err != nil {
 		WriteError(w, err)
 		return
 	}
 
-	signOpts := authority.SignOptions{
+	opts := provisioner.Options{
 		NotBefore: body.NotBefore,
 		NotAfter:  body.NotAfter,
 	}
 
-	extraOpts, err := h.Authority.Authorize(body.OTT)
+	signOpts, err := h.Authority.AuthorizeSign(body.OTT)
 	if err != nil {
 		WriteError(w, Unauthorized(err))
 		return
 	}
 
-	cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, signOpts, extraOpts...)
+	cert, root, err := h.Authority.Sign(body.CsrPEM.CertificateRequest, opts, signOpts...)
 	if err != nil {
 		WriteError(w, Forbidden(err))
 		return
 	}
 
-	w.WriteHeader(http.StatusCreated)
-	JSON(w, &SignResponse{
+	logCertificate(w, cert)
+	JSONStatus(w, &SignResponse{
 		ServerPEM:  Certificate{cert},
 		CaPEM:      Certificate{root},
 		TLSOptions: h.Authority.GetTLSOptions(),
-	})
+	}, http.StatusCreated)
 }
 
 // Renew uses the information of certificate in the TLS connection to create a
@@ -296,12 +330,12 @@ func (h *caHandler) Renew(w http.ResponseWriter, r *http.Request) {
 		return
 	}
 
-	w.WriteHeader(http.StatusCreated)
-	JSON(w, &SignResponse{
+	logCertificate(w, cert)
+	JSONStatus(w, &SignResponse{
 		ServerPEM:  Certificate{cert},
 		CaPEM:      Certificate{root},
 		TLSOptions: h.Authority.GetTLSOptions(),
-	})
+	}, http.StatusCreated)
 }
 
 // Provisioners returns the list of provisioners configured in the authority.
@@ -347,10 +381,9 @@ func (h *caHandler) Roots(w http.ResponseWriter, r *http.Request) {
 		certs[i] = Certificate{roots[i]}
 	}
 
-	w.WriteHeader(http.StatusCreated)
-	JSON(w, &RootsResponse{
+	JSONStatus(w, &RootsResponse{
 		Certificates: certs,
-	})
+	}, http.StatusCreated)
 }
 
 // Federation returns all the public certificates in the federation.
@@ -366,10 +399,51 @@ func (h *caHandler) Federation(w http.ResponseWriter, r *http.Request) {
 		certs[i] = Certificate{federated[i]}
 	}
 
-	w.WriteHeader(http.StatusCreated)
-	JSON(w, &FederationResponse{
+	JSONStatus(w, &FederationResponse{
 		Certificates: certs,
-	})
+	}, http.StatusCreated)
+}
+
+var oidStepProvisioner = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64, 1}
+
+type stepProvisioner struct {
+	Type         int
+	Name         []byte
+	CredentialID []byte
+}
+
+func logOtt(w http.ResponseWriter, token string) {
+	if rl, ok := w.(logging.ResponseLogger); ok {
+		rl.WithFields(map[string]interface{}{
+			"ott": token,
+		})
+	}
+}
+
+func logCertificate(w http.ResponseWriter, cert *x509.Certificate) {
+	if rl, ok := w.(logging.ResponseLogger); ok {
+		m := map[string]interface{}{
+			"serial":      cert.SerialNumber,
+			"subject":     cert.Subject.CommonName,
+			"issuer":      cert.Issuer.CommonName,
+			"valid-from":  cert.NotBefore.Format(time.RFC3339),
+			"valid-to":    cert.NotAfter.Format(time.RFC3339),
+			"public-key":  fmtPublicKey(cert),
+			"certificate": base64.StdEncoding.EncodeToString(cert.Raw),
+		}
+		for _, ext := range cert.Extensions {
+			if ext.Id.Equal(oidStepProvisioner) {
+				val := &stepProvisioner{}
+				rest, err := asn1.Unmarshal(ext.Value, val)
+				if err != nil || len(rest) > 0 {
+					break
+				}
+				m["provisioner"] = fmt.Sprintf("%s (%s)", val.Name, val.CredentialID)
+				break
+			}
+		}
+		rl.WithFields(m)
+	}
 }
 
 func parseCursor(r *http.Request) (cursor string, limit int, err error) {
@@ -383,3 +457,19 @@ func parseCursor(r *http.Request) (cursor string, limit int, err error) {
 	}
 	return
 }
+
+// TODO: add support for Ed25519 once it's supported
+func fmtPublicKey(cert *x509.Certificate) string {
+	var params string
+	switch pk := cert.PublicKey.(type) {
+	case *ecdsa.PublicKey:
+		params = pk.Curve.Params().Name
+	case *rsa.PublicKey:
+		params = strconv.Itoa(pk.Size() * 8)
+	case *dsa.PublicKey:
+		params = strconv.Itoa(pk.Q.BitLen() * 8)
+	default:
+		params = "unknown"
+	}
+	return fmt.Sprintf("%s %s", cert.PublicKeyAlgorithm, params)
+}

+ 279 - 46
api/api_test.go

@@ -3,12 +3,19 @@ package api
 import (
 	"bytes"
 	"context"
+	"crypto/dsa"
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"crypto/rsa"
 	"crypto/tls"
 	"crypto/x509"
+	"crypto/x509/pkix"
 	"encoding/json"
 	"encoding/pem"
 	"fmt"
 	"io/ioutil"
+	"math/big"
 	"net/http"
 	"net/http/httptest"
 	"reflect"
@@ -17,9 +24,14 @@ import (
 	"time"
 
 	"github.com/go-chi/chi"
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
 	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/logging"
 	"github.com/smallstep/cli/crypto/tlsutil"
 	"github.com/smallstep/cli/jose"
+	"golang.org/x/crypto/ssh"
 )
 
 const (
@@ -98,6 +110,23 @@ Q7vMNPBWrJWu+A++vHY61WGET+h4lY3GFr2I8OE4IiHPQi1D7Y0+fwOmStwuRPM4
 DCbKzWTW8lqVdp9Kyf7XEhhc2R8C5w==
 -----END CERTIFICATE REQUEST-----`
 
+	stepCertPEM = `-----BEGIN CERTIFICATE-----
+MIIChTCCAiugAwIBAgIRAJ3O5T28Rdj2lr/UPjf+GAUwCgYIKoZIzj0EAwIwJDEi
+MCAGA1UEAxMZU21hbGxzdGVwIEludGVybWVkaWF0ZSBDQTAeFw0xOTAyMjAyMDE1
+NDNaFw0xOTAyMjEyMDE1NDNaMHExCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJDQTEW
+MBQGA1UEBxMNU2FuIEZyYW5jaXNjbzEcMBoGA1UEChMTU21hbGxzdGVwIExhYnMg
+SW5jLjEfMB0GA1UEAxMWaW50ZXJuYWwuc21hbGxzdGVwLmNvbTBZMBMGByqGSM49
+AgEGCCqGSM49AwEHA0IABC0aKrTNl+gXFuNkXisqX4/foLO3VMt+Kphngziim+fz
+aJhiS9JU+oFYLTNW6HWGUD8CNzfwrmWlVsAmiJwHKlKjgfAwge0wDgYDVR0PAQH/
+BAQDAgWgMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHQ4EFgQU
+JheKvlZqNv1IcgaC8WOS1Zg0i1QwHwYDVR0jBBgwFoAUu97PaFQPfuyKOeew7Hg4
+5WFIAVMwIQYDVR0RBBowGIIWaW50ZXJuYWwuc21hbGxzdGVwLmNvbTBZBgwrBgEE
+AYKkZMYoQAEESTBHAgEBBBVtYXJpYW5vQHNtYWxsc3RlcC5jb20EK2pPMzdkdERi
+a3UtUW5hYnM1VlIwWXc2WUZGdjl3ZUExOGRwM2h0dmRFanMwCgYIKoZIzj0EAwID
+SAAwRQIhAIrn17fP5CBrGtKuhyPiq6eSwryBCf8ki+k17u5a+E/LAiB24Y2E0Put
+nIHOI54lAqDeF7A0y73fPRVCiJEWmuxz0g==
+-----END CERTIFICATE-----`
+
 	pubKey = `{
 	"use": "sig",
 	"kty": "EC",
@@ -124,7 +153,7 @@ func parseCertificate(data string) *x509.Certificate {
 }
 
 func parseCertificateRequest(data string) *x509.CertificateRequest {
-	block, _ := pem.Decode([]byte(csrPEM))
+	block, _ := pem.Decode([]byte(data))
 	if block == nil {
 		panic("failed to parse certificate request PEM")
 	}
@@ -359,48 +388,142 @@ func TestSignRequest_Validate(t *testing.T) {
 		NotAfter  time.Time
 	}
 	tests := []struct {
-		name    string
-		fields  fields
-		wantErr bool
+		name   string
+		fields fields
+		err    error
 	}{
-		{"missing csr", fields{CertificateRequest{}, "foobarzar", time.Time{}, time.Time{}}, true},
-		{"invalid csr", fields{CertificateRequest{bad}, "foobarzar", time.Time{}, time.Time{}}, true},
-		{"missing ott", fields{CertificateRequest{csr}, "", time.Time{}, time.Time{}}, true},
+		{"missing csr", fields{CertificateRequest{}, "foobarzar", time.Time{}, time.Time{}}, errors.New("missing csr")},
+		{"invalid csr", fields{CertificateRequest{bad}, "foobarzar", time.Time{}, time.Time{}}, errors.New("invalid csr")},
+		{"missing ott", fields{CertificateRequest{csr}, "", time.Time{}, time.Time{}}, errors.New("missing ott")},
 	}
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			s := &SignRequest{
 				CsrPEM:    tt.fields.CsrPEM,
 				OTT:       tt.fields.OTT,
-				NotAfter:  tt.fields.NotAfter,
-				NotBefore: tt.fields.NotBefore,
+				NotAfter:  NewTimeDuration(tt.fields.NotAfter),
+				NotBefore: NewTimeDuration(tt.fields.NotBefore),
 			}
-			if err := s.Validate(); (err != nil) != tt.wantErr {
-				t.Errorf("SignRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
+			if err := s.Validate(); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				assert.Nil(t, tt.err)
 			}
 		})
 	}
 }
 
+type mockProvisioner struct {
+	ret1, ret2, ret3 interface{}
+	err              error
+	getID            func() string
+	getTokenID       func(string) (string, error)
+	getName          func() string
+	getType          func() provisioner.Type
+	getEncryptedKey  func() (string, string, bool)
+	init             func(provisioner.Config) error
+	authorizeRevoke  func(ott string) error
+	authorizeSign    func(ctx context.Context, ott string) ([]provisioner.SignOption, error)
+	authorizeRenewal func(*x509.Certificate) error
+}
+
+func (m *mockProvisioner) GetID() string {
+	if m.getID != nil {
+		return m.getID()
+	}
+	return m.ret1.(string)
+}
+
+func (m *mockProvisioner) GetTokenID(token string) (string, error) {
+	if m.getTokenID != nil {
+		return m.getTokenID(token)
+	}
+	if m.ret1 == nil {
+		return "", m.err
+	}
+	return m.ret1.(string), m.err
+}
+
+func (m *mockProvisioner) GetName() string {
+	if m.getName != nil {
+		return m.getName()
+	}
+	return m.ret1.(string)
+}
+
+func (m *mockProvisioner) GetType() provisioner.Type {
+	if m.getType != nil {
+		return m.getType()
+	}
+	return m.ret1.(provisioner.Type)
+}
+
+func (m *mockProvisioner) GetEncryptedKey() (string, string, bool) {
+	if m.getEncryptedKey != nil {
+		return m.getEncryptedKey()
+	}
+	return m.ret1.(string), m.ret2.(string), m.ret3.(bool)
+}
+
+func (m *mockProvisioner) Init(c provisioner.Config) error {
+	if m.init != nil {
+		return m.init(c)
+	}
+	return m.err
+}
+
+func (m *mockProvisioner) AuthorizeRevoke(ott string) error {
+	if m.authorizeRevoke != nil {
+		return m.authorizeRevoke(ott)
+	}
+	return m.err
+}
+
+func (m *mockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
+	if m.authorizeSign != nil {
+		return m.authorizeSign(ctx, ott)
+	}
+	return m.ret1.([]provisioner.SignOption), m.err
+}
+
+func (m *mockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
+	if m.authorizeRenewal != nil {
+		return m.authorizeRenewal(c)
+	}
+	return m.err
+}
+
 type mockAuthority struct {
-	ret1, ret2      interface{}
-	err             error
-	authorize       func(ott string) ([]interface{}, error)
-	getTLSOptions   func() *tlsutil.TLSOptions
-	root            func(shasum string) (*x509.Certificate, error)
-	sign            func(cr *x509.CertificateRequest, signOpts authority.SignOptions, extraOpts ...interface{}) (*x509.Certificate, *x509.Certificate, error)
-	renew           func(cert *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
-	getProvisioners func(nextCursor string, limit int) ([]*authority.Provisioner, string, error)
-	getEncryptedKey func(kid string) (string, error)
-	getRoots        func() ([]*x509.Certificate, error)
-	getFederation   func() ([]*x509.Certificate, error)
+	ret1, ret2                   interface{}
+	err                          error
+	authorizeSign                func(ott string) ([]provisioner.SignOption, error)
+	getTLSOptions                func() *tlsutil.TLSOptions
+	root                         func(shasum string) (*x509.Certificate, error)
+	sign                         func(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error)
+	signSSH                      func(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
+	signSSHAddUser               func(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
+	renew                        func(cert *x509.Certificate) (*x509.Certificate, *x509.Certificate, error)
+	loadProvisionerByCertificate func(cert *x509.Certificate) (provisioner.Interface, error)
+	loadProvisionerByID          func(provID string) (provisioner.Interface, error)
+	getProvisioners              func(nextCursor string, limit int) (provisioner.List, string, error)
+	revoke                       func(*authority.RevokeOptions) error
+	getEncryptedKey              func(kid string) (string, error)
+	getRoots                     func() ([]*x509.Certificate, error)
+	getFederation                func() ([]*x509.Certificate, error)
 }
 
-func (m *mockAuthority) Authorize(ott string) ([]interface{}, error) {
-	if m.authorize != nil {
-		return m.authorize(ott)
+// TODO: remove once Authorize is deprecated.
+func (m *mockAuthority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
+	return m.AuthorizeSign(ott)
+}
+
+func (m *mockAuthority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
+	if m.authorizeSign != nil {
+		return m.authorizeSign(ott)
 	}
-	return m.ret1.([]interface{}), m.err
+	return m.ret1.([]provisioner.SignOption), m.err
 }
 
 func (m *mockAuthority) GetTLSOptions() *tlsutil.TLSOptions {
@@ -417,13 +540,27 @@ func (m *mockAuthority) Root(shasum string) (*x509.Certificate, error) {
 	return m.ret1.(*x509.Certificate), m.err
 }
 
-func (m *mockAuthority) Sign(cr *x509.CertificateRequest, signOpts authority.SignOptions, extraOpts ...interface{}) (*x509.Certificate, *x509.Certificate, error) {
+func (m *mockAuthority) Sign(cr *x509.CertificateRequest, opts provisioner.Options, signOpts ...provisioner.SignOption) (*x509.Certificate, *x509.Certificate, error) {
 	if m.sign != nil {
-		return m.sign(cr, signOpts, extraOpts...)
+		return m.sign(cr, opts, signOpts...)
 	}
 	return m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate), m.err
 }
 
+func (m *mockAuthority) SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
+	if m.signSSH != nil {
+		return m.signSSH(key, opts, signOpts...)
+	}
+	return m.ret1.(*ssh.Certificate), m.err
+}
+
+func (m *mockAuthority) SignSSHAddUser(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
+	if m.signSSHAddUser != nil {
+		return m.signSSHAddUser(key, cert)
+	}
+	return m.ret1.(*ssh.Certificate), m.err
+}
+
 func (m *mockAuthority) Renew(cert *x509.Certificate) (*x509.Certificate, *x509.Certificate, error) {
 	if m.renew != nil {
 		return m.renew(cert)
@@ -431,11 +568,32 @@ func (m *mockAuthority) Renew(cert *x509.Certificate) (*x509.Certificate, *x509.
 	return m.ret1.(*x509.Certificate), m.ret2.(*x509.Certificate), m.err
 }
 
-func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) ([]*authority.Provisioner, string, error) {
+func (m *mockAuthority) GetProvisioners(nextCursor string, limit int) (provisioner.List, string, error) {
 	if m.getProvisioners != nil {
 		return m.getProvisioners(nextCursor, limit)
 	}
-	return m.ret1.([]*authority.Provisioner), m.ret2.(string), m.err
+	return m.ret1.(provisioner.List), m.ret2.(string), m.err
+}
+
+func (m *mockAuthority) LoadProvisionerByCertificate(cert *x509.Certificate) (provisioner.Interface, error) {
+	if m.loadProvisionerByCertificate != nil {
+		return m.loadProvisionerByCertificate(cert)
+	}
+	return m.ret1.(provisioner.Interface), m.err
+}
+
+func (m *mockAuthority) LoadProvisionerByID(provID string) (provisioner.Interface, error) {
+	if m.loadProvisionerByID != nil {
+		return m.loadProvisionerByID(provID)
+	}
+	return m.ret1.(provisioner.Interface), m.err
+}
+
+func (m *mockAuthority) Revoke(opts *authority.RevokeOptions) error {
+	if m.revoke != nil {
+		return m.revoke(opts)
+	}
+	return m.err
 }
 
 func (m *mockAuthority) GetEncryptedKey(kid string) (string, error) {
@@ -566,30 +724,33 @@ func Test_caHandler_Sign(t *testing.T) {
 		t.Fatal(err)
 	}
 
+	expected1 := []byte(`{"crt":"` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"}`)
+	expected2 := []byte(`{"crt":"` + strings.Replace(stepCertPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"}`)
+
 	tests := []struct {
 		name         string
 		input        string
-		certAttrOpts []interface{}
+		certAttrOpts []provisioner.SignOption
 		autherr      error
 		cert         *x509.Certificate
 		root         *x509.Certificate
 		signErr      error
 		statusCode   int
+		expected     []byte
 	}{
-		{"ok", string(valid), nil, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated},
-		{"json read error", "{", nil, nil, nil, nil, nil, http.StatusBadRequest},
-		{"validate error", string(invalid), nil, nil, nil, nil, nil, http.StatusBadRequest},
-		{"authorize error", string(valid), nil, fmt.Errorf("an error"), nil, nil, nil, http.StatusUnauthorized},
-		{"sign error", string(valid), nil, nil, nil, nil, fmt.Errorf("an error"), http.StatusForbidden},
+		{"ok", string(valid), nil, nil, parseCertificate(certPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected1},
+		{"ok with Provisioner", string(valid), nil, nil, parseCertificate(stepCertPEM), parseCertificate(rootPEM), nil, http.StatusCreated, expected2},
+		{"json read error", "{", nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
+		{"validate error", string(invalid), nil, nil, nil, nil, nil, http.StatusBadRequest, nil},
+		{"authorize error", string(valid), nil, fmt.Errorf("an error"), nil, nil, nil, http.StatusUnauthorized, nil},
+		{"sign error", string(valid), nil, nil, nil, nil, fmt.Errorf("an error"), http.StatusForbidden, nil},
 	}
 
-	expected := []byte(`{"crt":"` + strings.Replace(certPEM, "\n", `\n`, -1) + `\n","ca":"` + strings.Replace(rootPEM, "\n", `\n`, -1) + `\n"}`)
-
 	for _, tt := range tests {
 		t.Run(tt.name, func(t *testing.T) {
 			h := New(&mockAuthority{
 				ret1: tt.cert, ret2: tt.root, err: tt.signErr,
-				authorize: func(ott string) ([]interface{}, error) {
+				authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
 					return tt.certAttrOpts, tt.autherr
 				},
 				getTLSOptions: func() *tlsutil.TLSOptions {
@@ -598,7 +759,7 @@ func Test_caHandler_Sign(t *testing.T) {
 			}).(*caHandler)
 			req := httptest.NewRequest("POST", "http://example.com/sign", strings.NewReader(tt.input))
 			w := httptest.NewRecorder()
-			h.Sign(w, req)
+			h.Sign(logging.NewResponseLogger(w), req)
 			res := w.Result()
 
 			if res.StatusCode != tt.statusCode {
@@ -611,8 +772,8 @@ func Test_caHandler_Sign(t *testing.T) {
 				t.Errorf("caHandler.Root unexpected error = %v", err)
 			}
 			if tt.statusCode < http.StatusBadRequest {
-				if !bytes.Equal(bytes.TrimSpace(body), expected) {
-					t.Errorf("caHandler.Root Body = %s, wants %s", body, expected)
+				if !bytes.Equal(bytes.TrimSpace(body), tt.expected) {
+					t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.expected)
 				}
 			}
 		})
@@ -650,7 +811,7 @@ func Test_caHandler_Renew(t *testing.T) {
 			req := httptest.NewRequest("POST", "http://example.com/renew", nil)
 			req.TLS = tt.tls
 			w := httptest.NewRecorder()
-			h.Renew(w, req)
+			h.Renew(logging.NewResponseLogger(w), req)
 			res := w.Result()
 
 			if res.StatusCode != tt.statusCode {
@@ -695,14 +856,14 @@ func Test_caHandler_Provisioners(t *testing.T) {
 		t.Fatal(err)
 	}
 
-	p := []*authority.Provisioner{
-		{
+	p := provisioner.List{
+		&provisioner.JWK{
 			Type:         "JWK",
 			Name:         "max",
 			EncryptedKey: "abc",
 			Key:          &key,
 		},
-		{
+		&provisioner.JWK{
 			Type:         "JWK",
 			Name:         "mariano",
 			EncryptedKey: "def",
@@ -920,3 +1081,75 @@ func Test_caHandler_Federation(t *testing.T) {
 		})
 	}
 }
+
+func Test_fmtPublicKey(t *testing.T) {
+	p256, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		t.Fatal(err)
+	}
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	if err != nil {
+		t.Fatal(err)
+	}
+	var dsa2048 dsa.PrivateKey
+	if err := dsa.GenerateParameters(&dsa2048.Parameters, rand.Reader, dsa.L2048N256); err != nil {
+		t.Fatal(err)
+	}
+	if err := dsa.GenerateKey(&dsa2048, rand.Reader); err != nil {
+		t.Fatal(err)
+	}
+
+	type args struct {
+		pub, priv interface{}
+		cert      *x509.Certificate
+	}
+	tests := []struct {
+		name string
+		args args
+		want string
+	}{
+		{"p256", args{p256.Public(), p256, nil}, "ECDSA P-256"},
+		{"rsa1024", args{rsa1024.Public(), rsa1024, nil}, "RSA 1024"},
+		{"dsa2048", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.DSA, PublicKey: &dsa2048.PublicKey}}, "DSA 2048"},
+		{"unknown", args{cert: &x509.Certificate{PublicKeyAlgorithm: x509.ECDSA, PublicKey: []byte("12345678")}}, "ECDSA unknown"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			var cert *x509.Certificate
+			if tt.args.cert != nil {
+				cert = tt.args.cert
+			} else {
+				cert = mustCertificate(t, tt.args.pub, tt.args.priv)
+			}
+			if got := fmtPublicKey(cert); got != tt.want {
+				t.Errorf("fmtPublicKey() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func mustCertificate(t *testing.T, pub, priv interface{}) *x509.Certificate {
+	template := x509.Certificate{
+		SerialNumber: big.NewInt(1),
+		Subject: pkix.Name{
+			Organization: []string{"Acme Co"},
+		},
+		NotBefore: time.Now(),
+		NotAfter:  time.Now().Add(24 * time.Hour),
+
+		KeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
+		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+		BasicConstraintsValid: true,
+	}
+
+	der, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, priv)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	cert, err := x509.ParseCertificate(der)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return cert
+}

+ 13 - 1
api/errors.go

@@ -7,6 +7,7 @@ import (
 	"os"
 
 	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/acme"
 	"github.com/smallstep/certificates/logging"
 )
 
@@ -82,6 +83,11 @@ func InternalServerError(err error) error {
 	return NewError(http.StatusInternalServerError, err)
 }
 
+// NotImplemented returns a 500 error with the given error.
+func NotImplemented(err error) error {
+	return NewError(http.StatusNotImplemented, err)
+}
+
 // BadRequest returns an 400 error with the given error.
 func BadRequest(err error) error {
 	return NewError(http.StatusBadRequest, err)
@@ -104,7 +110,13 @@ func NotFound(err error) error {
 
 // WriteError writes to w a JSON representation of the given error.
 func WriteError(w http.ResponseWriter, err error) {
-	w.Header().Set("Content-Type", "application/json")
+	switch k := err.(type) {
+	case *acme.Error:
+		w.Header().Set("Content-Type", "application/problem+json")
+		err = k.ToACME()
+	default:
+		w.Header().Set("Content-Type", "application/json")
+	}
 	cause := errors.Cause(err)
 	if sc, ok := err.(StatusCoder); ok {
 		w.WriteHeader(sc.StatusCode())

+ 103 - 0
api/revoke.go

@@ -0,0 +1,103 @@
+package api
+
+import (
+	"net/http"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/logging"
+	"golang.org/x/crypto/ocsp"
+)
+
+// RevokeResponse is the response object that returns the health of the server.
+type RevokeResponse struct {
+	Status string `json:"status"`
+}
+
+// RevokeRequest is the request body for a revocation request.
+type RevokeRequest struct {
+	Serial     string `json:"serial"`
+	OTT        string `json:"ott"`
+	ReasonCode int    `json:"reasonCode"`
+	Reason     string `json:"reason"`
+	Passive    bool   `json:"passive"`
+}
+
+// Validate checks the fields of the RevokeRequest and returns nil if they are ok
+// or an error if something is wrong.
+func (r *RevokeRequest) Validate() (err error) {
+	if r.Serial == "" {
+		return BadRequest(errors.New("missing serial"))
+	}
+	if r.ReasonCode < ocsp.Unspecified || r.ReasonCode > ocsp.AACompromise {
+		return BadRequest(errors.New("reasonCode out of bounds"))
+	}
+	if !r.Passive {
+		return NotImplemented(errors.New("non-passive revocation not implemented"))
+	}
+
+	return
+}
+
+// Revoke supports handful of different methods that revoke a Certificate.
+//
+// NOTE: currently only Passive revocation is supported.
+//
+// TODO: Add CRL and OCSP support.
+func (h *caHandler) Revoke(w http.ResponseWriter, r *http.Request) {
+	var body RevokeRequest
+	if err := ReadJSON(r.Body, &body); err != nil {
+		WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
+		return
+	}
+
+	if err := body.Validate(); err != nil {
+		WriteError(w, err)
+		return
+	}
+
+	opts := &authority.RevokeOptions{
+		Serial:      body.Serial,
+		Reason:      body.Reason,
+		ReasonCode:  body.ReasonCode,
+		PassiveOnly: body.Passive,
+	}
+
+	// A token indicates that we are using the api via a provisioner token,
+	// otherwise it is assumed that the certificate is revoking itself over mTLS.
+	if len(body.OTT) > 0 {
+		logOtt(w, body.OTT)
+		opts.OTT = body.OTT
+	} else {
+		// If no token is present, then the request must be made over mTLS and
+		// the client certificate Serial Number must match the serial number
+		// being revoked.
+		if r.TLS == nil || len(r.TLS.PeerCertificates) == 0 {
+			WriteError(w, BadRequest(errors.New("missing ott or peer certificate")))
+			return
+		}
+		opts.Crt = r.TLS.PeerCertificates[0]
+		logCertificate(w, opts.Crt)
+		opts.MTLS = true
+	}
+
+	if err := h.Authority.Revoke(opts); err != nil {
+		WriteError(w, Forbidden(err))
+		return
+	}
+
+	logRevoke(w, opts)
+	JSON(w, &RevokeResponse{Status: "ok"})
+}
+
+func logRevoke(w http.ResponseWriter, ri *authority.RevokeOptions) {
+	if rl, ok := w.(logging.ResponseLogger); ok {
+		rl.WithFields(map[string]interface{}{
+			"serial":      ri.Serial,
+			"reasonCode":  ri.ReasonCode,
+			"reason":      ri.Reason,
+			"passiveOnly": ri.PassiveOnly,
+			"mTLS":        ri.MTLS,
+		})
+	}
+}

+ 233 - 0
api/revoke_test.go

@@ -0,0 +1,233 @@
+package api
+
+import (
+	"bytes"
+	"crypto/tls"
+	"crypto/x509"
+	"encoding/json"
+	"io/ioutil"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/logging"
+)
+
+func TestRevokeRequestValidate(t *testing.T) {
+	type test struct {
+		rr  *RevokeRequest
+		err *Error
+	}
+	tests := map[string]test{
+		"error/missing serial": {
+			rr:  &RevokeRequest{},
+			err: &Error{Err: errors.New("missing serial"), Status: http.StatusBadRequest},
+		},
+		"error/bad reasonCode": {
+			rr: &RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 15,
+				Passive:    true,
+			},
+			err: &Error{Err: errors.New("reasonCode out of bounds"), Status: http.StatusBadRequest},
+		},
+		"error/non-passive not implemented": {
+			rr: &RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 8,
+				Passive:    false,
+			},
+			err: &Error{Err: errors.New("non-passive revocation not implemented"), Status: http.StatusNotImplemented},
+		},
+		"ok": {
+			rr: &RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 9,
+				Passive:    true,
+			},
+		},
+	}
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			if err := tc.rr.Validate(); err != nil {
+				switch v := err.(type) {
+				case *Error:
+					assert.HasPrefix(t, v.Error(), tc.err.Error())
+					assert.Equals(t, v.StatusCode(), tc.err.Status)
+				default:
+					t.Errorf("unexpected error type: %T", v)
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func Test_caHandler_Revoke(t *testing.T) {
+	type test struct {
+		input      string
+		auth       Authority
+		tls        *tls.ConnectionState
+		statusCode int
+		expected   []byte
+	}
+	tests := map[string]func(*testing.T) test{
+		"400/json read error": func(t *testing.T) test {
+			return test{
+				input:      "{",
+				statusCode: http.StatusBadRequest,
+			}
+		},
+		"400/invalid request body": func(t *testing.T) test {
+			input, err := json.Marshal(RevokeRequest{})
+			assert.FatalError(t, err)
+			return test{
+				input:      string(input),
+				statusCode: http.StatusBadRequest,
+			}
+		},
+		"200/ott": func(t *testing.T) test {
+			input, err := json.Marshal(RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 4,
+				Reason:     "foo",
+				OTT:        "valid",
+				Passive:    true,
+			})
+			assert.FatalError(t, err)
+			return test{
+				input:      string(input),
+				statusCode: http.StatusOK,
+				auth: &mockAuthority{
+					revoke: func(opts *authority.RevokeOptions) error {
+						assert.True(t, opts.PassiveOnly)
+						assert.False(t, opts.MTLS)
+						assert.Equals(t, opts.Serial, "sn")
+						assert.Equals(t, opts.ReasonCode, 4)
+						assert.Equals(t, opts.Reason, "foo")
+						return nil
+					},
+				},
+				expected: []byte(`{"status":"ok"}`),
+			}
+		},
+		"400/no OTT and no peer certificate": func(t *testing.T) test {
+			input, err := json.Marshal(RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 4,
+				Passive:    true,
+			})
+			assert.FatalError(t, err)
+			return test{
+				input:      string(input),
+				statusCode: http.StatusBadRequest,
+			}
+		},
+		"200/no ott": func(t *testing.T) test {
+			cs := &tls.ConnectionState{
+				PeerCertificates: []*x509.Certificate{parseCertificate(certPEM)},
+			}
+			input, err := json.Marshal(RevokeRequest{
+				Serial:     "1404354960355712309",
+				ReasonCode: 4,
+				Reason:     "foo",
+				Passive:    true,
+			})
+			assert.FatalError(t, err)
+
+			return test{
+				input:      string(input),
+				statusCode: http.StatusOK,
+				tls:        cs,
+				auth: &mockAuthority{
+					revoke: func(ri *authority.RevokeOptions) error {
+						assert.True(t, ri.PassiveOnly)
+						assert.True(t, ri.MTLS)
+						assert.Equals(t, ri.Serial, "1404354960355712309")
+						assert.Equals(t, ri.ReasonCode, 4)
+						assert.Equals(t, ri.Reason, "foo")
+						return nil
+					},
+					loadProvisionerByCertificate: func(crt *x509.Certificate) (provisioner.Interface, error) {
+						return &mockProvisioner{
+							getID: func() string {
+								return "mock-provisioner-id"
+							},
+						}, err
+					},
+				},
+				expected: []byte(`{"status":"ok"}`),
+			}
+		},
+		"500/ott authority.Revoke": func(t *testing.T) test {
+			input, err := json.Marshal(RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 4,
+				Reason:     "foo",
+				OTT:        "valid",
+				Passive:    true,
+			})
+			assert.FatalError(t, err)
+			return test{
+				input:      string(input),
+				statusCode: http.StatusInternalServerError,
+				auth: &mockAuthority{
+					revoke: func(opts *authority.RevokeOptions) error {
+						return InternalServerError(errors.New("force"))
+					},
+				},
+			}
+		},
+		"403/ott authority.Revoke": func(t *testing.T) test {
+			input, err := json.Marshal(RevokeRequest{
+				Serial:     "sn",
+				ReasonCode: 4,
+				Reason:     "foo",
+				OTT:        "valid",
+				Passive:    true,
+			})
+			assert.FatalError(t, err)
+			return test{
+				input:      string(input),
+				statusCode: http.StatusForbidden,
+				auth: &mockAuthority{
+					revoke: func(opts *authority.RevokeOptions) error {
+						return errors.New("force")
+					},
+				},
+			}
+		},
+	}
+
+	for name, _tc := range tests {
+		tc := _tc(t)
+		t.Run(name, func(t *testing.T) {
+			h := New(tc.auth).(*caHandler)
+			req := httptest.NewRequest("POST", "http://example.com/revoke", strings.NewReader(tc.input))
+			if tc.tls != nil {
+				req.TLS = tc.tls
+			}
+			w := httptest.NewRecorder()
+			h.Revoke(logging.NewResponseLogger(w), req)
+			res := w.Result()
+
+			assert.Equals(t, tc.statusCode, res.StatusCode)
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			assert.FatalError(t, err)
+
+			if tc.statusCode < http.StatusBadRequest {
+				if !bytes.Equal(bytes.TrimSpace(body), tc.expected) {
+					t.Errorf("caHandler.Root Body = %s, wants %s", body, tc.expected)
+				}
+			}
+		})
+	}
+}

+ 159 - 0
api/ssh.go

@@ -0,0 +1,159 @@
+package api
+
+import (
+	"context"
+	"encoding/base64"
+	"encoding/json"
+	"net/http"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"golang.org/x/crypto/ssh"
+)
+
+// SSHAuthority is the interface implemented by a SSH CA authority.
+type SSHAuthority interface {
+	SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error)
+	SignSSHAddUser(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error)
+}
+
+// SignSSHRequest is the request body of an SSH certificate request.
+type SignSSHRequest struct {
+	PublicKey        []byte       `json:"publicKey"` //base64 encoded
+	OTT              string       `json:"ott"`
+	CertType         string       `json:"certType,omitempty"`
+	Principals       []string     `json:"principals,omitempty"`
+	ValidAfter       TimeDuration `json:"validAfter,omitempty"`
+	ValidBefore      TimeDuration `json:"validBefore,omitempty"`
+	AddUserPublicKey []byte       `json:"addUserPublicKey,omitempty"`
+}
+
+// SignSSHResponse is the response object that returns the SSH certificate.
+type SignSSHResponse struct {
+	Certificate        SSHCertificate  `json:"crt"`
+	AddUserCertificate *SSHCertificate `json:"addUserCrt,omitempty"`
+}
+
+// SSHCertificate represents the response SSH certificate.
+type SSHCertificate struct {
+	*ssh.Certificate `json:"omitempty"`
+}
+
+// MarshalJSON implements the json.Marshaler interface. Returns a quoted,
+// base64 encoded, openssh wire format version of the certificate.
+func (c SSHCertificate) MarshalJSON() ([]byte, error) {
+	if c.Certificate == nil {
+		return []byte("null"), nil
+	}
+	s := base64.StdEncoding.EncodeToString(c.Certificate.Marshal())
+	return []byte(`"` + s + `"`), nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface. The certificate is
+// expected to be a quoted, base64 encoded, openssh wire formatted block of bytes.
+func (c *SSHCertificate) UnmarshalJSON(data []byte) error {
+	var s string
+	if err := json.Unmarshal(data, &s); err != nil {
+		return errors.Wrap(err, "error decoding certificate")
+	}
+	if s == "" {
+		c.Certificate = nil
+		return nil
+	}
+	certData, err := base64.StdEncoding.DecodeString(s)
+	if err != nil {
+		return errors.Wrap(err, "error decoding ssh certificate")
+	}
+	pub, err := ssh.ParsePublicKey(certData)
+	if err != nil {
+		return errors.Wrap(err, "error parsing ssh certificate")
+	}
+	cert, ok := pub.(*ssh.Certificate)
+	if !ok {
+		return errors.Errorf("error decoding ssh certificate: %T is not an *ssh.Certificate", pub)
+	}
+	c.Certificate = cert
+	return nil
+}
+
+// Validate validates the SignSSHRequest.
+func (s *SignSSHRequest) Validate() error {
+	switch {
+	case s.CertType != "" && s.CertType != provisioner.SSHUserCert && s.CertType != provisioner.SSHHostCert:
+		return errors.Errorf("unknown certType %s", s.CertType)
+	case len(s.PublicKey) == 0:
+		return errors.New("missing or empty publicKey")
+	case len(s.OTT) == 0:
+		return errors.New("missing or empty ott")
+	default:
+		return nil
+	}
+}
+
+// SignSSH is an HTTP handler that reads an SignSSHRequest with a one-time-token
+// (ott) from the body and creates a new SSH certificate with the information in
+// the request.
+func (h *caHandler) SignSSH(w http.ResponseWriter, r *http.Request) {
+	var body SignSSHRequest
+	if err := ReadJSON(r.Body, &body); err != nil {
+		WriteError(w, BadRequest(errors.Wrap(err, "error reading request body")))
+		return
+	}
+
+	logOtt(w, body.OTT)
+	if err := body.Validate(); err != nil {
+		WriteError(w, BadRequest(err))
+		return
+	}
+
+	publicKey, err := ssh.ParsePublicKey(body.PublicKey)
+	if err != nil {
+		WriteError(w, BadRequest(errors.Wrap(err, "error parsing publicKey")))
+		return
+	}
+
+	var addUserPublicKey ssh.PublicKey
+	if body.AddUserPublicKey != nil {
+		addUserPublicKey, err = ssh.ParsePublicKey(body.AddUserPublicKey)
+		if err != nil {
+			WriteError(w, BadRequest(errors.Wrap(err, "error parsing addUserPublicKey")))
+			return
+		}
+	}
+
+	opts := provisioner.SSHOptions{
+		CertType:    body.CertType,
+		Principals:  body.Principals,
+		ValidBefore: body.ValidBefore,
+		ValidAfter:  body.ValidAfter,
+	}
+
+	ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignSSHMethod)
+	signOpts, err := h.Authority.Authorize(ctx, body.OTT)
+	if err != nil {
+		WriteError(w, Unauthorized(err))
+		return
+	}
+
+	cert, err := h.Authority.SignSSH(publicKey, opts, signOpts...)
+	if err != nil {
+		WriteError(w, Forbidden(err))
+		return
+	}
+
+	var addUserCertificate *SSHCertificate
+	if addUserPublicKey != nil && cert.CertType == ssh.UserCert && len(cert.ValidPrincipals) == 1 {
+		addUserCert, err := h.Authority.SignSSHAddUser(addUserPublicKey, cert)
+		if err != nil {
+			WriteError(w, Forbidden(err))
+			return
+		}
+		addUserCertificate = &SSHCertificate{addUserCert}
+	}
+
+	w.WriteHeader(http.StatusCreated)
+	JSON(w, &SignSSHResponse{
+		Certificate:        SSHCertificate{cert},
+		AddUserCertificate: addUserCertificate,
+	})
+}

+ 320 - 0
api/ssh_test.go

@@ -0,0 +1,320 @@
+package api
+
+import (
+	"bytes"
+	"crypto/ecdsa"
+	"crypto/elliptic"
+	"crypto/rand"
+	"encoding/base64"
+	"encoding/json"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"net/http/httptest"
+	"reflect"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/logging"
+	"golang.org/x/crypto/ssh"
+)
+
+var (
+	sshSignerKey = mustKey()
+	sshUserKey   = mustKey()
+	sshHostKey   = mustKey()
+)
+
+func mustKey() *ecdsa.PrivateKey {
+	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+	if err != nil {
+		panic(err)
+	}
+	return priv
+}
+
+func signSSHCertificate(cert *ssh.Certificate) error {
+	signerKey, err := ssh.NewPublicKey(sshSignerKey.Public())
+	if err != nil {
+		return err
+	}
+	signer, err := ssh.NewSignerFromSigner(sshSignerKey)
+	if err != nil {
+		return err
+	}
+	cert.SignatureKey = signerKey
+	data := cert.Marshal()
+	data = data[:len(data)-4]
+	sig, err := signer.Sign(rand.Reader, data)
+	if err != nil {
+		return err
+	}
+	cert.Signature = sig
+	return nil
+}
+
+func getSignedUserCertificate() (*ssh.Certificate, error) {
+	key, err := ssh.NewPublicKey(sshUserKey.Public())
+	if err != nil {
+		return nil, err
+	}
+	t := time.Now()
+	cert := &ssh.Certificate{
+		Nonce:           []byte("1234567890"),
+		Key:             key,
+		Serial:          1234567890,
+		CertType:        ssh.UserCert,
+		KeyId:           "user@localhost",
+		ValidPrincipals: []string{"user"},
+		ValidAfter:      uint64(t.Unix()),
+		ValidBefore:     uint64(t.Add(time.Hour).Unix()),
+		Permissions: ssh.Permissions{
+			CriticalOptions: map[string]string{},
+			Extensions: map[string]string{
+				"permit-X11-forwarding":   "",
+				"permit-agent-forwarding": "",
+				"permit-port-forwarding":  "",
+				"permit-pty":              "",
+				"permit-user-rc":          "",
+			},
+		},
+		Reserved: []byte{},
+	}
+	if err := signSSHCertificate(cert); err != nil {
+		return nil, err
+	}
+	return cert, nil
+}
+
+func getSignedHostCertificate() (*ssh.Certificate, error) {
+	key, err := ssh.NewPublicKey(sshHostKey.Public())
+	if err != nil {
+		return nil, err
+	}
+	t := time.Now()
+	cert := &ssh.Certificate{
+		Nonce:           []byte("1234567890"),
+		Key:             key,
+		Serial:          1234567890,
+		CertType:        ssh.UserCert,
+		KeyId:           "internal.smallstep.com",
+		ValidPrincipals: []string{"internal.smallstep.com"},
+		ValidAfter:      uint64(t.Unix()),
+		ValidBefore:     uint64(t.Add(time.Hour).Unix()),
+		Permissions: ssh.Permissions{
+			CriticalOptions: map[string]string{},
+			Extensions:      map[string]string{},
+		},
+		Reserved: []byte{},
+	}
+	if err := signSSHCertificate(cert); err != nil {
+		return nil, err
+	}
+	return cert, nil
+}
+
+func TestSSHCertificate_MarshalJSON(t *testing.T) {
+	user, err := getSignedUserCertificate()
+	assert.FatalError(t, err)
+	host, err := getSignedHostCertificate()
+	assert.FatalError(t, err)
+	userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
+	hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
+
+	type fields struct {
+		Certificate *ssh.Certificate
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		want    []byte
+		wantErr bool
+	}{
+		{"nil", fields{Certificate: nil}, []byte("null"), false},
+		{"user", fields{Certificate: user}, []byte(`"` + userB64 + `"`), false},
+		{"user", fields{Certificate: host}, []byte(`"` + hostB64 + `"`), false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := SSHCertificate{
+				Certificate: tt.fields.Certificate,
+			}
+			got, err := c.MarshalJSON()
+			if (err != nil) != tt.wantErr {
+				t.Errorf("SSHCertificate.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("SSHCertificate.MarshalJSON() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestSSHCertificate_UnmarshalJSON(t *testing.T) {
+	user, err := getSignedUserCertificate()
+	assert.FatalError(t, err)
+	host, err := getSignedHostCertificate()
+	assert.FatalError(t, err)
+	userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
+	hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
+	keyB64 := base64.StdEncoding.EncodeToString(user.Key.Marshal())
+
+	type args struct {
+		data []byte
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    *ssh.Certificate
+		wantErr bool
+	}{
+		{"null", args{[]byte(`null`)}, nil, false},
+		{"empty", args{[]byte(`""`)}, nil, false},
+		{"user", args{[]byte(`"` + userB64 + `"`)}, user, false},
+		{"host", args{[]byte(`"` + hostB64 + `"`)}, host, false},
+		{"bad-string", args{[]byte(userB64)}, nil, true},
+		{"bad-base64", args{[]byte(`"this-is-not-base64"`)}, nil, true},
+		{"bad-key", args{[]byte(`"bm90LWEta2V5"`)}, nil, true},
+		{"bat-cert", args{[]byte(`"` + keyB64 + `"`)}, nil, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := &SSHCertificate{}
+			if err := c.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
+				t.Errorf("SSHCertificate.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+			}
+			if !reflect.DeepEqual(tt.want, c.Certificate) {
+				t.Errorf("SSHCertificate.UnmarshalJSON() got = %v, want %v\n", c.Certificate, tt.want)
+			}
+		})
+	}
+}
+
+func TestSignSSHRequest_Validate(t *testing.T) {
+	type fields struct {
+		PublicKey        []byte
+		OTT              string
+		CertType         string
+		Principals       []string
+		ValidAfter       TimeDuration
+		ValidBefore      TimeDuration
+		AddUserPublicKey []byte
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		wantErr bool
+	}{
+		{"ok-empty", fields{[]byte("Zm9v"), "ott", "", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
+		{"ok-user", fields{[]byte("Zm9v"), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
+		{"ok-host", fields{[]byte("Zm9v"), "ott", "host", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, false},
+		{"key", fields{nil, "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
+		{"key", fields{[]byte(""), "ott", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
+		{"type", fields{[]byte("Zm9v"), "ott", "foo", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
+		{"ott", fields{[]byte("Zm9v"), "", "user", []string{"user"}, TimeDuration{}, TimeDuration{}, nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			s := &SignSSHRequest{
+				PublicKey:        tt.fields.PublicKey,
+				OTT:              tt.fields.OTT,
+				CertType:         tt.fields.CertType,
+				Principals:       tt.fields.Principals,
+				ValidAfter:       tt.fields.ValidAfter,
+				ValidBefore:      tt.fields.ValidBefore,
+				AddUserPublicKey: tt.fields.AddUserPublicKey,
+			}
+			if err := s.Validate(); (err != nil) != tt.wantErr {
+				t.Errorf("SignSSHRequest.Validate() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_caHandler_SignSSH(t *testing.T) {
+	user, err := getSignedUserCertificate()
+	assert.FatalError(t, err)
+	host, err := getSignedHostCertificate()
+	assert.FatalError(t, err)
+
+	userB64 := base64.StdEncoding.EncodeToString(user.Marshal())
+	hostB64 := base64.StdEncoding.EncodeToString(host.Marshal())
+
+	userReq, err := json.Marshal(SignSSHRequest{
+		PublicKey: user.Key.Marshal(),
+		OTT:       "ott",
+	})
+	assert.FatalError(t, err)
+	hostReq, err := json.Marshal(SignSSHRequest{
+		PublicKey: host.Key.Marshal(),
+		OTT:       "ott",
+	})
+	assert.FatalError(t, err)
+	userAddReq, err := json.Marshal(SignSSHRequest{
+		PublicKey:        user.Key.Marshal(),
+		OTT:              "ott",
+		AddUserPublicKey: user.Key.Marshal(),
+	})
+	assert.FatalError(t, err)
+
+	tests := []struct {
+		name        string
+		req         []byte
+		authErr     error
+		signCert    *ssh.Certificate
+		signErr     error
+		addUserCert *ssh.Certificate
+		addUserErr  error
+		body        []byte
+		statusCode  int
+	}{
+		{"ok-user", userReq, nil, user, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, userB64)), http.StatusCreated},
+		{"ok-host", hostReq, nil, host, nil, nil, nil, []byte(fmt.Sprintf(`{"crt":"%s"}`, hostB64)), http.StatusCreated},
+		{"ok-user-add", userAddReq, nil, user, nil, user, nil, []byte(fmt.Sprintf(`{"crt":"%s","addUserCrt":"%s"}`, userB64, userB64)), http.StatusCreated},
+		{"fail-body", []byte("bad-json"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
+		{"fail-validate", []byte("{}"), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
+		{"fail-publicKey", []byte(`{"publicKey":"Zm9v","ott":"ott"}`), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
+		{"fail-publicKey", []byte(fmt.Sprintf(`{"publicKey":"%s","ott":"ott","addUserPublicKey":"Zm9v"}`, base64.StdEncoding.EncodeToString(user.Key.Marshal()))), nil, nil, nil, nil, nil, nil, http.StatusBadRequest},
+		{"fail-authorize", userReq, fmt.Errorf("an-error"), nil, nil, nil, nil, nil, http.StatusUnauthorized},
+		{"fail-signSSH", userReq, nil, nil, fmt.Errorf("an-error"), nil, nil, nil, http.StatusForbidden},
+		{"fail-SignSSHAddUser", userAddReq, nil, user, nil, nil, fmt.Errorf("an-error"), nil, http.StatusForbidden},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			h := New(&mockAuthority{
+				authorizeSign: func(ott string) ([]provisioner.SignOption, error) {
+					return []provisioner.SignOption{}, tt.authErr
+				},
+				signSSH: func(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
+					return tt.signCert, tt.signErr
+				},
+				signSSHAddUser: func(key ssh.PublicKey, cert *ssh.Certificate) (*ssh.Certificate, error) {
+					return tt.addUserCert, tt.addUserErr
+				},
+			}).(*caHandler)
+
+			req := httptest.NewRequest("POST", "http://example.com/sign-ssh", bytes.NewReader(tt.req))
+			w := httptest.NewRecorder()
+			h.SignSSH(logging.NewResponseLogger(w), req)
+			res := w.Result()
+
+			if res.StatusCode != tt.statusCode {
+				t.Errorf("caHandler.Root StatusCode = %d, wants %d", res.StatusCode, tt.statusCode)
+			}
+
+			body, err := ioutil.ReadAll(res.Body)
+			res.Body.Close()
+			if err != nil {
+				t.Errorf("caHandler.Root unexpected error = %v", err)
+			}
+			if tt.statusCode < http.StatusBadRequest {
+				if !bytes.Equal(bytes.TrimSpace(body), tt.body) {
+					t.Errorf("caHandler.Root Body = %s, wants %s", body, tt.body)
+				}
+			}
+		})
+	}
+}

+ 33 - 0
api/utils.go

@@ -10,6 +10,11 @@ import (
 	"github.com/smallstep/certificates/logging"
 )
 
+// EnableLogger is an interface that enables response logging for an object.
+type EnableLogger interface {
+	ToLog() (interface{}, error)
+}
+
 // LogError adds to the response writer the given error if it implements
 // logging.ResponseLogger. If it does not implement it, then writes the error
 // using the log package.
@@ -23,12 +28,40 @@ func LogError(rw http.ResponseWriter, err error) {
 	}
 }
 
+// LogEnabledResponse log the response object if it implements the EnableLogger
+// interface.
+func LogEnabledResponse(rw http.ResponseWriter, v interface{}) {
+	if el, ok := v.(EnableLogger); ok {
+		out, err := el.ToLog()
+		if err != nil {
+			LogError(rw, err)
+			return
+		}
+		if rl, ok := rw.(logging.ResponseLogger); ok {
+			rl.WithFields(map[string]interface{}{
+				"response": out,
+			})
+		} else {
+			log.Println(out)
+		}
+	}
+}
+
 // JSON writes the passed value into the http.ResponseWriter.
 func JSON(w http.ResponseWriter, v interface{}) {
+	JSONStatus(w, v, http.StatusOK)
+}
+
+// JSONStatus writes the given value into the http.ResponseWriter and the
+// given status is written as the status code of the response.
+func JSONStatus(w http.ResponseWriter, v interface{}, status int) {
 	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(status)
 	if err := json.NewEncoder(w).Encode(v); err != nil {
 		LogError(w, err)
+		return
 	}
+	LogEnabledResponse(w, v)
 }
 
 // ReadJSON reads JSON from the request body and stores it in the value

+ 91 - 45
authority/authority.go

@@ -1,62 +1,59 @@
 package authority
 
 import (
+	"crypto"
 	"crypto/sha256"
 	"crypto/x509"
 	"encoding/hex"
-	"fmt"
 	"sync"
 	"time"
 
+	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
 	"github.com/smallstep/certificates/ct"
+	"github.com/smallstep/certificates/db"
 	"github.com/smallstep/cli/crypto/pemutil"
 	"github.com/smallstep/cli/crypto/x509util"
 )
 
-const legacyAuthority = "step-certificate-authority"
+const (
+	legacyAuthority = "step-certificate-authority"
+)
 
 // Authority implements the Certificate Authority internal interface.
 type Authority struct {
-	config                 *Config
-	rootX509Certs          []*x509.Certificate
-	intermediateIdentity   *x509util.Identity
-	validateOnce           bool
-	certificates           *sync.Map
-	ottMap                 *sync.Map
-	startTime              time.Time
-	provisionerIDIndex     *sync.Map
-	encryptedKeyIndex      *sync.Map
-	provisionerKeySetIndex *sync.Map
-	sortedProvisioners     provisionerSlice
-	audiences              []string
-	ctClient               ct.Client
+	config               *Config
+	rootX509Certs        []*x509.Certificate
+	intermediateIdentity *x509util.Identity
+	sshCAUserCertSignKey crypto.Signer
+	sshCAHostCertSignKey crypto.Signer
+	certificates         *sync.Map
+	startTime            time.Time
+	provisioners         *provisioner.Collection
+	db                   db.AuthDB
+	ctClient             ct.Client
 	// Do not re-initialize
 	initOnce bool
 }
 
+// Option sets options to the Authority.
+type Option func(*Authority)
+
+// WithDatabase sets an already initialized authority database to a new
+// authority. This option is intended to be use on graceful reloads.
+func WithDatabase(db db.AuthDB) Option {
+	return func(a *Authority) {
+		a.db = db
+	}
+}
+
 // New creates and initiates a new Authority type.
-func New(config *Config) (*Authority, error) {
+func New(config *Config, opts ...Option) (*Authority, error) {
 	err := config.Validate()
 	if err != nil {
 		return nil, err
 	}
 
-	// Get sorted provisioners
-	var sorted provisionerSlice
-	if config.AuthorityConfig != nil {
-		sorted, err = newSortedProvisioners(config.AuthorityConfig.Provisioners)
-		if err != nil {
-			return nil, err
-		}
-	}
-
-	// Define audiences: legacy + possible urls without the ports.
-	// The CA might have proxies in front so we cannot rely on the port.
-	audiences := []string{legacyAuthority}
-	for _, name := range config.DNSNames {
-		audiences = append(audiences, fmt.Sprintf("https://%s/sign", name), fmt.Sprintf("https://%s/1.0/sign", name))
-	}
-
 	var ctClient ct.Client
 	// only first one is supported at the moment.
 	if len(config.CTs) > 0 {
@@ -66,15 +63,13 @@ func New(config *Config) (*Authority, error) {
 	}
 
 	var a = &Authority{
-		config:                 config,
-		certificates:           new(sync.Map),
-		ottMap:                 new(sync.Map),
-		provisionerIDIndex:     new(sync.Map),
-		encryptedKeyIndex:      new(sync.Map),
-		provisionerKeySetIndex: new(sync.Map),
-		sortedProvisioners:     sorted,
-		audiences:              audiences,
-		ctClient:               ctClient,
+		config:       config,
+		certificates: new(sync.Map),
+		provisioners: provisioner.NewCollection(config.getAudiences()),
+		ctClient:     ctClient,
+	}
+	for _, opt := range opts {
+		opt(a)
 	}
 	if err := a.init(); err != nil {
 		return nil, err
@@ -90,6 +85,13 @@ func (a *Authority) init() error {
 	}
 
 	var err error
+	// Initialize step-ca Database if it's not already initialized with WithDB.
+	// If a.config.DB is nil then a simple, barebones in memory DB will be used.
+	if a.db == nil {
+		if a.db, err = db.New(a.config.DB); err != nil {
+			return err
+		}
+	}
 
 	// Load the root certificates and add them to the certificate store
 	a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
@@ -131,17 +133,61 @@ func (a *Authority) init() error {
 		}
 	}
 
+	// Decrypt and load SSH keys
+	if a.config.SSH != nil {
+		if a.config.SSH.HostKey != "" {
+			a.sshCAHostCertSignKey, err = parseCryptoSigner(a.config.SSH.HostKey, a.config.Password)
+			if err != nil {
+				return err
+			}
+		}
+		if a.config.SSH.UserKey != "" {
+			a.sshCAUserCertSignKey, err = parseCryptoSigner(a.config.SSH.UserKey, a.config.Password)
+			if err != nil {
+				return err
+			}
+		}
+	}
+
+	// Store all the provisioners
 	for _, p := range a.config.AuthorityConfig.Provisioners {
-		a.provisionerIDIndex.Store(p.ID(), p)
-		if len(p.EncryptedKey) != 0 {
-			a.encryptedKeyIndex.Store(p.Key.KeyID, p.EncryptedKey)
+		if err := a.provisioners.Store(p); err != nil {
+			return err
 		}
 	}
 
-	a.startTime = time.Now()
+	// JWT numeric dates are seconds.
+	a.startTime = time.Now().Truncate(time.Second)
 	// Set flag indicating that initialization has been completed, and should
 	// not be repeated.
 	a.initOnce = true
 
 	return nil
 }
+
+// GetDatabase returns the authority database. If the configuration does not
+// define a database, GetDatabase will return a db.SimpleDB instance.
+func (a *Authority) GetDatabase() db.AuthDB {
+	return a.db
+}
+
+// Shutdown safely shuts down any clients, databases, etc. held by the Authority.
+func (a *Authority) Shutdown() error {
+	return a.db.Shutdown()
+}
+
+func parseCryptoSigner(filename, password string) (crypto.Signer, error) {
+	var opts []pemutil.Options
+	if password != "" {
+		opts = append(opts, pemutil.WithPassword([]byte(password)))
+	}
+	key, err := pemutil.Read(filename, opts...)
+	if err != nil {
+		return nil, err
+	}
+	signer, ok := key.(crypto.Signer)
+	if !ok {
+		return nil, errors.Errorf("key %s of type %T cannot be used for signing operations", filename, key)
+	}
+	return signer, nil
+}

+ 48 - 18
authority/authority_test.go

@@ -3,10 +3,13 @@ package authority
 import (
 	"crypto/sha256"
 	"encoding/hex"
+	"reflect"
 	"testing"
 
 	"github.com/pkg/errors"
 	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/certificates/db"
 	stepJOSE "github.com/smallstep/cli/jose"
 )
 
@@ -16,30 +19,38 @@ func testAuthority(t *testing.T) *Authority {
 	clijwk, err := stepJOSE.ParseKey("testdata/secrets/step_cli_key_pub.jwk")
 	assert.FatalError(t, err)
 	disableRenewal := true
-	p := []*Provisioner{
-		{
+	p := provisioner.List{
+		&provisioner.JWK{
 			Name: "Max",
 			Type: "JWK",
 			Key:  maxjwk,
 		},
-		{
+		&provisioner.JWK{
 			Name: "step-cli",
 			Type: "JWK",
 			Key:  clijwk,
 		},
-		{
+		&provisioner.JWK{
 			Name: "dev",
 			Type: "JWK",
 			Key:  maxjwk,
-			Claims: &ProvisionerClaims{
+			Claims: &provisioner.Claims{
+				DisableRenewal: &disableRenewal,
+			},
+		},
+		&provisioner.JWK{
+			Name: "renew_disabled",
+			Type: "JWK",
+			Key:  maxjwk,
+			Claims: &provisioner.Claims{
 				DisableRenewal: &disableRenewal,
 			},
 		},
 	}
 	c := &Config{
 		Address:          "127.0.0.1:443",
-		Root:             []string{"testdata/secrets/root_ca.crt"},
-		IntermediateCert: "testdata/secrets/intermediate_ca.crt",
+		Root:             []string{"testdata/certs/root_ca.crt"},
+		IntermediateCert: "testdata/certs/intermediate_ca.crt",
 		IntermediateKey:  "testdata/secrets/intermediate_ca_key",
 		DNSNames:         []string{"test.ca.smallstep.com"},
 		Password:         "pass",
@@ -113,26 +124,45 @@ func TestAuthorityNew(t *testing.T) {
 					assert.True(t, auth.initOnce)
 					assert.NotNil(t, auth.intermediateIdentity)
 					for _, p := range tc.config.AuthorityConfig.Provisioners {
-						_p, ok := auth.provisionerIDIndex.Load(p.ID())
+						var _p provisioner.Interface
+						_p, ok = auth.provisioners.Load(p.GetID())
 						assert.True(t, ok)
 						assert.Equals(t, p, _p)
-						if len(p.EncryptedKey) > 0 {
-							key, ok := auth.encryptedKeyIndex.Load(p.Key.KeyID)
+						var kid, encryptedKey string
+						if kid, encryptedKey, ok = p.GetEncryptedKey(); ok {
+							var key string
+							key, ok = auth.provisioners.LoadEncryptedKey(kid)
 							assert.True(t, ok)
-							assert.Equals(t, p.EncryptedKey, key)
+							assert.Equals(t, encryptedKey, key)
 						}
 					}
 					// sanity check
-					_, ok = auth.provisionerIDIndex.Load("fooo")
+					_, ok = auth.provisioners.Load("fooo")
 					assert.False(t, ok)
-
-					assert.Equals(t, auth.audiences, []string{
-						"step-certificate-authority",
-						"https://127.0.0.1/sign",
-						"https://127.0.0.1/1.0/sign",
-					})
 				}
 			}
 		})
 	}
 }
+
+func TestAuthority_GetDatabase(t *testing.T) {
+	auth := testAuthority(t)
+	authWithDatabase, err := New(auth.config, WithDatabase(auth.db))
+	assert.FatalError(t, err)
+
+	tests := []struct {
+		name string
+		auth *Authority
+		want db.AuthDB
+	}{
+		{"ok", auth, auth.db},
+		{"ok WithDatabase", authWithDatabase, auth.db},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := tt.auth.GetDatabase(); !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Authority.GetDatabase() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 136 - 147
authority/authorize.go

@@ -1,153 +1,150 @@
 package authority
 
 import (
+	"context"
 	"crypto/x509"
-	"encoding/asn1"
 	"net/http"
-	"net/url"
-	"time"
+	"strings"
 
 	"github.com/pkg/errors"
-	"github.com/smallstep/cli/crypto/x509util"
-	"gopkg.in/square/go-jose.v2/jwt"
+	"github.com/smallstep/certificates/authority/provisioner"
+	"github.com/smallstep/cli/jose"
 )
 
-type idUsed struct {
-	UsedAt  int64  `json:"ua,omitempty"`
-	Subject string `json:"sub,omitempty"`
-}
-
-// Claims extends jwt.Claims with step attributes.
+// Claims extends jose.Claims with step attributes.
 type Claims struct {
-	jwt.Claims
-	SANs []string `json:"sans,omitempty"`
+	jose.Claims
+	SANs  []string `json:"sans,omitempty"`
+	Email string   `json:"email,omitempty"`
+	Nonce string   `json:"nonce,omitempty"`
 }
 
-// matchesAudience returns true if A and B share at least one element.
-func matchesAudience(as, bs []string) bool {
-	if len(bs) == 0 || len(as) == 0 {
-		return false
-	}
-
-	for _, b := range bs {
-		for _, a := range as {
-			if b == a || stripPort(a) == stripPort(b) {
-				return true
-			}
-		}
-	}
-	return false
-}
-
-// stripPort attempts to strip the port from the given url. If parsing the url
-// produces errors it will just return the passed argument.
-func stripPort(rawurl string) string {
-	u, err := url.Parse(rawurl)
-	if err != nil {
-		return rawurl
-	}
-	u.Host = u.Hostname()
-	return u.String()
-}
-
-// Authorize authorizes a signature request by validating and authenticating
-// a OTT that must be sent w/ the request.
-func (a *Authority) Authorize(ott string) ([]interface{}, error) {
-	var (
-		errContext = map[string]interface{}{"ott": ott}
-		claims     = Claims{}
-	)
+// authorizeToken parses the token and returns the provisioner used to generate
+// the token. This method enforces the One-Time use policy (tokens can only be
+// used once).
+func (a *Authority) authorizeToken(ott string) (provisioner.Interface, error) {
+	var errContext = map[string]interface{}{"ott": ott}
 
 	// Validate payload
-	token, err := jwt.ParseSigned(ott)
+	token, err := jose.ParseSigned(ott)
 	if err != nil {
-		return nil, &apiError{errors.Wrapf(err, "authorize: error parsing token"),
+		return nil, &apiError{errors.Wrapf(err, "authorizeToken: error parsing token"),
 			http.StatusUnauthorized, errContext}
 	}
 
 	// Get claims w/out verification. We need to look up the provisioner
 	// key in order to verify the claims and we need the issuer from the claims
 	// before we can look up the provisioner.
+	var claims Claims
 	if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
-		return nil, &apiError{err, http.StatusUnauthorized, errContext}
-	}
-	kid := token.Headers[0].KeyID // JWT will only have 1 header.
-	if len(kid) == 0 {
-		return nil, &apiError{errors.New("authorize: token KeyID cannot be empty"),
-			http.StatusUnauthorized, errContext}
-	}
-	pid := claims.Issuer + ":" + kid
-	val, ok := a.provisionerIDIndex.Load(pid)
-	if !ok {
-		return nil, &apiError{errors.Errorf("authorize: provisioner with id %s not found", pid),
-			http.StatusUnauthorized, errContext}
-	}
-	p, ok := val.(*Provisioner)
-	if !ok {
-		return nil, &apiError{errors.Errorf("authorize: invalid provisioner type"),
-			http.StatusInternalServerError, errContext}
-	}
-
-	if err = token.Claims(p.Key, &claims); err != nil {
-		return nil, &apiError{err, http.StatusUnauthorized, errContext}
-	}
-
-	// According to "rfc7519 JSON Web Token" acceptable skew should be no
-	// more than a few minutes.
-	if err = claims.ValidateWithLeeway(jwt.Expected{
-		Issuer: p.Name,
-	}, time.Minute); err != nil {
-		return nil, &apiError{errors.Wrapf(err, "authorize: invalid token"),
-			http.StatusUnauthorized, errContext}
+		return nil, &apiError{errors.Wrap(err, "authorizeToken"), http.StatusUnauthorized, errContext}
 	}
 
+	// TODO: use new persistence layer abstraction.
 	// Do not accept tokens issued before the start of the ca.
 	// This check is meant as a stopgap solution to the current lack of a persistence layer.
 	if a.config.AuthorityConfig != nil && !a.config.AuthorityConfig.DisableIssuedAtCheck {
-		if claims.IssuedAt > 0 && claims.IssuedAt.Time().Before(a.startTime) {
-			return nil, &apiError{errors.New("token issued before the bootstrap of certificate authority"),
+		if claims.IssuedAt != nil && claims.IssuedAt.Time().Before(a.startTime) {
+			return nil, &apiError{errors.New("authorizeToken: token issued before the bootstrap of certificate authority"),
 				http.StatusUnauthorized, errContext}
 		}
 	}
 
-	if !matchesAudience(claims.Audience, a.audiences) {
-		return nil, &apiError{errors.New("authorize: token audience invalid"), http.StatusUnauthorized,
-			errContext}
+	// This method will also validate the audiences for JWK provisioners.
+	p, ok := a.provisioners.LoadByToken(token, &claims.Claims)
+	if !ok {
+		return nil, &apiError{
+			errors.Errorf("authorizeToken: provisioner not found or invalid audience (%s)", strings.Join(claims.Audience, ", ")),
+			http.StatusUnauthorized, errContext}
 	}
 
-	if claims.Subject == "" {
-		return nil, &apiError{errors.New("authorize: token subject cannot be empty"),
-			http.StatusUnauthorized, errContext}
+	// Store the token to protect against reuse.
+	if reuseKey, err := p.GetTokenID(ott); err == nil {
+		ok, err := a.db.UseToken(reuseKey, ott)
+		if err != nil {
+			return nil, &apiError{errors.Wrap(err, "authorizeToken: failed when checking if token already used"),
+				http.StatusInternalServerError, errContext}
+		}
+		if !ok {
+			return nil, &apiError{errors.Errorf("authorizeToken: token already used"), http.StatusUnauthorized, errContext}
+		}
 	}
 
-	// NOTE: This is for backwards compatibility with older versions of cli
-	// and certificates. Older versions added the token subject as the only SAN
-	// in a CSR by default.
-	if len(claims.SANs) == 0 {
-		claims.SANs = []string{claims.Subject}
+	return p, nil
+}
+
+// Authorize grabs the method from the context and authorizes a signature
+// request by validating the one-time-token.
+func (a *Authority) Authorize(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
+	var errContext = apiCtx{"ott": ott}
+	switch m := provisioner.MethodFromContext(ctx); m {
+	case provisioner.SignMethod:
+		return a.authorizeSign(ctx, ott)
+	case provisioner.SignSSHMethod:
+		if a.sshCAHostCertSignKey == nil && a.sshCAUserCertSignKey == nil {
+			return nil, &apiError{errors.New("authorize: ssh signing is not enabled"), http.StatusNotImplemented, errContext}
+		}
+		return a.authorizeSign(ctx, ott)
+	case provisioner.RevokeMethod:
+		return nil, &apiError{errors.New("authorize: revoke method is not supported"), http.StatusInternalServerError, errContext}
+	default:
+		return nil, &apiError{errors.Errorf("authorize: method %d is not supported", m), http.StatusInternalServerError, errContext}
 	}
-	dnsNames, ips := x509util.SplitSANs(claims.SANs)
+}
+
+// authorizeSign loads the provisioner from the token, checks that it has not
+// been used again and calls the provisioner AuthorizeSign method. Returns a
+// list of methods to apply to the signing flow.
+func (a *Authority) authorizeSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
+	var errContext = apiCtx{"ott": ott}
+	p, err := a.authorizeToken(ott)
 	if err != nil {
-		return nil, err
+		return nil, &apiError{errors.Wrap(err, "authorizeSign"), http.StatusUnauthorized, errContext}
 	}
-
-	signOps := []interface{}{
-		&commonNameClaim{claims.Subject},
-		&dnsNamesClaim{dnsNames},
-		&ipAddressesClaim{ips},
-		p,
+	opts, err := p.AuthorizeSign(ctx, ott)
+	if err != nil {
+		return nil, &apiError{errors.Wrap(err, "authorizeSign"), http.StatusUnauthorized, errContext}
 	}
+	return opts, nil
+}
 
-	// Store the token to protect against reuse.
-	if _, ok := a.ottMap.LoadOrStore(claims.ID, &idUsed{
-		UsedAt:  time.Now().Unix(),
-		Subject: claims.Subject,
-	}); ok {
-		return nil, &apiError{errors.Errorf("token already used"), http.StatusUnauthorized,
-			errContext}
-	}
+// AuthorizeSign authorizes a signature request by validating and authenticating
+// a OTT that must be sent w/ the request.
+//
+// NOTE: This method is deprecated and should not be used. We make it available
+// in the short term os as not to break existing clients.
+func (a *Authority) AuthorizeSign(ott string) ([]provisioner.SignOption, error) {
+	ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
+	return a.Authorize(ctx, ott)
+}
 
-	return signOps, nil
+// authorizeRevoke authorizes a revocation request by validating and authenticating
+// the RevokeOptions POSTed with the request.
+// Returns a tuple of the provisioner ID and error, if one occurred.
+func (a *Authority) authorizeRevoke(opts *RevokeOptions) (p provisioner.Interface, err error) {
+	if opts.MTLS {
+		if opts.Crt.SerialNumber.String() != opts.Serial {
+			return nil, errors.New("authorizeRevoke: serial number in certificate different than body")
+		}
+		// Load the Certificate provisioner if one exists.
+		p, err = a.LoadProvisionerByCertificate(opts.Crt)
+		if err != nil {
+			return nil, errors.Wrap(err, "authorizeRevoke")
+		}
+	} else {
+		// Gets the token provisioner and validates common token fields.
+		p, err = a.authorizeToken(opts.OTT)
+		if err != nil {
+			return nil, errors.Wrap(err, "authorizeRevoke")
+		}
+
+		// Call the provisioner AuthorizeRevoke to apply provisioner specific auth claims.
+		err = p.AuthorizeRevoke(opts.OTT)
+		if err != nil {
+			return nil, errors.Wrap(err, "authorizeRevoke")
+		}
+	}
+	return
 }
 
 // authorizeRenewal tries to locate the step provisioner extension, and checks
@@ -157,46 +154,38 @@ func (a *Authority) Authorize(ott string) ([]interface{}, error) {
 // TODO(mariano): should we authorize by default?
 func (a *Authority) authorizeRenewal(crt *x509.Certificate) error {
 	errContext := map[string]interface{}{"serialNumber": crt.SerialNumber.String()}
-	for _, e := range crt.Extensions {
-		if e.Id.Equal(stepOIDProvisioner) {
-			var provisioner stepProvisionerASN1
-			if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
-				return &apiError{
-					err:     errors.Wrap(err, "error decoding step provisioner extension"),
-					code:    http.StatusInternalServerError,
-					context: errContext,
-				}
-			}
-
-			// Look for the provisioner, if it cannot be found, renewal will not
-			// be authorized.
-			pid := string(provisioner.Name) + ":" + string(provisioner.CredentialID)
-			val, ok := a.provisionerIDIndex.Load(pid)
-			if !ok {
-				return &apiError{
-					err:     errors.Errorf("not found: provisioner %s", pid),
-					code:    http.StatusUnauthorized,
-					context: errContext,
-				}
-			}
-			p, ok := val.(*Provisioner)
-			if !ok {
-				return &apiError{
-					err:     errors.Errorf("invalid type: provisioner %s, type %T", pid, val),
-					code:    http.StatusInternalServerError,
-					context: errContext,
-				}
-			}
-			if p.Claims.IsDisableRenewal() {
-				return &apiError{
-					err:     errors.Errorf("renew disabled: provisioner %s", pid),
-					code:    http.StatusUnauthorized,
-					context: errContext,
-				}
-			}
-			return nil
+
+	// Check the passive revocation table.
+	isRevoked, err := a.db.IsRevoked(crt.SerialNumber.String())
+	if err != nil {
+		return &apiError{
+			err:     errors.Wrap(err, "renew"),
+			code:    http.StatusInternalServerError,
+			context: errContext,
+		}
+	}
+	if isRevoked {
+		return &apiError{
+			err:     errors.New("renew: certificate has been revoked"),
+			code:    http.StatusUnauthorized,
+			context: errContext,
 		}
 	}
 
+	p, ok := a.provisioners.LoadByCertificate(crt)
+	if !ok {
+		return &apiError{
+			err:     errors.New("renew: provisioner not found"),
+			code:    http.StatusUnauthorized,
+			context: errContext,
+		}
+	}
+	if err := p.AuthorizeRenewal(crt); err != nil {
+		return &apiError{
+			err:     errors.Wrap(err, "renew"),
+			code:    http.StatusUnauthorized,
+			context: errContext,
+		}
+	}
 	return nil
 }

+ 479 - 131
authority/authorize_test.go

@@ -1,150 +1,125 @@
 package authority
 
 import (
+	"context"
+	"crypto/x509"
 	"net/http"
 	"testing"
 	"time"
 
+	"github.com/smallstep/certificates/authority/provisioner"
+
 	"github.com/pkg/errors"
 	"github.com/smallstep/assert"
-	"github.com/smallstep/cli/crypto/keys"
-	stepJOSE "github.com/smallstep/cli/jose"
-	jose "gopkg.in/square/go-jose.v2"
+	"github.com/smallstep/cli/crypto/pemutil"
+	"github.com/smallstep/cli/crypto/randutil"
+	"github.com/smallstep/cli/jose"
 	"gopkg.in/square/go-jose.v2/jwt"
 )
 
-func TestMatchesAudience(t *testing.T) {
-	type matchesTest struct {
-		a, b []string
-		exp  bool
+func generateToken(sub, iss, aud string, sans []string, iat time.Time, jwk *jose.JSONWebKey) (string, error) {
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
+	)
+	if err != nil {
+		return "", err
 	}
-	tests := map[string]matchesTest{
-		"false arg1 empty": {
-			a:   []string{},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			exp: false,
-		},
-		"false arg2 empty": {
-			a:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			b:   []string{},
-			exp: false,
-		},
-		"false arg1,arg2 empty": {
-			a:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			b:   []string{"step-gateway", "step-cli"},
-			exp: false,
-		},
-		"false": {
-			a:   []string{"step-gateway", "step-cli"},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			exp: false,
-		},
-		"true": {
-			a:   []string{"step-gateway", "https://test.ca.smallstep.com/sign"},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			exp: true,
-		},
-		"true,portsA": {
-			a:   []string{"step-gateway", "https://test.ca.smallstep.com:9000/sign"},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
-			exp: true,
-		},
-		"true,portsB": {
-			a:   []string{"step-gateway", "https://test.ca.smallstep.com/sign"},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com:9000/sign"},
-			exp: true,
-		},
-		"true,portsAB": {
-			a:   []string{"step-gateway", "https://test.ca.smallstep.com:9000/sign"},
-			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com:8000/sign"},
-			exp: true,
-		},
-	}
-	for name, tc := range tests {
-		t.Run(name, func(t *testing.T) {
-			assert.Equals(t, tc.exp, matchesAudience(tc.a, tc.b))
-		})
-	}
-}
 
-func TestStripPort(t *testing.T) {
-	type args struct {
-		rawurl string
+	id, err := randutil.ASCII(64)
+	if err != nil {
+		return "", err
 	}
-	tests := []struct {
-		name string
-		args args
-		want string
+
+	claims := struct {
+		jose.Claims
+		SANS []string `json:"sans"`
 	}{
-		{"with port", args{"https://ca.smallstep.com:9000/sign"}, "https://ca.smallstep.com/sign"},
-		{"with no port", args{"https://ca.smallstep.com/sign/"}, "https://ca.smallstep.com/sign/"},
-		{"bad url", args{"https://a bad url:9000"}, "https://a bad url:9000"},
-	}
-	for _, tt := range tests {
-		t.Run(tt.name, func(t *testing.T) {
-			if got := stripPort(tt.args.rawurl); got != tt.want {
-				t.Errorf("stripPort() = %v, want %v", got, tt.want)
-			}
-		})
+		Claims: jose.Claims{
+			ID:        id,
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+		},
+		SANS: sans,
 	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
 }
 
-func TestAuthorize(t *testing.T) {
+func TestAuthority_authorizeToken(t *testing.T) {
 	a := testAuthority(t)
-	jwk, err := stepJOSE.ParseKey("testdata/secrets/step_cli_key_priv.jwk",
-		stepJOSE.WithPassword([]byte("pass")))
+
+	jwk, err := jose.ParseKey("testdata/secrets/step_cli_key_priv.jwk", jose.WithPassword([]byte("pass")))
 	assert.FatalError(t, err)
 
 	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
 		(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", jwk.KeyID))
 	assert.FatalError(t, err)
 
-	now := time.Now()
+	now := time.Now().UTC()
 
 	validIssuer := "step-cli"
-	validAudience := []string{"https://test.ca.smallstep.com/sign"}
+	validAudience := []string{"https://test.ca.smallstep.com/revoke"}
 
 	type authorizeTest struct {
 		auth *Authority
 		ott  string
 		err  *apiError
-		res  []interface{}
 	}
 	tests := map[string]func(t *testing.T) *authorizeTest{
-		"fail invalid ott": func(t *testing.T) *authorizeTest {
+		"fail/invalid-ott": func(t *testing.T) *authorizeTest {
 			return &authorizeTest{
 				auth: a,
 				ott:  "foo",
-				err: &apiError{errors.New("authorize: error parsing token"),
-					http.StatusUnauthorized, context{"ott": "foo"}},
+				err: &apiError{errors.New("authorizeToken: error parsing token"),
+					http.StatusUnauthorized, apiCtx{"ott": "foo"}},
 			}
 		},
-		"fail empty key id": func(t *testing.T) *authorizeTest {
-			_sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
-				(&jose.SignerOptions{}).WithType("JWT"))
-			assert.FatalError(t, err)
+		"fail/prehistoric-token": func(t *testing.T) *authorizeTest {
 			cl := jwt.Claims{
 				Subject:   "test.smallstep.com",
 				Issuer:    validIssuer,
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				IssuedAt:  jwt.NewNumericDate(now.Add(-time.Hour)),
 				Audience:  validAudience,
 				ID:        "43",
 			}
-			raw, err := jwt.Signed(_sig).Claims(cl).CompactSerialize()
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
 				ott:  raw,
-				err: &apiError{errors.New("authorize: token KeyID cannot be empty"),
-					http.StatusUnauthorized, context{"ott": raw}},
+				err: &apiError{errors.New("authorizeToken: token issued before the bootstrap of certificate authority"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
 			}
 		},
-		"fail provisioner not found": func(t *testing.T) *authorizeTest {
+		"fail/provisioner-not-found": func(t *testing.T) *authorizeTest {
+			cl := jwt.Claims{
+				Subject:   "test.smallstep.com",
+				Issuer:    validIssuer,
+				NotBefore: jwt.NewNumericDate(now),
+				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				Audience:  validAudience,
+				ID:        "44",
+			}
 			_sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
 				(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "foo"))
 			assert.FatalError(t, err)
 
+			raw, err := jwt.Signed(_sig).Claims(cl).CompactSerialize()
+			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: a,
+				ott:  raw,
+				err: &apiError{errors.New("authorizeToken: provisioner not found or invalid audience (https://test.ca.smallstep.com/revoke)"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
+			}
+		},
+		"ok/simpledb": func(t *testing.T) *authorizeTest {
 			cl := jwt.Claims{
 				Subject:   "test.smallstep.com",
 				Issuer:    validIssuer,
@@ -153,23 +128,64 @@ func TestAuthorize(t *testing.T) {
 				Audience:  validAudience,
 				ID:        "43",
 			}
-			raw, err := jwt.Signed(_sig).Claims(cl).CompactSerialize()
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
 				ott:  raw,
-				err: &apiError{errors.New("authorize: provisioner with id step-cli:foo not found"),
-					http.StatusUnauthorized, context{"ott": raw}},
 			}
 		},
-		"fail invalid provisioner": func(t *testing.T) *authorizeTest {
+		"fail/simpledb/token-already-used": func(t *testing.T) *authorizeTest {
 			_a := testAuthority(t)
-
-			_sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
-				(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", "foo"))
+			cl := jwt.Claims{
+				Subject:   "test.smallstep.com",
+				Issuer:    validIssuer,
+				NotBefore: jwt.NewNumericDate(now),
+				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				Audience:  validAudience,
+				ID:        "43",
+			}
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
+			_, err = _a.authorizeToken(raw)
+			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: _a,
+				ott:  raw,
+				err: &apiError{errors.New("authorizeToken: token already used"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
+			}
+		},
+		"ok/mockNoSQLDB": func(t *testing.T) *authorizeTest {
+			_a := testAuthority(t)
+			_a.db = &MockAuthDB{
+				useToken: func(id, tok string) (bool, error) {
+					return true, nil
+				},
+			}
 
-			_a.provisionerIDIndex.Store(validIssuer+":foo", "42")
+			cl := jwt.Claims{
+				Subject:   "test.smallstep.com",
+				Issuer:    validIssuer,
+				NotBefore: jwt.NewNumericDate(now),
+				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				Audience:  validAudience,
+				ID:        "43",
+			}
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
+			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: _a,
+				ott:  raw,
+			}
+		},
+		"fail/mockNoSQLDB/error": func(t *testing.T) *authorizeTest {
+			_a := testAuthority(t)
+			_a.db = &MockAuthDB{
+				useToken: func(id, tok string) (bool, error) {
+					return false, errors.New("force")
+				},
+			}
 
 			cl := jwt.Claims{
 				Subject:   "test.smallstep.com",
@@ -179,91 +195,313 @@ func TestAuthorize(t *testing.T) {
 				Audience:  validAudience,
 				ID:        "43",
 			}
-			raw, err := jwt.Signed(_sig).Claims(cl).CompactSerialize()
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: _a,
 				ott:  raw,
-				err: &apiError{errors.New("authorize: invalid provisioner type"),
-					http.StatusInternalServerError, context{"ott": raw}},
+				err: &apiError{errors.New("authorizeToken: failed when checking if token already used: force"),
+					http.StatusInternalServerError, apiCtx{"ott": raw}},
 			}
 		},
-		"fail invalid issuer": func(t *testing.T) *authorizeTest {
+		"fail/mockNoSQLDB/token-already-used": func(t *testing.T) *authorizeTest {
+			_a := testAuthority(t)
+			_a.db = &MockAuthDB{
+				useToken: func(id, tok string) (bool, error) {
+					return false, nil
+				},
+			}
+
 			cl := jwt.Claims{
-				Subject:   "subject",
-				Issuer:    "invalid-issuer",
+				Subject:   "test.smallstep.com",
+				Issuer:    validIssuer,
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
 				Audience:  validAudience,
+				ID:        "43",
 			}
 			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
-				auth: a,
+				auth: _a,
 				ott:  raw,
-				err: &apiError{errors.New("authorize: provisioner with id invalid-issuer:4UELJx8e0aS9m0CH3fZ0EB7D5aUPICb759zALHFejvc not found"),
-					http.StatusUnauthorized, context{"ott": raw}},
+				err: &apiError{errors.New("authorizeToken: token already used"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
 			}
 		},
-		"fail empty subject": func(t *testing.T) *authorizeTest {
+	}
+
+	for name, genTestCase := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := genTestCase(t)
+
+			p, err := tc.auth.authorizeToken(tc.ott)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					switch v := err.(type) {
+					case *apiError:
+						assert.HasPrefix(t, v.err.Error(), tc.err.Error())
+						assert.Equals(t, v.code, tc.err.code)
+						assert.Equals(t, v.context, tc.err.context)
+					default:
+						t.Errorf("unexpected error type: %T", v)
+					}
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Equals(t, p.GetID(), "step-cli:4UELJx8e0aS9m0CH3fZ0EB7D5aUPICb759zALHFejvc")
+				}
+			}
+		})
+	}
+}
+
+func TestAuthority_authorizeRevoke(t *testing.T) {
+	a := testAuthority(t)
+
+	jwk, err := jose.ParseKey("testdata/secrets/step_cli_key_priv.jwk", jose.WithPassword([]byte("pass")))
+	assert.FatalError(t, err)
+
+	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", jwk.KeyID))
+	assert.FatalError(t, err)
+
+	now := time.Now().UTC()
+
+	validIssuer := "step-cli"
+	validAudience := []string{"https://test.ca.smallstep.com/revoke"}
+
+	type authorizeTest struct {
+		auth *Authority
+		opts *RevokeOptions
+		err  error
+	}
+	tests := map[string]func(t *testing.T) *authorizeTest{
+		"fail/token/invalid-ott": func(t *testing.T) *authorizeTest {
+			return &authorizeTest{
+				auth: a,
+				opts: &RevokeOptions{OTT: "foo"},
+				err:  errors.New("authorizeRevoke: authorizeToken: error parsing token"),
+			}
+		},
+		"fail/token/invalid-subject": func(t *testing.T) *authorizeTest {
 			cl := jwt.Claims{
 				Subject:   "",
 				Issuer:    validIssuer,
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
 				Audience:  validAudience,
+				ID:        "43",
 			}
 			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
-				ott:  raw,
-				err: &apiError{errors.New("authorize: token subject cannot be empty"),
-					http.StatusUnauthorized, context{"ott": raw}},
+				opts: &RevokeOptions{OTT: raw},
+				err:  errors.New("authorizeRevoke: token subject cannot be empty"),
 			}
 		},
-		"fail verify-sig-failure": func(t *testing.T) *authorizeTest {
-			_, priv2, err := keys.GenerateDefaultKeyPair()
+		"ok/token": func(t *testing.T) *authorizeTest {
+			cl := jwt.Claims{
+				Subject:   "test.smallstep.com",
+				Issuer:    validIssuer,
+				NotBefore: jwt.NewNumericDate(now),
+				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				Audience:  validAudience,
+				ID:        "44",
+			}
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
-			invalidKeySig, err := jose.NewSigner(jose.SigningKey{
-				Algorithm: jose.ES256,
-				Key:       priv2,
-			}, (&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", jwk.KeyID))
+			return &authorizeTest{
+				auth: a,
+				opts: &RevokeOptions{OTT: raw},
+			}
+		},
+		"fail/mTLS/invalid-serial": func(t *testing.T) *authorizeTest {
+			crt, err := pemutil.ReadCertificate("./testdata/certs/foo.crt")
 			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: a,
+				opts: &RevokeOptions{MTLS: true, Crt: crt, Serial: "foo"},
+				err:  errors.New("authorizeRevoke: serial number in certificate different than body"),
+			}
+		},
+		"fail/mTLS/load-provisioner": func(t *testing.T) *authorizeTest {
+			crt, err := pemutil.ReadCertificate("./testdata/certs/provisioner-not-found.crt")
+			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: a,
+				opts: &RevokeOptions{MTLS: true, Crt: crt, Serial: "41633491264736369593451462439668497527"},
+				err:  errors.New("authorizeRevoke: provisioner not found"),
+			}
+		},
+		"ok/mTLS": func(t *testing.T) *authorizeTest {
+			crt, err := pemutil.ReadCertificate("./testdata/certs/foo.crt")
+			assert.FatalError(t, err)
+			return &authorizeTest{
+				auth: a,
+				opts: &RevokeOptions{MTLS: true, Crt: crt, Serial: "102012593071130646873265215610956555026"},
+			}
+		},
+	}
+
+	for name, genTestCase := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := genTestCase(t)
+
+			p, err := tc.auth.authorizeRevoke(tc.opts)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					assert.HasPrefix(t, err.Error(), tc.err.Error())
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					if assert.NotNil(t, p) {
+						assert.Equals(t, p.GetID(), "step-cli:4UELJx8e0aS9m0CH3fZ0EB7D5aUPICb759zALHFejvc")
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestAuthority_AuthorizeSign(t *testing.T) {
+	a := testAuthority(t)
+
+	jwk, err := jose.ParseKey("testdata/secrets/step_cli_key_priv.jwk", jose.WithPassword([]byte("pass")))
+	assert.FatalError(t, err)
+
+	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", jwk.KeyID))
+	assert.FatalError(t, err)
+
+	now := time.Now().UTC()
+
+	validIssuer := "step-cli"
+	validAudience := []string{"https://test.ca.smallstep.com/sign"}
+
+	type authorizeTest struct {
+		auth *Authority
+		ott  string
+		err  *apiError
+	}
+	tests := map[string]func(t *testing.T) *authorizeTest{
+		"fail/invalid-ott": func(t *testing.T) *authorizeTest {
+			return &authorizeTest{
+				auth: a,
+				ott:  "foo",
+				err: &apiError{errors.New("authorizeSign: authorizeToken: error parsing token"),
+					http.StatusUnauthorized, apiCtx{"ott": "foo"}},
+			}
+		},
+		"fail/invalid-subject": func(t *testing.T) *authorizeTest {
 			cl := jwt.Claims{
-				Subject:   "test.smallstep.com",
+				Subject:   "",
 				Issuer:    validIssuer,
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
 				Audience:  validAudience,
+				ID:        "43",
 			}
-			raw, err := jwt.Signed(invalidKeySig).Claims(cl).CompactSerialize()
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
 				ott:  raw,
-				err: &apiError{errors.New("square/go-jose: error in cryptographic primitive"),
-					http.StatusUnauthorized, context{"ott": raw}},
+				err: &apiError{errors.New("authorizeSign: token subject cannot be empty"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
 			}
 		},
-		"fail token-already-used": func(t *testing.T) *authorizeTest {
+		"ok": func(t *testing.T) *authorizeTest {
 			cl := jwt.Claims{
 				Subject:   "test.smallstep.com",
 				Issuer:    validIssuer,
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
 				Audience:  validAudience,
-				ID:        "42",
+				ID:        "44",
 			}
 			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
-			_, err = a.Authorize(raw)
+			return &authorizeTest{
+				auth: a,
+				ott:  raw,
+			}
+		},
+	}
+
+	for name, genTestCase := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := genTestCase(t)
+
+			got, err := tc.auth.AuthorizeSign(tc.ott)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					assert.Nil(t, got)
+					switch v := err.(type) {
+					case *apiError:
+						assert.HasPrefix(t, v.err.Error(), tc.err.Error())
+						assert.Equals(t, v.code, tc.err.code)
+						assert.Equals(t, v.context, tc.err.context)
+					default:
+						t.Errorf("unexpected error type: %T", v)
+					}
+				}
+			} else {
+				if assert.Nil(t, tc.err) {
+					assert.Len(t, 8, got)
+				}
+			}
+		})
+	}
+}
+
+// TODO: remove once Authorize deprecated.
+func TestAuthority_Authorize(t *testing.T) {
+	a := testAuthority(t)
+
+	jwk, err := jose.ParseKey("testdata/secrets/step_cli_key_priv.jwk", jose.WithPassword([]byte("pass")))
+	assert.FatalError(t, err)
+
+	sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		(&jose.SignerOptions{}).WithType("JWT").WithHeader("kid", jwk.KeyID))
+	assert.FatalError(t, err)
+
+	now := time.Now().UTC()
+
+	validIssuer := "step-cli"
+	validAudience := []string{"https://test.ca.smallstep.com/sign"}
+
+	type authorizeTest struct {
+		auth *Authority
+		ott  string
+		err  *apiError
+	}
+	tests := map[string]func(t *testing.T) *authorizeTest{
+		"fail/invalid-ott": func(t *testing.T) *authorizeTest {
+			return &authorizeTest{
+				auth: a,
+				ott:  "foo",
+				err: &apiError{errors.New("authorizeSign: authorizeToken: error parsing token"),
+					http.StatusUnauthorized, apiCtx{"ott": "foo"}},
+			}
+		},
+		"fail/invalid-subject": func(t *testing.T) *authorizeTest {
+			cl := jwt.Claims{
+				Subject:   "",
+				Issuer:    validIssuer,
+				NotBefore: jwt.NewNumericDate(now),
+				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
+				Audience:  validAudience,
+				ID:        "43",
+			}
+			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
 				ott:  raw,
-				err: &apiError{errors.New("token already used"),
-					http.StatusUnauthorized, context{"ott": raw}},
+				err: &apiError{errors.New("authorizeSign: token subject cannot be empty"),
+					http.StatusUnauthorized, apiCtx{"ott": raw}},
 			}
 		},
 		"ok": func(t *testing.T) *authorizeTest {
@@ -273,14 +511,13 @@ func TestAuthorize(t *testing.T) {
 				NotBefore: jwt.NewNumericDate(now),
 				Expiry:    jwt.NewNumericDate(now.Add(time.Minute)),
 				Audience:  validAudience,
-				ID:        "43",
+				ID:        "44",
 			}
 			raw, err := jwt.Signed(sig).Claims(cl).CompactSerialize()
 			assert.FatalError(t, err)
 			return &authorizeTest{
 				auth: a,
 				ott:  raw,
-				res:  []interface{}{"1", "2", "3", "4"},
 			}
 		},
 	}
@@ -288,11 +525,11 @@ func TestAuthorize(t *testing.T) {
 	for name, genTestCase := range tests {
 		t.Run(name, func(t *testing.T) {
 			tc := genTestCase(t)
-			assert.FatalError(t, err)
-
-			crtOpts, err := tc.auth.Authorize(tc.ott)
+			ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
+			got, err := tc.auth.Authorize(ctx, tc.ott)
 			if err != nil {
 				if assert.NotNil(t, tc.err) {
+					assert.Nil(t, got)
 					switch v := err.(type) {
 					case *apiError:
 						assert.HasPrefix(t, v.err.Error(), tc.err.Error())
@@ -304,9 +541,120 @@ func TestAuthorize(t *testing.T) {
 				}
 			} else {
 				if assert.Nil(t, tc.err) {
-					assert.Equals(t, len(crtOpts), len(tc.res))
+					assert.Len(t, 8, got)
 				}
 			}
 		})
 	}
 }
+
+func TestAuthority_authorizeRenewal(t *testing.T) {
+	fooCrt, err := pemutil.ReadCertificate("testdata/certs/foo.crt")
+	assert.FatalError(t, err)
+
+	renewDisabledCrt, err := pemutil.ReadCertificate("testdata/certs/renew-disabled.crt")
+	assert.FatalError(t, err)
+
+	otherCrt, err := pemutil.ReadCertificate("testdata/certs/provisioner-not-found.crt")
+	assert.FatalError(t, err)
+
+	type authorizeTest struct {
+		auth *Authority
+		crt  *x509.Certificate
+		err  *apiError
+	}
+	tests := map[string]func(t *testing.T) *authorizeTest{
+		"fail/db.IsRevoked-error": func(t *testing.T) *authorizeTest {
+			a := testAuthority(t)
+			a.db = &MockAuthDB{
+				isRevoked: func(key string) (bool, error) {
+					return false, errors.New("force")
+				},
+			}
+
+			return &authorizeTest{
+				auth: a,
+				crt:  fooCrt,
+				err: &apiError{errors.New("renew: force"),
+					http.StatusInternalServerError, apiCtx{"serialNumber": "102012593071130646873265215610956555026"}},
+			}
+		},
+		"fail/revoked": func(t *testing.T) *authorizeTest {
+			a := testAuthority(t)
+			a.db = &MockAuthDB{
+				isRevoked: func(key string) (bool, error) {
+					return true, nil
+				},
+			}
+			return &authorizeTest{
+				auth: a,
+				crt:  fooCrt,
+				err: &apiError{errors.New("renew: certificate has been revoked"),
+					http.StatusUnauthorized, apiCtx{"serialNumber": "102012593071130646873265215610956555026"}},
+			}
+		},
+		"fail/load-provisioner": func(t *testing.T) *authorizeTest {
+			a := testAuthority(t)
+			a.db = &MockAuthDB{
+				isRevoked: func(key string) (bool, error) {
+					return false, nil
+				},
+			}
+			return &authorizeTest{
+				auth: a,
+				crt:  otherCrt,
+				err: &apiError{errors.New("renew: provisioner not found"),
+					http.StatusUnauthorized, apiCtx{"serialNumber": "41633491264736369593451462439668497527"}},
+			}
+		},
+		"fail/provisioner-authorize-renewal-fail": func(t *testing.T) *authorizeTest {
+			a := testAuthority(t)
+			a.db = &MockAuthDB{
+				isRevoked: func(key string) (bool, error) {
+					return false, nil
+				},
+			}
+
+			return &authorizeTest{
+				auth: a,
+				crt:  renewDisabledCrt,
+				err: &apiError{errors.New("renew: renew is disabled for provisioner renew_disabled:IMi94WBNI6gP5cNHXlZYNUzvMjGdHyBRmFoo-lCEaqk"),
+					http.StatusUnauthorized, apiCtx{"serialNumber": "119772236532068856521070735128919532568"}},
+			}
+		},
+		"ok": func(t *testing.T) *authorizeTest {
+			a := testAuthority(t)
+			a.db = &MockAuthDB{
+				isRevoked: func(key string) (bool, error) {
+					return false, nil
+				},
+			}
+			return &authorizeTest{
+				auth: a,
+				crt:  fooCrt,
+			}
+		},
+	}
+
+	for name, genTestCase := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := genTestCase(t)
+
+			err := tc.auth.authorizeRenewal(tc.crt)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					switch v := err.(type) {
+					case *apiError:
+						assert.HasPrefix(t, v.err.Error(), tc.err.Error())
+						assert.Equals(t, v.code, tc.err.code)
+						assert.Equals(t, v.context, tc.err.context)
+					default:
+						t.Errorf("unexpected error type: %T", v)
+					}
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}

+ 0 - 115
authority/claims.go

@@ -1,115 +0,0 @@
-package authority
-
-import (
-	"net"
-	"reflect"
-	"time"
-
-	"github.com/pkg/errors"
-	x509 "github.com/smallstep/cli/pkg/x509"
-)
-
-// certClaim interface is implemented by types used to validate specific claims in a
-// certificate request.
-type certClaim interface {
-	Valid(crt *x509.Certificate) error
-}
-
-// ValidateClaims returns nil if all the claims are validated, it will return
-// the first error if a claim fails.
-func validateClaims(crt *x509.Certificate, claims []certClaim) (err error) {
-	for _, c := range claims {
-		if err = c.Valid(crt); err != nil {
-			return err
-		}
-	}
-	return
-}
-
-// commonNameClaim validates the common name of a certificate request.
-type commonNameClaim struct {
-	name string
-}
-
-// Valid checks that certificate request common name matches the one configured.
-func (c *commonNameClaim) Valid(crt *x509.Certificate) error {
-	if crt.Subject.CommonName == "" {
-		return errors.New("common name cannot be empty")
-	}
-	if crt.Subject.CommonName != c.name {
-		return errors.Errorf("common name claim failed - got %s, want %s", crt.Subject.CommonName, c.name)
-	}
-	return nil
-}
-
-type dnsNamesClaim struct {
-	names []string
-}
-
-// Valid checks that certificate request common name matches the one configured.
-func (c *dnsNamesClaim) Valid(crt *x509.Certificate) error {
-	tokMap := make(map[string]int)
-	for _, e := range c.names {
-		tokMap[e] = 1
-	}
-	crtMap := make(map[string]int)
-	for _, e := range crt.DNSNames {
-		crtMap[e] = 1
-	}
-	if !reflect.DeepEqual(tokMap, crtMap) {
-		return errors.Errorf("DNS names claim failed - got %s, want %s", crt.DNSNames, c.names)
-	}
-	return nil
-}
-
-type ipAddressesClaim struct {
-	ips []net.IP
-}
-
-// Valid checks that certificate request common name matches the one configured.
-func (c *ipAddressesClaim) Valid(crt *x509.Certificate) error {
-	tokMap := make(map[string]int)
-	for _, e := range c.ips {
-		tokMap[e.String()] = 1
-	}
-	crtMap := make(map[string]int)
-	for _, e := range crt.IPAddresses {
-		crtMap[e.String()] = 1
-	}
-	if !reflect.DeepEqual(tokMap, crtMap) {
-		return errors.Errorf("IP Addresses claim failed - got %v, want %v", crt.IPAddresses, c.ips)
-	}
-	return nil
-}
-
-// certTemporalClaim validates the certificate temporal validity settings.
-type certTemporalClaim struct {
-	min time.Duration
-	max time.Duration
-}
-
-// Validate validates the certificate temporal validity settings.
-func (ctc *certTemporalClaim) Valid(crt *x509.Certificate) error {
-	var (
-		na  = crt.NotAfter
-		nb  = crt.NotBefore
-		d   = na.Sub(nb)
-		now = time.Now()
-	)
-
-	if na.Before(now) {
-		return errors.Errorf("NotAfter: %v cannot be in the past", na)
-	}
-	if na.Before(nb) {
-		return errors.Errorf("NotAfter: %v cannot be before NotBefore: %v", na, nb)
-	}
-	if d < ctc.min {
-		return errors.Errorf("requested duration of %v is less than the authorized minimum certificate duration of %v",
-			d, ctc.min)
-	}
-	if d > ctc.max {
-		return errors.Errorf("requested duration of %v is more than the authorized maximum certificate duration of %v",
-			d, ctc.max)
-	}
-	return nil
-}

+ 0 - 132
authority/claims_test.go

@@ -1,132 +0,0 @@
-package authority
-
-import (
-	"crypto/x509/pkix"
-	"net"
-	"testing"
-
-	"github.com/pkg/errors"
-	"github.com/smallstep/assert"
-	x509 "github.com/smallstep/cli/pkg/x509"
-)
-
-func TestCommonNameClaim_Valid(t *testing.T) {
-	tests := map[string]struct {
-		cnc certClaim
-		crt *x509.Certificate
-		err error
-	}{
-		"empty-common-name": {
-			cnc: &commonNameClaim{name: "foo"},
-			crt: &x509.Certificate{},
-			err: errors.New("common name cannot be empty"),
-		},
-		"wrong-common-name": {
-			cnc: &commonNameClaim{name: "foo"},
-			crt: &x509.Certificate{Subject: pkix.Name{CommonName: "bar"}},
-			err: errors.New("common name claim failed - got bar, want foo"),
-		},
-		"ok": {
-			cnc: &commonNameClaim{name: "foo"},
-			crt: &x509.Certificate{Subject: pkix.Name{CommonName: "foo"}},
-		},
-	}
-
-	for name, tc := range tests {
-		t.Run(name, func(t *testing.T) {
-			err := tc.cnc.Valid(tc.crt)
-			if err != nil {
-				if assert.NotNil(t, tc.err) {
-					assert.Equals(t, tc.err.Error(), err.Error())
-				}
-			} else {
-				assert.Nil(t, tc.err)
-			}
-		})
-	}
-}
-
-func TestIPAddressesClaim_Valid(t *testing.T) {
-	tests := map[string]struct {
-		iac certClaim
-		crt *x509.Certificate
-		err error
-	}{
-		"unexpected-ip-in-crt": {
-			iac: &ipAddressesClaim{ips: []net.IP{net.ParseIP("127.0.0.1")}},
-			crt: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("1.1.1.1")}},
-			err: errors.New("IP Addresses claim failed - got [127.0.0.1 1.1.1.1], want [127.0.0.1]"),
-		},
-		"missing-ip-in-crt": {
-			iac: &ipAddressesClaim{ips: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("1.1.1.1")}},
-			crt: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}},
-			err: errors.New("IP Addresses claim failed - got [127.0.0.1], want [127.0.0.1 1.1.1.1]"),
-		},
-		"invalid-matcher-nonempty-ips": {
-			iac: &ipAddressesClaim{ips: []net.IP{}},
-			crt: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}},
-			err: errors.New("IP Addresses claim failed - got [127.0.0.1], want []"),
-		},
-		"ok": {
-			iac: &ipAddressesClaim{ips: []net.IP{net.ParseIP("127.0.0.1")}},
-			crt: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}},
-		},
-		"ok-multiple-identical-ip-entries": {
-			iac: &ipAddressesClaim{ips: []net.IP{net.ParseIP("127.0.0.1")}},
-			crt: &x509.Certificate{IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("127.0.0.1"), net.ParseIP("127.0.0.1")}},
-		},
-	}
-
-	for name, tc := range tests {
-		t.Run(name, func(t *testing.T) {
-			err := tc.iac.Valid(tc.crt)
-			if err != nil {
-				if assert.NotNil(t, tc.err) {
-					assert.Equals(t, tc.err.Error(), err.Error())
-				}
-			} else {
-				assert.Nil(t, tc.err)
-			}
-		})
-	}
-}
-
-func TestDNSNamesClaim_Valid(t *testing.T) {
-	tests := map[string]struct {
-		dnc certClaim
-		crt *x509.Certificate
-		err error
-	}{
-		"unexpected-dns-name-in-crt": {
-			dnc: &dnsNamesClaim{names: []string{"foo"}},
-			crt: &x509.Certificate{DNSNames: []string{"foo", "bar"}},
-			err: errors.New("DNS names claim failed - got [foo bar], want [foo]"),
-		},
-		"ok": {
-			dnc: &dnsNamesClaim{names: []string{"foo", "bar"}},
-			crt: &x509.Certificate{DNSNames: []string{"bar", "foo"}},
-		},
-		"missing-dns-name-in-crt": {
-			dnc: &dnsNamesClaim{names: []string{"foo", "bar"}},
-			crt: &x509.Certificate{DNSNames: []string{"foo"}},
-			err: errors.New("DNS names claim failed - got [foo], want [foo bar]"),
-		},
-		"ok-multiple-identical-dns-entries": {
-			dnc: &dnsNamesClaim{names: []string{"foo"}},
-			crt: &x509.Certificate{DNSNames: []string{"foo", "foo", "foo"}},
-		},
-	}
-
-	for name, tc := range tests {
-		t.Run(name, func(t *testing.T) {
-			err := tc.dnc.Valid(tc.crt)
-			if err != nil {
-				if assert.NotNil(t, tc.err) {
-					assert.Equals(t, tc.err.Error(), err.Error())
-				}
-			} else {
-				assert.Nil(t, tc.err)
-			}
-		})
-	}
-}

+ 62 - 15
authority/config.go

@@ -2,12 +2,15 @@ package authority
 
 import (
 	"encoding/json"
+	"fmt"
 	"net"
 	"os"
 	"time"
 
 	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
 	"github.com/smallstep/certificates/ct"
+	"github.com/smallstep/certificates/db"
 	"github.com/smallstep/cli/crypto/tlsutil"
 	"github.com/smallstep/cli/crypto/x509util"
 )
@@ -26,11 +29,19 @@ var (
 		Renegotiation: false,
 	}
 	defaultDisableRenewal   = false
-	globalProvisionerClaims = ProvisionerClaims{
-		MinTLSDur:      &Duration{5 * time.Minute},
-		MaxTLSDur:      &Duration{24 * time.Hour},
-		DefaultTLSDur:  &Duration{24 * time.Hour},
-		DisableRenewal: &defaultDisableRenewal,
+	defaultEnableSSHCA      = false
+	globalProvisionerClaims = provisioner.Claims{
+		MinTLSDur:         &provisioner.Duration{Duration: 5 * time.Minute}, // TLS certs
+		MaxTLSDur:         &provisioner.Duration{Duration: 24 * time.Hour},
+		DefaultTLSDur:     &provisioner.Duration{Duration: 24 * time.Hour},
+		DisableRenewal:    &defaultDisableRenewal,
+		MinUserSSHDur:     &provisioner.Duration{Duration: 5 * time.Minute}, // User SSH certs
+		MaxUserSSHDur:     &provisioner.Duration{Duration: 24 * time.Hour},
+		DefaultUserSSHDur: &provisioner.Duration{Duration: 4 * time.Hour},
+		MinHostSSHDur:     &provisioner.Duration{Duration: 5 * time.Minute}, // Host SSH certs
+		MaxHostSSHDur:     &provisioner.Duration{Duration: 30 * 24 * time.Hour},
+		DefaultHostSSHDur: &provisioner.Duration{Duration: 30 * 24 * time.Hour},
+		EnableSSHCA:       &defaultEnableSSHCA,
 	}
 )
 
@@ -42,7 +53,9 @@ type Config struct {
 	IntermediateKey  string              `json:"key"`
 	Address          string              `json:"address"`
 	DNSNames         []string            `json:"dnsNames"`
+	SSH              *SSHConfig          `json:"ssh,omitempty"`
 	Logger           json.RawMessage     `json:"logger,omitempty"`
+	DB               *db.Config          `json:"db,omitempty"`
 	Monitoring       json.RawMessage     `json:"monitoring,omitempty"`
 	AuthorityConfig  *AuthConfig         `json:"authority,omitempty"`
 	TLS              *tlsutil.TLSOptions `json:"tls,omitempty"`
@@ -52,16 +65,14 @@ type Config struct {
 
 // AuthConfig represents the configuration options for the authority.
 type AuthConfig struct {
-	Provisioners         []*Provisioner     `json:"provisioners,omitempty"`
-	Template             *x509util.ASN1DN   `json:"template,omitempty"`
-	Claims               *ProvisionerClaims `json:"claims,omitempty"`
-	DisableIssuedAtCheck bool               `json:"disableIssuedAtCheck,omitempty"`
+	Provisioners         provisioner.List    `json:"provisioners"`
+	Template             *x509util.ASN1DN    `json:"template,omitempty"`
+	Claims               *provisioner.Claims `json:"claims,omitempty"`
+	DisableIssuedAtCheck bool                `json:"disableIssuedAtCheck,omitempty"`
 }
 
 // Validate validates the authority configuration.
-func (c *AuthConfig) Validate() error {
-	var err error
-
+func (c *AuthConfig) Validate(audiences provisioner.Audiences) error {
 	if c == nil {
 		return errors.New("authority cannot be undefined")
 	}
@@ -69,20 +80,37 @@ func (c *AuthConfig) Validate() error {
 		return errors.New("authority.provisioners cannot be empty")
 	}
 
-	if c.Claims, err = c.Claims.Init(&globalProvisionerClaims); err != nil {
+	// Merge global and configuration claims
+	claimer, err := provisioner.NewClaimer(c.Claims, globalProvisionerClaims)
+	if err != nil {
 		return err
 	}
+
+	// Initialize provisioners
+	config := provisioner.Config{
+		Claims:    claimer.Claims(),
+		Audiences: audiences,
+	}
 	for _, p := range c.Provisioners {
-		if err := p.Init(c.Claims); err != nil {
+		if err := p.Init(config); err != nil {
 			return err
 		}
 	}
+
 	if c.Template == nil {
 		c.Template = &x509util.ASN1DN{}
 	}
 	return nil
 }
 
+// SSHConfig contains the user and host keys.
+type SSHConfig struct {
+	HostKey          string `json:"hostKey"`
+	UserKey          string `json:"userKey"`
+	AddUserPrincipal string `json:"addUserPrincipal"`
+	AddUserCommand   string `json:"addUserCommand"`
+}
+
 // LoadConfiguration parses the given filename in JSON format and returns the
 // configuration struct.
 func LoadConfiguration(filename string) (*Config, error) {
@@ -163,5 +191,24 @@ func (c *Config) Validate() error {
 		}
 	}
 
-	return c.AuthorityConfig.Validate()
+	return c.AuthorityConfig.Validate(c.getAudiences())
+}
+
+// getAudiences returns the legacy and possible urls without the ports that will
+// be used as the default provisioner audiences. The CA might have proxies in
+// front so we cannot rely on the port.
+func (c *Config) getAudiences() provisioner.Audiences {
+	audiences := provisioner.Audiences{
+		Sign:   []string{legacyAuthority},
+		Revoke: []string{legacyAuthority},
+	}
+
+	for _, name := range c.DNSNames {
+		audiences.Sign = append(audiences.Sign,
+			fmt.Sprintf("https://%s/sign", name), fmt.Sprintf("https://%s/1.0/sign", name))
+		audiences.Revoke = append(audiences.Revoke,
+			fmt.Sprintf("https://%s/revoke", name), fmt.Sprintf("https://%s/1.0/revoke", name))
+	}
+
+	return audiences
 }

+ 22 - 10
authority/config_test.go

@@ -5,6 +5,7 @@ import (
 
 	"github.com/pkg/errors"
 	"github.com/smallstep/assert"
+	"github.com/smallstep/certificates/authority/provisioner"
 	"github.com/smallstep/cli/crypto/tlsutil"
 	"github.com/smallstep/cli/crypto/x509util"
 	stepJOSE "github.com/smallstep/cli/jose"
@@ -17,13 +18,13 @@ func TestConfigValidate(t *testing.T) {
 	clijwk, err := stepJOSE.ParseKey("testdata/secrets/step_cli_key_pub.jwk")
 	assert.FatalError(t, err)
 	ac := &AuthConfig{
-		Provisioners: []*Provisioner{
-			{
+		Provisioners: provisioner.List{
+			&provisioner.JWK{
 				Name: "Max",
 				Type: "JWK",
 				Key:  maxjwk,
 			},
-			{
+			&provisioner.JWK{
 				Name: "step-cli",
 				Type: "JWK",
 				Key:  clijwk,
@@ -229,13 +230,13 @@ func TestAuthConfigValidate(t *testing.T) {
 	assert.FatalError(t, err)
 	clijwk, err := stepJOSE.ParseKey("testdata/secrets/step_cli_key_pub.jwk")
 	assert.FatalError(t, err)
-	p := []*Provisioner{
-		{
+	p := provisioner.List{
+		&provisioner.JWK{
 			Name: "Max",
 			Type: "JWK",
 			Key:  maxjwk,
 		},
-		{
+		&provisioner.JWK{
 			Name: "step-cli",
 			Type: "JWK",
 			Key:  clijwk,
@@ -263,14 +264,25 @@ func TestAuthConfigValidate(t *testing.T) {
 		"fail-invalid-provisioners": func(t *testing.T) AuthConfigValidateTest {
 			return AuthConfigValidateTest{
 				ac: &AuthConfig{
-					Provisioners: []*Provisioner{
-						{Name: "foo", Type: "bar", Key: &jose.JSONWebKey{}},
-						{Name: "foo", Key: &jose.JSONWebKey{}},
+					Provisioners: provisioner.List{
+						&provisioner.JWK{Name: "foo", Type: "bar", Key: &jose.JSONWebKey{}},
+						&provisioner.JWK{Name: "foo", Key: &jose.JSONWebKey{}},
 					},
 				},
 				err: errors.New("provisioner type cannot be empty"),
 			}
 		},
+		"fail-invalid-claims": func(t *testing.T) AuthConfigValidateTest {
+			return AuthConfigValidateTest{
+				ac: &AuthConfig{
+					Provisioners: p,
+					Claims: &provisioner.Claims{
+						MinTLSDur: &provisioner.Duration{Duration: -1},
+					},
+				},
+				err: errors.New("claims: MinTLSCertDuration must be greater than 0"),
+			}
+		},
 		"ok-empty-asn1dn-template": func(t *testing.T) AuthConfigValidateTest {
 			return AuthConfigValidateTest{
 				ac: &AuthConfig{
@@ -293,7 +305,7 @@ func TestAuthConfigValidate(t *testing.T) {
 	for name, get := range tests {
 		t.Run(name, func(t *testing.T) {
 			tc := get(t)
-			err := tc.ac.Validate()
+			err := tc.ac.Validate(provisioner.Audiences{})
 			if err != nil {
 				if assert.NotNil(t, tc.err) {
 					assert.Equals(t, tc.err.Error(), err.Error())

+ 66 - 0
authority/db_test.go

@@ -0,0 +1,66 @@
+package authority
+
+import (
+	"crypto/x509"
+
+	"github.com/smallstep/certificates/db"
+)
+
+type MockAuthDB struct {
+	err              error
+	ret1             interface{}
+	init             func(*db.Config) (db.AuthDB, error)
+	isRevoked        func(string) (bool, error)
+	revoke           func(rci *db.RevokedCertificateInfo) error
+	storeCertificate func(crt *x509.Certificate) error
+	useToken         func(id, tok string) (bool, error)
+	shutdown         func() error
+}
+
+func (m *MockAuthDB) Init(c *db.Config) (db.AuthDB, error) {
+	if m.init != nil {
+		return m.init(c)
+	}
+	if m.ret1 == nil {
+		return nil, m.err
+	}
+	return m.ret1.(*db.DB), m.err
+}
+
+func (m *MockAuthDB) IsRevoked(sn string) (bool, error) {
+	if m.isRevoked != nil {
+		return m.isRevoked(sn)
+	}
+	return m.ret1.(bool), m.err
+}
+
+func (m *MockAuthDB) UseToken(id, tok string) (bool, error) {
+	if m.useToken != nil {
+		return m.useToken(id, tok)
+	}
+	if m.ret1 == nil {
+		return false, m.err
+	}
+	return m.ret1.(bool), m.err
+}
+
+func (m *MockAuthDB) Revoke(rci *db.RevokedCertificateInfo) error {
+	if m.revoke != nil {
+		return m.revoke(rci)
+	}
+	return m.err
+}
+
+func (m *MockAuthDB) StoreCertificate(crt *x509.Certificate) error {
+	if m.storeCertificate != nil {
+		return m.storeCertificate(crt)
+	}
+	return m.err
+}
+
+func (m *MockAuthDB) Shutdown() error {
+	if m.shutdown != nil {
+		return m.shutdown()
+	}
+	return m.err
+}

+ 26 - 2
authority/error.go

@@ -1,16 +1,18 @@
 package authority
 
 import (
+	"encoding/json"
+	"fmt"
 	"net/http"
 )
 
-type context map[string]interface{}
+type apiCtx map[string]interface{}
 
 // Error implements the api.Error interface and adds context to error messages.
 type apiError struct {
 	err     error
 	code    int
-	context context
+	context apiCtx
 }
 
 // Cause implements the errors.Causer interface and returns the original error.
@@ -33,6 +35,12 @@ func (e *apiError) Error() string {
 	return ret
 }
 
+// ErrorResponse represents an error in JSON format.
+type ErrorResponse struct {
+	Status  int    `json:"status"`
+	Message string `json:"message"`
+}
+
 // StatusCode returns an http status code indicating the type and severity of
 // the error.
 func (e *apiError) StatusCode() int {
@@ -41,3 +49,19 @@ func (e *apiError) StatusCode() int {
 	}
 	return e.code
 }
+
+// MarshalJSON implements json.Marshaller interface for the Error struct.
+func (e *apiError) MarshalJSON() ([]byte, error) {
+	return json.Marshal(&ErrorResponse{Status: e.code, Message: http.StatusText(e.code)})
+}
+
+// UnmarshalJSON implements json.Unmarshaler interface for the Error struct.
+func (e *apiError) UnmarshalJSON(data []byte) error {
+	var er ErrorResponse
+	if err := json.Unmarshal(data, &er); err != nil {
+		return err
+	}
+	e.code = er.Status
+	e.err = fmt.Errorf(er.Message)
+	return nil
+}

+ 0 - 144
authority/provisioner.go

@@ -1,144 +0,0 @@
-package authority
-
-import (
-	"time"
-
-	"github.com/pkg/errors"
-	"github.com/smallstep/cli/crypto/x509util"
-
-	jose "gopkg.in/square/go-jose.v2"
-)
-
-// ProvisionerClaims so that individual provisioners can override global claims.
-type ProvisionerClaims struct {
-	globalClaims   *ProvisionerClaims
-	MinTLSDur      *Duration `json:"minTLSCertDuration,omitempty"`
-	MaxTLSDur      *Duration `json:"maxTLSCertDuration,omitempty"`
-	DefaultTLSDur  *Duration `json:"defaultTLSCertDuration,omitempty"`
-	DisableRenewal *bool     `json:"disableRenewal,omitempty"`
-}
-
-// Init initializes and validates the individual provisioner claims.
-func (pc *ProvisionerClaims) Init(global *ProvisionerClaims) (*ProvisionerClaims, error) {
-	if pc == nil {
-		pc = &ProvisionerClaims{}
-	}
-	pc.globalClaims = global
-	err := pc.Validate()
-	return pc, err
-}
-
-// DefaultTLSCertDuration returns the default TLS cert duration for the
-// provisioner. If the default is not set within the provisioner, then the global
-// default from the authority configuration will be used.
-func (pc *ProvisionerClaims) DefaultTLSCertDuration() time.Duration {
-	if pc.DefaultTLSDur == nil || pc.DefaultTLSDur.Duration == 0 {
-		return pc.globalClaims.DefaultTLSCertDuration()
-	}
-	return pc.DefaultTLSDur.Duration
-}
-
-// MinTLSCertDuration returns the minimum TLS cert duration for the provisioner.
-// If the minimum is not set within the provisioner, then the global
-// minimum from the authority configuration will be used.
-func (pc *ProvisionerClaims) MinTLSCertDuration() time.Duration {
-	if pc.MinTLSDur == nil || pc.MinTLSDur.Duration == 0 {
-		return pc.globalClaims.MinTLSCertDuration()
-	}
-	return pc.MinTLSDur.Duration
-}
-
-// MaxTLSCertDuration returns the maximum TLS cert duration for the provisioner.
-// If the maximum is not set within the provisioner, then the global
-// maximum from the authority configuration will be used.
-func (pc *ProvisionerClaims) MaxTLSCertDuration() time.Duration {
-	if pc.MaxTLSDur == nil || pc.MaxTLSDur.Duration == 0 {
-		return pc.globalClaims.MaxTLSCertDuration()
-	}
-	return pc.MaxTLSDur.Duration
-}
-
-// IsDisableRenewal returns if the renewal flow is disabled for the
-// provisioner. If the property is not set within the provisioner, then the
-// global value from the authority configuration will be used.
-func (pc *ProvisionerClaims) IsDisableRenewal() bool {
-	if pc.DisableRenewal == nil {
-		return pc.globalClaims.IsDisableRenewal()
-	}
-	return *pc.DisableRenewal
-}
-
-// Validate validates and modifies the Claims with default values.
-func (pc *ProvisionerClaims) Validate() error {
-	var (
-		min = pc.MinTLSCertDuration()
-		max = pc.MaxTLSCertDuration()
-		def = pc.DefaultTLSCertDuration()
-	)
-	switch {
-	case min == 0:
-		return errors.Errorf("claims: MinTLSCertDuration cannot be empty")
-	case max == 0:
-		return errors.Errorf("claims: MaxTLSCertDuration cannot be empty")
-	case def == 0:
-		return errors.Errorf("claims: DefaultTLSCertDuration cannot be empty")
-	case max < min:
-		return errors.Errorf("claims: MaxCertDuration cannot be less "+
-			"than MinCertDuration: MaxCertDuration - %v, MinCertDuration - %v", max, min)
-	case def < min:
-		return errors.Errorf("claims: DefaultCertDuration cannot be less than MinCertDuration: DefaultCertDuration - %v, MinCertDuration - %v", def, min)
-	case max < def:
-		return errors.Errorf("claims: MaxCertDuration cannot be less than DefaultCertDuration: MaxCertDuration - %v, DefaultCertDuration - %v", max, def)
-	default:
-		return nil
-	}
-}
-
-// Provisioner - authorized entity that can sign tokens necessary for signature requests.
-type Provisioner struct {
-	Name         string             `json:"name,omitempty"`
-	Type         string             `json:"type,omitempty"`
-	Key          *jose.JSONWebKey   `json:"key,omitempty"`
-	EncryptedKey string             `json:"encryptedKey,omitempty"`
-	Claims       *ProvisionerClaims `json:"claims,omitempty"`
-}
-
-// Init initializes and validates a the fields of Provisioner type.
-func (p *Provisioner) Init(global *ProvisionerClaims) error {
-	switch {
-	case p.Name == "":
-		return errors.New("provisioner name cannot be empty")
-
-	case p.Type == "":
-		return errors.New("provisioner type cannot be empty")
-
-	case p.Key == nil:
-		return errors.New("provisioner key cannot be empty")
-	}
-
-	var err error
-	p.Claims, err = p.Claims.Init(global)
-	return err
-}
-
-// getTLSApps returns a list of modifiers and validators that will be applied to
-// the certificate.
-func (p *Provisioner) getTLSApps(so SignOptions) ([]x509util.WithOption, []certClaim, error) {
-	c := p.Claims
-	return []x509util.WithOption{
-			x509util.WithNotBeforeAfterDuration(so.NotBefore,
-				so.NotAfter, c.DefaultTLSCertDuration()),
-			withProvisionerOID(p.Name, p.Key.KeyID),
-		}, []certClaim{
-			&certTemporalClaim{
-				min: c.MinTLSCertDuration(),
-				max: c.MaxTLSCertDuration(),
-			},
-		}, nil
-}
-
-// ID returns the provisioner identifier. The name and credential id should
-// uniquely identify any provisioner.
-func (p *Provisioner) ID() string {
-	return p.Name + ":" + p.Key.KeyID
-}

+ 85 - 0
authority/provisioner/acme.go

@@ -0,0 +1,85 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+
+	"github.com/pkg/errors"
+)
+
+// ACME is the acme provisioner type, an entity that can authorize the ACME
+// provisioning flow.
+type ACME struct {
+	Type    string  `json:"type"`
+	Name    string  `json:"name"`
+	Claims  *Claims `json:"claims,omitempty"`
+	claimer *Claimer
+}
+
+// GetID returns the provisioner unique identifier.
+func (p ACME) GetID() string {
+	return "acme/" + p.Name
+}
+
+// GetTokenID returns the identifier of the token.
+func (p *ACME) GetTokenID(ott string) (string, error) {
+	return "", errors.New("acme provisioner does not implement GetTokenID")
+}
+
+// GetName returns the name of the provisioner.
+func (p *ACME) GetName() string {
+	return p.Name
+}
+
+// GetType returns the type of provisioner.
+func (p *ACME) GetType() Type {
+	return TypeACME
+}
+
+// GetEncryptedKey returns the base provisioner encrypted key if it's defined.
+func (p *ACME) GetEncryptedKey() (string, string, bool) {
+	return "", "", false
+}
+
+// Init initializes and validates the fields of a JWK type.
+func (p *ACME) Init(config Config) (err error) {
+	switch {
+	case p.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case p.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	}
+
+	// Update claims with global ones
+	if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
+		return err
+	}
+
+	return err
+}
+
+// AuthorizeRevoke is not implemented yet for the ACME provisioner.
+func (p *ACME) AuthorizeRevoke(token string) error {
+	return nil
+}
+
+// AuthorizeSign validates the given token.
+func (p *ACME) AuthorizeSign(ctx context.Context, _ string) ([]SignOption, error) {
+	if m := MethodFromContext(ctx); m != SignMethod {
+		return nil, errors.Errorf("unexpected method type %d in context", m)
+	}
+	return []SignOption{
+		profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeACME, p.Name, ""),
+		newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
+		defaultPublicKeyValidator{},
+	}, nil
+}
+
+// AuthorizeRenewal is not implemented for the ACME provisioner.
+func (p *ACME) AuthorizeRenewal(cert *x509.Certificate) error {
+	if p.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
+	}
+	return nil
+}

+ 184 - 0
authority/provisioner/acme_test.go

@@ -0,0 +1,184 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+)
+
+func TestACME_Getters(t *testing.T) {
+	p, err := generateACME()
+	assert.FatalError(t, err)
+	id := "acme/" + p.Name
+	if got := p.GetID(); got != id {
+		t.Errorf("ACME.GetID() = %v, want %v", got, id)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("ACME.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeACME {
+		t.Errorf("ACME.GetType() = %v, want %v", got, TypeACME)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != "" || key != "" || ok == true {
+		t.Errorf("ACME.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, "", "", false)
+	}
+}
+
+func TestACME_Init(t *testing.T) {
+	type ProvisionerValidateTest struct {
+		p   *ACME
+		err error
+	}
+	tests := map[string]func(*testing.T) ProvisionerValidateTest{
+		"fail-empty": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &ACME{},
+				err: errors.New("provisioner type cannot be empty"),
+			}
+		},
+		"fail-empty-name": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p: &ACME{
+					Type: "ACME",
+				},
+				err: errors.New("provisioner name cannot be empty"),
+			}
+		},
+		"fail-empty-type": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &ACME{Name: "foo"},
+				err: errors.New("provisioner type cannot be empty"),
+			}
+		},
+		"fail-bad-claims": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &ACME{Name: "foo", Type: "bar", Claims: &Claims{DefaultTLSDur: &Duration{0}}},
+				err: errors.New("claims: DefaultTLSCertDuration must be greater than 0"),
+			}
+		},
+		"ok": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p: &ACME{Name: "foo", Type: "bar"},
+			}
+		},
+	}
+
+	config := Config{
+		Claims:    globalProvisionerClaims,
+		Audiences: testAudiences,
+	}
+	for name, get := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := get(t)
+			err := tc.p.Init(config)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					assert.Equals(t, tc.err.Error(), err.Error())
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestACME_AuthorizeRevoke(t *testing.T) {
+	p, err := generateACME()
+	assert.FatalError(t, err)
+	assert.Nil(t, p.AuthorizeRevoke(""))
+}
+
+func TestACME_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateACME()
+	assert.FatalError(t, err)
+	p2, err := generateACME()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name string
+		prov *ACME
+		args args
+		err  error
+	}{
+		{"ok", p1, args{nil}, nil},
+		{"fail", p2, args{nil}, errors.Errorf("renew is disabled for provisioner %s", p2.GetID())},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.prov.AuthorizeRenewal(tt.args.cert); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				assert.Nil(t, tt.err)
+			}
+		})
+	}
+}
+
+func TestACME_AuthorizeSign(t *testing.T) {
+	p1, err := generateACME()
+	assert.FatalError(t, err)
+
+	tests := []struct {
+		name   string
+		prov   *ACME
+		method Method
+		err    error
+	}{
+		{"fail/method", p1, SignSSHMethod, errors.New("unexpected method type 1 in context")},
+		{"ok", p1, SignMethod, nil},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), tt.method)
+			if got, err := tt.prov.AuthorizeSign(ctx, ""); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				if assert.NotNil(t, got) {
+					assert.Len(t, 4, got)
+
+					_pdd := got[0]
+					pdd, ok := _pdd.(profileDefaultDuration)
+					assert.True(t, ok)
+					assert.Equals(t, pdd, profileDefaultDuration(86400000000000))
+
+					_peo := got[1]
+					peo, ok := _peo.(*provisionerExtensionOption)
+					assert.True(t, ok)
+					assert.Equals(t, peo.Type, 6)
+					assert.Equals(t, peo.Name, "test@acme-provisioner.com")
+					assert.Equals(t, peo.CredentialID, "")
+					assert.Equals(t, peo.KeyValuePairs, nil)
+
+					_vv := got[2]
+					vv, ok := _vv.(*validityValidator)
+					assert.True(t, ok)
+					assert.Equals(t, vv.min, time.Duration(300000000000))
+					assert.Equals(t, vv.max, time.Duration(86400000000000))
+
+					_dpkv := got[3]
+					_, ok = _dpkv.(defaultPublicKeyValidator)
+					assert.True(t, ok)
+				}
+			}
+		})
+	}
+}

+ 478 - 0
authority/provisioner/aws.go

@@ -0,0 +1,478 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/hex"
+	"encoding/json"
+	"encoding/pem"
+	"fmt"
+	"io/ioutil"
+	"net"
+	"net/http"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+// awsIssuer is the string used as issuer in the generated tokens.
+const awsIssuer = "ec2.amazonaws.com"
+
+// awsIdentityURL is the url used to retrieve the instance identity document.
+const awsIdentityURL = "http://169.254.169.254/latest/dynamic/instance-identity/document"
+
+// awsSignatureURL is the url used to retrieve the instance identity signature.
+const awsSignatureURL = "http://169.254.169.254/latest/dynamic/instance-identity/signature"
+
+// awsCertificate is the certificate used to validate the instance identity
+// signature.
+const awsCertificate = `-----BEGIN CERTIFICATE-----
+MIIDIjCCAougAwIBAgIJAKnL4UEDMN/FMA0GCSqGSIb3DQEBBQUAMGoxCzAJBgNV
+BAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdTZWF0dGxlMRgw
+FgYDVQQKEw9BbWF6b24uY29tIEluYy4xGjAYBgNVBAMTEWVjMi5hbWF6b25hd3Mu
+Y29tMB4XDTE0MDYwNTE0MjgwMloXDTI0MDYwNTE0MjgwMlowajELMAkGA1UEBhMC
+VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1NlYXR0bGUxGDAWBgNV
+BAoTD0FtYXpvbi5jb20gSW5jLjEaMBgGA1UEAxMRZWMyLmFtYXpvbmF3cy5jb20w
+gZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAIe9GN//SRK2knbjySG0ho3yqQM3
+e2TDhWO8D2e8+XZqck754gFSo99AbT2RmXClambI7xsYHZFapbELC4H91ycihvrD
+jbST1ZjkLQgga0NE1q43eS68ZeTDccScXQSNivSlzJZS8HJZjgqzBlXjZftjtdJL
+XeE4hwvo0sD4f3j9AgMBAAGjgc8wgcwwHQYDVR0OBBYEFCXWzAgVyrbwnFncFFIs
+77VBdlE4MIGcBgNVHSMEgZQwgZGAFCXWzAgVyrbwnFncFFIs77VBdlE4oW6kbDBq
+MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHU2Vh
+dHRsZTEYMBYGA1UEChMPQW1hem9uLmNvbSBJbmMuMRowGAYDVQQDExFlYzIuYW1h
+em9uYXdzLmNvbYIJAKnL4UEDMN/FMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEF
+BQADgYEAFYcz1OgEhQBXIwIdsgCOS8vEtiJYF+j9uO6jz7VOmJqO+pRlAbRlvY8T
+C1haGgSI/A1uZUKs/Zfnph0oEI0/hu1IIJ/SKBDtN5lvmZ/IzbOPIJWirlsllQIQ
+7zvWbGd9c9+Rm3p04oTvhup99la7kZqevJK0QRdD/6NpCKsqP/0=
+-----END CERTIFICATE-----`
+
+// awsSignatureAlgorithm is the signature algorithm used to verify the identity
+// document signature.
+const awsSignatureAlgorithm = x509.SHA256WithRSA
+
+type awsConfig struct {
+	identityURL        string
+	signatureURL       string
+	certificate        *x509.Certificate
+	signatureAlgorithm x509.SignatureAlgorithm
+}
+
+func newAWSConfig() (*awsConfig, error) {
+	block, _ := pem.Decode([]byte(awsCertificate))
+	if block == nil || block.Type != "CERTIFICATE" {
+		return nil, errors.New("error decoding AWS certificate")
+	}
+	cert, err := x509.ParseCertificate(block.Bytes)
+	if err != nil {
+		return nil, errors.Wrap(err, "error parsing AWS certificate")
+	}
+	return &awsConfig{
+		identityURL:        awsIdentityURL,
+		signatureURL:       awsSignatureURL,
+		certificate:        cert,
+		signatureAlgorithm: awsSignatureAlgorithm,
+	}, nil
+}
+
+type awsPayload struct {
+	jose.Claims
+	Amazon   awsAmazonPayload `json:"amazon"`
+	SANs     []string         `json:"sans"`
+	document awsInstanceIdentityDocument
+}
+
+type awsAmazonPayload struct {
+	Document  []byte `json:"document"`
+	Signature []byte `json:"signature"`
+}
+
+type awsInstanceIdentityDocument struct {
+	AccountID          string    `json:"accountId"`
+	Architecture       string    `json:"architecture"`
+	AvailabilityZone   string    `json:"availabilityZone"`
+	BillingProducts    []string  `json:"billingProducts"`
+	DevpayProductCodes []string  `json:"devpayProductCodes"`
+	ImageID            string    `json:"imageId"`
+	InstanceID         string    `json:"instanceId"`
+	InstanceType       string    `json:"instanceType"`
+	KernelID           string    `json:"kernelId"`
+	PendingTime        time.Time `json:"pendingTime"`
+	PrivateIP          string    `json:"privateIp"`
+	RamdiskID          string    `json:"ramdiskId"`
+	Region             string    `json:"region"`
+	Version            string    `json:"version"`
+}
+
+// AWS is the provisioner that supports identity tokens created from the Amazon
+// Web Services Instance Identity Documents.
+//
+// If DisableCustomSANs is true, only the internal DNS and IP will be added as a
+// SAN. By default it will accept any SAN in the CSR.
+//
+// If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
+// with the same instance will be accepted. By default only the first request
+// will be accepted.
+//
+// If InstanceAge is set, only the instances with a pendingTime within the given
+// period will be accepted.
+//
+// Amazon Identity docs are available at
+// https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-identity-documents.html
+type AWS struct {
+	Type                   string   `json:"type"`
+	Name                   string   `json:"name"`
+	Accounts               []string `json:"accounts"`
+	DisableCustomSANs      bool     `json:"disableCustomSANs"`
+	DisableTrustOnFirstUse bool     `json:"disableTrustOnFirstUse"`
+	InstanceAge            Duration `json:"instanceAge,omitempty"`
+	Claims                 *Claims  `json:"claims,omitempty"`
+	claimer                *Claimer
+	config                 *awsConfig
+	audiences              Audiences
+}
+
+// GetID returns the provisioner unique identifier.
+func (p *AWS) GetID() string {
+	return "aws/" + p.Name
+}
+
+// GetTokenID returns the identifier of the token.
+func (p *AWS) GetTokenID(token string) (string, error) {
+	payload, err := p.authorizeToken(token)
+	if err != nil {
+		return "", err
+	}
+	// If TOFU is disabled create an ID for the token, so it cannot be reused.
+	// The timestamps, document and signatures should be mostly unique.
+	if p.DisableTrustOnFirstUse {
+		sum := sha256.Sum256([]byte(token))
+		return strings.ToLower(hex.EncodeToString(sum[:])), nil
+	}
+	return payload.ID, nil
+}
+
+// GetName returns the name of the provisioner.
+func (p *AWS) GetName() string {
+	return p.Name
+}
+
+// GetType returns the type of provisioner.
+func (p *AWS) GetType() Type {
+	return TypeAWS
+}
+
+// GetEncryptedKey is not available in an AWS provisioner.
+func (p *AWS) GetEncryptedKey() (kid string, key string, ok bool) {
+	return "", "", false
+}
+
+// GetIdentityToken retrieves the identity document and it's signature and
+// generates a token with them.
+func (p *AWS) GetIdentityToken(subject, caURL string) (string, error) {
+	// Initialize the config if this method is used from the cli.
+	if err := p.assertConfig(); err != nil {
+		return "", err
+	}
+
+	var idoc awsInstanceIdentityDocument
+	doc, err := p.readURL(p.config.identityURL)
+	if err != nil {
+		return "", errors.Wrap(err, "error retrieving identity document, are you in an AWS VM?")
+	}
+	if err := json.Unmarshal(doc, &idoc); err != nil {
+		return "", errors.Wrap(err, "error unmarshaling identity document")
+	}
+	sig, err := p.readURL(p.config.signatureURL)
+	if err != nil {
+		return "", errors.Wrap(err, "error retrieving identity document signature, are you in an AWS VM?")
+	}
+	signature, err := base64.StdEncoding.DecodeString(string(sig))
+	if err != nil {
+		return "", errors.Wrap(err, "error decoding identity document signature")
+	}
+	if err := p.checkSignature(doc, signature); err != nil {
+		return "", err
+	}
+
+	audience, err := generateSignAudience(caURL, p.GetID())
+	if err != nil {
+		return "", err
+	}
+
+	// Create unique ID for Trust On First Use (TOFU). Only the first instance
+	// per provisioner is allowed as we don't have a way to trust the given
+	// sans.
+	unique := fmt.Sprintf("%s.%s", p.GetID(), idoc.InstanceID)
+	sum := sha256.Sum256([]byte(unique))
+
+	// Create a JWT from the identity document
+	signer, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.HS256, Key: signature},
+		new(jose.SignerOptions).WithType("JWT"),
+	)
+	if err != nil {
+		return "", errors.Wrap(err, "error creating signer")
+	}
+
+	now := time.Now()
+	payload := awsPayload{
+		Claims: jose.Claims{
+			Issuer:    awsIssuer,
+			Subject:   subject,
+			Audience:  []string{audience},
+			Expiry:    jose.NewNumericDate(now.Add(5 * time.Minute)),
+			NotBefore: jose.NewNumericDate(now),
+			IssuedAt:  jose.NewNumericDate(now),
+			ID:        strings.ToLower(hex.EncodeToString(sum[:])),
+		},
+		Amazon: awsAmazonPayload{
+			Document:  doc,
+			Signature: signature,
+		},
+	}
+
+	tok, err := jose.Signed(signer).Claims(payload).CompactSerialize()
+	if err != nil {
+		return "", errors.Wrap(err, "error serialiazing token")
+	}
+
+	return tok, nil
+}
+
+// Init validates and initializes the AWS provisioner.
+func (p *AWS) Init(config Config) (err error) {
+	switch {
+	case p.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case p.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	case p.InstanceAge.Value() < 0:
+		return errors.New("provisioner instanceAge cannot be negative")
+	}
+	// Update claims with global ones
+	if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
+		return err
+	}
+	// Add default config
+	if p.config, err = newAWSConfig(); err != nil {
+		return err
+	}
+	p.audiences = config.Audiences.WithFragment(p.GetID())
+	return nil
+}
+
+// AuthorizeSign validates the given token and returns the sign options that
+// will be used on certificate creation.
+func (p *AWS) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	payload, err := p.authorizeToken(token)
+	if err != nil {
+		return nil, err
+	}
+
+	// Check for the sign ssh method, default to sign X.509
+	if m := MethodFromContext(ctx); m == SignSSHMethod {
+		if p.claimer.IsSSHCAEnabled() == false {
+			return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
+		}
+		return p.authorizeSSHSign(payload)
+	}
+
+	doc := payload.document
+	// Enforce known CN and default DNS and IP if configured.
+	// By default we'll accept the CN and SANs in the CSR.
+	// There's no way to trust them other than TOFU.
+	var so []SignOption
+	if p.DisableCustomSANs {
+		so = append(so, dnsNamesValidator([]string{
+			fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
+		}))
+		so = append(so, ipAddressesValidator([]net.IP{
+			net.ParseIP(doc.PrivateIP),
+		}))
+	}
+
+	return append(so,
+		defaultPublicKeyValidator{},
+		commonNameValidator(payload.Claims.Subject),
+		profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeAWS, p.Name, doc.AccountID, "InstanceID", doc.InstanceID),
+		newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
+	), nil
+}
+
+// AuthorizeRenewal returns an error if the renewal is disabled.
+func (p *AWS) AuthorizeRenewal(cert *x509.Certificate) error {
+	if p.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
+	}
+	return nil
+}
+
+// AuthorizeRevoke returns an error because revoke is not supported on AWS
+// provisioners.
+func (p *AWS) AuthorizeRevoke(token string) error {
+	return errors.New("revoke is not supported on a AWS provisioner")
+}
+
+// assertConfig initializes the config if it has not been initialized
+func (p *AWS) assertConfig() (err error) {
+	if p.config != nil {
+		return
+	}
+	p.config, err = newAWSConfig()
+	return err
+}
+
+// checkSignature returns an error if the signature is not valid.
+func (p *AWS) checkSignature(signed, signature []byte) error {
+	if err := p.config.certificate.CheckSignature(p.config.signatureAlgorithm, signed, signature); err != nil {
+		return errors.Wrap(err, "error validating identity document signature")
+	}
+	return nil
+}
+
+// readURL does a GET request to the given url and returns the body. It's not
+// using pkg/errors to avoid verbose errors, the caller should use it and write
+// the appropriate error.
+func (p *AWS) readURL(url string) ([]byte, error) {
+	r, err := http.Get(url)
+	if err != nil {
+		return nil, err
+	}
+	defer r.Body.Close()
+	b, err := ioutil.ReadAll(r.Body)
+	if err != nil {
+		return nil, err
+	}
+	return b, nil
+}
+
+// authorizeToken performs common jwt authorization actions and returns the
+// claims for case specific downstream parsing.
+// e.g. a Sign request will auth/validate different fields than a Revoke request.
+func (p *AWS) authorizeToken(token string) (*awsPayload, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing token")
+	}
+	if len(jwt.Headers) == 0 {
+		return nil, errors.New("error parsing token: header is missing")
+	}
+
+	var unsafeClaims awsPayload
+	if err := jwt.UnsafeClaimsWithoutVerification(&unsafeClaims); err != nil {
+		return nil, errors.Wrap(err, "error unmarshaling claims")
+	}
+
+	var payload awsPayload
+	if err := jwt.Claims(unsafeClaims.Amazon.Signature, &payload); err != nil {
+		return nil, errors.Wrap(err, "error verifying claims")
+	}
+
+	// Validate identity document signature
+	if err := p.checkSignature(payload.Amazon.Document, payload.Amazon.Signature); err != nil {
+		return nil, err
+	}
+
+	var doc awsInstanceIdentityDocument
+	if err := json.Unmarshal(payload.Amazon.Document, &doc); err != nil {
+		return nil, errors.Wrap(err, "error unmarshaling identity document")
+	}
+
+	switch {
+	case doc.AccountID == "":
+		return nil, errors.New("identity document accountId cannot be empty")
+	case doc.InstanceID == "":
+		return nil, errors.New("identity document instanceId cannot be empty")
+	case doc.PrivateIP == "":
+		return nil, errors.New("identity document privateIp cannot be empty")
+	case doc.Region == "":
+		return nil, errors.New("identity document region cannot be empty")
+	}
+
+	// According to "rfc7519 JSON Web Token" acceptable skew should be no
+	// more than a few minutes.
+	now := time.Now().UTC()
+	if err = payload.ValidateWithLeeway(jose.Expected{
+		Issuer: awsIssuer,
+		Time:   now,
+	}, time.Minute); err != nil {
+		return nil, errors.Wrapf(err, "invalid token")
+	}
+
+	// validate audiences with the defaults
+	if !matchesAudience(payload.Audience, p.audiences.Sign) {
+		return nil, errors.New("invalid token: invalid audience claim (aud)")
+	}
+
+	// Validate subject, it has to be known if disableCustomSANs is enabled
+	if p.DisableCustomSANs {
+		if payload.Subject != doc.InstanceID &&
+			payload.Subject != doc.PrivateIP &&
+			payload.Subject != fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region) {
+			return nil, errors.New("invalid token: invalid subject claim (sub)")
+		}
+	}
+
+	// validate accounts
+	if len(p.Accounts) > 0 {
+		var found bool
+		for _, sa := range p.Accounts {
+			if sa == doc.AccountID {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return nil, errors.New("invalid identity document: accountId is not valid")
+		}
+	}
+
+	// validate instance age
+	if d := p.InstanceAge.Value(); d > 0 {
+		if now.Sub(doc.PendingTime) > d {
+			return nil, errors.New("identity document pendingTime is too old")
+		}
+	}
+
+	payload.document = doc
+	return &payload, nil
+}
+
+// authorizeSSHSign returns the list of SignOption for a SignSSH request.
+func (p *AWS) authorizeSSHSign(claims *awsPayload) ([]SignOption, error) {
+	doc := claims.document
+
+	signOptions := []SignOption{
+		// set the key id to the token subject
+		sshCertificateKeyIDModifier(claims.Subject),
+	}
+
+	// Default to host + known IPs/hostnames
+	defaults := SSHOptions{
+		CertType: SSHHostCert,
+		Principals: []string{
+			doc.PrivateIP,
+			fmt.Sprintf("ip-%s.%s.compute.internal", strings.Replace(doc.PrivateIP, ".", "-", -1), doc.Region),
+		},
+	}
+	// Validate user options
+	signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
+	// Set defaults if not given as user options
+	signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
+
+	return append(signOptions,
+		// set the default extensions
+		&sshDefaultExtensionModifier{},
+		// checks the validity bounds, and set the validity if has not been set
+		&sshCertificateValidityModifier{p.claimer},
+		// validate public key
+		&sshDefaultPublicKeyValidator{},
+		// require all the fields in the SSH certificate
+		&sshCertificateDefaultValidator{},
+	), nil
+}

+ 510 - 0
authority/provisioner/aws_test.go

@@ -0,0 +1,510 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/hex"
+	"encoding/pem"
+	"fmt"
+	"net/url"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/jose"
+)
+
+func TestAWS_Getters(t *testing.T) {
+	p, err := generateAWS()
+	assert.FatalError(t, err)
+	aud := "aws/" + p.Name
+	if got := p.GetID(); got != aud {
+		t.Errorf("AWS.GetID() = %v, want %v", got, aud)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("AWS.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeAWS {
+		t.Errorf("AWS.GetType() = %v, want %v", got, TypeAWS)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != "" || key != "" || ok == true {
+		t.Errorf("AWS.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, "", "", false)
+	}
+}
+
+func TestAWS_GetTokenID(t *testing.T) {
+	p1, srv, err := generateAWSWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	p2, err := generateAWS()
+	assert.FatalError(t, err)
+	p2.Accounts = p1.Accounts
+	p2.config = p1.config
+	p2.DisableTrustOnFirstUse = true
+
+	t1, err := p1.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+	_, claims, err := parseAWSToken(t1)
+	assert.FatalError(t, err)
+	sum := sha256.Sum256([]byte(fmt.Sprintf("%s.%s", p1.GetID(), claims.document.InstanceID)))
+	w1 := strings.ToLower(hex.EncodeToString(sum[:]))
+
+	t2, err := p2.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+	sum = sha256.Sum256([]byte(t2))
+	w2 := strings.ToLower(hex.EncodeToString(sum[:]))
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		aws     *AWS
+		args    args
+		want    string
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, w1, false},
+		{"ok no TOFU", p2, args{t2}, w2, false},
+		{"fail", p1, args{"bad-token"}, "", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.aws.GetTokenID(tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("AWS.GetTokenID() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("AWS.GetTokenID() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestAWS_GetIdentityToken(t *testing.T) {
+	p1, srv, err := generateAWSWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	p2, err := generateAWS()
+	assert.FatalError(t, err)
+	p2.Accounts = p1.Accounts
+	p2.config.identityURL = srv.URL + "/bad-document"
+	p2.config.signatureURL = p1.config.signatureURL
+
+	p3, err := generateAWS()
+	assert.FatalError(t, err)
+	p3.Accounts = p1.Accounts
+	p3.config.signatureURL = srv.URL
+	p3.config.identityURL = p1.config.identityURL
+
+	p4, err := generateAWS()
+	assert.FatalError(t, err)
+	p4.Accounts = p1.Accounts
+	p4.config.signatureURL = srv.URL + "/bad-signature"
+	p4.config.identityURL = p1.config.identityURL
+
+	p5, err := generateAWS()
+	assert.FatalError(t, err)
+	p5.Accounts = p1.Accounts
+	p5.config.identityURL = "https://1234.1234.1234.1234"
+	p5.config.signatureURL = p1.config.signatureURL
+
+	p6, err := generateAWS()
+	assert.FatalError(t, err)
+	p6.Accounts = p1.Accounts
+	p6.config.identityURL = p1.config.identityURL
+	p6.config.signatureURL = "https://1234.1234.1234.1234"
+
+	p7, err := generateAWS()
+	assert.FatalError(t, err)
+	p7.Accounts = p1.Accounts
+	p7.config.identityURL = srv.URL + "/bad-json"
+	p7.config.signatureURL = p1.config.signatureURL
+
+	caURL := "https://ca.smallstep.com"
+	u, err := url.Parse(caURL)
+	assert.FatalError(t, err)
+
+	type args struct {
+		subject string
+		caURL   string
+	}
+	tests := []struct {
+		name    string
+		aws     *AWS
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{"foo.local", caURL}, false},
+		{"fail ca url", p1, args{"foo.local", "://ca.smallstep.com"}, true},
+		{"fail identityURL", p2, args{"foo.local", caURL}, true},
+		{"fail signatureURL", p3, args{"foo.local", caURL}, true},
+		{"fail signature", p4, args{"foo.local", caURL}, true},
+		{"fail read identityURL", p5, args{"foo.local", caURL}, true},
+		{"fail read signatureURL", p6, args{"foo.local", caURL}, true},
+		{"fail unmarshal identityURL", p7, args{"foo.local", caURL}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.aws.GetIdentityToken(tt.args.subject, tt.args.caURL)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("AWS.GetIdentityToken() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if tt.wantErr == false {
+				_, c, err := parseAWSToken(got)
+				if assert.NoError(t, err) {
+					assert.Equals(t, awsIssuer, c.Issuer)
+					assert.Equals(t, tt.args.subject, c.Subject)
+					assert.Equals(t, jose.Audience{u.ResolveReference(&url.URL{Path: "/1.0/sign", Fragment: tt.aws.GetID()}).String()}, c.Audience)
+					assert.Equals(t, tt.aws.Accounts[0], c.document.AccountID)
+					err = tt.aws.config.certificate.CheckSignature(
+						tt.aws.config.signatureAlgorithm, c.Amazon.Document, c.Amazon.Signature)
+					assert.NoError(t, err)
+				}
+			}
+		})
+	}
+}
+
+func TestAWS_Init(t *testing.T) {
+	config := Config{
+		Claims: globalProvisionerClaims,
+	}
+	badClaims := &Claims{
+		DefaultTLSDur: &Duration{0},
+	}
+	zero := Duration{Duration: 0}
+
+	type fields struct {
+		Type                   string
+		Name                   string
+		Accounts               []string
+		DisableCustomSANs      bool
+		DisableTrustOnFirstUse bool
+		InstanceAge            Duration
+		Claims                 *Claims
+	}
+	type args struct {
+		config Config
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		args    args
+		wantErr bool
+	}{
+		{"ok", fields{"AWS", "name", []string{"account"}, false, false, zero, nil}, args{config}, false},
+		{"ok", fields{"AWS", "name", []string{"account"}, true, true, Duration{Duration: 1 * time.Minute}, nil}, args{config}, false},
+		{"fail type ", fields{"", "name", []string{"account"}, false, false, zero, nil}, args{config}, true},
+		{"fail name", fields{"AWS", "", []string{"account"}, false, false, zero, nil}, args{config}, true},
+		{"bad instance age", fields{"AWS", "name", []string{"account"}, false, false, Duration{Duration: -1 * time.Minute}, nil}, args{config}, true},
+		{"fail claims", fields{"AWS", "name", []string{"account"}, false, false, zero, badClaims}, args{config}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			p := &AWS{
+				Type:                   tt.fields.Type,
+				Name:                   tt.fields.Name,
+				Accounts:               tt.fields.Accounts,
+				DisableCustomSANs:      tt.fields.DisableCustomSANs,
+				DisableTrustOnFirstUse: tt.fields.DisableTrustOnFirstUse,
+				InstanceAge:            tt.fields.InstanceAge,
+				Claims:                 tt.fields.Claims,
+			}
+			if err := p.Init(tt.args.config); (err != nil) != tt.wantErr {
+				t.Errorf("AWS.Init() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestAWS_AuthorizeSign(t *testing.T) {
+	p1, srv, err := generateAWSWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	p2, err := generateAWS()
+	assert.FatalError(t, err)
+	p2.Accounts = p1.Accounts
+	p2.config = p1.config
+	p2.DisableCustomSANs = true
+	p2.InstanceAge = Duration{1 * time.Minute}
+
+	p3, err := generateAWS()
+	assert.FatalError(t, err)
+	p3.config = p1.config
+
+	t1, err := p1.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+	t2, err := p2.GetIdentityToken("instance-id", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+	assert.FatalError(t, err)
+	t3, err := p3.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+
+	// Alternative common names with DisableCustomSANs = true
+	t2PrivateIP, err := p2.GetIdentityToken("127.0.0.1", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+	t2Hostname, err := p2.GetIdentityToken("ip-127-0-0-1.us-west-1.compute.internal", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+
+	block, _ := pem.Decode([]byte(awsTestKey))
+	if block == nil || block.Type != "RSA PRIVATE KEY" {
+		t.Fatal("error decoding AWS key")
+	}
+	key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
+	assert.FatalError(t, err)
+
+	badKey, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	t4, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failSubject, err := generateAWSToken(
+		"bad-subject", awsIssuer, p2.GetID(), p2.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failIssuer, err := generateAWSToken(
+		"instance-id", "bad-issuer", p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failAudience, err := generateAWSToken(
+		"instance-id", awsIssuer, "bad-audience", p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failAccount, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), "", "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failInstanceID, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "",
+		"127.0.0.1", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failPrivateIP, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"", "us-west-1", time.Now(), key)
+	assert.FatalError(t, err)
+	failRegion, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "", time.Now(), key)
+	assert.FatalError(t, err)
+	failExp, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now().Add(-360*time.Second), key)
+	assert.FatalError(t, err)
+	failNbf, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now().Add(360*time.Second), key)
+	assert.FatalError(t, err)
+	failKey, err := generateAWSToken(
+		"instance-id", awsIssuer, p1.GetID(), p1.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now(), badKey)
+	assert.FatalError(t, err)
+	failInstanceAge, err := generateAWSToken(
+		"instance-id", awsIssuer, p2.GetID(), p2.Accounts[0], "instance-id",
+		"127.0.0.1", "us-west-1", time.Now().Add(-1*time.Minute), key)
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		aws     *AWS
+		args    args
+		wantLen int
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, 5, false},
+		{"ok", p2, args{t2}, 7, false},
+		{"ok", p2, args{t2Hostname}, 7, false},
+		{"ok", p2, args{t2PrivateIP}, 7, false},
+		{"ok", p1, args{t4}, 5, false},
+		{"fail account", p3, args{t3}, 0, true},
+		{"fail token", p1, args{"token"}, 0, true},
+		{"fail subject", p1, args{failSubject}, 0, true},
+		{"fail issuer", p1, args{failIssuer}, 0, true},
+		{"fail audience", p1, args{failAudience}, 0, true},
+		{"fail account", p1, args{failAccount}, 0, true},
+		{"fail instanceID", p1, args{failInstanceID}, 0, true},
+		{"fail privateIP", p1, args{failPrivateIP}, 0, true},
+		{"fail region", p1, args{failRegion}, 0, true},
+		{"fail exp", p1, args{failExp}, 0, true},
+		{"fail nbf", p1, args{failNbf}, 0, true},
+		{"fail key", p1, args{failKey}, 0, true},
+		{"fail instance age", p2, args{failInstanceAge}, 0, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignMethod)
+			got, err := tt.aws.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("AWS.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			assert.Len(t, tt.wantLen, got)
+		})
+	}
+}
+
+func TestAWS_AuthorizeSign_SSH(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	p1, srv, err := generateAWSWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	t1, err := p1.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	pub := key.Public().Key
+	rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
+	assert.FatalError(t, err)
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"127.0.0.1", "ip-127-0-0-1.us-west-1.compute.internal"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+	expectedHostOptionsIP := &SSHOptions{
+		CertType: "host", Principals: []string{"127.0.0.1"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+	expectedHostOptionsHostname := &SSHOptions{
+		CertType: "host", Principals: []string{"ip-127-0-0-1.us-west-1.compute.internal"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+
+	type args struct {
+		token   string
+		sshOpts SSHOptions
+		key     interface{}
+	}
+	tests := []struct {
+		name        string
+		aws         *AWS
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"ok", p1, args{t1, SSHOptions{}, pub}, expectedHostOptions, false, false},
+		{"ok-rsa2048", p1, args{t1, SSHOptions{}, rsa2048.Public()}, expectedHostOptions, false, false},
+		{"ok-type", p1, args{t1, SSHOptions{CertType: "host"}, pub}, expectedHostOptions, false, false},
+		{"ok-principals", p1, args{t1, SSHOptions{Principals: []string{"127.0.0.1", "ip-127-0-0-1.us-west-1.compute.internal"}}, pub}, expectedHostOptions, false, false},
+		{"ok-principal-ip", p1, args{t1, SSHOptions{Principals: []string{"127.0.0.1"}}, pub}, expectedHostOptionsIP, false, false},
+		{"ok-principal-hostname", p1, args{t1, SSHOptions{Principals: []string{"ip-127-0-0-1.us-west-1.compute.internal"}}, pub}, expectedHostOptionsHostname, false, false},
+		{"ok-options", p1, args{t1, SSHOptions{CertType: "host", Principals: []string{"127.0.0.1", "ip-127-0-0-1.us-west-1.compute.internal"}}, pub}, expectedHostOptions, false, false},
+		{"fail-rsa1024", p1, args{t1, SSHOptions{}, rsa1024.Public()}, expectedHostOptions, false, true},
+		{"fail-type", p1, args{t1, SSHOptions{CertType: "user"}, pub}, nil, false, true},
+		{"fail-principal", p1, args{t1, SSHOptions{Principals: []string{"smallstep.com"}}, pub}, nil, false, true},
+		{"fail-extra-principal", p1, args{t1, SSHOptions{Principals: []string{"127.0.0.1", "ip-127-0-0-1.us-west-1.compute.internal", "smallstep.com"}}, pub}, nil, false, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			got, err := tt.aws.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("AWS.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else if assert.NotNil(t, got) {
+				cert, err := signSSHCertificate(tt.args.key, tt.args.sshOpts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}
+func TestAWS_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateAWS()
+	assert.FatalError(t, err)
+	p2, err := generateAWS()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		aws     *AWS
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{nil}, false},
+		{"fail", p2, args{nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.aws.AuthorizeRenewal(tt.args.cert); (err != nil) != tt.wantErr {
+				t.Errorf("AWS.AuthorizeRenewal() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestAWS_AuthorizeRevoke(t *testing.T) {
+	p1, srv, err := generateAWSWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	t1, err := p1.GetIdentityToken("foo.local", "https://ca.smallstep.com")
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		aws     *AWS
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, true}, // revoke is disabled
+		{"fail", p1, args{"token"}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.aws.AuthorizeRevoke(tt.args.token); (err != nil) != tt.wantErr {
+				t.Errorf("AWS.AuthorizeRevoke() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}

+ 342 - 0
authority/provisioner/azure.go

@@ -0,0 +1,342 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/hex"
+	"encoding/json"
+	"io/ioutil"
+	"net/http"
+	"regexp"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+// azureOIDCBaseURL is the base discovery url for Microsoft Azure tokens.
+const azureOIDCBaseURL = "https://login.microsoftonline.com"
+
+// azureIdentityTokenURL is the URL to get the identity token for an instance.
+const azureIdentityTokenURL = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.azure.com%2F"
+
+// azureDefaultAudience is the default audience used.
+const azureDefaultAudience = "https://management.azure.com/"
+
+// azureXMSMirIDRegExp is the regular expression used to parse the xms_mirid claim.
+// Using case insensitive as resourceGroups appears as resourcegroups.
+var azureXMSMirIDRegExp = regexp.MustCompile(`(?i)^/subscriptions/([^/]+)/resourceGroups/([^/]+)/providers/Microsoft.Compute/virtualMachines/([^/]+)$`)
+
+type azureConfig struct {
+	oidcDiscoveryURL string
+	identityTokenURL string
+}
+
+func newAzureConfig(tenantID string) *azureConfig {
+	return &azureConfig{
+		oidcDiscoveryURL: azureOIDCBaseURL + "/" + tenantID + "/.well-known/openid-configuration",
+		identityTokenURL: azureIdentityTokenURL,
+	}
+}
+
+type azureIdentityToken struct {
+	AccessToken  string `json:"access_token"`
+	RefreshToken string `json:"refresh_token"`
+	ClientID     string `json:"client_id"`
+	ExpiresIn    int64  `json:"expires_in,string"`
+	ExpiresOn    int64  `json:"expires_on,string"`
+	ExtExpiresIn int64  `json:"ext_expires_in,string"`
+	NotBefore    int64  `json:"not_before,string"`
+	Resource     string `json:"resource"`
+	TokenType    string `json:"token_type"`
+}
+
+type azurePayload struct {
+	jose.Claims
+	AppID            string `json:"appid"`
+	AppIDAcr         string `json:"appidacr"`
+	IdentityProvider string `json:"idp"`
+	ObjectID         string `json:"oid"`
+	TenantID         string `json:"tid"`
+	Version          string `json:"ver"`
+	XMSMirID         string `json:"xms_mirid"`
+}
+
+// Azure is the provisioner that supports identity tokens created from the
+// Microsoft Azure Instance Metadata service.
+//
+// The default audience is "https://management.azure.com/".
+//
+// If DisableCustomSANs is true, only the internal DNS and IP will be added as a
+// SAN. By default it will accept any SAN in the CSR.
+//
+// If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
+// with the same instance will be accepted. By default only the first request
+// will be accepted.
+//
+// Microsoft Azure identity docs are available at
+// https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token
+// and https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service
+type Azure struct {
+	Type                   string   `json:"type"`
+	Name                   string   `json:"name"`
+	TenantID               string   `json:"tenantId"`
+	ResourceGroups         []string `json:"resourceGroups"`
+	Audience               string   `json:"audience,omitempty"`
+	DisableCustomSANs      bool     `json:"disableCustomSANs"`
+	DisableTrustOnFirstUse bool     `json:"disableTrustOnFirstUse"`
+	Claims                 *Claims  `json:"claims,omitempty"`
+	claimer                *Claimer
+	config                 *azureConfig
+	oidcConfig             openIDConfiguration
+	keyStore               *keyStore
+}
+
+// GetID returns the provisioner unique identifier.
+func (p *Azure) GetID() string {
+	return p.TenantID
+}
+
+// GetTokenID returns the identifier of the token. The default value for Azure
+// the SHA256 of "xms_mirid", but if DisableTrustOnFirstUse is set to true, then
+// it will be the token kid.
+func (p *Azure) GetTokenID(token string) (string, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return "", errors.Wrap(err, "error parsing token")
+	}
+
+	// Get claims w/out verification. We need to look up the provisioner
+	// key in order to verify the claims and we need the issuer from the claims
+	// before we can look up the provisioner.
+	var claims azurePayload
+	if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
+		return "", errors.Wrap(err, "error verifying claims")
+	}
+
+	// If TOFU is disabled create return the token kid
+	if p.DisableTrustOnFirstUse {
+		return claims.ID, nil
+	}
+
+	sum := sha256.Sum256([]byte(claims.XMSMirID))
+	return strings.ToLower(hex.EncodeToString(sum[:])), nil
+}
+
+// GetName returns the name of the provisioner.
+func (p *Azure) GetName() string {
+	return p.Name
+}
+
+// GetType returns the type of provisioner.
+func (p *Azure) GetType() Type {
+	return TypeAzure
+}
+
+// GetEncryptedKey is not available in an Azure provisioner.
+func (p *Azure) GetEncryptedKey() (kid string, key string, ok bool) {
+	return "", "", false
+}
+
+// GetIdentityToken retrieves from the metadata service the identity token and
+// returns it.
+func (p *Azure) GetIdentityToken(subject, caURL string) (string, error) {
+	// Initialize the config if this method is used from the cli.
+	p.assertConfig()
+
+	req, err := http.NewRequest("GET", p.config.identityTokenURL, http.NoBody)
+	if err != nil {
+		return "", errors.Wrap(err, "error creating request")
+	}
+	req.Header.Set("Metadata", "true")
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return "", errors.Wrap(err, "error getting identity token, are you in a Azure VM?")
+	}
+	defer resp.Body.Close()
+
+	b, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return "", errors.Wrap(err, "error reading identity token response")
+	}
+	if resp.StatusCode >= 400 {
+		return "", errors.Errorf("error getting identity token: status=%d, response=%s", resp.StatusCode, b)
+	}
+
+	var identityToken azureIdentityToken
+	if err := json.Unmarshal(b, &identityToken); err != nil {
+		return "", errors.Wrap(err, "error unmarshaling identity token response")
+	}
+
+	return identityToken.AccessToken, nil
+}
+
+// Init validates and initializes the Azure provisioner.
+func (p *Azure) Init(config Config) (err error) {
+	switch {
+	case p.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case p.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	case p.TenantID == "":
+		return errors.New("provisioner tenantId cannot be empty")
+	case p.Audience == "": // use default audience
+		p.Audience = azureDefaultAudience
+	}
+	// Initialize config
+	p.assertConfig()
+
+	// Update claims with global ones
+	if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
+		return err
+	}
+
+	// Decode and validate openid-configuration endpoint
+	if err := getAndDecode(p.config.oidcDiscoveryURL, &p.oidcConfig); err != nil {
+		return err
+	}
+	if err := p.oidcConfig.Validate(); err != nil {
+		return errors.Wrapf(err, "error parsing %s", p.config.oidcDiscoveryURL)
+	}
+	// Get JWK key set
+	if p.keyStore, err = newKeyStore(p.oidcConfig.JWKSetURI); err != nil {
+		return err
+	}
+
+	return nil
+}
+
+// AuthorizeSign validates the given token and returns the sign options that
+// will be used on certificate creation.
+func (p *Azure) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing token")
+	}
+	if len(jwt.Headers) == 0 {
+		return nil, errors.New("error parsing token: header is missing")
+	}
+
+	var found bool
+	var claims azurePayload
+	keys := p.keyStore.Get(jwt.Headers[0].KeyID)
+	for _, key := range keys {
+		if err := jwt.Claims(key.Public(), &claims); err == nil {
+			found = true
+			break
+		}
+	}
+	if !found {
+		return nil, errors.New("cannot validate token")
+	}
+
+	if err := claims.ValidateWithLeeway(jose.Expected{
+		Audience: []string{p.Audience},
+		Issuer:   p.oidcConfig.Issuer,
+		Time:     time.Now(),
+	}, 1*time.Minute); err != nil {
+		return nil, errors.Wrap(err, "failed to validate payload")
+	}
+
+	// Validate TenantID
+	if claims.TenantID != p.TenantID {
+		return nil, errors.New("validation failed: invalid tenant id claim (tid)")
+	}
+
+	re := azureXMSMirIDRegExp.FindStringSubmatch(claims.XMSMirID)
+	if len(re) != 4 {
+		return nil, errors.Errorf("error parsing xms_mirid claim: %s", claims.XMSMirID)
+	}
+	group, name := re[2], re[3]
+
+	// Filter by resource group
+	if len(p.ResourceGroups) > 0 {
+		var found bool
+		for _, g := range p.ResourceGroups {
+			if g == group {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return nil, errors.New("validation failed: invalid resource group")
+		}
+	}
+
+	// Check for the sign ssh method, default to sign X.509
+	if m := MethodFromContext(ctx); m == SignSSHMethod {
+		if p.claimer.IsSSHCAEnabled() == false {
+			return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
+		}
+		return p.authorizeSSHSign(claims, name)
+	}
+
+	// Enforce known common name and default DNS if configured.
+	// By default we'll accept the CN and SANs in the CSR.
+	// There's no way to trust them other than TOFU.
+	var so []SignOption
+	if p.DisableCustomSANs {
+		// name will work only inside the virtual network
+		so = append(so, commonNameValidator(name))
+		so = append(so, dnsNamesValidator([]string{name}))
+	}
+
+	return append(so,
+		defaultPublicKeyValidator{},
+		profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeAzure, p.Name, p.TenantID),
+		newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
+	), nil
+}
+
+// AuthorizeRenewal returns an error if the renewal is disabled.
+func (p *Azure) AuthorizeRenewal(cert *x509.Certificate) error {
+	if p.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
+	}
+	return nil
+}
+
+// AuthorizeRevoke returns an error because revoke is not supported on Azure
+// provisioners.
+func (p *Azure) AuthorizeRevoke(token string) error {
+	return errors.New("revoke is not supported on a Azure provisioner")
+}
+
+// authorizeSSHSign returns the list of SignOption for a SignSSH request.
+func (p *Azure) authorizeSSHSign(claims azurePayload, name string) ([]SignOption, error) {
+	signOptions := []SignOption{
+		// set the key id to the token subject
+		sshCertificateKeyIDModifier(name),
+	}
+
+	// Default to host + known hostnames
+	defaults := SSHOptions{
+		CertType:   SSHHostCert,
+		Principals: []string{name},
+	}
+	// Validate user options
+	signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
+	// Set defaults if not given as user options
+	signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
+
+	return append(signOptions,
+		// set the default extensions
+		&sshDefaultExtensionModifier{},
+		// checks the validity bounds, and set the validity if has not been set
+		&sshCertificateValidityModifier{p.claimer},
+		// validate public key
+		&sshDefaultPublicKeyValidator{},
+		// require all the fields in the SSH certificate
+		&sshCertificateDefaultValidator{},
+	), nil
+}
+
+// assertConfig initializes the config if it has not been initialized
+func (p *Azure) assertConfig() {
+	if p.config == nil {
+		p.config = newAzureConfig(p.TenantID)
+	}
+}

+ 472 - 0
authority/provisioner/azure_test.go

@@ -0,0 +1,472 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/hex"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+)
+
+func TestAzure_Getters(t *testing.T) {
+	p, err := generateAzure()
+	assert.FatalError(t, err)
+	if got := p.GetID(); got != p.TenantID {
+		t.Errorf("Azure.GetID() = %v, want %v", got, p.TenantID)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("Azure.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeAzure {
+		t.Errorf("Azure.GetType() = %v, want %v", got, TypeAzure)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != "" || key != "" || ok == true {
+		t.Errorf("Azure.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, "", "", false)
+	}
+}
+
+func TestAzure_GetTokenID(t *testing.T) {
+	p1, srv, err := generateAzureWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	p2, err := generateAzure()
+	assert.FatalError(t, err)
+	p2.TenantID = p1.TenantID
+	p2.config = p1.config
+	p2.oidcConfig = p1.oidcConfig
+	p2.keyStore = p1.keyStore
+	p2.DisableTrustOnFirstUse = true
+
+	t1, err := p1.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+	t2, err := p2.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+
+	sum := sha256.Sum256([]byte("/subscriptions/subscriptionID/resourceGroups/resourceGroup/providers/Microsoft.Compute/virtualMachines/virtualMachine"))
+	w1 := strings.ToLower(hex.EncodeToString(sum[:]))
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		azure   *Azure
+		args    args
+		want    string
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, w1, false},
+		{"ok no TOFU", p2, args{t2}, "the-jti", false},
+		{"fail token", p1, args{"bad-token"}, "", true},
+		{"fail claims", p1, args{"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ey.fooo"}, "", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.azure.GetTokenID(tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Azure.GetTokenID() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("Azure.GetTokenID() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestAzure_GetIdentityToken(t *testing.T) {
+	p1, err := generateAzure()
+	assert.FatalError(t, err)
+
+	t1, err := generateAzureToken("subject", p1.oidcConfig.Issuer, azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/bad-request":
+			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+		case "/bad-json":
+			w.Write([]byte(t1))
+		default:
+			w.Header().Add("Content-Type", "application/json")
+			w.Write([]byte(fmt.Sprintf(`{"access_token":"%s"}`, t1)))
+		}
+	}))
+	defer srv.Close()
+
+	type args struct {
+		subject string
+		caURL   string
+	}
+	tests := []struct {
+		name             string
+		azure            *Azure
+		args             args
+		identityTokenURL string
+		want             string
+		wantErr          bool
+	}{
+		{"ok", p1, args{"subject", "caURL"}, srv.URL, t1, false},
+		{"fail request", p1, args{"subject", "caURL"}, srv.URL + "/bad-request", "", true},
+		{"fail unmarshal", p1, args{"subject", "caURL"}, srv.URL + "/bad-json", "", true},
+		{"fail url", p1, args{"subject", "caURL"}, "://ca.smallstep.com", "", true},
+		{"fail connect", p1, args{"subject", "caURL"}, "foobarzar", "", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			tt.azure.config.identityTokenURL = tt.identityTokenURL
+			got, err := tt.azure.GetIdentityToken(tt.args.subject, tt.args.caURL)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Azure.GetIdentityToken() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("Azure.GetIdentityToken() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestAzure_Init(t *testing.T) {
+	p1, srv, err := generateAzureWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	config := Config{
+		Claims: globalProvisionerClaims,
+	}
+	badClaims := &Claims{
+		DefaultTLSDur: &Duration{0},
+	}
+
+	badDiscoveryURL := &azureConfig{
+		oidcDiscoveryURL: srv.URL + "/error",
+		identityTokenURL: p1.config.identityTokenURL,
+	}
+	badJWKURL := &azureConfig{
+		oidcDiscoveryURL: srv.URL + "/openid-configuration-fail-jwk",
+		identityTokenURL: p1.config.identityTokenURL,
+	}
+	badAzureConfig := &azureConfig{
+		oidcDiscoveryURL: srv.URL + "/openid-configuration-no-issuer",
+		identityTokenURL: p1.config.identityTokenURL,
+	}
+
+	type fields struct {
+		Type     string
+		Name     string
+		TenantID string
+		Claims   *Claims
+		config   *azureConfig
+	}
+	type args struct {
+		config Config
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		args    args
+		wantErr bool
+	}{
+		{"ok", fields{p1.Type, p1.Name, p1.TenantID, nil, p1.config}, args{config}, false},
+		{"ok with config", fields{p1.Type, p1.Name, p1.TenantID, nil, p1.config}, args{config}, false},
+		{"fail type", fields{"", p1.Name, p1.TenantID, nil, p1.config}, args{config}, true},
+		{"fail name", fields{p1.Type, "", p1.TenantID, nil, p1.config}, args{config}, true},
+		{"fail tenant id", fields{p1.Type, p1.Name, "", nil, p1.config}, args{config}, true},
+		{"fail claims", fields{p1.Type, p1.Name, p1.TenantID, badClaims, p1.config}, args{config}, true},
+		{"fail discovery URL", fields{p1.Type, p1.Name, p1.TenantID, nil, badDiscoveryURL}, args{config}, true},
+		{"fail JWK URL", fields{p1.Type, p1.Name, p1.TenantID, nil, badJWKURL}, args{config}, true},
+		{"fail config Validate", fields{p1.Type, p1.Name, p1.TenantID, nil, badAzureConfig}, args{config}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			p := &Azure{
+				Type:     tt.fields.Type,
+				Name:     tt.fields.Name,
+				TenantID: tt.fields.TenantID,
+				Claims:   tt.fields.Claims,
+				config:   tt.fields.config,
+			}
+			if err := p.Init(tt.args.config); (err != nil) != tt.wantErr {
+				t.Errorf("Azure.Init() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestAzure_AuthorizeSign(t *testing.T) {
+	p1, srv, err := generateAzureWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	p2, err := generateAzure()
+	assert.FatalError(t, err)
+	p2.TenantID = p1.TenantID
+	p2.ResourceGroups = []string{"resourceGroup"}
+	p2.config = p1.config
+	p2.oidcConfig = p1.oidcConfig
+	p2.keyStore = p1.keyStore
+	p2.DisableCustomSANs = true
+
+	p3, err := generateAzure()
+	assert.FatalError(t, err)
+	p3.config = p1.config
+	p3.oidcConfig = p1.oidcConfig
+	p3.keyStore = p1.keyStore
+
+	p4, err := generateAzure()
+	assert.FatalError(t, err)
+	p4.TenantID = p1.TenantID
+	p4.ResourceGroups = []string{"foobarzar"}
+	p4.config = p1.config
+	p4.oidcConfig = p1.oidcConfig
+	p4.keyStore = p1.keyStore
+
+	badKey, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	t1, err := p1.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+	t2, err := p2.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+	t3, err := p3.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+	t4, err := p4.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+
+	t11, err := generateAzureToken("subject", p1.oidcConfig.Issuer, azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	failIssuer, err := generateAzureToken("subject", "bad-issuer", azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failAudience, err := generateAzureToken("subject", p1.oidcConfig.Issuer, "bad-audience",
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failExp, err := generateAzureToken("subject", p1.oidcConfig.Issuer, azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now().Add(-360*time.Second), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failNbf, err := generateAzureToken("subject", p1.oidcConfig.Issuer, azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now().Add(360*time.Second), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failKey, err := generateAzureToken("subject", p1.oidcConfig.Issuer, azureDefaultAudience,
+		p1.TenantID, "subscriptionID", "resourceGroup", "virtualMachine",
+		time.Now(), badKey)
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		azure   *Azure
+		args    args
+		wantLen int
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, 4, false},
+		{"ok", p2, args{t2}, 6, false},
+		{"ok", p1, args{t11}, 4, false},
+		{"fail tenant", p3, args{t3}, 0, true},
+		{"fail resource group", p4, args{t4}, 0, true},
+		{"fail token", p1, args{"token"}, 0, true},
+		{"fail issuer", p1, args{failIssuer}, 0, true},
+		{"fail audience", p1, args{failAudience}, 0, true},
+		{"fail exp", p1, args{failExp}, 0, true},
+		{"fail nbf", p1, args{failNbf}, 0, true},
+		{"fail key", p1, args{failKey}, 0, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignMethod)
+			got, err := tt.azure.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Azure.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			assert.Len(t, tt.wantLen, got)
+		})
+	}
+}
+
+func TestAzure_AuthorizeSign_SSH(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	p1, srv, err := generateAzureWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	t1, err := p1.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	pub := key.Public().Key
+	rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
+	assert.FatalError(t, err)
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"virtualMachine"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+
+	type args struct {
+		token   string
+		sshOpts SSHOptions
+		key     interface{}
+	}
+	tests := []struct {
+		name        string
+		azure       *Azure
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"ok", p1, args{t1, SSHOptions{}, pub}, expectedHostOptions, false, false},
+		{"ok-rsa2048", p1, args{t1, SSHOptions{}, rsa2048.Public()}, expectedHostOptions, false, false},
+		{"ok-type", p1, args{t1, SSHOptions{CertType: "host"}, pub}, expectedHostOptions, false, false},
+		{"ok-principals", p1, args{t1, SSHOptions{Principals: []string{"virtualMachine"}}, pub}, expectedHostOptions, false, false},
+		{"ok-options", p1, args{t1, SSHOptions{CertType: "host", Principals: []string{"virtualMachine"}}, pub}, expectedHostOptions, false, false},
+		{"fail-rsa1024", p1, args{t1, SSHOptions{}, rsa1024.Public()}, expectedHostOptions, false, true},
+		{"fail-type", p1, args{t1, SSHOptions{CertType: "user"}, pub}, nil, false, true},
+		{"fail-principal", p1, args{t1, SSHOptions{Principals: []string{"smallstep.com"}}, pub}, nil, false, true},
+		{"fail-extra-principal", p1, args{t1, SSHOptions{Principals: []string{"virtualMachine", "smallstep.com"}}, pub}, nil, false, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			got, err := tt.azure.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Azure.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else if assert.NotNil(t, got) {
+				cert, err := signSSHCertificate(tt.args.key, tt.args.sshOpts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestAzure_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateAzure()
+	assert.FatalError(t, err)
+	p2, err := generateAzure()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		azure   *Azure
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{nil}, false},
+		{"fail", p2, args{nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.azure.AuthorizeRenewal(tt.args.cert); (err != nil) != tt.wantErr {
+				t.Errorf("Azure.AuthorizeRenewal() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestAzure_AuthorizeRevoke(t *testing.T) {
+	az, srv, err := generateAzureWithServer()
+	assert.FatalError(t, err)
+	defer srv.Close()
+
+	token, err := az.GetIdentityToken("subject", "caURL")
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		azure   *Azure
+		args    args
+		wantErr bool
+	}{
+		{"ok token", az, args{token}, true}, // revoke is disabled
+		{"bad token", az, args{"bad token"}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.azure.AuthorizeRevoke(tt.args.token); (err != nil) != tt.wantErr {
+				t.Errorf("Azure.AuthorizeRevoke() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestAzure_assertConfig(t *testing.T) {
+	p1, err := generateAzure()
+	assert.FatalError(t, err)
+	p2, err := generateAzure()
+	assert.FatalError(t, err)
+	p2.config = nil
+
+	tests := []struct {
+		name  string
+		azure *Azure
+	}{
+		{"ok with config", p1},
+		{"ok no config", p2},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			tt.azure.assertConfig()
+		})
+	}
+}

+ 192 - 0
authority/provisioner/claims.go

@@ -0,0 +1,192 @@
+package provisioner
+
+import (
+	"time"
+
+	"github.com/pkg/errors"
+)
+
+// Claims so that individual provisioners can override global claims.
+type Claims struct {
+	// TLS CA properties
+	MinTLSDur      *Duration `json:"minTLSCertDuration,omitempty"`
+	MaxTLSDur      *Duration `json:"maxTLSCertDuration,omitempty"`
+	DefaultTLSDur  *Duration `json:"defaultTLSCertDuration,omitempty"`
+	DisableRenewal *bool     `json:"disableRenewal,omitempty"`
+	// SSH CA properties
+	MinUserSSHDur     *Duration `json:"minUserSSHCertDuration,omitempty"`
+	MaxUserSSHDur     *Duration `json:"maxUserSSHCertDuration,omitempty"`
+	DefaultUserSSHDur *Duration `json:"defaultUserSSHCertDuration,omitempty"`
+	MinHostSSHDur     *Duration `json:"minHostSSHCertDuration,omitempty"`
+	MaxHostSSHDur     *Duration `json:"maxHostSSHCertDuration,omitempty"`
+	DefaultHostSSHDur *Duration `json:"defaultHostSSHCertDuration,omitempty"`
+	EnableSSHCA       *bool     `json:"enableSSHCA,omitempty"`
+}
+
+// Claimer is the type that controls claims. It provides an interface around the
+// current claim and the global one.
+type Claimer struct {
+	global Claims
+	claims *Claims
+}
+
+// NewClaimer initializes a new claimer with the given claims.
+func NewClaimer(claims *Claims, global Claims) (*Claimer, error) {
+	c := &Claimer{global: global, claims: claims}
+	return c, c.Validate()
+}
+
+// Claims returns the merge of the inner and global claims.
+func (c *Claimer) Claims() Claims {
+	disableRenewal := c.IsDisableRenewal()
+	enableSSHCA := c.IsSSHCAEnabled()
+	return Claims{
+		MinTLSDur:         &Duration{c.MinTLSCertDuration()},
+		MaxTLSDur:         &Duration{c.MaxTLSCertDuration()},
+		DefaultTLSDur:     &Duration{c.DefaultTLSCertDuration()},
+		DisableRenewal:    &disableRenewal,
+		MinUserSSHDur:     &Duration{c.MinUserSSHCertDuration()},
+		MaxUserSSHDur:     &Duration{c.MaxUserSSHCertDuration()},
+		DefaultUserSSHDur: &Duration{c.DefaultUserSSHCertDuration()},
+		MinHostSSHDur:     &Duration{c.MinHostSSHCertDuration()},
+		MaxHostSSHDur:     &Duration{c.MaxHostSSHCertDuration()},
+		DefaultHostSSHDur: &Duration{c.DefaultHostSSHCertDuration()},
+		EnableSSHCA:       &enableSSHCA,
+	}
+}
+
+// DefaultTLSCertDuration returns the default TLS cert duration for the
+// provisioner. If the default is not set within the provisioner, then the global
+// default from the authority configuration will be used.
+func (c *Claimer) DefaultTLSCertDuration() time.Duration {
+	if c.claims == nil || c.claims.DefaultTLSDur == nil {
+		return c.global.DefaultTLSDur.Duration
+	}
+	return c.claims.DefaultTLSDur.Duration
+}
+
+// MinTLSCertDuration returns the minimum TLS cert duration for the provisioner.
+// If the minimum is not set within the provisioner, then the global
+// minimum from the authority configuration will be used.
+func (c *Claimer) MinTLSCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MinTLSDur == nil {
+		return c.global.MinTLSDur.Duration
+	}
+	return c.claims.MinTLSDur.Duration
+}
+
+// MaxTLSCertDuration returns the maximum TLS cert duration for the provisioner.
+// If the maximum is not set within the provisioner, then the global
+// maximum from the authority configuration will be used.
+func (c *Claimer) MaxTLSCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MaxTLSDur == nil {
+		return c.global.MaxTLSDur.Duration
+	}
+	return c.claims.MaxTLSDur.Duration
+}
+
+// IsDisableRenewal returns if the renewal flow is disabled for the
+// provisioner. If the property is not set within the provisioner, then the
+// global value from the authority configuration will be used.
+func (c *Claimer) IsDisableRenewal() bool {
+	if c.claims == nil || c.claims.DisableRenewal == nil {
+		return *c.global.DisableRenewal
+	}
+	return *c.claims.DisableRenewal
+}
+
+// DefaultUserSSHCertDuration returns the default SSH user cert duration for the
+// provisioner. If the default is not set within the provisioner, then the
+// global default from the authority configuration will be used.
+func (c *Claimer) DefaultUserSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.DefaultUserSSHDur == nil {
+		return c.global.DefaultUserSSHDur.Duration
+	}
+	return c.claims.DefaultUserSSHDur.Duration
+}
+
+// MinUserSSHCertDuration returns the minimum SSH user cert duration for the
+// provisioner. If the minimum is not set within the provisioner, then the
+// global minimum from the authority configuration will be used.
+func (c *Claimer) MinUserSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MinUserSSHDur == nil {
+		return c.global.MinUserSSHDur.Duration
+	}
+	return c.claims.MinUserSSHDur.Duration
+}
+
+// MaxUserSSHCertDuration returns the maximum SSH user cert duration for the
+// provisioner. If the maximum is not set within the provisioner, then the
+// global maximum from the authority configuration will be used.
+func (c *Claimer) MaxUserSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MaxUserSSHDur == nil {
+		return c.global.MaxUserSSHDur.Duration
+	}
+	return c.claims.MaxUserSSHDur.Duration
+}
+
+// DefaultHostSSHCertDuration returns the default SSH host cert duration for the
+// provisioner. If the default is not set within the provisioner, then the
+// global default from the authority configuration will be used.
+func (c *Claimer) DefaultHostSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.DefaultHostSSHDur == nil {
+		return c.global.DefaultHostSSHDur.Duration
+	}
+	return c.claims.DefaultHostSSHDur.Duration
+}
+
+// MinHostSSHCertDuration returns the minimum SSH host cert duration for the
+// provisioner. If the minimum is not set within the provisioner, then the
+// global minimum from the authority configuration will be used.
+func (c *Claimer) MinHostSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MinHostSSHDur == nil {
+		return c.global.MinHostSSHDur.Duration
+	}
+	return c.claims.MinHostSSHDur.Duration
+}
+
+// MaxHostSSHCertDuration returns the maximum SSH Host cert duration for the
+// provisioner. If the maximum is not set within the provisioner, then the
+// global maximum from the authority configuration will be used.
+func (c *Claimer) MaxHostSSHCertDuration() time.Duration {
+	if c.claims == nil || c.claims.MaxHostSSHDur == nil {
+		return c.global.MaxHostSSHDur.Duration
+	}
+	return c.claims.MaxHostSSHDur.Duration
+}
+
+// IsSSHCAEnabled returns if the SSH CA is enabled for the provisioner. If the
+// property is not set within the provisioner, then the global value from the
+// authority configuration will be used.
+func (c *Claimer) IsSSHCAEnabled() bool {
+	if c.claims == nil || c.claims.EnableSSHCA == nil {
+		return *c.global.EnableSSHCA
+	}
+	return *c.claims.EnableSSHCA
+}
+
+// Validate validates and modifies the Claims with default values.
+func (c *Claimer) Validate() error {
+	var (
+		min = c.MinTLSCertDuration()
+		max = c.MaxTLSCertDuration()
+		def = c.DefaultTLSCertDuration()
+	)
+	switch {
+	case min <= 0:
+		return errors.Errorf("claims: MinTLSCertDuration must be greater than 0")
+	case max <= 0:
+		return errors.Errorf("claims: MaxTLSCertDuration must be greater than 0")
+	case def <= 0:
+		return errors.Errorf("claims: DefaultTLSCertDuration must be greater than 0")
+	case max < min:
+		return errors.Errorf("claims: MaxCertDuration cannot be less "+
+			"than MinCertDuration: MaxCertDuration - %v, MinCertDuration - %v", max, min)
+	case def < min:
+		return errors.Errorf("claims: DefaultCertDuration cannot be less than MinCertDuration: DefaultCertDuration - %v, MinCertDuration - %v", def, min)
+	case max < def:
+		return errors.Errorf("claims: MaxCertDuration cannot be less than DefaultCertDuration: MaxCertDuration - %v, DefaultCertDuration - %v", max, def)
+	default:
+		return nil
+	}
+}

+ 261 - 0
authority/provisioner/collection.go

@@ -0,0 +1,261 @@
+package provisioner
+
+import (
+	"crypto/sha1"
+	"crypto/x509"
+	"encoding/asn1"
+	"encoding/binary"
+	"encoding/hex"
+	"fmt"
+	"net/url"
+	"sort"
+	"strings"
+	"sync"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+// DefaultProvisionersLimit is the default limit for listing provisioners.
+const DefaultProvisionersLimit = 20
+
+// DefaultProvisionersMax is the maximum limit for listing provisioners.
+const DefaultProvisionersMax = 100
+
+type uidProvisioner struct {
+	provisioner Interface
+	uid         string
+}
+
+type provisionerSlice []uidProvisioner
+
+func (p provisionerSlice) Len() int           { return len(p) }
+func (p provisionerSlice) Less(i, j int) bool { return p[i].uid < p[j].uid }
+func (p provisionerSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
+
+// loadByTokenPayload is a payload used to extract the id used to load the
+// provisioner.
+type loadByTokenPayload struct {
+	jose.Claims
+	AuthorizedParty string `json:"azp"` // OIDC client id
+	TenantID        string `json:"tid"` // Microsoft Azure tenant id
+}
+
+// Collection is a memory map of provisioners.
+type Collection struct {
+	byID      *sync.Map
+	byKey     *sync.Map
+	sorted    provisionerSlice
+	audiences Audiences
+}
+
+// NewCollection initializes a collection of provisioners. The given list of
+// audiences are the audiences used by the JWT provisioner.
+func NewCollection(audiences Audiences) *Collection {
+	return &Collection{
+		byID:      new(sync.Map),
+		byKey:     new(sync.Map),
+		audiences: audiences,
+	}
+}
+
+// Load a provisioner by the ID.
+func (c *Collection) Load(id string) (Interface, bool) {
+	return loadProvisioner(c.byID, id)
+}
+
+// LoadByToken parses the token claims and loads the provisioner associated.
+func (c *Collection) LoadByToken(token *jose.JSONWebToken, claims *jose.Claims) (Interface, bool) {
+	var audiences []string
+	// Get all audiences with the given fragment
+	fragment := extractFragment(claims.Audience)
+	if fragment == "" {
+		audiences = c.audiences.All()
+	} else {
+		audiences = c.audiences.WithFragment(fragment).All()
+	}
+
+	// match with server audiences
+	if matchesAudience(claims.Audience, audiences) {
+		// Use fragment to get provisioner name (GCP, AWS)
+		if fragment != "" {
+			return c.Load(fragment)
+		}
+		// If matches with stored audiences it will be a JWT token (default), and
+		// the id would be <issuer>:<kid>.
+		return c.Load(claims.Issuer + ":" + token.Headers[0].KeyID)
+	}
+
+	// The ID will be just the clientID stored in azp, aud or tid.
+	var payload loadByTokenPayload
+	if err := token.UnsafeClaimsWithoutVerification(&payload); err != nil {
+		return nil, false
+	}
+	// Audience is required
+	if len(payload.Audience) == 0 {
+		return nil, false
+	}
+	// Try with azp (OIDC)
+	if len(payload.AuthorizedParty) > 0 {
+		if p, ok := c.Load(payload.AuthorizedParty); ok {
+			return p, ok
+		}
+	}
+	// Try with tid (Azure)
+	if payload.TenantID != "" {
+		if p, ok := c.Load(payload.TenantID); ok {
+			return p, ok
+		}
+	}
+	// Fallback to aud
+	return c.Load(payload.Audience[0])
+}
+
+// LoadByCertificate looks for the provisioner extension and extracts the
+// proper id to load the provisioner.
+func (c *Collection) LoadByCertificate(cert *x509.Certificate) (Interface, bool) {
+	for _, e := range cert.Extensions {
+		if e.Id.Equal(stepOIDProvisioner) {
+			var provisioner stepProvisionerASN1
+			if _, err := asn1.Unmarshal(e.Value, &provisioner); err != nil {
+				return nil, false
+			}
+			switch Type(provisioner.Type) {
+			case TypeJWK:
+				return c.Load(string(provisioner.Name) + ":" + string(provisioner.CredentialID))
+			case TypeAWS:
+				return c.Load("aws/" + string(provisioner.Name))
+			case TypeGCP:
+				return c.Load("gcp/" + string(provisioner.Name))
+			case TypeACME:
+				return c.Load("acme/" + string(provisioner.Name))
+			default:
+				return c.Load(string(provisioner.CredentialID))
+			}
+		}
+	}
+
+	// Default to noop provisioner if an extension is not found. This allows to
+	// accept a renewal of a cert without the provisioner extension.
+	return &noop{}, true
+}
+
+// LoadEncryptedKey returns an encrypted key by indexed by KeyID. At this moment
+// only JWK encrypted keys are indexed by KeyID.
+func (c *Collection) LoadEncryptedKey(keyID string) (string, bool) {
+	p, ok := loadProvisioner(c.byKey, keyID)
+	if !ok {
+		return "", false
+	}
+	_, key, ok := p.GetEncryptedKey()
+	return key, ok
+}
+
+// Store adds a provisioner to the collection and enforces the uniqueness of
+// provisioner IDs.
+func (c *Collection) Store(p Interface) error {
+	// Store provisioner always in byID. ID must be unique.
+	if _, loaded := c.byID.LoadOrStore(p.GetID(), p); loaded {
+		return errors.New("cannot add multiple provisioners with the same id")
+	}
+
+	// Store provisioner in byKey if EncryptedKey is defined.
+	if kid, _, ok := p.GetEncryptedKey(); ok {
+		c.byKey.Store(kid, p)
+	}
+
+	// Store sorted provisioners.
+	// Use the first 4 bytes (32bit) of the sum to insert the order
+	// Using big endian format to get the strings sorted:
+	// 0x00000000, 0x00000001, 0x00000002, ...
+	bi := make([]byte, 4)
+	sum := provisionerSum(p)
+	binary.BigEndian.PutUint32(bi, uint32(c.sorted.Len()))
+	sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
+	c.sorted = append(c.sorted, uidProvisioner{
+		provisioner: p,
+		uid:         hex.EncodeToString(sum),
+	})
+	sort.Sort(c.sorted)
+	return nil
+}
+
+// Find implements pagination on a list of sorted provisioners.
+func (c *Collection) Find(cursor string, limit int) (List, string) {
+	switch {
+	case limit <= 0:
+		limit = DefaultProvisionersLimit
+	case limit > DefaultProvisionersMax:
+		limit = DefaultProvisionersMax
+	}
+
+	n := c.sorted.Len()
+	cursor = fmt.Sprintf("%040s", cursor)
+	i := sort.Search(n, func(i int) bool { return c.sorted[i].uid >= cursor })
+
+	slice := List{}
+	for ; i < n && len(slice) < limit; i++ {
+		slice = append(slice, c.sorted[i].provisioner)
+	}
+
+	if i < n {
+		return slice, strings.TrimLeft(c.sorted[i].uid, "0")
+	}
+	return slice, ""
+}
+
+func loadProvisioner(m *sync.Map, key string) (Interface, bool) {
+	i, ok := m.Load(key)
+	if !ok {
+		return nil, false
+	}
+	p, ok := i.(Interface)
+	if !ok {
+		return nil, false
+	}
+	return p, true
+}
+
+// provisionerSum returns the SHA1 of the provisioners ID. From this we will
+// create the unique and sorted id.
+func provisionerSum(p Interface) []byte {
+	sum := sha1.Sum([]byte(p.GetID()))
+	return sum[:]
+}
+
+// matchesAudience returns true if A and B share at least one element.
+func matchesAudience(as, bs []string) bool {
+	if len(bs) == 0 || len(as) == 0 {
+		return false
+	}
+
+	for _, b := range bs {
+		for _, a := range as {
+			if b == a || stripPort(a) == stripPort(b) {
+				return true
+			}
+		}
+	}
+	return false
+}
+
+// stripPort attempts to strip the port from the given url. If parsing the url
+// produces errors it will just return the passed argument.
+func stripPort(rawurl string) string {
+	u, err := url.Parse(rawurl)
+	if err != nil {
+		return rawurl
+	}
+	u.Host = u.Hostname()
+	return u.String()
+}
+
+// extractFragment extracts the first fragment of an audience url.
+func extractFragment(audience []string) string {
+	for _, s := range audience {
+		if u, err := url.Parse(s); err == nil && u.Fragment != "" {
+			return u.Fragment
+		}
+	}
+	return ""
+}

+ 399 - 0
authority/provisioner/collection_test.go

@@ -0,0 +1,399 @@
+package provisioner
+
+import (
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"reflect"
+	"strings"
+	"sync"
+	"testing"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/jose"
+)
+
+func TestCollection_Load(t *testing.T) {
+	p, err := generateJWK()
+	assert.FatalError(t, err)
+	byID := new(sync.Map)
+	byID.Store(p.GetID(), p)
+	byID.Store("string", "a-string")
+
+	type fields struct {
+		byID *sync.Map
+	}
+	type args struct {
+		id string
+	}
+	tests := []struct {
+		name   string
+		fields fields
+		args   args
+		want   Interface
+		want1  bool
+	}{
+		{"ok", fields{byID}, args{p.GetID()}, p, true},
+		{"fail", fields{byID}, args{"fail"}, nil, false},
+		{"invalid", fields{byID}, args{"string"}, nil, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := &Collection{
+				byID: tt.fields.byID,
+			}
+			got, got1 := c.Load(tt.args.id)
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Collection.Load() got = %v, want %v", got, tt.want)
+			}
+			if got1 != tt.want1 {
+				t.Errorf("Collection.Load() got1 = %v, want %v", got1, tt.want1)
+			}
+		})
+	}
+}
+
+func TestCollection_LoadByToken(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	p2, err := generateJWK()
+	assert.FatalError(t, err)
+	p3, err := generateOIDC()
+	assert.FatalError(t, err)
+
+	byID := new(sync.Map)
+	byID.Store(p1.GetID(), p1)
+	byID.Store(p2.GetID(), p2)
+	byID.Store(p3.GetID(), p3)
+	byID.Store("string", "a-string")
+
+	jwk, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+	token, err := generateSimpleToken(p1.Name, testAudiences.Sign[0], jwk)
+	assert.FatalError(t, err)
+	t1, c1, err := parseToken(token)
+	assert.FatalError(t, err)
+
+	jwk, err = decryptJSONWebKey(p2.EncryptedKey)
+	assert.FatalError(t, err)
+	token, err = generateSimpleToken(p2.Name, testAudiences.Sign[1], jwk)
+	assert.FatalError(t, err)
+	t2, c2, err := parseToken(token)
+	assert.FatalError(t, err)
+
+	token, err = generateSimpleToken(p3.configuration.Issuer, p3.ClientID, &p3.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	t3, c3, err := parseToken(token)
+	assert.FatalError(t, err)
+
+	token, err = generateSimpleToken(p3.configuration.Issuer, "string", &p3.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	t4, c4, err := parseToken(token)
+	assert.FatalError(t, err)
+
+	type fields struct {
+		byID      *sync.Map
+		audiences Audiences
+	}
+	type args struct {
+		token  *jose.JSONWebToken
+		claims *jose.Claims
+	}
+	tests := []struct {
+		name   string
+		fields fields
+		args   args
+		want   Interface
+		want1  bool
+	}{
+		{"ok1", fields{byID, testAudiences}, args{t1, c1}, p1, true},
+		{"ok2", fields{byID, testAudiences}, args{t2, c2}, p2, true},
+		{"ok3", fields{byID, testAudiences}, args{t3, c3}, p3, true},
+		{"bad", fields{byID, testAudiences}, args{t4, c4}, nil, false},
+		{"fail", fields{byID, Audiences{Sign: []string{"https://foo"}}}, args{t1, c1}, nil, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := &Collection{
+				byID:      tt.fields.byID,
+				audiences: tt.fields.audiences,
+			}
+			got, got1 := c.LoadByToken(tt.args.token, tt.args.claims)
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Collection.LoadByToken() got = %v, want %v", got, tt.want)
+			}
+			if got1 != tt.want1 {
+				t.Errorf("Collection.LoadByToken() got1 = %v, want %v", got1, tt.want1)
+			}
+		})
+	}
+}
+
+func TestCollection_LoadByCertificate(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+	p3, err := generateACME()
+	assert.FatalError(t, err)
+
+	byID := new(sync.Map)
+	byID.Store(p1.GetID(), p1)
+	byID.Store(p2.GetID(), p2)
+	byID.Store(p3.GetID(), p3)
+
+	ok1Ext, err := createProvisionerExtension(1, p1.Name, p1.Key.KeyID)
+	assert.FatalError(t, err)
+	ok2Ext, err := createProvisionerExtension(2, p2.Name, p2.ClientID)
+	assert.FatalError(t, err)
+	ok3Ext, err := createProvisionerExtension(int(TypeACME), p3.Name, "")
+	assert.FatalError(t, err)
+	notFoundExt, err := createProvisionerExtension(1, "foo", "bar")
+	assert.FatalError(t, err)
+
+	ok1Cert := &x509.Certificate{
+		Extensions: []pkix.Extension{ok1Ext},
+	}
+	ok2Cert := &x509.Certificate{
+		Extensions: []pkix.Extension{ok2Ext},
+	}
+	ok3Cert := &x509.Certificate{
+		Extensions: []pkix.Extension{ok3Ext},
+	}
+	notFoundCert := &x509.Certificate{
+		Extensions: []pkix.Extension{notFoundExt},
+	}
+	badCert := &x509.Certificate{
+		Extensions: []pkix.Extension{
+			{Id: stepOIDProvisioner, Critical: false, Value: []byte("foobar")},
+		},
+	}
+
+	type fields struct {
+		byID      *sync.Map
+		audiences Audiences
+	}
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name   string
+		fields fields
+		args   args
+		want   Interface
+		want1  bool
+	}{
+		{"ok1", fields{byID, testAudiences}, args{ok1Cert}, p1, true},
+		{"ok2", fields{byID, testAudiences}, args{ok2Cert}, p2, true},
+		{"ok3", fields{byID, testAudiences}, args{ok3Cert}, p3, true},
+		{"noExtension", fields{byID, testAudiences}, args{&x509.Certificate{}}, &noop{}, true},
+		{"notFound", fields{byID, testAudiences}, args{notFoundCert}, nil, false},
+		{"badCert", fields{byID, testAudiences}, args{badCert}, nil, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := &Collection{
+				byID:      tt.fields.byID,
+				audiences: tt.fields.audiences,
+			}
+			got, got1 := c.LoadByCertificate(tt.args.cert)
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Collection.LoadByCertificate() got = %v, want %v", got, tt.want)
+			}
+			if got1 != tt.want1 {
+				t.Errorf("Collection.LoadByCertificate() got1 = %v, want %v", got1, tt.want1)
+			}
+		})
+	}
+}
+
+func TestCollection_LoadEncryptedKey(t *testing.T) {
+	c := NewCollection(testAudiences)
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	assert.FatalError(t, c.Store(p1))
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+	assert.FatalError(t, c.Store(p2))
+
+	// Add oidc in byKey.
+	// It should not happen.
+	p2KeyID := p2.keyStore.keySet.Keys[0].KeyID
+	c.byKey.Store(p2KeyID, p2)
+
+	type args struct {
+		keyID string
+	}
+	tests := []struct {
+		name  string
+		args  args
+		want  string
+		want1 bool
+	}{
+		{"ok", args{p1.Key.KeyID}, p1.EncryptedKey, true},
+		{"oidc", args{p2KeyID}, "", false},
+		{"notFound", args{"not-found"}, "", false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, got1 := c.LoadEncryptedKey(tt.args.keyID)
+			if got != tt.want {
+				t.Errorf("Collection.LoadEncryptedKey() got = %v, want %v", got, tt.want)
+			}
+			if got1 != tt.want1 {
+				t.Errorf("Collection.LoadEncryptedKey() got1 = %v, want %v", got1, tt.want1)
+			}
+		})
+	}
+}
+
+func TestCollection_Store(t *testing.T) {
+	c := NewCollection(testAudiences)
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+
+	type args struct {
+		p Interface
+	}
+	tests := []struct {
+		name    string
+		args    args
+		wantErr bool
+	}{
+		{"ok1", args{p1}, false},
+		{"ok2", args{p2}, false},
+		{"fail1", args{p1}, true},
+		{"fail2", args{p2}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := c.Store(tt.args.p); (err != nil) != tt.wantErr {
+				t.Errorf("Collection.Store() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestCollection_Find(t *testing.T) {
+	c, err := generateCollection(10, 10)
+	assert.FatalError(t, err)
+
+	trim := func(s string) string {
+		return strings.TrimLeft(s, "0")
+	}
+	toList := func(ps provisionerSlice) List {
+		l := List{}
+		for _, p := range ps {
+			l = append(l, p.provisioner)
+		}
+		return l
+	}
+
+	type args struct {
+		cursor string
+		limit  int
+	}
+	tests := []struct {
+		name  string
+		args  args
+		want  List
+		want1 string
+	}{
+		{"all", args{"", DefaultProvisionersMax}, toList(c.sorted[0:20]), ""},
+		{"0 to 19", args{"", 20}, toList(c.sorted[0:20]), ""},
+		{"0 to 9", args{"", 10}, toList(c.sorted[0:10]), trim(c.sorted[10].uid)},
+		{"9 to 19", args{trim(c.sorted[10].uid), 10}, toList(c.sorted[10:20]), ""},
+		{"1", args{trim(c.sorted[1].uid), 1}, toList(c.sorted[1:2]), trim(c.sorted[2].uid)},
+		{"1 to 5", args{trim(c.sorted[1].uid), 4}, toList(c.sorted[1:5]), trim(c.sorted[5].uid)},
+		{"defaultLimit", args{"", 0}, toList(c.sorted[0:20]), ""},
+		{"overTheLimit", args{"", DefaultProvisionersMax + 1}, toList(c.sorted[0:20]), ""},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, got1 := c.Find(tt.args.cursor, tt.args.limit)
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Collection.Find() got = %v, want %v", got, tt.want)
+			}
+			if got1 != tt.want1 {
+				t.Errorf("Collection.Find() got1 = %v, want %v", got1, tt.want1)
+			}
+		})
+	}
+}
+
+func Test_matchesAudience(t *testing.T) {
+	type matchesTest struct {
+		a, b []string
+		exp  bool
+	}
+	tests := map[string]matchesTest{
+		"false arg1 empty": {
+			a:   []string{},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			exp: false,
+		},
+		"false arg2 empty": {
+			a:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			b:   []string{},
+			exp: false,
+		},
+		"false arg1,arg2 empty": {
+			a:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			b:   []string{"step-gateway", "step-cli"},
+			exp: false,
+		},
+		"false": {
+			a:   []string{"step-gateway", "step-cli"},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			exp: false,
+		},
+		"true": {
+			a:   []string{"step-gateway", "https://test.ca.smallstep.com/sign"},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			exp: true,
+		},
+		"true,portsA": {
+			a:   []string{"step-gateway", "https://test.ca.smallstep.com:9000/sign"},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com/sign"},
+			exp: true,
+		},
+		"true,portsB": {
+			a:   []string{"step-gateway", "https://test.ca.smallstep.com/sign"},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com:9000/sign"},
+			exp: true,
+		},
+		"true,portsAB": {
+			a:   []string{"step-gateway", "https://test.ca.smallstep.com:9000/sign"},
+			b:   []string{"https://127.0.0.1:0/sign", "https://test.ca.smallstep.com:8000/sign"},
+			exp: true,
+		},
+	}
+	for name, tc := range tests {
+		t.Run(name, func(t *testing.T) {
+			assert.Equals(t, tc.exp, matchesAudience(tc.a, tc.b))
+		})
+	}
+}
+
+func Test_stripPort(t *testing.T) {
+	type args struct {
+		rawurl string
+	}
+	tests := []struct {
+		name string
+		args args
+		want string
+	}{
+		{"with port", args{"https://ca.smallstep.com:9000/sign"}, "https://ca.smallstep.com/sign"},
+		{"with no port", args{"https://ca.smallstep.com/sign/"}, "https://ca.smallstep.com/sign/"},
+		{"bad url", args{"https://a bad url:9000"}, "https://a bad url:9000"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := stripPort(tt.args.rawurl); got != tt.want {
+				t.Errorf("stripPort() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 63 - 0
authority/provisioner/duration.go

@@ -0,0 +1,63 @@
+package provisioner
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/pkg/errors"
+)
+
+// Duration is a wrapper around Time.Duration to aid with marshal/unmarshal.
+type Duration struct {
+	time.Duration
+}
+
+// NewDuration parses a duration string and returns a Duration type or an error
+// if the given string is not a duration.
+func NewDuration(s string) (*Duration, error) {
+	d, err := time.ParseDuration(s)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing %s as duration", s)
+	}
+	return &Duration{Duration: d}, nil
+}
+
+// MarshalJSON parses a duration string and sets it to the duration.
+//
+// A duration string is a possibly signed sequence of decimal numbers, each with
+// optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
+// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
+func (d *Duration) MarshalJSON() ([]byte, error) {
+	return json.Marshal(d.Duration.String())
+}
+
+// UnmarshalJSON parses a duration string and sets it to the duration.
+//
+// A duration string is a possibly signed sequence of decimal numbers, each with
+// optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".
+// Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
+func (d *Duration) UnmarshalJSON(data []byte) (err error) {
+	var (
+		s  string
+		dd time.Duration
+	)
+	if d == nil {
+		return errors.New("duration cannot be nil")
+	}
+	if err = json.Unmarshal(data, &s); err != nil {
+		return errors.Wrapf(err, "error unmarshaling %s", data)
+	}
+	if dd, err = time.ParseDuration(s); err != nil {
+		return errors.Wrapf(err, "error parsing %s as duration", s)
+	}
+	d.Duration = dd
+	return
+}
+
+// Value returns 0 if the duration is null, the inner duration otherwise.
+func (d *Duration) Value() time.Duration {
+	if d == nil {
+		return 0
+	}
+	return d.Duration
+}

+ 111 - 0
authority/provisioner/duration_test.go

@@ -0,0 +1,111 @@
+package provisioner
+
+import (
+	"reflect"
+	"testing"
+	"time"
+)
+
+func TestNewDuration(t *testing.T) {
+	type args struct {
+		s string
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    *Duration
+		wantErr bool
+	}{
+		{"ok", args{"1h2m3s"}, &Duration{Duration: 3723 * time.Second}, false},
+		{"fail empty", args{""}, nil, true},
+		{"fail number", args{"123"}, nil, true},
+		{"fail string", args{"1hour"}, nil, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := NewDuration(tt.args.s)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("NewDuration() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("NewDuration() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestDuration_UnmarshalJSON(t *testing.T) {
+	type args struct {
+		data []byte
+	}
+	tests := []struct {
+		name    string
+		d       *Duration
+		args    args
+		want    *Duration
+		wantErr bool
+	}{
+		{"empty", new(Duration), args{[]byte{}}, new(Duration), true},
+		{"bad type", new(Duration), args{[]byte(`15`)}, new(Duration), true},
+		{"empty string", new(Duration), args{[]byte(`""`)}, new(Duration), true},
+		{"non duration", new(Duration), args{[]byte(`"15"`)}, new(Duration), true},
+		{"duration", new(Duration), args{[]byte(`"15m30s"`)}, &Duration{15*time.Minute + 30*time.Second}, false},
+		{"nil", nil, args{nil}, nil, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.d.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
+				t.Errorf("Duration.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(tt.d, tt.want) {
+				t.Errorf("Duration.UnmarshalJSON() = %v, want %v", tt.d, tt.want)
+			}
+		})
+	}
+}
+
+func TestDuration_MarshalJSON(t *testing.T) {
+	tests := []struct {
+		name    string
+		d       *Duration
+		want    []byte
+		wantErr bool
+	}{
+		{"string", &Duration{15*time.Minute + 30*time.Second}, []byte(`"15m30s"`), false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.d.MarshalJSON()
+			if (err != nil) != tt.wantErr {
+				t.Errorf("Duration.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("Duration.MarshalJSON() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestDuration_Value(t *testing.T) {
+	var dur *Duration
+	tests := []struct {
+		name     string
+		duration *Duration
+		want     time.Duration
+	}{
+		{"ok", &Duration{Duration: 1 * time.Minute}, 1 * time.Minute},
+		{"ok new", new(Duration), 0},
+		{"ok nil", nil, 0},
+		{"ok nil var", dur, 0},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := tt.duration.Value(); got != tt.want {
+				t.Errorf("Duration.Value() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 390 - 0
authority/provisioner/gcp.go

@@ -0,0 +1,390 @@
+package provisioner
+
+import (
+	"bytes"
+	"context"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/hex"
+	"fmt"
+	"io/ioutil"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+// gcpCertsURL is the url that serves Google OAuth2 public keys.
+const gcpCertsURL = "https://www.googleapis.com/oauth2/v3/certs"
+
+// gcpIdentityURL is the base url for the identity document in GCP.
+const gcpIdentityURL = "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity"
+
+// gcpPayload extends jwt.Claims with custom GCP attributes.
+type gcpPayload struct {
+	jose.Claims
+	AuthorizedParty string           `json:"azp"`
+	Email           string           `json:"email"`
+	EmailVerified   bool             `json:"email_verified"`
+	Google          gcpGooglePayload `json:"google"`
+}
+
+type gcpGooglePayload struct {
+	ComputeEngine gcpComputeEnginePayload `json:"compute_engine"`
+}
+
+type gcpComputeEnginePayload struct {
+	InstanceID                string            `json:"instance_id"`
+	InstanceName              string            `json:"instance_name"`
+	InstanceCreationTimestamp *jose.NumericDate `json:"instance_creation_timestamp"`
+	ProjectID                 string            `json:"project_id"`
+	ProjectNumber             int64             `json:"project_number"`
+	Zone                      string            `json:"zone"`
+	LicenseID                 []string          `json:"license_id"`
+}
+
+type gcpConfig struct {
+	CertsURL    string
+	IdentityURL string
+}
+
+func newGCPConfig() *gcpConfig {
+	return &gcpConfig{
+		CertsURL:    gcpCertsURL,
+		IdentityURL: gcpIdentityURL,
+	}
+}
+
+// GCP is the provisioner that supports identity tokens created by the Google
+// Cloud Platform metadata API.
+//
+// If DisableCustomSANs is true, only the internal DNS and IP will be added as a
+// SAN. By default it will accept any SAN in the CSR.
+//
+// If DisableTrustOnFirstUse is true, multiple sign request for this provisioner
+// with the same instance will be accepted. By default only the first request
+// will be accepted.
+//
+// If InstanceAge is set, only the instances with an instance_creation_timestamp
+// within the given period will be accepted.
+//
+// Google Identity docs are available at
+// https://cloud.google.com/compute/docs/instances/verifying-instance-identity
+type GCP struct {
+	Type                   string   `json:"type"`
+	Name                   string   `json:"name"`
+	ServiceAccounts        []string `json:"serviceAccounts"`
+	ProjectIDs             []string `json:"projectIDs"`
+	DisableCustomSANs      bool     `json:"disableCustomSANs"`
+	DisableTrustOnFirstUse bool     `json:"disableTrustOnFirstUse"`
+	InstanceAge            Duration `json:"instanceAge,omitempty"`
+	Claims                 *Claims  `json:"claims,omitempty"`
+	claimer                *Claimer
+	config                 *gcpConfig
+	keyStore               *keyStore
+	audiences              Audiences
+}
+
+// GetID returns the provisioner unique identifier. The name should uniquely
+// identify any GCP provisioner.
+func (p *GCP) GetID() string {
+	return "gcp/" + p.Name
+}
+
+// GetTokenID returns the identifier of the token. The default value for GCP the
+// SHA256 of "provisioner_id.instance_id", but if DisableTrustOnFirstUse is set
+// to true, then it will be the SHA256 of the token.
+func (p *GCP) GetTokenID(token string) (string, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return "", errors.Wrap(err, "error parsing token")
+	}
+
+	// If TOFU is disabled create an ID for the token, so it cannot be reused.
+	if p.DisableTrustOnFirstUse {
+		sum := sha256.Sum256([]byte(token))
+		return strings.ToLower(hex.EncodeToString(sum[:])), nil
+	}
+
+	// Get claims w/out verification.
+	var claims gcpPayload
+	if err = jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
+		return "", errors.Wrap(err, "error verifying claims")
+	}
+
+	// Create unique ID for Trust On First Use (TOFU). Only the first instance
+	// per provisioner is allowed as we don't have a way to trust the given
+	// sans.
+	unique := fmt.Sprintf("%s.%s", p.GetID(), claims.Google.ComputeEngine.InstanceID)
+	sum := sha256.Sum256([]byte(unique))
+	return strings.ToLower(hex.EncodeToString(sum[:])), nil
+}
+
+// GetName returns the name of the provisioner.
+func (p *GCP) GetName() string {
+	return p.Name
+}
+
+// GetType returns the type of provisioner.
+func (p *GCP) GetType() Type {
+	return TypeGCP
+}
+
+// GetEncryptedKey is not available in a GCP provisioner.
+func (p *GCP) GetEncryptedKey() (kid string, key string, ok bool) {
+	return "", "", false
+}
+
+// GetIdentityURL returns the url that generates the GCP token.
+func (p *GCP) GetIdentityURL(audience string) string {
+	// Initialize config if required
+	p.assertConfig()
+
+	q := url.Values{}
+	q.Add("audience", audience)
+	q.Add("format", "full")
+	q.Add("licenses", "FALSE")
+	return fmt.Sprintf("%s?%s", p.config.IdentityURL, q.Encode())
+}
+
+// GetIdentityToken does an HTTP request to the identity url.
+func (p *GCP) GetIdentityToken(subject, caURL string) (string, error) {
+	audience, err := generateSignAudience(caURL, p.GetID())
+	if err != nil {
+		return "", err
+	}
+
+	req, err := http.NewRequest("GET", p.GetIdentityURL(audience), http.NoBody)
+	if err != nil {
+		return "", errors.Wrap(err, "error creating identity request")
+	}
+	req.Header.Set("Metadata-Flavor", "Google")
+	resp, err := http.DefaultClient.Do(req)
+	if err != nil {
+		return "", errors.Wrap(err, "error doing identity request, are you in a GCP VM?")
+	}
+	defer resp.Body.Close()
+	b, err := ioutil.ReadAll(resp.Body)
+	if err != nil {
+		return "", errors.Wrap(err, "error on identity request")
+	}
+	if resp.StatusCode >= 400 {
+		return "", errors.Errorf("error on identity request: status=%d, response=%s", resp.StatusCode, b)
+	}
+	return string(bytes.TrimSpace(b)), nil
+}
+
+// Init validates and initializes the GCP provisioner.
+func (p *GCP) Init(config Config) error {
+	var err error
+	switch {
+	case p.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case p.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	case p.InstanceAge.Value() < 0:
+		return errors.New("provisioner instanceAge cannot be negative")
+	}
+	// Initialize config
+	p.assertConfig()
+	// Update claims with global ones
+	if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
+		return err
+	}
+	// Initialize key store
+	p.keyStore, err = newKeyStore(p.config.CertsURL)
+	if err != nil {
+		return err
+	}
+
+	p.audiences = config.Audiences.WithFragment(p.GetID())
+	return nil
+}
+
+// AuthorizeSign validates the given token and returns the sign options that
+// will be used on certificate creation.
+func (p *GCP) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	claims, err := p.authorizeToken(token)
+	if err != nil {
+		return nil, err
+	}
+
+	// Check for the sign ssh method, default to sign X.509
+	if m := MethodFromContext(ctx); m == SignSSHMethod {
+		if p.claimer.IsSSHCAEnabled() == false {
+			return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
+		}
+		return p.authorizeSSHSign(claims)
+	}
+
+	ce := claims.Google.ComputeEngine
+	// Enforce known common name and default DNS if configured.
+	// By default we we'll accept the CN and SANs in the CSR.
+	// There's no way to trust them other than TOFU.
+	var so []SignOption
+	if p.DisableCustomSANs {
+		dnsName1 := fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID)
+		dnsName2 := fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID)
+		so = append(so, commonNameSliceValidator([]string{
+			ce.InstanceName, ce.InstanceID, dnsName1, dnsName2,
+		}))
+		so = append(so, dnsNamesValidator([]string{
+			dnsName1, dnsName2,
+		}))
+	}
+
+	return append(so,
+		defaultPublicKeyValidator{},
+		profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeGCP, p.Name, claims.Subject, "InstanceID", ce.InstanceID, "InstanceName", ce.InstanceName),
+		newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
+	), nil
+}
+
+// AuthorizeRenewal returns an error if the renewal is disabled.
+func (p *GCP) AuthorizeRenewal(cert *x509.Certificate) error {
+	if p.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
+	}
+	return nil
+}
+
+// AuthorizeRevoke returns an error because revoke is not supported on GCP
+// provisioners.
+func (p *GCP) AuthorizeRevoke(token string) error {
+	return errors.New("revoke is not supported on a GCP provisioner")
+}
+
+// assertConfig initializes the config if it has not been initialized.
+func (p *GCP) assertConfig() {
+	if p.config == nil {
+		p.config = newGCPConfig()
+	}
+}
+
+// authorizeToken performs common jwt authorization actions and returns the
+// claims for case specific downstream parsing.
+// e.g. a Sign request will auth/validate different fields than a Revoke request.
+func (p *GCP) authorizeToken(token string) (*gcpPayload, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing token")
+	}
+	if len(jwt.Headers) == 0 {
+		return nil, errors.New("error parsing token: header is missing")
+	}
+
+	var found bool
+	var claims gcpPayload
+	kid := jwt.Headers[0].KeyID
+	keys := p.keyStore.Get(kid)
+	for _, key := range keys {
+		if err := jwt.Claims(key.Public(), &claims); err == nil {
+			found = true
+			break
+		}
+	}
+	if !found {
+		return nil, errors.Errorf("failed to validate payload: cannot find key for kid %s", kid)
+	}
+
+	// According to "rfc7519 JSON Web Token" acceptable skew should be no
+	// more than a few minutes.
+	now := time.Now().UTC()
+	if err = claims.ValidateWithLeeway(jose.Expected{
+		Issuer: "https://accounts.google.com",
+		Time:   now,
+	}, time.Minute); err != nil {
+		return nil, errors.Wrapf(err, "invalid token")
+	}
+
+	// validate audiences with the defaults
+	if !matchesAudience(claims.Audience, p.audiences.Sign) {
+		return nil, errors.New("invalid token: invalid audience claim (aud)")
+	}
+
+	// validate subject (service account)
+	if len(p.ServiceAccounts) > 0 {
+		var found bool
+		for _, sa := range p.ServiceAccounts {
+			if sa == claims.Subject || sa == claims.Email {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return nil, errors.New("invalid token: invalid subject claim")
+		}
+	}
+
+	// validate projects
+	if len(p.ProjectIDs) > 0 {
+		var found bool
+		for _, pi := range p.ProjectIDs {
+			if pi == claims.Google.ComputeEngine.ProjectID {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return nil, errors.New("invalid token: invalid project id")
+		}
+	}
+
+	// validate instance age
+	if d := p.InstanceAge.Value(); d > 0 {
+		if now.Sub(claims.Google.ComputeEngine.InstanceCreationTimestamp.Time()) > d {
+			return nil, errors.New("token google.compute_engine.instance_creation_timestamp is too old")
+		}
+	}
+
+	switch {
+	case claims.Google.ComputeEngine.InstanceID == "":
+		return nil, errors.New("token google.compute_engine.instance_id cannot be empty")
+	case claims.Google.ComputeEngine.InstanceName == "":
+		return nil, errors.New("token google.compute_engine.instance_name cannot be empty")
+	case claims.Google.ComputeEngine.ProjectID == "":
+		return nil, errors.New("token google.compute_engine.project_id cannot be empty")
+	case claims.Google.ComputeEngine.Zone == "":
+		return nil, errors.New("token google.compute_engine.zone cannot be empty")
+	}
+
+	return &claims, nil
+}
+
+// authorizeSSHSign returns the list of SignOption for a SignSSH request.
+func (p *GCP) authorizeSSHSign(claims *gcpPayload) ([]SignOption, error) {
+	ce := claims.Google.ComputeEngine
+
+	signOptions := []SignOption{
+		// set the key id to the token subject
+		sshCertificateKeyIDModifier(ce.InstanceName),
+	}
+
+	// Default to host + known hostnames
+	defaults := SSHOptions{
+		CertType: SSHHostCert,
+		Principals: []string{
+			fmt.Sprintf("%s.c.%s.internal", ce.InstanceName, ce.ProjectID),
+			fmt.Sprintf("%s.%s.c.%s.internal", ce.InstanceName, ce.Zone, ce.ProjectID),
+		},
+	}
+	// Validate user options
+	signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
+	// Set defaults if not given as user options
+	signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
+
+	return append(signOptions,
+		// set the default extensions
+		&sshDefaultExtensionModifier{},
+		// checks the validity bounds, and set the validity if has not been set
+		&sshCertificateValidityModifier{p.claimer},
+		// validate public key
+		&sshDefaultPublicKeyValidator{},
+		// require all the fields in the SSH certificate
+		&sshCertificateDefaultValidator{},
+	), nil
+}

+ 500 - 0
authority/provisioner/gcp_test.go

@@ -0,0 +1,500 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/hex"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"net/url"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+)
+
+func TestGCP_Getters(t *testing.T) {
+	p, err := generateGCP()
+	assert.FatalError(t, err)
+	id := "gcp/" + p.Name
+	if got := p.GetID(); got != id {
+		t.Errorf("GCP.GetID() = %v, want %v", got, id)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("GCP.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeGCP {
+		t.Errorf("GCP.GetType() = %v, want %v", got, TypeGCP)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != "" || key != "" || ok == true {
+		t.Errorf("GCP.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, "", "", false)
+	}
+
+	aud := "https://ca.smallstep.com/1.0/sign#" + url.QueryEscape(id)
+	expected := fmt.Sprintf("http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?audience=%s&format=full&licenses=FALSE", url.QueryEscape(aud))
+	if got := p.GetIdentityURL(aud); got != expected {
+		t.Errorf("GCP.GetIdentityURL() = %v, want %v", got, expected)
+	}
+}
+
+func TestGCP_GetTokenID(t *testing.T) {
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+	p1.Name = "name"
+
+	p2, err := generateGCP()
+	assert.FatalError(t, err)
+	p2.DisableTrustOnFirstUse = true
+
+	now := time.Now()
+	t1, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", "gcp/name",
+		"instance-id", "instance-name", "project-id", "zone",
+		now, &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	t2, err := generateGCPToken(p2.ServiceAccounts[0],
+		"https://accounts.google.com", p2.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		now, &p2.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	sum := sha256.Sum256([]byte("gcp/name.instance-id"))
+	want1 := strings.ToLower(hex.EncodeToString(sum[:]))
+	sum = sha256.Sum256([]byte(t2))
+	want2 := strings.ToLower(hex.EncodeToString(sum[:]))
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		gcp     *GCP
+		args    args
+		want    string
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, want1, false},
+		{"ok", p2, args{t2}, want2, false},
+		{"fail token", p1, args{"token"}, "", true},
+		{"fail claims", p1, args{"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.ey.fooo"}, "", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.gcp.GetTokenID(tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GCP.GetTokenID() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("GCP.GetTokenID() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestGCP_GetIdentityToken(t *testing.T) {
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+
+	t1, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/bad-request":
+			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+		default:
+			w.Write([]byte(t1))
+		}
+	}))
+	defer srv.Close()
+
+	type args struct {
+		subject string
+		caURL   string
+	}
+	tests := []struct {
+		name        string
+		gcp         *GCP
+		args        args
+		identityURL string
+		want        string
+		wantErr     bool
+	}{
+		{"ok", p1, args{"subject", "https://ca"}, srv.URL, t1, false},
+		{"fail ca url", p1, args{"subject", "://ca"}, srv.URL, "", true},
+		{"fail request", p1, args{"subject", "https://ca"}, srv.URL + "/bad-request", "", true},
+		{"fail url", p1, args{"subject", "https://ca"}, "://ca.smallstep.com", "", true},
+		{"fail connect", p1, args{"subject", "https://ca"}, "foobarzar", "", true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			tt.gcp.config.IdentityURL = tt.identityURL
+			got, err := tt.gcp.GetIdentityToken(tt.args.subject, tt.args.caURL)
+			t.Log(err)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GCP.GetIdentityToken() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if got != tt.want {
+				t.Errorf("GCP.GetIdentityToken() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestGCP_Init(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	config := Config{
+		Claims: globalProvisionerClaims,
+	}
+	badClaims := &Claims{
+		DefaultTLSDur: &Duration{0},
+	}
+	zero := Duration{Duration: 0}
+	type fields struct {
+		Type            string
+		Name            string
+		ServiceAccounts []string
+		InstanceAge     Duration
+		Claims          *Claims
+	}
+	type args struct {
+		config   Config
+		certsURL string
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		args    args
+		wantErr bool
+	}{
+		{"ok", fields{"GCP", "name", nil, zero, nil}, args{config, srv.URL}, false},
+		{"ok", fields{"GCP", "name", []string{"service-account"}, zero, nil}, args{config, srv.URL}, false},
+		{"ok", fields{"GCP", "name", []string{"service-account"}, Duration{Duration: 1 * time.Minute}, nil}, args{config, srv.URL}, false},
+		{"bad type", fields{"", "name", nil, zero, nil}, args{config, srv.URL}, true},
+		{"bad name", fields{"GCP", "", nil, zero, nil}, args{config, srv.URL}, true},
+		{"bad duration", fields{"GCP", "name", nil, Duration{Duration: -1 * time.Minute}, nil}, args{config, srv.URL}, true},
+		{"bad claims", fields{"GCP", "name", nil, zero, badClaims}, args{config, srv.URL}, true},
+		{"bad certs", fields{"GCP", "name", nil, zero, nil}, args{config, srv.URL + "/error"}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			p := &GCP{
+				Type:            tt.fields.Type,
+				Name:            tt.fields.Name,
+				ServiceAccounts: tt.fields.ServiceAccounts,
+				InstanceAge:     tt.fields.InstanceAge,
+				Claims:          tt.fields.Claims,
+				config: &gcpConfig{
+					CertsURL:    tt.args.certsURL,
+					IdentityURL: gcpIdentityURL,
+				},
+			}
+			if err := p.Init(tt.args.config); (err != nil) != tt.wantErr {
+				t.Errorf("GCP.Init() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestGCP_AuthorizeSign(t *testing.T) {
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+
+	p2, err := generateGCP()
+	assert.FatalError(t, err)
+	p2.DisableCustomSANs = true
+
+	p3, err := generateGCP()
+	assert.FatalError(t, err)
+	p3.ProjectIDs = []string{"other-project-id"}
+	p3.ServiceAccounts = []string{"foo@developer.gserviceaccount.com"}
+	p3.InstanceAge = Duration{1 * time.Minute}
+
+	aKey, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	t1, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	t2, err := generateGCPToken(p2.ServiceAccounts[0],
+		"https://accounts.google.com", p2.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p2.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	t3, err := generateGCPToken(p3.ServiceAccounts[0],
+		"https://accounts.google.com", p3.GetID(),
+		"instance-id", "instance-name", "other-project-id", "zone",
+		time.Now(), &p3.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	failKey, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), aKey)
+	assert.FatalError(t, err)
+	failIss, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://foo.bar.zar", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failAud, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", "gcp:foo",
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failExp, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now().Add(-360*time.Second), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failNbf, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now().Add(360*time.Second), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failServiceAccount, err := generateGCPToken("foo",
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failInvalidProjectID, err := generateGCPToken(p3.ServiceAccounts[0],
+		"https://accounts.google.com", p3.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p3.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failInvalidInstanceAge, err := generateGCPToken(p3.ServiceAccounts[0],
+		"https://accounts.google.com", p3.GetID(),
+		"instance-id", "instance-name", "other-project-id", "zone",
+		time.Now().Add(-1*time.Minute), &p3.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failInstanceID, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failInstanceName, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failProjectID, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+	failZone, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		gcp     *GCP
+		args    args
+		wantLen int
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, 4, false},
+		{"ok", p2, args{t2}, 6, false},
+		{"ok", p3, args{t3}, 4, false},
+		{"fail token", p1, args{"token"}, 0, true},
+		{"fail key", p1, args{failKey}, 0, true},
+		{"fail iss", p1, args{failIss}, 0, true},
+		{"fail aud", p1, args{failAud}, 0, true},
+		{"fail exp", p1, args{failExp}, 0, true},
+		{"fail nbf", p1, args{failNbf}, 0, true},
+		{"fail service account", p1, args{failServiceAccount}, 0, true},
+		{"fail invalid project id", p3, args{failInvalidProjectID}, 0, true},
+		{"fail invalid instance age", p3, args{failInvalidInstanceAge}, 0, true},
+		{"fail instance id", p1, args{failInstanceID}, 0, true},
+		{"fail instance name", p1, args{failInstanceName}, 0, true},
+		{"fail project id", p1, args{failProjectID}, 0, true},
+		{"fail zone", p1, args{failZone}, 0, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignMethod)
+			got, err := tt.gcp.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GCP.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			assert.Len(t, tt.wantLen, got)
+		})
+	}
+}
+
+func TestGCP_AuthorizeSign_SSH(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+
+	t1, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	pub := key.Public().Key
+	rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
+	assert.FatalError(t, err)
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"instance-name.c.project-id.internal", "instance-name.zone.c.project-id.internal"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+	expectedHostOptionsPrincipal1 := &SSHOptions{
+		CertType: "host", Principals: []string{"instance-name.c.project-id.internal"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+	expectedHostOptionsPrincipal2 := &SSHOptions{
+		CertType: "host", Principals: []string{"instance-name.zone.c.project-id.internal"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+
+	type args struct {
+		token   string
+		sshOpts SSHOptions
+		key     interface{}
+	}
+	tests := []struct {
+		name        string
+		gcp         *GCP
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"ok", p1, args{t1, SSHOptions{}, pub}, expectedHostOptions, false, false},
+		{"ok-rsa2048", p1, args{t1, SSHOptions{}, rsa2048.Public()}, expectedHostOptions, false, false},
+		{"ok-type", p1, args{t1, SSHOptions{CertType: "host"}, pub}, expectedHostOptions, false, false},
+		{"ok-principals", p1, args{t1, SSHOptions{Principals: []string{"instance-name.c.project-id.internal", "instance-name.zone.c.project-id.internal"}}, pub}, expectedHostOptions, false, false},
+		{"ok-principal1", p1, args{t1, SSHOptions{Principals: []string{"instance-name.c.project-id.internal"}}, pub}, expectedHostOptionsPrincipal1, false, false},
+		{"ok-principal2", p1, args{t1, SSHOptions{Principals: []string{"instance-name.zone.c.project-id.internal"}}, pub}, expectedHostOptionsPrincipal2, false, false},
+		{"ok-options", p1, args{t1, SSHOptions{CertType: "host", Principals: []string{"instance-name.c.project-id.internal", "instance-name.zone.c.project-id.internal"}}, pub}, expectedHostOptions, false, false},
+		{"fail-rsa1024", p1, args{t1, SSHOptions{}, rsa1024.Public()}, expectedHostOptions, false, true},
+		{"fail-type", p1, args{t1, SSHOptions{CertType: "user"}, pub}, nil, false, true},
+		{"fail-principal", p1, args{t1, SSHOptions{Principals: []string{"smallstep.com"}}, pub}, nil, false, true},
+		{"fail-extra-principal", p1, args{t1, SSHOptions{Principals: []string{"instance-name.c.project-id.internal", "instance-name.zone.c.project-id.internal", "smallstep.com"}}, pub}, nil, false, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			got, err := tt.gcp.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("GCP.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else if assert.NotNil(t, got) {
+				cert, err := signSSHCertificate(tt.args.key, tt.args.sshOpts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestGCP_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+	p2, err := generateGCP()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		prov    *GCP
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{nil}, false},
+		{"fail", p2, args{nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.prov.AuthorizeRenewal(tt.args.cert); (err != nil) != tt.wantErr {
+				t.Errorf("GCP.AuthorizeRenewal() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestGCP_AuthorizeRevoke(t *testing.T) {
+	p1, err := generateGCP()
+	assert.FatalError(t, err)
+
+	t1, err := generateGCPToken(p1.ServiceAccounts[0],
+		"https://accounts.google.com", p1.GetID(),
+		"instance-id", "instance-name", "project-id", "zone",
+		time.Now(), &p1.keyStore.keySet.Keys[0])
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		gcp     *GCP
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{t1}, true}, // revoke is disabled
+		{"fail", p1, args{"token"}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.gcp.AuthorizeRevoke(tt.args.token); (err != nil) != tt.wantErr {
+				t.Errorf("GCP.AuthorizeRevoke() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}

+ 218 - 0
authority/provisioner/jwk.go

@@ -0,0 +1,218 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/crypto/x509util"
+	"github.com/smallstep/cli/jose"
+)
+
+// jwtPayload extends jwt.Claims with step attributes.
+type jwtPayload struct {
+	jose.Claims
+	SANs []string     `json:"sans,omitempty"`
+	Step *stepPayload `json:"step,omitempty"`
+}
+
+type stepPayload struct {
+	SSH *SSHOptions `json:"ssh,omitempty"`
+}
+
+// JWK is the default provisioner, an entity that can sign tokens necessary for
+// signature requests.
+type JWK struct {
+	Type         string           `json:"type"`
+	Name         string           `json:"name"`
+	Key          *jose.JSONWebKey `json:"key"`
+	EncryptedKey string           `json:"encryptedKey,omitempty"`
+	Claims       *Claims          `json:"claims,omitempty"`
+	claimer      *Claimer
+	audiences    Audiences
+}
+
+// GetID returns the provisioner unique identifier. The name and credential id
+// should uniquely identify any JWK provisioner.
+func (p *JWK) GetID() string {
+	return p.Name + ":" + p.Key.KeyID
+}
+
+// GetTokenID returns the identifier of the token.
+func (p *JWK) GetTokenID(ott string) (string, error) {
+	// Validate payload
+	token, err := jose.ParseSigned(ott)
+	if err != nil {
+		return "", errors.Wrap(err, "error parsing token")
+	}
+
+	// Get claims w/out verification. We need to look up the provisioner
+	// key in order to verify the claims and we need the issuer from the claims
+	// before we can look up the provisioner.
+	var claims jose.Claims
+	if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
+		return "", errors.Wrap(err, "error verifying claims")
+	}
+	return claims.ID, nil
+}
+
+// GetName returns the name of the provisioner.
+func (p *JWK) GetName() string {
+	return p.Name
+}
+
+// GetType returns the type of provisioner.
+func (p *JWK) GetType() Type {
+	return TypeJWK
+}
+
+// GetEncryptedKey returns the base provisioner encrypted key if it's defined.
+func (p *JWK) GetEncryptedKey() (string, string, bool) {
+	return p.Key.KeyID, p.EncryptedKey, len(p.EncryptedKey) > 0
+}
+
+// Init initializes and validates the fields of a JWK type.
+func (p *JWK) Init(config Config) (err error) {
+	switch {
+	case p.Type == "":
+		return errors.New("provisioner type cannot be empty")
+	case p.Name == "":
+		return errors.New("provisioner name cannot be empty")
+	case p.Key == nil:
+		return errors.New("provisioner key cannot be empty")
+	}
+
+	// Update claims with global ones
+	if p.claimer, err = NewClaimer(p.Claims, config.Claims); err != nil {
+		return err
+	}
+
+	p.audiences = config.Audiences
+	return err
+}
+
+// authorizeToken performs common jwt authorization actions and returns the
+// claims for case specific downstream parsing.
+// e.g. a Sign request will auth/validate different fields than a Revoke request.
+func (p *JWK) authorizeToken(token string, audiences []string) (*jwtPayload, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing token")
+	}
+
+	var claims jwtPayload
+	if err = jwt.Claims(p.Key, &claims); err != nil {
+		return nil, errors.Wrap(err, "error parsing claims")
+	}
+
+	// According to "rfc7519 JSON Web Token" acceptable skew should be no
+	// more than a few minutes.
+	if err = claims.ValidateWithLeeway(jose.Expected{
+		Issuer: p.Name,
+		Time:   time.Now().UTC(),
+	}, time.Minute); err != nil {
+		return nil, errors.Wrapf(err, "invalid token")
+	}
+
+	// validate audiences with the defaults
+	if !matchesAudience(claims.Audience, audiences) {
+		return nil, errors.New("invalid token: invalid audience claim (aud)")
+	}
+
+	if claims.Subject == "" {
+		return nil, errors.New("token subject cannot be empty")
+	}
+
+	return &claims, nil
+}
+
+// AuthorizeRevoke returns an error if the provisioner does not have rights to
+// revoke the certificate with serial number in the `sub` property.
+func (p *JWK) AuthorizeRevoke(token string) error {
+	_, err := p.authorizeToken(token, p.audiences.Revoke)
+	return err
+}
+
+// AuthorizeSign validates the given token.
+func (p *JWK) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	claims, err := p.authorizeToken(token, p.audiences.Sign)
+	if err != nil {
+		return nil, err
+	}
+
+	// Check for SSH token
+	if claims.Step != nil && claims.Step.SSH != nil {
+		if p.claimer.IsSSHCAEnabled() == false {
+			return nil, errors.Errorf("ssh ca is disabled for provisioner %s", p.GetID())
+		}
+		return p.authorizeSSHSign(claims)
+	}
+
+	// NOTE: This is for backwards compatibility with older versions of cli
+	// and certificates. Older versions added the token subject as the only SAN
+	// in a CSR by default.
+	if len(claims.SANs) == 0 {
+		claims.SANs = []string{claims.Subject}
+	}
+
+	dnsNames, ips, emails := x509util.SplitSANs(claims.SANs)
+	return []SignOption{
+		defaultPublicKeyValidator{},
+		commonNameValidator(claims.Subject),
+		dnsNamesValidator(dnsNames),
+		ipAddressesValidator(ips),
+		emailAddressesValidator(emails),
+		profileDefaultDuration(p.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeJWK, p.Name, p.Key.KeyID),
+		newValidityValidator(p.claimer.MinTLSCertDuration(), p.claimer.MaxTLSCertDuration()),
+	}, nil
+}
+
+// AuthorizeRenewal returns an error if the renewal is disabled.
+func (p *JWK) AuthorizeRenewal(cert *x509.Certificate) error {
+	if p.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", p.GetID())
+	}
+	return nil
+}
+
+// authorizeSSHSign returns the list of SignOption for a SignSSH request.
+func (p *JWK) authorizeSSHSign(claims *jwtPayload) ([]SignOption, error) {
+	t := now()
+	opts := claims.Step.SSH
+	signOptions := []SignOption{
+		// validates user's SSHOptions with the ones in the token
+		sshCertificateOptionsValidator(*opts),
+		// set the key id to the token subject
+		sshCertificateKeyIDModifier(claims.Subject),
+	}
+
+	// Add modifiers from custom claims
+	if opts.CertType != "" {
+		signOptions = append(signOptions, sshCertificateCertTypeModifier(opts.CertType))
+	}
+	if len(opts.Principals) > 0 {
+		signOptions = append(signOptions, sshCertificatePrincipalsModifier(opts.Principals))
+	}
+	if !opts.ValidAfter.IsZero() {
+		signOptions = append(signOptions, sshCertificateValidAfterModifier(opts.ValidAfter.RelativeTime(t).Unix()))
+	}
+	if !opts.ValidBefore.IsZero() {
+		signOptions = append(signOptions, sshCertificateValidBeforeModifier(opts.ValidBefore.RelativeTime(t).Unix()))
+	}
+
+	// Default to a user certificate with no principals if not set
+	signOptions = append(signOptions, sshCertificateDefaultsModifier{CertType: SSHUserCert})
+
+	return append(signOptions,
+		// set the default extensions
+		&sshDefaultExtensionModifier{},
+		// checks the validity bounds, and set the validity if has not been set
+		&sshCertificateValidityModifier{p.claimer},
+		// validate public key
+		&sshDefaultPublicKeyValidator{},
+		// require all the fields in the SSH certificate
+		&sshCertificateDefaultValidator{},
+	), nil
+}

+ 540 - 0
authority/provisioner/jwk_test.go

@@ -0,0 +1,540 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"errors"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/jose"
+)
+
+var (
+	defaultDisableRenewal   = false
+	defaultEnableSSHCA      = true
+	globalProvisionerClaims = Claims{
+		MinTLSDur:         &Duration{5 * time.Minute},
+		MaxTLSDur:         &Duration{24 * time.Hour},
+		DefaultTLSDur:     &Duration{24 * time.Hour},
+		DisableRenewal:    &defaultDisableRenewal,
+		MinUserSSHDur:     &Duration{Duration: 5 * time.Minute}, // User SSH certs
+		MaxUserSSHDur:     &Duration{Duration: 24 * time.Hour},
+		DefaultUserSSHDur: &Duration{Duration: 4 * time.Hour},
+		MinHostSSHDur:     &Duration{Duration: 5 * time.Minute}, // Host SSH certs
+		MaxHostSSHDur:     &Duration{Duration: 30 * 24 * time.Hour},
+		DefaultHostSSHDur: &Duration{Duration: 30 * 24 * time.Hour},
+		EnableSSHCA:       &defaultEnableSSHCA,
+	}
+)
+
+func TestJWK_Getters(t *testing.T) {
+	p, err := generateJWK()
+	assert.FatalError(t, err)
+	if got := p.GetID(); got != p.Name+":"+p.Key.KeyID {
+		t.Errorf("JWK.GetID() = %v, want %v:%v", got, p.Name, p.Key.KeyID)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("JWK.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeJWK {
+		t.Errorf("JWK.GetType() = %v, want %v", got, TypeJWK)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != p.Key.KeyID || key != p.EncryptedKey || ok == false {
+		t.Errorf("JWK.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, p.Key.KeyID, p.EncryptedKey, true)
+	}
+	p.EncryptedKey = ""
+	kid, key, ok = p.GetEncryptedKey()
+	if kid != p.Key.KeyID || key != "" || ok == true {
+		t.Errorf("JWK.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, p.Key.KeyID, "", false)
+	}
+}
+
+func TestJWK_Init(t *testing.T) {
+	type ProvisionerValidateTest struct {
+		p   *JWK
+		err error
+	}
+	tests := map[string]func(*testing.T) ProvisionerValidateTest{
+		"fail-empty": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &JWK{},
+				err: errors.New("provisioner type cannot be empty"),
+			}
+		},
+		"fail-empty-name": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p: &JWK{
+					Type: "JWK",
+				},
+				err: errors.New("provisioner name cannot be empty"),
+			}
+		},
+		"fail-empty-type": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &JWK{Name: "foo"},
+				err: errors.New("provisioner type cannot be empty"),
+			}
+		},
+		"fail-empty-key": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &JWK{Name: "foo", Type: "bar"},
+				err: errors.New("provisioner key cannot be empty"),
+			}
+		},
+		"fail-bad-claims": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p:   &JWK{Name: "foo", Type: "bar", Key: &jose.JSONWebKey{}, audiences: testAudiences, Claims: &Claims{DefaultTLSDur: &Duration{0}}},
+				err: errors.New("claims: DefaultTLSCertDuration must be greater than 0"),
+			}
+		},
+		"ok": func(t *testing.T) ProvisionerValidateTest {
+			return ProvisionerValidateTest{
+				p: &JWK{Name: "foo", Type: "bar", Key: &jose.JSONWebKey{}, audiences: testAudiences},
+			}
+		},
+	}
+
+	config := Config{
+		Claims:    globalProvisionerClaims,
+		Audiences: testAudiences,
+	}
+	for name, get := range tests {
+		t.Run(name, func(t *testing.T) {
+			tc := get(t)
+			err := tc.p.Init(config)
+			if err != nil {
+				if assert.NotNil(t, tc.err) {
+					assert.Equals(t, tc.err.Error(), err.Error())
+				}
+			} else {
+				assert.Nil(t, tc.err)
+			}
+		})
+	}
+}
+
+func TestJWK_authorizeToken(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	p2, err := generateJWK()
+	assert.FatalError(t, err)
+
+	key1, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+	key2, err := decryptJSONWebKey(p2.EncryptedKey)
+	assert.FatalError(t, err)
+
+	t1, err := generateSimpleToken(p1.Name, testAudiences.Sign[0], key1)
+	assert.FatalError(t, err)
+	t2, err := generateSimpleToken(p2.Name, testAudiences.Sign[1], key2)
+	assert.FatalError(t, err)
+	t3, err := generateToken("test.smallstep.com", p1.Name, testAudiences.Sign[0], "", []string{}, time.Now(), key1)
+	assert.FatalError(t, err)
+
+	// Invalid tokens
+	parts := strings.Split(t1, ".")
+	key3, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+	// missing key
+	failKey, err := generateSimpleToken(p1.Name, testAudiences.Sign[0], key3)
+	assert.FatalError(t, err)
+	// invalid token
+	failTok := "foo." + parts[1] + "." + parts[2]
+	// invalid claims
+	failClaims := parts[0] + ".foo." + parts[1]
+	// invalid issuer
+	failIss, err := generateSimpleToken("foobar", testAudiences.Sign[0], key1)
+	assert.FatalError(t, err)
+	// invalid audience
+	failAud, err := generateSimpleToken(p1.Name, "foobar", key1)
+	assert.FatalError(t, err)
+	// invalid signature
+	failSig := t1[0 : len(t1)-2]
+	// no subject
+	failSub, err := generateToken("", p1.Name, testAudiences.Sign[0], "", []string{"test.smallstep.com"}, time.Now(), key1)
+	assert.FatalError(t, err)
+	// expired
+	failExp, err := generateToken("subject", p1.Name, testAudiences.Sign[0], "", []string{"test.smallstep.com"}, time.Now().Add(-360*time.Second), key1)
+	assert.FatalError(t, err)
+	// not before
+	failNbf, err := generateToken("subject", p1.Name, testAudiences.Sign[0], "", []string{"test.smallstep.com"}, time.Now().Add(360*time.Second), key1)
+	assert.FatalError(t, err)
+
+	// Remove encrypted key for p2
+	p2.EncryptedKey = ""
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name string
+		prov *JWK
+		args args
+		err  error
+	}{
+		{"fail-token", p1, args{failTok}, errors.New("error parsing token")},
+		{"fail-key", p1, args{failKey}, errors.New("error parsing claims")},
+		{"fail-claims", p1, args{failClaims}, errors.New("error parsing claims")},
+		{"fail-signature", p1, args{failSig}, errors.New("error parsing claims: square/go-jose: error in cryptographic primitive")},
+		{"fail-issuer", p1, args{failIss}, errors.New("invalid token: square/go-jose/jwt: validation failed, invalid issuer claim (iss)")},
+		{"fail-expired", p1, args{failExp}, errors.New("invalid token: square/go-jose/jwt: validation failed, token is expired (exp)")},
+		{"fail-not-before", p1, args{failNbf}, errors.New("invalid token: square/go-jose/jwt: validation failed, token not valid yet (nbf)")},
+		{"fail-audience", p1, args{failAud}, errors.New("invalid token: invalid audience claim (aud)")},
+		{"fail-subject", p1, args{failSub}, errors.New("token subject cannot be empty")},
+		{"ok", p1, args{t1}, nil},
+		{"ok-no-encrypted-key", p2, args{t2}, nil},
+		{"ok-no-sans", p1, args{t3}, nil},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got, err := tt.prov.authorizeToken(tt.args.token, testAudiences.Sign); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				assert.Nil(t, tt.err)
+				assert.NotNil(t, got)
+			}
+		})
+	}
+}
+
+func TestJWK_AuthorizeRevoke(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	key1, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+	t1, err := generateSimpleToken(p1.Name, testAudiences.Revoke[0], key1)
+	assert.FatalError(t, err)
+	// invalid signature
+	failSig := t1[0 : len(t1)-2]
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name string
+		prov *JWK
+		args args
+		err  error
+	}{
+		{"fail-signature", p1, args{failSig}, errors.New("error parsing claims: square/go-jose: error in cryptographic primitive")},
+		{"ok", p1, args{t1}, nil},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.prov.AuthorizeRevoke(tt.args.token); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			}
+		})
+	}
+}
+
+func TestJWK_AuthorizeSign(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	key1, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+
+	t1, err := generateSimpleToken(p1.Name, testAudiences.Sign[0], key1)
+	assert.FatalError(t, err)
+
+	t2, err := generateToken("subject", p1.Name, testAudiences.Sign[0], "name@smallstep.com", []string{}, time.Now(), key1)
+	assert.FatalError(t, err)
+
+	// invalid signature
+	failSig := t1[0 : len(t1)-2]
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name string
+		prov *JWK
+		args args
+		err  error
+	}{
+		{"fail-signature", p1, args{failSig}, errors.New("error parsing claims: square/go-jose: error in cryptographic primitive")},
+		{"ok-sans", p1, args{t1}, nil},
+		{"ok-no-sans", p1, args{t2}, nil},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignMethod)
+			if got, err := tt.prov.AuthorizeSign(ctx, tt.args.token); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				if assert.NotNil(t, got) {
+					assert.Len(t, 8, got)
+
+					_cnv := got[1]
+					cnv, ok := _cnv.(commonNameValidator)
+					assert.True(t, ok)
+					assert.Equals(t, string(cnv), "subject")
+
+					_dnv := got[2]
+					dnv, ok := _dnv.(dnsNamesValidator)
+					assert.True(t, ok)
+					if tt.name == "ok-sans" {
+						assert.Equals(t, []string(dnv), []string{"test.smallstep.com"})
+					} else {
+						assert.Equals(t, []string(dnv), []string{"subject"})
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestJWK_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	p2, err := generateJWK()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		prov    *JWK
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{nil}, false},
+		{"fail", p2, args{nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.prov.AuthorizeRenewal(tt.args.cert); (err != nil) != tt.wantErr {
+				t.Errorf("JWK.AuthorizeRenewal() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestJWK_AuthorizeSign_SSH(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	jwk, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+
+	iss, aud := p1.Name, testAudiences.Sign[0]
+
+	t1, err := generateSimpleSSHUserToken(iss, aud, jwk)
+	assert.FatalError(t, err)
+
+	t2, err := generateSimpleSSHHostToken(iss, aud, jwk)
+	assert.FatalError(t, err)
+
+	// invalid signature
+	failSig := t1[0 : len(t1)-2]
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	pub := key.Public().Key
+	rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
+	assert.FatalError(t, err)
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	userDuration := p1.claimer.DefaultUserSSHCertDuration()
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedUserOptions := &SSHOptions{
+		CertType: "user", Principals: []string{"name"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(userDuration)),
+	}
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"smallstep.com"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+
+	type args struct {
+		token   string
+		sshOpts SSHOptions
+		key     interface{}
+	}
+	tests := []struct {
+		name        string
+		prov        *JWK
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"user", p1, args{t1, SSHOptions{}, pub}, expectedUserOptions, false, false},
+		{"user-rsa2048", p1, args{t1, SSHOptions{}, rsa2048.Public()}, expectedUserOptions, false, false},
+		{"user-type", p1, args{t1, SSHOptions{CertType: "user"}, pub}, expectedUserOptions, false, false},
+		{"user-principals", p1, args{t1, SSHOptions{Principals: []string{"name"}}, pub}, expectedUserOptions, false, false},
+		{"user-options", p1, args{t1, SSHOptions{CertType: "user", Principals: []string{"name"}}, pub}, expectedUserOptions, false, false},
+		{"host", p1, args{t2, SSHOptions{}, pub}, expectedHostOptions, false, false},
+		{"host-type", p1, args{t2, SSHOptions{CertType: "host"}, pub}, expectedHostOptions, false, false},
+		{"host-principals", p1, args{t2, SSHOptions{Principals: []string{"smallstep.com"}}, pub}, expectedHostOptions, false, false},
+		{"host-options", p1, args{t2, SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, pub}, expectedHostOptions, false, false},
+		{"fail-signature", p1, args{failSig, SSHOptions{}, pub}, nil, true, false},
+		{"rail-rsa1024", p1, args{t1, SSHOptions{}, rsa1024.Public()}, expectedUserOptions, false, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			got, err := tt.prov.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else if assert.NotNil(t, got) {
+				cert, err := signSSHCertificate(tt.args.key, tt.args.sshOpts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestJWK_AuthorizeSign_SSHOptions(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	p1, err := generateJWK()
+	assert.FatalError(t, err)
+	jwk, err := decryptJSONWebKey(p1.EncryptedKey)
+	assert.FatalError(t, err)
+
+	sub, iss, aud, iat := "subject@smallstep.com", p1.Name, testAudiences.Sign[0], time.Now()
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	userDuration := p1.claimer.DefaultUserSSHCertDuration()
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedUserOptions := &SSHOptions{
+		CertType: "user", Principals: []string{"name"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(userDuration)),
+	}
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"smallstep.com"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+	type args struct {
+		sub, iss, aud string
+		iat           time.Time
+		tokSSHOpts    *SSHOptions
+		userSSHOpts   *SSHOptions
+		jwk           *jose.JSONWebKey
+	}
+	tests := []struct {
+		name        string
+		prov        *JWK
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"ok-user", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, expectedUserOptions, false, false},
+		{"ok-host", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, &SSHOptions{}, jwk}, expectedHostOptions, false, false},
+		{"ok-user-opts", p1, args{sub, iss, aud, iat, &SSHOptions{}, &SSHOptions{CertType: "user", Principals: []string{"name"}}, jwk}, expectedUserOptions, false, false},
+		{"ok-host-opts", p1, args{sub, iss, aud, iat, &SSHOptions{}, &SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, jwk}, expectedHostOptions, false, false},
+		{"ok-user-mixed", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user"}, &SSHOptions{Principals: []string{"name"}}, jwk}, expectedUserOptions, false, false},
+		{"ok-host-mixed", p1, args{sub, iss, aud, iat, &SSHOptions{Principals: []string{"smallstep.com"}}, &SSHOptions{CertType: "host"}, jwk}, expectedHostOptions, false, false},
+		{"ok-user-validAfter", p1, args{sub, iss, aud, iat, &SSHOptions{
+			CertType: "user", Principals: []string{"name"},
+		}, &SSHOptions{
+			ValidAfter: NewTimeDuration(tm.Add(-time.Hour)),
+		}, jwk}, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm.Add(-time.Hour)), ValidBefore: NewTimeDuration(tm.Add(userDuration - time.Hour)),
+		}, false, false},
+		{"ok-user-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{
+			CertType: "user", Principals: []string{"name"},
+		}, &SSHOptions{
+			ValidBefore: NewTimeDuration(tm.Add(time.Hour)),
+		}, jwk}, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(time.Hour)),
+		}, false, false},
+		{"ok-user-validAfter-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{
+			CertType: "user", Principals: []string{"name"},
+		}, &SSHOptions{
+			ValidAfter: NewTimeDuration(tm.Add(10 * time.Minute)), ValidBefore: NewTimeDuration(tm.Add(time.Hour)),
+		}, jwk}, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm.Add(10 * time.Minute)), ValidBefore: NewTimeDuration(tm.Add(time.Hour)),
+		}, false, false},
+		{"ok-user-match", p1, args{sub, iss, aud, iat, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(1 * time.Hour)),
+		}, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(1 * time.Hour)),
+		}, jwk}, &SSHOptions{
+			CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(time.Hour)),
+		}, false, false},
+		{"fail-certType", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{CertType: "host"}, jwk}, nil, false, true},
+		{"fail-principals", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{Principals: []string{"root"}}, jwk}, nil, false, true},
+		{"fail-validAfter", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}, ValidAfter: NewTimeDuration(tm)}, &SSHOptions{ValidAfter: NewTimeDuration(tm.Add(time.Hour))}, jwk}, nil, false, true},
+		{"fail-validBefore", p1, args{sub, iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}, ValidBefore: NewTimeDuration(tm.Add(time.Hour))}, &SSHOptions{ValidBefore: NewTimeDuration(tm.Add(10 * time.Hour))}, jwk}, nil, false, true},
+		{"fail-subject", p1, args{"", iss, aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, nil, true, false},
+		{"fail-issuer", p1, args{sub, "invalid", aud, iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, nil, true, false},
+		{"fail-audience", p1, args{sub, iss, "invalid", iat, &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, nil, true, false},
+		{"fail-expired", p1, args{sub, iss, aud, iat.Add(-6 * time.Minute), &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, nil, true, false},
+		{"fail-notBefore", p1, args{sub, iss, aud, iat.Add(5 * time.Minute), &SSHOptions{CertType: "user", Principals: []string{"name"}}, &SSHOptions{}, jwk}, nil, true, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			token, err := generateSSHToken(tt.args.sub, tt.args.iss, tt.args.aud, tt.args.iat, tt.args.tokSSHOpts, tt.args.jwk)
+			assert.FatalError(t, err)
+			if got, err := tt.prov.AuthorizeSign(ctx, token); (err != nil) != tt.wantErr {
+				t.Errorf("JWK.AuthorizeSign() error = %v, wantErr %v", err, tt.wantErr)
+			} else if !tt.wantErr && assert.NotNil(t, got) {
+				var opts SSHOptions
+				if tt.args.userSSHOpts != nil {
+					opts = *tt.args.userSSHOpts
+				}
+				cert, err := signSSHCertificate(key.Public().Key, opts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}

+ 147 - 0
authority/provisioner/keystore.go

@@ -0,0 +1,147 @@
+package provisioner
+
+import (
+	"encoding/json"
+	"math/rand"
+	"net/http"
+	"regexp"
+	"strconv"
+	"sync"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+const (
+	defaultCacheAge    = 12 * time.Hour
+	defaultCacheJitter = 1 * time.Hour
+)
+
+var maxAgeRegex = regexp.MustCompile("max-age=([0-9]+)")
+
+type keyStore struct {
+	sync.RWMutex
+	uri    string
+	keySet jose.JSONWebKeySet
+	timer  *time.Timer
+	expiry time.Time
+	jitter time.Duration
+}
+
+func newKeyStore(uri string) (*keyStore, error) {
+	keys, age, err := getKeysFromJWKsURI(uri)
+	if err != nil {
+		return nil, err
+	}
+	ks := &keyStore{
+		uri:    uri,
+		keySet: keys,
+		expiry: getExpirationTime(age),
+		jitter: getCacheJitter(age),
+	}
+	next := ks.nextReloadDuration(age)
+	ks.timer = time.AfterFunc(next, ks.reload)
+	return ks, nil
+}
+
+func (ks *keyStore) Close() {
+	ks.timer.Stop()
+}
+
+func (ks *keyStore) Get(kid string) (keys []jose.JSONWebKey) {
+	ks.RLock()
+	// Force reload if expiration has passed
+	if time.Now().After(ks.expiry) {
+		ks.RUnlock()
+		ks.reload()
+		ks.RLock()
+	}
+	keys = ks.keySet.Key(kid)
+	ks.RUnlock()
+	return
+}
+
+func (ks *keyStore) reload() {
+	var next time.Duration
+	keys, age, err := getKeysFromJWKsURI(ks.uri)
+	if err != nil {
+		next = ks.nextReloadDuration(ks.jitter / 2)
+	} else {
+		ks.Lock()
+		ks.keySet = keys
+		ks.expiry = getExpirationTime(age)
+		ks.jitter = getCacheJitter(age)
+		next = ks.nextReloadDuration(age)
+		ks.Unlock()
+	}
+
+	ks.Lock()
+	ks.timer.Reset(next)
+	ks.Unlock()
+}
+
+// nextReloadDuration would return the duration for the next rotation. If age is
+// 0 it will randomly rotate between 0-12 hours, but every time we call to Get
+// it will automatically rotate.
+func (ks *keyStore) nextReloadDuration(age time.Duration) time.Duration {
+	n := rand.Int63n(int64(ks.jitter))
+	age -= time.Duration(n)
+	return abs(age)
+}
+
+func getKeysFromJWKsURI(uri string) (jose.JSONWebKeySet, time.Duration, error) {
+	var keys jose.JSONWebKeySet
+	resp, err := http.Get(uri)
+	if err != nil {
+		return keys, 0, errors.Wrapf(err, "failed to connect to %s", uri)
+	}
+	defer resp.Body.Close()
+	if err := json.NewDecoder(resp.Body).Decode(&keys); err != nil {
+		return keys, 0, errors.Wrapf(err, "error reading %s", uri)
+	}
+	return keys, getCacheAge(resp.Header.Get("cache-control")), nil
+}
+
+func getCacheAge(cacheControl string) time.Duration {
+	age := defaultCacheAge
+	if len(cacheControl) > 0 {
+		match := maxAgeRegex.FindAllStringSubmatch(cacheControl, -1)
+		if len(match) > 0 {
+			if len(match[0]) == 2 {
+				maxAge := match[0][1]
+				maxAgeInt, err := strconv.ParseInt(maxAge, 10, 64)
+				if err != nil {
+					return defaultCacheAge
+				}
+				age = time.Duration(maxAgeInt) * time.Second
+			}
+		}
+	}
+	return age
+}
+
+func getCacheJitter(age time.Duration) time.Duration {
+	switch {
+	case age > time.Hour:
+		return defaultCacheJitter
+	case age == 0:
+		// Avoids a 0 jitter. The duration is not important as it will rotate
+		// automatically on each Get request.
+		return defaultCacheJitter
+	default:
+		return age / 3
+	}
+}
+
+func getExpirationTime(age time.Duration) time.Time {
+	return time.Now().Truncate(time.Second).Add(age)
+}
+
+// abs returns the absolute value of n.
+func abs(n time.Duration) time.Duration {
+	if n < 0 {
+		return -n
+	}
+	return n
+}

+ 192 - 0
authority/provisioner/keystore_test.go

@@ -0,0 +1,192 @@
+package provisioner
+
+import (
+	"encoding/json"
+	"fmt"
+	"reflect"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/jose"
+)
+
+func Test_newKeyStore(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+	ks, err := newKeyStore(srv.URL)
+	assert.FatalError(t, err)
+	defer ks.Close()
+
+	type args struct {
+		uri string
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    jose.JSONWebKeySet
+		wantErr bool
+	}{
+		{"ok", args{srv.URL}, ks.keySet, false},
+		{"fail", args{srv.URL + "/error"}, jose.JSONWebKeySet{}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := newKeyStore(tt.args.uri)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("newKeyStore() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err == nil {
+				if !reflect.DeepEqual(got.keySet, tt.want) {
+					t.Errorf("newKeyStore() = %v, want %v", got, tt.want)
+				}
+				got.Close()
+			}
+		})
+	}
+}
+
+func Test_keyStore(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	ks, err := newKeyStore(srv.URL + "/random")
+	assert.FatalError(t, err)
+	defer ks.Close()
+	ks.RLock()
+	keySet1 := ks.keySet
+	ks.RUnlock()
+	// Check contents
+	assert.Len(t, 2, keySet1.Keys)
+	assert.Len(t, 1, ks.Get(keySet1.Keys[0].KeyID))
+	assert.Len(t, 1, ks.Get(keySet1.Keys[1].KeyID))
+	assert.Len(t, 0, ks.Get("foobar"))
+
+	// Wait for rotation
+	time.Sleep(5 * time.Second)
+
+	ks.RLock()
+	keySet2 := ks.keySet
+	ks.RUnlock()
+	if reflect.DeepEqual(keySet1, keySet2) {
+		t.Error("keyStore did not rotated")
+	}
+
+	// Check contents
+	assert.Len(t, 2, keySet2.Keys)
+	assert.Len(t, 1, ks.Get(keySet2.Keys[0].KeyID))
+	assert.Len(t, 1, ks.Get(keySet2.Keys[1].KeyID))
+	assert.Len(t, 0, ks.Get("foobar"))
+
+	// Check hits
+	resp, err := srv.Client().Get(srv.URL + "/hits")
+	assert.FatalError(t, err)
+	hits := struct {
+		Hits int `json:"hits"`
+	}{}
+	defer resp.Body.Close()
+	err = json.NewDecoder(resp.Body).Decode(&hits)
+	assert.FatalError(t, err)
+	assert.True(t, hits.Hits > 1, fmt.Sprintf("invalid number of hits: %d is not greater than 1", hits.Hits))
+}
+
+func Test_keyStore_noCache(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	ks, err := newKeyStore(srv.URL + "/no-cache")
+	assert.FatalError(t, err)
+	defer ks.Close()
+	ks.RLock()
+	keySet1 := ks.keySet
+	ks.RUnlock()
+	// The keys will rotate on Get.
+	// So we won't be able to find the cached ones
+	assert.Len(t, 2, keySet1.Keys)
+	assert.Len(t, 0, ks.Get(keySet1.Keys[0].KeyID))
+	assert.Len(t, 0, ks.Get(keySet1.Keys[1].KeyID))
+	assert.Len(t, 0, ks.Get("foobar"))
+
+	ks.RLock()
+	keySet2 := ks.keySet
+	ks.RUnlock()
+	if reflect.DeepEqual(keySet1, keySet2) {
+		t.Error("keyStore did not rotated")
+	}
+
+	// The keys will rotate on Get.
+	// So we won't be able to find the cached ones
+	assert.Len(t, 2, keySet2.Keys)
+	assert.Len(t, 0, ks.Get(keySet2.Keys[0].KeyID))
+	assert.Len(t, 0, ks.Get(keySet2.Keys[1].KeyID))
+	assert.Len(t, 0, ks.Get("foobar"))
+
+	// Check hits
+	resp, err := srv.Client().Get(srv.URL + "/hits")
+	assert.FatalError(t, err)
+	hits := struct {
+		Hits int `json:"hits"`
+	}{}
+	defer resp.Body.Close()
+	err = json.NewDecoder(resp.Body).Decode(&hits)
+	assert.FatalError(t, err)
+	assert.True(t, hits.Hits > 1, fmt.Sprintf("invalid number of hits: %d is not greater than 1", hits.Hits))
+}
+
+func Test_keyStore_Get(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+	ks, err := newKeyStore(srv.URL)
+	assert.FatalError(t, err)
+	defer ks.Close()
+
+	type args struct {
+		kid string
+	}
+	tests := []struct {
+		name     string
+		ks       *keyStore
+		args     args
+		wantKeys []jose.JSONWebKey
+	}{
+		{"ok1", ks, args{ks.keySet.Keys[0].KeyID}, []jose.JSONWebKey{ks.keySet.Keys[0]}},
+		{"ok2", ks, args{ks.keySet.Keys[1].KeyID}, []jose.JSONWebKey{ks.keySet.Keys[1]}},
+		{"fail", ks, args{"fail"}, []jose.JSONWebKey(nil)},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if gotKeys := tt.ks.Get(tt.args.kid); !reflect.DeepEqual(gotKeys, tt.wantKeys) {
+				t.Errorf("keyStore.Get() = %v, want %v", gotKeys, tt.wantKeys)
+			}
+		})
+	}
+}
+
+func Test_abs(t *testing.T) {
+	maxInt64 := time.Duration(1<<63 - 1)
+	minInt64 := time.Duration(-1 << 63)
+	type args struct {
+		n time.Duration
+	}
+	tests := []struct {
+		name string
+		args args
+		want time.Duration
+	}{
+		{"ok", args{0}, 0},
+		{"ok", args{-time.Hour}, time.Hour},
+		{"ok", args{time.Hour}, time.Hour},
+		{"ok maxInt64", args{maxInt64}, maxInt64},
+		{"ok minInt64 + 1", args{minInt64 + 1}, maxInt64},
+		{"overflow on minInt64", args{minInt64}, minInt64},
+		{"overflow on minInt64", args{minInt64}, -minInt64},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := abs(tt.args.n); got != tt.want {
+				t.Errorf("abs() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 34 - 0
authority/provisioner/method.go

@@ -0,0 +1,34 @@
+package provisioner
+
+import (
+	"context"
+)
+
+// Method indicates the action to action that we will perform, it's used as part
+// of the context in the call to authorize. It defaults to Sing.
+type Method int
+
+// The key to save the Method in the context.
+type methodKey struct{}
+
+const (
+	// SignMethod is the method used to sign X.509 certificates.
+	SignMethod Method = iota
+	// SignSSHMethod is the method used to sign SSH certificate.
+	SignSSHMethod
+	// RevokeMethod is the method used to revoke X.509 certificates.
+	RevokeMethod
+)
+
+// NewContextWithMethod creates a new context from ctx and attaches method to
+// it.
+func NewContextWithMethod(ctx context.Context, method Method) context.Context {
+	return context.WithValue(ctx, methodKey{}, method)
+}
+
+// MethodFromContext returns the Method saved in ctx. Returns Sign if the given
+// context has no Method associated with it.
+func MethodFromContext(ctx context.Context) Method {
+	m, _ := ctx.Value(methodKey{}).(Method)
+	return m
+}

+ 44 - 0
authority/provisioner/noop.go

@@ -0,0 +1,44 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+)
+
+// noop provisioners is a provisioner that accepts anything.
+type noop struct{}
+
+func (p *noop) GetID() string {
+	return "noop"
+}
+
+func (p *noop) GetTokenID(token string) (string, error) {
+	return "", nil
+}
+
+func (p *noop) GetName() string {
+	return "noop"
+}
+func (p *noop) GetType() Type {
+	return noopType
+}
+
+func (p *noop) GetEncryptedKey() (kid string, key string, ok bool) {
+	return "", "", false
+}
+
+func (p *noop) Init(config Config) error {
+	return nil
+}
+
+func (p *noop) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	return []SignOption{}, nil
+}
+
+func (p *noop) AuthorizeRenewal(cert *x509.Certificate) error {
+	return nil
+}
+
+func (p *noop) AuthorizeRevoke(token string) error {
+	return nil
+}

+ 29 - 0
authority/provisioner/noop_test.go

@@ -0,0 +1,29 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+	"testing"
+
+	"github.com/smallstep/assert"
+)
+
+func Test_noop(t *testing.T) {
+	p := noop{}
+	assert.Equals(t, "noop", p.GetID())
+	assert.Equals(t, "noop", p.GetName())
+	assert.Equals(t, noopType, p.GetType())
+	assert.Equals(t, nil, p.Init(Config{}))
+	assert.Equals(t, nil, p.AuthorizeRenewal(&x509.Certificate{}))
+	assert.Equals(t, nil, p.AuthorizeRevoke("foo"))
+
+	kid, key, ok := p.GetEncryptedKey()
+	assert.Equals(t, "", kid)
+	assert.Equals(t, "", key)
+	assert.Equals(t, false, ok)
+
+	ctx := NewContextWithMethod(context.Background(), SignMethod)
+	sigOptions, err := p.AuthorizeSign(ctx, "foo")
+	assert.Equals(t, []SignOption{}, sigOptions)
+	assert.Equals(t, nil, err)
+}

+ 374 - 0
authority/provisioner/oidc.go

@@ -0,0 +1,374 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+	"encoding/json"
+	"net"
+	"net/http"
+	"net/url"
+	"path"
+	"strings"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/jose"
+)
+
+// openIDConfiguration contains the necessary properties in the
+// `/.well-known/openid-configuration` document.
+type openIDConfiguration struct {
+	Issuer    string `json:"issuer"`
+	JWKSetURI string `json:"jwks_uri"`
+}
+
+// Validate validates the values in a well-known OpenID configuration endpoint.
+func (c openIDConfiguration) Validate() error {
+	switch {
+	case c.Issuer == "":
+		return errors.New("issuer cannot be empty")
+	case c.JWKSetURI == "":
+		return errors.New("jwks_uri cannot be empty")
+	default:
+		return nil
+	}
+}
+
+// openIDPayload represents the fields on the id_token JWT payload.
+type openIDPayload struct {
+	jose.Claims
+	AtHash          string   `json:"at_hash"`
+	AuthorizedParty string   `json:"azp"`
+	Email           string   `json:"email"`
+	EmailVerified   bool     `json:"email_verified"`
+	Hd              string   `json:"hd"`
+	Nonce           string   `json:"nonce"`
+	Groups          []string `json:"groups"`
+}
+
+// OIDC represents an OAuth 2.0 OpenID Connect provider.
+//
+// ClientSecret is mandatory, but it can be an empty string.
+type OIDC struct {
+	Type                  string   `json:"type"`
+	Name                  string   `json:"name"`
+	ClientID              string   `json:"clientID"`
+	ClientSecret          string   `json:"clientSecret"`
+	ConfigurationEndpoint string   `json:"configurationEndpoint"`
+	Admins                []string `json:"admins,omitempty"`
+	Domains               []string `json:"domains,omitempty"`
+	Groups                []string `json:"groups,omitempty"`
+	ListenAddress         string   `json:"listenAddress,omitempty"`
+	Claims                *Claims  `json:"claims,omitempty"`
+	configuration         openIDConfiguration
+	keyStore              *keyStore
+	claimer               *Claimer
+}
+
+// IsAdmin returns true if the given email is in the Admins whitelist, false
+// otherwise.
+func (o *OIDC) IsAdmin(email string) bool {
+	email = sanitizeEmail(email)
+	for _, e := range o.Admins {
+		if email == sanitizeEmail(e) {
+			return true
+		}
+	}
+	return false
+}
+
+func sanitizeEmail(email string) string {
+	if i := strings.LastIndex(email, "@"); i >= 0 {
+		email = email[:i] + strings.ToLower(email[i:])
+	}
+	return email
+}
+
+// GetID returns the provisioner unique identifier, the OIDC provisioner the
+// uses the clientID for this.
+func (o *OIDC) GetID() string {
+	return o.ClientID
+}
+
+// GetTokenID returns the provisioner unique identifier, the OIDC provisioner the
+// uses the clientID for this.
+func (o *OIDC) GetTokenID(ott string) (string, error) {
+	// Validate payload
+	token, err := jose.ParseSigned(ott)
+	if err != nil {
+		return "", errors.Wrap(err, "error parsing token")
+	}
+
+	// Get claims w/out verification. We need to look up the provisioner
+	// key in order to verify the claims and we need the issuer from the claims
+	// before we can look up the provisioner.
+	var claims openIDPayload
+	if err = token.UnsafeClaimsWithoutVerification(&claims); err != nil {
+		return "", errors.Wrap(err, "error verifying claims")
+	}
+	return claims.Nonce, nil
+}
+
+// GetName returns the name of the provisioner.
+func (o *OIDC) GetName() string {
+	return o.Name
+}
+
+// GetType returns the type of provisioner.
+func (o *OIDC) GetType() Type {
+	return TypeOIDC
+}
+
+// GetEncryptedKey is not available in an OIDC provisioner.
+func (o *OIDC) GetEncryptedKey() (kid string, key string, ok bool) {
+	return "", "", false
+}
+
+// Init validates and initializes the OIDC provider.
+func (o *OIDC) Init(config Config) (err error) {
+	switch {
+	case o.Type == "":
+		return errors.New("type cannot be empty")
+	case o.Name == "":
+		return errors.New("name cannot be empty")
+	case o.ClientID == "":
+		return errors.New("clientID cannot be empty")
+	case o.ConfigurationEndpoint == "":
+		return errors.New("configurationEndpoint cannot be empty")
+	}
+
+	// Validate listenAddress if given
+	if o.ListenAddress != "" {
+		if _, _, err := net.SplitHostPort(o.ListenAddress); err != nil {
+			return errors.Wrap(err, "error parsing listenAddress")
+		}
+	}
+
+	// Update claims with global ones
+	if o.claimer, err = NewClaimer(o.Claims, config.Claims); err != nil {
+		return err
+	}
+
+	// Decode and validate openid-configuration endpoint
+	u, err := url.Parse(o.ConfigurationEndpoint)
+	if err != nil {
+		return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
+	}
+	if !strings.Contains(u.Path, "/.well-known/openid-configuration") {
+		u.Path = path.Join(u.Path, "/.well-known/openid-configuration")
+	}
+	if err := getAndDecode(u.String(), &o.configuration); err != nil {
+		return err
+	}
+	if err := o.configuration.Validate(); err != nil {
+		return errors.Wrapf(err, "error parsing %s", o.ConfigurationEndpoint)
+	}
+	// Get JWK key set
+	o.keyStore, err = newKeyStore(o.configuration.JWKSetURI)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+// ValidatePayload validates the given token payload.
+func (o *OIDC) ValidatePayload(p openIDPayload) error {
+	// According to "rfc7519 JSON Web Token" acceptable skew should be no more
+	// than a few minutes.
+	if err := p.ValidateWithLeeway(jose.Expected{
+		Issuer:   o.configuration.Issuer,
+		Audience: jose.Audience{o.ClientID},
+		Time:     time.Now().UTC(),
+	}, time.Minute); err != nil {
+		return errors.Wrap(err, "failed to validate payload")
+	}
+
+	// Validate azp if present
+	if p.AuthorizedParty != "" && p.AuthorizedParty != o.ClientID {
+		return errors.New("failed to validate payload: invalid azp")
+	}
+
+	// Enforce an email claim
+	if p.Email == "" {
+		return errors.New("failed to validate payload: email not found")
+	}
+
+	// Validate domains (case-insensitive)
+	if !o.IsAdmin(p.Email) && len(o.Domains) > 0 {
+		email := sanitizeEmail(p.Email)
+		var found bool
+		for _, d := range o.Domains {
+			if strings.HasSuffix(email, "@"+strings.ToLower(d)) {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return errors.New("failed to validate payload: email is not allowed")
+		}
+	}
+
+	// Filter by oidc group claim
+	if len(o.Groups) > 0 {
+		var found bool
+		for _, group := range o.Groups {
+			for _, g := range p.Groups {
+				if g == group {
+					found = true
+					break
+				}
+			}
+		}
+		if !found {
+			return errors.New("validation failed: invalid group")
+		}
+	}
+
+	return nil
+}
+
+// authorizeToken applies the most common provisioner authorization claims,
+// leaving the rest to context specific methods.
+func (o *OIDC) authorizeToken(token string) (*openIDPayload, error) {
+	jwt, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, errors.Wrapf(err, "error parsing token")
+	}
+
+	// Parse claims to get the kid
+	var claims openIDPayload
+	if err := jwt.UnsafeClaimsWithoutVerification(&claims); err != nil {
+		return nil, errors.Wrap(err, "error parsing claims")
+	}
+
+	found := false
+	kid := jwt.Headers[0].KeyID
+	keys := o.keyStore.Get(kid)
+	for _, key := range keys {
+		if err := jwt.Claims(key, &claims); err == nil {
+			found = true
+			break
+		}
+	}
+	if !found {
+		return nil, errors.New("cannot validate token")
+	}
+
+	if err := o.ValidatePayload(claims); err != nil {
+		return nil, err
+	}
+
+	return &claims, nil
+}
+
+// AuthorizeRevoke returns an error if the provisioner does not have rights to
+// revoke the certificate with serial number in the `sub` property.
+// Only tokens generated by an admin have the right to revoke a certificate.
+func (o *OIDC) AuthorizeRevoke(token string) error {
+	claims, err := o.authorizeToken(token)
+	if err != nil {
+		return err
+	}
+
+	// Only admins can revoke certificates.
+	if o.IsAdmin(claims.Email) {
+		return nil
+	}
+	return errors.New("cannot revoke with non-admin token")
+}
+
+// AuthorizeSign validates the given token.
+func (o *OIDC) AuthorizeSign(ctx context.Context, token string) ([]SignOption, error) {
+	claims, err := o.authorizeToken(token)
+	if err != nil {
+		return nil, err
+	}
+
+	// Check for the sign ssh method, default to sign X.509
+	if m := MethodFromContext(ctx); m == SignSSHMethod {
+		if o.claimer.IsSSHCAEnabled() == false {
+			return nil, errors.Errorf("ssh ca is disabled for provisioner %s", o.GetID())
+		}
+		return o.authorizeSSHSign(claims)
+	}
+
+	// Admins should be able to authorize any SAN
+	if o.IsAdmin(claims.Email) {
+		return []SignOption{
+			profileDefaultDuration(o.claimer.DefaultTLSCertDuration()),
+			newProvisionerExtensionOption(TypeOIDC, o.Name, o.ClientID),
+			newValidityValidator(o.claimer.MinTLSCertDuration(), o.claimer.MaxTLSCertDuration()),
+		}, nil
+	}
+
+	so := []SignOption{
+		defaultPublicKeyValidator{},
+		profileDefaultDuration(o.claimer.DefaultTLSCertDuration()),
+		newProvisionerExtensionOption(TypeOIDC, o.Name, o.ClientID),
+		newValidityValidator(o.claimer.MinTLSCertDuration(), o.claimer.MaxTLSCertDuration()),
+	}
+	// Admins should be able to authorize any SAN
+	if o.IsAdmin(claims.Email) {
+		return so, nil
+	}
+
+	return append(so, emailOnlyIdentity(claims.Email)), nil
+}
+
+// AuthorizeRenewal returns an error if the renewal is disabled.
+func (o *OIDC) AuthorizeRenewal(cert *x509.Certificate) error {
+	if o.claimer.IsDisableRenewal() {
+		return errors.Errorf("renew is disabled for provisioner %s", o.GetID())
+	}
+	return nil
+}
+
+// authorizeSSHSign returns the list of SignOption for a SignSSH request.
+func (o *OIDC) authorizeSSHSign(claims *openIDPayload) ([]SignOption, error) {
+	signOptions := []SignOption{
+		// set the key id to the token subject
+		sshCertificateKeyIDModifier(claims.Email),
+	}
+
+	name := SanitizeSSHUserPrincipal(claims.Email)
+	if !sshUserRegex.MatchString(name) {
+		return nil, errors.Errorf("invalid principal '%s' from email address '%s'", name, claims.Email)
+	}
+
+	// Admin users will default to user + name but they can be changed by the
+	// user options. Non-admins are only able to sign user certificates.
+	defaults := SSHOptions{
+		CertType:   SSHUserCert,
+		Principals: []string{name},
+	}
+
+	if !o.IsAdmin(claims.Email) {
+		signOptions = append(signOptions, sshCertificateOptionsValidator(defaults))
+	}
+
+	// Default to a user with name as principal if not set
+	signOptions = append(signOptions, sshCertificateDefaultsModifier(defaults))
+
+	return append(signOptions,
+		// set the default extensions
+		&sshDefaultExtensionModifier{},
+		// checks the validity bounds, and set the validity if has not been set
+		&sshCertificateValidityModifier{o.claimer},
+		// validate public key
+		&sshDefaultPublicKeyValidator{},
+		// require all the fields in the SSH certificate
+		&sshCertificateDefaultValidator{},
+	), nil
+}
+
+func getAndDecode(uri string, v interface{}) error {
+	resp, err := http.Get(uri)
+	if err != nil {
+		return errors.Wrapf(err, "failed to connect to %s", uri)
+	}
+	defer resp.Body.Close()
+	if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
+		return errors.Wrapf(err, "error reading %s", uri)
+	}
+	return nil
+}

+ 540 - 0
authority/provisioner/oidc_test.go

@@ -0,0 +1,540 @@
+package provisioner
+
+import (
+	"context"
+	"crypto"
+	"crypto/rand"
+	"crypto/rsa"
+	"crypto/x509"
+	"fmt"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/jose"
+)
+
+func Test_openIDConfiguration_Validate(t *testing.T) {
+	type fields struct {
+		Issuer    string
+		JWKSetURI string
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		wantErr bool
+	}{
+		{"ok", fields{"the-issuer", "the-jwks-uri"}, false},
+		{"no-issuer", fields{"", "the-jwks-uri"}, true},
+		{"no-jwks-uri", fields{"the-issuer", ""}, true},
+		{"empty", fields{"", ""}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			c := openIDConfiguration{
+				Issuer:    tt.fields.Issuer,
+				JWKSetURI: tt.fields.JWKSetURI,
+			}
+			if err := c.Validate(); (err != nil) != tt.wantErr {
+				t.Errorf("openIDConfiguration.Validate() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func TestOIDC_Getters(t *testing.T) {
+	p, err := generateOIDC()
+	assert.FatalError(t, err)
+	if got := p.GetID(); got != p.ClientID {
+		t.Errorf("OIDC.GetID() = %v, want %v", got, p.ClientID)
+	}
+	if got := p.GetName(); got != p.Name {
+		t.Errorf("OIDC.GetName() = %v, want %v", got, p.Name)
+	}
+	if got := p.GetType(); got != TypeOIDC {
+		t.Errorf("OIDC.GetType() = %v, want %v", got, TypeOIDC)
+	}
+	kid, key, ok := p.GetEncryptedKey()
+	if kid != "" || key != "" || ok == true {
+		t.Errorf("OIDC.GetEncryptedKey() = (%v, %v, %v), want (%v, %v, %v)",
+			kid, key, ok, "", "", false)
+	}
+}
+
+func TestOIDC_Init(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+	config := Config{
+		Claims: globalProvisionerClaims,
+	}
+	badClaims := &Claims{
+		DefaultTLSDur: &Duration{0},
+	}
+
+	type fields struct {
+		Type                  string
+		Name                  string
+		ClientID              string
+		ClientSecret          string
+		ConfigurationEndpoint string
+		Claims                *Claims
+		Admins                []string
+		Domains               []string
+		ListenAddress         string
+	}
+	type args struct {
+		config Config
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		args    args
+		wantErr bool
+	}{
+		{"ok", fields{"oidc", "name", "client-id", "client-secret", srv.URL, nil, nil, nil, ""}, args{config}, false},
+		{"ok-admins", fields{"oidc", "name", "client-id", "client-secret", srv.URL + "/.well-known/openid-configuration", nil, []string{"foo@smallstep.com"}, nil, ""}, args{config}, false},
+		{"ok-domains", fields{"oidc", "name", "client-id", "client-secret", srv.URL, nil, nil, []string{"smallstep.com"}, ""}, args{config}, false},
+		{"ok-listen-port", fields{"oidc", "name", "client-id", "client-secret", srv.URL, nil, nil, nil, ":10000"}, args{config}, false},
+		{"ok-listen-host-port", fields{"oidc", "name", "client-id", "client-secret", srv.URL, nil, nil, nil, "127.0.0.1:10000"}, args{config}, false},
+		{"ok-no-secret", fields{"oidc", "name", "client-id", "", srv.URL, nil, nil, nil, ""}, args{config}, false},
+		{"no-name", fields{"oidc", "", "client-id", "client-secret", srv.URL, nil, nil, nil, ""}, args{config}, true},
+		{"no-type", fields{"", "name", "client-id", "client-secret", srv.URL, nil, nil, nil, ""}, args{config}, true},
+		{"no-client-id", fields{"oidc", "name", "", "client-secret", srv.URL, nil, nil, nil, ""}, args{config}, true},
+		{"no-configuration", fields{"oidc", "name", "client-id", "client-secret", "", nil, nil, nil, ""}, args{config}, true},
+		{"bad-configuration", fields{"oidc", "name", "client-id", "client-secret", srv.URL + "/random", nil, nil, nil, ""}, args{config}, true},
+		{"bad-claims", fields{"oidc", "name", "client-id", "client-secret", srv.URL + "/.well-known/openid-configuration", badClaims, nil, nil, ""}, args{config}, true},
+		{"bad-parse-url", fields{"oidc", "name", "client-id", "client-secret", ":", nil, nil, nil, ""}, args{config}, true},
+		{"bad-get-url", fields{"oidc", "name", "client-id", "client-secret", "https://", nil, nil, nil, ""}, args{config}, true},
+		{"bad-listen-address", fields{"oidc", "name", "client-id", "client-secret", srv.URL, nil, nil, nil, "127.0.0.1"}, args{config}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			p := &OIDC{
+				Type:                  tt.fields.Type,
+				Name:                  tt.fields.Name,
+				ClientID:              tt.fields.ClientID,
+				ConfigurationEndpoint: tt.fields.ConfigurationEndpoint,
+				Claims:                tt.fields.Claims,
+				Admins:                tt.fields.Admins,
+				Domains:               tt.fields.Domains,
+				ListenAddress:         tt.fields.ListenAddress,
+			}
+			if err := p.Init(tt.args.config); (err != nil) != tt.wantErr {
+				t.Errorf("OIDC.Init() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if tt.wantErr == false {
+				assert.Len(t, 2, p.keyStore.keySet.Keys)
+				assert.Equals(t, openIDConfiguration{
+					Issuer:    "the-issuer",
+					JWKSetURI: srv.URL + "/jwks_uri",
+				}, p.configuration)
+			}
+		})
+	}
+}
+
+func TestOIDC_authorizeToken(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	var keys jose.JSONWebKeySet
+	assert.FatalError(t, getAndDecode(srv.URL+"/private", &keys))
+
+	// Create test provisioners
+	p1, err := generateOIDC()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+	p3, err := generateOIDC()
+	assert.FatalError(t, err)
+	// Admin + Domains
+	p3.Admins = []string{"name@smallstep.com", "root@example.com"}
+	p3.Domains = []string{"smallstep.com"}
+
+	// Update configuration endpoints and initialize
+	config := Config{Claims: globalProvisionerClaims}
+	p1.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p2.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p3.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	assert.FatalError(t, p1.Init(config))
+	assert.FatalError(t, p2.Init(config))
+	assert.FatalError(t, p3.Init(config))
+
+	t1, err := generateSimpleToken("the-issuer", p1.ClientID, &keys.Keys[0])
+	assert.FatalError(t, err)
+	t2, err := generateSimpleToken("the-issuer", p2.ClientID, &keys.Keys[1])
+	assert.FatalError(t, err)
+	// Invalid email
+	failEmail, err := generateToken("subject", "the-issuer", p3.ClientID, "", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+	failDomain, err := generateToken("subject", "the-issuer", p3.ClientID, "name@example.com", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+
+	// Invalid tokens
+	parts := strings.Split(t1, ".")
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+	// missing key
+	failKey, err := generateSimpleToken("the-issuer", p1.ClientID, key)
+	assert.FatalError(t, err)
+	// invalid token
+	failTok := "foo." + parts[1] + "." + parts[2]
+	// invalid claims
+	failClaims := parts[0] + ".foo." + parts[1]
+	// invalid issuer
+	failIss, err := generateSimpleToken("bad-issuer", p1.ClientID, &keys.Keys[0])
+	assert.FatalError(t, err)
+	// invalid audience
+	failAud, err := generateSimpleToken("the-issuer", "foobar", &keys.Keys[0])
+	assert.FatalError(t, err)
+	// invalid signature
+	failSig := t1[0 : len(t1)-2]
+	// expired
+	failExp, err := generateToken("subject", "the-issuer", p1.ClientID, "name@smallstep.com", []string{}, time.Now().Add(-360*time.Second), &keys.Keys[0])
+	assert.FatalError(t, err)
+	// not before
+	failNbf, err := generateToken("subject", "the-issuer", p1.ClientID, "name@smallstep.com", []string{}, time.Now().Add(360*time.Second), &keys.Keys[0])
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		prov    *OIDC
+		args    args
+		wantErr bool
+	}{
+		{"ok1", p1, args{t1}, false},
+		{"ok2", p2, args{t2}, false},
+		{"fail-email", p3, args{failEmail}, true},
+		{"fail-domain", p3, args{failDomain}, true},
+		{"fail-key", p1, args{failKey}, true},
+		{"fail-token", p1, args{failTok}, true},
+		{"fail-claims", p1, args{failClaims}, true},
+		{"fail-issuer", p1, args{failIss}, true},
+		{"fail-audience", p1, args{failAud}, true},
+		{"fail-signature", p1, args{failSig}, true},
+		{"fail-expired", p1, args{failExp}, true},
+		{"fail-not-before", p1, args{failNbf}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.prov.authorizeToken(tt.args.token)
+			if (err != nil) != tt.wantErr {
+				fmt.Println(tt)
+				t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else {
+				assert.NotNil(t, got)
+				assert.Equals(t, got.Issuer, "the-issuer")
+			}
+		})
+	}
+}
+
+func TestOIDC_AuthorizeSign(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	var keys jose.JSONWebKeySet
+	assert.FatalError(t, getAndDecode(srv.URL+"/private", &keys))
+
+	// Create test provisioners
+	p1, err := generateOIDC()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+	p3, err := generateOIDC()
+	assert.FatalError(t, err)
+	// Admin + Domains
+	p3.Admins = []string{"name@smallstep.com", "root@example.com"}
+	p3.Domains = []string{"smallstep.com"}
+
+	// Update configuration endpoints and initialize
+	config := Config{Claims: globalProvisionerClaims}
+	p1.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p2.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p3.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	assert.FatalError(t, p1.Init(config))
+	assert.FatalError(t, p2.Init(config))
+	assert.FatalError(t, p3.Init(config))
+
+	t1, err := generateSimpleToken("the-issuer", p1.ClientID, &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Admin email not in domains
+	okAdmin, err := generateToken("subject", "the-issuer", p3.ClientID, "root@example.com", []string{"test.smallstep.com"}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Invalid email
+	failEmail, err := generateToken("subject", "the-issuer", p3.ClientID, "", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		prov    *OIDC
+		args    args
+		wantErr bool
+	}{
+		{"ok1", p1, args{t1}, false},
+		{"admin", p3, args{okAdmin}, false},
+		{"fail-email", p3, args{failEmail}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignMethod)
+			got, err := tt.prov.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else {
+				assert.NotNil(t, got)
+				if tt.name == "admin" {
+					assert.Len(t, 3, got)
+				} else {
+					assert.Len(t, 5, got)
+				}
+			}
+		})
+	}
+}
+
+func TestOIDC_AuthorizeSign_SSH(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	var keys jose.JSONWebKeySet
+	assert.FatalError(t, getAndDecode(srv.URL+"/private", &keys))
+
+	// Create test provisioners
+	p1, err := generateOIDC()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+	p3, err := generateOIDC()
+	assert.FatalError(t, err)
+	// Admin + Domains
+	p3.Admins = []string{"name@smallstep.com", "root@example.com"}
+	p3.Domains = []string{"smallstep.com"}
+
+	// Update configuration endpoints and initialize
+	config := Config{Claims: globalProvisionerClaims}
+	p1.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p2.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p3.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	assert.FatalError(t, p1.Init(config))
+	assert.FatalError(t, p2.Init(config))
+	assert.FatalError(t, p3.Init(config))
+
+	t1, err := generateSimpleToken("the-issuer", p1.ClientID, &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Admin email not in domains
+	okAdmin, err := generateToken("subject", "the-issuer", p3.ClientID, "root@example.com", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Invalid email
+	failEmail, err := generateToken("subject", "the-issuer", p3.ClientID, "", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+
+	key, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	signer, err := generateJSONWebKey()
+	assert.FatalError(t, err)
+
+	pub := key.Public().Key
+	rsa2048, err := rsa.GenerateKey(rand.Reader, 2048)
+	assert.FatalError(t, err)
+	rsa1024, err := rsa.GenerateKey(rand.Reader, 1024)
+	assert.FatalError(t, err)
+
+	userDuration := p1.claimer.DefaultUserSSHCertDuration()
+	hostDuration := p1.claimer.DefaultHostSSHCertDuration()
+	expectedUserOptions := &SSHOptions{
+		CertType: "user", Principals: []string{"name"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(userDuration)),
+	}
+	expectedAdminOptions := &SSHOptions{
+		CertType: "user", Principals: []string{"root"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(userDuration)),
+	}
+	expectedHostOptions := &SSHOptions{
+		CertType: "host", Principals: []string{"smallstep.com"},
+		ValidAfter: NewTimeDuration(tm), ValidBefore: NewTimeDuration(tm.Add(hostDuration)),
+	}
+
+	type args struct {
+		token   string
+		sshOpts SSHOptions
+		key     interface{}
+	}
+	tests := []struct {
+		name        string
+		prov        *OIDC
+		args        args
+		expected    *SSHOptions
+		wantErr     bool
+		wantSignErr bool
+	}{
+		{"ok", p1, args{t1, SSHOptions{}, pub}, expectedUserOptions, false, false},
+		{"ok-rsa2048", p1, args{t1, SSHOptions{}, rsa2048.Public()}, expectedUserOptions, false, false},
+		{"ok-user", p1, args{t1, SSHOptions{CertType: "user"}, pub}, expectedUserOptions, false, false},
+		{"ok-principals", p1, args{t1, SSHOptions{Principals: []string{"name"}}, pub}, expectedUserOptions, false, false},
+		{"ok-options", p1, args{t1, SSHOptions{CertType: "user", Principals: []string{"name"}}, pub}, expectedUserOptions, false, false},
+		{"admin", p3, args{okAdmin, SSHOptions{}, pub}, expectedAdminOptions, false, false},
+		{"admin-user", p3, args{okAdmin, SSHOptions{CertType: "user"}, pub}, expectedAdminOptions, false, false},
+		{"admin-principals", p3, args{okAdmin, SSHOptions{Principals: []string{"root"}}, pub}, expectedAdminOptions, false, false},
+		{"admin-options", p3, args{okAdmin, SSHOptions{CertType: "user", Principals: []string{"name"}}, pub}, expectedUserOptions, false, false},
+		{"admin-host", p3, args{okAdmin, SSHOptions{CertType: "host", Principals: []string{"smallstep.com"}}, pub}, expectedHostOptions, false, false},
+		{"fail-rsa1024", p1, args{t1, SSHOptions{}, rsa1024.Public()}, expectedUserOptions, false, true},
+		{"fail-user-host", p1, args{t1, SSHOptions{CertType: "host"}, pub}, nil, false, true},
+		{"fail-user-principals", p1, args{t1, SSHOptions{Principals: []string{"root"}}, pub}, nil, false, true},
+		{"fail-email", p3, args{failEmail, SSHOptions{}, pub}, nil, true, false},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx := NewContextWithMethod(context.Background(), SignSSHMethod)
+			got, err := tt.prov.AuthorizeSign(ctx, tt.args.token)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if err != nil {
+				assert.Nil(t, got)
+			} else if assert.NotNil(t, got) {
+				cert, err := signSSHCertificate(tt.args.key, tt.args.sshOpts, got, signer.Key.(crypto.Signer))
+				if (err != nil) != tt.wantSignErr {
+					t.Errorf("SignSSH error = %v, wantSignErr %v", err, tt.wantSignErr)
+				} else {
+					if tt.wantSignErr {
+						assert.Nil(t, cert)
+					} else {
+						assert.NoError(t, validateSSHCertificate(cert, tt.expected))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestOIDC_AuthorizeRevoke(t *testing.T) {
+	srv := generateJWKServer(2)
+	defer srv.Close()
+
+	var keys jose.JSONWebKeySet
+	assert.FatalError(t, getAndDecode(srv.URL+"/private", &keys))
+
+	// Create test provisioners
+	p1, err := generateOIDC()
+	assert.FatalError(t, err)
+	p3, err := generateOIDC()
+	assert.FatalError(t, err)
+	// Admin + Domains
+	p3.Admins = []string{"name@smallstep.com", "root@example.com"}
+	p3.Domains = []string{"smallstep.com"}
+
+	// Update configuration endpoints and initialize
+	config := Config{Claims: globalProvisionerClaims}
+	p1.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	p3.ConfigurationEndpoint = srv.URL + "/.well-known/openid-configuration"
+	assert.FatalError(t, p1.Init(config))
+	assert.FatalError(t, p3.Init(config))
+
+	t1, err := generateSimpleToken("the-issuer", p1.ClientID, &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Admin email not in domains
+	okAdmin, err := generateToken("subject", "the-issuer", p3.ClientID, "root@example.com", []string{"test.smallstep.com"}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+	// Invalid email
+	failEmail, err := generateToken("subject", "the-issuer", p3.ClientID, "", []string{}, time.Now(), &keys.Keys[0])
+	assert.FatalError(t, err)
+
+	type args struct {
+		token string
+	}
+	tests := []struct {
+		name    string
+		prov    *OIDC
+		args    args
+		wantErr bool
+	}{
+		{"ok1", p1, args{t1}, true},
+		{"admin", p3, args{okAdmin}, false},
+		{"fail-email", p3, args{failEmail}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			err := tt.prov.AuthorizeRevoke(tt.args.token)
+			if (err != nil) != tt.wantErr {
+				fmt.Println(tt)
+				t.Errorf("OIDC.Authorize() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+		})
+	}
+}
+
+func TestOIDC_AuthorizeRenewal(t *testing.T) {
+	p1, err := generateOIDC()
+	assert.FatalError(t, err)
+	p2, err := generateOIDC()
+	assert.FatalError(t, err)
+
+	// disable renewal
+	disable := true
+	p2.Claims = &Claims{DisableRenewal: &disable}
+	p2.claimer, err = NewClaimer(p2.Claims, globalProvisionerClaims)
+	assert.FatalError(t, err)
+
+	type args struct {
+		cert *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		prov    *OIDC
+		args    args
+		wantErr bool
+	}{
+		{"ok", p1, args{nil}, false},
+		{"fail", p2, args{nil}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.prov.AuthorizeRenewal(tt.args.cert); (err != nil) != tt.wantErr {
+				t.Errorf("OIDC.AuthorizeRenewal() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_sanitizeEmail(t *testing.T) {
+	tests := []struct {
+		name  string
+		email string
+		want  string
+	}{
+		{"equal", "name@smallstep.com", "name@smallstep.com"},
+		{"domain-insensitive", "name@SMALLSTEP.COM", "name@smallstep.com"},
+		{"local-sensitive", "NaMe@smallSTEP.CoM", "NaMe@smallstep.com"},
+		{"multiple-@", "NaMe@NaMe@smallSTEP.CoM", "NaMe@NaMe@smallstep.com"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := sanitizeEmail(tt.email); got != tt.want {
+				t.Errorf("sanitizeEmail() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 295 - 0
authority/provisioner/provisioner.go

@@ -0,0 +1,295 @@
+package provisioner
+
+import (
+	"context"
+	"crypto/x509"
+	"encoding/json"
+	"net/url"
+	"regexp"
+	"strings"
+
+	"github.com/pkg/errors"
+)
+
+// Interface is the interface that all provisioner types must implement.
+type Interface interface {
+	GetID() string
+	GetTokenID(token string) (string, error)
+	GetName() string
+	GetType() Type
+	GetEncryptedKey() (kid string, key string, ok bool)
+	Init(config Config) error
+	AuthorizeSign(ctx context.Context, token string) ([]SignOption, error)
+	AuthorizeRenewal(cert *x509.Certificate) error
+	AuthorizeRevoke(token string) error
+}
+
+// Audiences stores all supported audiences by request type.
+type Audiences struct {
+	Sign   []string
+	Revoke []string
+}
+
+// All returns all supported audiences across all request types in one list.
+func (a Audiences) All() []string {
+	return append(a.Sign, a.Revoke...)
+}
+
+// WithFragment returns a copy of audiences where the url audiences contains the
+// given fragment.
+func (a Audiences) WithFragment(fragment string) Audiences {
+	ret := Audiences{
+		Sign:   make([]string, len(a.Sign)),
+		Revoke: make([]string, len(a.Revoke)),
+	}
+	for i, s := range a.Sign {
+		if u, err := url.Parse(s); err == nil {
+			ret.Sign[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
+		} else {
+			ret.Sign[i] = s
+		}
+	}
+	for i, s := range a.Revoke {
+		if u, err := url.Parse(s); err == nil {
+			ret.Revoke[i] = u.ResolveReference(&url.URL{Fragment: fragment}).String()
+		} else {
+			ret.Revoke[i] = s
+		}
+	}
+	return ret
+}
+
+// generateSignAudience generates a sign audience with the format
+// https://<host>/1.0/sign#provisionerID
+func generateSignAudience(caURL string, provisionerID string) (string, error) {
+	u, err := url.Parse(caURL)
+	if err != nil {
+		return "", errors.Wrapf(err, "error parsing %s", caURL)
+	}
+	return u.ResolveReference(&url.URL{Path: "/1.0/sign", Fragment: provisionerID}).String(), nil
+}
+
+// Type indicates the provisioner Type.
+type Type int
+
+const (
+	noopType Type = 0
+	// TypeJWK is used to indicate the JWK provisioners.
+	TypeJWK Type = 1
+	// TypeOIDC is used to indicate the OIDC provisioners.
+	TypeOIDC Type = 2
+	// TypeGCP is used to indicate the GCP provisioners.
+	TypeGCP Type = 3
+	// TypeAWS is used to indicate the AWS provisioners.
+	TypeAWS Type = 4
+	// TypeAzure is used to indicate the Azure provisioners.
+	TypeAzure Type = 5
+	// TypeACME is used to indicate the ACME provisioners.
+	TypeACME Type = 6
+
+	// RevokeAudienceKey is the key for the 'revoke' audiences in the audiences map.
+	RevokeAudienceKey = "revoke"
+	// SignAudienceKey is the key for the 'sign' audiences in the audiences map.
+	SignAudienceKey = "sign"
+)
+
+// String returns the string representation of the type.
+func (t Type) String() string {
+	switch t {
+	case TypeJWK:
+		return "JWK"
+	case TypeOIDC:
+		return "OIDC"
+	case TypeGCP:
+		return "GCP"
+	case TypeAWS:
+		return "AWS"
+	case TypeAzure:
+		return "Azure"
+	case TypeACME:
+		return "ACME"
+	default:
+		return ""
+	}
+}
+
+// Config defines the default parameters used in the initialization of
+// provisioners.
+type Config struct {
+	// Claims are the default claims.
+	Claims Claims
+	// Audiences are the audiences used in the default provisioner, (JWK).
+	Audiences Audiences
+}
+
+type provisioner struct {
+	Type string `json:"type"`
+}
+
+// List represents a list of provisioners.
+type List []Interface
+
+// UnmarshalJSON implements json.Unmarshaler and allows to unmarshal a list of a
+// interfaces into the right type.
+func (l *List) UnmarshalJSON(data []byte) error {
+	ps := []json.RawMessage{}
+	if err := json.Unmarshal(data, &ps); err != nil {
+		return errors.Wrap(err, "error unmarshaling provisioner list")
+	}
+
+	*l = List{}
+	for _, data := range ps {
+		var typ provisioner
+		if err := json.Unmarshal(data, &typ); err != nil {
+			return errors.Errorf("error unmarshaling provisioner")
+		}
+		var p Interface
+		switch strings.ToLower(typ.Type) {
+		case "jwk":
+			p = &JWK{}
+		case "oidc":
+			p = &OIDC{}
+		case "gcp":
+			p = &GCP{}
+		case "aws":
+			p = &AWS{}
+		case "azure":
+			p = &Azure{}
+		case "acme":
+			p = &ACME{}
+		default:
+			// Skip unsupported provisioners. A client using this method may be
+			// compiled with a version of smallstep/certificates that does not
+			// support a specific provisioner type. If we don't skip unknown
+			// provisioners, a client encountering an unknown provisioner will
+			// break. Rather than break the client, we skip the provisioner.
+			// TODO: accept a pluggable logger (depending on client) that can
+			// warn the user that an unknown provisioner was found and suggest
+			// that the user update their client's dependency on
+			// step/certificates and recompile.
+			continue
+		}
+		if err := json.Unmarshal(data, p); err != nil {
+			return errors.Errorf("error unmarshaling provisioner")
+		}
+		*l = append(*l, p)
+	}
+
+	return nil
+}
+
+var sshUserRegex = regexp.MustCompile("^[a-z][-a-z0-9_]*$")
+
+// SanitizeSSHUserPrincipal grabs an email or a string with the format
+// local@domain and returns a sanitized version of the local, valid to be used
+// as a user name. If the email starts with a letter between a and z, the
+// resulting string will match the regular expression `^[a-z][-a-z0-9_]*$`.
+func SanitizeSSHUserPrincipal(email string) string {
+	if i := strings.LastIndex(email, "@"); i >= 0 {
+		email = email[:i]
+	}
+	return strings.Map(func(r rune) rune {
+		switch {
+		case r >= 'a' && r <= 'z':
+			return r
+		case r >= '0' && r <= '9':
+			return r
+		case r == '-':
+			return '-'
+		case r == '.': // drop dots
+			return -1
+		default:
+			return '_'
+		}
+	}, strings.ToLower(email))
+}
+
+// MockProvisioner for testing
+type MockProvisioner struct {
+	Mret1, Mret2, Mret3 interface{}
+	Merr                error
+	MgetID              func() string
+	MgetTokenID         func(string) (string, error)
+	MgetName            func() string
+	MgetType            func() Type
+	MgetEncryptedKey    func() (string, string, bool)
+	Minit               func(Config) error
+	MauthorizeRevoke    func(ott string) error
+	MauthorizeSign      func(ctx context.Context, ott string) ([]SignOption, error)
+	MauthorizeRenewal   func(*x509.Certificate) error
+}
+
+// GetID mock
+func (m *MockProvisioner) GetID() string {
+	if m.MgetID != nil {
+		return m.MgetID()
+	}
+	return m.Mret1.(string)
+}
+
+// GetTokenID mock
+func (m *MockProvisioner) GetTokenID(token string) (string, error) {
+	if m.MgetTokenID != nil {
+		return m.MgetTokenID(token)
+	}
+	if m.Mret1 == nil {
+		return "", m.Merr
+	}
+	return m.Mret1.(string), m.Merr
+}
+
+// GetName mock
+func (m *MockProvisioner) GetName() string {
+	if m.MgetName != nil {
+		return m.MgetName()
+	}
+	return m.Mret1.(string)
+}
+
+// GetType mock
+func (m *MockProvisioner) GetType() Type {
+	if m.MgetType != nil {
+		return m.MgetType()
+	}
+	return m.Mret1.(Type)
+}
+
+// GetEncryptedKey mock
+func (m *MockProvisioner) GetEncryptedKey() (string, string, bool) {
+	if m.MgetEncryptedKey != nil {
+		return m.MgetEncryptedKey()
+	}
+	return m.Mret1.(string), m.Mret2.(string), m.Mret3.(bool)
+}
+
+// Init mock
+func (m *MockProvisioner) Init(c Config) error {
+	if m.Minit != nil {
+		return m.Minit(c)
+	}
+	return m.Merr
+}
+
+// AuthorizeRevoke mock
+func (m *MockProvisioner) AuthorizeRevoke(ott string) error {
+	if m.MauthorizeRevoke != nil {
+		return m.MauthorizeRevoke(ott)
+	}
+	return m.Merr
+}
+
+// AuthorizeSign mock
+func (m *MockProvisioner) AuthorizeSign(ctx context.Context, ott string) ([]SignOption, error) {
+	if m.MauthorizeSign != nil {
+		return m.MauthorizeSign(ctx, ott)
+	}
+	return m.Mret1.([]SignOption), m.Merr
+}
+
+// AuthorizeRenewal mock
+func (m *MockProvisioner) AuthorizeRenewal(c *x509.Certificate) error {
+	if m.MauthorizeRenewal != nil {
+		return m.MauthorizeRenewal(c)
+	}
+	return m.Merr
+}

+ 54 - 0
authority/provisioner/provisioner_test.go

@@ -0,0 +1,54 @@
+package provisioner
+
+import (
+	"testing"
+)
+
+func TestType_String(t *testing.T) {
+	tests := []struct {
+		name string
+		t    Type
+		want string
+	}{
+		{"JWK", TypeJWK, "JWK"},
+		{"OIDC", TypeOIDC, "OIDC"},
+		{"AWS", TypeAWS, "AWS"},
+		{"Azure", TypeAzure, "Azure"},
+		{"GCP", TypeGCP, "GCP"},
+		{"noop", noopType, ""},
+		{"notFound", 1000, ""},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := tt.t.String(); got != tt.want {
+				t.Errorf("Type.String() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestSanitizeSSHUserPrincipal(t *testing.T) {
+	type args struct {
+		email string
+	}
+	tests := []struct {
+		name string
+		args args
+		want string
+	}{
+		{"simple", args{"foobar"}, "foobar"},
+		{"camelcase", args{"FooBar"}, "foobar"},
+		{"email", args{"foo@example.com"}, "foo"},
+		{"email with dots", args{"foo.bar.zar@example.com"}, "foobarzar"},
+		{"email with dashes", args{"foo-bar-zar@example.com"}, "foo-bar-zar"},
+		{"email with underscores", args{"foo_bar_zar@example.com"}, "foo_bar_zar"},
+		{"email with symbols", args{"Foo.Bar0123456789!#$%&'*+-/=?^_`{|}~;@example.com"}, "foobar0123456789________-___________"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := SanitizeSSHUserPrincipal(tt.args.email); got != tt.want {
+				t.Errorf("SanitizeSSHUserPrincipal() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 297 - 0
authority/provisioner/sign_options.go

@@ -0,0 +1,297 @@
+package provisioner
+
+import (
+	"crypto/ecdsa"
+	"crypto/rsa"
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"encoding/asn1"
+	"net"
+	"reflect"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/crypto/x509util"
+	"golang.org/x/crypto/ed25519"
+)
+
+// Options contains the options that can be passed to the Sign method.
+type Options struct {
+	NotAfter  TimeDuration `json:"notAfter"`
+	NotBefore TimeDuration `json:"notBefore"`
+}
+
+// SignOption is the interface used to collect all extra options used in the
+// Sign method.
+type SignOption interface{}
+
+// CertificateValidator is the interface used to validate a X.509 certificate.
+type CertificateValidator interface {
+	SignOption
+	Valid(crt *x509.Certificate) error
+}
+
+// CertificateRequestValidator is the interface used to validate a X.509
+// certificate request.
+type CertificateRequestValidator interface {
+	SignOption
+	Valid(req *x509.CertificateRequest) error
+}
+
+// ProfileModifier is the interface used to add custom options to the profile
+// constructor. The options are used to modify the final certificate.
+type ProfileModifier interface {
+	SignOption
+	Option(o Options) x509util.WithOption
+}
+
+// profileWithOption is a wrapper against x509util.WithOption to conform the
+// interface.
+type profileWithOption x509util.WithOption
+
+func (v profileWithOption) Option(Options) x509util.WithOption {
+	return x509util.WithOption(v)
+}
+
+// profileDefaultDuration is a wrapper against x509util.WithOption to conform the
+// interface.
+type profileDefaultDuration time.Duration
+
+func (v profileDefaultDuration) Option(so Options) x509util.WithOption {
+	notBefore := so.NotBefore.Time()
+	if notBefore.IsZero() {
+		notBefore = time.Now()
+	}
+	notAfter := so.NotAfter.RelativeTime(notBefore)
+	return x509util.WithNotBeforeAfterDuration(notBefore, notAfter, time.Duration(v))
+}
+
+// emailOnlyIdentity is a CertificateRequestValidator that checks that the only
+// SAN provided is the given email address.
+type emailOnlyIdentity string
+
+func (e emailOnlyIdentity) Valid(req *x509.CertificateRequest) error {
+	switch {
+	case len(req.DNSNames) > 0:
+		return errors.New("certificate request cannot contain DNS names")
+	case len(req.IPAddresses) > 0:
+		return errors.New("certificate request cannot contain IP addresses")
+	case len(req.URIs) > 0:
+		return errors.New("certificate request cannot contain URIs")
+	case len(req.EmailAddresses) == 0:
+		return errors.New("certificate request does not contain any email address")
+	case len(req.EmailAddresses) > 1:
+		return errors.New("certificate request contains too many email addresses")
+	case req.EmailAddresses[0] == "":
+		return errors.New("certificate request cannot contain an empty email address")
+	case req.EmailAddresses[0] != string(e):
+		return errors.Errorf("certificate request does not contain the valid email address, got %s, want %s", req.EmailAddresses[0], e)
+	default:
+		return nil
+	}
+}
+
+// defaultPublicKeyValidator validates the public key of a certificate request.
+type defaultPublicKeyValidator struct{}
+
+// Valid checks that certificate request common name matches the one configured.
+func (v defaultPublicKeyValidator) Valid(req *x509.CertificateRequest) error {
+	switch k := req.PublicKey.(type) {
+	case *rsa.PublicKey:
+		if k.Size() < 256 {
+			return errors.New("rsa key in CSR must be at least 2048 bits (256 bytes)")
+		}
+	case *ecdsa.PublicKey, ed25519.PublicKey:
+	default:
+		return errors.Errorf("unrecognized public key of type '%T' in CSR", k)
+	}
+	return nil
+}
+
+// commonNameValidator validates the common name of a certificate request.
+type commonNameValidator string
+
+// Valid checks that certificate request common name matches the one configured.
+func (v commonNameValidator) Valid(req *x509.CertificateRequest) error {
+	if req.Subject.CommonName == "" {
+		return errors.New("certificate request cannot contain an empty common name")
+	}
+	if req.Subject.CommonName != string(v) {
+		return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
+	}
+	return nil
+}
+
+// commonNameSliceValidator validates thats the common name of a certificate request is present in the slice.
+type commonNameSliceValidator []string
+
+func (v commonNameSliceValidator) Valid(req *x509.CertificateRequest) error {
+	if req.Subject.CommonName == "" {
+		return errors.New("certificate request cannot contain an empty common name")
+	}
+	for _, cn := range v {
+		if req.Subject.CommonName == cn {
+			return nil
+		}
+	}
+	return errors.Errorf("certificate request does not contain the valid common name, got %s, want %s", req.Subject.CommonName, v)
+}
+
+// dnsNamesValidator validates the DNS names SAN of a certificate request.
+type dnsNamesValidator []string
+
+// Valid checks that certificate request DNS Names match those configured in
+// the bootstrap (token) flow.
+func (v dnsNamesValidator) Valid(req *x509.CertificateRequest) error {
+	want := make(map[string]bool)
+	for _, s := range v {
+		want[s] = true
+	}
+	got := make(map[string]bool)
+	for _, s := range req.DNSNames {
+		got[s] = true
+	}
+	if !reflect.DeepEqual(want, got) {
+		return errors.Errorf("certificate request does not contain the valid DNS names - got %v, want %v", req.DNSNames, v)
+	}
+	return nil
+}
+
+// ipAddressesValidator validates the IP addresses SAN of a certificate request.
+type ipAddressesValidator []net.IP
+
+// Valid checks that certificate request IP Addresses match those configured in
+// the bootstrap (token) flow.
+func (v ipAddressesValidator) Valid(req *x509.CertificateRequest) error {
+	want := make(map[string]bool)
+	for _, ip := range v {
+		want[ip.String()] = true
+	}
+	got := make(map[string]bool)
+	for _, ip := range req.IPAddresses {
+		got[ip.String()] = true
+	}
+	if !reflect.DeepEqual(want, got) {
+		return errors.Errorf("IP Addresses claim failed - got %v, want %v", req.IPAddresses, v)
+	}
+	return nil
+}
+
+// emailAddressesValidator validates the email address SANs of a certificate request.
+type emailAddressesValidator []string
+
+// Valid checks that certificate request IP Addresses match those configured in
+// the bootstrap (token) flow.
+func (v emailAddressesValidator) Valid(req *x509.CertificateRequest) error {
+	want := make(map[string]bool)
+	for _, s := range v {
+		want[s] = true
+	}
+	got := make(map[string]bool)
+	for _, s := range req.EmailAddresses {
+		got[s] = true
+	}
+	if !reflect.DeepEqual(want, got) {
+		return errors.Errorf("certificate request does not contain the valid Email Addresses - got %v, want %v", req.EmailAddresses, v)
+	}
+	return nil
+}
+
+// validityValidator validates the certificate temporal validity settings.
+type validityValidator struct {
+	min time.Duration
+	max time.Duration
+}
+
+// newValidityValidator return a new validity validator.
+func newValidityValidator(min, max time.Duration) *validityValidator {
+	return &validityValidator{min: min, max: max}
+}
+
+// Validate validates the certificate temporal validity settings.
+func (v *validityValidator) Valid(crt *x509.Certificate) error {
+	var (
+		na  = crt.NotAfter
+		nb  = crt.NotBefore
+		d   = na.Sub(nb)
+		now = time.Now()
+	)
+
+	if na.Before(now) {
+		return errors.Errorf("NotAfter: %v cannot be in the past", na)
+	}
+	if na.Before(nb) {
+		return errors.Errorf("NotAfter: %v cannot be before NotBefore: %v", na, nb)
+	}
+	if d < v.min {
+		return errors.Errorf("requested duration of %v is less than the authorized minimum certificate duration of %v",
+			d, v.min)
+	}
+	if d > v.max {
+		return errors.Errorf("requested duration of %v is more than the authorized maximum certificate duration of %v",
+			d, v.max)
+	}
+	return nil
+}
+
+var (
+	stepOIDRoot        = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 37476, 9000, 64}
+	stepOIDProvisioner = append(asn1.ObjectIdentifier(nil), append(stepOIDRoot, 1)...)
+)
+
+type stepProvisionerASN1 struct {
+	Type          int
+	Name          []byte
+	CredentialID  []byte
+	KeyValuePairs []string `asn1:"optional,omitempty"`
+}
+
+type provisionerExtensionOption struct {
+	Type          int
+	Name          string
+	CredentialID  string
+	KeyValuePairs []string
+}
+
+func newProvisionerExtensionOption(typ Type, name, credentialID string, keyValuePairs ...string) *provisionerExtensionOption {
+	return &provisionerExtensionOption{
+		Type:          int(typ),
+		Name:          name,
+		CredentialID:  credentialID,
+		KeyValuePairs: keyValuePairs,
+	}
+}
+
+func (o *provisionerExtensionOption) Option(Options) x509util.WithOption {
+	return func(p x509util.Profile) error {
+		crt := p.Subject()
+		ext, err := createProvisionerExtension(o.Type, o.Name, o.CredentialID, o.KeyValuePairs...)
+		if err != nil {
+			return err
+		}
+		crt.ExtraExtensions = append(crt.ExtraExtensions, ext)
+		return nil
+	}
+}
+
+func createProvisionerExtension(typ int, name, credentialID string, keyValuePairs ...string) (pkix.Extension, error) {
+	b, err := asn1.Marshal(stepProvisionerASN1{
+		Type:          typ,
+		Name:          []byte(name),
+		CredentialID:  []byte(credentialID),
+		KeyValuePairs: keyValuePairs,
+	})
+	if err != nil {
+		return pkix.Extension{}, errors.Wrapf(err, "error marshaling provisioner extension")
+	}
+	return pkix.Extension{
+		Id:       stepOIDProvisioner,
+		Critical: false,
+		Value:    b,
+	}, nil
+}
+
+func init() {
+	// Avoid dead-code warning in profileWithOption
+	_ = profileWithOption(nil)
+}

+ 275 - 0
authority/provisioner/sign_options_test.go

@@ -0,0 +1,275 @@
+package provisioner
+
+import (
+	"crypto/x509"
+	"crypto/x509/pkix"
+	"net"
+	"net/url"
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/crypto/pemutil"
+	"github.com/smallstep/cli/crypto/x509util"
+	stepx509 "github.com/smallstep/cli/pkg/x509"
+)
+
+func Test_emailOnlyIdentity_Valid(t *testing.T) {
+	uri, err := url.Parse("https://example.com/1.0/getUser")
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		e       emailOnlyIdentity
+		args    args
+		wantErr bool
+	}{
+		{"ok", "name@smallstep.com", args{&x509.CertificateRequest{EmailAddresses: []string{"name@smallstep.com"}}}, false},
+		{"DNSNames", "name@smallstep.com", args{&x509.CertificateRequest{DNSNames: []string{"foo.bar.zar"}}}, true},
+		{"IPAddresses", "name@smallstep.com", args{&x509.CertificateRequest{IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}}}, true},
+		{"URIs", "name@smallstep.com", args{&x509.CertificateRequest{URIs: []*url.URL{uri}}}, true},
+		{"no-emails", "name@smallstep.com", args{&x509.CertificateRequest{EmailAddresses: []string{}}}, true},
+		{"empty-email", "", args{&x509.CertificateRequest{EmailAddresses: []string{""}}}, true},
+		{"multiple-emails", "name@smallstep.com", args{&x509.CertificateRequest{EmailAddresses: []string{"name@smallstep.com", "foo@smallstep.com"}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.e.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("emailOnlyIdentity.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_defaultPublicKeyValidator_Valid(t *testing.T) {
+	_shortRSA, err := pemutil.Read("./testdata/short-rsa.csr")
+	assert.FatalError(t, err)
+	shortRSA, ok := _shortRSA.(*x509.CertificateRequest)
+	assert.Fatal(t, ok)
+
+	_rsa, err := pemutil.Read("./testdata/rsa.csr")
+	assert.FatalError(t, err)
+	rsaCSR, ok := _rsa.(*x509.CertificateRequest)
+	assert.Fatal(t, ok)
+
+	_ecdsa, err := pemutil.Read("./testdata/ecdsa.csr")
+	assert.FatalError(t, err)
+	ecdsaCSR, ok := _ecdsa.(*x509.CertificateRequest)
+	assert.Fatal(t, ok)
+
+	_ed25519, err := pemutil.Read("./testdata/ed25519.csr", pemutil.WithStepCrypto())
+	assert.FatalError(t, err)
+	ed25519CSR, ok := _ed25519.(*stepx509.CertificateRequest)
+	assert.Fatal(t, ok)
+
+	v := defaultPublicKeyValidator{}
+	tests := []struct {
+		name string
+		csr  *x509.CertificateRequest
+		err  error
+	}{
+		{
+			"fail/unrecognized-key-type",
+			&x509.CertificateRequest{PublicKey: "foo"},
+			errors.New("unrecognized public key of type 'string' in CSR"),
+		},
+		{
+			"fail/rsa/too-short",
+			shortRSA,
+			errors.New("rsa key in CSR must be at least 2048 bits (256 bytes)"),
+		},
+		{
+			"ok/rsa",
+			rsaCSR,
+			nil,
+		},
+		{
+			"ok/ecdsa",
+			ecdsaCSR,
+			nil,
+		},
+		{
+			"ok/ed25519",
+			x509util.ToX509CertificateRequest(ed25519CSR),
+			nil,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := v.Valid(tt.csr); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				assert.Nil(t, tt.err)
+			}
+		})
+	}
+}
+
+func Test_commonNameValidator_Valid(t *testing.T) {
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		v       commonNameValidator
+		args    args
+		wantErr bool
+	}{
+		{"ok", "foo.bar.zar", args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: "foo.bar.zar"}}}, false},
+		{"empty", "", args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: ""}}}, true},
+		{"wrong", "foo.bar.zar", args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: "example.com"}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.v.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("commonNameValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_commonNameSliceValidator_Valid(t *testing.T) {
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		v       commonNameSliceValidator
+		args    args
+		wantErr bool
+	}{
+		{"ok", []string{"foo.bar.zar"}, args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: "foo.bar.zar"}}}, false},
+		{"ok", []string{"example.com", "foo.bar.zar"}, args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: "foo.bar.zar"}}}, false},
+		{"empty", []string{""}, args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: ""}}}, true},
+		{"wrong", []string{"foo.bar.zar"}, args{&x509.CertificateRequest{Subject: pkix.Name{CommonName: "example.com"}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.v.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("commonNameSliceValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_emailAddressesValidator_Valid(t *testing.T) {
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		v       emailAddressesValidator
+		args    args
+		wantErr bool
+	}{
+		{"ok0", []string{}, args{&x509.CertificateRequest{EmailAddresses: []string{}}}, false},
+		{"ok1", []string{"max@smallstep.com"}, args{&x509.CertificateRequest{EmailAddresses: []string{"max@smallstep.com"}}}, false},
+		{"ok2", []string{"max@step.com", "mike@step.com"}, args{&x509.CertificateRequest{EmailAddresses: []string{"max@step.com", "mike@step.com"}}}, false},
+		{"ok3", []string{"max@step.com", "mike@step.com"}, args{&x509.CertificateRequest{EmailAddresses: []string{"mike@step.com", "max@step.com"}}}, false},
+		{"fail1", []string{"max@step.com"}, args{&x509.CertificateRequest{EmailAddresses: []string{"mike@step.com"}}}, true},
+		{"fail2", []string{"mike@step.com"}, args{&x509.CertificateRequest{EmailAddresses: []string{"max@step.com", "mike@step.com"}}}, true},
+		{"fail3", []string{"mike@step.com", "max@step.com"}, args{&x509.CertificateRequest{DNSNames: []string{"mike@step.com", "mex@step.com"}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.v.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("dnsNamesValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_dnsNamesValidator_Valid(t *testing.T) {
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		v       dnsNamesValidator
+		args    args
+		wantErr bool
+	}{
+		{"ok0", []string{}, args{&x509.CertificateRequest{DNSNames: []string{}}}, false},
+		{"ok1", []string{"foo.bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"foo.bar.zar"}}}, false},
+		{"ok2", []string{"foo.bar.zar", "bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"foo.bar.zar", "bar.zar"}}}, false},
+		{"ok3", []string{"foo.bar.zar", "bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"bar.zar", "foo.bar.zar"}}}, false},
+		{"fail1", []string{"foo.bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"bar.zar"}}}, true},
+		{"fail2", []string{"foo.bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"bar.zar", "foo.bar.zar"}}}, true},
+		{"fail3", []string{"foo.bar.zar", "bar.zar"}, args{&x509.CertificateRequest{DNSNames: []string{"foo.bar.zar", "zar.bar"}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.v.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("dnsNamesValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_ipAddressesValidator_Valid(t *testing.T) {
+	ip1 := net.IPv4(10, 3, 2, 1)
+	ip2 := net.IPv4(10, 3, 2, 2)
+	ip3 := net.IPv4(10, 3, 2, 3)
+
+	type args struct {
+		req *x509.CertificateRequest
+	}
+	tests := []struct {
+		name    string
+		v       ipAddressesValidator
+		args    args
+		wantErr bool
+	}{
+		{"ok0", []net.IP{}, args{&x509.CertificateRequest{IPAddresses: []net.IP{}}}, false},
+		{"ok1", []net.IP{ip1}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip1}}}, false},
+		{"ok2", []net.IP{ip1, ip2}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip1, ip2}}}, false},
+		{"ok3", []net.IP{ip1, ip2}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip2, ip1}}}, false},
+		{"fail1", []net.IP{ip1}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip2}}}, true},
+		{"fail2", []net.IP{ip1}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip2, ip1}}}, true},
+		{"fail3", []net.IP{ip1, ip2}, args{&x509.CertificateRequest{IPAddresses: []net.IP{ip1, ip3}}}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := tt.v.Valid(tt.args.req); (err != nil) != tt.wantErr {
+				t.Errorf("ipAddressesValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}
+
+func Test_validityValidator_Valid(t *testing.T) {
+	type fields struct {
+		min time.Duration
+		max time.Duration
+	}
+	type args struct {
+		crt *x509.Certificate
+	}
+	tests := []struct {
+		name    string
+		fields  fields
+		args    args
+		wantErr bool
+	}{
+		// TODO: Add test cases.
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			v := &validityValidator{
+				min: tt.fields.min,
+				max: tt.fields.max,
+			}
+			if err := v.Valid(tt.args.crt); (err != nil) != tt.wantErr {
+				t.Errorf("validityValidator.Valid() error = %v, wantErr %v", err, tt.wantErr)
+			}
+		})
+	}
+}

+ 380 - 0
authority/provisioner/sign_ssh_options.go

@@ -0,0 +1,380 @@
+package provisioner
+
+import (
+	"crypto/rsa"
+	"encoding/binary"
+	"math/big"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/crypto/keys"
+	"golang.org/x/crypto/ssh"
+)
+
+const (
+	// SSHUserCert is the string used to represent ssh.UserCert.
+	SSHUserCert = "user"
+
+	// SSHHostCert is the string used to represent ssh.HostCert.
+	SSHHostCert = "host"
+)
+
+// SSHCertificateModifier is the interface used to change properties in an SSH
+// certificate.
+type SSHCertificateModifier interface {
+	SignOption
+	Modify(cert *ssh.Certificate) error
+}
+
+// SSHCertificateOptionModifier is the interface used to add custom options used
+// to modify the SSH certificate.
+type SSHCertificateOptionModifier interface {
+	SignOption
+	Option(o SSHOptions) SSHCertificateModifier
+}
+
+// SSHCertificateValidator is the interface used to validate an SSH certificate.
+type SSHCertificateValidator interface {
+	SignOption
+	Valid(cert *ssh.Certificate) error
+}
+
+// SSHCertificateOptionsValidator is the interface used to validate the custom
+// options used to modify the SSH certificate.
+type SSHCertificateOptionsValidator interface {
+	SignOption
+	Valid(got SSHOptions) error
+}
+
+// SSHOptions contains the options that can be passed to the SignSSH method.
+type SSHOptions struct {
+	CertType    string       `json:"certType"`
+	Principals  []string     `json:"principals"`
+	ValidAfter  TimeDuration `json:"validAfter,omitempty"`
+	ValidBefore TimeDuration `json:"validBefore,omitempty"`
+}
+
+// Type returns the uint32 representation of the CertType.
+func (o SSHOptions) Type() uint32 {
+	return sshCertTypeUInt32(o.CertType)
+}
+
+// Modify implements SSHCertificateModifier and sets the SSHOption in the ssh.Certificate.
+func (o SSHOptions) Modify(cert *ssh.Certificate) error {
+	switch o.CertType {
+	case "": // ignore
+	case SSHUserCert:
+		cert.CertType = ssh.UserCert
+	case SSHHostCert:
+		cert.CertType = ssh.HostCert
+	default:
+		return errors.Errorf("ssh certificate has an unknown type: %s", o.CertType)
+	}
+	cert.ValidPrincipals = o.Principals
+	if !o.ValidAfter.IsZero() {
+		cert.ValidAfter = uint64(o.ValidAfter.Time().Unix())
+	}
+	if !o.ValidBefore.IsZero() {
+		cert.ValidBefore = uint64(o.ValidBefore.Time().Unix())
+	}
+	if cert.ValidAfter > 0 && cert.ValidBefore > 0 && cert.ValidAfter > cert.ValidBefore {
+		return errors.New("ssh certificate valid after cannot be greater than valid before")
+	}
+	return nil
+}
+
+// match compares two SSHOptions and return an error if they don't match. It
+// ignores zero values.
+func (o SSHOptions) match(got SSHOptions) error {
+	if o.CertType != "" && got.CertType != "" && o.CertType != got.CertType {
+		return errors.Errorf("ssh certificate type does not match - got %v, want %v", got.CertType, o.CertType)
+	}
+	if len(o.Principals) > 0 && len(got.Principals) > 0 && !containsAllMembers(o.Principals, got.Principals) {
+		return errors.Errorf("ssh certificate principals does not match - got %v, want %v", got.Principals, o.Principals)
+	}
+	if !o.ValidAfter.IsZero() && !got.ValidAfter.IsZero() && !o.ValidAfter.Equal(&got.ValidAfter) {
+		return errors.Errorf("ssh certificate valid after does not match - got %v, want %v", got.ValidAfter, o.ValidAfter)
+	}
+	if !o.ValidBefore.IsZero() && !got.ValidBefore.IsZero() && !o.ValidBefore.Equal(&got.ValidBefore) {
+		return errors.Errorf("ssh certificate valid before does not match - got %v, want %v", got.ValidBefore, o.ValidBefore)
+	}
+	return nil
+}
+
+// sshCertificateKeyIDModifier is an SSHCertificateModifier that sets the given
+// Key ID in the SSH certificate.
+type sshCertificateKeyIDModifier string
+
+func (m sshCertificateKeyIDModifier) Modify(cert *ssh.Certificate) error {
+	cert.KeyId = string(m)
+	return nil
+}
+
+// sshCertificateCertTypeModifier is an SSHCertificateModifier that sets the
+// certificate type to the SSH certificate.
+type sshCertificateCertTypeModifier string
+
+func (m sshCertificateCertTypeModifier) Modify(cert *ssh.Certificate) error {
+	cert.CertType = sshCertTypeUInt32(string(m))
+	return nil
+}
+
+// sshCertificatePrincipalsModifier is an SSHCertificateModifier that sets the
+// principals to the SSH certificate.
+type sshCertificatePrincipalsModifier []string
+
+func (m sshCertificatePrincipalsModifier) Modify(cert *ssh.Certificate) error {
+	cert.ValidPrincipals = []string(m)
+	return nil
+}
+
+// sshCertificateValidAfterModifier is an SSHCertificateModifier that sets the
+// ValidAfter in the SSH certificate.
+type sshCertificateValidAfterModifier uint64
+
+func (m sshCertificateValidAfterModifier) Modify(cert *ssh.Certificate) error {
+	cert.ValidAfter = uint64(m)
+	return nil
+}
+
+// sshCertificateValidBeforeModifier is an SSHCertificateModifier that sets the
+// ValidBefore in the SSH certificate.
+type sshCertificateValidBeforeModifier uint64
+
+func (m sshCertificateValidBeforeModifier) Modify(cert *ssh.Certificate) error {
+	cert.ValidBefore = uint64(m)
+	return nil
+}
+
+// sshCertificateDefaultModifier implements a SSHCertificateModifier that
+// modifies the certificate with the given options if they are not set.
+type sshCertificateDefaultsModifier SSHOptions
+
+// Modify implements the SSHCertificateModifier interface.
+func (m sshCertificateDefaultsModifier) Modify(cert *ssh.Certificate) error {
+	if cert.CertType == 0 {
+		cert.CertType = sshCertTypeUInt32(m.CertType)
+	}
+	if len(cert.ValidPrincipals) == 0 {
+		cert.ValidPrincipals = m.Principals
+	}
+	if cert.ValidAfter == 0 && !m.ValidAfter.IsZero() {
+		cert.ValidAfter = uint64(m.ValidAfter.Unix())
+	}
+	if cert.ValidBefore == 0 && !m.ValidBefore.IsZero() {
+		cert.ValidBefore = uint64(m.ValidBefore.Unix())
+	}
+	return nil
+}
+
+// sshDefaultExtensionModifier implements an SSHCertificateModifier that sets
+// the default extensions in an SSH certificate.
+type sshDefaultExtensionModifier struct{}
+
+func (m *sshDefaultExtensionModifier) Modify(cert *ssh.Certificate) error {
+	switch cert.CertType {
+	// Default to no extensions for HostCert.
+	case ssh.HostCert:
+		return nil
+	case ssh.UserCert:
+		if cert.Extensions == nil {
+			cert.Extensions = make(map[string]string)
+		}
+		cert.Extensions["permit-X11-forwarding"] = ""
+		cert.Extensions["permit-agent-forwarding"] = ""
+		cert.Extensions["permit-port-forwarding"] = ""
+		cert.Extensions["permit-pty"] = ""
+		cert.Extensions["permit-user-rc"] = ""
+		return nil
+	default:
+		return errors.New("ssh certificate type has not been set or is invalid")
+	}
+}
+
+// sshCertificateValidityModifier is a SSHCertificateModifier checks the
+// validity bounds, setting them if they are not provided. It will fail if a
+// CertType has not been set or is not valid.
+type sshCertificateValidityModifier struct {
+	*Claimer
+}
+
+func (m *sshCertificateValidityModifier) Modify(cert *ssh.Certificate) error {
+	var d, min, max time.Duration
+	switch cert.CertType {
+	case ssh.UserCert:
+		d = m.DefaultUserSSHCertDuration()
+		min = m.MinUserSSHCertDuration()
+		max = m.MaxUserSSHCertDuration()
+	case ssh.HostCert:
+		d = m.DefaultHostSSHCertDuration()
+		min = m.MinHostSSHCertDuration()
+		max = m.MaxHostSSHCertDuration()
+	case 0:
+		return errors.New("ssh certificate type has not been set")
+	default:
+		return errors.Errorf("unknown ssh certificate type %d", cert.CertType)
+	}
+
+	if cert.ValidAfter == 0 {
+		cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
+	}
+	if cert.ValidBefore == 0 {
+		t := time.Unix(int64(cert.ValidAfter), 0)
+		cert.ValidBefore = uint64(t.Add(d).Unix())
+	}
+
+	diff := time.Duration(cert.ValidBefore-cert.ValidAfter) * time.Second
+	switch {
+	case diff < min:
+		return errors.Errorf("ssh certificate duration cannot be lower than %s", min)
+	case diff > max:
+		return errors.Errorf("ssh certificate duration cannot be greater than %s", max)
+	default:
+		return nil
+	}
+}
+
+// sshCertificateOptionsValidator validates the user SSHOptions with the ones
+// usually present in the token.
+type sshCertificateOptionsValidator SSHOptions
+
+// Valid implements SSHCertificateOptionsValidator and returns nil if both
+// SSHOptions match.
+func (v sshCertificateOptionsValidator) Valid(got SSHOptions) error {
+	want := SSHOptions(v)
+	return want.match(got)
+}
+
+// sshCertificateDefaultValidator implements a simple validator for all the
+// fields in the SSH certificate.
+type sshCertificateDefaultValidator struct{}
+
+// Valid returns an error if the given certificate does not contain the necessary fields.
+func (v *sshCertificateDefaultValidator) Valid(cert *ssh.Certificate) error {
+	switch {
+	case len(cert.Nonce) == 0:
+		return errors.New("ssh certificate nonce cannot be empty")
+	case cert.Key == nil:
+		return errors.New("ssh certificate key cannot be nil")
+	case cert.Serial == 0:
+		return errors.New("ssh certificate serial cannot be 0")
+	case cert.CertType != ssh.UserCert && cert.CertType != ssh.HostCert:
+		return errors.Errorf("ssh certificate has an unknown type: %d", cert.CertType)
+	case cert.KeyId == "":
+		return errors.New("ssh certificate key id cannot be empty")
+	case len(cert.ValidPrincipals) == 0:
+		return errors.New("ssh certificate valid principals cannot be empty")
+	case cert.ValidAfter == 0:
+		return errors.New("ssh certificate validAfter cannot be 0")
+	case cert.ValidBefore < uint64(now().Unix()):
+		return errors.New("ssh certificate validBefore cannot be in the past")
+	case cert.ValidBefore < cert.ValidAfter:
+		return errors.New("ssh certificate validBefore cannot be before validAfter")
+	case cert.CertType == ssh.UserCert && len(cert.Extensions) == 0:
+		return errors.New("ssh certificate extensions cannot be empty")
+	case cert.SignatureKey == nil:
+		return errors.New("ssh certificate signature key cannot be nil")
+	case cert.Signature == nil:
+		return errors.New("ssh certificate signature cannot be nil")
+	default:
+		return nil
+	}
+}
+
+// sshDefaultPublicKeyValidator implements a validator for the certificate key.
+type sshDefaultPublicKeyValidator struct{}
+
+// Valid checks that certificate request common name matches the one configured.
+func (v sshDefaultPublicKeyValidator) Valid(cert *ssh.Certificate) error {
+	if cert.Key == nil {
+		return errors.New("ssh certificate key cannot be nil")
+	}
+	switch cert.Key.Type() {
+	case ssh.KeyAlgoRSA:
+		_, in, ok := sshParseString(cert.Key.Marshal())
+		if !ok {
+			return errors.New("ssh certificate key is invalid")
+		}
+		key, err := sshParseRSAPublicKey(in)
+		if err != nil {
+			return err
+		}
+		if key.Size() < keys.MinRSAKeyBytes {
+			return errors.Errorf("ssh certificate key must be at least %d bits (%d bytes)",
+				8*keys.MinRSAKeyBytes, keys.MinRSAKeyBytes)
+		}
+		return nil
+	case ssh.KeyAlgoDSA:
+		return errors.New("ssh certificate key algorithm (DSA) is not supported")
+	default:
+		return nil
+	}
+}
+
+// sshCertTypeUInt32
+func sshCertTypeUInt32(ct string) uint32 {
+	switch ct {
+	case SSHUserCert:
+		return ssh.UserCert
+	case SSHHostCert:
+		return ssh.HostCert
+	default:
+		return 0
+	}
+}
+
+// containsAllMembers reports whether all members of subgroup are within group.
+func containsAllMembers(group, subgroup []string) bool {
+	lg, lsg := len(group), len(subgroup)
+	if lsg > lg || (lg > 0 && lsg == 0) {
+		return false
+	}
+	visit := make(map[string]struct{}, lg)
+	for i := 0; i < lg; i++ {
+		visit[group[i]] = struct{}{}
+	}
+	for i := 0; i < lsg; i++ {
+		if _, ok := visit[subgroup[i]]; !ok {
+			return false
+		}
+	}
+	return true
+}
+
+func sshParseString(in []byte) (out, rest []byte, ok bool) {
+	if len(in) < 4 {
+		return
+	}
+	length := binary.BigEndian.Uint32(in)
+	in = in[4:]
+	if uint32(len(in)) < length {
+		return
+	}
+	out = in[:length]
+	rest = in[length:]
+	ok = true
+	return
+}
+
+func sshParseRSAPublicKey(in []byte) (*rsa.PublicKey, error) {
+	var w struct {
+		E    *big.Int
+		N    *big.Int
+		Rest []byte `ssh:"rest"`
+	}
+	if err := ssh.Unmarshal(in, &w); err != nil {
+		return nil, errors.Wrap(err, "error unmarshalling public key")
+	}
+	if w.E.BitLen() > 24 {
+		return nil, errors.New("invalid public key: exponent too large")
+	}
+	e := w.E.Int64()
+	if e < 3 || e&1 == 0 {
+		return nil, errors.New("invalid public key: incorrect exponent")
+	}
+
+	var key rsa.PublicKey
+	key.E = int(e)
+	key.N = w.N
+	return &key, nil
+}

+ 192 - 0
authority/provisioner/sign_ssh_options_test.go

@@ -0,0 +1,192 @@
+package provisioner
+
+import (
+	"testing"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/assert"
+	"github.com/smallstep/cli/crypto/keys"
+	"golang.org/x/crypto/ssh"
+)
+
+func Test_sshCertificateDefaultValidator_Valid(t *testing.T) {
+	pub, _, err := keys.GenerateDefaultKeyPair()
+	assert.FatalError(t, err)
+	sshPub, err := ssh.NewPublicKey(pub)
+	assert.FatalError(t, err)
+	v := sshCertificateDefaultValidator{}
+	tests := []struct {
+		name string
+		cert *ssh.Certificate
+		err  error
+	}{
+		{
+			"fail/zero-nonce",
+			&ssh.Certificate{},
+			errors.New("ssh certificate nonce cannot be empty"),
+		},
+		{
+			"fail/nil-key",
+			&ssh.Certificate{Nonce: []byte("foo")},
+			errors.New("ssh certificate key cannot be nil"),
+		},
+		{
+			"fail/zero-serial",
+			&ssh.Certificate{Nonce: []byte("foo"), Key: sshPub},
+			errors.New("ssh certificate serial cannot be 0"),
+		},
+		{
+			"fail/unexpected-cert-type",
+			// UserCert = 1, HostCert = 2
+			&ssh.Certificate{Nonce: []byte("foo"), Key: sshPub, CertType: 3, Serial: 1},
+			errors.New("ssh certificate has an unknown type: 3"),
+		},
+		{
+			"fail/empty-cert-key-id",
+			&ssh.Certificate{Nonce: []byte("foo"), Key: sshPub, Serial: 1, CertType: 1},
+			errors.New("ssh certificate key id cannot be empty"),
+		},
+		{
+			"fail/empty-valid-principals",
+			&ssh.Certificate{Nonce: []byte("foo"), Key: sshPub, Serial: 1, CertType: 1, KeyId: "foo"},
+			errors.New("ssh certificate valid principals cannot be empty"),
+		},
+		{
+			"fail/zero-validAfter",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      0,
+			},
+			errors.New("ssh certificate validAfter cannot be 0"),
+		},
+		{
+			"fail/validBefore-past",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Add(-10 * time.Minute).Unix()),
+				ValidBefore:     uint64(time.Now().Add(-5 * time.Minute).Unix()),
+			},
+			errors.New("ssh certificate validBefore cannot be in the past"),
+		},
+		{
+			"fail/validAfter-after-validBefore",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Add(15 * time.Minute).Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+			},
+			errors.New("ssh certificate validBefore cannot be before validAfter"),
+		},
+		{
+			"fail/empty-extensions",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+			},
+			errors.New("ssh certificate extensions cannot be empty"),
+		},
+		{
+			"fail/nil-signature-key",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+				Permissions: ssh.Permissions{
+					Extensions: map[string]string{"foo": "bar"},
+				},
+			},
+			errors.New("ssh certificate signature key cannot be nil"),
+		},
+		{
+			"fail/nil-signature",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+				Permissions: ssh.Permissions{
+					Extensions: map[string]string{"foo": "bar"},
+				},
+				SignatureKey: sshPub,
+			},
+			errors.New("ssh certificate signature cannot be nil"),
+		},
+		{
+			"ok/userCert",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        1,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+				Permissions: ssh.Permissions{
+					Extensions: map[string]string{"foo": "bar"},
+				},
+				SignatureKey: sshPub,
+				Signature:    &ssh.Signature{},
+			},
+			nil,
+		},
+		{
+			"ok/hostCert",
+			&ssh.Certificate{
+				Nonce:           []byte("foo"),
+				Key:             sshPub,
+				Serial:          1,
+				CertType:        2,
+				KeyId:           "foo",
+				ValidPrincipals: []string{"foo"},
+				ValidAfter:      uint64(time.Now().Unix()),
+				ValidBefore:     uint64(time.Now().Add(10 * time.Minute).Unix()),
+				SignatureKey:    sshPub,
+				Signature:       &ssh.Signature{},
+			},
+			nil,
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if err := v.Valid(tt.cert); err != nil {
+				if assert.NotNil(t, tt.err) {
+					assert.HasPrefix(t, err.Error(), tt.err.Error())
+				}
+			} else {
+				assert.Nil(t, tt.err)
+			}
+		})
+	}
+}

+ 125 - 0
authority/provisioner/ssh_test.go

@@ -0,0 +1,125 @@
+package provisioner
+
+import (
+	"crypto"
+	"crypto/rand"
+	"fmt"
+	"reflect"
+	"time"
+
+	"golang.org/x/crypto/ssh"
+)
+
+func validateSSHCertificate(cert *ssh.Certificate, opts *SSHOptions) error {
+	switch {
+	case cert == nil:
+		return fmt.Errorf("certificate is nil")
+	case cert.Signature == nil:
+		return fmt.Errorf("certificate signature is nil")
+	case cert.SignatureKey == nil:
+		return fmt.Errorf("certificate signature is nil")
+	case !reflect.DeepEqual(cert.ValidPrincipals, opts.Principals):
+		return fmt.Errorf("certificate principals are not equal, want %v, got %v", opts.Principals, cert.ValidPrincipals)
+	case cert.CertType != ssh.UserCert && cert.CertType != ssh.HostCert:
+		return fmt.Errorf("certificate type %v is not valid", cert.CertType)
+	case opts.CertType == "user" && cert.CertType != ssh.UserCert:
+		return fmt.Errorf("certificate type is not valid, want %v, got %v", ssh.UserCert, cert.CertType)
+	case opts.CertType == "host" && cert.CertType != ssh.HostCert:
+		return fmt.Errorf("certificate type is not valid, want %v, got %v", ssh.HostCert, cert.CertType)
+	case cert.ValidAfter != uint64(opts.ValidAfter.Unix()):
+		return fmt.Errorf("certificate valid after is not valid, want %v, got %v", opts.ValidAfter.Unix(), time.Unix(int64(cert.ValidAfter), 0))
+	case cert.ValidBefore != uint64(opts.ValidBefore.Unix()):
+		return fmt.Errorf("certificate valid after is not valid, want %v, got %v", opts.ValidAfter.Unix(), time.Unix(int64(cert.ValidAfter), 0))
+	case opts.CertType == "user" && len(cert.Extensions) != 5:
+		return fmt.Errorf("certificate extensions number is invalid, want 5, got %d", len(cert.Extensions))
+	case opts.CertType == "host" && len(cert.Extensions) != 0:
+		return fmt.Errorf("certificate extensions number is invalid, want 0, got %d", len(cert.Extensions))
+	default:
+		return nil
+	}
+}
+
+func signSSHCertificate(key crypto.PublicKey, opts SSHOptions, signOpts []SignOption, signKey crypto.Signer) (*ssh.Certificate, error) {
+	pub, err := ssh.NewPublicKey(key)
+	if err != nil {
+		return nil, err
+	}
+
+	var mods []SSHCertificateModifier
+	var validators []SSHCertificateValidator
+
+	for _, op := range signOpts {
+		switch o := op.(type) {
+		// modify the ssh.Certificate
+		case SSHCertificateModifier:
+			mods = append(mods, o)
+		// modify the ssh.Certificate given the SSHOptions
+		case SSHCertificateOptionModifier:
+			mods = append(mods, o.Option(opts))
+		// validate the ssh.Certificate
+		case SSHCertificateValidator:
+			validators = append(validators, o)
+		// validate the given SSHOptions
+		case SSHCertificateOptionsValidator:
+			if err := o.Valid(opts); err != nil {
+				return nil, err
+			}
+		default:
+			return nil, fmt.Errorf("signSSH: invalid extra option type %T", o)
+		}
+	}
+
+	// Build base certificate with the key and some random values
+	cert := &ssh.Certificate{
+		Nonce:  []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},
+		Key:    pub,
+		Serial: 1234567890,
+	}
+
+	// Use opts to modify the certificate
+	if err := opts.Modify(cert); err != nil {
+		return nil, err
+	}
+
+	// Use provisioner modifiers
+	for _, m := range mods {
+		if err := m.Modify(cert); err != nil {
+			return nil, err
+		}
+	}
+
+	// Get signer from authority keys
+	var signer ssh.Signer
+	switch cert.CertType {
+	case ssh.UserCert:
+		signer, err = ssh.NewSignerFromSigner(signKey)
+	case ssh.HostCert:
+		signer, err = ssh.NewSignerFromSigner(signKey)
+	default:
+		return nil, fmt.Errorf("unexpected ssh certificate type: %d", cert.CertType)
+	}
+	if err != nil {
+		return nil, err
+	}
+	cert.SignatureKey = signer.PublicKey()
+
+	// Get bytes for signing trailing the signature length.
+	data := cert.Marshal()
+	data = data[:len(data)-4]
+
+	// Sign the certificate
+	sig, err := signer.Sign(rand.Reader, data)
+	if err != nil {
+		return nil, err
+	}
+	cert.Signature = sig
+
+	// User provisioners validators
+	for _, v := range validators {
+		if err := v.Valid(cert); err != nil {
+			return nil, err
+		}
+	}
+
+	return cert, nil
+}

+ 7 - 0
authority/provisioner/testdata/ecdsa.csr

@@ -0,0 +1,7 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIHqMIGRAgEAMA4xDDAKBgNVBAMTA2ZvbzBZMBMGByqGSM49AgEGCCqGSM49AwEH
+A0IABKdDjTb7XIYCWC4QUq1xn5hgf3J4WpfWbd3C5frKrA4/VdQ+XfpHQIxDoHqh
+jcWke0SEETc9i6HDDtWv8bXSETegITAfBgkqhkiG9w0BCQ4xEjAQMA4GA1UdEQQH
+MAWCA2ZvbzAKBggqhkjOPQQDAgNIADBFAiEA1pFLT8p/YogG0o6NEEmdxzwbOzJA
+A+C+DvoT91c1OcQCIGUjP3s+k6Xwdf/VukUZXTfG1lobmkZhO3vYxAjPkwA7
+-----END CERTIFICATE REQUEST-----

+ 8 - 0
authority/provisioner/testdata/ecdsa.key

@@ -0,0 +1,8 @@
+-----BEGIN EC PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: AES-256-CBC,54abd40e525b255542ee6161ec438721
+
+fJvmEc5n0IG4t4FKF+ekKhpog4ods2nZjBR5KLkGH5oSGAOEADSXIRBK76Jnm/nz
+Kv8ZwGqxNnoJUQyeTMlyg5OnOUAQPyNBPvoItOlD2DP32WJXgQ+NSHB2h9pcBGYG
+yLWrCtzl9/P9REWskanPO4RujP27Ht62omcMO7SxxNI=
+-----END EC PRIVATE KEY-----

+ 6 - 0
authority/provisioner/testdata/ed25519.csr

@@ -0,0 +1,6 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIGuMGICAQAwDjEMMAoGA1UEAxMDZm9vMCowBQYDK2VwAyEA3yF/Igqb5UTp6XOq
+yj+cZL9nIfjDKrUT0fMzDAHtIqqgITAfBgkqhkiG9w0BCQ4xEjAQMA4GA1UdEQQH
+MAWCA2ZvbzAFBgMrZXADQQAIAx7N6ezi4NL8n0oJU8v3AmVSi0XvTuIHXUtcLGoU
+OZtlO3zjWI+DgcT/ADeEKn+T8OazDxcCbTBbHiM2hIsA
+-----END CERTIFICATE REQUEST-----

+ 6 - 0
authority/provisioner/testdata/ed25519.key

@@ -0,0 +1,6 @@
+-----BEGIN ENCRYPTED PRIVATE KEY-----
+MIGkMGAGCSqGSIb3DQEFDTBTMDIGCSqGSIb3DQEFDDAlBBDJ0vCXdpPyUiLlbge5
+1g0jAgMBhqAwDAYIKoZIhvcNAgkAADAdBglghkgBZQMEASoEENtOknzU2eS2mlxl
+73Yo/IoEQEyJS2EEx3+oYaKlFIB90e1Zkmi8da7d3r2iUlfc7faRAiKChcEvtEas
+vYF2l9LEZ9DXv1Rm1uyNuSpXuddHScE=
+-----END ENCRYPTED PRIVATE KEY-----

+ 11 - 0
authority/provisioner/testdata/root_ca.crt

@@ -0,0 +1,11 @@
+-----BEGIN CERTIFICATE-----
+MIIBhzCCASygAwIBAgIRANJiwPnM38wWznkJGOcIyIYwCgYIKoZIzj0EAwIwITEf
+MB0GA1UEAxMWU21hbGxzdGVwIFRlc3QgUm9vdCBDQTAeFw0xODA5MjcxODE4MDla
+Fw0yODA5MjQxODE4MDlaMCExHzAdBgNVBAMTFlNtYWxsc3RlcCBUZXN0IFJvb3Qg
+Q0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAS15w7dx9zPjCnQ7+RlRkvUXQJN
+Fjk5Hg5K9nCoiiNQQhcQMw63/pXQxHNsugiMshcN59XJC8195KJPm25nXN8co0Uw
+QzAOBgNVHQ8BAf8EBAMCAaYwEgYDVR0TAQH/BAgwBgEB/wIBATAdBgNVHQ4EFgQU
+B2BAXUSPZbFjnY6VzbApV48Tn3owCgYIKoZIzj0EAwIDSQAwRgIhAJRTVmc2xW8c
+ESx4oIp2d/OX9KBZzpcNi9fHnnJCS0FXAiEA7OpFb2+b8KBzg1c02x21PS7pHoET
+/A8LXNH4M06A7vE=
+-----END CERTIFICATE-----

+ 16 - 0
authority/provisioner/testdata/rsa.csr

@@ -0,0 +1,16 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIICdDCCAVwCAQAwDjEMMAoGA1UEAxMDZm9vMIIBIjANBgkqhkiG9w0BAQEFAAOC
+AQ8AMIIBCgKCAQEA86h3t/KJylE0/aPxvF9JqPaOwSsGexuDWqDVJSOWBJi/ZqUA
+Ea2Gy05ZIJkQ5GOy0bUs2JCNCVXVkfPrUkX6IvIlXpTjutjMDYyYGdgQjzpKPnOA
+v3mO2a7mLMzJunws7pvrUPP7z5KDCKSAPf6VAcu/na8rGDWn1TUYR8hINK1rLQQf
+OcyNWrr7yLkR84jSsrw/Qgc8NS//F4ccca1NfZecPEtxgcHjKdDQZ3SYRAfb6Dc0
+jRuvoByAd3q9okOOr70gpMXgpoFVArDynaHMPK9xJ1w2p3s2/NhOYgY9f9rtcWTo
+afoAcHK1jy5iQCogFUKt1bUCz5IsaYkRt+D+HQIDAQABoCEwHwYJKoZIhvcNAQkO
+MRIwEDAOBgNVHREEBzAFggNmb28wDQYJKoZIhvcNAQELBQADggEBAOsv1UKwEbcY
+8Fj2Pl55BjkqQG4PqSQdWJZfK0ol/GRty5XFaTgOUZyTeXOag84OGw0qM0E7kkUa
+O5QwDOpnmIgg01Ywr4QM166l1iED+eOUscXJMonBAsS3JNYF1JxcDyKzIl/dt9+w
+JXQ64uquuD57amOs8++ROfKW988HzXm0OnoHj8LZ1Mq2yUmxvnnfVnmMpZWo43sA
+8NQs4v9dT5wLByFvBjcaWiGVZwZiwT4Q/Msskv9L0o1On0fgCJ6PjLYdblTwMHDZ
+syH+X8SsUqeEmyvtiRc1XUeFbxS2hnPXJCXeyfljqwsBNGaVhBXcsV2Lg7IaloBF
+/RyWqQZ44eE=
+-----END CERTIFICATE REQUEST-----

+ 30 - 0
authority/provisioner/testdata/rsa.key

@@ -0,0 +1,30 @@
+-----BEGIN RSA PRIVATE KEY-----
+Proc-Type: 4,ENCRYPTED
+DEK-Info: AES-256-CBC,e77ed7e2d2572b5a246a1c4b994190bb
+
+29o7UA/L7OF7inTPKkwBrtd8CJdXVQs9R3oJPitmFk8SZbrLHEiEhF1C0uB3xK3s
+GWQ9O7bjERM3uAvQkd7MSkUUBpyPXS9GFacd85e85d1Ubl6miTAwkFrQnT9yn6n/
+Fak5JtkmdB6ObfVTioOwT1jdtGTifKg1bIhYISgwqCWhgV2fUFk6HQAAIMXTTRc+
+ZK1WbunT7LimYrnN3gQ4ylm/4C8nQl3JCGpvWZaRoH91q1LLD6IwWmX0D09F37dU
+X3KoKv/GvuDlV3H1dUBwxhU+GI5/lItPp9OcdLZnnr67Gs+X+do3MFT1h675TM4N
+c9QEIJB6RYatLBKHCS7j8W7EbuJAFZ+MCCapP92ERmVVVsWPY+V7CDVQxM2v4X/w
+7C7JYx8b4xuQbdvu9KVU5irsXg8hBx7kDb/mtWjT4+8+sseLKA4oOmI6XwVMdbow
+MciGilAIaNtWwQHe0EK9E9tiQfc9OyzxdrfplRckAAehHuPGU7+iMCsigCLT3aiV
+CDHmnLdTXKIvGe8faTQoJphrb9F8bobGo5D4ZqX5f6gKuPIJsfd/r0GD8VNSF/Q7
+SJQMhkVyaixFB0gQbmea7sTyScdW+Qne7nLpam3ISgo+G4CAH8W88wLnuHMLmvoC
+ZE3HvArSeQZ0WPHgB86AfoNRIxd6Emgb+dFyA6wPJC29nZkB8PFSrAHp0zp7KilF
+fe9K2dVAUBZFhQthQIYAjJmYLCukLhxUALiqdSmQZrt6DSE33K8s5ed2KJu/60G6
+lZwIzQHPXesRhwmwbkfPB8CyWM+L6osdWv8QyMdM8Wb+66zkhKWBNbm+ccMfP6Zf
+1ynF/a/DRX8bf81w+nvLsCGTdxVuEVEpuzS1NclKTmYQu58Ol0RgQe2JSxL89n+A
+JAHUu9g9LcTg2jNPjxeA/vusSXMZRrPqrUCYhHhcgR4mE13uyyFI/9frk0gPpKXp
+/FislMydWov2JRp1ixzypMBqlFR/zF6j6m3P1g7gchwScWzrZQHD58xdRin4Udiv
+OR4huswh5v2i/0KozBoUAwbvPGERnMlTaGoBMPJ5Xe/jkBJw3uC3Dhi74uyUCjqU
+hMQW4RJKmuiZVfAIX0RdgeUWXPs+8pf2pXrpIiVHCAHDrxXNMC7X6/9EcBN15B88
+W5/KIRngDeB2oVYrn1GfO7iLu1Rd8VFXyaVItOXq7WrL2pwm8ANhWcFDdnXf6jHW
+BcKss1j8rZxOchksf+ZPXhn3QkdooD9iVONky1zLIsV5GPwMe8+yXwXznzJSbHH7
+dOfhK93fZqUwx4gFULwCuWIwLTfNmQ3VzdKioGt39RFDVQb+pbR7p9jv899VjsVO
+TBBpRa00fvbK1H2CMVHnwwIf82M4XypSNGR/tSD3AImZPb5RfZnznoXXCMEfYVsd
+8/Ry4GHusA+zxCjCxHFtXVkb9sklewJtnUmN5mUzo/81szuigLB5IADR21IOyVBq
+A4kz96Ta885Z5owhonfZp1HD53pDEbxCuuIy+fgYfjfDSAj3L/QT3ZKrdcIdYQap
+PhrNRW3j38koAatTLd3+E9KqBO5BiY+T5h+Q3XesWnaXInfu5WKiiEm5hHiejA0C
+-----END RSA PRIVATE KEY-----

+ 10 - 0
authority/provisioner/testdata/short-rsa.csr

@@ -0,0 +1,10 @@
+-----BEGIN CERTIFICATE REQUEST-----
+MIIBdDCB2wIBADAOMQwwCgYDVQQDEwNmb28wgaIwDQYJKoZIhvcNAQEBBQADgZAA
+MIGMAoGEAK8dks7oV6kcIFEaWna7CDGYPAE8IL7rNi+ruQ1dIYz+JtxT7OPjbCn/
+t5iqni96+35iS/8CvMtEuquOMTMSWOWwlurrbTbLqCazuz/g233o8udxSxhny3cY
+wHogp4cXCX6cFll6DeUnoCEuTTSIu8IBHbK48VfNw4V4gGz6cp/H93HrAgMBAAGg
+ITAfBgkqhkiG9w0BCQ4xEjAQMA4GA1UdEQQHMAWCA2ZvbzANBgkqhkiG9w0BAQsF
+AAOBhABCZsYM+Kgje68Z9Fjl2+cBwtQHvZDarh+cz6W1SchinZ1T0aNQvSj/otOe
+ttnEF4Rq8zqzr4fbv+AF451Mx36AkfgZr9XWGzxidrH+fBCNWXWNR+ymhrL6UFTG
+2FbarLt9jN2aJLAYQPwtSeGTAZ74tLOPRPnTP6aMfFNg4XCR0uveHA==
+-----END CERTIFICATE REQUEST-----

+ 146 - 0
authority/provisioner/timeduration.go

@@ -0,0 +1,146 @@
+package provisioner
+
+import (
+	"encoding/json"
+	"time"
+
+	"github.com/pkg/errors"
+)
+
+var now = func() time.Time {
+	return time.Now().UTC()
+}
+
+// TimeDuration is a type that represents a time but the JSON unmarshaling can
+// use a time using the RFC 3339 format or a time.Duration string. If a duration
+// is used, the time will be set on the first call to TimeDuration.Time.
+type TimeDuration struct {
+	t time.Time
+	d time.Duration
+}
+
+// NewTimeDuration returns a TimeDuration with the defined time.
+func NewTimeDuration(t time.Time) TimeDuration {
+	return TimeDuration{t: t}
+}
+
+// ParseTimeDuration returns a new TimeDuration parsing the RFC 3339 time or
+// time.Duration string.
+func ParseTimeDuration(s string) (TimeDuration, error) {
+	if s == "" {
+		return TimeDuration{}, nil
+	}
+
+	// Try to use the unquoted RFC 3339 format
+	var t time.Time
+	if err := t.UnmarshalText([]byte(s)); err == nil {
+		return TimeDuration{t: t.UTC()}, nil
+	}
+
+	// Try to use the time.Duration string format
+	if d, err := time.ParseDuration(s); err == nil {
+		return TimeDuration{d: d}, nil
+	}
+
+	return TimeDuration{}, errors.Errorf("failed to parse %s", s)
+}
+
+// SetDuration initializes the TimeDuration with the given duration string. If
+// the time was set it will re-set to zero.
+func (t *TimeDuration) SetDuration(d time.Duration) {
+	t.t, t.d = time.Time{}, d
+}
+
+// SetTime initializes the TimeDuration with the given time. If the duration is
+// set it will be re-set to zero.
+func (t *TimeDuration) SetTime(tt time.Time) {
+	t.t, t.d = tt, 0
+}
+
+// IsZero returns true the TimeDuration represents the zero value, false
+// otherwise.
+func (t *TimeDuration) IsZero() bool {
+	return t.t.IsZero() && t.d == 0
+}
+
+// Equal returns if t and other are equal.
+func (t *TimeDuration) Equal(other *TimeDuration) bool {
+	return t.t.Equal(other.t) && t.d == other.d
+}
+
+// MarshalJSON implements the json.Marshaler interface. If the time is set it
+// will return the time in RFC 3339 format if not it will return the duration
+// string.
+func (t TimeDuration) MarshalJSON() ([]byte, error) {
+	switch {
+	case t.t.IsZero():
+		if t.d == 0 {
+			return []byte(`""`), nil
+		}
+		return json.Marshal(t.d.String())
+	default:
+		return t.t.MarshalJSON()
+	}
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface. The time is expected
+// to be a quoted string in RFC 3339 format or a quoted time.Duration string.
+func (t *TimeDuration) UnmarshalJSON(data []byte) error {
+	var s string
+	if err := json.Unmarshal(data, &s); err != nil {
+		return errors.Wrapf(err, "error unmarshaling %s", data)
+	}
+
+	// Empty TimeDuration
+	if s == "" {
+		*t = TimeDuration{}
+		return nil
+	}
+
+	// Try to use the unquoted RFC 3339 format
+	var tt time.Time
+	if err := tt.UnmarshalText([]byte(s)); err == nil {
+		*t = TimeDuration{t: tt}
+		return nil
+	}
+
+	// Try to use the time.Duration string format
+	if d, err := time.ParseDuration(s); err == nil {
+		*t = TimeDuration{d: d}
+		return nil
+	}
+
+	return errors.Errorf("failed to parse %s", data)
+}
+
+// Time calculates the time if needed and returns it.
+func (t *TimeDuration) Time() time.Time {
+	return t.RelativeTime(now())
+}
+
+// Unix calculates the time if needed it and returns the Unix time in seconds.
+func (t *TimeDuration) Unix() int64 {
+	return t.RelativeTime(now()).Unix()
+}
+
+// RelativeTime returns the embedded time.Time or the base time plus the
+// duration if this is not zero.
+func (t *TimeDuration) RelativeTime(base time.Time) time.Time {
+	switch {
+	case t == nil:
+		return time.Time{}
+	case t.t.IsZero():
+		if t.d == 0 {
+			return time.Time{}
+		}
+		t.t = base.Add(t.d)
+		return t.t.UTC()
+	default:
+		return t.t.UTC()
+	}
+}
+
+// String implements the fmt.Stringer interface.
+func (t *TimeDuration) String() string {
+	return t.Time().String()
+}

+ 268 - 0
authority/provisioner/timeduration_test.go

@@ -0,0 +1,268 @@
+package provisioner
+
+import (
+	"reflect"
+	"testing"
+	"time"
+)
+
+func mockNow() (time.Time, func()) {
+	tm := time.Unix(1584198566, 535897000).UTC()
+	nowFn := now
+	now = func() time.Time {
+		return tm
+	}
+	return tm, func() {
+		now = nowFn
+	}
+}
+
+func TestNewTimeDuration(t *testing.T) {
+	tm := time.Unix(1584198566, 535897000).UTC()
+	type args struct {
+		t time.Time
+	}
+	tests := []struct {
+		name string
+		args args
+		want TimeDuration
+	}{
+		{"ok", args{tm}, TimeDuration{t: tm}},
+		{"zero", args{time.Time{}}, TimeDuration{}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := NewTimeDuration(tt.args.t); !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("NewTimeDuration() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestParseTimeDuration(t *testing.T) {
+	type args struct {
+		s string
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    TimeDuration
+		wantErr bool
+	}{
+		{"timestamp", args{"2020-03-14T15:09:26.535897Z"}, TimeDuration{t: time.Unix(1584198566, 535897000).UTC()}, false},
+		{"timestamp", args{"2020-03-14T15:09:26Z"}, TimeDuration{t: time.Unix(1584198566, 0).UTC()}, false},
+		{"timestamp", args{"2020-03-14T15:09:26.535897-07:00"}, TimeDuration{t: time.Unix(1584223766, 535897000).UTC()}, false},
+		{"timestamp", args{"2020-03-14T15:09:26-07:00"}, TimeDuration{t: time.Unix(1584223766, 0).UTC()}, false},
+		{"timestamp", args{"2020-03-14T15:09:26.535897+07:00"}, TimeDuration{t: time.Unix(1584173366, 535897000).UTC()}, false},
+		{"timestamp", args{"2020-03-14T15:09:26+07:00"}, TimeDuration{t: time.Unix(1584173366, 0).UTC()}, false},
+		{"1h", args{"1h"}, TimeDuration{d: 1 * time.Hour}, false},
+		{"-24h60m60s", args{"-24h60m60s"}, TimeDuration{d: -24*time.Hour - 60*time.Minute - 60*time.Second}, false},
+		{"0", args{"0"}, TimeDuration{}, false},
+		{"empty", args{""}, TimeDuration{}, false},
+		{"fail", args{"2020-03-14T15:09:26Z07:00"}, TimeDuration{}, true},
+		{"fail", args{"1d"}, TimeDuration{}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := ParseTimeDuration(tt.args.s)
+			if (err != nil) != tt.wantErr {
+				t.Errorf("ParseTimeDuration() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("ParseTimeDuration() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_SetDuration(t *testing.T) {
+	type fields struct {
+		t time.Time
+		d time.Duration
+	}
+	type args struct {
+		d time.Duration
+	}
+	tests := []struct {
+		name   string
+		fields fields
+		args   args
+		want   *TimeDuration
+	}{
+		{"new", fields{}, args{2 * time.Hour}, &TimeDuration{d: 2 * time.Hour}},
+		{"old", fields{time.Now(), 1 * time.Hour}, args{2 * time.Hour}, &TimeDuration{d: 2 * time.Hour}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			td := &TimeDuration{
+				t: tt.fields.t,
+				d: tt.fields.d,
+			}
+			td.SetDuration(tt.args.d)
+			if !reflect.DeepEqual(td, tt.want) {
+				t.Errorf("SetDuration() = %v, want %v", td, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_SetTime(t *testing.T) {
+	tm := time.Unix(1584198566, 535897000).UTC()
+
+	type fields struct {
+		t time.Time
+		d time.Duration
+	}
+	type args struct {
+		tt time.Time
+	}
+	tests := []struct {
+		name   string
+		fields fields
+		args   args
+		want   *TimeDuration
+	}{
+		{"new", fields{}, args{tm}, &TimeDuration{t: tm}},
+		{"old", fields{time.Now(), 1 * time.Hour}, args{tm}, &TimeDuration{t: tm}},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			td := &TimeDuration{
+				t: tt.fields.t,
+				d: tt.fields.d,
+			}
+			td.SetTime(tt.args.tt)
+			if !reflect.DeepEqual(td, tt.want) {
+				t.Errorf("SetTime() = %v, want %v", td, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_MarshalJSON(t *testing.T) {
+	tm := time.Unix(1584198566, 535897000).UTC()
+	tests := []struct {
+		name         string
+		timeDuration TimeDuration
+		want         []byte
+		wantErr      bool
+	}{
+		{"empty", TimeDuration{}, []byte(`""`), false},
+		{"timestamp", TimeDuration{t: tm}, []byte(`"2020-03-14T15:09:26.535897Z"`), false},
+		{"duration", TimeDuration{d: 1 * time.Hour}, []byte(`"1h0m0s"`), false},
+		{"fail", TimeDuration{t: time.Date(-1, 0, 0, 0, 0, 0, 0, time.UTC)}, nil, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got, err := tt.timeDuration.MarshalJSON()
+			if (err != nil) != tt.wantErr {
+				t.Errorf("TimeDuration.MarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+				return
+			}
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("TimeDuration.MarshalJSON() = %s, want %s", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_UnmarshalJSON(t *testing.T) {
+	type args struct {
+		data []byte
+	}
+	tests := []struct {
+		name    string
+		args    args
+		want    *TimeDuration
+		wantErr bool
+	}{
+		{"empty", args{[]byte(`""`)}, &TimeDuration{}, false},
+		{"timestamp", args{[]byte(`"2020-03-14T15:09:26.535897Z"`)}, &TimeDuration{t: time.Unix(1584198566, 535897000).UTC()}, false},
+		{"duration", args{[]byte(`"1h"`)}, &TimeDuration{d: time.Hour}, false},
+		{"fail", args{[]byte("123")}, &TimeDuration{}, true},
+		{"fail", args{[]byte(`"2020-03-14T15:09:26.535897Z07:00"`)}, &TimeDuration{}, true},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			td := &TimeDuration{}
+			if err := td.UnmarshalJSON(tt.args.data); (err != nil) != tt.wantErr {
+				t.Errorf("TimeDuration.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
+			}
+			if !reflect.DeepEqual(td, tt.want) {
+				t.Errorf("TimeDuration.UnmarshalJSON() = %s, want %s", td, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_Time(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+	tests := []struct {
+		name         string
+		timeDuration *TimeDuration
+		want         time.Time
+	}{
+		{"zero", nil, time.Time{}},
+		{"zero", &TimeDuration{}, time.Time{}},
+		{"timestamp", &TimeDuration{t: tm}, tm},
+		{"local", &TimeDuration{t: tm.Local()}, tm},
+		{"duration", &TimeDuration{d: 1 * time.Hour}, tm.Add(1 * time.Hour)},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := tt.timeDuration.Time()
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("TimeDuration.Time() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestTimeDuration_Unix(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+	tests := []struct {
+		name         string
+		timeDuration *TimeDuration
+		want         int64
+	}{
+		{"zero", nil, -62135596800},
+		{"zero", &TimeDuration{}, -62135596800},
+		{"timestamp", &TimeDuration{t: tm}, 1584198566},
+		{"local", &TimeDuration{t: tm.Local()}, 1584198566},
+		{"duration", &TimeDuration{d: 1 * time.Hour}, 1584202166},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			got := tt.timeDuration.Unix()
+			if !reflect.DeepEqual(got, tt.want) {
+				t.Errorf("TimeDuration.Unix() = %v, want %v", got, tt.want)
+
+			}
+		})
+	}
+}
+
+func TestTimeDuration_String(t *testing.T) {
+	tm, fn := mockNow()
+	defer fn()
+	tests := []struct {
+		name         string
+		timeDuration *TimeDuration
+		want         string
+	}{
+		{"zero", nil, "0001-01-01 00:00:00 +0000 UTC"},
+		{"zero", &TimeDuration{}, "0001-01-01 00:00:00 +0000 UTC"},
+		{"timestamp", &TimeDuration{t: tm}, "2020-03-14 15:09:26.535897 +0000 UTC"},
+		{"duration", &TimeDuration{d: 1 * time.Hour}, "2020-03-14 16:09:26.535897 +0000 UTC"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := tt.timeDuration.String(); got != tt.want {
+				t.Errorf("TimeDuration.String() = %v, want %v", got, tt.want)
+			}
+		})
+	}
+}

+ 744 - 0
authority/provisioner/utils_test.go

@@ -0,0 +1,744 @@
+package provisioner
+
+import (
+	"crypto"
+	"crypto/rand"
+	"crypto/sha256"
+	"crypto/x509"
+	"encoding/base64"
+	"encoding/hex"
+	"encoding/json"
+	"encoding/pem"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"time"
+
+	"github.com/pkg/errors"
+	"github.com/smallstep/cli/crypto/randutil"
+	"github.com/smallstep/cli/jose"
+)
+
+var testAudiences = Audiences{
+	Sign:   []string{"https://ca.smallstep.com/sign", "https://ca.smallstep.com/1.0/sign"},
+	Revoke: []string{"https://ca.smallstep.com/revoke", "https://ca.smallstep.com/1.0/revoke"},
+}
+
+const awsTestCertificate = `-----BEGIN CERTIFICATE-----
+MIICFTCCAX6gAwIBAgIRAKmbVVYAl/1XEqRfF3eJ97MwDQYJKoZIhvcNAQELBQAw
+GDEWMBQGA1UEAxMNQVdTIFRlc3QgQ2VydDAeFw0xOTA0MjQyMjU3MzlaFw0yOTA0
+MjEyMjU3MzlaMBgxFjAUBgNVBAMTDUFXUyBUZXN0IENlcnQwgZ8wDQYJKoZIhvcN
+AQEBBQADgY0AMIGJAoGBAOHMmMXwbXN90SoRl/xXAcJs5TacaVYJ5iNAVWM5KYyF
++JwqYuJp/umLztFUi0oX0luu3EzD4KurVeUJSzZjTFTX1d/NX6hA45+bvdSUOcgV
+UghO+2uhBZ4SNFxFRZ7SKvoWIN195l5bVX6/60Eo6+kUCKCkyxW4V/ksWzdXjHnf
+AgMBAAGjXzBdMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEBMB0G
+A1UdDgQWBBRHfLOjEddK/CWCIHNg8Oc/oJa1IzAYBgNVHREEETAPgg1BV1MgVGVz
+dCBDZXJ0MA0GCSqGSIb3DQEBCwUAA4GBAKNCiVM9eGb9dW2xNyHaHAmmy7ERB2OJ
+7oXHfLjooOavk9lU/Gs2jfX/JSBa84+DzWg9ShmCNLti8CxU/dhzXW7jE/5CcdTa
+DCA6B3Yl5TmfG9+D9dtFqRB2CiMgNcsJJE5Dc6pDwBIiSj/MkE0AaGVQmSwn6Cb6
+vX1TAxqeWJHq
+-----END CERTIFICATE-----`
+
+const awsTestKey = `-----BEGIN RSA PRIVATE KEY-----
+MIICXAIBAAKBgQDhzJjF8G1zfdEqEZf8VwHCbOU2nGlWCeYjQFVjOSmMhficKmLi
+af7pi87RVItKF9JbrtxMw+Crq1XlCUs2Y0xU19XfzV+oQOOfm73UlDnIFVIITvtr
+oQWeEjRcRUWe0ir6FiDdfeZeW1V+v+tBKOvpFAigpMsVuFf5LFs3V4x53wIDAQAB
+AoGADZQFF9oWatyFCHeYYSdGRs/PlNIhD3h262XB/L6CPh4MTi/KVH01RAwROstP
+uPvnvXWtb7xTtV8PQj+l0zZzb4W/DLCSBdoRwpuNXyffUCtbI22jPupTsVu+ENWR
+3x7HHzoZYjU45ADSTMxEtwD7/zyNgpRKjIA2HYpkt+fI27ECQQD5/AOr9/yQD73x
+cquF+FWahWgDL25YeMwdfe1HfpUxUxd9kJJKieB8E2BtBAv9XNguxIBpf7VlAKsF
+NFhdfWFHAkEA5zuX8vqDecSzyNNEQd3tugxt1pGOXNesHzuPbdlw3ppN9Rbd93an
+uU2TaAvTjr/3EkxulYNRmHs+RSVK54+uqQJAKWurhBQMAibJlzcj2ofiTz8pk9WJ
+GBmz4HMcHMuJlumoq8KHqtgbnRNs18Ni5TE8FMu0Z0ak3L52l98rgRokQwJBAJS8
+9KTLF79AFBVeME3eH4jJbe3TeyulX4ZHnZ8fe0b1IqhAqU8A+CpuCB+pW9A7Ewam
+O4vZCKd4vzljH6eL+OECQHHxhYoTW7lFpKGnUDG9fPZ3eYzWpgka6w1vvBk10BAu
+6fbwppM9pQ7DPMg7V6YGEjjT0gX9B9TttfHxGhvtZNQ=
+-----END RSA PRIVATE KEY-----`
+
+func must(args ...interface{}) []interface{} {
+	if l := len(args); l > 0 && args[l-1] != nil {
+		if err, ok := args[l-1].(error); ok {
+			panic(err)
+		}
+	}
+	return args
+}
+
+func generateJSONWebKey() (*jose.JSONWebKey, error) {
+	jwk, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
+	if err != nil {
+		return nil, err
+	}
+	fp, err := jwk.Thumbprint(crypto.SHA256)
+	if err != nil {
+		return nil, err
+	}
+	jwk.KeyID = string(hex.EncodeToString(fp))
+	return jwk, nil
+}
+
+func generateJSONWebKeySet(n int) (jose.JSONWebKeySet, error) {
+	var keySet jose.JSONWebKeySet
+	for i := 0; i < n; i++ {
+		key, err := generateJSONWebKey()
+		if err != nil {
+			return jose.JSONWebKeySet{}, err
+		}
+		keySet.Keys = append(keySet.Keys, *key)
+	}
+	return keySet, nil
+}
+
+func encryptJSONWebKey(jwk *jose.JSONWebKey) (*jose.JSONWebEncryption, error) {
+	b, err := json.Marshal(jwk)
+	if err != nil {
+		return nil, err
+	}
+	salt, err := randutil.Salt(jose.PBKDF2SaltSize)
+	if err != nil {
+		return nil, err
+	}
+	opts := new(jose.EncrypterOptions)
+	opts.WithContentType(jose.ContentType("jwk+json"))
+	recipient := jose.Recipient{
+		Algorithm:  jose.PBES2_HS256_A128KW,
+		Key:        []byte("password"),
+		PBES2Count: jose.PBKDF2Iterations,
+		PBES2Salt:  salt,
+	}
+	encrypter, err := jose.NewEncrypter(jose.DefaultEncAlgorithm, recipient, opts)
+	if err != nil {
+		return nil, err
+	}
+	return encrypter.Encrypt(b)
+}
+
+func decryptJSONWebKey(key string) (*jose.JSONWebKey, error) {
+	enc, err := jose.ParseEncrypted(key)
+	if err != nil {
+		return nil, err
+	}
+	b, err := enc.Decrypt([]byte("password"))
+	if err != nil {
+		return nil, err
+	}
+	jwk := new(jose.JSONWebKey)
+	if err := json.Unmarshal(b, jwk); err != nil {
+		return nil, err
+	}
+	return jwk, nil
+}
+
+func generateJWK() (*JWK, error) {
+	name, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	jwk, err := generateJSONWebKey()
+	if err != nil {
+		return nil, err
+	}
+	jwe, err := encryptJSONWebKey(jwk)
+	if err != nil {
+		return nil, err
+	}
+	public := jwk.Public()
+	encrypted, err := jwe.CompactSerialize()
+	if err != nil {
+		return nil, err
+	}
+	claimer, err := NewClaimer(nil, globalProvisionerClaims)
+	if err != nil {
+		return nil, err
+	}
+	return &JWK{
+		Name:         name,
+		Type:         "JWK",
+		Key:          &public,
+		EncryptedKey: encrypted,
+		Claims:       &globalProvisionerClaims,
+		audiences:    testAudiences,
+		claimer:      claimer,
+	}, nil
+}
+
+func generateOIDC() (*OIDC, error) {
+	name, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	clientID, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	issuer, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	jwk, err := generateJSONWebKey()
+	if err != nil {
+		return nil, err
+	}
+	claimer, err := NewClaimer(nil, globalProvisionerClaims)
+	if err != nil {
+		return nil, err
+	}
+	return &OIDC{
+		Name:                  name,
+		Type:                  "OIDC",
+		ClientID:              clientID,
+		ConfigurationEndpoint: "https://example.com/.well-known/openid-configuration",
+		Claims:                &globalProvisionerClaims,
+		configuration: openIDConfiguration{
+			Issuer:    issuer,
+			JWKSetURI: "https://example.com/.well-known/jwks",
+		},
+		keyStore: &keyStore{
+			keySet: jose.JSONWebKeySet{Keys: []jose.JSONWebKey{*jwk}},
+			expiry: time.Now().Add(24 * time.Hour),
+		},
+		claimer: claimer,
+	}, nil
+}
+
+func generateGCP() (*GCP, error) {
+	name, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	serviceAccount, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	jwk, err := generateJSONWebKey()
+	if err != nil {
+		return nil, err
+	}
+	claimer, err := NewClaimer(nil, globalProvisionerClaims)
+	if err != nil {
+		return nil, err
+	}
+	return &GCP{
+		Type:            "GCP",
+		Name:            name,
+		ServiceAccounts: []string{serviceAccount},
+		Claims:          &globalProvisionerClaims,
+		claimer:         claimer,
+		config:          newGCPConfig(),
+		keyStore: &keyStore{
+			keySet: jose.JSONWebKeySet{Keys: []jose.JSONWebKey{*jwk}},
+			expiry: time.Now().Add(24 * time.Hour),
+		},
+		audiences: testAudiences.WithFragment("gcp/" + name),
+	}, nil
+}
+
+func generateAWS() (*AWS, error) {
+	name, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	accountID, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	claimer, err := NewClaimer(nil, globalProvisionerClaims)
+	if err != nil {
+		return nil, err
+	}
+	block, _ := pem.Decode([]byte(awsTestCertificate))
+	if block == nil || block.Type != "CERTIFICATE" {
+		return nil, errors.New("error decoding AWS certificate")
+	}
+	cert, err := x509.ParseCertificate(block.Bytes)
+	if err != nil {
+		return nil, errors.Wrap(err, "error parsing AWS certificate")
+	}
+	return &AWS{
+		Type:     "AWS",
+		Name:     name,
+		Accounts: []string{accountID},
+		Claims:   &globalProvisionerClaims,
+		claimer:  claimer,
+		config: &awsConfig{
+			identityURL:        awsIdentityURL,
+			signatureURL:       awsSignatureURL,
+			certificate:        cert,
+			signatureAlgorithm: awsSignatureAlgorithm,
+		},
+		audiences: testAudiences.WithFragment("aws/" + name),
+	}, nil
+}
+
+func generateAWSWithServer() (*AWS, *httptest.Server, error) {
+	aws, err := generateAWS()
+	if err != nil {
+		return nil, nil, err
+	}
+	block, _ := pem.Decode([]byte(awsTestKey))
+	if block == nil || block.Type != "RSA PRIVATE KEY" {
+		return nil, nil, errors.New("error decoding AWS key")
+	}
+	key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
+	if err != nil {
+		return nil, nil, errors.Wrap(err, "error parsing AWS private key")
+	}
+	doc, err := json.MarshalIndent(awsInstanceIdentityDocument{
+		AccountID:        aws.Accounts[0],
+		Architecture:     "x86_64",
+		AvailabilityZone: "us-west-2b",
+		ImageID:          "image-id",
+		InstanceID:       "instance-id",
+		InstanceType:     "t2.micro",
+		PendingTime:      time.Now(),
+		PrivateIP:        "127.0.0.1",
+		Region:           "us-west-1",
+		Version:          "2017-09-30",
+	}, "", "  ")
+	if err != nil {
+		return nil, nil, err
+	}
+
+	sum := sha256.Sum256(doc)
+	signature, err := key.Sign(rand.Reader, sum[:], crypto.SHA256)
+	if err != nil {
+		return nil, nil, errors.Wrap(err, "error signing document")
+	}
+	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/latest/dynamic/instance-identity/document":
+			w.Write(doc)
+		case "/latest/dynamic/instance-identity/signature":
+			w.Write([]byte(base64.StdEncoding.EncodeToString(signature)))
+		case "/bad-document":
+			w.Write([]byte("{}"))
+		case "/bad-signature":
+			w.Write([]byte("YmFkLXNpZ25hdHVyZQo="))
+		case "/bad-json":
+			w.Write([]byte("{"))
+		default:
+			http.NotFound(w, r)
+		}
+	}))
+	aws.config.identityURL = srv.URL + "/latest/dynamic/instance-identity/document"
+	aws.config.signatureURL = srv.URL + "/latest/dynamic/instance-identity/signature"
+	return aws, srv, nil
+}
+
+func generateAzure() (*Azure, error) {
+	name, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	tenantID, err := randutil.Alphanumeric(10)
+	if err != nil {
+		return nil, err
+	}
+	claimer, err := NewClaimer(nil, globalProvisionerClaims)
+	if err != nil {
+		return nil, err
+	}
+	jwk, err := generateJSONWebKey()
+	if err != nil {
+		return nil, err
+	}
+	return &Azure{
+		Type:     "Azure",
+		Name:     name,
+		TenantID: tenantID,
+		Audience: azureDefaultAudience,
+		Claims:   &globalProvisionerClaims,
+		claimer:  claimer,
+		config:   newAzureConfig(tenantID),
+		oidcConfig: openIDConfiguration{
+			Issuer:    "https://sts.windows.net/" + tenantID + "/",
+			JWKSetURI: "https://login.microsoftonline.com/common/discovery/keys",
+		},
+		keyStore: &keyStore{
+			keySet: jose.JSONWebKeySet{Keys: []jose.JSONWebKey{*jwk}},
+			expiry: time.Now().Add(24 * time.Hour),
+		},
+	}, nil
+}
+
+func generateAzureWithServer() (*Azure, *httptest.Server, error) {
+	az, err := generateAzure()
+	if err != nil {
+		return nil, nil, err
+	}
+	writeJSON := func(w http.ResponseWriter, v interface{}) {
+		b, err := json.Marshal(v)
+		if err != nil {
+			w.WriteHeader(http.StatusInternalServerError)
+			return
+		}
+		w.Header().Add("Content-Type", "application/json")
+		w.WriteHeader(http.StatusOK)
+		w.Write(b)
+	}
+	getPublic := func(ks jose.JSONWebKeySet) jose.JSONWebKeySet {
+		var ret jose.JSONWebKeySet
+		for _, k := range ks.Keys {
+			ret.Keys = append(ret.Keys, k.Public())
+		}
+		return ret
+	}
+	issuer := "https://sts.windows.net/" + az.TenantID + "/"
+	srv := httptest.NewUnstartedServer(nil)
+	srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		switch r.URL.Path {
+		case "/error":
+			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+		case "/" + az.TenantID + "/.well-known/openid-configuration":
+			writeJSON(w, openIDConfiguration{Issuer: issuer, JWKSetURI: srv.URL + "/jwks_uri"})
+		case "/openid-configuration-no-issuer":
+			writeJSON(w, openIDConfiguration{Issuer: "", JWKSetURI: srv.URL + "/jwks_uri"})
+		case "/openid-configuration-fail-jwk":
+			writeJSON(w, openIDConfiguration{Issuer: issuer, JWKSetURI: srv.URL + "/error"})
+		case "/random":
+			keySet := must(generateJSONWebKeySet(2))[0].(jose.JSONWebKeySet)
+			w.Header().Add("Cache-Control", "max-age=5")
+			writeJSON(w, getPublic(keySet))
+		case "/private":
+			writeJSON(w, az.keyStore.keySet)
+		case "/jwks_uri":
+			w.Header().Add("Cache-Control", "max-age=5")
+			writeJSON(w, getPublic(az.keyStore.keySet))
+		case "/metadata/identity/oauth2/token":
+			tok, err := generateAzureToken("subject", issuer, "https://management.azure.com/", az.TenantID, "subscriptionID", "resourceGroup", "virtualMachine", time.Now(), &az.keyStore.keySet.Keys[0])
+			if err != nil {
+				http.Error(w, err.Error(), http.StatusInternalServerError)
+			} else {
+				writeJSON(w, azureIdentityToken{
+					AccessToken: tok,
+				})
+			}
+		default:
+			http.NotFound(w, r)
+		}
+	})
+	srv.Start()
+	az.config.oidcDiscoveryURL = srv.URL + "/" + az.TenantID + "/.well-known/openid-configuration"
+	az.config.identityTokenURL = srv.URL + "/metadata/identity/oauth2/token"
+	return az, srv, nil
+}
+
+func generateCollection(nJWK, nOIDC int) (*Collection, error) {
+	col := NewCollection(testAudiences)
+	for i := 0; i < nJWK; i++ {
+		p, err := generateJWK()
+		if err != nil {
+			return nil, err
+		}
+		col.Store(p)
+	}
+	for i := 0; i < nOIDC; i++ {
+		p, err := generateOIDC()
+		if err != nil {
+			return nil, err
+		}
+		col.Store(p)
+	}
+	return col, nil
+}
+
+func generateSimpleToken(iss, aud string, jwk *jose.JSONWebKey) (string, error) {
+	return generateToken("subject", iss, aud, "name@smallstep.com", []string{"test.smallstep.com"}, time.Now(), jwk)
+}
+
+func generateToken(sub, iss, aud string, email string, sans []string, iat time.Time, jwk *jose.JSONWebKey) (string, error) {
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
+	)
+	if err != nil {
+		return "", err
+	}
+
+	id, err := randutil.ASCII(64)
+	if err != nil {
+		return "", err
+	}
+
+	claims := struct {
+		jose.Claims
+		Email string   `json:"email"`
+		SANS  []string `json:"sans"`
+	}{
+		Claims: jose.Claims{
+			ID:        id,
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+		},
+		Email: email,
+		SANS:  sans,
+	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
+}
+
+func generateSimpleSSHUserToken(iss, aud string, jwk *jose.JSONWebKey) (string, error) {
+	return generateSSHToken("subject@localhost", iss, aud, time.Now(), &SSHOptions{
+		CertType:   "user",
+		Principals: []string{"name"},
+	}, jwk)
+}
+
+func generateSimpleSSHHostToken(iss, aud string, jwk *jose.JSONWebKey) (string, error) {
+	return generateSSHToken("subject@localhost", iss, aud, time.Now(), &SSHOptions{
+		CertType:   "host",
+		Principals: []string{"smallstep.com"},
+	}, jwk)
+}
+
+func generateSSHToken(sub, iss, aud string, iat time.Time, sshOpts *SSHOptions, jwk *jose.JSONWebKey) (string, error) {
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
+	)
+	if err != nil {
+		return "", err
+	}
+
+	id, err := randutil.ASCII(64)
+	if err != nil {
+		return "", err
+	}
+
+	claims := struct {
+		jose.Claims
+		Step *stepPayload `json:"step,omitempty"`
+	}{
+		Claims: jose.Claims{
+			ID:        id,
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+		},
+		Step: &stepPayload{
+			SSH: sshOpts,
+		},
+	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
+}
+
+func generateGCPToken(sub, iss, aud, instanceID, instanceName, projectID, zone string, iat time.Time, jwk *jose.JSONWebKey) (string, error) {
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
+	)
+	if err != nil {
+		return "", err
+	}
+	aud, err = generateSignAudience("https://ca.smallstep.com", aud)
+	if err != nil {
+		return "", err
+	}
+	claims := gcpPayload{
+		Claims: jose.Claims{
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+		},
+		AuthorizedParty: sub,
+		Email:           "foo@developer.gserviceaccount.com",
+		EmailVerified:   true,
+		Google: gcpGooglePayload{
+			ComputeEngine: gcpComputeEnginePayload{
+				InstanceID:                instanceID,
+				InstanceName:              instanceName,
+				InstanceCreationTimestamp: jose.NewNumericDate(iat),
+				ProjectID:                 projectID,
+				ProjectNumber:             1234567890,
+				Zone:                      zone,
+			},
+		},
+	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
+}
+
+func generateAWSToken(sub, iss, aud, accountID, instanceID, privateIP, region string, iat time.Time, key crypto.Signer) (string, error) {
+	doc, err := json.MarshalIndent(awsInstanceIdentityDocument{
+		AccountID:        accountID,
+		Architecture:     "x86_64",
+		AvailabilityZone: "us-west-2b",
+		ImageID:          "ami-123123",
+		InstanceID:       instanceID,
+		InstanceType:     "t2.micro",
+		PendingTime:      iat,
+		PrivateIP:        privateIP,
+		Region:           region,
+		Version:          "2017-09-30",
+	}, "", "  ")
+	if err != nil {
+		return "", err
+	}
+
+	sum := sha256.Sum256(doc)
+	signature, err := key.Sign(rand.Reader, sum[:], crypto.SHA256)
+	if err != nil {
+		return "", errors.Wrap(err, "error signing document")
+	}
+
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.HS256, Key: signature},
+		new(jose.SignerOptions).WithType("JWT"),
+	)
+	if err != nil {
+		return "", err
+	}
+
+	aud, err = generateSignAudience("https://ca.smallstep.com", aud)
+	if err != nil {
+		return "", err
+	}
+
+	claims := awsPayload{
+		Claims: jose.Claims{
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+		},
+		Amazon: awsAmazonPayload{
+			Document:  doc,
+			Signature: signature,
+		},
+	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
+}
+
+func generateAzureToken(sub, iss, aud, tenantID, subscriptionID, resourceGroup, virtualMachine string, iat time.Time, jwk *jose.JSONWebKey) (string, error) {
+	sig, err := jose.NewSigner(
+		jose.SigningKey{Algorithm: jose.ES256, Key: jwk.Key},
+		new(jose.SignerOptions).WithType("JWT").WithHeader("kid", jwk.KeyID),
+	)
+	if err != nil {
+		return "", err
+	}
+
+	claims := azurePayload{
+		Claims: jose.Claims{
+			Subject:   sub,
+			Issuer:    iss,
+			IssuedAt:  jose.NewNumericDate(iat),
+			NotBefore: jose.NewNumericDate(iat),
+			Expiry:    jose.NewNumericDate(iat.Add(5 * time.Minute)),
+			Audience:  []string{aud},
+			ID:        "the-jti",
+		},
+		AppID:            "the-appid",
+		AppIDAcr:         "the-appidacr",
+		IdentityProvider: "the-idp",
+		ObjectID:         "the-oid",
+		TenantID:         tenantID,
+		Version:          "the-version",
+		XMSMirID:         fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Compute/virtualMachines/%s", subscriptionID, resourceGroup, virtualMachine),
+	}
+	return jose.Signed(sig).Claims(claims).CompactSerialize()
+}
+
+func parseToken(token string) (*jose.JSONWebToken, *jose.Claims, error) {
+	tok, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, nil, err
+	}
+	claims := new(jose.Claims)
+	if err := tok.UnsafeClaimsWithoutVerification(claims); err != nil {
+		return nil, nil, err
+	}
+	return tok, claims, nil
+}
+
+func parseAWSToken(token string) (*jose.JSONWebToken, *awsPayload, error) {
+	tok, err := jose.ParseSigned(token)
+	if err != nil {
+		return nil, nil, err
+	}
+	claims := new(awsPayload)
+	if err := tok.UnsafeClaimsWithoutVerification(claims); err != nil {
+		return nil, nil, err
+	}
+	var doc awsInstanceIdentityDocument
+	if err := json.Unmarshal(claims.Amazon.Document, &doc); err != nil {
+		return nil, nil, errors.Wrap(err, "error unmarshaling identity document")
+	}
+	claims.document = doc
+	return tok, claims, nil
+}
+
+func generateJWKServer(n int) *httptest.Server {
+	hits := struct {
+		Hits int `json:"hits"`
+	}{}
+	writeJSON := func(w http.ResponseWriter, v interface{}) {
+		b, err := json.Marshal(v)
+		if err != nil {
+			w.WriteHeader(http.StatusInternalServerError)
+			return
+		}
+		w.Header().Add("Content-Type", "application/json")
+		w.WriteHeader(http.StatusOK)
+		w.Write(b)
+	}
+	getPublic := func(ks jose.JSONWebKeySet) jose.JSONWebKeySet {
+		var ret jose.JSONWebKeySet
+		for _, k := range ks.Keys {
+			ret.Keys = append(ret.Keys, k.Public())
+		}
+		return ret
+	}
+
+	defaultKeySet := must(generateJSONWebKeySet(n))[0].(jose.JSONWebKeySet)
+	srv := httptest.NewUnstartedServer(nil)
+	srv.Config.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		hits.Hits++
+		switch r.RequestURI {
+		case "/error":
+			http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
+		case "/hits":
+			writeJSON(w, hits)
+		case "/.well-known/openid-configuration":
+			writeJSON(w, openIDConfiguration{Issuer: "the-issuer", JWKSetURI: srv.URL + "/jwks_uri"})
+		case "/random":
+			keySet := must(generateJSONWebKeySet(n))[0].(jose.JSONWebKeySet)
+			w.Header().Add("Cache-Control", "max-age=5")
+			writeJSON(w, getPublic(keySet))
+		case "/no-cache":
+			keySet := must(generateJSONWebKeySet(n))[0].(jose.JSONWebKeySet)
+			w.Header().Add("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate")
+			writeJSON(w, getPublic(keySet))
+		case "/private":
+			writeJSON(w, defaultKeySet)
+		default:
+			w.Header().Add("Cache-Control", "max-age=5")
+			writeJSON(w, getPublic(defaultKeySet))
+		}
+	})
+
+	srv.Start()
+	return srv
+}
+
+func generateACME() (*ACME, error) {
+	// Initialize provisioners
+	p := &ACME{
+		Type: "ACME",
+		Name: "test@acme-provisioner.com",
+	}
+	if err := p.Init(Config{Claims: globalProvisionerClaims}); err != nil {
+		return nil, err
+	}
+	return p, nil
+}

+ 0 - 55
authority/provisioner_test.go

@@ -1,55 +0,0 @@
-package authority
-
-import (
-	"errors"
-	"testing"
-
-	"github.com/smallstep/assert"
-	jose "gopkg.in/square/go-jose.v2"
-)
-
-func TestProvisionerInit(t *testing.T) {
-	type ProvisionerValidateTest struct {
-		p   *Provisioner
-		err error
-	}
-	tests := map[string]func(*testing.T) ProvisionerValidateTest{
-		"fail-empty-name": func(t *testing.T) ProvisionerValidateTest {
-			return ProvisionerValidateTest{
-				p:   &Provisioner{},
-				err: errors.New("provisioner name cannot be empty"),
-			}
-		},
-		"fail-empty-type": func(t *testing.T) ProvisionerValidateTest {
-			return ProvisionerValidateTest{
-				p:   &Provisioner{Name: "foo"},
-				err: errors.New("provisioner type cannot be empty"),
-			}
-		},
-		"fail-empty-key": func(t *testing.T) ProvisionerValidateTest {
-			return ProvisionerValidateTest{
-				p:   &Provisioner{Name: "foo", Type: "bar"},
-				err: errors.New("provisioner key cannot be empty"),
-			}
-		},
-		"ok": func(t *testing.T) ProvisionerValidateTest {
-			return ProvisionerValidateTest{
-				p: &Provisioner{Name: "foo", Type: "bar", Key: &jose.JSONWebKey{}},
-			}
-		},
-	}
-
-	for name, get := range tests {
-		t.Run(name, func(t *testing.T) {
-			tc := get(t)
-			err := tc.p.Init(&globalProvisionerClaims)
-			if err != nil {
-				if assert.NotNil(t, tc.err) {
-					assert.Equals(t, tc.err.Error(), err.Error())
-				}
-			} else {
-				assert.Nil(t, tc.err)
-			}
-		})
-	}
-}

+ 21 - 89
authority/provisioners.go

@@ -1,115 +1,47 @@
 package authority
 
 import (
-	"crypto/sha1"
-	"encoding/binary"
-	"encoding/hex"
-	"encoding/json"
-	"fmt"
-	"math"
+	"crypto/x509"
 	"net/http"
-	"sort"
-	"strings"
 
 	"github.com/pkg/errors"
+	"github.com/smallstep/certificates/authority/provisioner"
 )
 
-// DefaultProvisionersLimit is the default limit for listing provisioners.
-const DefaultProvisionersLimit = 20
-
-// DefaultProvisionersMax is the maximum limit for listing provisioners.
-const DefaultProvisionersMax = 100
-
 // GetEncryptedKey returns the JWE key corresponding to the given kid argument.
 func (a *Authority) GetEncryptedKey(kid string) (string, error) {
-	val, ok := a.encryptedKeyIndex.Load(kid)
+	key, ok := a.provisioners.LoadEncryptedKey(kid)
 	if !ok {
 		return "", &apiError{errors.Errorf("encrypted key with kid %s was not found", kid),
-			http.StatusNotFound, context{}}
-	}
-
-	key, ok := val.(string)
-	if !ok {
-		return "", &apiError{errors.Errorf("stored value is not a string"),
-			http.StatusInternalServerError, context{}}
+			http.StatusNotFound, apiCtx{}}
 	}
 	return key, nil
 }
 
 // GetProvisioners returns a map listing each provisioner and the JWK Key Set
 // with their public keys.
-func (a *Authority) GetProvisioners(cursor string, limit int) ([]*Provisioner, string, error) {
-	provisioners, nextCursor := a.sortedProvisioners.Find(cursor, limit)
+func (a *Authority) GetProvisioners(cursor string, limit int) (provisioner.List, string, error) {
+	provisioners, nextCursor := a.provisioners.Find(cursor, limit)
 	return provisioners, nextCursor, nil
 }
 
-type uidProvisioner struct {
-	provisioner *Provisioner
-	uid         string
-}
-
-func newSortedProvisioners(provisioners []*Provisioner) (provisionerSlice, error) {
-	if len(provisioners) > math.MaxInt32 {
-		return nil, errors.New("too many provisioners")
-	}
-
-	var slice provisionerSlice
-	bi := make([]byte, 4)
-	for i, p := range provisioners {
-		sum, err := provisionerSum(p)
-		if err != nil {
-			return nil, err
-		}
-		// Use the first 4 bytes (32bit) of the sum to insert the order
-		// Using big endian format to get the strings sorted:
-		// 0x00000000, 0x00000001, 0x00000002, ...
-		binary.BigEndian.PutUint32(bi, uint32(i))
-		sum[0], sum[1], sum[2], sum[3] = bi[0], bi[1], bi[2], bi[3]
-		bi[0], bi[1], bi[2], bi[3] = 0, 0, 0, 0
-		slice = append(slice, uidProvisioner{
-			provisioner: p,
-			uid:         hex.EncodeToString(sum),
-		})
-	}
-	sort.Sort(slice)
-	return slice, nil
-}
-
-type provisionerSlice []uidProvisioner
-
-func (p provisionerSlice) Len() int           { return len(p) }
-func (p provisionerSlice) Less(i, j int) bool { return p[i].uid < p[j].uid }
-func (p provisionerSlice) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
-
-func (p provisionerSlice) Find(cursor string, limit int) ([]*Provisioner, string) {
-	switch {
-	case limit <= 0:
-		limit = DefaultProvisionersLimit
-	case limit > DefaultProvisionersMax:
-		limit = DefaultProvisionersMax
-	}
-
-	n := len(p)
-	cursor = fmt.Sprintf("%040s", cursor)
-	i := sort.Search(n, func(i int) bool { return p[i].uid >= cursor })
-
-	var slice []*Provisioner
-	for ; i < n && len(slice) < limit; i++ {
-		slice = append(slice, p[i].provisioner)
-	}
-	if i < n {
-		return slice, strings.TrimLeft(p[i].uid, "0")
+// LoadProvisionerByCertificate returns an interface to the provisioner that
+// provisioned the certificate.
+func (a *Authority) LoadProvisionerByCertificate(crt *x509.Certificate) (provisioner.Interface, error) {
+	p, ok := a.provisioners.LoadByCertificate(crt)
+	if !ok {
+		return nil, &apiError{errors.Errorf("provisioner not found"),
+			http.StatusNotFound, apiCtx{}}
 	}
-	return slice, ""
+	return p, nil
 }
 
-// provisionerSum returns the SHA1 of the json representation of the
-// provisioner. From this we will create the unique and sorted id.
-func provisionerSum(p *Provisioner) ([]byte, error) {
-	b, err := json.Marshal(p.Key)
-	if err != nil {
-		return nil, errors.Wrap(err, "error marshalling provisioner")
+// LoadProvisionerByID returns an interface to the provisioner with the given ID.
+func (a *Authority) LoadProvisionerByID(id string) (provisioner.Interface, error) {
+	p, ok := a.provisioners.Load(id)
+	if !ok {
+		return nil, &apiError{errors.Errorf("provisioner not found"),
+			http.StatusNotFound, apiCtx{}}
 	}
-	sum := sha1.Sum(b)
-	return sum[:], nil
+	return p, nil
 }

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно