/
client.go
2560 lines (2255 loc) · 73.2 KB
/
client.go
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 client
import (
"bytes"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"github.com/ProtonMail/go-crypto/openpgp/clearsign"
"github.com/timapril/go-registrar/epp"
"github.com/timapril/go-registrar/keychain"
"github.com/timapril/go-registrar/lib"
"github.com/timapril/go-registrar/whois/objects"
"github.com/howeyc/gopass"
logging "github.com/op/go-logging"
)
var format = logging.MustStringFormatter(
"%{color}%{level:.4s} %{time:15:04:05.000000} %{shortfile} %{longfunc} %{callpath} %{id:03x}%{color:reset} %{message}",
)
// DiskCacheConfig is used to include in configruations files to handle the
// initialization of Disk Caches
type DiskCacheConfig struct {
CacheDirectory string
Enabled bool
UseHints bool
}
// DiskCache is used to handle the storage and reterival of objects stored on
// the local disk
type DiskCache struct {
Enabled bool
BasePath string
UseHints bool
log *logging.Logger
}
// NewDiskCache will generate an initialize a disk cache using the
// DiskCacheConfig passed
func NewDiskCache(dcc DiskCacheConfig, log *logging.Logger) (DiskCache, error) {
cache := DiskCache{
BasePath: dcc.CacheDirectory,
Enabled: dcc.Enabled,
UseHints: dcc.UseHints,
log: log,
}
createRootErr := createDirIfNotExist(dcc.CacheDirectory, log)
if createRootErr != nil {
return cache, createRootErr
}
createCrErr := createDirIfNotExist(path.Join(dcc.CacheDirectory, lib.ChangeRequestType), log)
if createCrErr != nil {
return cache, createCrErr
}
createObjectErr := createDirIfNotExist(path.Join(dcc.CacheDirectory, "object"), log)
if createObjectErr != nil {
return cache, createObjectErr
}
createRevisionErr := createDirIfNotExist(path.Join(dcc.CacheDirectory, "snapshots"), log)
if createRevisionErr != nil {
return cache, createRevisionErr
}
return cache, nil
}
// GetObject will attempt to reterive the object of the type passed with the id
// pass from disk otherwise an error will be returned
func (d *DiskCache) GetObject(objType string, id int64, lastUpdate *time.Time) (outObj lib.RegistrarObjectExport, errs []error) {
d.log.Debugf("Checking for %s with the ID of %d", objType, id)
var filePath string
if objType == lib.ChangeRequestType {
filePath = d.changeRequestPath(id)
} else {
filePath = d.objectPath(objType, id)
}
fc, err := os.ReadFile(filePath)
if err != nil {
d.log.Error(err)
errs = append(errs, err)
return
}
var oc ObjectCache
err = json.Unmarshal(fc, &oc)
if err != nil {
d.log.Error(err)
errs = append(errs, err)
return
}
obj, objErr := oc.Response.GetRegistrarObject()
needsRefresh := false
if lastUpdate != nil {
switch t := obj.(type) {
case lib.ContactExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
case lib.HostExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
case lib.DomainExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
}
}
if needsRefresh {
errs = append(errs, errors.New("Objects needs to be refreshed"))
return outObj, errs
}
return obj, objErr
}
// GetObjectAt will attempt to retrieve the object type with the id passed at
// the timestamp given. If no object is caches for that timestamp, an error
// is returned
func (d *DiskCache) GetObjectAt(objectType string, id int64, timestamp int64, od ObjectDirectory) (outObj lib.RegistrarObjectExport, errs []error) {
d.log.Debugf("Checking for %s with the ID of %d @ %d", objectType, id, timestamp)
if d.UseHints {
var hint int64
var lastUpdate time.Time
canHandle := false
switch objectType {
case lib.DomainType:
if val, ok := od.DomainHints[id]; ok {
hint = val.RevisionID
lastUpdate = val.LastUpdate
canHandle = true
}
case lib.ContactType:
if val, ok := od.ContactHints[id]; ok {
hint = val.RevisionID
lastUpdate = val.LastUpdate
canHandle = true
}
case lib.HostType:
if val, ok := od.HostHints[id]; ok {
hint = val.RevisionID
lastUpdate = val.LastUpdate
canHandle = true
}
default:
canHandle = false
}
if canHandle {
outObj, errs = d.getSnapshotObject(objectType, hint, &lastUpdate)
if len(errs) == 0 {
return
}
}
}
return d.getRevisionObject(objectType, id, timestamp, nil)
}
// ObjectCache is used to serialize and object into the disk cache
type ObjectCache struct {
Response lib.APIResponse
}
// ErrUnexpectedObject represents an unexpected object type received
var ErrUnexpectedObject = errors.New("unexpected object")
// SaveObject will take the given object and save it to disk in the cache
func (d *DiskCache) SaveObject(resp lib.APIResponse) error {
oc := ObjectCache{
Response: resp,
}
var objType string
var objID int64
typedObj, errs := resp.GetRegistrarObject()
if len(errs) != 0 {
var lastErr error
for _, err := range errs {
d.log.Error(err)
lastErr = err
}
return fmt.Errorf("error retrieving object type: %w", lastErr)
}
switch t := typedObj.(type) {
case *lib.ChangeRequestExport:
objType = lib.ChangeRequestType
objID = t.ID
default:
d.log.Errorf("Unhandled type %T", t)
return ErrUnexpectedObject
}
d.log.Debugf("Saving object type %s", objType)
var filePath string
if objType == lib.ChangeRequestType {
filePath = d.changeRequestPath(objID)
} else {
filePath = d.objectPath(objType, objID)
}
return d.saveObject(oc, filePath)
}
// SaveObjectAt will save the given object to disk for the given ID and add the
// timestamp to the date rage for the object revision table
func (d *DiskCache) SaveObjectAt(resp lib.APIResponse, id int64, timestamp int64) error {
oc := ObjectCache{
Response: resp,
}
var objType string
var objID int64
var currentRev int64
typedObj, errs := resp.GetRegistrarObject()
if len(errs) != 0 {
var lastErr error
for _, err := range errs {
d.log.Error(err)
lastErr = err
}
return fmt.Errorf("error retrieving object type: %w", lastErr)
}
switch t := typedObj.(type) {
case *lib.ChangeRequestExport:
objType = lib.ChangeRequestType
objID = t.ID
currentRev = t.ID
case *lib.HostExport:
objType = "host"
objID = t.ID
currentRev = t.CurrentRevision.ID
case *lib.DomainExport:
objType = "domain"
objID = t.ID
currentRev = t.CurrentRevision.ID
case *lib.ApproverExportFull:
objType = "approver"
objID = t.ID
currentRev = t.CurrentRevision.ID
case *lib.ApproverSetExportFull:
objType = "approverset"
objID = t.ID
currentRev = t.CurrentRevision.ID
case *lib.ContactExport:
objType = "contact"
objID = t.ID
currentRev = t.CurrentRevision.ID
default:
d.log.Errorf("Unhandled type %T", t)
return ErrUnexpectedObject
}
d.log.Noticef("%s id %d -- Current Revision ID %d", objType, objID, currentRev)
path := d.snapshotPath(objType, currentRev)
err := d.saveObject(oc, path)
if err != nil {
return err
}
return d.UpdateRevisionList(objType, objID, currentRev, timestamp)
}
// RevisionValidity is used to store information about which revisions were
// active for given times
type RevisionValidity struct {
RevisionID int64
MinTime int64
MaxTime int64
}
// ObjectInfo is used to store multiple revision validity windows for objects
// of the same ID. Object info is what will be serialized to disk
type ObjectInfo struct {
ObjectID int64
Revisions []RevisionValidity
}
// getRevisionObject wil attempt to retrieve the object type with the id passed
// at the given timestamp from disk. If the object cannot be found on disk
// or there is an error reading the object off disk, an error will be returned
func (d *DiskCache) getRevisionObject(objectType string, objectID int64, ts int64, lastUpdate *time.Time) (outObj lib.RegistrarObjectExport, errs []error) {
var oi ObjectInfo
path := d.objectPath(objectType, objectID)
fc, err := os.ReadFile(path)
if err != nil {
errs = append(errs, err)
d.log.Error(err)
return
}
err = json.Unmarshal(fc, &oi)
if err != nil {
errs = append(errs, err)
d.log.Error(err)
return
}
for _, rev := range oi.Revisions {
if rev.MaxTime >= ts && rev.MinTime <= ts {
d.log.Noticef("Use revision %d", rev.RevisionID)
return d.getSnapshotObject(objectType, rev.RevisionID, lastUpdate)
}
}
errs = append(errs, errors.New("Unable to located a cached version of the object"))
return
}
// getSnapshotObject will attempt to read the object at a specific revision from
// disk
func (d *DiskCache) getSnapshotObject(objectType string, revision int64, lastUpdate *time.Time) (outObj lib.RegistrarObjectExport, errs []error) {
filePath := d.snapshotPath(objectType, revision)
fc, err := os.ReadFile(filePath)
if err != nil {
d.log.Error(err)
errs = append(errs, err)
return
}
var oc ObjectCache
err = json.Unmarshal(fc, &oc)
if err != nil {
d.log.Error(err)
errs = append(errs, err)
return
}
obj, objErr := oc.Response.GetRegistrarObject()
needsRefresh := false
if lastUpdate != nil {
switch t := obj.(type) {
case *lib.ContactExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
case *lib.HostExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
case *lib.DomainExport:
if (*lastUpdate).After(t.UpdatedAt) {
needsRefresh = true
}
}
}
if needsRefresh {
errs = append(errs, errors.New("Objects needs to be refreshed"))
return outObj, errs
}
return obj, objErr
}
// UpdateRevisionList will attempt to read in a object from cache and add a
// revision at a timestamp to the object infomration and then write the object
// back to disk
func (d *DiskCache) UpdateRevisionList(objectType string, objectID int64, revisionID int64, ts int64) error {
var oi ObjectInfo
path := d.objectPath(objectType, objectID)
fc, err := os.ReadFile(path)
if err != nil {
oi.ObjectID = objectID
} else {
err = json.Unmarshal(fc, &oi)
if err != nil {
d.log.Error(err)
return err
}
}
foundRevision := false
for idx, rev := range oi.Revisions {
if rev.RevisionID == revisionID {
foundRevision = true
if ts > rev.MaxTime {
oi.Revisions[idx].MaxTime = ts
}
if ts < rev.MinTime {
oi.Revisions[idx].MinTime = ts
}
}
}
if !foundRevision {
rv := RevisionValidity{
RevisionID: revisionID,
MinTime: ts,
MaxTime: ts,
}
oi.Revisions = append(oi.Revisions, rv)
}
return d.saveObject(oi, path)
}
// saveObject will serialize and save the given object to the provided path
func (d *DiskCache) saveObject(obj interface{}, path string) error {
d.log.Debugf("Saving to %s", path)
fc, err := json.MarshalIndent(obj, "", " ")
if err != nil {
d.log.Error(err)
return err
}
writeErr := os.WriteFile(path, fc, 0644)
if writeErr != nil {
d.log.Error(writeErr)
return writeErr
}
return nil
}
// objectPath will generate and return the path for the object based on the
// object type and id passed
func (d *DiskCache) objectPath(objType string, id int64) string {
return path.Join(d.BasePath, "object", fmt.Sprintf("%s.%d.json", objType, id))
}
// snapshotPath will generate and return the path for the object based on the
// object type and id passed
func (d *DiskCache) snapshotPath(objType string, id int64) string {
return path.Join(d.BasePath, "snapshots", fmt.Sprintf("%s.%d.json", objType, id))
}
// changeRequestPath will generate and return the path for a change request with
// the provided id
func (d *DiskCache) changeRequestPath(id int64) string {
return path.Join(d.BasePath, lib.ChangeRequestType, fmt.Sprintf("%d.json", id))
}
// createDirIfNotExist will check if the given directory exists and then create
// it if it does not exit
func createDirIfNotExist(directory string, log *logging.Logger) error {
log.Debugf("Checking to see if %s exists", directory)
stat, err := os.Stat(directory)
if err != nil || stat == nil {
log.Debug("Fresh Cache Directory Created")
err := os.Mkdir(directory, 0777)
if err != nil {
return err
}
return nil
}
if !stat.IsDir() {
return errors.New("path provided is not a directory")
}
return nil
}
// ObjectDirectory handles a list of IDs and revision hints for the client to
// allow quick lookups in the disk cache if used
type ObjectDirectory struct {
DomainIDs []int64
DomainHints map[int64]lib.APIRevisionHint
HostIDs []int64
HostHints map[int64]lib.APIRevisionHint
ContactIDs []int64
ContactHints map[int64]lib.APIRevisionHint
}
// NewObjectDirectory will initialize a new object directory object and return
// it
func NewObjectDirectory() ObjectDirectory {
od := ObjectDirectory{}
od.DomainHints = make(map[int64]lib.APIRevisionHint)
od.ContactHints = make(map[int64]lib.APIRevisionHint)
od.HostHints = make(map[int64]lib.APIRevisionHint)
return od
}
// LoadObjectDirectory will attempt to load the list of active objects and the
// current hints for all objects. If any errors are returned when trying to
// load the objects, the errors will be returned
func (od *ObjectDirectory) LoadObjectDirectory(cli *Client) (errs []error) {
var domErrs, conErrs, hosErrs []error
od.DomainIDs, od.DomainHints, domErrs = cli.GetAll(lib.DomainType)
if len(domErrs) != 0 {
return domErrs
}
od.ContactIDs, od.ContactHints, conErrs = cli.GetAll(lib.ContactType)
if len(conErrs) != 0 {
return conErrs
}
od.HostIDs, od.HostHints, hosErrs = cli.GetAll(lib.HostType)
if len(hosErrs) != 0 {
return hosErrs
}
return errs
}
// Client is an object that will hold the required state to
// communicate with the registrar server
type Client struct {
httpsClient *http.Client
basePath string
spoofedClientCert string
spoofedHeaderName string
log *logging.Logger
currentRunID int64
TrustAnchor TrustAnchors
cache DiskCache
ObjectDir ObjectDirectory
}
// Get will send a request to the server using the current client
// and return a respose and error, similar to the response from
// http.Client.Get
func (a *Client) Get(path string) (data []byte, err error) {
a.logDebug(fmt.Sprintf("Get %s%s", a.basePath, path))
req, reqErr := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s", a.basePath, path), nil)
if reqErr != nil {
a.logDebug("Error creating request")
err = reqErr
return
}
if len(a.spoofedClientCert) != 0 {
a.logDebug("Adding spoofed header")
req.Header.Add(a.spoofedHeaderName, strings.Replace(a.spoofedClientCert, "\n", " ", -1))
}
resp, getErr := a.httpsClient.Do(req)
if getErr != nil {
err = getErr
return
}
defer resp.Body.Close()
var readErr error
data, readErr = io.ReadAll(resp.Body)
if readErr != nil {
err = readErr
return
}
return
}
// Post will send a request to the server using the current client
// and return a respose and error, similar to the response from
// http.Client.Post
func (a *Client) Post(path string, bodyType string, body io.Reader) (*http.Response, error) {
req, reqErr := http.NewRequest(http.MethodPost, fmt.Sprintf("%s%s", a.basePath, path), body)
if reqErr != nil {
return nil, reqErr
}
if len(a.spoofedClientCert) != 0 {
a.logDebug("Adding spoofed header")
req.Header.Add(a.spoofedHeaderName, strings.Replace(a.spoofedClientCert, "\n", " ", -1))
}
return a.httpsClient.Do(req)
}
// Prepare will take the required information for the client and prepare
// it to send queries to the server
func (a *Client) Prepare(base string, log *logging.Logger, dcc DiskCacheConfig) {
a.ObjectDir = NewObjectDirectory()
a.basePath = base
a.httpsClient = &http.Client{}
if log != nil {
a.log = log
} else {
backend := logging.NewLogBackend(os.Stdout, "", 0)
backendFormatter := logging.NewBackendFormatter(backend, format)
backendLevel := logging.AddModuleLevel(backendFormatter)
backendLevel.SetLevel(logging.CRITICAL, "")
logging.SetBackend(backendLevel)
a.log = logging.MustGetLogger("registrar")
}
var cacheCreateErr error
a.cache, cacheCreateErr = NewDiskCache(dcc, log)
if cacheCreateErr != nil {
log.Error(cacheCreateErr)
}
}
// SpoofCertificateForTesting is used to spoof a client certificate that
// is used to authenticatea client to the testing server
func (a *Client) SpoofCertificateForTesting(cert string, headername string) {
a.spoofedClientCert = cert
a.spoofedHeaderName = headername
}
// PrepareSSL will take the required infomration for the client and
// prepare it to send queries to the server using TLS
func (a *Client) PrepareSSL(base, certFile, keyFile, caFile string, keychainConf keychain.Conf, log *logging.Logger, dcc DiskCacheConfig) {
a.ObjectDir = NewObjectDirectory()
a.basePath = base
if log != nil {
a.log = log
} else {
backend := logging.NewLogBackend(os.Stdout, "", 0)
backendFormatter := logging.NewBackendFormatter(backend, format)
backendLevel := logging.AddModuleLevel(backendFormatter)
backendLevel.SetLevel(logging.CRITICAL, "")
logging.SetBackend(backendLevel)
a.log = logging.MustGetLogger("registrar")
}
var cacheCreateErr error
a.cache, cacheCreateErr = NewDiskCache(dcc, log)
if cacheCreateErr != nil {
log.Error(cacheCreateErr)
}
a.logDebugf("Cert File Path: %s", certFile)
a.logDebugf("Key File Path: %s", keyFile)
a.logDebugf("CA File Path: %s", caFile)
// Load client cert
cert, err := loadCert(certFile, keyFile, keychainConf) //tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
a.logError(err.Error())
}
// Load CA cert
caCert, err := os.ReadFile(caFile)
if err != nil {
a.logError(err.Error())
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
log.Debug("checking for HTTP_PROXY")
var proxyUrl *url.URL = nil
httpProxyEnv := os.Getenv("HTTP_PROXY")
if httpProxyEnv != "" {
proxyUrl, err = url.Parse(httpProxyEnv)
if err != nil {
panic(err)
}
log.Debug("using HTTP proxy ", httpProxyEnv)
} else {
log.Debug("HTTP_PROXY is not set, not using a proxy")
}
// Setup HTTPS client
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
tlsConfig.BuildNameToCertificate()
var transport *http.Transport
if proxyUrl == nil {
transport = &http.Transport{TLSClientConfig: tlsConfig}
} else {
transport = &http.Transport{TLSClientConfig: tlsConfig, Proxy: http.ProxyURL(proxyUrl)}
}
a.httpsClient = &http.Client{Transport: transport}
}
// PrepareObjectDirectory will attempt to prepare the object directory for use.
// If any errors are encountered, they will be returned
func (a *Client) PrepareObjectDirectory() (errs []error) {
return a.ObjectDir.LoadObjectDirectory(a)
}
// GetToken will retrieve a CSRF token from the server for the user that
// is currently logged in
func (a *Client) GetToken() (token string, errs []error) {
a.logDebug("Getting an api token")
data, getErr := a.Get("/api/gettoken")
if getErr != nil {
errs = []error{getErr}
return
}
respObj := lib.APIResponse{}
unmarshalErr := json.Unmarshal(data, &respObj)
if unmarshalErr != nil {
errs = append(errs, unmarshalErr)
return
}
if respObj.MessageType == lib.TokenResponseType && respObj.Token != nil {
token = respObj.Token.Token
} else if respObj.MessageType == lib.ErrorResponseType {
for _, err := range respObj.Errors {
errs = append(errs, errors.New(err))
}
} else {
errs = append(errs, fmt.Errorf("Expected a message type of %s, got %s", lib.TokenResponseType, respObj.MessageType))
}
return
}
// GetHostIPAllowList will retrieve the list of Host IPs that are allowlisted
// as they are trusted nameservers
func (a *Client) GetHostIPAllowList() (ips []string, errs []error) {
data, getErr := a.Get("/api/gethostipallowlist")
if getErr != nil {
errs = []error{getErr}
return
}
respObj := lib.APIResponse{}
unmarshalErr := json.Unmarshal(data, &respObj)
if unmarshalErr != nil {
errs = append(errs, unmarshalErr)
return
}
if respObj.MessageType == lib.HostIPAllowList && respObj.HostIPAllowList != nil {
ips = *respObj.HostIPAllowList
} else if respObj.MessageType == lib.ErrorResponseType {
for _, err := range respObj.Errors {
errs = append(errs, errors.New(err))
}
} else {
errs = append(errs, fmt.Errorf("Expected a message type of %s, got %s", lib.HostIPAllowList, respObj.MessageType))
}
return
}
// GetProtectedDomainList will retrieve the list of Protected domains that are
// stored in the registrar system. If an error is encountered, it will be
// returned
func (a *Client) GetProtectedDomainList() (domains []string, errs []error) {
data, getErr := a.Get("/api/getprotecteddomainlist")
if getErr != nil {
errs = []error{getErr}
return
}
respObj := lib.APIResponse{}
unmarshalErr := json.Unmarshal(data, &respObj)
if unmarshalErr != nil {
errs = append(errs, unmarshalErr)
return
}
if respObj.MessageType == lib.ProtectedDomainList && respObj.ProtectedDomainList != nil {
domains = *respObj.ProtectedDomainList
} else if respObj.MessageType == lib.ErrorResponseType {
for _, err := range respObj.Errors {
errs = append(errs, errors.New(err))
}
} else {
errs = append(errs, fmt.Errorf("Expected a message type of %s, got %s", lib.ProtectedDomainList, respObj.MessageType))
}
return
}
// GetApproval will try to retrieve an approval from the registrar
// server given the approval ID and the desired approver id
func (a *Client) GetApproval(approvalID int64, approverID int64, action string) (approvalObject []byte, errs []error) {
token, tokenErrs := a.GetToken()
if tokenErrs != nil {
errs = tokenErrs
return
}
data, getErr := a.Get(fmt.Sprintf("/api/approval/%d/download?approverid=%d&action=%s&csrf_token=%s", approvalID, approverID, action, token))
if getErr != nil {
errs = []error{getErr}
return
}
respObj := lib.APIResponse{}
unmarshalErr := json.Unmarshal(data, &respObj)
if unmarshalErr != nil {
errs = append(errs, unmarshalErr)
return
}
if respObj.MessageType == lib.ApprovalDownloadType && respObj.Approval != nil {
approvalObject = respObj.Approval.Approval
} else if respObj.MessageType == lib.ErrorResponseType {
for _, err := range respObj.Errors {
errs = append(errs, errors.New(err))
}
} else {
errs = append(errs, fmt.Errorf("Expected a message type of %s, got %s", lib.ApprovalDownloadType, respObj.MessageType))
}
return
}
// GetDomain will try and retrieve a domain object from the server
func (a *Client) GetDomain(id int64) (outobj *lib.DomainExport, errs []error) {
obj, errs := a.GetObject(lib.DomainType, id, nil)
outObj, ok := obj.(*lib.DomainExport)
if ok {
return outObj, errs
}
errs = append(errs, errors.New("Unable to parse object"))
return
}
// GetDomainIDFromName will attempt to find the domain ID from the domain name
// provided. If a domain object is found, its id will be returned, otherwise
// an error will be returned
func (a *Client) GetDomainIDFromName(domainName string) (id int64, errs []error) {
data, getErr := a.Get(fmt.Sprintf("/api/domainnametoid/%s", domainName))
if getErr != nil {
errs = []error{getErr}
return
}
fmt.Println(string(data))
respObj := lib.APIResponse{}
unmarshalErr := json.Unmarshal(data, &respObj)
if unmarshalErr != nil {
errs = append(errs, unmarshalErr)
return
}
if respObj.MessageType == lib.DomainIDListType {
if len(*respObj.DomainIDList) == 1 {
id = (*respObj.DomainIDList)[0]
return
}
errs = append(errs, errors.New("Only expected one domain ID to be returned"))
return
}
if len(respObj.Errors) != 0 {
for _, err := range respObj.Errors {
errs = append(errs, errors.New(err))
}
} else {
errs = append(errs, fmt.Errorf("Unexpected message type of %s", respObj.MessageType))
}
return
}
// GetVerifiedDomain will attempt to download and verify a Domain
// with the given ID at the given time. A bool of if the Domain was
// verified or not, a list of errors and the resulting
// DomainExport object will be returned. An empty object is
// returned if the object did not verify.
func (a *Client) GetVerifiedDomain(domainID int64, timestamp int64) (verified bool, errs []error, obj *lib.DomainExport) {
verified = false
dom, domGetErrs := a.GetDomainAt(domainID, timestamp)
a.log.Debugf("Getting Domain %d", domainID)
if len(domGetErrs) != 0 {
errs = append(errs, domGetErrs...)
return
}
if dom.CurrentRevision.ID <= 0 {
errMsg := fmt.Sprintf("No current revision found for Domain %d", dom.ID)
a.log.Error(errMsg)
errs = append(errs, errors.New(errMsg))
return
}
crid := dom.CurrentRevision.ChangeRequestID
if crid <= 0 {
errMsg := fmt.Sprintf("Unable to find a change request for Domain Revision %d", dom.CurrentRevision.ID)
a.log.Error(errMsg)
errs = append(errs, errors.New(errMsg))
return
}
a.log.Debugf("Found Change Request %d for Domain %d", crid, dom.ID)
verified, errs, signedData := a.VerifyChangeRequest(crid, dom.CurrentRevision)
if !verified {
return false, errs, obj
}
var de lib.DomainExport
err := json.Unmarshal(signedData, &de)
if err != nil {
errs = append(errs, err)
return false, errs, obj
}
// Compare the export version to the current working export
// object
isSame, errList := dom.CurrentRevision.CompareExport(de.PendingRevision)
// If they are the same, the object is verified
if isSame {
a.log.Debugf("Domain %d has been transativly signed by one of the trust anchors", de.ID)
return true, errs, dom
}
errs = append(errs, errList...)
return false, errs, obj
}
// GetDomainRevision will try and retrieve a domain object from the server
func (a *Client) GetDomainRevision(id int64) (outobj *lib.DomainRevisionExport, errs []error) {
obj, errs := a.GetObject(lib.DomainRevisionType, id, nil)
outObj, ok := obj.(*lib.DomainRevisionExport)
if ok {
return outObj, errs
}
errs = append(errs, errors.New("Unable to parse object"))
return
}
// GetContact will try and retrieve a domain object from the server
func (a *Client) GetContact(id int64) (outobj *lib.ContactExport, errs []error) {
obj, errs := a.GetObject(lib.ContactType, id, nil)
outObj, ok := obj.(*lib.ContactExport)
if ok {
return outObj, errs
}
errs = append(errs, errors.New("Unable to parse object"))
return
}
// GetVerifiedContact will attempt to download and verify a Contact
// with the given ID at the given time. A bool of if the Contact was
// verified or not, a list of errors and the resulting
// ContactExport object will be returned. An empty object is
// returned if the object did not verify.
func (a *Client) GetVerifiedContact(contactID int64, timestamp int64) (verified bool, errs []error, obj *lib.ContactExport) {
verified = false
con, conGetErrs := a.GetContactAt(contactID, timestamp)
a.log.Debugf("Getting Contact %d", contactID)
if len(conGetErrs) != 0 {
errs = append(errs, conGetErrs...)
return
}
if con.CurrentRevision.ID <= 0 {
errMsg := fmt.Sprintf("No current revision found for Contact %d", con.ID)
a.log.Error(errMsg)
errs = append(errs, errors.New(errMsg))
return
}
crid := con.CurrentRevision.ChangeRequestID
if crid <= 0 {
errMsg := fmt.Sprintf("Unable to find a change request for Contact Revision %d", con.CurrentRevision.ID)
a.log.Error(errMsg)
errs = append(errs, errors.New(errMsg))
return
}
a.log.Debugf("Found Change Request %d for Contact %d", crid, con.ID)
verified, errs, signedData := a.VerifyChangeRequest(crid, con.CurrentRevision)
if !verified {
return false, errs, obj
}
var ce lib.ContactExport
err := json.Unmarshal(signedData, &ce)
if err != nil {
errs = append(errs, err)
return false, errs, obj
}
// Compare the export version to the current working export
// object
isSame, errList := con.CurrentRevision.CompareExport(ce.PendingRevision)
// If they are the same, the object is verified
if isSame {
a.log.Debugf("Contact %d has been transativly signed by one of the trust anchors", ce.ID)
return true, errs, con
}
errs = append(errs, errList...)
return false, errs, obj
}
// GetContactRevision will try and retrieve a domain object from the server
func (a *Client) GetContactRevision(id int64) (outobj *lib.ContactRevisionExport, errs []error) {
obj, errs := a.GetObject(lib.ContactRevisionType, id, nil)
outObj, ok := obj.(*lib.ContactRevisionExport)
if ok {
return outObj, errs
}