fix(events): route webhooks by source UUID (#2127)
This commit is contained in:
16 files changed
+90
-176
No files matched your search
@@ -84,7 +84,7 @@ func TestIntakeAppliesTheDeliveryPolicyBeforeStoring(t *testing.T) {
|
||||
inserter := &onceInserter{stored: map[string]bool{}}
|
||||
m := &Module{
|
||||
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: inserter, deliveries: noEcho{},
|
||||
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", WebhookPath: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
|
||||
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
|
||||
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
|
||||
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
||||
},
|
||||
|
||||
+14
-32
@@ -8,7 +8,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -84,9 +83,8 @@ type SourceSettings struct {
|
||||
|
||||
type createSourceInput struct {
|
||||
Body struct {
|
||||
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
|
||||
WebhookPath string `json:"webhook_path,omitzero" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Defaults to the label"`
|
||||
Scope string `json:"scope,omitzero" enum:"org,person" doc:"Who owns the source: the organisation (default) or the caller, who alone can see and use it"`
|
||||
Label string `json:"label" minLength:"1" maxLength:"100" doc:"The name people see, unique among the sources of the same owner"`
|
||||
Scope string `json:"scope,omitzero" enum:"org,person" doc:"Who owns the source: the organisation (default) or the caller, who alone can see and use it"`
|
||||
SourceSettings
|
||||
}
|
||||
}
|
||||
@@ -98,32 +96,17 @@ type sourceCreated struct {
|
||||
URL string `json:"url" doc:"Where the sender posts its events"`
|
||||
}
|
||||
|
||||
var pathChars = regexp.MustCompile(`[^a-z0-9]+`)
|
||||
|
||||
// pathFor derives a webhook path from a label.
|
||||
func pathFor(label string) string {
|
||||
path := strings.Trim(pathChars.ReplaceAllString(strings.ToLower(label), "-"), "-")
|
||||
if len(path) > 63 {
|
||||
path = strings.Trim(path[:63], "-")
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
// createSource adds a source. It returns a token only for the token scheme,
|
||||
// and only its hash is stored. An HMAC secret is sealed and never returned,
|
||||
// except one generated here.
|
||||
func (m *Module) createSource(ctx context.Context, in *createSourceInput) (*httpapi.Reply[sourceCreated], error) {
|
||||
body := in.Body
|
||||
label := strings.TrimSpace(body.Label)
|
||||
path := body.WebhookPath
|
||||
if path == "" {
|
||||
path = pathFor(label)
|
||||
}
|
||||
if label == "" || !validName.MatchString(path) || !validName.MatchString(body.Connector) {
|
||||
return nil, huma.Error400BadRequest("a source needs a label, a webhook path of lowercase letters, digits and hyphens, and a connector")
|
||||
if label == "" || !validName.MatchString(body.Connector) {
|
||||
return nil, huma.Error400BadRequest("a source needs a label and a connector")
|
||||
}
|
||||
base := store.Source{
|
||||
ID: uuid.New(), Scope: store.ScopeOrg, OrgID: m.orgID, Label: label, WebhookPath: path,
|
||||
ID: uuid.New(), Scope: store.ScopeOrg, OrgID: m.orgID, Label: label,
|
||||
}
|
||||
if body.Scope == store.ScopePerson {
|
||||
base.Scope, base.PersonID = store.ScopePerson, sql.NullString{String: caller(ctx), Valid: true}
|
||||
@@ -135,7 +118,7 @@ func (m *Module) createSource(ctx context.Context, in *createSourceInput) (*http
|
||||
if err := sourceWriteError(m.store.InsertSource(ctx, src)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + src.WebhookPath}), nil
|
||||
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: webhookURL(src.ID)}), nil
|
||||
}
|
||||
|
||||
type updateSourceInput struct {
|
||||
@@ -163,7 +146,7 @@ func (m *Module) updateSource(ctx context.Context, in *updateSourceInput) (*http
|
||||
if err := sourceWriteError(m.store.UpdateSource(ctx, src)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: "/hooks/" + src.WebhookPath}), nil
|
||||
return httpapi.OK(sourceCreated{ID: src.ID, Token: issued.token, Secret: issued.secret, URL: webhookURL(src.ID)}), nil
|
||||
}
|
||||
|
||||
// issued is a credential generated for a saved source, returned once.
|
||||
@@ -539,13 +522,12 @@ type sourceView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
// Scope is org for an organisation's source and person for one only its
|
||||
// owner can see and use.
|
||||
Scope string `json:"scope" enum:"org,person"`
|
||||
// Label is the name people see; WebhookPath ends the URL deliveries post to.
|
||||
Label string `json:"label"`
|
||||
WebhookPath string `json:"webhook_path"`
|
||||
Connector string `json:"connector"`
|
||||
KeyFields []string `json:"key_fields"`
|
||||
TokenSet bool `json:"token_set"`
|
||||
Scope string `json:"scope" enum:"org,person"`
|
||||
Label string `json:"label"`
|
||||
URL string `json:"url" doc:"The webhook URL identified by the source UUID"`
|
||||
Connector string `json:"connector"`
|
||||
KeyFields []string `json:"key_fields"`
|
||||
TokenSet bool `json:"token_set"`
|
||||
// Verification and the HMAC header and prefix are shown; the secret is
|
||||
// only reported as set.
|
||||
Verification string `json:"verification"`
|
||||
@@ -583,7 +565,7 @@ func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sou
|
||||
|
||||
func viewOfSource(src store.Source) (sourceView, error) {
|
||||
view := sourceView{
|
||||
ID: src.ID, Scope: src.Scope, Label: src.Label, WebhookPath: src.WebhookPath,
|
||||
ID: src.ID, Scope: src.Scope, Label: src.Label, URL: webhookURL(src.ID),
|
||||
Connector: src.Connector, TokenSet: src.TokenSHA256 != "", KeyFields: []string{},
|
||||
Verification: src.Verification, HMACHeader: src.HMACHeader, HMACPrefix: src.HMACPrefix, HMACSecretSet: len(src.HMACSecretSealed) > 0,
|
||||
DeliveryHeader: src.DeliveryHeader, Signing: signingOf(src), Capture: src.Capture,
|
||||
|
||||
@@ -29,7 +29,6 @@ func (m *Module) registerSourceSettings(api huma.API) {
|
||||
}
|
||||
admin := httpapi.AdminAuthorized[governance.Action, governance.ResourceKind]
|
||||
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-label", http.MethodPut, "/api/sources/{id}/label", "Rename a source"), m.setSourceLabel)
|
||||
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-webhook-path", http.MethodPut, "/api/sources/{id}/webhook-path", "Move the address a source receives deliveries at"), m.setWebhookPath)
|
||||
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-delivery-header", http.MethodPut, "/api/sources/{id}/delivery-header", "Name the header a sender repeats when it retries a delivery"), m.setDeliveryHeader)
|
||||
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-capture", http.MethodPut, "/api/sources/{id}/capture", "Keep or stop keeping the headers and payloads a source receives"), m.setCapture)
|
||||
httpapi.Register(api, admin(governance.ActionUpdate, governance.KindSource), op("set-source-signing", http.MethodPost, "/api/sources/{id}/signing", "Require an HMAC signature, or ask to take unsigned deliveries"), m.setSigning)
|
||||
@@ -132,27 +131,6 @@ func (m *Module) setSourceLabel(ctx context.Context, in *sourceLabelInput) (*htt
|
||||
return m.sourceReply(ctx, in.ID, "")
|
||||
}
|
||||
|
||||
type webhookPathInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
Path string `json:"path" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it. Senders must post to the new address."`
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Module) setWebhookPath(ctx context.Context, in *webhookPathInput) (*httpapi.Reply[sourceView], error) {
|
||||
src, err := m.readSource(ctx, in.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !validName.MatchString(in.Body.Path) {
|
||||
return nil, huma.Error400BadRequest("a webhook path is lowercase letters, digits and hyphens")
|
||||
}
|
||||
if err := sourceWriteError(m.store.SetWebhookPath(ctx, m.orgID, src.ID, in.Body.Path)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m.sourceReply(ctx, in.ID, "")
|
||||
}
|
||||
|
||||
type deliveryHeaderInput struct {
|
||||
ID string `path:"id" format:"uuid"`
|
||||
Body struct {
|
||||
@@ -299,7 +277,7 @@ func sourceWriteError(err error) error {
|
||||
return nil
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
return huma.Error404NotFound("no such source")
|
||||
case errors.Is(err, store.ErrLabelTaken), errors.Is(err, store.ErrPathTaken):
|
||||
case errors.Is(err, store.ErrLabelTaken):
|
||||
return huma.Error409Conflict(err.Error())
|
||||
}
|
||||
return huma.Error500InternalServerError("couldn't save the source", err)
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestIntakeRecordsHowEachDeliveryWasVerified(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := store.Source{ID: hookID, OrgID: "org", WebhookPath: "hook", Connector: "c", Capture: true}
|
||||
base := store.Source{ID: hookID, OrgID: "org", Connector: "c", Capture: true}
|
||||
hmacSource := base
|
||||
hmacSource.Verification, hmacSource.HMACHeader, hmacSource.HMACPrefix, hmacSource.HMACSecretSealed = store.HMAC, "X-Signature", "sha256=", sealed
|
||||
tokenSource := base
|
||||
|
||||
@@ -47,7 +47,7 @@ func TestIntakeEvaluatesThePolicyAgainstTheClientBehindTrustedProxies(t *testing
|
||||
policy := &deliveryPolicy{decision: governance.Allowed()}
|
||||
m := &Module{
|
||||
orgID: "default", log: slog.New(slog.DiscardHandler), inserter: &onceInserter{stored: map[string]bool{}}, deliveries: noEcho{},
|
||||
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", WebhookPath: "hook", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
|
||||
reader: fakeSources{store.Source{ID: hookID, OrgID: "default", Connector: "c", Verification: store.Token, TokenSHA256: httpjson.TokenHash(token)}},
|
||||
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
|
||||
return []connectors.Event{{Type: "alert", SourceEventID: "evt-1"}}, nil
|
||||
},
|
||||
|
||||
@@ -117,8 +117,7 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Con
|
||||
return m
|
||||
}
|
||||
|
||||
// sourceReader looks up a source by the webhook path a delivery addressed, or
|
||||
// by its id for a stored event.
|
||||
// sourceReader looks up sources by ID or an existing webhook alias.
|
||||
type sourceReader interface {
|
||||
SourceByPath(ctx context.Context, orgID, path string) (store.Source, error)
|
||||
Source(ctx context.Context, orgID string, id uuid.UUID) (store.Source, error)
|
||||
@@ -134,12 +133,28 @@ type eventInserter interface {
|
||||
// sender address, who may deliver. Until it is set every delivery is refused.
|
||||
func (m *Module) UseDeliveryPolicy(d governance.DeliveryAuthorizer) { m.delivery = d }
|
||||
|
||||
// Routes adds the webhook intake. It stays outside the API because each
|
||||
// source verifies its own deliveries.
|
||||
const webhookPrefix = "/hooks/id/"
|
||||
|
||||
func webhookURL(id uuid.UUID) string { return webhookPrefix + id.String() }
|
||||
|
||||
// Routes adds the webhook intake outside the API because sources verify their own deliveries.
|
||||
func (m *Module) Routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST "+webhookPrefix+"{sourceID}", m.intake)
|
||||
// Keep issued URLs working without letting an alias shadow a UUID route.
|
||||
mux.HandleFunc("POST /hooks/{path}", m.intake)
|
||||
}
|
||||
|
||||
func (m *Module) webhookSource(r *http.Request) (store.Source, error) {
|
||||
if path := r.PathValue("path"); path != "" {
|
||||
return m.reader.SourceByPath(r.Context(), m.orgID, path)
|
||||
}
|
||||
id, err := uuid.Parse(r.PathValue("sourceID"))
|
||||
if err != nil {
|
||||
return store.Source{}, store.ErrNotFound
|
||||
}
|
||||
return m.reader.Source(r.Context(), m.orgID, id)
|
||||
}
|
||||
|
||||
// intake verifies a delivery, checks the source's delivery policy, parses it
|
||||
// with the source's connector and stores each event before responding. A
|
||||
// redelivered event violates a uniqueness constraint, is counted as a
|
||||
@@ -175,7 +190,7 @@ type delivery struct {
|
||||
// caller cannot use it to discover webhook paths.
|
||||
func (m *Module) accept(r *http.Request) (d delivery, status int, err error) {
|
||||
ctx := r.Context()
|
||||
src, err := m.reader.SourceByPath(ctx, m.orgID, r.PathValue("path"))
|
||||
src, err := m.webhookSource(r)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return d, http.StatusUnauthorized, errUnknown
|
||||
}
|
||||
|
||||
@@ -19,12 +19,8 @@ var ErrInUse = errors.New("in use")
|
||||
// ErrExists means a row with that name already exists.
|
||||
var ErrExists = errors.New("already exists")
|
||||
|
||||
// ErrLabelTaken and ErrPathTaken mean another source of the same scope has the
|
||||
// label, or another source has the webhook path.
|
||||
var (
|
||||
ErrLabelTaken = errors.New("a source with that label already exists")
|
||||
ErrPathTaken = errors.New("a source with that webhook path already exists")
|
||||
)
|
||||
// ErrLabelTaken means another source of the same scope has the label.
|
||||
var ErrLabelTaken = errors.New("a source with that label already exists")
|
||||
|
||||
// Postgres reports a delete blocked by ON DELETE RESTRICT as 23001 and a
|
||||
// reference to a missing row as 23503.
|
||||
@@ -48,13 +44,9 @@ func classify(err error) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// classifySource turns a unique violation on a source's label or webhook path
|
||||
// into its sentinel.
|
||||
// classifySource translates a conflicting source label into ErrLabelTaken.
|
||||
func classifySource(err error) error {
|
||||
if pqErr, ok := errors.AsType[*pgconn.PgError](err); ok && pqErr.Code == uniqueViolation {
|
||||
if pqErr.ConstraintName == "sources_webhook_path_key" {
|
||||
return ErrPathTaken
|
||||
}
|
||||
return ErrLabelTaken
|
||||
}
|
||||
return err
|
||||
@@ -285,12 +277,6 @@ func (s *Store) SetLabel(ctx context.Context, orgID string, id uuid.UUID, label
|
||||
return s.setSource(ctx, orgID, id, "label", label)
|
||||
}
|
||||
|
||||
// SetWebhookPath moves the address a source receives deliveries at. Stored
|
||||
// events, event types and triggers refer to the source by id and are unaffected.
|
||||
func (s *Store) SetWebhookPath(ctx context.Context, orgID string, id uuid.UUID, path string) error {
|
||||
return s.setSource(ctx, orgID, id, "webhook_path", path)
|
||||
}
|
||||
|
||||
// SetDeliveryHeader names the header a sender repeats on a delivery's retries.
|
||||
func (s *Store) SetDeliveryHeader(ctx context.Context, orgID string, id uuid.UUID, header string) error {
|
||||
return s.setSource(ctx, orgID, id, "delivery_header", header)
|
||||
|
||||
@@ -41,10 +41,8 @@ type Source struct {
|
||||
// PersonID is the owning person of a person source, null for an
|
||||
// organisation's.
|
||||
PersonID sql.NullString `db:"person_id"`
|
||||
// Label is the name people see, unique within the scope. WebhookPath is the
|
||||
// last segment of the URL deliveries post to, unique across the instance.
|
||||
Label string `db:"label"`
|
||||
WebhookPath string `db:"webhook_path"`
|
||||
// Label is the name people see, unique within the scope.
|
||||
Label string `db:"label"`
|
||||
// Connector is the connector's immutable package identifier, never renamed
|
||||
// and never given to a different package.
|
||||
Connector string `db:"connector"`
|
||||
@@ -161,7 +159,7 @@ type Store struct {
|
||||
// New returns a store on db.
|
||||
func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
||||
|
||||
const sourceColumns = `id, scope, org_id, person_id, label, webhook_path, connector, token_sha256, verification,
|
||||
const sourceColumns = `id, scope, org_id, person_id, label, connector, token_sha256, verification,
|
||||
hmac_header, hmac_prefix, hmac_secret_sealed, cursor, key_fields, delivery_header, unsigned_approved, capture`
|
||||
|
||||
// Source returns one source of the organisation, whoever owns it. Callers that
|
||||
@@ -178,7 +176,7 @@ func (s *Store) Source(ctx context.Context, orgID string, id uuid.UUID) (Source,
|
||||
return src, nil
|
||||
}
|
||||
|
||||
// SourceByPath returns the source a webhook path addresses.
|
||||
// SourceByPath resolves a previously issued webhook alias.
|
||||
func (s *Store) SourceByPath(ctx context.Context, orgID, path string) (Source, error) {
|
||||
var src Source
|
||||
err := s.db.GetContext(ctx, &src, `SELECT `+sourceColumns+` FROM events.sources WHERE org_id = $1 AND webhook_path = $2`, orgID, path)
|
||||
@@ -223,13 +221,12 @@ func (s *Store) SetCursor(ctx context.Context, orgID string, id uuid.UUID, curso
|
||||
return nil
|
||||
}
|
||||
|
||||
// InsertSource stores a new source. It returns ErrLabelTaken or ErrPathTaken
|
||||
// when the label or the webhook path is in use.
|
||||
// InsertSource stores a new source. It returns ErrLabelTaken when the label is in use.
|
||||
func (s *Store) InsertSource(ctx context.Context, src Source) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO events.sources (id, scope, org_id, person_id, label, webhook_path, connector, token_sha256,
|
||||
INSERT INTO events.sources (id, scope, org_id, person_id, label, connector, token_sha256,
|
||||
verification, hmac_header, hmac_prefix, hmac_secret_sealed)
|
||||
VALUES (:id, :scope, :org_id, :person_id, :label, :webhook_path, :connector, :token_sha256,
|
||||
VALUES (:id, :scope, :org_id, :person_id, :label, :connector, :token_sha256,
|
||||
:verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)`, src); err != nil {
|
||||
return fmt.Errorf("save source: %w", classifySource(err))
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ func TestListenedEventsPassTheDeliveryPolicyBeforeStoring(t *testing.T) {
|
||||
if !tt.unwired {
|
||||
m.UseDeliveryPolicy(policy)
|
||||
}
|
||||
src := store.Source{ID: hookID, OrgID: "default", WebhookPath: "tg", Connector: "telegram"}
|
||||
src := store.Source{ID: hookID, OrgID: "default", Connector: "telegram"}
|
||||
err := m.storeListened(t.Context(), src, []connectors.Event{{Type: "message", SourceEventID: "evt-1"}})
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("error = %v, want error %v", err, tt.wantErr)
|
||||
|
||||
@@ -34,7 +34,7 @@ func (f fakeSources) Source(_ context.Context, _ string, id uuid.UUID) (store.So
|
||||
}
|
||||
|
||||
func (f fakeSources) SourceByPath(_ context.Context, _, path string) (store.Source, error) {
|
||||
if path != f.src.WebhookPath {
|
||||
if path != "hook" {
|
||||
return store.Source{}, store.ErrNotFound
|
||||
}
|
||||
return f.src, nil
|
||||
@@ -65,23 +65,28 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := store.Source{
|
||||
ID: hookID, OrgID: "org", WebhookPath: "hook", Connector: "c", Verification: store.HMAC,
|
||||
ID: hookID, OrgID: "org", Label: "monitoring", Connector: "c", Verification: store.HMAC,
|
||||
HMACHeader: "X-Signature", HMACPrefix: "sha256=", HMACSecretSealed: sealed,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
path string
|
||||
header string
|
||||
wantCode int
|
||||
wantParse bool
|
||||
}{
|
||||
{"correct signature", "sha256=" + sign(secret, body), 0, true},
|
||||
{"correct signature in upper case", "sha256=" + strings.ToUpper(sign(secret, body)), 0, true},
|
||||
{"missing signature", "", http.StatusUnauthorized, false},
|
||||
{"wrong secret", "sha256=" + sign("other-secret", body), http.StatusUnauthorized, false},
|
||||
{"signature of another body", "sha256=" + sign(secret, `{"id":"2"}`), http.StatusUnauthorized, false},
|
||||
{"missing prefix", sign(secret, body), http.StatusUnauthorized, false},
|
||||
{"not hex", "sha256=zz", http.StatusUnauthorized, false},
|
||||
{"correct signature", "", "sha256=" + sign(secret, body), http.StatusAccepted, true},
|
||||
{"correct signature in upper case", "", "sha256=" + strings.ToUpper(sign(secret, body)), http.StatusAccepted, true},
|
||||
{"existing webhook URL", "/hooks/hook", "sha256=" + sign(secret, body), http.StatusAccepted, true},
|
||||
{"display name is not a URL", "/hooks/monitoring", "sha256=" + sign(secret, body), http.StatusUnauthorized, false},
|
||||
{"invalid UUID", "/hooks/id/monitoring", "sha256=" + sign(secret, body), http.StatusUnauthorized, false},
|
||||
{"unknown UUID", "/hooks/id/" + uuid.Nil.String(), "sha256=" + sign(secret, body), http.StatusUnauthorized, false},
|
||||
{"missing signature", "", "", http.StatusUnauthorized, false},
|
||||
{"wrong secret", "", "sha256=" + sign("other-secret", body), http.StatusUnauthorized, false},
|
||||
{"signature of another body", "", "sha256=" + sign(secret, `{"id":"2"}`), http.StatusUnauthorized, false},
|
||||
{"missing prefix", "", sign(secret, body), http.StatusUnauthorized, false},
|
||||
{"not hex", "", "sha256=zz", http.StatusUnauthorized, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
@@ -94,14 +99,20 @@ func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/hooks/hook", strings.NewReader(body))
|
||||
req.SetPathValue("path", "hook")
|
||||
path := tt.path
|
||||
if path == "" {
|
||||
path = "/hooks/id/" + hookID.String()
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, path, strings.NewReader(body))
|
||||
if tt.header != "" {
|
||||
req.Header.Set("X-Signature", tt.header)
|
||||
}
|
||||
_, code, err := m.accept(req)
|
||||
if code != tt.wantCode || (err != nil) != (tt.wantCode != 0) {
|
||||
t.Fatalf("status %d, error %v; want status %d", code, err, tt.wantCode)
|
||||
mux := http.NewServeMux()
|
||||
m.Routes(mux)
|
||||
res := httptest.NewRecorder()
|
||||
mux.ServeHTTP(res, req)
|
||||
if res.Code != tt.wantCode {
|
||||
t.Fatalf("status %d; want %d", res.Code, tt.wantCode)
|
||||
}
|
||||
if parsed != tt.wantParse {
|
||||
t.Fatalf("connector parsed = %v, want %v", parsed, tt.wantParse)
|
||||
|
||||
Reference in new issue
Block a user