webhook_test.go 16 KB

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