|
| 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 | +} |
0 commit comments