wire_integration_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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. "encoding/pem"
  13. "errors"
  14. "io"
  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/config"
  27. "github.com/smallstep/certificates/authority/provisioner"
  28. "github.com/smallstep/certificates/authority/provisioner/wire"
  29. nosqlDB "github.com/smallstep/nosql"
  30. "github.com/stretchr/testify/assert"
  31. "github.com/stretchr/testify/require"
  32. "go.step.sm/crypto/jose"
  33. "go.step.sm/crypto/minica"
  34. "go.step.sm/crypto/pemutil"
  35. "go.step.sm/crypto/x509util"
  36. )
  37. const (
  38. baseURL = "test.ca.smallstep.com"
  39. linkerPrefix = "acme"
  40. )
  41. func newWireProvisionerWithOptions(t *testing.T, options *provisioner.Options) *provisioner.ACME {
  42. t.Helper()
  43. prov := &provisioner.ACME{
  44. Type: "ACME",
  45. Name: "test@acme-<test>provisioner.com",
  46. Options: options,
  47. Challenges: []provisioner.ACMEChallenge{
  48. provisioner.WIREOIDC_01,
  49. provisioner.WIREDPOP_01,
  50. },
  51. }
  52. err := prov.Init(provisioner.Config{
  53. Claims: config.GlobalProvisionerClaims,
  54. })
  55. require.NoError(t, err)
  56. return prov
  57. }
  58. func mutateStoredWireOrderDeviceID(t *testing.T, rawDB nosqlDB.DB, orderID, newValue string) {
  59. var wireIntegrationOrderTable = []byte("acme_orders")
  60. oldValue, err := rawDB.Get(wireIntegrationOrderTable, []byte(orderID))
  61. require.NoError(t, err)
  62. var stored map[string]json.RawMessage
  63. err = json.Unmarshal(oldValue, &stored)
  64. require.NoError(t, err)
  65. var identifiers []acme.Identifier
  66. err = json.Unmarshal(stored["identifiers"], &identifiers)
  67. require.NoError(t, err)
  68. replaced := false
  69. for i, identifier := range identifiers {
  70. if identifier.Type == acme.WireDevice {
  71. identifiers[i].Value = newValue
  72. replaced = true
  73. break
  74. }
  75. }
  76. require.True(t, replaced)
  77. stored["identifiers"], err = json.Marshal(identifiers)
  78. require.NoError(t, err)
  79. newStoredValue, err := json.Marshal(stored)
  80. require.NoError(t, err)
  81. _, swapped, err := rawDB.CmpAndSwap(wireIntegrationOrderTable, []byte(orderID), oldValue, newStoredValue)
  82. require.NoError(t, err)
  83. require.True(t, swapped)
  84. }
  85. // TODO(hs): replace with test CA server + acmez based test client for
  86. // more realistic integration test?
  87. func TestWireIntegration(t *testing.T) {
  88. runWireIntegration(t, nil, nil)
  89. }
  90. func TestWireIntegration_DBMutation_GetOrderWireDeviceMismatch(t *testing.T) {
  91. runWireIntegration(t, func(t *testing.T, rawDB nosqlDB.DB, order *acme.Order) {
  92. const substitutedWireDevice = `{
  93. "name": "Smith, Alice M (QA)",
  94. "domain": "example.com",
  95. "client-id": "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!deadbeefdeadbeef@example.com",
  96. "handle": "wireapp://%40alice.smith.qa@example.com"
  97. }`
  98. mutateStoredWireOrderDeviceID(t, rawDB, order.ID, substitutedWireDevice)
  99. }, func(t *testing.T, res *http.Response, body []byte) {
  100. require.Equal(t, http.StatusBadRequest, res.StatusCode)
  101. var acmeErr acme.Error
  102. err := json.Unmarshal(bytes.TrimSpace(body), &acmeErr)
  103. require.NoError(t, err)
  104. require.Equal(t, acme.NewError(acme.ErrorBadCSRType, "").Type, acmeErr.Type)
  105. require.Equal(t, "The CSR is unacceptable", acmeErr.Detail)
  106. })
  107. }
  108. func runWireIntegration(
  109. t *testing.T,
  110. beforeFinalize func(t *testing.T, rawDB nosqlDB.DB, order *acme.Order),
  111. checkFinalizeResponse func(t *testing.T, res *http.Response, body []byte),
  112. ) {
  113. t.Helper()
  114. accessTokenSignerJWK, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  115. require.NoError(t, err)
  116. accessTokenSignerPEMBlock, err := pemutil.Serialize(accessTokenSignerJWK.Public().Key)
  117. require.NoError(t, err)
  118. accessTokenSignerPEMBytes := pem.EncodeToMemory(accessTokenSignerPEMBlock)
  119. accessTokenSigner, err := jose.NewSigner(jose.SigningKey{
  120. Algorithm: jose.SignatureAlgorithm(accessTokenSignerJWK.Algorithm),
  121. Key: accessTokenSignerJWK,
  122. }, new(jose.SignerOptions))
  123. require.NoError(t, err)
  124. oidcTokenSignerJWK, err := jose.GenerateJWK("EC", "P-256", "ES256", "sig", "", 0)
  125. require.NoError(t, err)
  126. oidcTokenSigner, err := jose.NewSigner(jose.SigningKey{
  127. Algorithm: jose.SignatureAlgorithm(oidcTokenSignerJWK.Algorithm),
  128. Key: oidcTokenSignerJWK,
  129. }, new(jose.SignerOptions))
  130. require.NoError(t, err)
  131. prov := newWireProvisionerWithOptions(t, &provisioner.Options{
  132. X509: &provisioner.X509Options{
  133. Template: `{
  134. "subject": {
  135. "organization": "WireTest",
  136. "commonName": {{ toJson .Oidc.name }}
  137. },
  138. "uris": [{{ toJson .Oidc.preferred_username }}, {{ toJson .Dpop.sub }}],
  139. "keyUsage": ["digitalSignature"],
  140. "extKeyUsage": ["clientAuth"]
  141. }`,
  142. },
  143. Wire: &wire.Options{
  144. OIDC: &wire.OIDCOptions{
  145. Provider: &wire.Provider{
  146. IssuerURL: "https://issuer.example.com",
  147. AuthURL: "",
  148. TokenURL: "",
  149. JWKSURL: "",
  150. UserInfoURL: "",
  151. Algorithms: []string{"ES256"},
  152. },
  153. Config: &wire.Config{
  154. ClientID: "integration test",
  155. SignatureAlgorithms: []string{"ES256"},
  156. SkipClientIDCheck: true,
  157. SkipExpiryCheck: true,
  158. SkipIssuerCheck: true,
  159. InsecureSkipSignatureCheck: true, // NOTE: this skips actual token verification
  160. Now: time.Now,
  161. },
  162. TransformTemplate: "",
  163. },
  164. DPOP: &wire.DPOPOptions{
  165. SigningKey: accessTokenSignerPEMBytes,
  166. },
  167. },
  168. })
  169. // mock provisioner and linker
  170. ctx := context.Background()
  171. ctx = acme.NewProvisionerContext(ctx, prov)
  172. ctx = acme.NewLinkerContext(ctx, acme.NewLinker(baseURL, linkerPrefix))
  173. // create temporary BoltDB file
  174. file, err := os.CreateTemp(os.TempDir(), "integration-db-")
  175. require.NoError(t, err)
  176. t.Log("database file name:", file.Name())
  177. dbFn := file.Name()
  178. err = file.Close()
  179. require.NoError(t, err)
  180. // open BoltDB
  181. rawDB, err := nosqlDB.New(nosqlDB.BBoltDriver, dbFn)
  182. require.NoError(t, err)
  183. // create tables
  184. db, err := nosql.New(rawDB)
  185. require.NoError(t, err)
  186. // make DB available to handlers
  187. ctx = acme.NewDatabaseContext(ctx, db)
  188. // simulate signed payloads by making the signing key available in ctx
  189. jwk, err := jose.GenerateJWK("OKP", "", "EdDSA", "sig", "", 0)
  190. require.NoError(t, err)
  191. ed25519PrivKey, ok := jwk.Key.(ed25519.PrivateKey)
  192. require.True(t, ok)
  193. dpopSigner, err := jose.NewSigner(jose.SigningKey{
  194. Algorithm: jose.SignatureAlgorithm(jwk.Algorithm),
  195. Key: jwk,
  196. }, new(jose.SignerOptions))
  197. require.NoError(t, err)
  198. ed25519PubKey, ok := ed25519PrivKey.Public().(ed25519.PublicKey)
  199. require.True(t, ok)
  200. jwk.Key = ed25519PubKey
  201. ctx = context.WithValue(ctx, jwkContextKey, jwk)
  202. // get directory
  203. dir := func(ctx context.Context) (dir Directory) {
  204. req := httptest.NewRequest(http.MethodGet, "/foo/bar", http.NoBody)
  205. req = req.WithContext(ctx)
  206. w := httptest.NewRecorder()
  207. GetDirectory(w, req)
  208. res := w.Result()
  209. require.Equal(t, http.StatusOK, res.StatusCode)
  210. body, err := io.ReadAll(res.Body)
  211. require.NoError(t, err)
  212. err = json.Unmarshal(bytes.TrimSpace(body), &dir)
  213. require.NoError(t, err)
  214. return
  215. }(ctx)
  216. t.Log("directory:", dir)
  217. // get nonce
  218. nonce := func(ctx context.Context) (nonce string) {
  219. req := httptest.NewRequest(http.MethodGet, dir.NewNonce, http.NoBody).WithContext(ctx)
  220. w := httptest.NewRecorder()
  221. addNonce(GetNonce)(w, req)
  222. res := w.Result()
  223. require.Equal(t, http.StatusNoContent, res.StatusCode)
  224. nonce = res.Header["Replay-Nonce"][0]
  225. return
  226. }(ctx)
  227. t.Log("nonce:", nonce)
  228. // create new account
  229. acc := func(ctx context.Context) (acc *acme.Account) {
  230. // create payload
  231. nar := &NewAccountRequest{
  232. Contact: []string{"foo", "bar"},
  233. }
  234. rawNar, err := json.Marshal(nar)
  235. require.NoError(t, err)
  236. // create account
  237. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: rawNar})
  238. req := httptest.NewRequest(http.MethodGet, dir.NewAccount, http.NoBody).WithContext(ctx)
  239. w := httptest.NewRecorder()
  240. NewAccount(w, req)
  241. res := w.Result()
  242. require.Equal(t, http.StatusCreated, res.StatusCode)
  243. body, err := io.ReadAll(res.Body)
  244. defer res.Body.Close()
  245. require.NoError(t, err)
  246. err = json.Unmarshal(bytes.TrimSpace(body), &acc)
  247. require.NoError(t, err)
  248. locationParts := strings.Split(res.Header["Location"][0], "/")
  249. acc, err = db.GetAccount(ctx, locationParts[len(locationParts)-1])
  250. require.NoError(t, err)
  251. return
  252. }(ctx)
  253. ctx = context.WithValue(ctx, accContextKey, acc)
  254. t.Log("account ID:", acc.ID)
  255. // new order
  256. order := func(ctx context.Context) (order *acme.Order) {
  257. mockMustAuthority(t, &mockCA{})
  258. nor := &NewOrderRequest{
  259. Identifiers: []acme.Identifier{
  260. {
  261. Type: "wireapp-user",
  262. Value: `{"name": "Smith, Alice M (QA)", "domain": "example.com", "handle": "wireapp://%40alice.smith.qa@example.com"}`,
  263. },
  264. {
  265. Type: "wireapp-device",
  266. Value: `{"name": "Smith, Alice M (QA)", "domain": "example.com", "client-id": "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com", "handle": "wireapp://%40alice.smith.qa@example.com"}`,
  267. },
  268. },
  269. }
  270. b, err := json.Marshal(nor)
  271. require.NoError(t, err)
  272. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: b})
  273. req := httptest.NewRequest("POST", "https://random.local/", http.NoBody)
  274. req = req.WithContext(ctx)
  275. w := httptest.NewRecorder()
  276. NewOrder(w, req)
  277. res := w.Result()
  278. require.Equal(t, http.StatusCreated, res.StatusCode)
  279. body, err := io.ReadAll(res.Body)
  280. defer res.Body.Close()
  281. require.NoError(t, err)
  282. err = json.Unmarshal(bytes.TrimSpace(body), &order)
  283. require.NoError(t, err)
  284. order, err = db.GetOrder(ctx, order.ID)
  285. require.NoError(t, err)
  286. return
  287. }(ctx)
  288. t.Log("authzs IDs:", order.AuthorizationIDs)
  289. // get authorization
  290. getAuthz := func(ctx context.Context, authzID string) (az *acme.Authorization) {
  291. chiCtx := chi.NewRouteContext()
  292. chiCtx.URLParams.Add("authzID", authzID)
  293. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  294. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  295. w := httptest.NewRecorder()
  296. GetAuthorization(w, req)
  297. res := w.Result()
  298. require.Equal(t, http.StatusOK, res.StatusCode)
  299. body, err := io.ReadAll(res.Body)
  300. defer res.Body.Close()
  301. require.NoError(t, err)
  302. err = json.Unmarshal(bytes.TrimSpace(body), &az)
  303. require.NoError(t, err)
  304. az, err = db.GetAuthorization(ctx, authzID)
  305. require.NoError(t, err)
  306. return
  307. }
  308. var azs []*acme.Authorization
  309. for _, azID := range order.AuthorizationIDs {
  310. az := getAuthz(ctx, azID)
  311. azs = append(azs, az)
  312. for _, challenge := range az.Challenges {
  313. chiCtx := chi.NewRouteContext()
  314. chiCtx.URLParams.Add("chID", challenge.ID)
  315. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  316. var payload []byte
  317. switch challenge.Type {
  318. case acme.WIREDPOP01:
  319. dpopBytes, err := json.Marshal(struct {
  320. jose.Claims
  321. Challenge string `json:"chal,omitempty"`
  322. Handle string `json:"handle,omitempty"`
  323. Nonce string `json:"nonce,omitempty"`
  324. HTU string `json:"htu,omitempty"`
  325. }{
  326. Claims: jose.Claims{
  327. Subject: "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com",
  328. },
  329. Challenge: "token",
  330. Handle: "wireapp://%40alice.smith.qa@example.com",
  331. Nonce: "nonce",
  332. HTU: "http://issuer.example.com",
  333. })
  334. require.NoError(t, err)
  335. dpop, err := dpopSigner.Sign(dpopBytes)
  336. require.NoError(t, err)
  337. proof, err := dpop.CompactSerialize()
  338. require.NoError(t, err)
  339. tokenBytes, err := json.Marshal(struct {
  340. jose.Claims
  341. Challenge string `json:"chal,omitempty"`
  342. Cnf struct {
  343. Kid string `json:"kid,omitempty"`
  344. } `json:"cnf"`
  345. Proof string `json:"proof,omitempty"`
  346. ClientID string `json:"client_id"`
  347. APIVersion int `json:"api_version"`
  348. Scope string `json:"scope"`
  349. }{
  350. Claims: jose.Claims{
  351. Issuer: "http://issuer.example.com",
  352. Audience: []string{"test"},
  353. Expiry: jose.NewNumericDate(time.Now().Add(1 * time.Minute)),
  354. },
  355. Challenge: "token",
  356. Cnf: struct {
  357. Kid string `json:"kid,omitempty"`
  358. }{
  359. Kid: jwk.KeyID,
  360. },
  361. Proof: proof,
  362. ClientID: "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com",
  363. APIVersion: 5,
  364. Scope: "wire_client_id",
  365. })
  366. require.NoError(t, err)
  367. signed, err := accessTokenSigner.Sign(tokenBytes)
  368. require.NoError(t, err)
  369. accessToken, err := signed.CompactSerialize()
  370. require.NoError(t, err)
  371. p, err := json.Marshal(struct {
  372. AccessToken string `json:"access_token"`
  373. }{
  374. AccessToken: accessToken,
  375. })
  376. require.NoError(t, err)
  377. payload = p
  378. case acme.WIREOIDC01:
  379. keyAuth, err := acme.KeyAuthorization("token", jwk)
  380. require.NoError(t, err)
  381. tokenBytes, err := json.Marshal(struct {
  382. jose.Claims
  383. Name string `json:"name,omitempty"`
  384. PreferredUsername string `json:"preferred_username,omitempty"`
  385. KeyAuth string `json:"keyauth"`
  386. }{
  387. Claims: jose.Claims{
  388. Issuer: "https://issuer.example.com",
  389. Audience: []string{"test"},
  390. Expiry: jose.NewNumericDate(time.Now().Add(1 * time.Minute)),
  391. },
  392. Name: "Alice Smith",
  393. PreferredUsername: "wireapp://%40alice_wire@wire.com",
  394. KeyAuth: keyAuth,
  395. })
  396. require.NoError(t, err)
  397. signed, err := oidcTokenSigner.Sign(tokenBytes)
  398. require.NoError(t, err)
  399. idToken, err := signed.CompactSerialize()
  400. require.NoError(t, err)
  401. p, err := json.Marshal(struct {
  402. IDToken string `json:"id_token"`
  403. }{
  404. IDToken: idToken,
  405. })
  406. require.NoError(t, err)
  407. payload = p
  408. default:
  409. require.Fail(t, "unexpected challenge payload type")
  410. }
  411. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: payload})
  412. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  413. w := httptest.NewRecorder()
  414. GetChallenge(w, req)
  415. res := w.Result()
  416. require.Equal(t, http.StatusOK, res.StatusCode)
  417. body, err := io.ReadAll(res.Body)
  418. defer res.Body.Close() //nolint:gocritic // close the body
  419. require.NoError(t, err)
  420. err = json.Unmarshal(bytes.TrimSpace(body), &challenge)
  421. require.NoError(t, err)
  422. t.Log("challenge:", challenge.ID, challenge.Status)
  423. }
  424. }
  425. // get/validate challenge simulation
  426. updateAz := func(ctx context.Context, az *acme.Authorization) (updatedAz *acme.Authorization) {
  427. now := clock.Now().Format(time.RFC3339)
  428. for _, challenge := range az.Challenges {
  429. challenge.Status = acme.StatusValid
  430. challenge.ValidatedAt = now
  431. err := db.UpdateChallenge(ctx, challenge)
  432. if err != nil {
  433. t.Error("updating challenge", challenge.ID, ":", err)
  434. }
  435. }
  436. updatedAz, err = db.GetAuthorization(ctx, az.ID)
  437. require.NoError(t, err)
  438. return
  439. }
  440. for _, az := range azs {
  441. updatedAz := updateAz(ctx, az)
  442. for _, challenge := range updatedAz.Challenges {
  443. t.Log("updated challenge:", challenge.ID, challenge.Status)
  444. switch challenge.Type {
  445. case acme.WIREOIDC01:
  446. err = db.CreateOidcToken(ctx, order.ID, map[string]any{"name": "Smith, Alice M (QA)", "preferred_username": "wireapp://%40alice.smith.qa@example.com"})
  447. require.NoError(t, err)
  448. case acme.WIREDPOP01:
  449. err = db.CreateDpopToken(ctx, order.ID, map[string]any{"sub": "wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com"})
  450. require.NoError(t, err)
  451. default:
  452. require.Fail(t, "unexpected challenge type")
  453. }
  454. }
  455. }
  456. // get order
  457. updatedOrder := func(ctx context.Context) (updatedOrder *acme.Order) {
  458. chiCtx := chi.NewRouteContext()
  459. chiCtx.URLParams.Add("ordID", order.ID)
  460. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  461. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  462. w := httptest.NewRecorder()
  463. GetOrder(w, req)
  464. res := w.Result()
  465. require.Equal(t, http.StatusOK, res.StatusCode)
  466. body, err := io.ReadAll(res.Body)
  467. defer res.Body.Close()
  468. require.NoError(t, err)
  469. err = json.Unmarshal(bytes.TrimSpace(body), &updatedOrder)
  470. require.NoError(t, err)
  471. require.Equal(t, acme.StatusReady, updatedOrder.Status)
  472. return
  473. }(ctx)
  474. t.Log("updated order status:", updatedOrder.Status)
  475. if beforeFinalize != nil {
  476. beforeFinalize(t, rawDB, order)
  477. }
  478. // finalize order
  479. finalizedOrder := func(ctx context.Context) (finalizedOrder *acme.Order) {
  480. ca, err := minica.New(minica.WithName("WireTestCA"))
  481. require.NoError(t, err)
  482. mockMustAuthority(t, &mockCASigner{
  483. signer: func(csr *x509.CertificateRequest, signOpts provisioner.SignOptions, extraOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  484. var (
  485. certOptions []x509util.Option
  486. )
  487. for _, op := range extraOpts {
  488. if k, ok := op.(provisioner.CertificateOptions); ok {
  489. certOptions = append(certOptions, k.Options(signOpts)...)
  490. }
  491. }
  492. x509utilTemplate, err := x509util.NewCertificate(csr, certOptions...)
  493. require.NoError(t, err)
  494. template := x509utilTemplate.GetCertificate()
  495. require.NotNil(t, template)
  496. cert, err := ca.Sign(template)
  497. require.NoError(t, err)
  498. u1, err := url.Parse("wireapp://%40alice.smith.qa@example.com")
  499. require.NoError(t, err)
  500. u2, err := url.Parse("wireapp://lJGYPz0ZRq2kvc_XpdaDlA%21ed416ce8ecdd9fad@example.com")
  501. require.NoError(t, err)
  502. assert.Equal(t, []*url.URL{u1, u2}, cert.URIs)
  503. assert.Equal(t, "Smith, Alice M (QA)", cert.Subject.CommonName)
  504. return []*x509.Certificate{cert, ca.Intermediate}, nil
  505. },
  506. })
  507. qUserID, err := url.Parse("wireapp://lJGYPz0ZRq2kvc_XpdaDlA!ed416ce8ecdd9fad@example.com")
  508. require.NoError(t, err)
  509. qUserName, err := url.Parse("wireapp://%40alice.smith.qa@example.com")
  510. require.NoError(t, err)
  511. _, priv, err := ed25519.GenerateKey(rand.Reader)
  512. require.NoError(t, err)
  513. csrTemplate := &x509.CertificateRequest{
  514. Subject: pkix.Name{
  515. Organization: []string{"example.com"},
  516. ExtraNames: []pkix.AttributeTypeAndValue{
  517. {
  518. Type: asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 3, 1, 241},
  519. Value: "Smith, Alice M (QA)",
  520. },
  521. },
  522. },
  523. URIs: []*url.URL{
  524. qUserName,
  525. qUserID,
  526. },
  527. SignatureAlgorithm: x509.PureEd25519,
  528. }
  529. csr, err := x509.CreateCertificateRequest(rand.Reader, csrTemplate, priv)
  530. require.NoError(t, err)
  531. fr := FinalizeRequest{CSR: base64.RawURLEncoding.EncodeToString(csr)}
  532. frRaw, err := json.Marshal(fr)
  533. require.NoError(t, err)
  534. ctx = context.WithValue(ctx, payloadContextKey, &payloadInfo{value: frRaw})
  535. chiCtx := chi.NewRouteContext()
  536. chiCtx.URLParams.Add("ordID", order.ID)
  537. ctx = context.WithValue(ctx, chi.RouteCtxKey, chiCtx)
  538. req := httptest.NewRequest(http.MethodGet, "https://random.local/", http.NoBody).WithContext(ctx)
  539. w := httptest.NewRecorder()
  540. FinalizeOrder(w, req)
  541. res := w.Result()
  542. body, err := io.ReadAll(res.Body)
  543. defer res.Body.Close()
  544. require.NoError(t, err)
  545. if checkFinalizeResponse != nil {
  546. checkFinalizeResponse(t, res, body)
  547. return nil
  548. }
  549. require.Equal(t, http.StatusOK, res.StatusCode)
  550. err = json.Unmarshal(bytes.TrimSpace(body), &finalizedOrder)
  551. require.NoError(t, err)
  552. require.Equal(t, acme.StatusValid, finalizedOrder.Status)
  553. finalizedOrder, err = db.GetOrder(ctx, order.ID)
  554. require.NoError(t, err)
  555. return
  556. }(ctx)
  557. if finalizedOrder != nil {
  558. t.Log("finalized order status:", finalizedOrder.Status)
  559. }
  560. }
  561. type mockCASigner struct {
  562. signer func(*x509.CertificateRequest, provisioner.SignOptions, ...provisioner.SignOption) ([]*x509.Certificate, error)
  563. }
  564. func (m *mockCASigner) SignWithContext(_ context.Context, cr *x509.CertificateRequest, opts provisioner.SignOptions, signOpts ...provisioner.SignOption) ([]*x509.Certificate, error) {
  565. if m.signer == nil {
  566. return nil, errors.New("unimplemented")
  567. }
  568. return m.signer(cr, opts, signOpts...)
  569. }
  570. func (m *mockCASigner) AreSANsAllowed(ctx context.Context, sans []string) error {
  571. return nil
  572. }
  573. func (m *mockCASigner) IsRevoked(sn string) (bool, error) {
  574. return false, nil
  575. }
  576. func (m *mockCASigner) Revoke(ctx context.Context, opts *authority.RevokeOptions) error {
  577. return nil
  578. }
  579. func (m *mockCASigner) LoadProvisionerByName(string) (provisioner.Interface, error) {
  580. return nil, nil
  581. }
  582. func (m *mockCASigner) GetBackdate() *time.Duration {
  583. return nil
  584. }