fix(events): verify webhook signatures before parsing (#2021)
A source now declares how its deliveries prove themselves: token (the default, unchanged), hmac (HMAC-SHA256 over the raw body, per-source header and prefix, secret sealed at rest and write-only) or none. The events module verifies before the connector parses, answers 401 and logs the refusal. The digest comparison is ported from internal/webhookguard/hmac.go and the header-borne signature from internal/infrastructure/captureintake/receiver.go; the old copies stay until their service goes. The seal package moves to internal/platform/seal so events can seal the secret.
This commit is contained in:
15 files changed
+415
-65
No files matched your search
@@ -9,7 +9,7 @@ import (
|
||||
|
||||
"filippo.io/age"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/seal"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
// Package seal encrypts credentials at rest with age. Each sealed value is
|
||||
// bound to a label naming where it is stored, so a value copied into another
|
||||
// row doesn't open there.
|
||||
package seal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
json "encoding/json/v2"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
// ErrWrongLabel means a sealed value was opened under a label other than the
|
||||
// one it was sealed for.
|
||||
var ErrWrongLabel = errors.New("sealed value belongs to a different record")
|
||||
|
||||
// Sealer seals to its own identity and to any backup recipients, and opens
|
||||
// with its identity.
|
||||
type Sealer struct {
|
||||
identity *age.X25519Identity
|
||||
recipients []age.Recipient
|
||||
}
|
||||
|
||||
// New returns a sealer for an age identity ("AGE-SECRET-KEY-1...") and the
|
||||
// backup recipients ("age1...") that can also open what it seals.
|
||||
func New(identity string, backups []string) (*Sealer, error) {
|
||||
id, err := age.ParseX25519Identity(identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("age identity: %w", err)
|
||||
}
|
||||
s := &Sealer{identity: id, recipients: []age.Recipient{id.Recipient()}}
|
||||
for _, b := range backups {
|
||||
r, err := age.ParseX25519Recipient(b)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("backup recipient %q: %w", b, err)
|
||||
}
|
||||
s.recipients = append(s.recipients, r)
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
Label string `json:"label"`
|
||||
Data []byte `json:"data"`
|
||||
}
|
||||
|
||||
// Seal encrypts data for label.
|
||||
func (s *Sealer) Seal(label string, data []byte) ([]byte, error) {
|
||||
plain, err := json.Marshal(envelope{Label: label, Data: data})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out bytes.Buffer
|
||||
w, err := age.Encrypt(&out, s.recipients...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
if _, err := w.Write(plain); err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return nil, fmt.Errorf("seal: %w", err)
|
||||
}
|
||||
return out.Bytes(), nil
|
||||
}
|
||||
|
||||
// Open decrypts a value sealed for label.
|
||||
func (s *Sealer) Open(label string, sealed []byte) ([]byte, error) {
|
||||
r, err := age.Decrypt(bytes.NewReader(sealed), s.identity)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
plain, err := io.ReadAll(r)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
var env envelope
|
||||
if err := json.Unmarshal(plain, &env); err != nil {
|
||||
return nil, fmt.Errorf("open: %w", err)
|
||||
}
|
||||
if env.Label != label {
|
||||
return nil, ErrWrongLabel
|
||||
}
|
||||
return env.Data, nil
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package seal
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
)
|
||||
|
||||
// TestSealedValueOpensOnlyWhereItBelongs guards the credential store's
|
||||
// boundary: a sealed value opens with Archie's identity or a backup key, under
|
||||
// the label it was sealed for, and nowhere else. A value copied into another
|
||||
// row, or read with a stranger's key, stays shut.
|
||||
func TestSealedValueOpensOnlyWhereItBelongs(t *testing.T) {
|
||||
own, backup, stranger := identity(t), identity(t), identity(t)
|
||||
sealer, err := New(own.String(), []string{backup.Recipient().String()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
secret := []byte("plainly fake private key")
|
||||
sealed, err := sealer.Seal("default/host-a", secret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Contains(sealed, secret) {
|
||||
t.Fatal("sealed value contains the plaintext")
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
with *age.X25519Identity
|
||||
label string
|
||||
wantErr error
|
||||
}{
|
||||
{name: "own identity, own label", with: own, label: "default/host-a"},
|
||||
{name: "backup identity", with: backup, label: "default/host-a"},
|
||||
{name: "copied to another record", with: own, label: "default/host-b", wantErr: ErrWrongLabel},
|
||||
{name: "a stranger's identity", with: stranger, label: "default/host-a", wantErr: age.ErrIncorrectIdentity},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
opener, err := New(tt.with.String(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := opener.Open(tt.label, sealed)
|
||||
if tt.wantErr != nil {
|
||||
var noMatch *age.NoIdentityMatchError
|
||||
if !errors.Is(err, tt.wantErr) && !errors.As(err, &noMatch) {
|
||||
t.Fatalf("open = %v, want %v", err, tt.wantErr)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || !bytes.Equal(got, secret) {
|
||||
t.Fatalf("open = %q, %v", got, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func identity(t *testing.T) *age.X25519Identity {
|
||||
t.Helper()
|
||||
id, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/seal"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"filippo.io/age"
|
||||
"github.com/danielgtaylor/huma/v2"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/seal"
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
)
|
||||
|
||||
|
||||
+45
-12
@@ -29,7 +29,7 @@ func (m *Module) Register(api huma.API) {
|
||||
}, m.sources)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "put-source", Method: http.MethodPut, Path: "/api/sources/{name}",
|
||||
Summary: "Add a source or rotate its token", Tags: tags,
|
||||
Summary: "Add a source, or change how it verifies deliveries and rotate its token", Tags: tags,
|
||||
}, m.putSource)
|
||||
huma.Register(api, huma.Operation{
|
||||
OperationID: "put-source-key-fields", Method: http.MethodPut, Path: "/api/sources/{name}/key-fields",
|
||||
@@ -61,31 +61,57 @@ type putSourceInput struct {
|
||||
Name string `path:"name" doc:"Lowercase letters, digits and hyphens; the webhook URL ends in it"`
|
||||
Body struct {
|
||||
Connector string `json:"connector" doc:"The connector that parses this source's events"`
|
||||
// Verification defaults to a bearer token so a source that names none
|
||||
// keeps working.
|
||||
Verification string `json:"verification,omitzero" enum:"token,hmac,none" doc:"How a delivery proves itself: a bearer token, an HMAC-SHA256 signature of the body, or nothing"`
|
||||
HMACHeader string `json:"hmac_header,omitzero" doc:"The header that carries the signature, for hmac"`
|
||||
HMACPrefix string `json:"hmac_prefix,omitzero" doc:"Text before the hex digest in that header, such as sha256=, for hmac" example:"sha256="`
|
||||
HMACSecret string `json:"hmac_secret,omitzero" doc:"The shared signing secret, for hmac. Write-only: it is sealed and never returned"`
|
||||
}
|
||||
}
|
||||
|
||||
type sourceCreated struct {
|
||||
Source string `json:"source"`
|
||||
Token string `json:"token" doc:"Shown once; only its hash is stored"`
|
||||
Token string `json:"token,omitzero" doc:"Shown once, for a token source; only its hash is stored"`
|
||||
URL string `json:"url" doc:"Where the sender posts its events"`
|
||||
}
|
||||
|
||||
// putSource creates a source or rotates its token. The token is returned once
|
||||
// and stored only as its hash.
|
||||
// putSource creates a source or replaces how it verifies deliveries. A token
|
||||
// source's token is returned once and stored only as its hash. An hmac
|
||||
// source's secret is sealed and never returned.
|
||||
func (m *Module) putSource(ctx context.Context, in *putSourceInput) (*httpapi.Reply[sourceCreated], error) {
|
||||
if !validName.MatchString(in.Name) || !validName.MatchString(in.Body.Connector) {
|
||||
return nil, huma.Error400BadRequest("a source needs a lowercase name and a connector")
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't make a token", err)
|
||||
src := store.Source{OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector, Verification: in.Body.Verification}
|
||||
if src.Verification == "" {
|
||||
src.Verification = store.Token
|
||||
}
|
||||
if err := m.store.UpsertSource(ctx, store.Source{
|
||||
OrgID: m.orgID, Name: in.Name, Connector: in.Body.Connector, TokenSHA256: httpjson.TokenHash(token),
|
||||
}); err != nil {
|
||||
created := sourceCreated{Source: in.Name, URL: "/hooks/" + in.Name}
|
||||
switch src.Verification {
|
||||
case store.Token:
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't make a token", err)
|
||||
}
|
||||
src.TokenSHA256, created.Token = httpjson.TokenHash(token), token
|
||||
case store.HMAC:
|
||||
if in.Body.HMACHeader == "" || in.Body.HMACSecret == "" {
|
||||
return nil, huma.Error400BadRequest("an hmac source needs the signature header and a secret")
|
||||
}
|
||||
sealed, err := m.sealer.Seal(secretLabel(m.orgID, in.Name), []byte(in.Body.HMACSecret))
|
||||
if err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't seal the secret", err)
|
||||
}
|
||||
src.HMACHeader, src.HMACPrefix, src.HMACSecretSealed = in.Body.HMACHeader, in.Body.HMACPrefix, sealed
|
||||
case store.None:
|
||||
default:
|
||||
return nil, huma.Error400BadRequest("verification is token, hmac or none")
|
||||
}
|
||||
if err := m.store.UpsertSource(ctx, src); err != nil {
|
||||
return nil, huma.Error500InternalServerError("couldn't save the source", err)
|
||||
}
|
||||
return httpapi.OK(sourceCreated{Source: in.Name, Token: token, URL: "/hooks/" + in.Name}), nil
|
||||
return httpapi.OK(created), nil
|
||||
}
|
||||
|
||||
type putTriggerInput struct {
|
||||
@@ -212,6 +238,12 @@ type sourceView struct {
|
||||
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"`
|
||||
HMACHeader string `json:"hmac_header,omitzero"`
|
||||
HMACPrefix string `json:"hmac_prefix,omitzero"`
|
||||
HMACSecretSet bool `json:"hmac_secret_set"`
|
||||
}
|
||||
|
||||
func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sourceView], error) {
|
||||
@@ -222,7 +254,8 @@ func (m *Module) sources(ctx context.Context, _ *struct{}) (*httpapi.Reply[[]sou
|
||||
}
|
||||
out := make([]sourceView, 0, len(sources))
|
||||
for _, src := range sources {
|
||||
view := sourceView{Name: src.Name, Connector: src.Connector, TokenSet: src.TokenSHA256 != "", KeyFields: []string{}}
|
||||
view := sourceView{Name: src.Name, Connector: src.Connector, TokenSet: src.TokenSHA256 != "", KeyFields: []string{},
|
||||
Verification: src.Verification, HMACHeader: src.HMACHeader, HMACPrefix: src.HMACPrefix, HMACSecretSet: len(src.HMACSecretSealed) > 0}
|
||||
if len(src.KeyFields) > 0 {
|
||||
if err := json.Unmarshal(src.KeyFields, &view.KeyFields); err != nil {
|
||||
m.log.ErrorContext(ctx, "read source key fields", "source", src.Name, "error", err)
|
||||
|
||||
+86
-28
@@ -68,6 +68,9 @@ const listenRetry = 5 * time.Second
|
||||
type Module struct {
|
||||
orgID string
|
||||
store *store.Store
|
||||
reader sourceReader
|
||||
sealer Sealer
|
||||
parse func(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error)
|
||||
connectors Connectors
|
||||
runs Runs
|
||||
answers Answers
|
||||
@@ -77,43 +80,31 @@ type Module struct {
|
||||
}
|
||||
|
||||
// NewModule returns the events module for orgID.
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, c Connectors, r Runs, a Answers, d Deliveries) *Module {
|
||||
return &Module{orgID: orgID, store: store.New(db), connectors: c, runs: r, answers: a, deliveries: d, log: log, poll: time.Second}
|
||||
func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, sealer Sealer, c Connectors, r Runs, a Answers, d Deliveries) *Module {
|
||||
st := store.New(db)
|
||||
m := &Module{orgID: orgID, store: st, reader: st, sealer: sealer, connectors: c, runs: r, answers: a, deliveries: d, log: log, poll: time.Second}
|
||||
m.parse = m.parseWith
|
||||
return m
|
||||
}
|
||||
|
||||
// sourceReader is the one read intake makes of the store.
|
||||
type sourceReader interface {
|
||||
Source(ctx context.Context, orgID, name string) (store.Source, error)
|
||||
}
|
||||
|
||||
// Routes adds the webhook intake. It stays outside the API because each
|
||||
// source verifies its own token before the body is read.
|
||||
// source verifies its own deliveries.
|
||||
func (m *Module) Routes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /hooks/{source}", m.intake)
|
||||
}
|
||||
|
||||
// intake verifies the source's token before reading the body, has the
|
||||
// source's connector parse it, and stores each event before answering. A
|
||||
// re-delivered event is a constraint conflict, counted as a duplicate.
|
||||
// intake has the source's connector parse a verified delivery and stores each
|
||||
// event before answering. A re-delivered event is a constraint conflict,
|
||||
// counted as a duplicate.
|
||||
func (m *Module) intake(w http.ResponseWriter, r *http.Request) {
|
||||
src, err := m.store.Source(r.Context(), m.orgID, r.PathValue("source"))
|
||||
if errors.Is(err, store.ErrNotFound) || (err == nil && !httpjson.TokenMatches(httpjson.Bearer(r), src.TokenSHA256)) {
|
||||
// Unknown source and wrong token answer alike, so neither is probed.
|
||||
httpjson.Error(w, http.StatusUnauthorized, "unknown source or wrong token")
|
||||
return
|
||||
}
|
||||
src, parsed, body, status, err := m.accept(r)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusServiceUnavailable, "events store unavailable")
|
||||
return
|
||||
}
|
||||
conn, ok := m.connectors.Get(src.Connector)
|
||||
if !ok {
|
||||
httpjson.Error(w, http.StatusServiceUnavailable, "connector "+src.Connector+" isn't running")
|
||||
return
|
||||
}
|
||||
body, err := httpjson.Body(r)
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusRequestEntityTooLarge, err.Error())
|
||||
return
|
||||
}
|
||||
parsed, err := conn.Parse(r.Context(), body, map[string]string{"Content-Type": r.Header.Get("Content-Type")})
|
||||
if err != nil {
|
||||
httpjson.Error(w, http.StatusBadRequest, err.Error())
|
||||
httpjson.Error(w, status, err.Error())
|
||||
return
|
||||
}
|
||||
stored, duplicates, err := m.save(r.Context(), src, parsed, body)
|
||||
@@ -124,6 +115,73 @@ func (m *Module) intake(w http.ResponseWriter, r *http.Request) {
|
||||
httpjson.Write(w, http.StatusAccepted, map[string]int{"stored": stored, "duplicates": duplicates})
|
||||
}
|
||||
|
||||
// accept verifies a delivery against its source's scheme, then has the
|
||||
// connector parse it. A delivery that fails verification is refused with 401
|
||||
// before the connector sees its body, and the refusal is logged. An unknown
|
||||
// source and a failed delivery answer alike, so neither is probed.
|
||||
func (m *Module) accept(r *http.Request) (src store.Source, parsed []connectors.Event, body []byte, status int, err error) {
|
||||
ctx := r.Context()
|
||||
src, err = m.reader.Source(ctx, m.orgID, r.PathValue("source"))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return src, nil, nil, http.StatusUnauthorized, errUnknown
|
||||
}
|
||||
if err != nil {
|
||||
return src, nil, nil, http.StatusServiceUnavailable, errors.New("events store unavailable")
|
||||
}
|
||||
// A token is checked before the body is read. A signature covers the body,
|
||||
// so it is checked on the raw bytes as soon as they are read.
|
||||
switch src.Verification {
|
||||
case store.Token:
|
||||
if err := checkToken(src, r); err != nil {
|
||||
return m.refuse(ctx, src, err)
|
||||
}
|
||||
case store.HMAC, store.None:
|
||||
default:
|
||||
return m.refuse(ctx, src, fmt.Errorf("unknown verification %q", src.Verification))
|
||||
}
|
||||
body, err = httpjson.Body(r)
|
||||
if err != nil {
|
||||
return src, nil, nil, http.StatusRequestEntityTooLarge, err
|
||||
}
|
||||
if src.Verification == store.HMAC {
|
||||
if err := m.verifyHMAC(src, r.Header, body); err != nil {
|
||||
return m.refuse(ctx, src, err)
|
||||
}
|
||||
}
|
||||
parsed, err = m.parse(ctx, src.Connector, body, map[string]string{"Content-Type": r.Header.Get("Content-Type")})
|
||||
if errors.Is(err, errConnectorDown) {
|
||||
return src, nil, nil, http.StatusServiceUnavailable, err
|
||||
}
|
||||
if err != nil {
|
||||
return src, nil, nil, http.StatusBadRequest, err
|
||||
}
|
||||
return src, parsed, body, 0, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errUnknown = errors.New("unknown source or failed verification")
|
||||
errConnectorDown = errors.New("connector isn't running")
|
||||
)
|
||||
|
||||
// refuse logs why a delivery was turned away and picks its status: 401 when it
|
||||
// failed to prove itself, 503 when verification couldn't run.
|
||||
func (m *Module) refuse(ctx context.Context, src store.Source, err error) (store.Source, []connectors.Event, []byte, int, error) {
|
||||
m.log.WarnContext(ctx, "refused webhook delivery", "source", src.Name, "verification", src.Verification, "reason", err.Error())
|
||||
if errors.Is(err, errUnverified) {
|
||||
return src, nil, nil, http.StatusUnauthorized, errUnknown
|
||||
}
|
||||
return src, nil, nil, http.StatusServiceUnavailable, errors.New("couldn't verify the delivery")
|
||||
}
|
||||
|
||||
// parseWith has a running connector parse a delivery.
|
||||
func (m *Module) parseWith(ctx context.Context, connector string, body []byte, headers map[string]string) ([]connectors.Event, error) {
|
||||
conn, ok := m.connectors.Get(connector)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("connector %s: %w", connector, errConnectorDown)
|
||||
}
|
||||
return conn.Parse(ctx, body, headers)
|
||||
}
|
||||
|
||||
// save stores each event with the payload it arrived in, recording at arrival
|
||||
// whether it echoes a delivery Archie sent, so those never reach grouping.
|
||||
func (m *Module) save(ctx context.Context, src store.Source, parsed []connectors.Event, body []byte) (stored, duplicates int, err error) {
|
||||
|
||||
@@ -18,12 +18,26 @@ import (
|
||||
// ErrNotFound means the named row doesn't exist.
|
||||
var ErrNotFound = errors.New("not found")
|
||||
|
||||
// The ways a source verifies a delivery.
|
||||
const (
|
||||
Token = "token"
|
||||
HMAC = "hmac"
|
||||
None = "none"
|
||||
)
|
||||
|
||||
// Source is a named place events come from, read by one connector.
|
||||
type Source struct {
|
||||
OrgID string `db:"org_id"`
|
||||
Name string `db:"name"`
|
||||
Connector string `db:"connector"`
|
||||
TokenSHA256 string `db:"token_sha256"`
|
||||
// Verification is how a delivery proves itself: Token, HMAC or None.
|
||||
Verification string `db:"verification"`
|
||||
// HMACHeader carries the signature, HMACPrefix precedes its hex digest,
|
||||
// and HMACSecretSealed is the shared secret, sealed.
|
||||
HMACHeader string `db:"hmac_header"`
|
||||
HMACPrefix string `db:"hmac_prefix"`
|
||||
HMACSecretSealed []byte `db:"hmac_secret_sealed"`
|
||||
// Cursor is where a listening source resumes.
|
||||
Cursor string `db:"cursor"`
|
||||
// KeyFields are the paths its events are grouped by; none means the default.
|
||||
@@ -86,7 +100,7 @@ func New(db *sqlx.DB) *Store { return &Store{db: db} }
|
||||
func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error) {
|
||||
var src Source
|
||||
err := s.db.GetContext(ctx, &src, `
|
||||
SELECT org_id, name, connector, token_sha256, key_fields FROM events.sources
|
||||
SELECT org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed, key_fields FROM events.sources
|
||||
WHERE org_id = $1 AND name = $2`, orgID, name)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return Source{}, ErrNotFound
|
||||
@@ -101,7 +115,7 @@ func (s *Store) Source(ctx context.Context, orgID, name string) (Source, error)
|
||||
func (s *Store) Sources(ctx context.Context, orgID string) ([]Source, error) {
|
||||
var out []Source
|
||||
if err := s.db.SelectContext(ctx, &out, `
|
||||
SELECT org_id, name, connector, token_sha256, cursor, key_fields FROM events.sources
|
||||
SELECT org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed, cursor, key_fields FROM events.sources
|
||||
WHERE org_id = $1 ORDER BY name`, orgID); err != nil {
|
||||
return nil, fmt.Errorf("list sources: %w", err)
|
||||
}
|
||||
@@ -121,10 +135,13 @@ func (s *Store) SetCursor(ctx context.Context, orgID, name, cursor string) error
|
||||
// UpsertSource creates a source or replaces its connector and token.
|
||||
func (s *Store) UpsertSource(ctx context.Context, src Source) error {
|
||||
if _, err := s.db.NamedExecContext(ctx, `
|
||||
INSERT INTO events.sources (org_id, name, connector, token_sha256)
|
||||
VALUES (:org_id, :name, :connector, :token_sha256)
|
||||
INSERT INTO events.sources (org_id, name, connector, token_sha256, verification, hmac_header, hmac_prefix, hmac_secret_sealed)
|
||||
VALUES (:org_id, :name, :connector, :token_sha256, :verification, :hmac_header, :hmac_prefix, :hmac_secret_sealed)
|
||||
ON CONFLICT (org_id, name) DO UPDATE
|
||||
SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256, updated_at = now()`, src); err != nil {
|
||||
SET connector = EXCLUDED.connector, token_sha256 = EXCLUDED.token_sha256,
|
||||
verification = EXCLUDED.verification, hmac_header = EXCLUDED.hmac_header,
|
||||
hmac_prefix = EXCLUDED.hmac_prefix, hmac_secret_sealed = EXCLUDED.hmac_secret_sealed,
|
||||
updated_at = now()`, src); err != nil {
|
||||
return fmt.Errorf("save source: %w", err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||
)
|
||||
|
||||
// Sealer keeps a source's signing secret encrypted at rest. A sealed value
|
||||
// opens only under the label it was sealed for.
|
||||
type Sealer interface {
|
||||
Seal(label string, data []byte) ([]byte, error)
|
||||
Open(label string, sealed []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// secretLabel binds a sealed secret to its source, so a value copied into
|
||||
// another row doesn't open there.
|
||||
func secretLabel(orgID, name string) string {
|
||||
return "events.sources/" + orgID + "/" + name + "/hmac"
|
||||
}
|
||||
|
||||
// errUnverified means a delivery didn't prove itself. Its text is safe to
|
||||
// log: it names the scheme, never a secret or a signature.
|
||||
var errUnverified = errors.New("delivery not verified")
|
||||
|
||||
// checkToken verifies a token source before its body is read.
|
||||
func checkToken(src store.Source, r *http.Request) error {
|
||||
if !httpjson.TokenMatches(httpjson.Bearer(r), src.TokenSHA256) {
|
||||
return fmt.Errorf("%w: wrong or missing bearer token", errUnverified)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// verifyHMAC checks the signature header against an HMAC-SHA256 of the raw
|
||||
// body, which the connector hasn't seen yet. The header holds the hex digest
|
||||
// after the source's prefix, in either case. An absent or malformed
|
||||
// signature never verifies.
|
||||
//
|
||||
// Ported from internal/webhookguard/hmac.go (digest comparison) and
|
||||
// internal/infrastructure/captureintake/receiver.go (header-borne signature),
|
||||
// with the header and prefix set per source.
|
||||
func (m *Module) verifyHMAC(src store.Source, h http.Header, body []byte) error {
|
||||
secret, err := m.sealer.Open(secretLabel(src.OrgID, src.Name), src.HMACSecretSealed)
|
||||
if err != nil {
|
||||
return fmt.Errorf("open signing secret: %w", err)
|
||||
}
|
||||
signature := h.Get(src.HMACHeader)
|
||||
if signature == "" {
|
||||
return fmt.Errorf("%w: no %s header", errUnverified, src.HMACHeader)
|
||||
}
|
||||
digest, ok := strings.CutPrefix(signature, src.HMACPrefix)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: signature lacks the expected prefix", errUnverified)
|
||||
}
|
||||
supplied, err := hex.DecodeString(digest)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: signature isn't hex", errUnverified)
|
||||
}
|
||||
mac := hmac.New(sha256.New, secret)
|
||||
mac.Write(body)
|
||||
// Digests are compared as bytes, in constant time.
|
||||
if !hmac.Equal(supplied, mac.Sum(nil)) {
|
||||
return fmt.Errorf("%w: signature doesn't match", errUnverified)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"filippo.io/age"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/events/internal/store"
|
||||
)
|
||||
|
||||
type fakeSources struct{ src store.Source }
|
||||
|
||||
func (f fakeSources) Source(context.Context, string, string) (store.Source, error) {
|
||||
return f.src, nil
|
||||
}
|
||||
|
||||
func sign(secret, body string) string {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write([]byte(body))
|
||||
return hex.EncodeToString(mac.Sum(nil))
|
||||
}
|
||||
|
||||
// TestHMACSourceVerifiesBeforeParsing guards the invariant that a webhook's
|
||||
// signature is checked on the raw body before the connector sees it: a wrong
|
||||
// or missing signature answers 401 and Parse never runs.
|
||||
func TestHMACSourceVerifiesBeforeParsing(t *testing.T) {
|
||||
const secret = "not-a-real-secret" //nolint:gosec // fixture signing secret the verifier must accept
|
||||
const body = `{"id":"1"}`
|
||||
id, err := age.GenerateX25519Identity()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealer, err := seal.New(id.String(), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sealed, err := sealer.Seal(secretLabel("org", "hook"), []byte(secret))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
src := store.Source{
|
||||
OrgID: "org", Name: "hook", Connector: "c", Verification: store.HMAC,
|
||||
HMACHeader: "X-Signature", HMACPrefix: "sha256=", HMACSecretSealed: sealed,
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name 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},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
parsed := false
|
||||
m := &Module{
|
||||
orgID: "org", reader: fakeSources{src}, sealer: sealer,
|
||||
log: slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
parse: func(context.Context, string, []byte, map[string]string) ([]connectors.Event, error) {
|
||||
parsed = true
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequest(http.MethodPost, "/hooks/hook", strings.NewReader(body))
|
||||
req.SetPathValue("source", "hook")
|
||||
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)
|
||||
}
|
||||
if parsed != tt.wantParse {
|
||||
t.Fatalf("connector parsed = %v, want %v", parsed, tt.wantParse)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user