webhook_test.go 13 KB

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