webhook_test.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. package provisioner
  2. import (
  3. "context"
  4. "crypto/hmac"
  5. "crypto/sha256"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "encoding/json"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "net/http"
  15. "net/http/httptest"
  16. "testing"
  17. "time"
  18. "github.com/stretchr/testify/assert"
  19. "github.com/stretchr/testify/require"
  20. "go.step.sm/crypto/pemutil"
  21. "go.step.sm/crypto/x509util"
  22. "go.step.sm/linkedca"
  23. "github.com/smallstep/certificates/middleware/requestid"
  24. "github.com/smallstep/certificates/webhook"
  25. )
  26. func TestWebhookController_isCertTypeOK(t *testing.T) {
  27. type test struct {
  28. wc *WebhookController
  29. wh *Webhook
  30. want bool
  31. }
  32. tests := map[string]test{
  33. "all/all": {
  34. wc: &WebhookController{certType: linkedca.Webhook_ALL},
  35. wh: &Webhook{CertType: linkedca.Webhook_ALL.String()},
  36. want: true,
  37. },
  38. "all/x509": {
  39. wc: &WebhookController{certType: linkedca.Webhook_ALL},
  40. wh: &Webhook{CertType: linkedca.Webhook_X509.String()},
  41. want: true,
  42. },
  43. "all/ssh": {
  44. wc: &WebhookController{certType: linkedca.Webhook_ALL},
  45. wh: &Webhook{CertType: linkedca.Webhook_SSH.String()},
  46. want: true,
  47. },
  48. `all/""`: {
  49. wc: &WebhookController{certType: linkedca.Webhook_ALL},
  50. wh: &Webhook{},
  51. want: true,
  52. },
  53. "x509/all": {
  54. wc: &WebhookController{certType: linkedca.Webhook_X509},
  55. wh: &Webhook{CertType: linkedca.Webhook_ALL.String()},
  56. want: true,
  57. },
  58. "x509/x509": {
  59. wc: &WebhookController{certType: linkedca.Webhook_X509},
  60. wh: &Webhook{CertType: linkedca.Webhook_X509.String()},
  61. want: true,
  62. },
  63. "x509/ssh": {
  64. wc: &WebhookController{certType: linkedca.Webhook_X509},
  65. wh: &Webhook{CertType: linkedca.Webhook_SSH.String()},
  66. want: false,
  67. },
  68. `x509/""`: {
  69. wc: &WebhookController{certType: linkedca.Webhook_X509},
  70. wh: &Webhook{},
  71. want: true,
  72. },
  73. "ssh/all": {
  74. wc: &WebhookController{certType: linkedca.Webhook_SSH},
  75. wh: &Webhook{CertType: linkedca.Webhook_ALL.String()},
  76. want: true,
  77. },
  78. "ssh/x509": {
  79. wc: &WebhookController{certType: linkedca.Webhook_SSH},
  80. wh: &Webhook{CertType: linkedca.Webhook_X509.String()},
  81. want: false,
  82. },
  83. "ssh/ssh": {
  84. wc: &WebhookController{certType: linkedca.Webhook_SSH},
  85. wh: &Webhook{CertType: linkedca.Webhook_SSH.String()},
  86. want: true,
  87. },
  88. `ssh/""`: {
  89. wc: &WebhookController{certType: linkedca.Webhook_SSH},
  90. wh: &Webhook{},
  91. want: true,
  92. },
  93. }
  94. for name, test := range tests {
  95. t.Run(name, func(t *testing.T) {
  96. assert.Equal(t, test.want, test.wc.isCertTypeOK(test.wh))
  97. })
  98. }
  99. }
  100. // withRequestID is a helper that calls into [requestid.NewContext] and returns
  101. // a new context with the requestID added.
  102. func withRequestID(t *testing.T, ctx context.Context, requestID string) context.Context {
  103. t.Helper()
  104. return requestid.NewContext(ctx, requestID)
  105. }
  106. func TestWebhookController_Enrich(t *testing.T) {
  107. cert, err := pemutil.ReadCertificate("testdata/certs/x5c-leaf.crt", pemutil.WithFirstBlock())
  108. require.NoError(t, err)
  109. type test struct {
  110. ctl *WebhookController
  111. ctx context.Context
  112. req *webhook.RequestBody
  113. responses []*webhook.ResponseBody
  114. expectErr bool
  115. expectTemplateData any
  116. assertRequest func(t *testing.T, req *webhook.RequestBody)
  117. assertError func(t *testing.T, err error)
  118. }
  119. tests := map[string]test{
  120. "ok/no enriching webhooks": {
  121. ctl: &WebhookController{
  122. client: http.DefaultClient,
  123. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  124. TemplateData: nil,
  125. },
  126. req: &webhook.RequestBody{},
  127. responses: nil,
  128. expectErr: false,
  129. expectTemplateData: nil,
  130. },
  131. "ok/one webhook": {
  132. ctl: &WebhookController{
  133. client: http.DefaultClient,
  134. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  135. TemplateData: x509util.TemplateData{},
  136. },
  137. ctx: withRequestID(t, context.Background(), "reqID"),
  138. req: &webhook.RequestBody{},
  139. responses: []*webhook.ResponseBody{{Allow: true, Data: map[string]any{"role": "bar"}}},
  140. expectErr: false,
  141. expectTemplateData: x509util.TemplateData{"Webhooks": map[string]any{"people": map[string]any{"role": "bar"}}},
  142. },
  143. "ok/two webhooks": {
  144. ctl: &WebhookController{
  145. client: http.DefaultClient,
  146. webhooks: []*Webhook{
  147. {Name: "people", Kind: "ENRICHING"},
  148. {Name: "devices", Kind: "ENRICHING"},
  149. },
  150. TemplateData: x509util.TemplateData{},
  151. },
  152. ctx: withRequestID(t, context.Background(), "reqID"),
  153. req: &webhook.RequestBody{},
  154. responses: []*webhook.ResponseBody{
  155. {Allow: true, Data: map[string]any{"role": "bar"}},
  156. {Allow: true, Data: map[string]any{"serial": "123"}},
  157. },
  158. expectErr: false,
  159. expectTemplateData: x509util.TemplateData{
  160. "Webhooks": map[string]any{
  161. "devices": map[string]any{"serial": "123"},
  162. "people": map[string]any{"role": "bar"},
  163. },
  164. },
  165. },
  166. "ok/x509 only": {
  167. ctl: &WebhookController{
  168. client: http.DefaultClient,
  169. webhooks: []*Webhook{
  170. {Name: "people", Kind: "ENRICHING", CertType: linkedca.Webhook_SSH.String()},
  171. {Name: "devices", Kind: "ENRICHING"},
  172. },
  173. TemplateData: x509util.TemplateData{},
  174. certType: linkedca.Webhook_X509,
  175. },
  176. ctx: withRequestID(t, context.Background(), "reqID"),
  177. req: &webhook.RequestBody{},
  178. responses: []*webhook.ResponseBody{
  179. {Allow: true, Data: map[string]any{"role": "bar"}},
  180. {Allow: true, Data: map[string]any{"serial": "123"}},
  181. },
  182. expectErr: false,
  183. expectTemplateData: x509util.TemplateData{
  184. "Webhooks": map[string]any{
  185. "devices": map[string]any{"serial": "123"},
  186. },
  187. },
  188. },
  189. "ok/with options": {
  190. ctl: &WebhookController{
  191. client: http.DefaultClient,
  192. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  193. TemplateData: x509util.TemplateData{},
  194. options: []webhook.RequestBodyOption{webhook.WithX5CCertificate(cert)},
  195. },
  196. ctx: withRequestID(t, context.Background(), "reqID"),
  197. req: &webhook.RequestBody{},
  198. responses: []*webhook.ResponseBody{{Allow: true, Data: map[string]any{"role": "bar"}}},
  199. expectErr: false,
  200. expectTemplateData: x509util.TemplateData{"Webhooks": map[string]any{"people": map[string]any{"role": "bar"}}},
  201. assertRequest: func(t *testing.T, req *webhook.RequestBody) {
  202. key, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
  203. require.NoError(t, err)
  204. assert.Equal(t, &webhook.X5CCertificate{
  205. Raw: cert.Raw,
  206. PublicKey: key,
  207. PublicKeyAlgorithm: cert.PublicKeyAlgorithm.String(),
  208. NotBefore: cert.NotBefore,
  209. NotAfter: cert.NotAfter,
  210. }, req.X5CCertificate)
  211. },
  212. },
  213. "deny": {
  214. ctl: &WebhookController{
  215. client: http.DefaultClient,
  216. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  217. TemplateData: x509util.TemplateData{},
  218. },
  219. ctx: withRequestID(t, context.Background(), "reqID"),
  220. req: &webhook.RequestBody{},
  221. responses: []*webhook.ResponseBody{{Allow: false}},
  222. expectErr: true,
  223. expectTemplateData: x509util.TemplateData{},
  224. assertError: func(t *testing.T, err error) {
  225. assert.Equal(t, ErrWebhookDenied, err)
  226. },
  227. },
  228. "deny/with error": {
  229. ctl: &WebhookController{
  230. client: http.DefaultClient,
  231. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  232. TemplateData: x509util.TemplateData{},
  233. },
  234. ctx: withRequestID(t, context.Background(), "reqID"),
  235. req: &webhook.RequestBody{},
  236. responses: []*webhook.ResponseBody{{Allow: false, Error: &webhook.Error{
  237. Code: "theCode", Message: "Some message",
  238. }}},
  239. expectErr: true,
  240. expectTemplateData: x509util.TemplateData{},
  241. assertError: func(t *testing.T, err error) {
  242. assert.Equal(t, &webhook.Error{
  243. Code: "theCode", Message: "Some message",
  244. }, err)
  245. },
  246. },
  247. "fail/with options": {
  248. ctl: &WebhookController{
  249. client: http.DefaultClient,
  250. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  251. TemplateData: x509util.TemplateData{},
  252. options: []webhook.RequestBodyOption{webhook.WithX5CCertificate(&x509.Certificate{
  253. PublicKey: []byte("bad"),
  254. })},
  255. },
  256. ctx: withRequestID(t, context.Background(), "reqID"),
  257. req: &webhook.RequestBody{},
  258. responses: []*webhook.ResponseBody{{Allow: false}},
  259. expectErr: true,
  260. expectTemplateData: x509util.TemplateData{},
  261. },
  262. }
  263. for name, test := range tests {
  264. t.Run(name, func(t *testing.T) {
  265. for i, wh := range test.ctl.webhooks {
  266. var j = i
  267. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  268. assert.Equal(t, "reqID", r.Header.Get("X-Request-ID"))
  269. err := json.NewEncoder(w).Encode(test.responses[j])
  270. require.NoError(t, err)
  271. }))
  272. // nolint: gocritic // defer in loop isn't a memory leak
  273. defer ts.Close()
  274. wh.URL = ts.URL
  275. }
  276. err := test.ctl.Enrich(test.ctx, test.req)
  277. if (err != nil) != test.expectErr {
  278. t.Fatalf("Got err %v, want %v", err, test.expectErr)
  279. }
  280. assert.Equal(t, test.expectTemplateData, test.ctl.TemplateData)
  281. if test.assertRequest != nil {
  282. test.assertRequest(t, test.req)
  283. }
  284. if test.assertError != nil {
  285. test.assertError(t, err)
  286. }
  287. })
  288. }
  289. }
  290. func TestWebhookController_Authorize(t *testing.T) {
  291. cert, err := pemutil.ReadCertificate("testdata/certs/x5c-leaf.crt", pemutil.WithFirstBlock())
  292. require.NoError(t, err)
  293. type test struct {
  294. ctl *WebhookController
  295. ctx context.Context
  296. req *webhook.RequestBody
  297. responses []*webhook.ResponseBody
  298. expectErr bool
  299. assertRequest func(t *testing.T, req *webhook.RequestBody)
  300. assertError func(t *testing.T, err error)
  301. }
  302. tests := map[string]test{
  303. "ok/no enriching webhooks": {
  304. ctl: &WebhookController{
  305. client: http.DefaultClient,
  306. webhooks: []*Webhook{{Name: "people", Kind: "ENRICHING"}},
  307. },
  308. req: &webhook.RequestBody{},
  309. responses: nil,
  310. expectErr: false,
  311. },
  312. "ok": {
  313. ctl: &WebhookController{
  314. client: http.DefaultClient,
  315. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  316. },
  317. ctx: withRequestID(t, context.Background(), "reqID"),
  318. req: &webhook.RequestBody{},
  319. responses: []*webhook.ResponseBody{{Allow: true}},
  320. expectErr: false,
  321. },
  322. "ok/ssh only": {
  323. ctl: &WebhookController{
  324. client: http.DefaultClient,
  325. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING", CertType: linkedca.Webhook_X509.String()}},
  326. certType: linkedca.Webhook_SSH,
  327. },
  328. ctx: withRequestID(t, context.Background(), "reqID"),
  329. req: &webhook.RequestBody{},
  330. responses: []*webhook.ResponseBody{{Allow: false}},
  331. expectErr: false,
  332. },
  333. "ok/with options": {
  334. ctl: &WebhookController{
  335. client: http.DefaultClient,
  336. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  337. options: []webhook.RequestBodyOption{webhook.WithX5CCertificate(cert)},
  338. },
  339. ctx: withRequestID(t, context.Background(), "reqID"),
  340. req: &webhook.RequestBody{},
  341. responses: []*webhook.ResponseBody{{Allow: true}},
  342. expectErr: false,
  343. assertRequest: func(t *testing.T, req *webhook.RequestBody) {
  344. key, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
  345. require.NoError(t, err)
  346. assert.Equal(t, &webhook.X5CCertificate{
  347. Raw: cert.Raw,
  348. PublicKey: key,
  349. PublicKeyAlgorithm: cert.PublicKeyAlgorithm.String(),
  350. NotBefore: cert.NotBefore,
  351. NotAfter: cert.NotAfter,
  352. }, req.X5CCertificate)
  353. },
  354. },
  355. "deny": {
  356. ctl: &WebhookController{
  357. client: http.DefaultClient,
  358. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  359. },
  360. ctx: withRequestID(t, context.Background(), "reqID"),
  361. req: &webhook.RequestBody{},
  362. responses: []*webhook.ResponseBody{{Allow: false}},
  363. expectErr: true,
  364. assertError: func(t *testing.T, err error) {
  365. assert.Equal(t, ErrWebhookDenied, err)
  366. },
  367. },
  368. "deny/withError": {
  369. ctl: &WebhookController{
  370. client: http.DefaultClient,
  371. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  372. },
  373. ctx: withRequestID(t, context.Background(), "reqID"),
  374. req: &webhook.RequestBody{},
  375. responses: []*webhook.ResponseBody{{Allow: false, Error: &webhook.Error{
  376. Code: "theCode", Message: "Some message",
  377. }}},
  378. expectErr: true,
  379. assertError: func(t *testing.T, err error) {
  380. assert.Equal(t, &webhook.Error{
  381. Code: "theCode", Message: "Some message",
  382. }, err)
  383. },
  384. },
  385. "fail/with options": {
  386. ctl: &WebhookController{
  387. client: http.DefaultClient,
  388. webhooks: []*Webhook{{Name: "people", Kind: "AUTHORIZING"}},
  389. options: []webhook.RequestBodyOption{webhook.WithX5CCertificate(&x509.Certificate{
  390. PublicKey: []byte("bad"),
  391. })},
  392. },
  393. ctx: withRequestID(t, context.Background(), "reqID"),
  394. req: &webhook.RequestBody{},
  395. responses: []*webhook.ResponseBody{{Allow: false}},
  396. expectErr: true,
  397. },
  398. }
  399. for name, test := range tests {
  400. t.Run(name, func(t *testing.T) {
  401. for i, wh := range test.ctl.webhooks {
  402. var j = i
  403. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  404. assert.Equal(t, "reqID", r.Header.Get("X-Request-ID"))
  405. err := json.NewEncoder(w).Encode(test.responses[j])
  406. require.NoError(t, err)
  407. }))
  408. // nolint: gocritic // defer in loop isn't a memory leak
  409. defer ts.Close()
  410. wh.URL = ts.URL
  411. }
  412. err := test.ctl.Authorize(test.ctx, test.req)
  413. if (err != nil) != test.expectErr {
  414. t.Fatalf("Got err %v, want %v", err, test.expectErr)
  415. }
  416. if test.assertRequest != nil {
  417. test.assertRequest(t, test.req)
  418. }
  419. if test.assertError != nil {
  420. test.assertError(t, err)
  421. }
  422. })
  423. }
  424. }
  425. func TestWebhook_Do(t *testing.T) {
  426. csr := parseCertificateRequest(t, "testdata/certs/ecdsa.csr")
  427. type test struct {
  428. webhook Webhook
  429. dataArg any
  430. requestID string
  431. webhookResponse webhook.ResponseBody
  432. expectPath string
  433. errStatusCode int
  434. serverErrMsg string
  435. expectErr error
  436. // expectToken any
  437. }
  438. tests := map[string]test{
  439. "ok": {
  440. webhook: Webhook{
  441. ID: "abc123",
  442. Secret: "c2VjcmV0Cg==",
  443. },
  444. requestID: "reqID",
  445. webhookResponse: webhook.ResponseBody{
  446. Data: map[string]interface{}{"role": "dba"},
  447. },
  448. },
  449. "ok/no-request-id": {
  450. webhook: Webhook{
  451. ID: "abc123",
  452. Secret: "c2VjcmV0Cg==",
  453. },
  454. webhookResponse: webhook.ResponseBody{
  455. Data: map[string]interface{}{"role": "dba"},
  456. },
  457. },
  458. "ok/bearer": {
  459. webhook: Webhook{
  460. ID: "abc123",
  461. Secret: "c2VjcmV0Cg==",
  462. BearerToken: "mytoken",
  463. },
  464. requestID: "reqID",
  465. webhookResponse: webhook.ResponseBody{
  466. Data: map[string]interface{}{"role": "dba"},
  467. },
  468. },
  469. "ok/basic": {
  470. webhook: Webhook{
  471. ID: "abc123",
  472. Secret: "c2VjcmV0Cg==",
  473. BasicAuth: struct {
  474. Username string
  475. Password string
  476. }{
  477. Username: "myuser",
  478. Password: "mypass",
  479. },
  480. },
  481. requestID: "reqID",
  482. webhookResponse: webhook.ResponseBody{
  483. Data: map[string]interface{}{"role": "dba"},
  484. },
  485. },
  486. "ok/templated-url": {
  487. webhook: Webhook{
  488. ID: "abc123",
  489. // scheme, host, port will come from test server
  490. URL: "/users/{{ .username }}?region={{ .region }}",
  491. Secret: "c2VjcmV0Cg==",
  492. },
  493. requestID: "reqID",
  494. dataArg: map[string]interface{}{"username": "areed", "region": "central"},
  495. webhookResponse: webhook.ResponseBody{
  496. Data: map[string]interface{}{"role": "dba"},
  497. },
  498. expectPath: "/users/areed?region=central",
  499. },
  500. /*
  501. "ok/token from ssh template": {
  502. webhook: Webhook{
  503. ID: "abc123",
  504. Secret: "c2VjcmV0Cg==",
  505. },
  506. webhookResponse: webhook.ResponseBody{
  507. Data: map[string]interface{}{"role": "dba"},
  508. },
  509. dataArg: sshutil.TemplateData{sshutil.TokenKey: "token"},
  510. expectToken: "token",
  511. },
  512. "ok/token from x509 template": {
  513. webhook: Webhook{
  514. ID: "abc123",
  515. Secret: "c2VjcmV0Cg==",
  516. },
  517. webhookResponse: webhook.ResponseBody{
  518. Data: map[string]interface{}{"role": "dba"},
  519. },
  520. dataArg: x509util.TemplateData{sshutil.TokenKey: "token"},
  521. expectToken: "token",
  522. },
  523. */
  524. "ok/allow": {
  525. webhook: Webhook{
  526. ID: "abc123",
  527. Secret: "c2VjcmV0Cg==",
  528. },
  529. requestID: "reqID",
  530. webhookResponse: webhook.ResponseBody{
  531. Allow: true,
  532. },
  533. },
  534. "fail/404": {
  535. webhook: Webhook{
  536. ID: "abc123",
  537. Secret: "c2VjcmV0Cg==",
  538. },
  539. webhookResponse: webhook.ResponseBody{
  540. Data: map[string]interface{}{"role": "dba"},
  541. },
  542. requestID: "reqID",
  543. errStatusCode: 404,
  544. serverErrMsg: "item not found",
  545. expectErr: errors.New("Webhook server responded with 404"),
  546. },
  547. }
  548. for name, tc := range tests {
  549. t.Run(name, func(t *testing.T) {
  550. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  551. if tc.requestID != "" {
  552. assert.Equal(t, tc.requestID, r.Header.Get("X-Request-ID"))
  553. }
  554. assert.Equal(t, tc.webhook.ID, r.Header.Get("X-Smallstep-Webhook-ID"))
  555. sig, err := hex.DecodeString(r.Header.Get("X-Smallstep-Signature"))
  556. assert.NoError(t, err)
  557. body, err := io.ReadAll(r.Body)
  558. assert.NoError(t, err)
  559. secret, err := base64.StdEncoding.DecodeString(tc.webhook.Secret)
  560. assert.NoError(t, err)
  561. h := hmac.New(sha256.New, secret)
  562. h.Write(body)
  563. mac := h.Sum(nil)
  564. assert.True(t, hmac.Equal(sig, mac))
  565. switch {
  566. case tc.webhook.BearerToken != "":
  567. ah := fmt.Sprintf("Bearer %s", tc.webhook.BearerToken)
  568. assert.Equal(t, ah, r.Header.Get("Authorization"))
  569. case tc.webhook.BasicAuth.Username != "" || tc.webhook.BasicAuth.Password != "":
  570. whReq, err := http.NewRequest("", "", http.NoBody)
  571. require.NoError(t, err)
  572. whReq.SetBasicAuth(tc.webhook.BasicAuth.Username, tc.webhook.BasicAuth.Password)
  573. ah := whReq.Header.Get("Authorization")
  574. assert.Equal(t, ah, whReq.Header.Get("Authorization"))
  575. default:
  576. assert.Equal(t, "", r.Header.Get("Authorization"))
  577. }
  578. if tc.expectPath != "" {
  579. assert.Equal(t, tc.expectPath, r.URL.Path+"?"+r.URL.RawQuery)
  580. }
  581. if tc.errStatusCode != 0 {
  582. http.Error(w, tc.serverErrMsg, tc.errStatusCode)
  583. return
  584. }
  585. reqBody := new(webhook.RequestBody)
  586. err = json.Unmarshal(body, reqBody)
  587. require.NoError(t, err)
  588. err = json.NewEncoder(w).Encode(tc.webhookResponse)
  589. require.NoError(t, err)
  590. }))
  591. defer ts.Close()
  592. tc.webhook.URL = ts.URL + tc.webhook.URL
  593. reqBody, err := webhook.NewRequestBody(webhook.WithX509CertificateRequest(csr))
  594. require.NoError(t, err)
  595. ctx := context.Background()
  596. if tc.requestID != "" {
  597. ctx = withRequestID(t, ctx, tc.requestID)
  598. }
  599. ctx, cancel := context.WithTimeout(ctx, time.Second*10)
  600. defer cancel()
  601. got, err := tc.webhook.DoWithContext(ctx, http.DefaultClient, reqBody, tc.dataArg)
  602. if tc.expectErr != nil {
  603. assert.Equal(t, tc.expectErr.Error(), err.Error())
  604. return
  605. }
  606. assert.NoError(t, err)
  607. assert.Equal(t, &tc.webhookResponse, got)
  608. })
  609. }
  610. t.Run("disableTLSClientAuth", func(t *testing.T) {
  611. ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  612. w.Write([]byte("{}"))
  613. }))
  614. ts.TLS.ClientAuth = tls.RequireAnyClientCert
  615. wh := Webhook{
  616. URL: ts.URL,
  617. }
  618. cert, err := tls.LoadX509KeyPair("testdata/certs/foo.crt", "testdata/secrets/foo.key")
  619. require.NoError(t, err)
  620. transport := http.DefaultTransport.(*http.Transport).Clone()
  621. transport.TLSClientConfig = &tls.Config{
  622. InsecureSkipVerify: true,
  623. Certificates: []tls.Certificate{cert},
  624. }
  625. client := &http.Client{
  626. Transport: transport,
  627. }
  628. reqBody, err := webhook.NewRequestBody(webhook.WithX509CertificateRequest(csr))
  629. require.NoError(t, err)
  630. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  631. defer cancel()
  632. _, err = wh.DoWithContext(ctx, client, reqBody, nil)
  633. require.NoError(t, err)
  634. ctx, cancel = context.WithTimeout(context.Background(), time.Second*10)
  635. defer cancel()
  636. wh.DisableTLSClientAuth = true
  637. _, err = wh.DoWithContext(ctx, client, reqBody, nil)
  638. require.Error(t, err)
  639. })
  640. }