im_integration_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. package api
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/ed25519"
  6. "crypto/rand"
  7. "crypto/x509"
  8. "crypto/x509/pkix"
  9. "encoding/base64"
  10. "encoding/json"
  11. "errors"
  12. "io"
  13. "math/big"
  14. "net/http"
  15. "net/http/httptest"
  16. "net/url"
  17. "os"
  18. "strings"
  19. "testing"
  20. "time"
  21. "github.com/go-chi/chi"
  22. "github.com/smallstep/certificates/acme"
  23. "github.com/smallstep/certificates/acme/db/nosql"
  24. "github.com/smallstep/certificates/authority"
  25. "github.com/smallstep/certificates/authority/provisioner"
  26. nosqlDB "github.com/smallstep/nosql"
  27. "go.step.sm/crypto/jose"
  28. )
  29. const (
  30. baseURL = "test.ca.smallstep.com"
  31. linkerPrefix = "acme"
  32. )
  33. func TestIMIntegration(t *testing.T) {
  34. ctx := context.Background()
  35. // mock provisioner and linker
  36. ctx = acme.NewProvisionerContext(ctx, newProvWithOptions(&provisioner.Options{
  37. OIDC: &provisioner.OIDCOptions{
  38. Provider: provisioner.ProviderJSON{
  39. IssuerURL: "",
  40. AuthURL: "",
  41. TokenURL: "",
  42. JWKSURL: "",
  43. UserInfoURL: "",
  44. Algorithms: []string{},
  45. },
  46. Config: provisioner.ConfigJSON{
  47. ClientID: "integration test",
  48. SupportedSigningAlgs: []string{},
  49. SkipClientIDCheck: true,
  50. SkipExpiryCheck: true,
  51. SkipIssuerCheck: true,
  52. InsecureSkipSignatureCheck: true,
  53. Now: time.Now,
  54. },
  55. },
  56. DPOP: &provisioner.DPOPOptions{
  57. ValidationExecPath: "true", // true will always exit with code 0
  58. },
  59. }))
  60. ctx = acme.NewLinkerContext(ctx, acme.NewLinker(baseURL, linkerPrefix))
  61. // create temporary BoltDB file
  62. file, err := os.CreateTemp(os.TempDir(), "integration-db-")
  63. if err != nil {
  64. t.Fatal("opening temporary database file:", err)
  65. }
  66. t.Log("database file name:", file.Name())
  67. dbFn := file.Name()
  68. err = file.Close()
  69. if err != nil {
  70. t.Error("closing database file:", err)
  71. }
  72. // open BoltDB
  73. rawDB, err := nosqlDB.New(nosqlDB.BBoltDriver, dbFn)
  74. if err != nil {
  75. t.Fatal("establishing raw db connection:", err)
  76. }
  77. // create tables
  78. db, err := nosql.New(rawDB)
  79. if err != nil {
  80. t.Fatal("establishing db connection:", err)
  81. }
  82. // make DB available to handlers
  83. ctx = acme.NewDatabaseContext(ctx, db)
  84. // simulate signed payloads by making the signing key available in ctx
  85. jwk, err := jose.GenerateJWK("OKP", "", "EdDSA", "sig", "", 0)
  86. if err != nil {
  87. t.Fatal("generating key:", err)
  88. }
  89. ed25519PrivKey, ok := jwk.Key.(ed25519.PrivateKey)
  90. if !ok {
  91. t.Fatal("failed to generate private key")
  92. }
  93. ed25519PubKey, ok := ed25519PrivKey.Public().(ed25519.PublicKey)
  94. if !ok {
  95. t.Fatal("failed to extract public key")
  96. }
  97. jwk.Key = ed25519PubKey
  98. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  99. // get directory
  100. dir := func(ctx context.Context) (dir Directory) {
  101. req := httptest.NewRequest(http.MethodGet, "/foo/bar", nil)
  102. req = req.WithContext(ctx)
  103. w := httptest.NewRecorder()
  104. GetDirectory(w, req)
  105. res := w.Result()
  106. if res.StatusCode != 200 {
  107. t.Errorf("expected 200, got %d", res.StatusCode)
  108. }
  109. body, err := io.ReadAll(res.Body)
  110. if err != nil {
  111. t.Fatal("failed to read the response body:", err)
  112. }
  113. err = json.Unmarshal(bytes.TrimSpace(body), &dir)
  114. if err != nil {
  115. t.Fatal("unmarshal response body:", err)
  116. }
  117. return
  118. }(ctx)
  119. t.Log("directory:", dir)
  120. // get nonce
  121. nonce := func(ctx context.Context) (nonce string) {
  122. req := httptest.NewRequest(http.MethodGet, dir.NewNonce, nil).WithContext(ctx)
  123. w := httptest.NewRecorder()
  124. addNonce(GetNonce)(w, req)
  125. res := w.Result()
  126. if res.StatusCode != http.StatusNoContent {
  127. t.Errorf("expected %d, got %d", http.StatusNoContent, res.StatusCode)
  128. }
  129. nonce = res.Header["Replay-Nonce"][0]
  130. return
  131. }(ctx)
  132. t.Log("nonce:", nonce)
  133. // create new account
  134. acc := func(ctx context.Context) (acc *acme.Account) {
  135. // create payload
  136. nar := &NewAccountRequest{
  137. Contact: []string{"foo", "bar"},
  138. }
  139. rawNar, err := json.Marshal(nar)
  140. if err != nil {
  141. t.Fatal("marshal nar:", err)
  142. }
  143. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: rawNar})
  144. // create account
  145. req := httptest.NewRequest(http.MethodGet, dir.NewAccount, nil).WithContext(ctx)
  146. w := httptest.NewRecorder()
  147. NewAccount(w, req)
  148. res := w.Result()
  149. if res.StatusCode != http.StatusCreated {
  150. t.Errorf("expected %d, got %d", http.StatusCreated, res.StatusCode)
  151. }
  152. body, err := io.ReadAll(res.Body)
  153. res.Body.Close()
  154. if err != nil {
  155. t.Fatal("read account payload:", err)
  156. }
  157. err = json.Unmarshal(bytes.TrimSpace(body), &acc)
  158. if err != nil {
  159. t.Fatal("unmarshal account:", err)
  160. }
  161. locationParts := strings.Split(res.Header["Location"][0], "/")
  162. acc, err = db.GetAccount(ctx, locationParts[len(locationParts)-1])
  163. if err != nil {
  164. t.Fatal("get account from DB:", err)
  165. }
  166. return
  167. }(ctx)
  168. ctx = context.WithValue(ctx, accContextKey, acc)
  169. t.Log("account ID:", acc.ID)
  170. // new order
  171. order := func(ctx context.Context) (order *acme.Order) {
  172. mockMustAuthority(t, &mockCA{})
  173. nor := &NewOrderRequest{
  174. Identifiers: []acme.Identifier{
  175. {
  176. Type: "wireapp-id",
  177. Value: `{"name": "Smith, Alice M (QA)", "domain": "example.com", "client-id": "im:wireapp=75d73550-16e0-4027-abfd-0137e32180cc/ed416ce8ecdd9fad@example.com", "handle": "im:wireapp=alice.smith.qa@example.com"}`,
  178. },
  179. },
  180. }
  181. b, err := json.Marshal(nor)
  182. if err != nil {
  183. t.Fatal("marshal new order request: ", err)
  184. }
  185. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  186. req := httptest.NewRequest("POST", "https://random.local/", nil)
  187. req = req.WithContext(ctx)
  188. w := httptest.NewRecorder()
  189. NewOrder(w, req)
  190. res := w.Result()
  191. if res.StatusCode != http.StatusCreated {
  192. t.Errorf("expected %d, got %d", http.StatusCreated, res.StatusCode)
  193. }
  194. body, err := io.ReadAll(res.Body)
  195. res.Body.Close()
  196. if err != nil {
  197. t.Fatal("read account payload:", err)
  198. }
  199. err = json.Unmarshal(bytes.TrimSpace(body), &order)
  200. if err != nil {
  201. t.Fatal("unmarshal order:", err)
  202. }
  203. order, err = db.GetOrder(ctx, order.ID)
  204. if err != nil {
  205. t.Fatal("get order from DB:", err)
  206. }
  207. return
  208. }(ctx)
  209. t.Log("authzs IDs:", order.AuthorizationIDs)
  210. // get authorization
  211. getAuthz := func(ctx context.Context, authzID string) (az *acme.Authorization) {
  212. chiCtx := chi.NewRouteContext()
  213. chiCtx.URLParams.Add("authzID", authzID)
  214. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  215. req := httptest.NewRequest(http.MethodGet, "https://random.local/", nil).WithContext(ctx)
  216. w := httptest.NewRecorder()
  217. GetAuthorization(w, req)
  218. res := w.Result()
  219. if res.StatusCode != http.StatusOK {
  220. t.Errorf("expected %d, got %d", http.StatusOK, res.StatusCode)
  221. }
  222. body, err := io.ReadAll(res.Body)
  223. res.Body.Close()
  224. if err != nil {
  225. t.Fatal("read account payload:", err)
  226. }
  227. err = json.Unmarshal(bytes.TrimSpace(body), &az)
  228. if err != nil {
  229. t.Fatal("unmarshal account:", err)
  230. }
  231. az, err = db.GetAuthorization(ctx, authzID)
  232. if err != nil {
  233. t.Fatal("update authorization from DB")
  234. }
  235. return
  236. }
  237. var azs []*acme.Authorization
  238. for _, azID := range order.AuthorizationIDs {
  239. az := getAuthz(ctx, azID)
  240. azs = append(azs, az)
  241. for _, challenge := range az.Challenges {
  242. chiCtx := chi.NewRouteContext()
  243. chiCtx.URLParams.Add("chID", challenge.ID)
  244. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  245. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: nil})
  246. req := httptest.NewRequest(http.MethodGet, "https://random.local/", nil).WithContext(ctx)
  247. w := httptest.NewRecorder()
  248. GetChallenge(w, req)
  249. res := w.Result()
  250. if res.StatusCode != http.StatusOK {
  251. t.Errorf("expected %d, got %d", http.StatusOK, res.StatusCode)
  252. }
  253. body, err := io.ReadAll(res.Body)
  254. res.Body.Close()
  255. if err != nil {
  256. t.Fatal("read challenge payload:", err)
  257. }
  258. err = json.Unmarshal(bytes.TrimSpace(body), &challenge)
  259. if err != nil {
  260. t.Fatal("unmarshal challenge:", err)
  261. }
  262. t.Log("challenge:", challenge.ID, challenge.Status)
  263. }
  264. }
  265. // get/validate challenge simulation
  266. updateAz := func(ctx context.Context, az *acme.Authorization) (updatedAz *acme.Authorization) {
  267. now := clock.Now().Format(time.RFC3339)
  268. for _, challenge := range az.Challenges {
  269. challenge.Status = acme.StatusValid
  270. challenge.ValidatedAt = now
  271. err := db.UpdateChallenge(ctx, challenge)
  272. if err != nil {
  273. t.Error("updating challenge", challenge.ID, ":", err)
  274. }
  275. }
  276. updatedAz, err = db.GetAuthorization(ctx, az.ID)
  277. if err != nil {
  278. t.Fatal("update authorization from DB", err)
  279. }
  280. return
  281. }
  282. for _, az := range azs {
  283. updatedAz := updateAz(ctx, az)
  284. for _, challenge := range updatedAz.Challenges {
  285. t.Log("updated challenge:", challenge.ID, challenge.Status)
  286. }
  287. }
  288. // get order
  289. updatedOrder := func(ctx context.Context) (updatedOrder *acme.Order) {
  290. chiCtx := chi.NewRouteContext()
  291. chiCtx.URLParams.Add("ordID", order.ID)
  292. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  293. req := httptest.NewRequest(http.MethodGet, "https://random.local/", nil).WithContext(ctx)
  294. w := httptest.NewRecorder()
  295. GetOrder(w, req)
  296. res := w.Result()
  297. if res.StatusCode != http.StatusOK {
  298. t.Errorf("expected %d, got %d", http.StatusOK, res.StatusCode)
  299. }
  300. body, err := io.ReadAll(res.Body)
  301. res.Body.Close()
  302. if err != nil {
  303. t.Fatal("read account payload:", err)
  304. }
  305. err = json.Unmarshal(bytes.TrimSpace(body), &updatedOrder)
  306. if err != nil {
  307. t.Fatal("unmarshal order:", err)
  308. }
  309. if updatedOrder.Status != acme.StatusReady {
  310. t.Errorf("expected %s, got %s", acme.StatusReady, updatedOrder.Status)
  311. }
  312. return
  313. }(ctx)
  314. t.Log("updated order status:", updatedOrder.Status)
  315. // finalise order
  316. finalizedOrder := func(ctx context.Context) (finalizedOrder *acme.Order) {
  317. mockMustAuthority(t, &mockCASigner{
  318. signer: func(*x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error) {
  319. return []*x509.Certificate{
  320. {SerialNumber: big.NewInt(2)},
  321. }, nil
  322. },
  323. })
  324. qUserID, err := url.Parse("im:wireapp=75d73550-16e0-4027-abfd-0137e32180cc/ed416ce8ecdd9fad@example.com")
  325. if err != nil {
  326. t.Fatal("parse user ID URI", err)
  327. }
  328. _ = qUserID
  329. qUserName, err := url.Parse("im:wireapp=alice.smith.qa@example.com")
  330. if err != nil {
  331. t.Fatal("parse user name URI", err)
  332. }
  333. _ = qUserName
  334. _, priv, err := ed25519.GenerateKey(rand.Reader)
  335. if err != nil {
  336. t.Fatal("generate key:", err)
  337. }
  338. csrTemplate := &x509.CertificateRequest{
  339. Subject: pkix.Name{
  340. Organization: []string{"example.com"},
  341. CommonName: "Smith, Alice M (QA)",
  342. },
  343. URIs: []*url.URL{
  344. qUserName,
  345. qUserID,
  346. },
  347. SignatureAlgorithm: x509.PureEd25519,
  348. }
  349. csr, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, priv)
  350. if err != nil {
  351. t.Fatal("create CSR from template:", err)
  352. }
  353. fr := FinalizeRequest{CSR: base64.RawURLEncoding.EncodeToString(csr)}
  354. frRaw, err := json.Marshal(fr)
  355. if err != nil {
  356. t.Fatal("encode finalize request:", err)
  357. }
  358. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: frRaw})
  359. chiCtx := chi.NewRouteContext()
  360. chiCtx.URLParams.Add("ordID", order.ID)
  361. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  362. req := httptest.NewRequest(http.MethodGet, "https://random.local/", nil).WithContext(ctx)
  363. w := httptest.NewRecorder()
  364. FinalizeOrder(w, req)
  365. res := w.Result()
  366. if res.StatusCode != http.StatusOK {
  367. t.Errorf("expected %d, got %d", http.StatusOK, res.StatusCode)
  368. }
  369. body, err := io.ReadAll(res.Body)
  370. res.Body.Close()
  371. if err != nil {
  372. t.Fatal("read account payload:", err)
  373. }
  374. err = json.Unmarshal(bytes.TrimSpace(body), &finalizedOrder)
  375. if err != nil {
  376. t.Fatal("unmarshal order:", err)
  377. }
  378. if finalizedOrder.Status != acme.StatusValid {
  379. t.Errorf("expected %s, got %s", acme.StatusValid, finalizedOrder.Status)
  380. }
  381. finalizedOrder, err = db.GetOrder(ctx, order.ID)
  382. if err != nil {
  383. t.Fatal("get order from DB:", err)
  384. }
  385. return
  386. }(ctx)
  387. t.Log("finalized order status:", finalizedOrder.Status)
  388. }
  389. type mockCASigner struct {
  390. signer func(*x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error)
  391. }
  392. func (m *mockCASigner) Sign(cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  393. if m.signer == nil {
  394. return nil, errors.New("unimplemented")
  395. }
  396. return m.signer(cr, opts, signOpts...)
  397. }
  398. func (m *mockCASigner) AreSANsAllowed(ctx context.Context, sans []string) error {
  399. return nil
  400. }
  401. func (m *mockCASigner) IsRevoked(sn string) (bool, error) {
  402. return false, nil
  403. }
  404. func (m *mockCASigner) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  405. return nil
  406. }
  407. func (m *mockCASigner) LoadProvisionerByName(string) (provisioner.Interface, error) {
  408. return nil, nil
  409. }