wire_integration_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/ed25519"
  6. "crypto/rand"
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/asn1"
  10. "encoding/base64"
  11. "encoding/json"
  12. "errors"
  13. "io"
  14. "math/big"
  15. "net/http"
  16. "net/http/httptest"
  17. "net/url"
  18. "os"
  19. "strings"
  20. "testing"
  21. "time"
  22. "github.com/go-chi/chi/v5"
  23. "github.com/smallstep/certificates/acme"
  24. "github.com/smallstep/certificates/acme/db/nosql"
  25. "github.com/smallstep/certificates/authority"
  26. "github.com/smallstep/certificates/authority/provisioner"
  27. "github.com/smallstep/certificates/authority/provisioner/wire"
  28. nosqlDB "github.com/smallstep/nosql"
  29. "github.com/stretchr/testify/require"
  30. "go.step.sm/crypto/jose"
  31. )
  32. const (
  33. baseURL = "test.ca.smallstep.com"
  34. linkerPrefix = "acme"
  35. )
  36. func newWireProvisionerWithOptions(t *testing.T, options *provisioner.Options) *provisioner.ACME {
  37. p := newProvWithOptions(options)
  38. a, ok := p.(*provisioner.ACME)
  39. if !ok {
  40. t.Fatal("not a valid ACME provisioner")
  41. }
  42. a.Challenges = []provisioner.ACMEChallenge{
  43. provisioner.WIREOIDC_01,
  44. provisioner.WIREDPOP_01,
  45. }
  46. return a
  47. }
  48. func TestWireIntegration(t *testing.T) {
  49. fakeKey := `-----BEGIN PUBLIC KEY-----
  50. MCowBQYDK2VwAyEA5c+4NKZSNQcR1T8qN6SjwgdPZQ0Ge12Ylx/YeGAJ35k=
  51. -----END PUBLIC KEY-----`
  52. prov := newWireProvisionerWithOptions(t, &provisioner.Options{
  53. Wire: &wire.Options{
  54. OIDC: &wire.OIDCOptions{
  55. Provider: &wire.Provider{
  56. IssuerURL: "https://issuer.example.com",
  57. AuthURL: "",
  58. TokenURL: "",
  59. JWKSURL: "",
  60. UserInfoURL: "",
  61. Algorithms: []string{},
  62. },
  63. Config: &wire.Config{
  64. ClientID: "integration test",
  65. SignatureAlgorithms: []string{},
  66. SkipClientIDCheck: true,
  67. SkipExpiryCheck: true,
  68. SkipIssuerCheck: true,
  69. InsecureSkipSignatureCheck: true,
  70. Now: time.Now,
  71. },
  72. },
  73. DPOP: &wire.DPOPOptions{
  74. SigningKey: []byte(fakeKey),
  75. },
  76. },
  77. })
  78. // mock provisioner and linker
  79. ctx := context.Background()
  80. ctx = acme.NewProvisionerContext(ctx, prov)
  81. ctx = acme.NewLinkerContext(ctx, acme.NewLinker(baseURL, linkerPrefix))
  82. // create temporary BoltDB file
  83. file, err := os.CreateTemp(os.TempDir(), "integration-db-")
  84. require.NoError(t, err)
  85. t.Log("database file name:", file.Name())
  86. dbFn := file.Name()
  87. err = file.Close()
  88. require.NoError(t, err)
  89. // open BoltDB
  90. rawDB, err := nosqlDB.New(nosqlDB.BBoltDriver, dbFn)
  91. require.NoError(t, err)
  92. // create tables
  93. db, err := nosql.New(rawDB)
  94. require.NoError(t, err)
  95. // make DB available to handlers
  96. ctx = acme.NewDatabaseContext(ctx, db)
  97. // simulate signed payloads by making the signing key available in ctx
  98. jwk, err := jose.GenerateJWK("OKP", "", "EdDSA", "sig", "", 0)
  99. require.NoError(t, err)
  100. ed25519PrivKey, ok := jwk.Key.(ed25519.PrivateKey)
  101. require.True(t, ok)
  102. ed25519PubKey, ok := ed25519PrivKey.Public().(ed25519.PublicKey)
  103. require.True(t, ok)
  104. jwk.Key = ed25519PubKey
  105. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  106. // get directory
  107. dir := func(ctx context.Context) (dir Directory) {
  108. req := httptest.NewRequest(http.MethodGet, "/foo/bar", http.NoBody)
  109. req = req.WithContext(ctx)
  110. w := httptest.NewRecorder()
  111. GetDirectory(w, req)
  112. res := w.Result()
  113. require.Equal(t, http.StatusOK, res.StatusCode)
  114. body, err := io.ReadAll(res.Body)
  115. require.NoError(t, err)
  116. err = json.Unmarshal(bytes.TrimSpace(body), &dir)
  117. require.NoError(t, err)
  118. return
  119. }(ctx)
  120. t.Log("directory:", dir)
  121. // get nonce
  122. nonce := func(ctx context.Context) (nonce string) {
  123. req := httptest.NewRequest(http.MethodGet, dir.NewNonce, http.NoBody).WithContext(ctx)
  124. w := httptest.NewRecorder()
  125. addNonce(GetNonce)(w, req)
  126. res := w.Result()
  127. require.Equal(t, http.StatusNoContent, res.StatusCode)
  128. nonce = res.Header["Replay-Nonce"][0]
  129. return
  130. }(ctx)
  131. t.Log("nonce:", nonce)
  132. // create new account
  133. acc := func(ctx context.Context) (acc *acme.Account) {
  134. // create payload
  135. nar := &NewAccountRequest{
  136. Contact: []string{"foo", "bar"},
  137. }
  138. rawNar, err := json.Marshal(nar)
  139. require.NoError(t, err)
  140. // create account
  141. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: rawNar})
  142. req := httptest.NewRequest(http.MethodGet, dir.NewAccount, http.NoBody).WithContext(ctx)
  143. w := httptest.NewRecorder()
  144. NewAccount(w, req)
  145. res := w.Result()
  146. require.Equal(t, http.StatusCreated, res.StatusCode)
  147. body, err := io.ReadAll(res.Body)
  148. defer res.Body.Close()
  149. require.NoError(t, err)
  150. err = json.Unmarshal(bytes.TrimSpace(body), &acc)
  151. require.NoError(t, err)
  152. locationParts := strings.Split(res.Header["Location"][0], "/")
  153. acc, err = db.GetAccount(ctx, locationParts[len(locationParts)-1])
  154. require.NoError(t, err)
  155. return
  156. }(ctx)
  157. ctx = context.WithValue(ctx, accContextKey, acc)
  158. t.Log("account ID:", acc.ID)
  159. // new order
  160. order := func(ctx context.Context) (order *acme.Order) {
  161. mockMustAuthority(t, &mockCA{})
  162. nor := &NewOrderRequest{
  163. Identifiers: []acme.Identifier{
  164. {
  165. Type: "wireapp-id",
  166. Value: `{"name": "Smith, Alice M (QA)", "domain": "example.com", "client-id": "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com", "handle": "wireapp://%40alice.smith.qa@example.com"}`,
  167. },
  168. },
  169. }
  170. b, err := json.Marshal(nor)
  171. require.NoError(t, err)
  172. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  173. req := httptest.NewRequest("POST", "https://random.local/", http.NoBody)
  174. req = req.WithContext(ctx)
  175. w := httptest.NewRecorder()
  176. NewOrder(w, req)
  177. res := w.Result()
  178. require.Equal(t, http.StatusCreated, res.StatusCode)
  179. body, err := io.ReadAll(res.Body)
  180. defer res.Body.Close()
  181. require.NoError(t, err)
  182. err = json.Unmarshal(bytes.TrimSpace(body), &order)
  183. require.NoError(t, err)
  184. order, err = db.GetOrder(ctx, order.ID)
  185. require.NoError(t, err)
  186. return
  187. }(ctx)
  188. t.Log("authzs IDs:", order.AuthorizationIDs)
  189. // get authorization
  190. getAuthz := func(ctx context.Context, authzID string) (az *acme.Authorization) {
  191. chiCtx := chi.NewRouteContext()
  192. chiCtx.URLParams.Add("authzID", authzID)
  193. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  194. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  195. w := httptest.NewRecorder()
  196. GetAuthorization(w, req)
  197. res := w.Result()
  198. require.Equal(t, http.StatusOK, res.StatusCode)
  199. body, err := io.ReadAll(res.Body)
  200. defer res.Body.Close()
  201. require.NoError(t, err)
  202. err = json.Unmarshal(bytes.TrimSpace(body), &az)
  203. require.NoError(t, err)
  204. az, err = db.GetAuthorization(ctx, authzID)
  205. require.NoError(t, err)
  206. return
  207. }
  208. var azs []*acme.Authorization
  209. for _, azID := range order.AuthorizationIDs {
  210. az := getAuthz(ctx, azID)
  211. azs = append(azs, az)
  212. for _, challenge := range az.Challenges {
  213. chiCtx := chi.NewRouteContext()
  214. chiCtx.URLParams.Add("chID", challenge.ID)
  215. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  216. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: nil})
  217. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  218. w := httptest.NewRecorder()
  219. GetChallenge(w, req)
  220. res := w.Result()
  221. require.Equal(t, http.StatusOK, res.StatusCode)
  222. body, err := io.ReadAll(res.Body)
  223. defer res.Body.Close() //nolint:gocritic // close the body
  224. require.NoError(t, err)
  225. err = json.Unmarshal(bytes.TrimSpace(body), &challenge)
  226. require.NoError(t, err)
  227. t.Log("challenge:", challenge.ID, challenge.Status)
  228. }
  229. }
  230. // get/validate challenge simulation
  231. updateAz := func(ctx context.Context, az *acme.Authorization) (updatedAz *acme.Authorization) {
  232. now := clock.Now().Format(time.RFC3339)
  233. for _, challenge := range az.Challenges {
  234. challenge.Status = acme.StatusValid
  235. challenge.ValidatedAt = now
  236. err := db.UpdateChallenge(ctx, challenge)
  237. if err != nil {
  238. t.Error("updating challenge", challenge.ID, ":", err)
  239. }
  240. }
  241. updatedAz, err = db.GetAuthorization(ctx, az.ID)
  242. require.NoError(t, err)
  243. return
  244. }
  245. for _, az := range azs {
  246. updatedAz := updateAz(ctx, az)
  247. for _, challenge := range updatedAz.Challenges {
  248. t.Log("updated challenge:", challenge.ID, challenge.Status)
  249. }
  250. }
  251. // get order
  252. updatedOrder := func(ctx context.Context) (updatedOrder *acme.Order) {
  253. chiCtx := chi.NewRouteContext()
  254. chiCtx.URLParams.Add("ordID", order.ID)
  255. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  256. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  257. w := httptest.NewRecorder()
  258. GetOrder(w, req)
  259. res := w.Result()
  260. require.Equal(t, http.StatusOK, res.StatusCode)
  261. body, err := io.ReadAll(res.Body)
  262. defer res.Body.Close()
  263. require.NoError(t, err)
  264. err = json.Unmarshal(bytes.TrimSpace(body), &updatedOrder)
  265. require.NoError(t, err)
  266. require.Equal(t, acme.StatusReady, updatedOrder.Status)
  267. return
  268. }(ctx)
  269. t.Log("updated order status:", updatedOrder.Status)
  270. // finalize order
  271. finalizedOrder := func(ctx context.Context) (finalizedOrder *acme.Order) {
  272. mockMustAuthority(t, &mockCASigner{
  273. signer: func(*x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error) {
  274. return []*x509.Certificate{
  275. {SerialNumber: big.NewInt(2)},
  276. }, nil
  277. },
  278. })
  279. qUserID, err := url.Parse("wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com")
  280. require.NoError(t, err)
  281. qUserName, err := url.Parse("wireapp://%40alice.smith.qa@example.com")
  282. require.NoError(t, err)
  283. _, priv, err := ed25519.GenerateKey(rand.Reader)
  284. require.NoError(t, err)
  285. csrTemplate := &x509.CertificateRequest{
  286. Subject: pkix.Name{
  287. Organization: []string{"example.com"},
  288. ExtraNames: []pkix.AttributeTypeAndValue{
  289. {
  290. Type: asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 3, 1, 241},
  291. Value: "Smith, Alice M (QA)",
  292. },
  293. },
  294. },
  295. URIs: []*url.URL{
  296. qUserName,
  297. qUserID,
  298. },
  299. SignatureAlgorithm: x509.PureEd25519,
  300. }
  301. csr, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, priv)
  302. require.NoError(t, err)
  303. fr := FinalizeRequest{CSR: base64.RawURLEncoding.EncodeToString(csr)}
  304. frRaw, err := json.Marshal(fr)
  305. require.NoError(t, err)
  306. // TODO(hs): move these to a more appropriate place and/or provide more realistic value
  307. err = db.CreateDpopToken(ctx, order.ID, &acme.WireDpopToken{Challenge: "challenge", Handle: "handle", Team: "wire"})
  308. require.NoError(t, err)
  309. err = db.CreateOidcToken(ctx, order.ID, map[string]any{"fake-oidc": "oidc-value"})
  310. require.NoError(t, err)
  311. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: frRaw})
  312. chiCtx := chi.NewRouteContext()
  313. chiCtx.URLParams.Add("ordID", order.ID)
  314. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  315. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  316. w := httptest.NewRecorder()
  317. FinalizeOrder(w, req)
  318. res := w.Result()
  319. require.Equal(t, http.StatusOK, res.StatusCode)
  320. body, err := io.ReadAll(res.Body)
  321. defer res.Body.Close()
  322. require.NoError(t, err)
  323. err = json.Unmarshal(bytes.TrimSpace(body), &finalizedOrder)
  324. require.NoError(t, err)
  325. require.Equal(t, acme.StatusValid, finalizedOrder.Status)
  326. finalizedOrder, err = db.GetOrder(ctx, order.ID)
  327. require.NoError(t, err)
  328. return
  329. }(ctx)
  330. t.Log("finalized order status:", finalizedOrder.Status)
  331. }
  332. type mockCASigner struct {
  333. signer func(*x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error)
  334. }
  335. func (m *mockCASigner) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  336. if m.signer == nil {
  337. return nil, errors.New("unimplemented")
  338. }
  339. return m.signer(cr, opts, signOpts...)
  340. }
  341. func (m *mockCASigner) AreSANsAllowed(ctx context.Context, sans []string) error {
  342. return nil
  343. }
  344. func (m *mockCASigner) IsRevoked(sn string) (bool, error) {
  345. return false, nil
  346. }
  347. func (m *mockCASigner) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  348. return nil
  349. }
  350. func (m *mockCASigner) LoadProvisionerByName(string) (provisioner.Interface, error) {
  351. return nil, nil
  352. }