100 lines
2.5 KiB
Go
100 lines
2.5 KiB
Go
package inbound
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxAPIResponseBodyBytes int64 = 4 * 1024 * 1024
|
|
|
|
func (s Server) post(ctx context.Context, path string, payload any, result any) error {
|
|
return s.postWithClient(ctx, s.HTTPClient, path, payload, result)
|
|
}
|
|
|
|
func (s Server) postWithClient(ctx context.Context, client *http.Client, path string, payload any, result any) error {
|
|
if client == nil {
|
|
client = &http.Client{Timeout: defaultHTTPTimeout}
|
|
}
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(apiBaseURL(s.APIBaseURL), "/")+path, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if strings.HasSuffix(path, "/security-detection") && s.SecurityEventToken != "" {
|
|
req.Header.Set("X-Security-Event-Token", s.SecurityEventToken)
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
// Read one byte beyond the supported boundary so an oversized upstream
|
|
// response is reported explicitly. Silently cutting JSON at the boundary
|
|
// turns a transport-capacity problem into a misleading syntax error and can
|
|
// leave recoverable downstream receipts stuck indefinitely.
|
|
responseBody, err := io.ReadAll(io.LimitReader(resp.Body, maxAPIResponseBodyBytes+1))
|
|
if err != nil {
|
|
return fmt.Errorf("read api response: %w", err)
|
|
}
|
|
if int64(len(responseBody)) > maxAPIResponseBodyBytes {
|
|
return fmt.Errorf("api response exceeds %d-byte limit", maxAPIResponseBodyBytes)
|
|
}
|
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
|
detail := strings.TrimSpace(string(responseBody))
|
|
if detail == "" {
|
|
return fmt.Errorf("api returned %s", resp.Status)
|
|
}
|
|
return fmt.Errorf("api returned %s: %s", resp.Status, detail)
|
|
}
|
|
if result != nil {
|
|
if len(responseBody) == 0 {
|
|
return io.EOF
|
|
}
|
|
return json.Unmarshal(responseBody, result)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func apiBaseURL(value string) string {
|
|
if value == "" {
|
|
return "http://127.0.0.1:3000/api"
|
|
}
|
|
return value
|
|
}
|
|
|
|
func remoteIP(addr net.Addr) string {
|
|
if tcp, ok := addr.(*net.TCPAddr); ok {
|
|
return tcp.IP.String()
|
|
}
|
|
host, _, err := net.SplitHostPort(addr.String())
|
|
if err == nil {
|
|
return host
|
|
}
|
|
return addr.String()
|
|
}
|
|
|
|
func defaultString(value string, fallback string) string {
|
|
if value == "" {
|
|
return fallback
|
|
}
|
|
return value
|
|
}
|
|
|
|
func formatRFC3339Nano(value time.Time) string {
|
|
if value.IsZero() {
|
|
return ""
|
|
}
|
|
return value.UTC().Format(time.RFC3339Nano)
|
|
}
|