-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
2058 lines (1712 loc) · 61.5 KB
/
Copy pathclient.go
File metadata and controls
2058 lines (1712 loc) · 61.5 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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package agent
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const (
// DefaultTimeout is the default HTTP request timeout.
DefaultTimeout = 30 * time.Second
// DefaultLogLines is the default number of log lines to fetch.
DefaultLogLines = 500
// MaxLogLines is the maximum number of log lines that can be requested.
MaxLogLines = 10000
)
// Client is an HTTP client for the HAProxy Agent API.
type Client struct {
baseURL string
apiKey string
kid string // optional; when set, sent as X-Gearbox-Kid header
onDrift DriftHandler
httpClient *http.Client
}
// HeaderKID is the request/response header name carrying the keyring
// entry id. The agent's middleware echoes the matched kid on every
// authenticated response (see middleware.ResponseHeaderKID); the
// dashboard sends this kid on outbound requests so the agent + audit
// log can correlate keys. Drift detection (Phase 5) compares the
// request-time kid with the echoed response kid.
const HeaderKID = "X-Gearbox-Kid"
// DriftHandler is invoked when the agent's echoed kid differs from
// the kid the client sent. Implementations typically log + surface a
// "rotation drift" banner; the default is to do nothing (set via
// SetDriftHandler).
//
// expected = what the client sent on the request
// actual = what the agent echoed back on the response
//
// The handler is called on the request goroutine; cheap operations
// only (logging is fine, network calls are not).
type DriftHandler func(expected, actual string)
// LogDriftHandler returns a DriftHandler that emits a structured
// warn-level log line — the lowest-friction wiring for a long-lived
// agent.Client. The "box_id" tag lets the operator filter the journal
// to a single box.
func LogDriftHandler(logger *slog.Logger, boxID int64) DriftHandler {
return func(expected, actual string) {
logger.Warn("rotation drift: agent matched a different kid than expected",
"box_id", boxID,
"expected_kid", expected,
"actual_kid", actual)
}
}
// NewClient creates a new HAProxy Agent API client.
func NewClient(baseURL, apiKey string) *Client {
return NewClientWithTimeout(baseURL, apiKey, DefaultTimeout)
}
// NewClientWithKID creates a client that also identifies the keyring
// entry it's signing with — the agent echoes back the matched kid in
// X-Gearbox-Kid and the dashboard compares the two to detect rotation
// drift. Empty kid is fine (legacy single-key boxes); the client just
// won't send the header.
func NewClientWithKID(baseURL, apiKey, kid string) *Client {
c := NewClient(baseURL, apiKey)
c.kid = kid
return c
}
// WithKID returns a shallow copy of c tagged with kid. Useful when a
// short-lived client wants to be rebuilt to point at a different
// keyring entry without re-doing TLS setup.
func (c *Client) WithKID(kid string) *Client {
clone := *c
clone.kid = kid
return &clone
}
// KID returns the kid this client signs requests with, or "" if it
// wasn't built with one. Used by the rotator and drift-detection
// paths.
func (c *Client) KID() string { return c.kid }
// SetDriftHandler installs a callback invoked when the agent's
// echoed X-Gearbox-Kid response header differs from the kid the
// client sent. Nil disables drift detection (the default).
//
// Use this on long-lived Client instances cached per box; the rotator
// builds short-lived clients per call and wouldn't benefit from
// installing a handler.
func (c *Client) SetDriftHandler(h DriftHandler) { c.onDrift = h }
// checkDrift inspects resp's X-Gearbox-Kid header against the kid the
// client sent. Called from each doRequest* path on success. No-op when
// the client has no kid or no handler is installed.
func (c *Client) checkDrift(resp *http.Response) {
if resp == nil || c.kid == "" || c.onDrift == nil {
return
}
actual := resp.Header.Get(HeaderKID)
if actual == "" || actual == c.kid {
return
}
c.onDrift(c.kid, actual)
}
// setAuthHeaders applies the standard auth + Accept headers and, when
// the client was built with a kid, the X-Gearbox-Kid request header.
// Callers must call this BEFORE setting Content-Type so their override
// wins (the helper deliberately doesn't set Content-Type — varied
// per-callsite based on whether the request has a body).
func (c *Client) setAuthHeaders(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Accept", "application/json")
if c.kid != "" {
req.Header.Set(HeaderKID, c.kid)
}
}
// NewClientWithTimeout creates a new HAProxy Agent API client with a custom timeout.
func NewClientWithTimeout(baseURL, apiKey string, timeout time.Duration) *Client {
// Ensure baseURL doesn't have trailing slash
baseURL = strings.TrimSuffix(baseURL, "/")
// SECURITY FIX: Implement certificate pinning instead of InsecureSkipVerify
// Create TLS configuration with certificate verification
tlsConfig := createTLSConfig()
transport := &http.Transport{
TLSClientConfig: tlsConfig,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}
// Retry up to 3 times on "no route to host" errors.
// macOS with multiple NICs on the same subnet can have
// intermittent routing failures due to IFSCOPE route expiry.
var lastErr error
for attempt := range 3 {
conn, err := dialer.DialContext(ctx, network, addr)
if err == nil {
if attempt > 0 {
log.Printf("[agent-client] dial succeeded on attempt %d for %s", attempt+1, addr)
}
return conn, nil
}
lastErr = err
// Only retry on "no route to host" errors
if !strings.Contains(err.Error(), "no route to host") {
return nil, err
}
log.Printf("[agent-client] dial attempt %d failed for %s: %v, retrying...", attempt+1, addr, err)
// Brief pause before retry to allow route refresh
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(500 * time.Millisecond):
}
}
return nil, lastErr
},
}
c := &Client{
baseURL: baseURL,
apiKey: apiKey,
}
c.httpClient = &http.Client{
Timeout: timeout,
// Wrap the base transport so every response is inspected for the
// X-Gearbox-Kid header against c.kid. The transport reads c.kid
// and c.onDrift at RoundTrip time, so SetDriftHandler is reflected
// immediately without rebuilding the client.
Transport: &kidObservingTransport{base: transport, c: c},
}
return c
}
// kidObservingTransport wraps an http.RoundTripper and invokes the
// owning Client's checkDrift on every successful response. Implements
// the drift-detection half of Phase 5 (issue #72) — the dashboard
// learns immediately when an agent's matched kid disagrees with the
// kid the dashboard sent, signalling a partial rotation.
type kidObservingTransport struct {
base http.RoundTripper
c *Client
}
func (t *kidObservingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
resp, err := t.base.RoundTrip(req)
if err == nil {
t.c.checkDrift(resp)
}
return resp, err
}
// BuildTLSConfig is the exported alias for createTLSConfig — used by
// code paths outside the HTTP client (e.g. the dashboard's console
// WebSocket proxy in handler/api_console.go) that need to dial agents
// with the same trust policy as a regular API call.
//
// Keeping a single implementation behind one exported entry point
// means a future operator who sets AGENT_CA_CERT_PATH gets both REST
// and WebSocket dials pinned in one place, instead of "REST is
// pinned but the WS proxy quietly accepts anything." See #89
// follow-up.
func BuildTLSConfig() *tls.Config {
return createTLSConfig()
}
// createTLSConfig creates a TLS configuration with certificate verification.
// Supports three modes via environment variables:
// 1. AGENT_CA_CERT_PATH: Path to CA certificate for validation (RECOMMENDED)
// 2. GEARBOX_INSECURE_TLS=true: Skip verification (NOT RECOMMENDED for production)
// 3. Default: Use system certificate pool
func createTLSConfig() *tls.Config {
// Check if user wants to skip TLS verification (insecure mode)
if os.Getenv("GEARBOX_INSECURE_TLS") == "true" {
// Log warning about insecure mode
// Note: In production code, use a proper logger
fmt.Fprintf(os.Stderr, "WARNING: TLS certificate verification is DISABLED (GEARBOX_INSECURE_TLS=true)\n")
fmt.Fprintf(os.Stderr, "WARNING: This is NOT recommended for production use\n")
return &tls.Config{
InsecureSkipVerify: true, //#nosec G402 -- User explicitly opted in via GEARBOX_INSECURE_TLS env var
MinVersion: tls.VersionTLS12,
}
}
// Check if custom CA certificate is provided
caCertPath := os.Getenv("AGENT_CA_CERT_PATH")
if caCertPath != "" {
// Load CA certificate for validating agent certificates
caCertPEM, err := os.ReadFile(caCertPath) //#nosec G304 -- Path from trusted env var AGENT_CA_CERT_PATH
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: Failed to read CA certificate from %s: %v\n", caCertPath, err)
fmt.Fprintf(os.Stderr, "ERROR: Falling back to system certificate pool\n")
return &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
// Create certificate pool with the CA certificate
caCertPool := x509.NewCertPool()
if !caCertPool.AppendCertsFromPEM(caCertPEM) {
fmt.Fprintf(os.Stderr, "ERROR: Failed to parse CA certificate from %s\n", caCertPath)
fmt.Fprintf(os.Stderr, "ERROR: Falling back to system certificate pool\n")
return &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
// Return TLS config with custom CA pool
return &tls.Config{
RootCAs: caCertPool,
MinVersion: tls.VersionTLS12,
}
}
// Default: Use system certificate pool with TLS 1.2+
return &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
// LongOperationTimeout is used for operations like apt update/install that may take several minutes.
const LongOperationTimeout = 5 * time.Minute
// parseErrorMessage extracts a meaningful error message from an HTTP error response body.
// It tries, in order:
// 1. JSON {"error": "..."} — used by structured API responses
// 2. JSON {"message": "..."} — used by jsonError responses
// 3. Plain text body (trimmed) — used by http.Error() in agent handlers
// 4. Generic "HTTP <code>: <status>" fallback
func parseErrorMessage(body []byte, statusCode int) string {
// Try JSON with "error" field
var errResp struct {
Error string `json:"error"`
}
if json.Unmarshal(body, &errResp) == nil && errResp.Error != "" {
return errResp.Error
}
// Try JSON with "message" field
var msgResp struct {
Message string `json:"message"`
}
if json.Unmarshal(body, &msgResp) == nil && msgResp.Message != "" {
return msgResp.Message
}
// Fall back to plain text body (http.Error sends text/plain)
if text := strings.TrimSpace(string(body)); text != "" {
return text
}
// Generic fallback
return fmt.Sprintf("HTTP %d: %s", statusCode, http.StatusText(statusCode))
}
// doRequest performs an HTTP request with authentication.
func (c *Client) doRequest(method, path string, query url.Values) ([]byte, error) {
fullURL := c.baseURL + path
if len(query) > 0 {
fullURL += "?" + query.Encode()
}
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
// Add bearer token authentication
c.setAuthHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
// Handle error status codes
if resp.StatusCode >= 400 {
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: parseErrorMessage(body, resp.StatusCode),
}
}
return body, nil
}
// doRequestLongRunning performs an HTTP request with an extended timeout for long-running operations
// like apt update/install that may take several minutes.
func (c *Client) doRequestLongRunning(method, path string, query url.Values) ([]byte, error) {
fullURL := c.baseURL + path
if len(query) > 0 {
fullURL += "?" + query.Encode()
}
ctx, cancel := context.WithTimeout(context.Background(), LongOperationTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, method, fullURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
c.setAuthHeaders(req)
// Use a separate client with extended timeout, sharing the same transport
longClient := &http.Client{
Timeout: LongOperationTimeout,
Transport: c.httpClient.Transport,
}
resp, err := longClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode >= 400 {
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: parseErrorMessage(body, resp.StatusCode),
}
}
return body, nil
}
// doRequestWithBody performs an HTTP request with a JSON body.
func (c *Client) doRequestWithBody(method, path string, reqBody interface{}) ([]byte, error) {
return c.doRequestWithBodyAndQuery(method, path, reqBody, nil)
}
// doRequestWithBodyAndQuery performs an HTTP request with a JSON body and query parameters.
func (c *Client) doRequestWithBodyAndQuery(method, path string, reqBody interface{}, query url.Values) ([]byte, error) {
fullURL := c.baseURL + path
if len(query) > 0 {
fullURL += "?" + query.Encode()
}
var bodyReader io.Reader
if reqBody != nil {
jsonBody, err := json.Marshal(reqBody)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
bodyReader = strings.NewReader(string(jsonBody))
}
req, err := http.NewRequest(method, fullURL, bodyReader)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
c.setAuthHeaders(req)
if reqBody != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode >= 400 {
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: parseErrorMessage(body, resp.StatusCode),
}
}
return body, nil
}
// doRequestNoAuth performs an HTTP request without authentication.
func (c *Client) doRequestNoAuth(method, path string) ([]byte, error) {
fullURL := c.baseURL + path
req, err := http.NewRequest(method, fullURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode >= 400 {
return nil, &APIError{
StatusCode: resp.StatusCode,
Message: fmt.Sprintf("HTTP %d: %s", resp.StatusCode, http.StatusText(resp.StatusCode)),
}
}
return body, nil
}
// Health checks if the agent is reachable (no authentication required).
func (c *Client) Health() (*HealthResponse, error) {
body, err := c.doRequestNoAuth("GET", "/health")
if err != nil {
return nil, err
}
var resp HealthResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse health response: %w", err)
}
return &resp, nil
}
// GetInfo retrieves HAProxy runtime information.
func (c *Client) GetInfo() (*RuntimeInfo, error) {
body, err := c.doRequest("GET", "/api/v1/haproxy/info", nil)
if err != nil {
return nil, err
}
var resp RuntimeInfo
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse info response: %w", err)
}
return &resp, nil
}
// GetStats retrieves HAProxy statistics as parsed JSON.
func (c *Client) GetStats() (*StatsResponse, error) {
body, err := c.doRequest("GET", "/api/v1/haproxy/stats", nil)
if err != nil {
return nil, err
}
var resp StatsResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse stats response: %w", err)
}
return &resp, nil
}
// GetStatsCSV retrieves HAProxy statistics in raw CSV format.
func (c *Client) GetStatsCSV() (string, error) {
query := url.Values{}
query.Set("format", "csv")
body, err := c.doRequest("GET", "/api/v1/haproxy/stats", query)
if err != nil {
return "", err
}
return string(body), nil
}
// GetStickTables retrieves HAProxy stick table information.
func (c *Client) GetStickTables() (*StickTablesResponse, error) {
body, err := c.doRequest("GET", "/api/v1/haproxy/tables", nil)
if err != nil {
return nil, err
}
var resp StickTablesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse stick tables response: %w", err)
}
return &resp, nil
}
// ValidateConfig validates the HAProxy configuration.
func (c *Client) ValidateConfig() (*ConfigValidationResponse, error) {
body, err := c.doRequest("GET", "/api/v1/haproxy/validate", nil)
if err != nil {
return nil, err
}
var resp ConfigValidationResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse validation response: %w", err)
}
return &resp, nil
}
// GetMetrics retrieves system metrics.
func (c *Client) GetMetrics() (*MetricsResponse, error) {
body, err := c.doRequest("GET", "/api/v1/metrics", nil)
if err != nil {
return nil, err
}
var resp MetricsResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse metrics response: %w", err)
}
return &resp, nil
}
// GetServices retrieves the status of specified services.
// If services is nil or empty, returns the default monitored services.
func (c *Client) GetServices(services []string) (*ServicesResponse, error) {
var query url.Values
if len(services) > 0 {
query = url.Values{}
query.Set("services", strings.Join(services, ","))
}
body, err := c.doRequest("GET", "/api/v1/services", query)
if err != nil {
return nil, err
}
var resp ServicesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse services response: %w", err)
}
return &resp, nil
}
// GetAvailableServices retrieves the list of all available systemd services on the target system.
func (c *Client) GetAvailableServices() (*AvailableServicesResponse, error) {
body, err := c.doRequest("GET", "/api/v1/services/available", nil)
if err != nil {
return nil, err
}
var resp AvailableServicesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse available services response: %w", err)
}
return &resp, nil
}
// GetLogSources retrieves the list of available log sources.
func (c *Client) GetLogSources() (*LogSourcesResponse, error) {
body, err := c.doRequest("GET", "/api/v1/logs", nil)
if err != nil {
return nil, err
}
var resp LogSourcesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse log sources response: %w", err)
}
return &resp, nil
}
// GetLogs retrieves logs from a specific source.
// Lines must be between 1 and 10000, or 0 to use the default (500).
func (c *Client) GetLogs(name string, lines int) (*LogResponse, error) {
if lines < 0 {
lines = DefaultLogLines
}
if lines > MaxLogLines {
lines = MaxLogLines
}
query := url.Values{}
if lines > 0 {
query.Set("lines", strconv.Itoa(lines))
}
path := "/api/v1/logs/" + url.PathEscape(name)
body, err := c.doRequest("GET", path, query)
if err != nil {
return nil, err
}
var resp LogResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse log response: %w", err)
}
return &resp, nil
}
// GetSecuritySummary retrieves a brief security overview.
func (c *Client) GetSecuritySummary() (*SecuritySummary, error) {
body, err := c.doRequest("GET", "/api/v1/security/summary", nil)
if err != nil {
return nil, err
}
var resp SecuritySummary
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse security summary response: %w", err)
}
return &resp, nil
}
// Fail2BanOptions configures the GetFail2BanStats request.
type Fail2BanOptions struct {
IncludeIPs bool // Include banned IP addresses
Recent int // Number of recent bans to include (0-100)
}
// GetFail2BanStats retrieves detailed fail2ban statistics.
func (c *Client) GetFail2BanStats(opts *Fail2BanOptions) (*Fail2BanStats, error) {
var query url.Values
if opts != nil {
query = url.Values{}
if opts.IncludeIPs {
query.Set("include_ips", "true")
}
if opts.Recent > 0 {
if opts.Recent > 100 {
opts.Recent = 100
}
query.Set("recent", strconv.Itoa(opts.Recent))
}
}
body, err := c.doRequest("GET", "/api/v1/security/fail2ban", query)
if err != nil {
return nil, err
}
var resp Fail2BanStats
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse fail2ban stats response: %w", err)
}
return &resp, nil
}
// FirewallOptions configures the GetFirewallStats request.
type FirewallOptions struct {
IncludeRules bool // Include firewall rules
Recent int // Number of recent blocks to include (0-100)
}
// GetFirewallStats retrieves detailed firewall statistics.
func (c *Client) GetFirewallStats(opts *FirewallOptions) (*FirewallStats, error) {
var query url.Values
if opts != nil {
query = url.Values{}
if opts.IncludeRules {
query.Set("include_rules", "true")
}
if opts.Recent > 0 {
if opts.Recent > 100 {
opts.Recent = 100
}
query.Set("recent", strconv.Itoa(opts.Recent))
}
}
body, err := c.doRequest("GET", "/api/v1/security/firewall", query)
if err != nil {
return nil, err
}
var resp FirewallStats
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse firewall stats response: %w", err)
}
return &resp, nil
}
// GetSyncStatus retrieves the git sync status.
func (c *Client) GetSyncStatus() (*SyncStatusResponse, error) {
body, err := c.doRequest("GET", "/api/v1/sync/status", nil)
if err != nil {
return nil, err
}
var resp SyncStatusResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse sync status response: %w", err)
}
return &resp, nil
}
// GetMetadata retrieves HAProxy configuration metadata.
func (c *Client) GetMetadata() (*MetadataResponse, error) {
body, err := c.doRequest("GET", "/api/v1/metadata", nil)
if err != nil {
return nil, err
}
var resp MetadataResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse metadata response: %w", err)
}
return &resp, nil
}
// GetWebSocketInfo retrieves WebSocket configuration information.
func (c *Client) GetWebSocketInfo() (*WSInfoResponse, error) {
body, err := c.doRequest("GET", "/api/v1/events/info", nil)
if err != nil {
return nil, err
}
var resp WSInfoResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse websocket info response: %w", err)
}
return &resp, nil
}
// GetWebSocketToken retrieves a token for WebSocket authentication.
// The token is valid for 60 seconds.
func (c *Client) GetWebSocketToken() (*WSTokenResponse, error) {
body, err := c.doRequest("POST", "/api/v1/events/token", nil)
if err != nil {
return nil, err
}
var resp WSTokenResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse websocket token response: %w", err)
}
return &resp, nil
}
// GetWebhookInfo retrieves webhook configuration information.
func (c *Client) GetWebhookInfo() (*WebhookInfoResponse, error) {
body, err := c.doRequest("GET", "/api/v1/webhook/info", nil)
if err != nil {
return nil, err
}
var resp WebhookInfoResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse webhook info response: %w", err)
}
return &resp, nil
}
// GetCertificates retrieves certificate information and metrics.
func (c *Client) GetCertificates() (*CertificatesResponse, error) {
body, err := c.doRequest("GET", "/api/v1/certificates", nil)
if err != nil {
return nil, err
}
var resp CertificatesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse certificates response: %w", err)
}
return &resp, nil
}
// RefreshCertificate triggers a certificate renewal for the specified domain.
// This will renew the certificate using acme.sh, install it to HAProxy, and reload HAProxy.
func (c *Client) RefreshCertificate(domain string) (*RefreshCertificateResponse, error) {
path := "/api/v1/certificates/" + url.PathEscape(domain) + "/refresh"
body, err := c.doRequest("POST", path, nil)
if err != nil {
return nil, err
}
var resp RefreshCertificateResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse refresh certificate response: %w", err)
}
return &resp, nil
}
// DownloadCertificate downloads a certificate PEM file for the specified domain.
// Returns the certificate data, filename, and any error.
func (c *Client) DownloadCertificate(domain string) ([]byte, string, error) {
path := "/api/v1/certificates/" + url.PathEscape(domain) + "/download"
fullURL := c.baseURL + path
req, err := http.NewRequest("GET", fullURL, nil)
if err != nil {
return nil, "", fmt.Errorf("failed to create request: %w", err)
}
c.setAuthHeaders(req)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
return nil, "", &APIError{
StatusCode: resp.StatusCode,
Message: string(body),
}
}
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", fmt.Errorf("failed to read response body: %w", err)
}
// Extract filename from Content-Disposition header, or use default
filename := domain + ".pem"
if cd := resp.Header.Get("Content-Disposition"); cd != "" {
// Parse "attachment; filename="example.pem""
if strings.Contains(cd, "filename=") {
parts := strings.Split(cd, "filename=")
if len(parts) > 1 {
filename = strings.Trim(parts[1], "\"")
}
}
}
return data, filename, nil
}
// GetTraffic retrieves detailed traffic analysis data.
func (c *Client) GetTraffic(limit, topN int) (*TrafficResponse, error) {
query := url.Values{}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if topN > 0 {
query.Set("top_n", strconv.Itoa(topN))
}
body, err := c.doRequest("GET", "/api/v1/traffic", query)
if err != nil {
return nil, err
}
var resp TrafficResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse traffic response: %w", err)
}
return &resp, nil
}
// GetTrafficSummary retrieves a summary of traffic statistics.
func (c *Client) GetTrafficSummary() (*TrafficSummaryResponse, error) {
body, err := c.doRequest("GET", "/api/v1/traffic/summary", nil)
if err != nil {
return nil, err
}
var resp TrafficSummaryResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse traffic summary response: %w", err)
}
return &resp, nil
}
// GetCapabilities retrieves the agent's probe table — every registered
// gear's availability verdict and detected capability key-values. Used by
// the dashboard's Gears settings page to hide gears the active box can't
// run (issue #71 item 2).
func (c *Client) GetCapabilities() (*CapabilitiesResponse, error) {
body, err := c.doRequest("GET", "/api/v1/system/capabilities", nil)
if err != nil {
return nil, err
}
var resp CapabilitiesResponse
if err := json.Unmarshal(body, &resp); err != nil {
return nil, fmt.Errorf("failed to parse capabilities response: %w", err)
}
return &resp, nil
}
// IsAPIError checks if an error is an API error and returns it.
func IsAPIError(err error) (*APIError, bool) {
if apiErr, ok := err.(*APIError); ok {
return apiErr, true
}
return nil, false
}
// BlockIPRequest represents a request to block an IP address.
type BlockIPRequest struct {
IP string `json:"ip"`
Reason string `json:"reason"`
}
// BlockIPResponse represents the response from blocking an IP.
type BlockIPResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
IP string `json:"ip"`
}
// BlockedIPInfo represents information about a blocked IP.
type BlockedIPInfo struct {
IP string `json:"ip"`
Packets int64 `json:"packets"`
Bytes int64 `json:"bytes"`
}
// BlockedIPsResponse represents the list of blocked IPs from the agent.
type BlockedIPsResponse struct {
Available bool `json:"available"`