Files
archie/modules/events/verify.go
T
sam 9c04b74e6f docs: fix Vale prose findings across comments, docs and prompts
Run Vale over every tracked Go, Markdown and template file and fix the remaining findings: long sentences, repetition, UI verbs, identifiers that should be backticked, and migration narration in comments.

AGENTS.md and CLAUDE.md keep their absolute rules; the prompt heuristic against repeated absolutes is disabled for rule files.
2026-11-24 03:26:16 +11:00

75 lines
2.4 KiB
Go

package events
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"net/http"
"strings"
"github.com/google/uuid"
"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 string, sourceID uuid.UUID) string {
return "events.sources/" + orgID + "/" + sourceID.String() + "/hmac"
}
// errUnverified means a delivery failed verification. 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, before the connector sees it. The header holds the hex digest, in
// either case, after the source's prefix. A missing or malformed signature
// always fails.
//
// The header and its prefix are set per source, and the digest is compared in
// constant time.
func (m *Module) verifyHMAC(src store.Source, h http.Header, body []byte) error {
secret, err := m.sealer.Open(secretLabel(src.OrgID, src.ID), 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
}