webhook_test.go 22 KB

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