-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinterceptor.go
More file actions
208 lines (173 loc) · 5.6 KB
/
interceptor.go
File metadata and controls
208 lines (173 loc) · 5.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package trusera
import (
"bytes"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
const maxBodySnippet = 500
// EnforcementMode determines how policy violations are handled
type EnforcementMode string
const (
ModeLog EnforcementMode = "log" // Record but allow all requests
ModeWarn EnforcementMode = "warn" // Log warnings for blocked patterns but allow
ModeBlock EnforcementMode = "block" // Reject blocked requests with error
)
// InterceptorOptions configures the HTTP interceptor
type InterceptorOptions struct {
Enforcement EnforcementMode
ExcludePatterns []string // URL patterns to skip interception
BlockPatterns []string // URL patterns to block (for testing enforcement)
}
// WrapHTTPClient wraps an http.Client to intercept all outbound requests
func WrapHTTPClient(client *http.Client, truseraClient *Client, opts InterceptorOptions) *http.Client {
if client == nil {
client = &http.Client{}
}
transport := client.Transport
if transport == nil {
transport = http.DefaultTransport
}
client.Transport = &interceptingTransport{
base: transport,
client: truseraClient,
opts: opts,
}
return client
}
// interceptingTransport wraps http.RoundTripper
type interceptingTransport struct {
base http.RoundTripper
client *Client
opts InterceptorOptions
}
// RoundTrip intercepts and records HTTP requests
func (t *interceptingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
// Check if URL should be excluded from interception
if t.shouldExclude(req.URL.String()) {
return t.base.RoundTrip(req)
}
// Check if URL matches block patterns (for enforcement)
blocked := t.isBlocked(req.URL.String())
// Read and restore request body for logging
var bodySnippet string
if req.Body != nil {
bodyBytes, err := io.ReadAll(req.Body)
if err == nil {
_ = req.Body.Close()
req.Body = io.NopCloser(bytes.NewReader(bodyBytes))
if len(bodyBytes) > maxBodySnippet {
bodySnippet = string(bodyBytes[:maxBodySnippet]) + "..."
} else {
bodySnippet = string(bodyBytes)
}
}
}
// Create event for this API call
event := NewEvent(EventAPICall, req.Method+" "+req.URL.String()).
WithPayload("method", req.Method).
WithPayload("url", req.URL.String()).
WithPayload("headers", sanitizeHeaders(req.Header)).
WithPayload("blocked", blocked).
WithMetadata("enforcement_mode", string(t.opts.Enforcement))
if bodySnippet != "" {
event = event.WithPayload("body_snippet", bodySnippet)
}
// Handle enforcement modes
if blocked {
event = event.WithPayload("enforcement_action", "blocked")
switch t.opts.Enforcement {
case ModeBlock:
t.client.Track(event)
return nil, errors.New("request blocked by Trusera policy")
case ModeWarn:
event = event.WithMetadata("warning", "URL matches block pattern but allowed in warn mode")
t.client.Track(event)
// Continue with request
case ModeLog:
// Just record, no action
t.client.Track(event)
}
} else {
event = event.WithPayload("enforcement_action", "allowed")
t.client.Track(event)
}
// Forward request to base transport
resp, err := t.base.RoundTrip(req)
if err != nil {
// Track the error
errorEvent := NewEvent(EventAPICall, "error").
WithPayload("method", req.Method).
WithPayload("url", req.URL.String()).
WithPayload("error", err.Error())
t.client.Track(errorEvent)
return resp, err
}
// Record response status
responseEvent := NewEvent(EventAPICall, "response").
WithPayload("method", req.Method).
WithPayload("url", req.URL.String()).
WithPayload("status_code", resp.StatusCode).
WithPayload("status", resp.Status)
t.client.Track(responseEvent)
return resp, nil
}
// shouldExclude checks if URL matches any exclude patterns
func (t *interceptingTransport) shouldExclude(url string) bool {
for _, pattern := range t.opts.ExcludePatterns {
if strings.Contains(url, pattern) {
return true
}
}
return false
}
// isBlocked checks if URL matches any block patterns
func (t *interceptingTransport) isBlocked(url string) bool {
for _, pattern := range t.opts.BlockPatterns {
if strings.Contains(url, pattern) {
return true
}
}
return false
}
const redactedValue = "[REDACTED]"
// sanitizeHeaders removes sensitive headers from logging
func sanitizeHeaders(headers http.Header) map[string]string {
sanitized := make(map[string]string)
sensitiveHeaders := map[string]bool{
"authorization": true,
"cookie": true,
"set-cookie": true,
"x-api-key": true,
}
for key, values := range headers {
lowerKey := strings.ToLower(key)
if sensitiveHeaders[lowerKey] {
sanitized[key] = redactedValue
} else if len(values) > 0 {
sanitized[key] = values[0]
}
}
return sanitized
}
// CreateInterceptedClient creates a new http.Client with Trusera interception
func CreateInterceptedClient(truseraClient *Client, opts InterceptorOptions) *http.Client {
return WrapHTTPClient(&http.Client{}, truseraClient, opts)
}
// InterceptDefault wraps http.DefaultClient with Trusera interception
func InterceptDefault(truseraClient *Client, opts InterceptorOptions) {
http.DefaultClient = WrapHTTPClient(http.DefaultClient, truseraClient, opts)
}
// MustRegisterAndIntercept is a convenience function that registers an agent and returns an intercepted client
func MustRegisterAndIntercept(apiKey, agentName, framework string, opts InterceptorOptions) (*Client, *http.Client, error) {
client := NewClient(apiKey)
_, err := client.RegisterAgent(agentName, framework)
if err != nil {
_ = client.Close()
return nil, nil, fmt.Errorf("failed to register agent: %w", err)
}
httpClient := CreateInterceptedClient(client, opts)
return client, httpClient, nil
}