-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
808 lines (669 loc) · 23.2 KB
/
Copy pathclient.go
File metadata and controls
808 lines (669 loc) · 23.2 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
package bluecat
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/netip"
"strings"
"time"
"github.com/libdns/libdns"
)
// Client handles communication with the Bluecat API
type Client struct {
baseURL string
username string
password string
httpClient *http.Client
apiToken string
authHeader string
// deployPollInterval is how often to poll for deployment completion (default 3s).
deployPollInterval time.Duration
// deployPollTimeout is how long to wait for a deployment to complete (default 120s).
deployPollTimeout time.Duration
}
// NewClient creates a new Bluecat API client
func NewClient(baseURL, username, password string) (*Client, error) {
// Trim trailing slash from baseURL
baseURL = strings.TrimSuffix(baseURL, "/")
return &Client{
baseURL: baseURL,
username: username,
password: password,
httpClient: &http.Client{
Timeout: 180 * time.Second,
},
deployPollInterval: 3 * time.Second,
deployPollTimeout: 120 * time.Second,
}, nil
}
// Authenticate authenticates with the Bluecat API and stores the token
func (c *Client) Authenticate(ctx context.Context) error {
url := c.baseURL + "/api/v2/sessions"
reqBody := map[string]string{
"username": c.username,
"password": c.password,
}
body, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal auth request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("failed to create auth request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to authenticate: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf("authentication failed with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var authResp struct {
APIToken string `json:"apiToken"`
BasicAuthenticationCredentials string `json:"basicAuthenticationCredentials"`
}
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return fmt.Errorf("failed to decode auth response: %w", err)
}
c.apiToken = authResp.APIToken
c.authHeader = authResp.BasicAuthenticationCredentials
return nil
}
// GetZoneID retrieves the zone ID for a given zone name
func (c *Client) GetZoneID(ctx context.Context, zone, configName, viewName string) (int64, error) {
// Clean up zone name (remove trailing dot)
zone = strings.TrimSuffix(zone, ".")
// Try to find the most specific zone by searching with absoluteName filter
// Walk from most specific to least specific
domainParts := strings.Split(zone, ".")
for i := 0; i < len(domainParts); i++ {
searchZone := strings.Join(domainParts[i:], ".")
if searchZone == "" {
continue
}
// Use filter to search for zone by absoluteName
apiURL := fmt.Sprintf("%s/api/v2/zones?filter=absoluteName:eq('%s')", c.baseURL, searchZone)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
continue
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
continue
}
if resp.StatusCode == http.StatusOK {
var zonesResp struct {
Data []struct {
ID int64 `json:"id"`
Name string `json:"name"`
AbsoluteName string `json:"absoluteName"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&zonesResp); err == nil && len(zonesResp.Data) > 0 {
resp.Body.Close()
return zonesResp.Data[0].ID, nil
}
}
resp.Body.Close()
}
return 0, fmt.Errorf("no zone found for %s", zone)
}
// GetResourceRecords retrieves all resource records for a zone.
// Note: This only fetches the first page of records (up to 1000).
// For Caddy ACME use case, records are deleted using stored IDs, so full enumeration is not needed.
func (c *Client) GetResourceRecords(ctx context.Context, zoneID int64, zone string) ([]libdns.Record, error) {
url := fmt.Sprintf("%s/api/v2/zones/%d/resourceRecords", c.baseURL, zoneID)
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to get resource records: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("failed to get resource records with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var recordsResp struct {
Data []BluecatResourceRecord `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&recordsResp); err != nil {
return nil, fmt.Errorf("failed to decode resource records: %w", err)
}
// Convert Bluecat records to libdns records
var records []libdns.Record
for _, bcRec := range recordsResp.Data {
rec, err := convertBluecatToLibdns(bcRec, zone)
if err != nil {
// Skip records we can't convert
continue
}
records = append(records, rec)
}
return records, nil
}
// CreateResourceRecord creates a new resource record in the specified zone
func (c *Client) CreateResourceRecord(ctx context.Context, zoneID int64, zone string, record libdns.Record) (libdns.Record, error) {
url := fmt.Sprintf("%s/api/v2/zones/%d/resourceRecords", c.baseURL, zoneID)
bcRecord, err := convertLibdnsToBluecat(record, zone)
if err != nil {
return nil, fmt.Errorf("failed to convert record: %w", err)
}
body, err := json.Marshal(bcRecord)
if err != nil {
return nil, fmt.Errorf("failed to marshal record: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to create resource record: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("failed to create resource record with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var createdRecord BluecatResourceRecord
if err := json.NewDecoder(resp.Body).Decode(&createdRecord); err != nil {
return nil, fmt.Errorf("failed to decode created record: %w", err)
}
return convertBluecatToLibdns(createdRecord, zone)
}
// DeleteResourceRecord deletes a resource record
func (c *Client) DeleteResourceRecord(ctx context.Context, record libdns.Record) error {
// Extract the record ID from ProviderData
recordID := getRecordID(record)
if recordID == 0 {
return fmt.Errorf("record ID not found in provider data")
}
url := fmt.Sprintf("%s/api/v2/resourceRecords/%d", c.baseURL, recordID)
req, err := http.NewRequestWithContext(ctx, "DELETE", url, nil)
if err != nil {
return fmt.Errorf("failed to create delete request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to delete resource record: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to delete resource record with status %d: %s", resp.StatusCode, string(bodyBytes))
}
return nil
}
// bluecatDeployment is the subset of the Bluecat deployment resource we need.
type bluecatDeployment struct {
ID int64 `json:"id"`
Status string `json:"status"`
}
// DeployZone triggers a quick deployment of changes for a specific zone and
// waits until Bluecat confirms the deployment is complete.
func (c *Client) DeployZone(ctx context.Context, zoneID int64) error {
url := fmt.Sprintf("%s/api/v2/zones/%d/deployments", c.baseURL, zoneID)
// Use QuickDeployment type for immediate deployment
payload := map[string]string{
"type": "QuickDeployment",
}
body, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("failed to marshal deployment payload: %w", err)
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("failed to create deployment request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to deploy zone: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted {
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to deploy zone with status %d: %s", resp.StatusCode, string(bodyBytes))
}
// 201/200: deployment is already complete.
if resp.StatusCode != http.StatusAccepted {
return nil
}
// 202: deployment is queued/running. Parse the deployment ID and poll
// until Bluecat reports it as complete so the caller (certmagic) doesn't
// start its DNS propagation check before the record is actually live.
var dep bluecatDeployment
if err := json.NewDecoder(resp.Body).Decode(&dep); err != nil || dep.ID == 0 {
// Response body didn't contain a parseable deployment ID.
// Fall back to a best-effort fixed wait so we don't block forever.
return c.waitForDeploymentFallback(ctx)
}
return c.waitForDeployment(ctx, dep.ID)
}
// waitForDeployment polls GET /api/v2/deployments/{id} until status is terminal.
func (c *Client) waitForDeployment(ctx context.Context, deployID int64) error {
pollURL := fmt.Sprintf("%s/api/v2/deployments/%d", c.baseURL, deployID)
deadline := time.Now().Add(c.deployPollTimeout)
for {
if time.Now().After(deadline) {
return fmt.Errorf("timed out waiting for deployment %d to complete", deployID)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(c.deployPollInterval):
}
req, err := http.NewRequestWithContext(ctx, "GET", pollURL, nil)
if err != nil {
return fmt.Errorf("failed to create deployment poll request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
// Transient network error — keep polling.
continue
}
var dep bluecatDeployment
decodeErr := json.NewDecoder(resp.Body).Decode(&dep)
resp.Body.Close()
if decodeErr != nil {
continue
}
switch dep.Status {
case "COMPLETE", "DONE", "SUCCESS":
return nil
case "FAILED", "ERROR", "CANCELLED":
return fmt.Errorf("deployment %d finished with status %s", deployID, dep.Status)
// QUEUED, RUNNING, and any unknown status: keep polling.
}
}
}
// waitForDeploymentFallback is used when the 202 response body didn't contain a
// deployment ID. It waits one poll interval as a best-effort settle time.
func (c *Client) waitForDeploymentFallback(ctx context.Context) error {
select {
case <-time.After(c.deployPollInterval):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// getConfigurationID retrieves the configuration ID by name, or the first one if name is empty
func (c *Client) getConfigurationID(ctx context.Context, configName string) (int64, error) {
apiURL := c.baseURL + "/api/v2/configurations"
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return 0, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, fmt.Errorf("failed to get configurations: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return 0, fmt.Errorf("failed to get configurations with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var configResp struct {
Data []struct {
ID int64 `json:"id"`
Name string `json:"name"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&configResp); err != nil {
return 0, fmt.Errorf("failed to decode configurations: %w", err)
}
if len(configResp.Data) == 0 {
return 0, fmt.Errorf("no configurations found")
}
// If a specific config name was requested, find it
if configName != "" {
for _, cfg := range configResp.Data {
if cfg.Name == configName {
return cfg.ID, nil
}
}
return 0, fmt.Errorf("configuration %s not found", configName)
}
// Otherwise return the first one
return configResp.Data[0].ID, nil
}
// getViewID retrieves the view ID by name, or the first one if name is empty
func (c *Client) getViewID(ctx context.Context, configID int64, viewName string) (int64, error) {
apiURL := fmt.Sprintf("%s/api/v2/configurations/%d/views", c.baseURL, configID)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return 0, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return 0, fmt.Errorf("failed to get views: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return 0, fmt.Errorf("failed to get views with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var viewResp struct {
Data []struct {
ID int64 `json:"id"`
Name string `json:"name"`
} `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&viewResp); err != nil {
return 0, fmt.Errorf("failed to decode views: %w", err)
}
if len(viewResp.Data) == 0 {
return 0, fmt.Errorf("no views found")
}
// If a specific view name was requested, find it
if viewName != "" {
for _, v := range viewResp.Data {
if v.Name == viewName {
return v.ID, nil
}
}
return 0, fmt.Errorf("view %s not found", viewName)
}
// Otherwise return the first one
return viewResp.Data[0].ID, nil
}
// BluecatResourceRecord represents a resource record in the Bluecat API
type BluecatResourceRecord struct {
ID int64 `json:"id,omitempty"`
Type string `json:"type"`
Name string `json:"name"`
AbsoluteName string `json:"absoluteName,omitempty"`
TTL int `json:"ttl,omitempty"`
RecordType string `json:"recordType,omitempty"`
RData string `json:"rdata,omitempty"`
Text string `json:"text,omitempty"`
LinkedRecordName string `json:"linkedRecordName,omitempty"`
Priority int `json:"priority,omitempty"`
Weight int `json:"weight,omitempty"`
Port int `json:"port,omitempty"`
Addresses []struct {
Address string `json:"address"`
} `json:"addresses,omitempty"`
}
// normalizeRecordName returns a zone-relative libdns name.
// It accepts either a relative name (e.g. "_acme-challenge") or
// an absolute name (e.g. "_acme-challenge.example.com.").
func normalizeRecordName(name, zone string) string {
zone = strings.TrimSuffix(zone, ".")
name = strings.TrimSuffix(name, ".")
if name == "" || name == "@" || name == zone {
return "@"
}
if strings.HasSuffix(name, "."+zone) {
return strings.TrimSuffix(name, "."+zone)
}
return name
}
// convertBluecatToLibdns converts a Bluecat resource record to a libdns record
func convertBluecatToLibdns(bcRec BluecatResourceRecord, zone string) (libdns.Record, error) {
// Clean up zone
zone = strings.TrimSuffix(zone, ".")
// Calculate relative name from absoluteName
var name string
if bcRec.AbsoluteName != "" {
// Use absoluteName to calculate the relative name
absName := strings.TrimSuffix(bcRec.AbsoluteName, ".")
if absName == zone {
name = "@"
} else if strings.HasSuffix(absName, "."+zone) {
name = strings.TrimSuffix(absName, "."+zone)
} else {
// Fallback to name field
name = bcRec.Name
}
} else {
name = bcRec.Name
}
if name == "" {
name = "@"
}
ttl := time.Duration(bcRec.TTL) * time.Second
// Determine the record type and create appropriate struct
switch bcRec.RecordType {
case "A", "AAAA":
// HostRecord uses addresses field
var ipStr string
if len(bcRec.Addresses) > 0 {
ipStr = bcRec.Addresses[0].Address
} else if bcRec.RData != "" {
ipStr = bcRec.RData
} else {
return nil, fmt.Errorf("no IP address found in record")
}
addr, err := netip.ParseAddr(ipStr)
if err != nil {
return nil, fmt.Errorf("failed to parse IP address: %w", err)
}
return libdns.Address{
Name: name,
TTL: ttl,
IP: addr,
ProviderData: bcRec.ID,
}, nil
case "CNAME":
return libdns.CNAME{
Name: name,
TTL: ttl,
Target: bcRec.LinkedRecordName,
ProviderData: bcRec.ID,
}, nil
case "TXT":
// TXTRecord uses 'text' field
textData := bcRec.Text
if textData == "" {
textData = bcRec.RData
}
return libdns.TXT{
Name: name,
TTL: ttl,
Text: textData,
ProviderData: bcRec.ID,
}, nil
case "MX":
return libdns.MX{
Name: name,
TTL: ttl,
Preference: uint16(bcRec.Priority),
Target: bcRec.LinkedRecordName,
ProviderData: bcRec.ID,
}, nil
case "NS":
return libdns.NS{
Name: name,
TTL: ttl,
Target: bcRec.LinkedRecordName,
ProviderData: bcRec.ID,
}, nil
case "SRV":
// Parse service and protocol from name (format: _service._protocol.name)
parts := strings.SplitN(name, ".", 3)
var service, protocol, recordName string
if len(parts) >= 3 {
service = strings.TrimPrefix(parts[0], "_")
protocol = strings.TrimPrefix(parts[1], "_")
recordName = parts[2]
}
return libdns.SRV{
Service: service,
Transport: protocol,
Name: recordName,
TTL: ttl,
Priority: uint16(bcRec.Priority),
Weight: uint16(bcRec.Weight),
Port: uint16(bcRec.Port),
Target: bcRec.LinkedRecordName,
ProviderData: bcRec.ID,
}, nil
default:
// Skip unsupported record types rather than returning generic RR
// as per libdns documentation requirements
return nil, fmt.Errorf("unsupported record type: %s", bcRec.RecordType)
}
}
// convertLibdnsToBluecat converts a libdns record to a Bluecat resource record
func convertLibdnsToBluecat(record libdns.Record, zone string) (BluecatResourceRecord, error) {
rr := record.RR()
// Remove trailing dot from zone for proper absolute name construction
zone = strings.TrimSuffix(zone, ".")
relativeName := normalizeRecordName(rr.Name, zone)
// Construct absolute name
var absoluteName string
if relativeName == "@" {
absoluteName = zone
} else {
absoluteName = relativeName + "." + zone
}
bcRec := BluecatResourceRecord{
Name: relativeName,
AbsoluteName: absoluteName,
TTL: int(rr.TTL.Seconds()),
}
// Set type-specific fields with proper Bluecat type names
switch rec := record.(type) {
case libdns.Address:
// Use HostRecord type for A/AAAA records
bcRec.Type = "HostRecord"
if rec.IP.Is4() {
bcRec.RecordType = "A"
} else {
bcRec.RecordType = "AAAA"
}
// HostRecord requires addresses field instead of rdata
bcRec.Addresses = []struct {
Address string `json:"address"`
}{
{Address: rec.IP.String()},
}
case libdns.CNAME:
bcRec.Type = "AliasRecord"
bcRec.RecordType = "CNAME"
bcRec.LinkedRecordName = rec.Target
case libdns.TXT:
bcRec.Type = "TXTRecord"
bcRec.RecordType = "TXT"
// TXTRecord uses 'text' field
bcRec.Text = rec.Text
case libdns.MX:
bcRec.Type = "MXRecord"
bcRec.RecordType = "MX"
bcRec.Priority = int(rec.Preference)
bcRec.LinkedRecordName = rec.Target
case libdns.NS:
bcRec.Type = "GenericRecord"
bcRec.RecordType = "NS"
bcRec.LinkedRecordName = rec.Target
case libdns.SRV:
bcRec.Type = "SRVRecord"
bcRec.RecordType = "SRV"
// Construct the full SRV name: _service._protocol.name
recordName := normalizeRecordName(rec.Name, zone)
bcRec.Name = fmt.Sprintf("_%s._%s.%s", rec.Service, rec.Transport, recordName)
if recordName == "@" {
bcRec.AbsoluteName = fmt.Sprintf("_%s._%s.%s", rec.Service, rec.Transport, zone)
} else {
bcRec.AbsoluteName = fmt.Sprintf("_%s._%s.%s.%s", rec.Service, rec.Transport, recordName, zone)
}
bcRec.Priority = int(rec.Priority)
bcRec.Weight = int(rec.Weight)
bcRec.Port = int(rec.Port)
bcRec.LinkedRecordName = rec.Target
case libdns.RR:
bcRec.Type = "GenericRecord"
bcRec.RecordType = rec.Type
bcRec.RData = rec.Data
}
// Parse TTL if provided in string form
if bcRec.TTL == 0 && rr.TTL > 0 {
bcRec.TTL = int(rr.TTL.Seconds())
}
return bcRec, nil
}
// GetResourceRecordByAbsoluteName searches for a resource record by its absolute name and type
// using BlueCat's filter API. This is useful when we need to find a record without knowing
// which zone it's directly under.
func (c *Client) GetResourceRecordByAbsoluteName(ctx context.Context, absoluteName, recordType string) (*BluecatResourceRecord, error) {
absoluteName = strings.TrimSuffix(absoluteName, ".")
// Build the filter query - search by absoluteName
// BlueCat API v2 supports filtering on resourceRecords endpoint
apiURL := fmt.Sprintf("%s/api/v2/resourceRecords?filter=absoluteName:eq('%s')", c.baseURL, absoluteName)
if recordType != "" {
apiURL += fmt.Sprintf(" and recordType:eq('%s')", recordType)
}
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to search resource records: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("failed to search resource records with status %d: %s", resp.StatusCode, string(bodyBytes))
}
var recordsResp struct {
Data []BluecatResourceRecord `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&recordsResp); err != nil {
return nil, fmt.Errorf("failed to decode resource records: %w", err)
}
if len(recordsResp.Data) == 0 {
return nil, nil
}
return &recordsResp.Data[0], nil
}
// DeleteResourceRecordByID deletes a resource record by its ID directly
func (c *Client) DeleteResourceRecordByID(ctx context.Context, recordID int64) error {
if recordID == 0 {
return fmt.Errorf("record ID cannot be zero")
}
url := fmt.Sprintf("%s/api/v2/resourceRecords/%d", c.baseURL, recordID)
req, err := http.NewRequestWithContext(ctx, "DELETE", url, nil)
if err != nil {
return fmt.Errorf("failed to create delete request: %w", err)
}
req.Header.Set("Authorization", "Basic "+c.authHeader)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to delete resource record: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to delete resource record with status %d: %s", resp.StatusCode, string(bodyBytes))
}
return nil
}