webhook_test.go 20 KB

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