Files
archie/internal/channels/webhook/webhook.go
T
sam c70fb61bfc fix(gateway): stamp the session platform from the channel that carried the message
One Router serves every channel and named itself "web", so Source.Platform -- the
FIRST component of the session natural key, and the platform GetByChannel filters
on -- was a constant, true of no channel but the dashboard. Two consequences
followed: the per-user identity policy was real code that no production call site
reached with a real channel name, and a curator pass's write to agent-user memory
could not be read back by the turn that wrote it, because that turn resolved no
UserID.

The channel now travels with the message. Frontends name the channel they carry
(pb.Message.platform: telegram, email, webhook, web), and the Gateway stamps the
session from it, falling back to its own name when a sender names none -- which is
what every existing row holds and what a frontend that does not participate keeps
doing.

Identity resolution reads the platform off the inbound rather than closing over a
channel name, so carriesPersonIdentity finally decides something in production:
telegram and email resolve a person, the dashboard and a webhook resolve nothing,
and an unknown platform fails closed.

Deliberately NOT changed, because it is where this could quietly widen scope:
TurnRunnerConfig.Channel still keys tool availability, so no channel gains or
loses a tool here. Only session lookup and identity follow the message's platform.

Consequence the maintainer accepted: a chat whose active session came from /new or
/branch re-resolves once, since GetByChannel now filters on the channel's name. A
chat with no /new re-resolves onto the same deterministic session id and heals
silently.

Verified: gateway, archied, gatewayrpc, messaging, webui, channels and cmd suites,
go vet ./..., go build ./..., golangci-lint run ./... (0 issues), docs:check.
New contracts: TestResolveSessionKeyStampsTheMessagesPlatform, the per-platform
identity table, and the transport-context wire round trip.
2026-09-22 04:30:15 +10:00

274 lines
7.2 KiB
Go

// Package webhook implements gateway.Gateway for inbound HTTP webhooks.
// External services push messages into archie-core's gateway for LLM
// processing. Outbound delivery is not supported (deliver-only mode).
package webhook
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"strings"
"sync"
"time"
"github.com/samcharles93/archie-core/internal/channels"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/webhookguard"
)
// Gateway is a deliver-only webhook gateway. It listens for HTTP POST
// requests, validates their HMAC signatures, and routes the extracted
// text through the messaging ChatContract for LLM processing.
type Gateway struct {
Host string
Port int
Routes []RouteConfig
log *slog.Logger
server *http.Server
client messaging.ChatContract
mu sync.Mutex
}
// RouteConfig defines one webhook endpoint.
type RouteConfig struct {
// Path is the URL path (e.g. "/github").
Path string
// Secret is the HMAC-SHA256 secret for payload validation.
// Empty = no validation.
Secret string
// Template extracts the message text from the JSON payload.
// Uses dot-notation: "issue.title" or "comment.body".
// Empty = use the raw body as message text.
Template string
// DeliverTo routes replies: "origin" (HTTP response) or empty (no reply).
DeliverTo string
}
// New returns an unstarted Gateway. Call Start to begin listening.
func New(host string, port int, routes []RouteConfig, log *slog.Logger) *Gateway {
if host == "" {
host = "0.0.0.0"
}
return &Gateway{
Host: host,
Port: port,
Routes: routes,
log: log.With("component", "gateway-webhook"),
}
}
func (g *Gateway) Name() string { return "webhook" }
// Start begins listening on the configured host:port. Blocks until ctx
// is cancelled.
func (g *Gateway) Start(ctx context.Context, client messaging.ChatContract, lifecycle channels.Lifecycle) error {
lifecycle.ReportStarting()
g.mu.Lock()
g.client = client
mux := http.NewServeMux()
for i := range g.Routes {
route := g.Routes[i] // capture
mux.HandleFunc(route.Path, g.handleWebhook(&route))
}
addr := fmt.Sprintf("%s:%d", g.Host, g.Port)
g.server = &http.Server{Addr: addr, Handler: mux}
server := g.server
g.mu.Unlock()
lc := net.ListenConfig{}
ln, err := lc.Listen(ctx, "tcp", addr)
if err != nil {
return fmt.Errorf("webhook: listen: %w", err)
}
g.log.Info("webhook gateway listening", "addr", addr)
lifecycle.ReportRunning()
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
}()
err = server.Serve(ln)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("webhook: listen: %w", err)
}
return nil
}
// Stop gracefully shuts down the HTTP server.
func (g *Gateway) Stop(ctx context.Context) error {
g.mu.Lock()
server := g.server
g.mu.Unlock()
if server == nil {
return nil
}
return server.Shutdown(ctx)
}
// WebhookHandler returns the HTTP handler for testing.
func (g *Gateway) WebhookHandler() http.Handler {
mux := http.NewServeMux()
for i := range g.Routes {
route := g.Routes[i]
mux.HandleFunc(route.Path, g.handleWebhook(&route))
}
return mux
}
// handleWebhook returns an http.HandlerFunc for one route.
func (g *Gateway) handleWebhook(route *RouteConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 1 MB
if err != nil {
g.log.Error("webhook read body", "err", err)
http.Error(w, "read error", http.StatusBadRequest)
return
}
// HMAC validation.
if route.Secret != "" {
sig := r.Header.Get("X-Hub-Signature-256")
if sig == "" {
sig = r.Header.Get("X-Signature-256")
}
if !webhookguard.VerifyHMAC(body, sig, route.Secret) {
g.log.Warn("webhook invalid signature", "path", route.Path)
http.Error(w, "invalid signature", http.StatusUnauthorized)
return
}
}
// Extract message text.
text := extractText(body, route.Template)
if text == "" {
http.Error(w, "empty message", http.StatusBadRequest)
return
}
// Route through the chat contract.
g.mu.Lock()
client := g.client
g.mu.Unlock()
if client == nil {
http.Error(w, "not started", http.StatusServiceUnavailable)
return
}
msg := messaging.Inbound{
Message: messaging.Message{
ConversationID: messaging.ConversationID{ChannelID: route.Path},
Sender: "webhook",
// A webhook has no per-caller identity, so SenderID stays
// empty: consumers read it as a person
// (internal/app/archied/chat_identity.go, sessioncurator),
// and a route path must never become a user identity
// (docs/prds/memory-engine-unification.md criterion 7).
Role: messaging.RoleUser,
Text: text,
},
// The route is still this message's source for inbound rate
// limiting, so it travels in the transport-only BudgetKey
// rather than borrowing the identity field.
BudgetKey: route.Path,
Platform: "webhook",
}
reply, err := client.Route(r.Context(), msg)
if err != nil {
g.log.Error("webhook route", "err", err, "path", route.Path)
http.Error(w, "route error", http.StatusInternalServerError)
return
}
if route.DeliverTo == "origin" && reply.Text != "" {
w.Header().Set("Content-Type", "text/plain")
_, _ = w.Write([]byte(reply.Text))
} else {
w.WriteHeader(http.StatusAccepted)
}
}
}
// ConfigSchema returns the JSON Schema for the webhook channel config.
func (g *Gateway) ConfigSchema() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"required": ["host", "port"],
"properties": {
"host": {
"type": "string",
"description": "Listen address (e.g. 0.0.0.0)"
},
"port": {
"type": "integer",
"description": "Listen port (e.g. 8644)"
},
"routes": {
"type": "array",
"items": {
"type": "object",
"properties": {
"path": { "type": "string" },
"secret": { "type": "string" },
"template": { "type": "string" }
}
}
}
}
}`)
}
// ValidateConfig checks the webhook channel configuration.
func (g *Gateway) ValidateConfig(cfg map[string]any) error {
if cfg == nil {
return fmt.Errorf("webhook config is required")
}
if host, _ := cfg["host"].(string); host == "" {
return fmt.Errorf("webhook.host is required")
}
return nil
}
// Compile-time guard.
var _ channels.Channel = (*Gateway)(nil)
// extractText pulls a value from a JSON body using dot-notation path.
// "issue.title" → body["issue"]["title"]. Empty path = raw body.
func extractText(body []byte, path string) string {
if path == "" {
return strings.TrimSpace(string(body))
}
var data map[string]any
if err := json.Unmarshal(body, &data); err != nil {
return strings.TrimSpace(string(body))
}
parts := strings.Split(path, ".")
var current any = data
for _, p := range parts {
m, ok := current.(map[string]any)
if !ok {
return ""
}
current = m[p]
}
if s, ok := current.(string); ok {
return strings.TrimSpace(s)
}
return ""
}