webhook.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package webhook
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "go.step.sm/linkedca"
  7. "github.com/smallstep/certificates/authority/provisioner"
  8. "github.com/smallstep/certificates/webhook"
  9. )
  10. // Controller controls webhook execution
  11. type Controller struct {
  12. client *http.Client
  13. webhooks []*provisioner.Webhook
  14. }
  15. // New returns a new SCEP webhook Controller
  16. func New(webhooks []*provisioner.Webhook) (*Controller, error) {
  17. return &Controller{
  18. client: http.DefaultClient,
  19. webhooks: webhooks,
  20. }, nil
  21. }
  22. // Validate executes zero or more configured webhooks to
  23. // validate the SCEP challenge. If at least one of indicates
  24. // the challenge value is accepted, validation succeeds. Other
  25. // webhooks will not be executed. If none of the webhooks
  26. // indicates the challenge is accepted, an error is
  27. // returned.
  28. func (c *Controller) Validate(ctx context.Context, challenge string) error {
  29. for _, wh := range c.webhooks {
  30. if wh.Kind != linkedca.Webhook_SCEPCHALLENGE.String() {
  31. continue
  32. }
  33. if !c.isCertTypeOK(wh) {
  34. continue
  35. }
  36. req := &webhook.RequestBody{
  37. SCEPChallenge: challenge,
  38. }
  39. resp, err := wh.DoWithContext(ctx, c.client, req, nil) // TODO(hs): support templated URL? Requires some refactoring
  40. if err != nil {
  41. return fmt.Errorf("failed executing webhook request: %w", err)
  42. }
  43. if resp.Allow {
  44. return nil // return early when response is positive
  45. }
  46. }
  47. return provisioner.ErrWebhookDenied
  48. }
  49. // isCertTypeOK returns whether or not the webhook can be used
  50. // with the SCEP challenge validation webhook controller.
  51. func (c *Controller) isCertTypeOK(wh *provisioner.Webhook) bool {
  52. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  53. return true
  54. }
  55. return linkedca.Webhook_X509.String() == wh.CertType
  56. }