Documentation
¶
Overview ¶
Package webhook is the Brigade webhook gateway: an ordinary team member that forwards its inbox to an HTTPS endpoint and turns signed HTTP POSTs back into Brigade messages.
It speaks to the backend ONLY through BAP/1 (docs/protocol-v1.md), via the Backend interface that *adapterclient.Client satisfies, so the same gateway runs over the filesystem adapter (a Syncthing-shared folder), the bundled Supabase adapter, or any conforming adapter. It never reads a store directly.
Outbound: every message addressed to the gateway's session is POSTed as JSON to the configured URL, signed with HMAC-SHA256 over "v1:<unix seconds>:<body>" (Sign). The message is acknowledged only after a 2xx answer; a retryable failure (transport error, 408, 425, 429, 5xx) leaves it unacknowledged for the next poll with a growing backoff; a permanent failure (any other status, or too many attempts) tells the sender once, then acknowledges.
Inbound: POST /v1/messages accepts a signed JSON document {to|member|reply_to, text, ...} (InboundRequest); the signature and timestamp window are checked with a constant-time compare BEFORE the body is parsed, unknown members and oversized bodies are refused, and the message is sent from the gateway's own session with an idempotency key so a retried or replayed POST is delivered once.
Nothing that arrives through this gateway approves anything (docs/security.md): an outbound payload is untrusted text from a teammate's session, and an inbound one becomes an ordinary message that the recipient's harness frames as untrusted.
Index ¶
- Constants
- func IsGatewayHarness(h string) bool
- func Run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer, ...) int
- func Sign(secret []byte, ts int64, body []byte) string
- func Verify(secret []byte, tsHeader, sigHeader string, body []byte, now time.Time, ...) error
- type Backend
- type Config
- type From
- type Gateway
- func (g *Gateway) Deliver(ctx context.Context) (int, error)
- func (g *Gateway) Handler(perMinute int) http.Handler
- func (g *Gateway) Run(ctx context.Context) error
- func (g *Gateway) SessionID() string
- func (g *Gateway) Start(ctx context.Context) error
- func (g *Gateway) Tick(ctx context.Context) error
- type GatewayInfo
- type InboundRequest
- type OutboundMessage
- type OutboundPayload
- type Thread
Constants ¶
const ( DefaultSessionName = "webhook-gateway" DefaultLeaseSeconds = 600 DefaultPoll = 5 * time.Second DefaultMaxAttempts = 24 )
Defaults.
const ( PathMessages = "/v1/messages" PathSessions = "/v1/sessions" PathHealth = "/healthz" )
Inbound paths.
const ( OutboundType = "brigade.message" OutboundVersion = 1 )
OutboundType and OutboundVersion identify the outbound document.
const ( // HeaderTimestamp carries the signing time in Unix seconds. HeaderTimestamp = "X-Brigade-Timestamp" // HeaderSignature carries "v1=<hex HMAC-SHA256>". HeaderSignature = "X-Brigade-Signature" // HeaderDelivery carries the Brigade message id on an outbound POST, // so a receiver can deduplicate an at-least-once redelivery. HeaderDelivery = "X-Brigade-Delivery" // DefaultMaxSkew is how far a timestamp may be from the verifier's // clock, either way (the Slack convention the hosted gateway uses). DefaultMaxSkew = 5 * time.Minute // MinSecretBytes is the shortest shared secret accepted. MinSecretBytes = 32 )
The signature headers, on both directions.
const DefaultGatewayURL = "http://" + DefaultListen
DefaultGatewayURL is where `send` and `sessions` find the running gateway: its default loopback listener.
const (
// DefaultInboundPerMinute bounds accepted POSTs, all callers together.
DefaultInboundPerMinute = 60
)
const DefaultListen = "127.0.0.1:8787"
DefaultListen is loopback: the inbound API is for a caller on the same machine (or behind a reverse proxy that terminates TLS).
const HarnessName = gateway.HarnessPrefix + "webhook"
HarnessName is the harness this gateway registers under. Every harness named "gateway-*" is a gateway (gateway.HarnessPrefix): never a --member target, never a recipient this gateway picks for a member.
const (
MaxInboundBytes = 64 << 10
)
Inbound limits. MaxInboundBytes bounds the whole request body; the text itself is further bounded by the protocol's body cap once framed.
Variables ¶
This section is empty.
Functions ¶
func IsGatewayHarness ¶
IsGatewayHarness reports whether a roster row is a gateway. The prefix itself is spelled once, in gateway.HarnessPrefix.
func Run ¶
func Run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer, environ []string) int
Run is the brigade-webhook-gateway entry point. It is also a multi-call binary: `adapter supabase …` runs the bundled Supabase adapter, which is what adapterclient spawns for a profile on the bundled adapter (it re-executes os.Executable with exactly those words), so one binary is enough on a machine with no `brigade` install.
func Verify ¶
func Verify(secret []byte, tsHeader, sigHeader string, body []byte, now time.Time, maxSkew time.Duration) error
Verify checks a request's timestamp and signature headers against body. The timestamp must be within maxSkew of now, either way, and the signature is compared in constant time. Only the v1 scheme is accepted.
Types ¶
type Backend ¶
type Backend interface {
Describe(ctx context.Context) (*protocol.DescribeResult, error)
Register(ctx context.Context, reg *protocol.SessionRegistration) (*adapterclient.RegisterResult, error)
Heartbeat(ctx context.Context, sessionID string, hb *protocol.HeartbeatRequest) (*protocol.HeartbeatResult, error)
Close(ctx context.Context, sessionID string) (*adapterclient.CloseResult, error)
ListSessions(ctx context.Context, includeOffline bool) (*adapterclient.ListResult, error)
Send(ctx context.Context, req *protocol.SendRequest) (*protocol.SendResponse, error)
Receive(ctx context.Context, sessionID string, limit int) (*adapterclient.ReceiveResult, error)
Ack(ctx context.Context, sessionID string, req *protocol.AckRequest) (*protocol.AckResult, error)
}
Backend is the slice of BAP/1 the gateway uses. *adapterclient.Client implements it for any adapter; tests may substitute a fake.
type Config ¶
type Config struct {
TargetURL string
Secret []byte
SessionName string
Description string
Version string
LeaseSeconds int
Poll time.Duration
MaxAttempts int
MaxSkew time.Duration
// ExtraHeaders are set on every POST to TargetURL before the
// gateway's own headers (a receiver's credential, from
// --header-file). They authenticate nothing to Brigade; the
// signature still does. The names parseHeaderFile refuses are
// refused here too.
ExtraHeaders http.Header
// StatePath is the local state file; "" keeps state in memory only.
StatePath string
HTTPClient *http.Client
Logger *slog.Logger
Now func() time.Time
}
Config configures a Gateway. TargetURL and Secret are required.
type From ¶
type From struct {
SessionID string `json:"session_id"`
SessionName string `json:"session_name"`
PrincipalRef string `json:"principal_ref"`
HumanLabel string `json:"human_label,omitzero"`
}
From is the sender as the backend reported it. session_id and principal_ref are the backend's facts; session_name and human_label are whatever the sender chose and are NOT verified.
type Gateway ¶
type Gateway struct {
// contains filtered or unexported fields
}
Gateway is one running webhook gateway session.
func (*Gateway) Deliver ¶
Deliver drains one batch of the inbox to the webhook and returns how many messages were acknowledged.
type GatewayInfo ¶
type GatewayInfo struct {
SessionID string `json:"session_id"`
TeamRef string `json:"team_ref,omitzero"`
}
GatewayInfo names the gateway session that relayed the message, so a receiver serving several gateways can tell them apart.
type InboundRequest ¶
type InboundRequest struct {
// ID is the caller's delivery id. Two POSTs with one id are one
// message (the backend's idempotency, 4.5.4). Optional: without it the
// signature itself is the key, so a replayed request is still one.
ID string `json:"id,omitzero"`
// To is a full session id, or a unique tail of at least 5 characters.
To string `json:"to,omitzero"`
// Member is a member's label (case-insensitive) or the first 8+
// characters of their principal reference; their best session gets it.
Member string `json:"member,omitzero"`
// ReplyTo is a Brigade message id this answers: one the gateway
// delivered to the webhook, or one it created from an earlier POST.
ReplyTo string `json:"reply_to,omitzero"`
Text string `json:"text"`
Summary string `json:"summary,omitzero"`
// From is a display name for the caller. Unverified; shown as such.
From string `json:"from,omitzero"`
// Ref is an opaque caller reference (a conversation id, say) echoed
// back in Thread.Ref when a teammate replies.
Ref string `json:"ref,omitzero"`
}
InboundRequest is the signed JSON document POST /v1/messages accepts. Exactly one recipient form is required, except that reply_to alone routes to the session that sent the message being answered.
func (*InboundRequest) Validate ¶
func (r *InboundRequest) Validate() error
Validate checks the shape. It never echoes a value.
type OutboundMessage ¶
type OutboundMessage struct {
MessageID string `json:"message_id"`
Summary string `json:"summary,omitzero"`
Body string `json:"body"`
ReplyTo string `json:"reply_to,omitzero"`
HopCount int `json:"hop_count"`
CreatedAt time.Time `json:"created_at"`
From From `json:"from"`
}
OutboundMessage is the relayed message. Every string in it is sanitised (protocol.Sanitize*) and remains untrusted.
type OutboundPayload ¶
type OutboundPayload struct {
Type string `json:"type"`
Version int `json:"version"`
DeliveryID string `json:"delivery_id"`
Message OutboundMessage `json:"message"`
Gateway GatewayInfo `json:"gateway"`
Thread *Thread `json:"thread,omitzero"`
Notice string `json:"notice"`
}
OutboundPayload is the JSON document POSTed for one Brigade message.