Skip to content

Commit a2f6d68

Browse files
committed
feat: add chat lifecycle hook dispatch backend
Adds the agenthooks SDK (event types, HTTP contract, JWT signing), the chathooks dispatcher with per-dispatch persistence and metrics, and a sample agenthooks-server script. Deployment configuration and the admin setup doc land with the dispatcher wiring in the next PR of the stack.
1 parent 5f61ea5 commit a2f6d68

11 files changed

Lines changed: 2732 additions & 0 deletions

File tree

‎coderd/x/chathooks/dispatcher.go‎

Lines changed: 722 additions & 0 deletions
Large diffs are not rendered by default.

‎coderd/x/chathooks/dispatcher_internal_test.go‎

Lines changed: 646 additions & 0 deletions
Large diffs are not rendered by default.

‎codersdk/agenthooks/agenthooks_test.go‎

Lines changed: 422 additions & 0 deletions
Large diffs are not rendered by default.

‎codersdk/agenthooks/http.go‎

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
package agenthooks
2+
3+
import (
4+
"context"
5+
"crypto/sha256"
6+
"encoding/hex"
7+
"encoding/json"
8+
"io"
9+
"net/http"
10+
"net/url"
11+
"strings"
12+
13+
"golang.org/x/xerrors"
14+
)
15+
16+
// Hooks lets a consumer implement only the lifecycle events it uses.
17+
type Hooks struct {
18+
SessionStart func(context.Context, Meta, SessionStartData) (Response, error)
19+
UserPromptSubmit func(context.Context, Meta, UserPromptSubmitData) (Response, error)
20+
PreToolUse func(context.Context, Meta, PreToolUseData) (Response, error)
21+
PostToolUse func(context.Context, Meta, PostToolUseData) (Response, error)
22+
PreCompact func(context.Context, Meta, PreCompactData) (Response, error)
23+
PostCompact func(context.Context, Meta, PostCompactData) (Response, error)
24+
Stop func(context.Context, Meta, StopData) (Response, error)
25+
}
26+
27+
// HandlerOption configures NewHTTPHandler.
28+
type HandlerOption func(*handlerOptions)
29+
30+
type handlerOptions struct {
31+
expectedIssuer string
32+
}
33+
34+
// WithExpectedIssuer requires the verified iss claim to match issuer.
35+
// If omitted, NewHTTPHandler accepts any non-empty issuer signed
36+
// with the secret.
37+
func WithExpectedIssuer(issuer string) HandlerOption {
38+
return func(options *handlerOptions) {
39+
options.expectedIssuer = issuer
40+
}
41+
}
42+
43+
func NewHTTPHandler(secret []byte, hooks Hooks, opts ...HandlerOption) http.Handler {
44+
var options handlerOptions
45+
for _, opt := range opts {
46+
opt(&options)
47+
}
48+
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
49+
if r.Method != http.MethodPost {
50+
rw.Header().Set("Allow", http.MethodPost)
51+
http.Error(rw, "method not allowed", http.StatusMethodNotAllowed)
52+
return
53+
}
54+
55+
claims, err := Verify(r.Header.Get("Authorization"), secret)
56+
if err != nil {
57+
http.Error(rw, err.Error(), http.StatusUnauthorized)
58+
return
59+
}
60+
if options.expectedIssuer != "" && claims.Issuer != options.expectedIssuer {
61+
http.Error(rw, "unexpected issuer", http.StatusUnauthorized)
62+
return
63+
}
64+
body, err := io.ReadAll(r.Body)
65+
if err != nil {
66+
http.Error(rw, "read request body", http.StatusBadRequest)
67+
return
68+
}
69+
var request Request
70+
if err := json.Unmarshal(body, &request); err != nil {
71+
http.Error(rw, "decode request body", http.StatusBadRequest)
72+
return
73+
}
74+
if err := verifyBody(r, body, claims, request); err != nil {
75+
http.Error(rw, err.Error(), http.StatusBadRequest)
76+
return
77+
}
78+
response, err := dispatch(r.Context(), hooks, request)
79+
if err != nil {
80+
http.Error(rw, err.Error(), http.StatusInternalServerError)
81+
return
82+
}
83+
84+
rw.Header().Set("Content-Type", "application/json")
85+
if err := json.NewEncoder(rw).Encode(response); err != nil {
86+
return
87+
}
88+
})
89+
}
90+
91+
func verifyBody(r *http.Request, body []byte, claims Claims, request Request) error {
92+
digest := sha256.Sum256(body)
93+
if claims.BodySHA256 != hex.EncodeToString(digest[:]) {
94+
return xerrors.New("request body does not match body_sha256 claim")
95+
}
96+
if canonicalAudience(claims.Audience) != requestAudience(r) {
97+
return xerrors.New("request URL does not match audience claim")
98+
}
99+
if request.Meta.SchemaVersion != SchemaVersion {
100+
return xerrors.New("unsupported schema version")
101+
}
102+
if request.Meta.DispatchID != claims.JTI {
103+
return xerrors.New("dispatch ID does not match JWT ID")
104+
}
105+
if request.Type != claims.Type {
106+
return xerrors.New("request type does not match type claim")
107+
}
108+
chatID, err := claims.ChatID()
109+
if err != nil {
110+
return err
111+
}
112+
if request.Meta.ChatID != chatID {
113+
return xerrors.New("chat ID does not match subject claim")
114+
}
115+
return nil
116+
}
117+
118+
func requestAudience(r *http.Request) string {
119+
requestURL := *r.URL
120+
if requestURL.Scheme == "" {
121+
requestURL.Scheme = "http"
122+
if r.TLS != nil {
123+
requestURL.Scheme = "https"
124+
}
125+
// Forwarded values reconstruct the signed client-facing audience.
126+
if proto := forwardedProto(r); proto != "" {
127+
requestURL.Scheme = proto
128+
}
129+
}
130+
if requestURL.Host == "" {
131+
requestURL.Host = r.Host
132+
if host := forwardedHost(r); host != "" {
133+
requestURL.Host = host
134+
}
135+
}
136+
return canonicalAudience(requestURL.String())
137+
}
138+
139+
func forwardedProto(r *http.Request) string {
140+
proto := r.Header.Get("X-Forwarded-Proto")
141+
// Proxies append values; the first is client-facing.
142+
proto, _, _ = strings.Cut(proto, ",")
143+
return strings.ToLower(strings.TrimSpace(proto))
144+
}
145+
146+
func forwardedHost(r *http.Request) string {
147+
host := r.Header.Get("X-Forwarded-Host")
148+
host, _, _ = strings.Cut(host, ",")
149+
return strings.TrimSpace(host)
150+
}
151+
152+
// canonicalAudience treats root URLs with and without a trailing
153+
// slash as equivalent.
154+
func canonicalAudience(audience string) string {
155+
parsed, err := url.Parse(audience)
156+
if err != nil {
157+
return audience
158+
}
159+
if parsed.Path == "/" && parsed.RawPath == "" {
160+
parsed.Path = ""
161+
}
162+
return parsed.String()
163+
}
164+
165+
func dispatch(ctx context.Context, hooks Hooks, request Request) (Response, error) {
166+
switch request.Type {
167+
case EventSessionStart:
168+
return dispatchHook(ctx, request, hooks.SessionStart)
169+
case EventUserPromptSubmit:
170+
return dispatchHook(ctx, request, hooks.UserPromptSubmit)
171+
case EventPreToolUse:
172+
return dispatchHook(ctx, request, hooks.PreToolUse)
173+
case EventPostToolUse:
174+
return dispatchHook(ctx, request, hooks.PostToolUse)
175+
case EventPreCompact:
176+
return dispatchHook(ctx, request, hooks.PreCompact)
177+
case EventPostCompact:
178+
return dispatchHook(ctx, request, hooks.PostCompact)
179+
case EventStop:
180+
return dispatchHook(ctx, request, hooks.Stop)
181+
default:
182+
return Response{}, xerrors.Errorf("unknown event type %q", request.Type)
183+
}
184+
}
185+
186+
func dispatchHook[T any](ctx context.Context, request Request, hook func(context.Context, Meta, T) (Response, error)) (Response, error) {
187+
if hook == nil {
188+
return Response{}, nil
189+
}
190+
var data T
191+
if err := json.Unmarshal(request.Data, &data); err != nil {
192+
return Response{}, xerrors.Errorf("decode %q event data: %w", request.Type, err)
193+
}
194+
return hook(ctx, request.Meta, data)
195+
}

‎codersdk/agenthooks/jwt.go‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,126 @@
1+
package agenthooks
2+
3+
import (
4+
"encoding/hex"
5+
"encoding/json"
6+
"strings"
7+
"time"
8+
9+
"github.com/go-jose/go-jose/v4"
10+
"github.com/google/uuid"
11+
"golang.org/x/xerrors"
12+
)
13+
14+
const jwtType = "JWT"
15+
16+
// SignClaims signs claims with the shared secret using HS256.
17+
func SignClaims(secret []byte, claims Claims) (string, error) {
18+
signer, err := jose.NewSigner(
19+
jose.SigningKey{Algorithm: jose.HS256, Key: secret},
20+
new(jose.SignerOptions).WithType(jwtType),
21+
)
22+
if err != nil {
23+
return "", xerrors.Errorf("create signer: %w", err)
24+
}
25+
26+
payload, err := json.Marshal(claims)
27+
if err != nil {
28+
return "", xerrors.Errorf("marshal claims: %w", err)
29+
}
30+
signed, err := signer.Sign(payload)
31+
if err != nil {
32+
return "", xerrors.Errorf("sign claims: %w", err)
33+
}
34+
token, err := signed.CompactSerialize()
35+
if err != nil {
36+
return "", xerrors.Errorf("serialize token: %w", err)
37+
}
38+
return token, nil
39+
}
40+
41+
func Verify(authzHeader string, secret []byte) (Claims, error) {
42+
const bearerPrefix = "Bearer "
43+
token, ok := strings.CutPrefix(authzHeader, bearerPrefix)
44+
if !ok || token == "" || strings.ContainsAny(token, " \t\r\n") {
45+
return Claims{}, xerrors.New("authorization header must contain one Bearer token")
46+
}
47+
48+
object, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{jose.HS256})
49+
if err != nil {
50+
return Claims{}, xerrors.Errorf("parse token: %w", err)
51+
}
52+
if len(object.Signatures) != 1 {
53+
return Claims{}, xerrors.New("token must contain one signature")
54+
}
55+
header := object.Signatures[0].Header
56+
if header.Algorithm != string(jose.HS256) {
57+
return Claims{}, xerrors.Errorf("token algorithm must be %q", jose.HS256)
58+
}
59+
typ, ok := header.ExtraHeaders[jose.HeaderType].(string)
60+
if !ok || typ != jwtType {
61+
return Claims{}, xerrors.Errorf("token type must be %q", jwtType)
62+
}
63+
64+
payload, err := object.Verify(secret)
65+
if err != nil {
66+
return Claims{}, xerrors.Errorf("verify token: %w", err)
67+
}
68+
var claims Claims
69+
if err := json.Unmarshal(payload, &claims); err != nil {
70+
return Claims{}, xerrors.Errorf("decode claims: %w", err)
71+
}
72+
if err := validateClaims(claims, time.Now()); err != nil {
73+
return Claims{}, err
74+
}
75+
return claims, nil
76+
}
77+
78+
func validateClaims(claims Claims, now time.Time) error {
79+
switch {
80+
case claims.Issuer == "":
81+
return xerrors.New("issuer is required")
82+
case claims.Subject == "":
83+
return xerrors.New("subject is required")
84+
case claims.Audience == "":
85+
return xerrors.New("audience is required")
86+
case claims.IssuedAt == 0:
87+
return xerrors.New("issued at is required")
88+
case claims.NotBefore == 0:
89+
return xerrors.New("not before is required")
90+
case claims.Expires == 0:
91+
return xerrors.New("expiry is required")
92+
case claims.JTI == uuid.Nil:
93+
return xerrors.New("JWT ID is required")
94+
case !validEventType(claims.Type):
95+
return xerrors.Errorf("invalid event type %q", claims.Type)
96+
case !validSHA256(claims.BodySHA256):
97+
return xerrors.New("body SHA-256 must be a hexadecimal SHA-256 digest")
98+
case claims.NotBefore > claims.Expires:
99+
return xerrors.New("not before must not be after expiry")
100+
case claims.IssuedAt > claims.Expires:
101+
return xerrors.New("issued at must not be after expiry")
102+
case now.Unix() < claims.NotBefore:
103+
return xerrors.New("token is not valid yet")
104+
case now.Unix() >= claims.Expires:
105+
return xerrors.New("token has expired")
106+
}
107+
if _, err := claims.ChatID(); err != nil {
108+
return err
109+
}
110+
return nil
111+
}
112+
113+
func validEventType(eventType EventType) bool {
114+
switch eventType {
115+
case EventSessionStart, EventUserPromptSubmit, EventPreToolUse,
116+
EventPostToolUse, EventPreCompact, EventPostCompact, EventStop:
117+
return true
118+
default:
119+
return false
120+
}
121+
}
122+
123+
func validSHA256(value string) bool {
124+
decoded, err := hex.DecodeString(value)
125+
return err == nil && len(decoded) == 32
126+
}

0 commit comments

Comments
 (0)