-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration.go
More file actions
574 lines (491 loc) · 15.6 KB
/
integration.go
File metadata and controls
574 lines (491 loc) · 15.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package module
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/GoCodeAlone/modular"
)
// isPrivateIP checks if an IP address belongs to a private/reserved range.
// This helps prevent Server-Side Request Forgery (SSRF) attacks.
func isPrivateIP(ip net.IP) bool {
privateRanges := []struct {
network string
}{
{"10.0.0.0/8"},
{"172.16.0.0/12"},
{"192.168.0.0/16"},
{"127.0.0.0/8"},
{"169.254.0.0/16"}, // Link-local / cloud metadata
{"0.0.0.0/8"},
{"::1/128"}, // IPv6 loopback
{"fc00::/7"}, // IPv6 private
{"fe80::/10"}, // IPv6 link-local
}
for _, r := range privateRanges {
_, cidr, err := net.ParseCIDR(r.network)
if err != nil {
continue
}
if cidr.Contains(ip) {
return true
}
}
return false
}
// validateURLHost checks that the constructed request URL targets the same host
// as the configured base URL. This prevents host injection via path manipulation
// (e.g. a crafted path that tries to redirect the request to a different server).
func validateURLHost(reqURL, baseURL string) error {
req, err := url.Parse(reqURL)
if err != nil {
return fmt.Errorf("invalid request URL: %w", err)
}
base, err := url.Parse(baseURL)
if err != nil {
return fmt.Errorf("invalid base URL: %w", err)
}
if req.Scheme != base.Scheme || req.Host != base.Host {
return fmt.Errorf("request URL host %q does not match configured base URL host %q", req.Host, base.Host)
}
return nil
}
// validateURL checks that a URL is safe to request (not targeting private/internal networks).
func validateURL(rawURL string) error {
parsed, err := url.Parse(rawURL)
if err != nil {
return fmt.Errorf("invalid URL: %w", err)
}
// Only allow http and https schemes
if parsed.Scheme != "http" && parsed.Scheme != "https" {
return fmt.Errorf("unsupported URL scheme: %q (only http and https are allowed)", parsed.Scheme)
}
// Resolve hostname to check for private IPs
host := parsed.Hostname()
if host == "" {
return fmt.Errorf("URL has no host")
}
ips, err := net.LookupIP(host)
if err != nil {
return fmt.Errorf("failed to resolve host %q: %w", host, err)
}
for _, ip := range ips {
if isPrivateIP(ip) {
return fmt.Errorf("request to private/internal IP address is not allowed: %s resolves to %s", host, ip)
}
}
return nil
}
// IntegrationConnector represents a connector to a third-party service
type IntegrationConnector interface {
// Connect establishes a connection to the external service
Connect(ctx context.Context) error
// Disconnect closes the connection to the external service
Disconnect(ctx context.Context) error
// Execute performs an action on the external service
Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error)
// GetName returns the name of the connector
GetName() string
// IsConnected checks if the connector is connected
IsConnected() bool
}
// HTTPIntegrationConnector implements a connector using HTTP requests
type HTTPIntegrationConnector struct {
name string
baseURL string
headers map[string]string
authType string
authToken string
username string
password string
client *http.Client
connected bool
timeout time.Duration
rateLimiter *time.Ticker
allowPrivateIPs bool // For testing/development - disables SSRF protection
}
// NewHTTPIntegrationConnector creates a new HTTP-based integration connector
func NewHTTPIntegrationConnector(name, baseURL string) *HTTPIntegrationConnector {
return &HTTPIntegrationConnector{
name: name,
baseURL: baseURL,
headers: make(map[string]string),
authType: "none",
client: &http.Client{},
connected: false,
timeout: time.Second * 30,
}
}
// SetBasicAuth sets basic authentication for the connector
func (c *HTTPIntegrationConnector) SetBasicAuth(username, password string) {
c.authType = "basic"
c.username = username
c.password = password
}
// SetBearerAuth sets bearer token authentication for the connector
func (c *HTTPIntegrationConnector) SetBearerAuth(token string) {
c.authType = "bearer"
c.authToken = token
}
// SetHeader sets a custom header for requests
func (c *HTTPIntegrationConnector) SetHeader(key, value string) {
c.headers[key] = value
}
// SetDefaultHeader is an alias for SetHeader for backward compatibility
func (c *HTTPIntegrationConnector) SetDefaultHeader(key, value string) {
c.SetHeader(key, value)
}
// SetTimeout sets the request timeout
func (c *HTTPIntegrationConnector) SetTimeout(timeout time.Duration) {
c.timeout = timeout
c.client.Timeout = timeout
}
// AllowPrivateIPs enables requests to private/internal IP addresses.
// This should only be used for testing or trusted internal services.
func (c *HTTPIntegrationConnector) AllowPrivateIPs() {
c.allowPrivateIPs = true
}
// DisallowPrivateIPs disables requests to private/internal IP addresses,
// restoring SSRF protection (this is the default).
func (c *HTTPIntegrationConnector) DisallowPrivateIPs() {
c.allowPrivateIPs = false
}
// SetRateLimit sets a rate limit for requests
func (c *HTTPIntegrationConnector) SetRateLimit(requestsPerMinute int) {
var interval time.Duration
if requestsPerMinute > 0 {
interval = time.Minute / time.Duration(requestsPerMinute)
} else {
interval = time.Second // Default fallback
}
c.rateLimiter = time.NewTicker(interval)
}
// GetName returns the connector name
func (c *HTTPIntegrationConnector) GetName() string {
return c.name
}
// Connect establishes a connection to the external service
func (c *HTTPIntegrationConnector) Connect(ctx context.Context) error {
// For HTTP connectors, this could involve validation of the connection
// by making a test request or just setting up the client
c.client.Timeout = c.timeout
// Set default headers
if _, exists := c.headers["Content-Type"]; !exists {
c.headers["Content-Type"] = "application/json"
}
c.connected = true
return nil
}
// IsConnected checks if the connector is connected
func (c *HTTPIntegrationConnector) IsConnected() bool {
return c.connected
}
// Disconnect closes the connection to the external service
func (c *HTTPIntegrationConnector) Disconnect(ctx context.Context) error {
c.connected = false
if c.rateLimiter != nil {
c.rateLimiter.Stop()
c.rateLimiter = nil
}
return nil
}
// Execute performs an action on the external service
func (c *HTTPIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error) {
if !c.connected {
return nil, fmt.Errorf("connector not connected")
}
// Rate limiting if enabled
if c.rateLimiter != nil {
select {
case <-c.rateLimiter.C:
// Rate limit satisfied, proceed
case <-ctx.Done():
return nil, ctx.Err()
}
}
// Parse action into method and path
parts := strings.SplitN(action, " ", 2)
if len(parts) != 2 {
return nil, fmt.Errorf("invalid action format: %s (expected 'METHOD /path')", action)
}
method := parts[0]
path := parts[1]
// Build URL
reqURL, err := url.JoinPath(c.baseURL, path)
if err != nil {
return nil, fmt.Errorf("invalid URL path: %w", err)
}
// Ensure the constructed URL still targets the configured base host (prevent host injection via path).
if err := validateURLHost(reqURL, c.baseURL); err != nil {
return nil, fmt.Errorf("invalid request URL: %w", err)
}
// Handle query parameters for GET requests
if method == "GET" && len(params) > 0 {
queryParams := url.Values{}
for k, v := range params {
queryParams.Add(k, fmt.Sprintf("%v", v))
}
reqURL = reqURL + "?" + queryParams.Encode()
}
// Prepare request body for non-GET requests
var body io.Reader
if method != "GET" && params != nil {
jsonData, err := json.Marshal(params)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
body = strings.NewReader(string(jsonData))
}
// Validate URL to prevent SSRF attacks (skip for trusted/test environments)
if !c.allowPrivateIPs {
if err := validateURL(reqURL); err != nil {
return nil, fmt.Errorf("SSRF protection: %w", err)
}
}
// Create request
req, err := http.NewRequestWithContext(ctx, method, reqURL, body)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Add headers
for k, v := range c.headers {
req.Header.Set(k, v)
}
// Add authentication
switch c.authType {
case "basic":
req.SetBasicAuth(c.username, c.password)
case "bearer":
req.Header.Set("Authorization", "Bearer "+c.authToken)
}
// Execute request
resp, err := c.client.Do(req) //nolint:gosec // G704: URL from configured integration endpoint
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("integration: failed to close response body: %v", err)
}
}()
// Read response body
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
// Parse response as JSON
var result map[string]any
if len(respBody) > 0 {
if err := json.Unmarshal(respBody, &result); err != nil {
// If not JSON, return the raw response
return map[string]any{
"statusCode": resp.StatusCode,
"raw": string(respBody),
}, nil
}
} else {
result = make(map[string]any)
}
// Add status code to result
result["statusCode"] = resp.StatusCode
// Check for error status codes
if resp.StatusCode >= 400 {
return result, fmt.Errorf("request returned error status: %d", resp.StatusCode)
}
return result, nil
}
// WebhookIntegrationConnector implements a connector that receives webhook callbacks
type WebhookIntegrationConnector struct {
name string
path string
port int
server *http.Server
handlers map[string]func(context.Context, map[string]any) error
connected bool
}
// NewWebhookIntegrationConnector creates a new webhook integration connector
func NewWebhookIntegrationConnector(name, path string, port int) *WebhookIntegrationConnector {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
return &WebhookIntegrationConnector{
name: name,
path: path,
port: port,
handlers: make(map[string]func(context.Context, map[string]any) error),
}
}
// GetName returns the connector name
func (c *WebhookIntegrationConnector) GetName() string {
return c.name
}
// Connect establishes the webhook server
func (c *WebhookIntegrationConnector) Connect(ctx context.Context) error {
mux := http.NewServeMux()
// Register handler for the webhook path
mux.HandleFunc(c.path, func(w http.ResponseWriter, r *http.Request) {
// Only allow POST requests
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the request body
defer func() {
if err := r.Body.Close(); err != nil {
log.Printf("integration: failed to close request body: %v", err)
}
}()
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
// Parse JSON
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
http.Error(w, "Invalid JSON payload", http.StatusBadRequest)
return
}
// Extract event type from payload
eventType, _ := payload["type"].(string)
if eventType == "" {
eventType = "default"
}
// Find handler for this event type
handler, exists := c.handlers[eventType]
if !exists {
handler, exists = c.handlers["default"]
if !exists {
http.Error(w, "No handler for event type", http.StatusNotImplemented)
return
}
}
// Execute handler
if err := handler(r.Context(), payload); err != nil {
http.Error(w, fmt.Sprintf("Error processing webhook: %v", err), http.StatusInternalServerError)
return
}
// Return success
w.WriteHeader(http.StatusOK)
if _, err := w.Write([]byte(`{"status":"ok"}`)); err != nil {
log.Printf("integration: failed to write webhook response: %v", err)
}
})
// Create server
c.server = &http.Server{
Addr: fmt.Sprintf(":%d", c.port),
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
// Start server in a goroutine
go func() {
if err := c.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
fmt.Printf("Webhook server error: %v\n", err)
}
}()
c.connected = true
return nil
}
// Disconnect stops the webhook server
func (c *WebhookIntegrationConnector) Disconnect(ctx context.Context) error {
if c.server != nil {
err := c.server.Shutdown(ctx)
c.connected = false
return err
}
return nil
}
// IsConnected checks if the connector is connected
func (c *WebhookIntegrationConnector) IsConnected() bool {
return c.connected
}
// Execute is a no-op for webhook connectors (they are passive)
func (c *WebhookIntegrationConnector) Execute(ctx context.Context, action string, params map[string]any) (map[string]any, error) {
return map[string]any{"status": "webhook connectors do not support active execution"}, nil
}
// RegisterEventHandler registers a handler for a specific event type
func (c *WebhookIntegrationConnector) RegisterEventHandler(eventType string, handler func(context.Context, map[string]any) error) {
c.handlers[eventType] = handler
}
type IntegrationRegistry interface {
// Name returns the name of the registry
Name() string
// Init initializes the registry
Init(app modular.Application) error
// Start starts the registry
Start() error
// Stop stops the registry
Stop() error
// RegisterConnector registers a new integration connector
RegisterConnector(connector IntegrationConnector)
// GetConnector retrieves a connector by name
GetConnector(name string) (IntegrationConnector, error)
// ListConnectors lists all registered connectors
ListConnectors() []string
}
// StdIntegrationRegistry manages available integration connectors
type StdIntegrationRegistry struct {
name string
connectors map[string]IntegrationConnector
}
// NewIntegrationRegistry creates a new integration registry
func NewIntegrationRegistry(name string) *StdIntegrationRegistry {
return &StdIntegrationRegistry{
name: name,
connectors: make(map[string]IntegrationConnector),
}
}
// Name returns the module name
func (r *StdIntegrationRegistry) Name() string {
return r.name
}
// Init initializes the registry with service dependencies
func (r *StdIntegrationRegistry) Init(app modular.Application) error {
return app.RegisterService(r.name, r)
}
// Start starts all registered connectors
func (r *StdIntegrationRegistry) Start() error {
ctx := context.Background()
for name, connector := range r.connectors {
if err := connector.Connect(ctx); err != nil {
return fmt.Errorf("failed to start connector '%s': %w", name, err)
}
}
return nil
}
// Stop stops all registered connectors
func (r *StdIntegrationRegistry) Stop() error {
ctx := context.Background()
for name, connector := range r.connectors {
if err := connector.Disconnect(ctx); err != nil {
return fmt.Errorf("failed to stop connector '%s': %w", name, err)
}
}
return nil
}
// RegisterConnector adds a connector to the registry
func (r *StdIntegrationRegistry) RegisterConnector(connector IntegrationConnector) {
r.connectors[connector.GetName()] = connector
}
// GetConnector retrieves a connector by name
func (r *StdIntegrationRegistry) GetConnector(name string) (IntegrationConnector, error) {
connector, exists := r.connectors[name]
if !exists {
return nil, fmt.Errorf("connector '%s' not found", name)
}
return connector, nil
}
// ListConnectors returns all registered connectors
func (r *StdIntegrationRegistry) ListConnectors() []string {
names := make([]string, 0, len(r.connectors))
for name := range r.connectors {
names = append(names, name)
}
return names
}