4
0

webhook.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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, transactionID 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. SCEPTransactionID: transactionID,
  39. }
  40. resp, err := wh.DoWithContext(ctx, c.client, req, nil) // TODO(hs): support templated URL? Requires some refactoring
  41. if err != nil {
  42. return fmt.Errorf("failed executing webhook request: %w", err)
  43. }
  44. if resp.Allow {
  45. return nil // return early when response is positive
  46. }
  47. }
  48. return provisioner.ErrWebhookDenied
  49. }
  50. // isCertTypeOK returns whether or not the webhook can be used
  51. // with the SCEP challenge validation webhook controller.
  52. func (c *Controller) isCertTypeOK(wh *provisioner.Webhook) bool {
  53. if wh.CertType == linkedca.Webhook_ALL.String() || wh.CertType == "" {
  54. return true
  55. }
  56. return linkedca.Webhook_X509.String() == wh.CertType
  57. }