diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml index 0f5ed269..7538a57a 100644 --- a/.github/workflows/checks.yml +++ b/.github/workflows/checks.yml @@ -11,6 +11,7 @@ on: - v4 - v5 - v6 + - v7 - master jobs: test: diff --git a/CHANGELOG.md b/CHANGELOG.md index 8502a72a..31dccc64 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,148 @@ # EDGEGRID GOLANG RELEASE NOTES +## 8.0.0 (March 19, 2024) + +#### BREAKING CHANGES: + +* Migrated to go 1.21 + +* CPS + * Split request and response structures for create and update enrollment operations + +* DNS + * Renamed following structs: + * `RecordsetQueryArgs` into `RecordSetQueryArgs` + * `Recordsets` into `RecordSets` + * `Recordset` into `RecordSet` + * `MetadataH` into `Metadata` + * Renamed following fields: + * `GroupId` into `GroupID` in `ListGroupRequest` + * `Recordsets` into `RecordSets` in `RecordSetResponse` + * `ContractIds` into `ContractIDs` in `TSIGQueryString` + * `Gid` into `GID` in `TSIGQueryString` and `TSIGReportMeta` + * `TsigKey` into `TSIGKey` in `ZoneCreate` and `ZoneResponse` + * `VersionId` into `VersionID` in `ZoneResponse` + * `RequestId` into `RequestID` in `BulkZonesResponse`, `BulkStatusResponse`, `BulkCreateResultResponse` and `BulkDeleteResultResponse` + * Renamed `RecordSets` interface into `Recordsets` + * Renamed following methods: + * `ListTsigKeys` into `ListTSIGKeys` + * `GetTsigKeyZones` into `GetTSIGKeyZones` + * `GetTsigKeyAliases` into `GetTSIGKeyAliases` + * `TsigKeyBulkUpdate` into `TSIGKeyBulkUpdate` + * `GetTsigKey` into `GetTSIGKey` + * `DeleteTsigKey` into `DeleteTSIGKey` + * `UpdateTsigKey` into `UpdateTSIGKey` + * `GetRecordsets` into `GetRecordSets` + * `CreateRecordsets` into `CreateRecordSets` + * `UpdateRecordsets` into `UpdateRecordSets` + * Deleted following methods: + * `NewAuthorityResponse` + * `NewChangeListResponse` + * `NewRecordBody` + * `NewRecordSetResponse` + * `NewTsigKey` + * `NewTsigQueryString` + * `NewZone` + * `NewZoneQueryString` + * `NewZoneResponse` + * `RecordToMap` + * Unexported following methods: + * `FullIPv6` + * `PadCoordinates` + * `ValidateZone` + +* GTM + * Renamed following structs: + * `AsAssignment` into `ASAssignment` + * `AsMap` into `ASMap` + * `AsMapList` into `ASMapList` + * `CidrAssignment` into `CIDRAssignment` + * `CidrMap` into `CIDRMap` + * `CidrMapList` into `CIDRMapList` + * `CidrMapResponse` into `CIDRMapResponse` + * `AsMapResponse` into `ASMapResponse` + * `HttpHeader` into `HTTPHeader` + * Renamed following fields: + * `AsNumbers` into `ASNumbers` in `ASAssignment` + * `AsMapItems` into `ASMapItems` in `ASMapList` + * `CidrMapItems` into `CIDRMapItems` in `CIDRMapList` + * `ChangeId` into `ChangeID` in `ResponseStatus` + * `DatacenterId` into `DatacenterID` in `DatacenterBase`, `Datacenter`, `TrafficTarget` and `ResourceInstance` + * `AsMaps` into `ASMaps` in `Domain` + * `DefaultSslClientPrivateKey` into `DefaultSSLClientPrivateKey` in `Domain` + * `CnameCoalescingEnabled` into `CNameCoalescingEnabled` in `Domain` + * `CidrMaps` into `CIDRMaps` in `Domain` + * `DefaultSslClientCertificate` into `DefaultSSLClientCertificate` in `Domain` + * `AcgId` into `AcgID` in `DomainItem` + * `HttpError3xx` into `HTTPError3xx` in `LivenessTest` + * `HttpError4xx` into `HTTPError4xx` in `LivenessTest` + * `HttpError5xx` into `HTTPError5xx` in `LivenessTest` + * `SslClientPrivateKey` into `SSLClientPrivateKey` in `LivenessTest` + * `SslClientCertificate` into `SSLClientCertificate` in `LivenessTest` + * `HttpHeaders` into `HTTPHeaders` in `LivenessTest` + * `Ipv6` into `IPv6` in `Property` + * `BackupIp` into `BackupIP` in `Property` + * Renamed `CidrMaps` interface into `CIDRMaps` + * Renamed following methods: + * `ListAsMaps` into `ListASMaps` + * `GetAsMap` into `GetASMap` + * `CreateAsMap` into `CreateASMap` + * `DeleteAsMap` into `DeleteASMap` + * `UpdateAsMap` into `UpdateASMap` + * `ListCidrMaps` into `ListCIDRMaps` + * `GetCidrMap` into `GetCIDRMap` + * `CreateCidrMap` into `CreateCIDRMap` + * `DeleteCidrMap` into `DeleteCIDRMap` + * `UpdateCidrMap` into `UpdateCIDRMap` + * Deleted following methods: + * `NewASAssignment` + * `NewAsMap` + * `NewCidrAssignment` + * `NewCidrMap` + * `NewDatacenter` + * `NewDatacenterBase` + * `NewDatacenterResponse` + * `NewDefaultDatacenter` + * `NewDomain` + * `NewGeoAssignment` + * `NewHttpHeader` + * `NewGeoMap` + * `NewLivenessTest` + * `NewLoadObject` + * `NewProperty` + * `NewResource` + * `NewResourceInstance` + * `NewResponseStatus` + * `NewStaticRRSet` + * `NewTrafficTarget` + +#### FEATURES/ENHANCEMENTS: + +* Added default value `application/json` for `Accept` header for all requests sent to API + +* Appsec + * Added `PenaltyBoxConditions` API - read and update + * Added `EvalPenaltyBoxConditions` API - read and update + +* CPS + * Added `ID`, `OrgID`, `ProductionSlots`, `StagingSlots` and `AssignedSlots` to the response structures of `GetEnrollment` and `ListEnrollment` operations + +* GTM + * Added new fields: + * `SignAndServe` and `SignAndServeAlgorithm` for the `Domain` + * `HTTPMethod`, `HTTPRequestBody`, `Pre2023SecurityPosture` and `AlternateCACertificates` for the `LivenessTest` in `Property` + * `Precedence` for the `TrafficTarget` in `Property` + * Enhanced error details by addition of `Errors` field in `Error` structure + * Added support for the creation of `ranked-failover` properties + +#### BUG FIXES: + +* DNS + * Removed not working `DeleteZone` method +* +* PAPI + * Updated documentation link for `GetProperties` method + ## 7.6.1 (February 14, 2024) #### BUG FIXES: diff --git a/README.md b/README.md index 4d812792..1dd3e2fa 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ -# Akamai OPEN EdgeGrid for GoLang v7 +# Akamai OPEN EdgeGrid for GoLang v8 ![Build Status](https://github.com/akamai/akamaiOPEN-edgegrid-golang/actions/workflows/checks.yml/badge.svg) -[![Go Report Card](https://goreportcard.com/badge/github.com/akamai/AkamaiOPEN-edgegrid-golang/v7)](https://goreportcard.com/report/github.com/akamai/AkamaiOPEN-edgegrid-golang/v7) +[![Go Report Card](https://goreportcard.com/badge/github.com/akamai/AkamaiOPEN-edgegrid-golang/v8)](https://goreportcard.com/report/github.com/akamai/AkamaiOPEN-edgegrid-golang/v8) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/akamai/akamaiOPEN-edgegrid-golang) [![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) -[![GoDoc](https://pkg.go.dev/badge/github.com/akamai/akamaiOPEN-edgegrid-golang?utm_source=godoc)](https://pkg.go.dev/github.com/akamai/AkamaiOPEN-edgegrid-golang/v7) +[![GoDoc](https://pkg.go.dev/badge/github.com/akamai/akamaiOPEN-edgegrid-golang?utm_source=godoc)](https://pkg.go.dev/github.com/akamai/AkamaiOPEN-edgegrid-golang/v8) This module is presently in active development and provides Akamai REST API support for the Akamai Terraform Provider. @@ -12,7 +12,7 @@ This module is presently in active development and provides Akamai REST API supp This module is not backward compatible with the version `v1`. -Originally branch `master` was representing version `v1`. Now it is representing the latest version `v7` and +Originally branch `master` was representing version `v1`. Now it is representing the latest version `v8` and version `v1` was moved to dedicated `v1` branch. @@ -23,6 +23,6 @@ The packages of library can be imported alongside the `v1` library versions with ``` import ( papiv1 "github.com/akamai/AkamaiOPEN-edgegrid-golang/papi-v1" - papi "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/papi" + papi "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/papi" ) ``` diff --git a/go.mod b/go.mod index 2f248118..81a39787 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ -module github.com/akamai/AkamaiOPEN-edgegrid-golang/v7 +module github.com/akamai/AkamaiOPEN-edgegrid-golang/v8 -go 1.18 +go 1.21 require ( github.com/apex/log v1.9.0 @@ -25,8 +25,6 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect github.com/smartystreets/goconvey v1.6.4 // indirect github.com/stretchr/objx v0.5.0 // indirect - golang.org/x/mod v0.14.0 // indirect - golang.org/x/tools v0.17.0 // indirect gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index 1d8a8226..dc7f0cd7 100644 --- a/go.sum +++ b/go.sum @@ -87,8 +87,6 @@ go.uber.org/ratelimit v0.2.0 h1:UQE2Bgi7p2B85uP5dC2bbRtig0C+OeNRnNEafLjsLPA= go.uber.org/ratelimit v0.2.0/go.mod h1:YYBV4e4naJvhpitQrWJu1vCpgB7CboMe0qhltKt6mUg= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= -golang.org/x/mod v0.14.0 h1:dGoOF9QVLYng8IHTm7BAyWqCqSheQ5pYWGhzW00YJr0= -golang.org/x/mod v0.14.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= @@ -104,8 +102,6 @@ golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= -golang.org/x/tools v0.17.0 h1:FvmRgNOcs3kOa+T20R1uhfP9F6HgG2mfxDv1vrx1Htc= -golang.org/x/tools v0.17.0/go.mod h1:xsh6VxdV005rRVaS6SSAf9oiAqljS7UZUacMZ8Bnsps= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= diff --git a/pkg/appsec/activations_test.go b/pkg/appsec/activations_test.go index a7347abc..a6bdb983 100644 --- a/pkg/appsec/activations_test.go +++ b/pkg/appsec/activations_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_attack_payload_logging.go b/pkg/appsec/advanced_settings_attack_payload_logging.go index cf8f7ae6..8698acd2 100644 --- a/pkg/appsec/advanced_settings_attack_payload_logging.go +++ b/pkg/appsec/advanced_settings_attack_payload_logging.go @@ -6,7 +6,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/appsec/advanced_settings_attack_payload_logging_test.go b/pkg/appsec/advanced_settings_attack_payload_logging_test.go index a0fe95a4..19e70960 100644 --- a/pkg/appsec/advanced_settings_attack_payload_logging_test.go +++ b/pkg/appsec/advanced_settings_attack_payload_logging_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_evasive_path_match_test.go b/pkg/appsec/advanced_settings_evasive_path_match_test.go index 016f114e..e4aea961 100644 --- a/pkg/appsec/advanced_settings_evasive_path_match_test.go +++ b/pkg/appsec/advanced_settings_evasive_path_match_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_logging_test.go b/pkg/appsec/advanced_settings_logging_test.go index b776940a..f4c6570d 100644 --- a/pkg/appsec/advanced_settings_logging_test.go +++ b/pkg/appsec/advanced_settings_logging_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_pii_learning.go b/pkg/appsec/advanced_settings_pii_learning.go index 4fe8fa11..c6649efa 100644 --- a/pkg/appsec/advanced_settings_pii_learning.go +++ b/pkg/appsec/advanced_settings_pii_learning.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/appsec/advanced_settings_pii_learning_test.go b/pkg/appsec/advanced_settings_pii_learning_test.go index eab6fe4d..4d80ab4e 100644 --- a/pkg/appsec/advanced_settings_pii_learning_test.go +++ b/pkg/appsec/advanced_settings_pii_learning_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_pragma_test.go b/pkg/appsec/advanced_settings_pragma_test.go index db842962..6826a8d8 100644 --- a/pkg/appsec/advanced_settings_pragma_test.go +++ b/pkg/appsec/advanced_settings_pragma_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_prefetch_test.go b/pkg/appsec/advanced_settings_prefetch_test.go index 0523f687..9ad00a7f 100644 --- a/pkg/appsec/advanced_settings_prefetch_test.go +++ b/pkg/appsec/advanced_settings_prefetch_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/advanced_settings_request_body.go b/pkg/appsec/advanced_settings_request_body.go index 34a1c98a..c36e92c1 100644 --- a/pkg/appsec/advanced_settings_request_body.go +++ b/pkg/appsec/advanced_settings_request_body.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/appsec/advanced_settings_request_body_test.go b/pkg/appsec/advanced_settings_request_body_test.go index 21e746da..92dc1588 100644 --- a/pkg/appsec/advanced_settings_request_body_test.go +++ b/pkg/appsec/advanced_settings_request_body_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_constraints_protection_test.go b/pkg/appsec/api_constraints_protection_test.go index 3ec4b01f..1fdca331 100644 --- a/pkg/appsec/api_constraints_protection_test.go +++ b/pkg/appsec/api_constraints_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_endpoints_test.go b/pkg/appsec/api_endpoints_test.go index 8b7970bf..e86c8434 100644 --- a/pkg/appsec/api_endpoints_test.go +++ b/pkg/appsec/api_endpoints_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_hostname_coverage_match_targets_test.go b/pkg/appsec/api_hostname_coverage_match_targets_test.go index f2600480..75745d47 100644 --- a/pkg/appsec/api_hostname_coverage_match_targets_test.go +++ b/pkg/appsec/api_hostname_coverage_match_targets_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_hostname_coverage_overlapping_test.go b/pkg/appsec/api_hostname_coverage_overlapping_test.go index d79fe41d..e7901175 100644 --- a/pkg/appsec/api_hostname_coverage_overlapping_test.go +++ b/pkg/appsec/api_hostname_coverage_overlapping_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_hostname_coverage_test.go b/pkg/appsec/api_hostname_coverage_test.go index e0cb79d0..ef345e44 100644 --- a/pkg/appsec/api_hostname_coverage_test.go +++ b/pkg/appsec/api_hostname_coverage_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/api_request_constraints_test.go b/pkg/appsec/api_request_constraints_test.go index 5a182142..b39feae6 100644 --- a/pkg/appsec/api_request_constraints_test.go +++ b/pkg/appsec/api_request_constraints_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/appsec.go b/pkg/appsec/appsec.go index 5cd199b8..cf935b83 100644 --- a/pkg/appsec/appsec.go +++ b/pkg/appsec/appsec.go @@ -4,7 +4,7 @@ package appsec import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( @@ -47,6 +47,7 @@ type ( Eval EvalGroup EvalPenaltyBox + EvalPenaltyBoxConditions EvalRule ExportConfiguration FailoverHostnames @@ -60,6 +61,7 @@ type ( MatchTargetSequence NetworkLayerProtection PenaltyBox + PenaltyBoxConditions PolicyProtections RatePolicy RatePolicyAction diff --git a/pkg/appsec/appsec_test.go b/pkg/appsec/appsec_test.go index 1c9442a8..268ab76b 100644 --- a/pkg/appsec/appsec_test.go +++ b/pkg/appsec/appsec_test.go @@ -12,8 +12,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/attack_group_test.go b/pkg/appsec/attack_group_test.go index bf4e0029..7c46d2b3 100644 --- a/pkg/appsec/attack_group_test.go +++ b/pkg/appsec/attack_group_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/configuration_clone_test.go b/pkg/appsec/configuration_clone_test.go index 5680d137..04e8eeb9 100644 --- a/pkg/appsec/configuration_clone_test.go +++ b/pkg/appsec/configuration_clone_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/configuration_test.go b/pkg/appsec/configuration_test.go index 7ddda6ed..c3571d37 100644 --- a/pkg/appsec/configuration_test.go +++ b/pkg/appsec/configuration_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/configuration_version_clone_test.go b/pkg/appsec/configuration_version_clone_test.go index 04646e19..a42e60dd 100644 --- a/pkg/appsec/configuration_version_clone_test.go +++ b/pkg/appsec/configuration_version_clone_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/configuration_version_test.go b/pkg/appsec/configuration_version_test.go index ea9f3c36..a604f7d3 100644 --- a/pkg/appsec/configuration_version_test.go +++ b/pkg/appsec/configuration_version_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/custom_deny_test.go b/pkg/appsec/custom_deny_test.go index be1d4ce6..2abfadd3 100644 --- a/pkg/appsec/custom_deny_test.go +++ b/pkg/appsec/custom_deny_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/custom_rule_action_test.go b/pkg/appsec/custom_rule_action_test.go index e28c0a6f..c28b166e 100644 --- a/pkg/appsec/custom_rule_action_test.go +++ b/pkg/appsec/custom_rule_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/custom_rule_test.go b/pkg/appsec/custom_rule_test.go index bf399167..ff2f98ab 100644 --- a/pkg/appsec/custom_rule_test.go +++ b/pkg/appsec/custom_rule_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/errors.go b/pkg/appsec/errors.go index 760896c0..77bf0f4c 100644 --- a/pkg/appsec/errors.go +++ b/pkg/appsec/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) var ( diff --git a/pkg/appsec/errors_test.go b/pkg/appsec/errors_test.go index 06aba76e..9f5c6f68 100644 --- a/pkg/appsec/errors_test.go +++ b/pkg/appsec/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/appsec/eval_group_test.go b/pkg/appsec/eval_group_test.go index a2409412..19c36874 100644 --- a/pkg/appsec/eval_group_test.go +++ b/pkg/appsec/eval_group_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/eval_penalty_box_conditions.go b/pkg/appsec/eval_penalty_box_conditions.go new file mode 100644 index 00000000..529e9f38 --- /dev/null +++ b/pkg/appsec/eval_penalty_box_conditions.go @@ -0,0 +1,82 @@ +package appsec + +import ( + "context" + "fmt" + "net/http" +) + +type ( + // EvalPenaltyBoxConditions interface supports retrieving or modifying the evaluation penalty box conditions for + // a specified security policy in evaluation mode. + EvalPenaltyBoxConditions interface { + // GetEvalPenaltyBoxConditions returns the eval penalty box conditions for a security policy in evaluation mode. + GetEvalPenaltyBoxConditions(ctx context.Context, params GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) + + // UpdateEvalPenaltyBoxConditions modifies the eval penalty box conditions for a security policy. + UpdateEvalPenaltyBoxConditions(ctx context.Context, params UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) + } +) + +func (p *appsec) GetEvalPenaltyBoxConditions(ctx context.Context, params GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) { + logger := p.Log(ctx) + logger.Debug("GetEvalPenaltyBoxConditions") + + if err := params.Validate(); err != nil { + return nil, fmt.Errorf("%w: %s", ErrStructValidation, err.Error()) + } + + uri := fmt.Sprintf( + "/appsec/v1/configs/%d/versions/%d/security-policies/%s/eval-penalty-box/conditions", + params.ConfigID, + params.Version, + params.PolicyID) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) + if err != nil { + return nil, fmt.Errorf("failed to create GetEvalPenaltyBoxConditions request: %w", err) + } + + var result GetPenaltyBoxConditionsResponse + resp, err := p.Exec(req, &result) + if err != nil { + return nil, fmt.Errorf("get eval penalty box conditions request failed: %w", err) + } + if resp.StatusCode != http.StatusOK { + return nil, p.Error(resp) + } + + return &result, nil +} + +func (p *appsec) UpdateEvalPenaltyBoxConditions(ctx context.Context, params UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) { + logger := p.Log(ctx) + logger.Debug("UpdateEvalPenaltyBoxConditions") + + if err := params.Validate(); err != nil { + return nil, fmt.Errorf("%w: %s", ErrStructValidation, err.Error()) + } + + uri := fmt.Sprintf( + "/appsec/v1/configs/%d/versions/%d/security-policies/%s/eval-penalty-box/conditions", + params.ConfigID, + params.Version, + params.PolicyID, + ) + + req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri, nil) + if err != nil { + return nil, fmt.Errorf("failed to create UpdateEvalPenaltyBoxConditions request: %w", err) + } + + var result UpdatePenaltyBoxConditionsResponse + resp, err := p.Exec(req, &result, params.ConditionsPayload) + if err != nil { + return nil, fmt.Errorf("update eval penalty box conditions request failed: %w", err) + } + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + return nil, p.Error(resp) + } + + return &result, nil +} diff --git a/pkg/appsec/eval_penalty_box_conditions_test.go b/pkg/appsec/eval_penalty_box_conditions_test.go new file mode 100644 index 00000000..59f22b86 --- /dev/null +++ b/pkg/appsec/eval_penalty_box_conditions_test.go @@ -0,0 +1,299 @@ +package appsec + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAppSec_GetEvalPenaltyBoxConditions(t *testing.T) { + + result := GetPenaltyBoxConditionsResponse{} + + respData := compactJSON(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json")) + err := json.Unmarshal([]byte(respData), &result) + require.NoError(t, err) + + tests := map[string]struct { + params GetPenaltyBoxConditionsRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *GetPenaltyBoxConditionsResponse + withError func(*testing.T, error) + }{ + "validation errors - PolicyID cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + }, + "validation errors - Version cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Version: cannot be blank", err.Error()) + }, + }, + "validation errors - ConfigID cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + Version: 15, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConfigID: cannot be blank", err.Error()) + }, + }, + "200 OK": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + }, + responseStatus: http.StatusOK, + responseBody: respData, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/eval-penalty-box/conditions", + expectedResponse: &result, + }, + "500 internal server error": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error fetching EvalPenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/eval-penalty-box/conditions", + withError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error fetching EvalPenaltyBoxConditions", + StatusCode: http.StatusInternalServerError, + } + assert.True(t, errors.Is(err, want), "want: %s; got: %s", want, err) + }, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, test.expectedPath, r.URL.String()) + assert.Equal(t, http.MethodGet, r.Method) + w.WriteHeader(test.responseStatus) + _, err := w.Write([]byte(test.responseBody)) + assert.NoError(t, err) + })) + client := mockAPIClient(t, mockServer) + result, err := client.GetEvalPenaltyBoxConditions(context.Background(), test.params) + if test.withError != nil { + test.withError(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, test.expectedResponse, result) + }) + } +} + +func TestAppsec_UpdateEvalPenaltyBoxConditions(t *testing.T) { + result := UpdatePenaltyBoxConditionsResponse{} + + respData := compactJSON(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json")) + err := json.Unmarshal([]byte(respData), &result) + require.NoError(t, err) + + reqData := PenaltyBoxConditionsPayload{} + err = json.Unmarshal(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json"), &reqData) + require.NoError(t, err) + + loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json") + + reqDataWithNoConditionOperator := PenaltyBoxConditionsPayload{ + ConditionOperator: "", + Conditions: &RuleConditions{}, + } + + reqDataWithNoConditions := PenaltyBoxConditionsPayload{ + ConditionOperator: "AND", + Conditions: nil, + } + + tests := map[string]struct { + params UpdatePenaltyBoxConditionsRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *UpdatePenaltyBoxConditionsResponse + headers http.Header + withError func(*testing.T, error) + }{ + "validation errors - PolicyID cannot be empty string": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + ConditionsPayload: reqData, + PolicyID: "", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + headers: nil, + }, + "validation errors - PolicyID cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + ConditionsPayload: reqData, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + headers: nil, + }, + "validation errors - ConfigId cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + Version: 15, + ConditionsPayload: reqData, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConfigID: cannot be blank", err.Error()) + }, + headers: nil, + }, + "validation errors - VersionId cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + ConditionsPayload: reqData, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Version: cannot be blank", err.Error()) + }, + headers: nil, + }, + "validation errors - Payload cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error creating EvalPenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/eval-penalty-box/conditions", + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConditionOperator: cannot be blank\nConditions: is required", err.Error()) + }, + }, + "validation errors - ConditionOperator cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqDataWithNoConditionOperator, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConditionOperator: cannot be blank", err.Error()) + }, + }, + "validation errors - Conditions cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqDataWithNoConditions, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Conditions: is required", err.Error()) + }, + }, + "200 Success": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqData, + }, + headers: http.Header{ + "Content-Type": []string{"application/json;charset=UTF-8"}, + }, + responseStatus: http.StatusCreated, + responseBody: respData, + expectedResponse: &result, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/eval-penalty-box/conditions", + }, + "500 internal server error": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqData, + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error creating EvalPenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/eval-penalty-box/conditions", + withError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error creating EvalPenaltyBoxConditions", + StatusCode: http.StatusInternalServerError, + } + assert.True(t, errors.Is(err, want), "want: %s; got: %s", want, err) + }, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPut, r.Method) + w.WriteHeader(test.responseStatus) + if len(test.responseBody) > 0 { + _, err := w.Write([]byte(test.responseBody)) + assert.NoError(t, err) + } + })) + client := mockAPIClient(t, mockServer) + result, err := client.UpdateEvalPenaltyBoxConditions( + session.ContextWithOptions( + context.Background(), + session.WithContextHeaders(test.headers)), test.params) + if test.withError != nil { + test.withError(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, test.expectedResponse, result) + }) + } +} diff --git a/pkg/appsec/eval_penalty_box_test.go b/pkg/appsec/eval_penalty_box_test.go index ca5ee658..ccb1eb1c 100644 --- a/pkg/appsec/eval_penalty_box_test.go +++ b/pkg/appsec/eval_penalty_box_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/eval_rule_test.go b/pkg/appsec/eval_rule_test.go index 41c2d1f9..16267999 100644 --- a/pkg/appsec/eval_rule_test.go +++ b/pkg/appsec/eval_rule_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/eval_test.go b/pkg/appsec/eval_test.go index f332d424..2aa50739 100644 --- a/pkg/appsec/eval_test.go +++ b/pkg/appsec/eval_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/export_configuration.go b/pkg/appsec/export_configuration.go index 5d7292d3..beed2b33 100644 --- a/pkg/appsec/export_configuration.go +++ b/pkg/appsec/export_configuration.go @@ -224,18 +224,20 @@ type ( ClientReputation struct { ReputationProfileActions *ClientReputationReputationProfileActions `json:"reputationProfileActions,omitempty"` } `json:"clientReputation"` - RatePolicyActions *SecurityPoliciesRatePolicyActions `json:"ratePolicyActions,omitempty"` - MalwarePolicyActions []MalwarePolicyActionBody `json:"malwarePolicyActions,omitempty"` - IPGeoFirewall *IPGeoFirewall `json:"ipGeoFirewall,omitempty"` - PenaltyBox *SecurityPoliciesPenaltyBox `json:"penaltyBox,omitempty"` - EvaluationPenaltyBox *SecurityPoliciesPenaltyBox `json:"evaluationPenaltyBox,omitempty"` - SlowPost *SlowPostexp `json:"slowPost,omitempty"` - LoggingOverrides *LoggingOverridesexp `json:"loggingOverrides,omitempty"` - AttackPayloadLoggingOverrides *AttackPayloadLoggingOverrides `json:"attackPayloadLoggingOverrides,omitempty"` - PragmaHeader *GetAdvancedSettingsPragmaResponse `json:"pragmaHeader,omitempty"` - EvasivePathMatch *EvasivePathMatchexp `json:"evasivePathMatch,omitempty"` - RequestBody *RequestBody `json:"requestBody,omitempty"` - BotManagement *BotManagement `json:"botManagement,omitempty"` + RatePolicyActions *SecurityPoliciesRatePolicyActions `json:"ratePolicyActions,omitempty"` + MalwarePolicyActions []MalwarePolicyActionBody `json:"malwarePolicyActions,omitempty"` + IPGeoFirewall *IPGeoFirewall `json:"ipGeoFirewall,omitempty"` + PenaltyBox *SecurityPoliciesPenaltyBox `json:"penaltyBox,omitempty"` + EvaluationPenaltyBox *SecurityPoliciesPenaltyBox `json:"evaluationPenaltyBox,omitempty"` + PenaltyBoxConditions *SecurityPoliciesPenaltyBoxConditions `json:"penaltyBoxConditions,omitempty"` + EvaluationPenaltyBoxConditions *SecurityPoliciesPenaltyBoxConditions `json:"evaluationPenaltyBoxConditions,omitempty"` + SlowPost *SlowPostexp `json:"slowPost,omitempty"` + LoggingOverrides *LoggingOverridesexp `json:"loggingOverrides,omitempty"` + AttackPayloadLoggingOverrides *AttackPayloadLoggingOverrides `json:"attackPayloadLoggingOverrides,omitempty"` + PragmaHeader *GetAdvancedSettingsPragmaResponse `json:"pragmaHeader,omitempty"` + EvasivePathMatch *EvasivePathMatchexp `json:"evasivePathMatch,omitempty"` + RequestBody *RequestBody `json:"requestBody,omitempty"` + BotManagement *BotManagement `json:"botManagement,omitempty"` } `json:"securityPolicies"` Siem *Siemexp `json:"siem,omitempty"` AdvancedOptions *AdvancedOptionsexp `json:"advancedOptions,omitempty"` @@ -436,13 +438,15 @@ type ( } } `json:"ukraineGeoControl,omitempty"` } `json:"ipGeoFirewall,omitempty"` - PenaltyBox *SecurityPoliciesPenaltyBox `json:"penaltyBox,omitempty"` - EvaluationPenaltyBox *SecurityPoliciesPenaltyBox `json:"evaluationPenaltyBox,omitempty"` - SlowPost *SlowPostexp `json:"slowPost,omitempty"` - LoggingOverrides *LoggingOverridesexp `json:"loggingOverrides,omitempty"` - AttackPayloadLoggingOverrides *AttackPayloadLoggingOverrides `json:"attackPayloadLoggingOverrides,omitempty"` - PragmaHeader *GetAdvancedSettingsPragmaResponse `json:"pragmaHeader,omitempty"` - EvasivePathMatch *EvasivePathMatchexp `json:"evasivePathMatch,omitempty"` + PenaltyBox *SecurityPoliciesPenaltyBox `json:"penaltyBox,omitempty"` + EvaluationPenaltyBox *SecurityPoliciesPenaltyBox `json:"evaluationPenaltyBox,omitempty"` + PenaltyBoxConditions *SecurityPoliciesPenaltyBoxConditions `json:"penaltyBoxConditions,omitempty"` + EvaluationPenaltyBoxConditions *SecurityPoliciesPenaltyBoxConditions `json:"evaluationPenaltyBoxConditions,omitempty"` + SlowPost *SlowPostexp `json:"slowPost,omitempty"` + LoggingOverrides *LoggingOverridesexp `json:"loggingOverrides,omitempty"` + AttackPayloadLoggingOverrides *AttackPayloadLoggingOverrides `json:"attackPayloadLoggingOverrides,omitempty"` + PragmaHeader *GetAdvancedSettingsPragmaResponse `json:"pragmaHeader,omitempty"` + EvasivePathMatch *EvasivePathMatchexp `json:"evasivePathMatch,omitempty"` } `json:"securityPolicies"` Siem *Siemexp `json:"siem,omitempty"` AdvancedOptions *AdvancedOptionsexp `json:"advancedOptions,omitempty"` @@ -722,6 +726,12 @@ type ( PenaltyBoxProtection bool `json:"penaltyBoxProtection,omitempty"` } + // SecurityPoliciesPenaltyBoxConditions is returned as part of GetExportConfigurationResponse. + SecurityPoliciesPenaltyBoxConditions struct { + ConditionOperator string `json:"conditionOperator,omitempty"` + Conditions *RuleConditions `json:"conditions,omitempty"` + } + // WebApplicationFirewallEvaluation is returned as part of GetExportConfigurationResponse. WebApplicationFirewallEvaluation struct { AttackGroupActions []struct { diff --git a/pkg/appsec/export_configuration_test.go b/pkg/appsec/export_configuration_test.go index 6353b3ad..5cf0c104 100644 --- a/pkg/appsec/export_configuration_test.go +++ b/pkg/appsec/export_configuration_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/failover_hostnames_test.go b/pkg/appsec/failover_hostnames_test.go index ae5a2b68..328f866b 100644 --- a/pkg/appsec/failover_hostnames_test.go +++ b/pkg/appsec/failover_hostnames_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/ip_geo_protection_test.go b/pkg/appsec/ip_geo_protection_test.go index eb6b79f1..bac1fa93 100644 --- a/pkg/appsec/ip_geo_protection_test.go +++ b/pkg/appsec/ip_geo_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/ip_geo_test.go b/pkg/appsec/ip_geo_test.go index a24ae984..a0dea382 100644 --- a/pkg/appsec/ip_geo_test.go +++ b/pkg/appsec/ip_geo_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/malware_policy_action_test.go b/pkg/appsec/malware_policy_action_test.go index c178b801..17816941 100644 --- a/pkg/appsec/malware_policy_action_test.go +++ b/pkg/appsec/malware_policy_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/malware_policy_test.go b/pkg/appsec/malware_policy_test.go index 17a2a5e7..6046dd65 100644 --- a/pkg/appsec/malware_policy_test.go +++ b/pkg/appsec/malware_policy_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/malware_protection_test.go b/pkg/appsec/malware_protection_test.go index c31988ae..21e79d49 100644 --- a/pkg/appsec/malware_protection_test.go +++ b/pkg/appsec/malware_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/match_target_sequence_test.go b/pkg/appsec/match_target_sequence_test.go index 7a45b473..75e6b023 100644 --- a/pkg/appsec/match_target_sequence_test.go +++ b/pkg/appsec/match_target_sequence_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/match_target_test.go b/pkg/appsec/match_target_test.go index 0331d4a0..74edbc99 100644 --- a/pkg/appsec/match_target_test.go +++ b/pkg/appsec/match_target_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/mocks.go b/pkg/appsec/mocks.go index 4141dde7..40c53e76 100644 --- a/pkg/appsec/mocks.go +++ b/pkg/appsec/mocks.go @@ -208,6 +208,14 @@ func (m *Mock) UpdatePenaltyBox(ctx context.Context, req UpdatePenaltyBoxRequest return args.Get(0).(*UpdatePenaltyBoxResponse), args.Error(1) } +func (m *Mock) UpdatePenaltyBoxConditions(ctx context.Context, req UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) { + args := m.Called(ctx, req) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*UpdatePenaltyBoxConditionsResponse), args.Error(1) +} + func (m *Mock) UpdateNetworkLayerProtection(ctx context.Context, req UpdateNetworkLayerProtectionRequest) (*UpdateNetworkLayerProtectionResponse, error) { args := m.Called(ctx, req) if args.Get(0) == nil { @@ -865,6 +873,14 @@ func (m *Mock) GetPenaltyBox(ctx context.Context, req GetPenaltyBoxRequest) (*Ge return args.Get(0).(*GetPenaltyBoxResponse), args.Error(1) } +func (m *Mock) GetPenaltyBoxConditions(ctx context.Context, req GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) { + args := m.Called(ctx, req) + if args.Get(0) == nil { + return nil, args.Error(1) + } + return args.Get(0).(*GetPenaltyBoxConditionsResponse), args.Error(1) +} + func (m *Mock) GetEvalPenaltyBox(ctx context.Context, params GetPenaltyBoxRequest) (*GetPenaltyBoxResponse, error) { args := m.Called(ctx, params) @@ -875,6 +891,16 @@ func (m *Mock) GetEvalPenaltyBox(ctx context.Context, params GetPenaltyBoxReques return args.Get(0).(*GetPenaltyBoxResponse), args.Error(1) } +func (m *Mock) GetEvalPenaltyBoxConditions(ctx context.Context, params GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) { + args := m.Called(ctx, params) + + if args.Get(0) == nil { + return nil, args.Error(1) + } + + return args.Get(0).(*GetPenaltyBoxConditionsResponse), args.Error(1) +} + func (m *Mock) UpdateEvalPenaltyBox(ctx context.Context, params UpdatePenaltyBoxRequest) (*UpdatePenaltyBoxResponse, error) { args := m.Called(ctx, params) @@ -885,6 +911,16 @@ func (m *Mock) UpdateEvalPenaltyBox(ctx context.Context, params UpdatePenaltyBox return args.Get(0).(*UpdatePenaltyBoxResponse), args.Error(1) } +func (m *Mock) UpdateEvalPenaltyBoxConditions(ctx context.Context, params UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) { + args := m.Called(ctx, params) + + if args.Get(0) == nil { + return nil, args.Error(1) + } + + return args.Get(0).(*UpdatePenaltyBoxConditionsResponse), args.Error(1) +} + func (m *Mock) GetNetworkLayerProtections(ctx context.Context, req GetNetworkLayerProtectionsRequest) (*GetNetworkLayerProtectionsResponse, error) { args := m.Called(ctx, req) if args.Get(0) == nil { diff --git a/pkg/appsec/penalty_box_conditions.go b/pkg/appsec/penalty_box_conditions.go new file mode 100644 index 00000000..ddb1894c --- /dev/null +++ b/pkg/appsec/penalty_box_conditions.go @@ -0,0 +1,139 @@ +package appsec + +import ( + "context" + "fmt" + "net/http" + + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" + validation "github.com/go-ozzo/ozzo-validation/v4" +) + +type ( + // PenaltyBoxConditions interface supports retrieving or modifying the penalty box conditions for + // a specified security policy + PenaltyBoxConditions interface { + // GetPenaltyBoxConditions retrieves the penalty box conditions + GetPenaltyBoxConditions(ctx context.Context, params GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) + + // UpdatePenaltyBoxConditions modifies the penalty box conditions for a security policy. + UpdatePenaltyBoxConditions(ctx context.Context, params UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) + } + + // GetPenaltyBoxConditionsRequest describes the GET request for penalty box conditions. + GetPenaltyBoxConditionsRequest struct { + ConfigID int + Version int + PolicyID string + } + + // UpdatePenaltyBoxConditionsRequest describes the PUT request to modify the penalty box conditions. + UpdatePenaltyBoxConditionsRequest struct { + ConfigID int + Version int + PolicyID string + ConditionsPayload PenaltyBoxConditionsPayload + } + + // PenaltyBoxConditionsPayload describes the penalty box conditions with operator + PenaltyBoxConditionsPayload struct { + ConditionOperator string `json:"conditionOperator"` + Conditions *RuleConditions `json:"conditions"` + } + + // GetPenaltyBoxConditionsResponse describes the response with the penalty box conditions. + GetPenaltyBoxConditionsResponse PenaltyBoxConditionsPayload + + // UpdatePenaltyBoxConditionsResponse describes the response with the update of penalty box conditions. + UpdatePenaltyBoxConditionsResponse PenaltyBoxConditionsPayload +) + +// Validate validates a GetPenaltyBoxConditionsRequest. +func (v GetPenaltyBoxConditionsRequest) Validate() error { + return edgegriderr.ParseValidationErrors(validation.Errors{ + "ConfigID": validation.Validate(v.ConfigID, validation.Required), + "Version": validation.Validate(v.Version, validation.Required), + "PolicyID": validation.Validate(v.PolicyID, validation.Required), + }) +} + +// Validate validates an UpdatePenaltyBoxConditionsRequest. +func (v UpdatePenaltyBoxConditionsRequest) Validate() error { + return edgegriderr.ParseValidationErrors(validation.Errors{ + "ConfigID": validation.Validate(v.ConfigID, validation.Required), + "Version": validation.Validate(v.Version, validation.Required), + "PolicyID": validation.Validate(v.PolicyID, validation.Required), + "ConditionsPayload": validation.Validate(v.ConditionsPayload, validation.Required), + }) +} + +// Validate validates an ConditionsPayload +func (v PenaltyBoxConditionsPayload) Validate() error { + return validation.Errors{ + "ConditionOperator": validation.Validate(v.ConditionOperator, validation.Required), + "Conditions": validation.Validate(v.Conditions, validation.NotNil), + }.Filter() +} + +func (p *appsec) GetPenaltyBoxConditions(ctx context.Context, params GetPenaltyBoxConditionsRequest) (*GetPenaltyBoxConditionsResponse, error) { + logger := p.Log(ctx) + logger.Debug("GetPenaltyBoxConditions") + + if err := params.Validate(); err != nil { + return nil, fmt.Errorf("%w: %s", ErrStructValidation, err.Error()) + } + + uri := fmt.Sprintf( + "/appsec/v1/configs/%d/versions/%d/security-policies/%s/penalty-box/conditions", + params.ConfigID, + params.Version, + params.PolicyID) + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil) + if err != nil { + return nil, fmt.Errorf("failed to create GetPenaltyBoxCondition request: %w", err) + } + + var result GetPenaltyBoxConditionsResponse + resp, err := p.Exec(req, &result) + if err != nil { + return nil, fmt.Errorf("get penalty box condition request failed: %w", err) + } + if resp.StatusCode != http.StatusOK { + return nil, p.Error(resp) + } + + return &result, nil +} + +func (p *appsec) UpdatePenaltyBoxConditions(ctx context.Context, params UpdatePenaltyBoxConditionsRequest) (*UpdatePenaltyBoxConditionsResponse, error) { + logger := p.Log(ctx) + logger.Debug("UpdatePenaltyBoxConditions") + + if err := params.Validate(); err != nil { + return nil, fmt.Errorf("%w: %s", ErrStructValidation, err.Error()) + } + + uri := fmt.Sprintf( + "/appsec/v1/configs/%d/versions/%d/security-policies/%s/penalty-box/conditions", + params.ConfigID, + params.Version, + params.PolicyID, + ) + + req, err := http.NewRequestWithContext(ctx, http.MethodPut, uri, nil) + if err != nil { + return nil, fmt.Errorf("failed update penalty box condition request: %w", err) + } + + var result UpdatePenaltyBoxConditionsResponse + resp, err := p.Exec(req, &result, params.ConditionsPayload) + if err != nil { + return nil, fmt.Errorf("update penalty box condition request failed: %w", err) + } + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { + return nil, p.Error(resp) + } + + return &result, nil +} diff --git a/pkg/appsec/penalty_box_conditions_test.go b/pkg/appsec/penalty_box_conditions_test.go new file mode 100644 index 00000000..94a8ae17 --- /dev/null +++ b/pkg/appsec/penalty_box_conditions_test.go @@ -0,0 +1,305 @@ +package appsec + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "testing" + + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestAppSec_ListPenaltyBoxConditions(t *testing.T) { + + result := GetPenaltyBoxConditionsResponse{} + + respData := compactJSON(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json")) + err := json.Unmarshal([]byte(respData), &result) + require.NoError(t, err) + + tests := map[string]struct { + params GetPenaltyBoxConditionsRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *GetPenaltyBoxConditionsResponse + withError func(*testing.T, error) + headers http.Header + }{ + "validation errors - PolicyID cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + }, + "validation errors - Version cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Version: cannot be blank", err.Error()) + }, + }, + "validation errors - ConfigID cannot be blank": { + params: GetPenaltyBoxConditionsRequest{ + Version: 15, + PolicyID: "AAAA_81230", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConfigID: cannot be blank", err.Error()) + }, + }, + "200 OK": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + }, + headers: http.Header{ + "Content-Type": []string{"application/json"}, + }, + responseStatus: http.StatusOK, + responseBody: string(respData), + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/penalty-box/conditions", + expectedResponse: &result, + }, + "500 internal server error": { + params: GetPenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error fetching PenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/penalty-box/conditions", + withError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error fetching PenaltyBoxConditions", + StatusCode: http.StatusInternalServerError, + } + assert.True(t, errors.Is(err, want), "want: %s; got: %s", want, err) + }, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, test.expectedPath, r.URL.String()) + assert.Equal(t, http.MethodGet, r.Method) + w.WriteHeader(test.responseStatus) + _, err := w.Write([]byte(test.responseBody)) + assert.NoError(t, err) + })) + client := mockAPIClient(t, mockServer) + result, err := client.GetPenaltyBoxConditions( + session.ContextWithOptions( + context.Background(), + session.WithContextHeaders(test.headers), + ), + test.params) + if test.withError != nil { + test.withError(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, test.expectedResponse, result) + }) + } +} + +func TestAppSec_UpdatePenaltyBoxConditions(t *testing.T) { + result := UpdatePenaltyBoxConditionsResponse{} + + respData := compactJSON(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json")) + err := json.Unmarshal([]byte(respData), &result) + require.NoError(t, err) + + // eval Penalty Box conditions update test + reqData := PenaltyBoxConditionsPayload{} + err = json.Unmarshal(loadFixtureBytes("testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json"), &reqData) + require.NoError(t, err) + + reqDataWithNoConditionOperator := PenaltyBoxConditionsPayload{ + ConditionOperator: "", + Conditions: &RuleConditions{}, + } + + reqDataWithNoConditions := PenaltyBoxConditionsPayload{ + ConditionOperator: "AND", + Conditions: nil, + } + + tests := map[string]struct { + params UpdatePenaltyBoxConditionsRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *UpdatePenaltyBoxConditionsResponse + withError func(*testing.T, error) + headers http.Header + }{ + "validation errors - PolicyID cannot be empty string": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + ConditionsPayload: reqData, + PolicyID: "", + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + headers: nil, + }, + "validation errors - PolicyID cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + ConditionsPayload: reqData, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: PolicyID: cannot be blank", err.Error()) + }, + }, + "validation errors - ConfigID cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + PolicyID: "AAAA_81230", + Version: 15, + ConditionsPayload: reqData, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConfigID: cannot be blank", err.Error()) + }, + }, + "validation errors - Version cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + PolicyID: "AAAA_81230", + ConditionsPayload: reqData, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Version: cannot be blank", err.Error()) + }, + }, + "validation errors - Request body payload cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + PolicyID: "AAAA_81230", + Version: 15, + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error creating PenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/penalty-box/conditions", + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConditionOperator: cannot be blank\nConditions: is required", err.Error()) + + }, + }, + "validation errors - ConditionOperator cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqDataWithNoConditionOperator, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: ConditionOperator: cannot be blank", err.Error()) + }, + }, + "validation errors - Conditions cannot be blank": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqDataWithNoConditions, + }, + withError: func(t *testing.T, err error) { + assert.Equal(t, "struct validation: Conditions: is required", err.Error()) + }, + }, + "200 Success": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqData, + }, + headers: http.Header{ + "Content-Type": []string{"application/json;charset=UTF-8"}, + }, + responseStatus: http.StatusCreated, + responseBody: respData, + expectedResponse: &result, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/penalty-box/conditions", + }, + "500 internal server error": { + params: UpdatePenaltyBoxConditionsRequest{ + ConfigID: 43253, + Version: 15, + PolicyID: "AAAA_81230", + ConditionsPayload: reqData, + }, + responseStatus: http.StatusInternalServerError, + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error creating PenaltyBoxConditions" + }`, + expectedPath: "/appsec/v1/configs/43253/versions/15/security-policies/AAAA_81230/penalty-box/conditions", + withError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error creating PenaltyBoxConditions", + StatusCode: http.StatusInternalServerError, + } + assert.True(t, errors.Is(err, want), "want: %s; got: %s", want, err) + }, + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + assert.Equal(t, http.MethodPut, r.Method) + w.WriteHeader(test.responseStatus) + if len(test.responseBody) > 0 { + _, err := w.Write([]byte(test.responseBody)) + assert.NoError(t, err) + } + })) + client := mockAPIClient(t, mockServer) + result, err := client.UpdatePenaltyBoxConditions( + session.ContextWithOptions( + context.Background(), + session.WithContextHeaders(test.headers)), test.params) + if test.withError != nil { + test.withError(t, err) + return + } + require.NoError(t, err) + assert.Equal(t, test.expectedResponse, result) + }) + } +} diff --git a/pkg/appsec/penalty_box_test.go b/pkg/appsec/penalty_box_test.go index b4b36577..b583a338 100644 --- a/pkg/appsec/penalty_box_test.go +++ b/pkg/appsec/penalty_box_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/rate_policy_action_test.go b/pkg/appsec/rate_policy_action_test.go index be334893..6ac39d21 100644 --- a/pkg/appsec/rate_policy_action_test.go +++ b/pkg/appsec/rate_policy_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/rate_policy_test.go b/pkg/appsec/rate_policy_test.go index 35f97d15..1ed7ae9a 100644 --- a/pkg/appsec/rate_policy_test.go +++ b/pkg/appsec/rate_policy_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/rate_protection_test.go b/pkg/appsec/rate_protection_test.go index 75b757a5..fab78eb0 100644 --- a/pkg/appsec/rate_protection_test.go +++ b/pkg/appsec/rate_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/reputation_analysis_test.go b/pkg/appsec/reputation_analysis_test.go index 6763bc84..37ba4902 100644 --- a/pkg/appsec/reputation_analysis_test.go +++ b/pkg/appsec/reputation_analysis_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/reputation_profile_action_test.go b/pkg/appsec/reputation_profile_action_test.go index 398ef5dc..985a3c6a 100644 --- a/pkg/appsec/reputation_profile_action_test.go +++ b/pkg/appsec/reputation_profile_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/reputation_profile_test.go b/pkg/appsec/reputation_profile_test.go index 821f032b..0369cfa0 100644 --- a/pkg/appsec/reputation_profile_test.go +++ b/pkg/appsec/reputation_profile_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/reputation_protection_test.go b/pkg/appsec/reputation_protection_test.go index 497b2395..49624695 100644 --- a/pkg/appsec/reputation_protection_test.go +++ b/pkg/appsec/reputation_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/rule_test.go b/pkg/appsec/rule_test.go index c84eb286..77a392b4 100644 --- a/pkg/appsec/rule_test.go +++ b/pkg/appsec/rule_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/rule_upgrade_test.go b/pkg/appsec/rule_upgrade_test.go index 0dd273aa..10d4272f 100644 --- a/pkg/appsec/rule_upgrade_test.go +++ b/pkg/appsec/rule_upgrade_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/security_policy.go b/pkg/appsec/security_policy.go index 462314d5..983a3677 100644 --- a/pkg/appsec/security_policy.go +++ b/pkg/appsec/security_policy.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/appsec/security_policy_clone_test.go b/pkg/appsec/security_policy_clone_test.go index ef96cd70..a2641353 100644 --- a/pkg/appsec/security_policy_clone_test.go +++ b/pkg/appsec/security_policy_clone_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/security_policy_protections_test.go b/pkg/appsec/security_policy_protections_test.go index a5a014f1..60c0ca6d 100644 --- a/pkg/appsec/security_policy_protections_test.go +++ b/pkg/appsec/security_policy_protections_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/security_policy_test.go b/pkg/appsec/security_policy_test.go index 0e39b255..be104ed0 100644 --- a/pkg/appsec/security_policy_test.go +++ b/pkg/appsec/security_policy_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/selectable_hostnames_test.go b/pkg/appsec/selectable_hostnames_test.go index cdc4d0f3..1f10fe64 100644 --- a/pkg/appsec/selectable_hostnames_test.go +++ b/pkg/appsec/selectable_hostnames_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/selected_hostname_test.go b/pkg/appsec/selected_hostname_test.go index 0ba22228..cb16f4fa 100644 --- a/pkg/appsec/selected_hostname_test.go +++ b/pkg/appsec/selected_hostname_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/siem_settings_test.go b/pkg/appsec/siem_settings_test.go index 42d9c323..d834319d 100644 --- a/pkg/appsec/siem_settings_test.go +++ b/pkg/appsec/siem_settings_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/slow_post_protection_setting_test.go b/pkg/appsec/slow_post_protection_setting_test.go index ce4fd812..0aafcdee 100644 --- a/pkg/appsec/slow_post_protection_setting_test.go +++ b/pkg/appsec/slow_post_protection_setting_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/slowpost_protection_test.go b/pkg/appsec/slowpost_protection_test.go index a07b2eae..723f45a6 100644 --- a/pkg/appsec/slowpost_protection_test.go +++ b/pkg/appsec/slowpost_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/testdata/TestExportConfiguration/ExportConfiguration.json b/pkg/appsec/testdata/TestExportConfiguration/ExportConfiguration.json index 992f781a..d80d1125 100644 --- a/pkg/appsec/testdata/TestExportConfiguration/ExportConfiguration.json +++ b/pkg/appsec/testdata/TestExportConfiguration/ExportConfiguration.json @@ -1691,6 +1691,30 @@ "ipGeoFirewall": { "block": "blockSpecificIPGeo" }, + "penaltyBoxConditions": { + "conditionOperator": "AND", + "conditions": [ + { + "type": "filenameMatch", + "filenames": [ + "appptest45" + ], + "positiveMatch": true + } + ] + }, + "evaluationPenaltyBoxConditions": { + "conditionOperator": "AND", + "conditions": [ + { + "type": "filenameMatch", + "filenames": [ + "appptest46" + ], + "positiveMatch": true + } + ] + }, "slowPost": { "action": "alert", "slowRateThreshold": { diff --git a/pkg/appsec/testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json b/pkg/appsec/testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json new file mode 100644 index 00000000..09d0c537 --- /dev/null +++ b/pkg/appsec/testdata/TestPenaltyBoxConditions/PenaltyBoxConditions.json @@ -0,0 +1,14 @@ +{ + "conditionOperator": "AND", + "conditions": [ + { + "type": "filenameMatch", + "filenames": [ + "hh" + ], + "order": 0, + "positiveMatch": true + } + ] +} + diff --git a/pkg/appsec/threat_intel_test.go b/pkg/appsec/threat_intel_test.go index 51df3179..93f394d3 100644 --- a/pkg/appsec/threat_intel_test.go +++ b/pkg/appsec/threat_intel_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/tuning_recommendations_test.go b/pkg/appsec/tuning_recommendations_test.go index 7f4dbef6..4ff76065 100644 --- a/pkg/appsec/tuning_recommendations_test.go +++ b/pkg/appsec/tuning_recommendations_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/version_notes_test.go b/pkg/appsec/version_notes_test.go index 46aada61..2f2cf363 100644 --- a/pkg/appsec/version_notes_test.go +++ b/pkg/appsec/version_notes_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/waf_mode_test.go b/pkg/appsec/waf_mode_test.go index 56ad6eba..72039ec9 100644 --- a/pkg/appsec/waf_mode_test.go +++ b/pkg/appsec/waf_mode_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/waf_protection_test.go b/pkg/appsec/waf_protection_test.go index 9dca5d08..47e64983 100644 --- a/pkg/appsec/waf_protection_test.go +++ b/pkg/appsec/waf_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/wap_bypass_network_lists_test.go b/pkg/appsec/wap_bypass_network_lists_test.go index 11a65c03..26475963 100644 --- a/pkg/appsec/wap_bypass_network_lists_test.go +++ b/pkg/appsec/wap_bypass_network_lists_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/appsec/wap_selected_hostnames_test.go b/pkg/appsec/wap_selected_hostnames_test.go index 65c312ea..14e7d349 100644 --- a/pkg/appsec/wap_selected_hostnames_test.go +++ b/pkg/appsec/wap_selected_hostnames_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/akamai_bot_category_action_test.go b/pkg/botman/akamai_bot_category_action_test.go index e6800ad9..9f2debe8 100644 --- a/pkg/botman/akamai_bot_category_action_test.go +++ b/pkg/botman/akamai_bot_category_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/akamai_bot_category_test.go b/pkg/botman/akamai_bot_category_test.go index 4dfb1a37..b202d4fb 100644 --- a/pkg/botman/akamai_bot_category_test.go +++ b/pkg/botman/akamai_bot_category_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/akamai_defined_bot_test.go b/pkg/botman/akamai_defined_bot_test.go index d1ab078f..54eeb483 100644 --- a/pkg/botman/akamai_defined_bot_test.go +++ b/pkg/botman/akamai_defined_bot_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_analytics_cookie_test.go b/pkg/botman/bot_analytics_cookie_test.go index aa24d009..823db04c 100644 --- a/pkg/botman/bot_analytics_cookie_test.go +++ b/pkg/botman/bot_analytics_cookie_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_analytics_cookie_values_test.go b/pkg/botman/bot_analytics_cookie_values_test.go index 34090fa0..c4f08a19 100644 --- a/pkg/botman/bot_analytics_cookie_values_test.go +++ b/pkg/botman/bot_analytics_cookie_values_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_category_exception_test.go b/pkg/botman/bot_category_exception_test.go index a48e24a6..2b1bbbe1 100644 --- a/pkg/botman/bot_category_exception_test.go +++ b/pkg/botman/bot_category_exception_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/botman/bot_detection_action_test.go b/pkg/botman/bot_detection_action_test.go index 91fce3f3..ec06a913 100644 --- a/pkg/botman/bot_detection_action_test.go +++ b/pkg/botman/bot_detection_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_detection_test.go b/pkg/botman/bot_detection_test.go index bcf5b88e..9e5454e9 100644 --- a/pkg/botman/bot_detection_test.go +++ b/pkg/botman/bot_detection_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_endpoint_coverage_report_test.go b/pkg/botman/bot_endpoint_coverage_report_test.go index 4ce951d3..75c5ef5d 100644 --- a/pkg/botman/bot_endpoint_coverage_report_test.go +++ b/pkg/botman/bot_endpoint_coverage_report_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/bot_management_setting_test.go b/pkg/botman/bot_management_setting_test.go index 740281c5..cd7231f3 100644 --- a/pkg/botman/bot_management_setting_test.go +++ b/pkg/botman/bot_management_setting_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/botman/botman.go b/pkg/botman/botman.go index 50dff4f1..5c062114 100644 --- a/pkg/botman/botman.go +++ b/pkg/botman/botman.go @@ -4,7 +4,7 @@ package botman import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/botman/botman_test.go b/pkg/botman/botman_test.go index 1f9a46d4..b30a12ee 100644 --- a/pkg/botman/botman_test.go +++ b/pkg/botman/botman_test.go @@ -12,8 +12,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/challenge_action_test.go b/pkg/botman/challenge_action_test.go index 7f27fdb6..f017d8f2 100644 --- a/pkg/botman/challenge_action_test.go +++ b/pkg/botman/challenge_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/challenge_injection_rules.go b/pkg/botman/challenge_injection_rules.go index 3d4d24e8..9d455a5d 100644 --- a/pkg/botman/challenge_injection_rules.go +++ b/pkg/botman/challenge_injection_rules.go @@ -6,7 +6,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/botman/challenge_injection_rules_test.go b/pkg/botman/challenge_injection_rules_test.go index 66f4fbd4..0d4f4743 100644 --- a/pkg/botman/challenge_injection_rules_test.go +++ b/pkg/botman/challenge_injection_rules_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/challenge_interception_rules_test.go b/pkg/botman/challenge_interception_rules_test.go index baf2a138..0f757cd3 100644 --- a/pkg/botman/challenge_interception_rules_test.go +++ b/pkg/botman/challenge_interception_rules_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/client_side_security_test.go b/pkg/botman/client_side_security_test.go index aa1355bd..3fbcc949 100644 --- a/pkg/botman/client_side_security_test.go +++ b/pkg/botman/client_side_security_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/conditonal_action_test.go b/pkg/botman/conditonal_action_test.go index f7225c95..0feaeddb 100644 --- a/pkg/botman/conditonal_action_test.go +++ b/pkg/botman/conditonal_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_bot_category_action_test.go b/pkg/botman/custom_bot_category_action_test.go index cd12fc49..ec230c50 100644 --- a/pkg/botman/custom_bot_category_action_test.go +++ b/pkg/botman/custom_bot_category_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_bot_category_sequence_test.go b/pkg/botman/custom_bot_category_sequence_test.go index 4263189d..c7c7719b 100644 --- a/pkg/botman/custom_bot_category_sequence_test.go +++ b/pkg/botman/custom_bot_category_sequence_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_bot_category_test.go b/pkg/botman/custom_bot_category_test.go index 0f83e137..20508a48 100644 --- a/pkg/botman/custom_bot_category_test.go +++ b/pkg/botman/custom_bot_category_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_client_sequence.go b/pkg/botman/custom_client_sequence.go index 299b6de2..5fbfc96b 100644 --- a/pkg/botman/custom_client_sequence.go +++ b/pkg/botman/custom_client_sequence.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/botman/custom_client_sequence_test.go b/pkg/botman/custom_client_sequence_test.go index 21b11158..6b18b426 100644 --- a/pkg/botman/custom_client_sequence_test.go +++ b/pkg/botman/custom_client_sequence_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_client_test.go b/pkg/botman/custom_client_test.go index 10c1b5f7..d5cd2758 100644 --- a/pkg/botman/custom_client_test.go +++ b/pkg/botman/custom_client_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_code_test.go b/pkg/botman/custom_code_test.go index 31c44fd9..e0d43ba3 100644 --- a/pkg/botman/custom_code_test.go +++ b/pkg/botman/custom_code_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_defined_bot_test.go b/pkg/botman/custom_defined_bot_test.go index 120837a5..ce4885cf 100644 --- a/pkg/botman/custom_defined_bot_test.go +++ b/pkg/botman/custom_defined_bot_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/custom_deny_action_test.go b/pkg/botman/custom_deny_action_test.go index 99e68e2d..68fcabc2 100644 --- a/pkg/botman/custom_deny_action_test.go +++ b/pkg/botman/custom_deny_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/errors.go b/pkg/botman/errors.go index 55173b63..c2c1a306 100644 --- a/pkg/botman/errors.go +++ b/pkg/botman/errors.go @@ -8,7 +8,7 @@ import ( "net/http" "strings" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/botman/errors_test.go b/pkg/botman/errors_test.go index 1e3acc0b..4efa1882 100644 --- a/pkg/botman/errors_test.go +++ b/pkg/botman/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" diff --git a/pkg/botman/javascript_injection_test.go b/pkg/botman/javascript_injection_test.go index a9831636..f7f5f900 100644 --- a/pkg/botman/javascript_injection_test.go +++ b/pkg/botman/javascript_injection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/recategorized_akamai_defined_bot_test.go b/pkg/botman/recategorized_akamai_defined_bot_test.go index a9444932..b51696bc 100644 --- a/pkg/botman/recategorized_akamai_defined_bot_test.go +++ b/pkg/botman/recategorized_akamai_defined_bot_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/response_action_test.go b/pkg/botman/response_action_test.go index 9a18ad06..47744a23 100644 --- a/pkg/botman/response_action_test.go +++ b/pkg/botman/response_action_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/serve_alternate_action_test.go b/pkg/botman/serve_alternate_action_test.go index a6519d0d..f9c1ead8 100644 --- a/pkg/botman/serve_alternate_action_test.go +++ b/pkg/botman/serve_alternate_action_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/transactional_endpoint_protection_test.go b/pkg/botman/transactional_endpoint_protection_test.go index 0d572e37..d8120e06 100644 --- a/pkg/botman/transactional_endpoint_protection_test.go +++ b/pkg/botman/transactional_endpoint_protection_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/botman/transactional_endpoint_test.go b/pkg/botman/transactional_endpoint_test.go index 80bb2cfc..5541c8f5 100644 --- a/pkg/botman/transactional_endpoint_test.go +++ b/pkg/botman/transactional_endpoint_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/clientlists/client_list.go b/pkg/clientlists/client_list.go index 2ac065a6..bae14f21 100644 --- a/pkg/clientlists/client_list.go +++ b/pkg/clientlists/client_list.go @@ -7,7 +7,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/clientlists/client_list_activation.go b/pkg/clientlists/client_list_activation.go index 90511773..b29ae558 100644 --- a/pkg/clientlists/client_list_activation.go +++ b/pkg/clientlists/client_list_activation.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/clientlists/client_list_activation_test.go b/pkg/clientlists/client_list_activation_test.go index 5d852594..2c9d807e 100644 --- a/pkg/clientlists/client_list_activation_test.go +++ b/pkg/clientlists/client_list_activation_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/clientlists/client_list_test.go b/pkg/clientlists/client_list_test.go index 6abebb10..373457f8 100644 --- a/pkg/clientlists/client_list_test.go +++ b/pkg/clientlists/client_list_test.go @@ -9,8 +9,8 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/clientlists/clientlists.go b/pkg/clientlists/clientlists.go index 1ea40582..b358c3c2 100644 --- a/pkg/clientlists/clientlists.go +++ b/pkg/clientlists/clientlists.go @@ -6,7 +6,7 @@ package clientlists import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/clientlists/clientlists_test.go b/pkg/clientlists/clientlists_test.go index e6576215..7e36a309 100644 --- a/pkg/clientlists/clientlists_test.go +++ b/pkg/clientlists/clientlists_test.go @@ -12,8 +12,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/clientlists/errors.go b/pkg/clientlists/errors.go index 173c208a..5095c72e 100644 --- a/pkg/clientlists/errors.go +++ b/pkg/clientlists/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/clientlists/errors_test.go b/pkg/clientlists/errors_test.go index ca5015d7..a5bb704d 100644 --- a/pkg/clientlists/errors_test.go +++ b/pkg/clientlists/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" diff --git a/pkg/cloudlets/cloudlets.go b/pkg/cloudlets/cloudlets.go index 692243c0..407e3894 100644 --- a/pkg/cloudlets/cloudlets.go +++ b/pkg/cloudlets/cloudlets.go @@ -4,7 +4,7 @@ package cloudlets import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/cloudlets/cloudlets_test.go b/pkg/cloudlets/cloudlets_test.go index cf694e53..341e0394 100644 --- a/pkg/cloudlets/cloudlets_test.go +++ b/pkg/cloudlets/cloudlets_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cloudlets/errors.go b/pkg/cloudlets/errors.go index 942c44ad..993c011b 100644 --- a/pkg/cloudlets/errors.go +++ b/pkg/cloudlets/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/cloudlets/errors_test.go b/pkg/cloudlets/errors_test.go index 11d4d711..9511d89e 100644 --- a/pkg/cloudlets/errors_test.go +++ b/pkg/cloudlets/errors_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/cloudlets/loadbalancer.go b/pkg/cloudlets/loadbalancer.go index 84b4b2a7..0f9e0b6f 100644 --- a/pkg/cloudlets/loadbalancer.go +++ b/pkg/cloudlets/loadbalancer.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/loadbalancer_activation.go b/pkg/cloudlets/loadbalancer_activation.go index 02a62fb7..269f9574 100644 --- a/pkg/cloudlets/loadbalancer_activation.go +++ b/pkg/cloudlets/loadbalancer_activation.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/loadbalancer_activation_test.go b/pkg/cloudlets/loadbalancer_activation_test.go index 043ed1ba..54ffc9fb 100644 --- a/pkg/cloudlets/loadbalancer_activation_test.go +++ b/pkg/cloudlets/loadbalancer_activation_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/cloudlets/loadbalancer_version.go b/pkg/cloudlets/loadbalancer_version.go index 11775f65..8859b21f 100644 --- a/pkg/cloudlets/loadbalancer_version.go +++ b/pkg/cloudlets/loadbalancer_version.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/loadbalancer_version_test.go b/pkg/cloudlets/loadbalancer_version_test.go index 345f3b2b..21914e24 100644 --- a/pkg/cloudlets/loadbalancer_version_test.go +++ b/pkg/cloudlets/loadbalancer_version_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" validation "github.com/go-ozzo/ozzo-validation/v4" "github.com/stretchr/testify/require" diff --git a/pkg/cloudlets/match_rule.go b/pkg/cloudlets/match_rule.go index 5fb1fff5..766f0496 100644 --- a/pkg/cloudlets/match_rule.go +++ b/pkg/cloudlets/match_rule.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/match_rule_test.go b/pkg/cloudlets/match_rule_test.go index 0edbb669..bb1586d9 100644 --- a/pkg/cloudlets/match_rule_test.go +++ b/pkg/cloudlets/match_rule_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tj/assert" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" ) func TestUnmarshalJSONMatchRules(t *testing.T) { diff --git a/pkg/cloudlets/policy_property.go b/pkg/cloudlets/policy_property.go index 83c60271..dd466fa0 100644 --- a/pkg/cloudlets/policy_property.go +++ b/pkg/cloudlets/policy_property.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/policy_test.go b/pkg/cloudlets/policy_test.go index 4ed3e82b..80233ea1 100644 --- a/pkg/cloudlets/policy_test.go +++ b/pkg/cloudlets/policy_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" diff --git a/pkg/cloudlets/policy_version.go b/pkg/cloudlets/policy_version.go index caa18fa3..42777378 100644 --- a/pkg/cloudlets/policy_version.go +++ b/pkg/cloudlets/policy_version.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/policy_version_activation.go b/pkg/cloudlets/policy_version_activation.go index 77bf3bef..1b2ce15b 100644 --- a/pkg/cloudlets/policy_version_activation.go +++ b/pkg/cloudlets/policy_version_activation.go @@ -8,7 +8,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/policy_version_test.go b/pkg/cloudlets/policy_version_test.go index 1b61c652..57786a96 100644 --- a/pkg/cloudlets/policy_version_test.go +++ b/pkg/cloudlets/policy_version_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" diff --git a/pkg/cloudlets/v3/cloudlets.go b/pkg/cloudlets/v3/cloudlets.go index 8f14eee9..c9aa5bd3 100644 --- a/pkg/cloudlets/v3/cloudlets.go +++ b/pkg/cloudlets/v3/cloudlets.go @@ -5,7 +5,7 @@ import ( "context" "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/cloudlets/v3/cloudlets_test.go b/pkg/cloudlets/v3/cloudlets_test.go index 59905a49..1075b301 100644 --- a/pkg/cloudlets/v3/cloudlets_test.go +++ b/pkg/cloudlets/v3/cloudlets_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cloudlets/v3/errors.go b/pkg/cloudlets/v3/errors.go index 0d9e9b61..860f7664 100644 --- a/pkg/cloudlets/v3/errors.go +++ b/pkg/cloudlets/v3/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) // Error is a cloudlets error interface. diff --git a/pkg/cloudlets/v3/errors_test.go b/pkg/cloudlets/v3/errors_test.go index bd9ba2c7..b3e3f28c 100644 --- a/pkg/cloudlets/v3/errors_test.go +++ b/pkg/cloudlets/v3/errors_test.go @@ -8,7 +8,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/cloudlets/v3/match_rule.go b/pkg/cloudlets/v3/match_rule.go index 1ab2a0fd..65d12e13 100644 --- a/pkg/cloudlets/v3/match_rule.go +++ b/pkg/cloudlets/v3/match_rule.go @@ -5,7 +5,7 @@ import ( "errors" "fmt" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/v3/match_rule_test.go b/pkg/cloudlets/v3/match_rule_test.go index 2f44d941..68ea0637 100644 --- a/pkg/cloudlets/v3/match_rule_test.go +++ b/pkg/cloudlets/v3/match_rule_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tj/assert" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" ) func TestUnmarshalJSONMatchRules(t *testing.T) { diff --git a/pkg/cloudlets/v3/policy.go b/pkg/cloudlets/v3/policy.go index bdc860cf..98e64516 100644 --- a/pkg/cloudlets/v3/policy.go +++ b/pkg/cloudlets/v3/policy.go @@ -10,7 +10,7 @@ import ( "strconv" "time" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/v3/policy_activation.go b/pkg/cloudlets/v3/policy_activation.go index fd52e42c..d3492886 100644 --- a/pkg/cloudlets/v3/policy_activation.go +++ b/pkg/cloudlets/v3/policy_activation.go @@ -9,7 +9,7 @@ import ( "strconv" "time" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/v3/policy_property.go b/pkg/cloudlets/v3/policy_property.go index 98b9e9d4..19869897 100644 --- a/pkg/cloudlets/v3/policy_property.go +++ b/pkg/cloudlets/v3/policy_property.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/v3/policy_test.go b/pkg/cloudlets/v3/policy_test.go index aa3ed6d6..5e0931a9 100644 --- a/pkg/cloudlets/v3/policy_test.go +++ b/pkg/cloudlets/v3/policy_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cloudlets/v3/policy_version.go b/pkg/cloudlets/v3/policy_version.go index 17f00661..eaf7abf9 100644 --- a/pkg/cloudlets/v3/policy_version.go +++ b/pkg/cloudlets/v3/policy_version.go @@ -8,7 +8,7 @@ import ( "net/url" "time" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudlets/v3/policy_version_test.go b/pkg/cloudlets/v3/policy_version_test.go index 35b377de..4f45a457 100644 --- a/pkg/cloudlets/v3/policy_version_test.go +++ b/pkg/cloudlets/v3/policy_version_test.go @@ -9,7 +9,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/cloudwrapper/cloudwrapper.go b/pkg/cloudwrapper/cloudwrapper.go index 1125da47..46b8bbcf 100644 --- a/pkg/cloudwrapper/cloudwrapper.go +++ b/pkg/cloudwrapper/cloudwrapper.go @@ -4,7 +4,7 @@ package cloudwrapper import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/cloudwrapper/cloudwrapper_test.go b/pkg/cloudwrapper/cloudwrapper_test.go index 8f48bdd6..1922f35e 100644 --- a/pkg/cloudwrapper/cloudwrapper_test.go +++ b/pkg/cloudwrapper/cloudwrapper_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cloudwrapper/configurations.go b/pkg/cloudwrapper/configurations.go index 39f34a9b..6d47041b 100644 --- a/pkg/cloudwrapper/configurations.go +++ b/pkg/cloudwrapper/configurations.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudwrapper/configurations_test.go b/pkg/cloudwrapper/configurations_test.go index 93347435..9f5cc7ed 100644 --- a/pkg/cloudwrapper/configurations_test.go +++ b/pkg/cloudwrapper/configurations_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cloudwrapper/errors.go b/pkg/cloudwrapper/errors.go index aa0c15e9..428b2b9b 100644 --- a/pkg/cloudwrapper/errors.go +++ b/pkg/cloudwrapper/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/cloudwrapper/errors_test.go b/pkg/cloudwrapper/errors_test.go index 478fdc94..aa030f54 100644 --- a/pkg/cloudwrapper/errors_test.go +++ b/pkg/cloudwrapper/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/cloudwrapper/multi_cdn.go b/pkg/cloudwrapper/multi_cdn.go index 3326d2db..8824ea2e 100644 --- a/pkg/cloudwrapper/multi_cdn.go +++ b/pkg/cloudwrapper/multi_cdn.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cloudwrapper/properties.go b/pkg/cloudwrapper/properties.go index fd5d3720..e4b12f89 100644 --- a/pkg/cloudwrapper/properties.go +++ b/pkg/cloudwrapper/properties.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/cps/change_management_info.go b/pkg/cps/change_management_info.go index 68cf2eeb..4e3c222f 100644 --- a/pkg/cps/change_management_info.go +++ b/pkg/cps/change_management_info.go @@ -131,7 +131,7 @@ func (c *cps) GetChangeDeploymentInfo(ctx context.Context, params GetChangeReque if err != nil { return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetChangeDeploymentInfo, err) } - req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v7+json") + req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v8+json") var result ChangeDeploymentInfoResponse resp, err := c.Exec(req, &result) diff --git a/pkg/cps/change_management_info_test.go b/pkg/cps/change_management_info_test.go index c5ad5a30..9e1bc348 100644 --- a/pkg/cps/change_management_info_test.go +++ b/pkg/cps/change_management_info_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -258,7 +258,7 @@ func TestGetChangeDeploymentInfo(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) - assert.Equal(t, "application/vnd.akamai.cps.deployment.v7+json", r.Header.Get("Accept")) + assert.Equal(t, "application/vnd.akamai.cps.deployment.v8+json", r.Header.Get("Accept")) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) diff --git a/pkg/cps/cps.go b/pkg/cps/cps.go index bbef90ff..c8166158 100644 --- a/pkg/cps/cps.go +++ b/pkg/cps/cps.go @@ -4,7 +4,7 @@ package cps import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/cps/cps_test.go b/pkg/cps/cps_test.go index f4b4b313..40aea834 100644 --- a/pkg/cps/cps_test.go +++ b/pkg/cps/cps_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cps/deployment_schedules_test.go b/pkg/cps/deployment_schedules_test.go index 492fe4f2..4f145882 100644 --- a/pkg/cps/deployment_schedules_test.go +++ b/pkg/cps/deployment_schedules_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/cps/deployments.go b/pkg/cps/deployments.go index dd74c9d9..b89f9ec1 100644 --- a/pkg/cps/deployments.go +++ b/pkg/cps/deployments.go @@ -119,7 +119,7 @@ func (c *cps) ListDeployments(ctx context.Context, params ListDeploymentsRequest if err != nil { return nil, fmt.Errorf("%w: failed to create request: %s", ErrListDeployments, err) } - req.Header.Set("Accept", "application/vnd.akamai.cps.deployments.v7+json") + req.Header.Set("Accept", "application/vnd.akamai.cps.deployments.v8+json") var result ListDeploymentsResponse resp, err := c.Exec(req, &result) @@ -148,7 +148,7 @@ func (c *cps) GetProductionDeployment(ctx context.Context, params GetDeploymentR if err != nil { return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetProductionDeployment, err) } - req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v7+json") + req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v8+json") var result GetProductionDeploymentResponse resp, err := c.Exec(req, &result) @@ -177,7 +177,7 @@ func (c *cps) GetStagingDeployment(ctx context.Context, params GetDeploymentRequ if err != nil { return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetStagingDeployment, err) } - req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v7+json") + req.Header.Set("Accept", "application/vnd.akamai.cps.deployment.v8+json") var result GetStagingDeploymentResponse resp, err := c.Exec(req, &result) diff --git a/pkg/cps/deployments_test.go b/pkg/cps/deployments_test.go index 0151679b..385a6989 100644 --- a/pkg/cps/deployments_test.go +++ b/pkg/cps/deployments_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -99,7 +99,7 @@ func TestListDeployments(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/10/deployments", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployments.v7+json", + "Accept": "application/vnd.akamai.cps.deployments.v8+json", }, expectedResponse: &ListDeploymentsResponse{ Production: &Deployment{ @@ -186,7 +186,7 @@ func TestListDeployments(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/500/deployments", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployments.v7+json", + "Accept": "application/vnd.akamai.cps.deployments.v8+json", }, withError: func(t *testing.T, err error) { want := &Error{ @@ -274,7 +274,7 @@ func TestGetProductionDeployment(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/10/deployments/production", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployment.v7+json", + "Accept": "application/vnd.akamai.cps.deployment.v8+json", }, expectedResponse: &GetProductionDeploymentResponse{ OCSPStapled: tools.BoolPtr(false), @@ -324,7 +324,7 @@ func TestGetProductionDeployment(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/500/deployments/production", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployment.v7+json", + "Accept": "application/vnd.akamai.cps.deployment.v8+json", }, withError: func(t *testing.T, err error) { want := &Error{ @@ -418,7 +418,7 @@ func TestGetStagingDeployment(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/10/deployments/staging", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployment.v7+json", + "Accept": "application/vnd.akamai.cps.deployment.v8+json", }, expectedResponse: &GetStagingDeploymentResponse{ @@ -469,7 +469,7 @@ func TestGetStagingDeployment(t *testing.T) { }`, expectedPath: "/cps/v2/enrollments/500/deployments/staging", expectedHeaders: map[string]string{ - "Accept": "application/vnd.akamai.cps.deployment.v7+json", + "Accept": "application/vnd.akamai.cps.deployment.v8+json", }, withError: func(t *testing.T, err error) { want := &Error{ diff --git a/pkg/cps/enrollments.go b/pkg/cps/enrollments.go index 16ffe758..ae83b04a 100644 --- a/pkg/cps/enrollments.go +++ b/pkg/cps/enrollments.go @@ -22,7 +22,7 @@ type ( // GetEnrollment fetches enrollment object with given ID // // See: https://techdocs.akamai.com/cps/reference/get-enrollment - GetEnrollment(context.Context, GetEnrollmentRequest) (*Enrollment, error) + GetEnrollment(context.Context, GetEnrollmentRequest) (*GetEnrollmentResponse, error) // CreateEnrollment creates a new enrollment // @@ -45,8 +45,15 @@ type ( Enrollments []Enrollment `json:"enrollments"` } - // Enrollment represents a CPS enrollment object. It is used both as a request body for enrollment creation and response body while fetching enrollment by ID + // GetEnrollmentResponse contains response body from GetEnrollment operation + GetEnrollmentResponse Enrollment + + // Enrollment represents a CPS enrollment object. It is used as a response body while fetching enrollment by ID and listing multiple enrollments Enrollment struct { + ID int `json:"id"` + ProductionSlots []int `json:"productionSlots"` + StagingSlots []int `json:"stagingSlots"` + AssignedSlots []int `json:"assignedSlots"` AdminContact *Contact `json:"adminContact"` AutoRenewalStartTime string `json:"autoRenewalStartTime,omitempty"` CertificateChainType string `json:"certificateChainType,omitempty"` @@ -59,6 +66,7 @@ type ( MaxAllowedWildcardSanNames int `json:"maxAllowedWildcardSanNames,omitempty"` NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration"` Org *Org `json:"org"` + OrgID *int `json:"orgId"` PendingChanges []PendingChange `json:"pendingChanges,omitempty"` RA string `json:"ra"` SignatureAlgorithm string `json:"signatureAlgorithm,omitempty"` @@ -167,13 +175,32 @@ type ( // CreateEnrollmentRequest contains request body and path parameters used to create an enrollment CreateEnrollmentRequest struct { - Enrollment + EnrollmentRequestBody ContractID string DeployNotAfter string DeployNotBefore string AllowDuplicateCN bool } + // EnrollmentRequestBody represents request body parameters specific to the enrollment + EnrollmentRequestBody struct { + AdminContact *Contact `json:"adminContact"` + AutoRenewalStartTime string `json:"autoRenewalStartTime,omitempty"` + CertificateChainType string `json:"certificateChainType,omitempty"` + CertificateType string `json:"certificateType"` + ChangeManagement bool `json:"changeManagement"` + CSR *CSR `json:"csr"` + EnableMultiStackedCertificates bool `json:"enableMultiStackedCertificates"` + NetworkConfiguration *NetworkConfiguration `json:"networkConfiguration"` + Org *Org `json:"org"` + OrgID *int `json:"orgId,omitempty"` + RA string `json:"ra"` + SignatureAlgorithm string `json:"signatureAlgorithm,omitempty"` + TechContact *Contact `json:"techContact"` + ThirdParty *ThirdParty `json:"thirdParty,omitempty"` + ValidationType string `json:"validationType"` + } + // CreateEnrollmentResponse contains response body returned after successful enrollment creation CreateEnrollmentResponse struct { ID int @@ -183,7 +210,7 @@ type ( // UpdateEnrollmentRequest contains request body and path parameters used to update an enrollment UpdateEnrollmentRequest struct { - Enrollment + EnrollmentRequestBody EnrollmentID int AllowCancelPendingChanges *bool AllowStagingBypass *bool @@ -227,8 +254,8 @@ const ( OCSPStaplingNotSet OCSPStapling = "not-set" ) -// Validate performs validation on Enrollment -func (e Enrollment) Validate() error { +// Validate performs validation on EnrollmentRequestBody +func (e EnrollmentRequestBody) Validate() error { errs := validation.Errors{ "adminContact": validation.Validate(e.AdminContact, validation.Required), "certificateType": validation.Validate(e.CertificateType, validation.Required), @@ -249,7 +276,7 @@ func (e Enrollment) Validate() error { return errs.Filter() } -// Validate performs validation on Enrollment +// Validate performs validation on CSR func (c CSR) Validate() error { return validation.Errors{ "cn": validation.Validate(c.CN, validation.Required), @@ -263,7 +290,7 @@ func (n NetworkConfiguration) Validate() error { }.Filter() } -// Validate performs validation on ListEnrollmentRequest +// Validate performs validation on ListEnrollmentsRequest func (e ListEnrollmentsRequest) Validate() error { return validation.Errors{ "contractId": validation.Validate(e.ContractID, validation.Required), @@ -280,7 +307,7 @@ func (e GetEnrollmentRequest) Validate() error { // Validate performs validation on CreateEnrollmentRequest func (e CreateEnrollmentRequest) Validate() error { return validation.Errors{ - "enrollment": validation.Validate(e.Enrollment, validation.Required), + "enrollment": validation.Validate(e.EnrollmentRequestBody, validation.Required), "contractId": validation.Validate(e.ContractID, validation.Required), }.Filter() } @@ -288,7 +315,7 @@ func (e CreateEnrollmentRequest) Validate() error { // Validate performs validation on UpdateEnrollmentRequest func (e UpdateEnrollmentRequest) Validate() error { return validation.Errors{ - "enrollment": validation.Validate(e.Enrollment, validation.Required), + "enrollment": validation.Validate(e.EnrollmentRequestBody, validation.Required), "enrollmentId": validation.Validate(e.EnrollmentID, validation.Required), }.Filter() } @@ -343,7 +370,7 @@ func (c *cps) ListEnrollments(ctx context.Context, params ListEnrollmentsRequest return &result, nil } -func (c *cps) GetEnrollment(ctx context.Context, params GetEnrollmentRequest) (*Enrollment, error) { +func (c *cps) GetEnrollment(ctx context.Context, params GetEnrollmentRequest) (*GetEnrollmentResponse, error) { if err := params.Validate(); err != nil { return nil, fmt.Errorf("%s: %w: %s", ErrGetEnrollment, ErrStructValidation, err) } @@ -359,7 +386,7 @@ func (c *cps) GetEnrollment(ctx context.Context, params GetEnrollmentRequest) (* } req.Header.Set("Accept", "application/vnd.akamai.cps.enrollment.v11+json") - var result Enrollment + var result GetEnrollmentResponse resp, err := c.Exec(req, &result) if err != nil { @@ -405,7 +432,7 @@ func (c *cps) CreateEnrollment(ctx context.Context, params CreateEnrollmentReque var result CreateEnrollmentResponse - resp, err := c.Exec(req, &result, params.Enrollment) + resp, err := c.Exec(req, &result, params.EnrollmentRequestBody) if err != nil { return nil, fmt.Errorf("%w: request failed: %s", ErrCreateEnrollment, err) } @@ -464,7 +491,7 @@ func (c *cps) UpdateEnrollment(ctx context.Context, params UpdateEnrollmentReque var result UpdateEnrollmentResponse - resp, err := c.Exec(req, &result, params.Enrollment) + resp, err := c.Exec(req, &result, params.EnrollmentRequestBody) if err != nil { return nil, fmt.Errorf("%w: request failed: %s", ErrUpdateEnrollment, err) } diff --git a/pkg/cps/enrollments_test.go b/pkg/cps/enrollments_test.go index 654089e6..451f02fc 100644 --- a/pkg/cps/enrollments_test.go +++ b/pkg/cps/enrollments_test.go @@ -3,10 +3,12 @@ package cps import ( "context" "errors" + "io" "net/http" "net/http/httptest" "testing" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -26,6 +28,10 @@ func TestListEnrollments(t *testing.T) { responseStatus: http.StatusOK, responseBody: ` {"enrollments":[ { + "id": 1, + "productionSlots": [11], + "stagingSlots": [22], + "assignedSlots": [33], "location" : "/cps-api/enrollments/1", "ra" : "third-party", "validationType" : "third-party", @@ -110,6 +116,10 @@ func TestListEnrollments(t *testing.T) { "maxAllowedSanNames" : 100, "maxAllowedWildcardSanNames" : 100 }, { + "id": 2, + "productionSlots": [22], + "stagingSlots": [33], + "assignedSlots": [44], "location" : "/cps-api/enrollments/2", "ra" : "lets-encrypt", "validationType" : "dv", @@ -193,6 +203,10 @@ func TestListEnrollments(t *testing.T) { "maxAllowedWildcardSanNames" : 25 }, { + "id": 3, + "productionSlots": [33], + "stagingSlots": [44], + "assignedSlots": [55], "location" : "/cps-api/enrollments/3", "ra" : "third-party", "validationType" : "third-party", @@ -283,6 +297,10 @@ func TestListEnrollments(t *testing.T) { }, expectedResponse: &ListEnrollmentsResponse{Enrollments: []Enrollment{ { + ID: 1, + ProductionSlots: []int{11}, + StagingSlots: []int{22}, + AssignedSlots: []int{33}, AdminContact: &Contact{ AddressLineOne: "EGL", City: "BLR", @@ -359,6 +377,10 @@ func TestListEnrollments(t *testing.T) { ValidationType: "third-party", }, { + ID: 2, + ProductionSlots: []int{22}, + StagingSlots: []int{33}, + AssignedSlots: []int{44}, AdminContact: &Contact{ Email: "rd3@nomail-akamai.com", FirstName: "R3", @@ -420,6 +442,10 @@ func TestListEnrollments(t *testing.T) { SignatureAlgorithm: "SHA-256", }, { + ID: 3, + ProductionSlots: []int{33}, + StagingSlots: []int{44}, + AssignedSlots: []int{55}, AdminContact: &Contact{ Email: "devqa@tester.com", FirstName: "DevQA", @@ -546,7 +572,7 @@ func TestGetEnrollment(t *testing.T) { responseBody string expectedPath string expectedHeaders map[string]string - expectedResponse *Enrollment + expectedResponse *GetEnrollmentResponse withError func(*testing.T, error) }{ "200 OK": { @@ -554,6 +580,10 @@ func TestGetEnrollment(t *testing.T) { responseStatus: http.StatusOK, responseBody: ` { + "id": 1, + "productionSlots": [11], + "stagingSlots": [22], + "assignedSlots": [33], "location": "/cps-api/enrollments/1", "ra": "third-party", "validationType": "third-party", @@ -656,7 +686,11 @@ func TestGetEnrollment(t *testing.T) { expectedHeaders: map[string]string{ "Accept": "application/vnd.akamai.cps.enrollment.v11+json", }, - expectedResponse: &Enrollment{ + expectedResponse: &GetEnrollmentResponse{ + ID: 1, + ProductionSlots: []int{11}, + StagingSlots: []int{22}, + AssignedSlots: []int{33}, AdminContact: &Contact{ AddressLineOne: "150 Broadway", City: "Cambridge", @@ -852,7 +886,11 @@ func TestGetEnrollment(t *testing.T) { expectedHeaders: map[string]string{ "Accept": "application/vnd.akamai.cps.enrollment.v11+json", }, - expectedResponse: &Enrollment{ + expectedResponse: &GetEnrollmentResponse{ + ID: 1, + ProductionSlots: []int{}, + StagingSlots: []int{}, + AssignedSlots: []int{12345}, AdminContact: &Contact{ AddressLineOne: "150 Broadway", City: "Cambridge", @@ -992,16 +1030,17 @@ func TestGetEnrollment(t *testing.T) { func TestCreateEnrollment(t *testing.T) { tests := map[string]struct { - request CreateEnrollmentRequest - responseStatus int - responseBody string - expectedPath string - expectedResponse *CreateEnrollmentResponse - withError error + request CreateEnrollmentRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *CreateEnrollmentResponse + expectedRequestBody string + withError error }{ "202 accepted": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1033,10 +1072,35 @@ func TestCreateEnrollment(t *testing.T) { Changes: []string{"/cps-api/enrollments/1/changes/10002"}, ID: 1, }, + expectedRequestBody: ` +{ + "adminContact": { + "email": "r1d1@akamai.com" + }, + "certificateType": "third-party", + "changeManagement": false, + "csr": { + "cn": "www.example.com" + }, + "networkConfiguration": { + "quicEnabled": false, + "sniOnly": false + }, + "enableMultiStackedCertificates": false, + "org": { + "name": "Akamai" + }, + "ra": "third-party", + "techContact": { + "email": "r2d2@akamai.com" + }, + "validationType": "third-party" +} +`, }, "202 accepted allow duplicate cn": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1046,6 +1110,7 @@ func TestCreateEnrollment(t *testing.T) { }, NetworkConfiguration: &NetworkConfiguration{}, Org: &Org{Name: "Akamai"}, + OrgID: tools.IntPtr(10), RA: "third-party", TechContact: &Contact{ Email: "r2d2@akamai.com", @@ -1069,10 +1134,36 @@ func TestCreateEnrollment(t *testing.T) { Changes: []string{"/cps-api/enrollments/1/changes/10002"}, ID: 1, }, + expectedRequestBody: ` +{ + "adminContact": { + "email": "r1d1@akamai.com" + }, + "certificateType": "third-party", + "changeManagement": false, + "csr": { + "cn": "www.example.com" + }, + "networkConfiguration": { + "quicEnabled": false, + "sniOnly": false + }, + "enableMultiStackedCertificates": false, + "org": { + "name": "Akamai" + }, + "orgId": 10, + "ra": "third-party", + "techContact": { + "email": "r2d2@akamai.com" + }, + "validationType": "third-party" +} +`, }, "202 accepted dv enrollment": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1105,10 +1196,36 @@ func TestCreateEnrollment(t *testing.T) { Changes: []string{"/cps-api/enrollments/1/changes/10002"}, ID: 1, }, + expectedRequestBody: ` +{ + "adminContact": { + "email": "r1d1@akamai.com" + }, + "certificateType": "san", + "changeManagement": false, + "csr": { + "cn": "www.example.com", + "preferredTrustChain": "intermediate-a" + }, + "networkConfiguration": { + "quicEnabled": false, + "sniOnly": false + }, + "enableMultiStackedCertificates": false, + "org": { + "name": "Akamai" + }, + "ra": "lets-encrypt", + "techContact": { + "email": "r2d2@akamai.com" + }, + "validationType": "dv" +} +`, }, "500 internal server error": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1150,7 +1267,7 @@ func TestCreateEnrollment(t *testing.T) { }, "validation error preferredTrustChain set for non dv enrollment": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1175,7 +1292,7 @@ func TestCreateEnrollment(t *testing.T) { }, "invalid location": { request: CreateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1211,6 +1328,11 @@ func TestCreateEnrollment(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodPost, r.Method) + if test.expectedRequestBody != "" { + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + assert.JSONEq(t, test.expectedRequestBody, string(body)) + } assert.Equal(t, "application/vnd.akamai.cps.enrollment-status.v1+json", r.Header.Get("Accept")) assert.Equal(t, "application/vnd.akamai.cps.enrollment.v11+json; charset=utf-8", r.Header.Get("Content-Type")) w.WriteHeader(test.responseStatus) @@ -1231,17 +1353,18 @@ func TestCreateEnrollment(t *testing.T) { func TestUpdateEnrollment(t *testing.T) { tests := map[string]struct { - request UpdateEnrollmentRequest - responseStatus int - responseBody string - expectedPath string - expectedResponse *UpdateEnrollmentResponse - withError error + request UpdateEnrollmentRequest + responseStatus int + responseBody string + expectedPath string + expectedResponse *UpdateEnrollmentResponse + expectedRequestBody string + withError error }{ "202 accepted": { request: UpdateEnrollmentRequest{ EnrollmentID: 1, - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1251,6 +1374,7 @@ func TestUpdateEnrollment(t *testing.T) { }, NetworkConfiguration: &NetworkConfiguration{}, Org: &Org{Name: "Akamai"}, + OrgID: tools.IntPtr(20), RA: "third-party", TechContact: &Contact{ Email: "r2d2@akamai.com", @@ -1276,11 +1400,37 @@ func TestUpdateEnrollment(t *testing.T) { Changes: []string{"/cps-api/enrollments/1/changes/10002"}, ID: 1, }, + expectedRequestBody: ` +{ + "adminContact": { + "email": "r1d1@akamai.com" + }, + "certificateType": "third-party", + "changeManagement": false, + "csr": { + "cn": "www.example.com" + }, + "networkConfiguration": { + "quicEnabled": false, + "sniOnly": false + }, + "enableMultiStackedCertificates": false, + "org": { + "name": "Akamai" + }, + "orgId": 20, + "ra": "third-party", + "techContact": { + "email": "r2d2@akamai.com" + }, + "validationType": "third-party" +} +`, }, "500 internal server error": { request: UpdateEnrollmentRequest{ EnrollmentID: 1, - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1321,7 +1471,7 @@ func TestUpdateEnrollment(t *testing.T) { }, "validation error preferredTrustChain set for non dv enrollment": { request: UpdateEnrollmentRequest{ - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1346,7 +1496,7 @@ func TestUpdateEnrollment(t *testing.T) { "invalid location URL": { request: UpdateEnrollmentRequest{ EnrollmentID: 1, - Enrollment: Enrollment{ + EnrollmentRequestBody: EnrollmentRequestBody{ AdminContact: &Contact{ Email: "r1d1@akamai.com", }, @@ -1385,6 +1535,11 @@ func TestUpdateEnrollment(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodPut, r.Method) + if test.expectedRequestBody != "" { + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + assert.JSONEq(t, test.expectedRequestBody, string(body)) + } assert.Equal(t, "application/vnd.akamai.cps.enrollment-status.v1+json", r.Header.Get("Accept")) assert.Equal(t, "application/vnd.akamai.cps.enrollment.v11+json; charset=utf-8", r.Header.Get("Content-Type")) w.WriteHeader(test.responseStatus) diff --git a/pkg/cps/errors_test.go b/pkg/cps/errors_test.go index b9d94abc..416df6db 100644 --- a/pkg/cps/errors_test.go +++ b/pkg/cps/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/cps/mocks.go b/pkg/cps/mocks.go index 444f3469..65f32ed3 100644 --- a/pkg/cps/mocks.go +++ b/pkg/cps/mocks.go @@ -24,14 +24,14 @@ func (m *Mock) ListEnrollments(ctx context.Context, r ListEnrollmentsRequest) (* return args.Get(0).(*ListEnrollmentsResponse), args.Error(1) } -func (m *Mock) GetEnrollment(ctx context.Context, r GetEnrollmentRequest) (*Enrollment, error) { +func (m *Mock) GetEnrollment(ctx context.Context, r GetEnrollmentRequest) (*GetEnrollmentResponse, error) { args := m.Called(ctx, r) if args.Error(1) != nil { return nil, args.Error(1) } - return args.Get(0).(*Enrollment), args.Error(1) + return args.Get(0).(*GetEnrollmentResponse), args.Error(1) } func (m *Mock) CreateEnrollment(ctx context.Context, r CreateEnrollmentRequest) (*CreateEnrollmentResponse, error) { diff --git a/pkg/cps/third_party_csr.go b/pkg/cps/third_party_csr.go index 4f1383fa..fba00799 100644 --- a/pkg/cps/third_party_csr.go +++ b/pkg/cps/third_party_csr.go @@ -6,7 +6,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/datastream/ds.go b/pkg/datastream/ds.go index 1e907b3b..e89ceca2 100644 --- a/pkg/datastream/ds.go +++ b/pkg/datastream/ds.go @@ -6,7 +6,7 @@ package datastream import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/datastream/ds_test.go b/pkg/datastream/ds_test.go index 947e906f..495df802 100644 --- a/pkg/datastream/ds_test.go +++ b/pkg/datastream/ds_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/datastream/errors.go b/pkg/datastream/errors.go index 386c99df..97d30292 100644 --- a/pkg/datastream/errors.go +++ b/pkg/datastream/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/datastream/errors_test.go b/pkg/datastream/errors_test.go index b84dc82d..98e99a1f 100644 --- a/pkg/datastream/errors_test.go +++ b/pkg/datastream/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/datastream/properties_test.go b/pkg/datastream/properties_test.go index 171a5989..5542f767 100644 --- a/pkg/datastream/properties_test.go +++ b/pkg/datastream/properties_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/datastream/stream_test.go b/pkg/datastream/stream_test.go index f59b0b70..63d7731a 100644 --- a/pkg/datastream/stream_test.go +++ b/pkg/datastream/stream_test.go @@ -9,7 +9,7 @@ import ( "reflect" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/dns/authorities.go b/pkg/dns/authorities.go index 4799729a..58c2de17 100644 --- a/pkg/dns/authorities.go +++ b/pkg/dns/authorities.go @@ -17,8 +17,6 @@ type ( // // See: https://techdocs.akamai.com/edge-dns/reference/get-data-authorities GetNameServerRecordList(context.Context, string) ([]string, error) - // NewAuthorityResponse instantiate authority response. - NewAuthorityResponse(context.Context, string) *AuthorityResponse } // Contract contains contractID and a list of currently assigned Akamai authoritative nameservers @@ -33,18 +31,8 @@ type ( } ) -func (p *dns) NewAuthorityResponse(ctx context.Context, _ string) *AuthorityResponse { - - logger := p.Log(ctx) - logger.Debug("NewAuthorityResponse") - - authorities := &AuthorityResponse{} - return authorities -} - -func (p *dns) GetAuthorities(ctx context.Context, contractID string) (*AuthorityResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetAuthorities(ctx context.Context, contractID string) (*AuthorityResponse, error) { + logger := d.Log(ctx) logger.Debug("GetAuthorities") if contractID == "" { @@ -58,45 +46,38 @@ func (p *dns) GetAuthorities(ctx context.Context, contractID string) (*Authority return nil, fmt.Errorf("failed to create getauthorities request: %w", err) } - var authNames AuthorityResponse - resp, err := p.Exec(req, &authNames) + var result AuthorityResponse + resp, err := d.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("getauthorities request failed: %w", err) + return nil, fmt.Errorf("GetAuthorities request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &authNames, nil + return &result, nil } -func (p *dns) GetNameServerRecordList(ctx context.Context, contractID string) ([]string, error) { - - logger := p.Log(ctx) +func (d *dns) GetNameServerRecordList(ctx context.Context, contractID string) ([]string, error) { + logger := d.Log(ctx) logger.Debug("GetNameServerRecordList") if contractID == "" { - return nil, fmt.Errorf("%w: GetAuthorities reqs valid contractId", ErrBadRequest) + return nil, fmt.Errorf("%w: GetAuthorities requires valid contractId", ErrBadRequest) } - NSrecords, err := p.GetAuthorities(ctx, contractID) - + NSrecords, err := d.GetAuthorities(ctx, contractID) if err != nil { return nil, err } - var arrLength int - for _, c := range NSrecords.Contracts { - arrLength = len(c.Authorities) - } - - ns := make([]string, 0, arrLength) - + var result []string for _, r := range NSrecords.Contracts { for _, n := range r.Authorities { - ns = append(ns, n) + result = append(result, n) } } - return ns, nil + + return result, nil } diff --git a/pkg/dns/authorities_test.go b/pkg/dns/authorities_test.go index da1012bf..d6ef7596 100644 --- a/pkg/dns/authorities_test.go +++ b/pkg/dns/authorities_test.go @@ -7,12 +7,11 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestDns_GetAuthorities(t *testing.T) { +func TestDNS_GetAuthorities(t *testing.T) { tests := map[string]struct { contractID string responseStatus int @@ -105,7 +104,7 @@ func TestDns_GetAuthorities(t *testing.T) { } } -func TestDns_GetNameServerRecordList(t *testing.T) { +func TestDNS_GetNameServerRecordList(t *testing.T) { tests := map[string]struct { contractID string responseStatus int @@ -163,11 +162,3 @@ func TestDns_GetNameServerRecordList(t *testing.T) { }) } } - -func TestDns_NewAuthorityResponse(t *testing.T) { - client := Client(session.Must(session.New())) - - resp := client.NewAuthorityResponse(context.Background(), "empty") - - assert.NotNil(t, resp) -} diff --git a/pkg/dns/data.go b/pkg/dns/data.go index d3d4c892..61744f85 100644 --- a/pkg/dns/data.go +++ b/pkg/dns/data.go @@ -24,7 +24,7 @@ type ( // ListGroupRequest is a request struct ListGroupRequest struct { - GroupId string + GroupID string } // Group contain the information of the particular group @@ -41,8 +41,8 @@ var ( ErrListGroups = errors.New("list groups") ) -func (p *dns) ListGroups(ctx context.Context, params ListGroupRequest) (*ListGroupResponse, error) { - logger := p.Log(ctx) +func (d *dns) ListGroups(ctx context.Context, params ListGroupRequest) (*ListGroupResponse, error) { + logger := d.Log(ctx) logger.Debug("ListGroups") uri, err := url.Parse("/config-dns/v2/data/groups/") @@ -51,8 +51,8 @@ func (p *dns) ListGroups(ctx context.Context, params ListGroupRequest) (*ListGro } q := uri.Query() - if params.GroupId != "" { - q.Add("gid", params.GroupId) + if params.GroupID != "" { + q.Add("gid", params.GroupID) } uri.RawQuery = q.Encode() @@ -61,15 +61,15 @@ func (p *dns) ListGroups(ctx context.Context, params ListGroupRequest) (*ListGro return nil, fmt.Errorf("failed to list listZoneGroups request: %w", err) } - var groups ListGroupResponse - resp, err := p.Exec(req, &groups) + var result ListGroupResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListZoneGroups request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &groups, nil + return &result, nil } diff --git a/pkg/dns/data_test.go b/pkg/dns/data_test.go index 5793e063..f233e8bf 100644 --- a/pkg/dns/data_test.go +++ b/pkg/dns/data_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/require" ) -func TestDns_ListGroups(t *testing.T) { +func TestDNS_ListGroups(t *testing.T) { tests := map[string]struct { request ListGroupRequest responseStatus int @@ -22,7 +22,7 @@ func TestDns_ListGroups(t *testing.T) { }{ "200 OK, when optional query parameter provided": { request: ListGroupRequest{ - GroupId: "9012", + GroupID: "9012", }, responseStatus: http.StatusOK, responseBody: ` diff --git a/pkg/dns/dns.go b/pkg/dns/dns.go index 47202ab7..7f3b3316 100644 --- a/pkg/dns/dns.go +++ b/pkg/dns/dns.go @@ -4,15 +4,9 @@ package dns import ( - "errors" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" -) - -var ( - // ErrStructValidation is returned returned when given struct validation failed - ErrStructValidation = errors.New("struct validation") + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) type ( @@ -20,7 +14,7 @@ type ( DNS interface { Authorities Data - RecordSets + Recordsets Records TSIGKeys Zones @@ -39,18 +33,17 @@ type ( // Client returns a new dns Client instance with the specified controller func Client(sess session.Session, opts ...Option) DNS { - p := &dns{ + d := &dns{ Session: sess, } for _, opt := range opts { - opt(p) + opt(d) } - return p + return d } // Exec overrides the session.Exec to add dns options -func (p *dns) Exec(r *http.Request, out interface{}, in ...interface{}) (*http.Response, error) { - - return p.Session.Exec(r, out, in...) +func (d *dns) Exec(r *http.Request, out interface{}, in ...interface{}) (*http.Response, error) { + return d.Session.Exec(r, out, in...) } diff --git a/pkg/dns/dns_test.go b/pkg/dns/dns_test.go index 84e520c9..f839d33f 100644 --- a/pkg/dns/dns_test.go +++ b/pkg/dns/dns_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/dns/errors.go b/pkg/dns/errors.go index 042d19b4..a82ebf23 100644 --- a/pkg/dns/errors.go +++ b/pkg/dns/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) var ( @@ -29,14 +29,14 @@ type ( ) // Error parses an error from the response -func (p *dns) Error(r *http.Response) error { +func (d *dns) Error(r *http.Response) error { var e Error var body []byte body, err := ioutil.ReadAll(r.Body) if err != nil { - p.Log(r.Request.Context()).Errorf("reading error response body: %s", err) + d.Log(r.Request.Context()).Errorf("reading error response body: %s", err) e.StatusCode = r.StatusCode e.Title = fmt.Sprintf("Failed to read error body") e.Detail = err.Error() @@ -44,7 +44,7 @@ func (p *dns) Error(r *http.Response) error { } if err := json.Unmarshal(body, &e); err != nil { - p.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) + d.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) e.Title = fmt.Sprintf("Failed to unmarshal error body. DNS API failed. Check details for more information.") e.Detail = errs.UnescapeContent(string(body)) } diff --git a/pkg/dns/errors_test.go b/pkg/dns/errors_test.go index 34fd599c..d3c41c8d 100644 --- a/pkg/dns/errors_test.go +++ b/pkg/dns/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" diff --git a/pkg/dns/mocks.go b/pkg/dns/mocks.go index 1c32338c..cd614228 100644 --- a/pkg/dns/mocks.go +++ b/pkg/dns/mocks.go @@ -4,7 +4,6 @@ package dns import ( "context" - "net" "github.com/stretchr/testify/mock" ) @@ -31,46 +30,6 @@ func (d *Mock) ListZones(ctx context.Context, query ...ZoneListQueryArgs) (*Zone return args.Get(0).(*ZoneListResponse), args.Error(1) } -func (d *Mock) NewZone(ctx context.Context, params ZoneCreate) *ZoneCreate { - args := d.Called(ctx, params) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*ZoneCreate) -} - -func (d *Mock) NewZoneResponse(ctx context.Context, param string) *ZoneResponse { - args := d.Called(ctx, param) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*ZoneResponse) -} - -func (d *Mock) NewChangeListResponse(ctx context.Context, param string) *ChangeListResponse { - args := d.Called(ctx, param) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*ChangeListResponse) -} - -func (d *Mock) NewZoneQueryString(ctx context.Context, param1 string, _ string) *ZoneQueryString { - args := d.Called(ctx, param1, param1) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*ZoneQueryString) -} - func (d *Mock) GetZone(ctx context.Context, name string) (*ZoneResponse, error) { args := d.Called(ctx, name) @@ -133,12 +92,6 @@ func (d *Mock) DeleteZone(ctx context.Context, param1 *ZoneCreate, param2 ZoneQu return args.Error(0) } -func (d *Mock) ValidateZone(ctx context.Context, param1 *ZoneCreate) error { - args := d.Called(ctx, param1) - - return args.Error(0) -} - func (d *Mock) GetZoneNames(ctx context.Context, param string) (*ZoneNamesResponse, error) { args := d.Called(ctx, param) @@ -157,23 +110,7 @@ func (d *Mock) GetZoneNameTypes(ctx context.Context, param1 string, param2 strin return args.Get(0).(*ZoneNameTypesResponse), args.Error(1) } -func (d *Mock) NewTsigKey(ctx context.Context, param string) *TSIGKey { - args := d.Called(ctx, param) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(*TSIGKey) -} - -func (d *Mock) NewTsigQueryString(ctx context.Context) *TSIGQueryString { - args := d.Called(ctx) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(*TSIGQueryString) -} - -func (d *Mock) ListTsigKeys(ctx context.Context, param *TSIGQueryString) (*TSIGReportResponse, error) { +func (d *Mock) ListTSIGKeys(ctx context.Context, param *TSIGQueryString) (*TSIGReportResponse, error) { args := d.Called(ctx, param) if args.Get(0) == nil { @@ -183,7 +120,7 @@ func (d *Mock) ListTsigKeys(ctx context.Context, param *TSIGQueryString) (*TSIGR return args.Get(0).(*TSIGReportResponse), args.Error(1) } -func (d *Mock) GetTsigKeyZones(ctx context.Context, param *TSIGKey) (*ZoneNameListResponse, error) { +func (d *Mock) GetTSIGKeyZones(ctx context.Context, param *TSIGKey) (*ZoneNameListResponse, error) { args := d.Called(ctx, param) if args.Get(0) == nil { @@ -193,7 +130,7 @@ func (d *Mock) GetTsigKeyZones(ctx context.Context, param *TSIGKey) (*ZoneNameLi return args.Get(0).(*ZoneNameListResponse), args.Error(1) } -func (d *Mock) GetTsigKeyAliases(ctx context.Context, param string) (*ZoneNameListResponse, error) { +func (d *Mock) GetTSIGKeyAliases(ctx context.Context, param string) (*ZoneNameListResponse, error) { args := d.Called(ctx, param) if args.Get(0) == nil { @@ -203,13 +140,13 @@ func (d *Mock) GetTsigKeyAliases(ctx context.Context, param string) (*ZoneNameLi return args.Get(0).(*ZoneNameListResponse), args.Error(1) } -func (d *Mock) TsigKeyBulkUpdate(ctx context.Context, param1 *TSIGKeyBulkPost) error { +func (d *Mock) TSIGKeyBulkUpdate(ctx context.Context, param1 *TSIGKeyBulkPost) error { args := d.Called(ctx, param1) return args.Error(0) } -func (d *Mock) GetTsigKey(ctx context.Context, param string) (*TSIGKeyResponse, error) { +func (d *Mock) GetTSIGKey(ctx context.Context, param string) (*TSIGKeyResponse, error) { args := d.Called(ctx, param) if args.Get(0) == nil { @@ -219,13 +156,13 @@ func (d *Mock) GetTsigKey(ctx context.Context, param string) (*TSIGKeyResponse, return args.Get(0).(*TSIGKeyResponse), args.Error(1) } -func (d *Mock) DeleteTsigKey(ctx context.Context, param1 string) error { +func (d *Mock) DeleteTSIGKey(ctx context.Context, param1 string) error { args := d.Called(ctx, param1) return args.Error(0) } -func (d *Mock) UpdateTsigKey(ctx context.Context, param1 *TSIGKey, param2 string) error { +func (d *Mock) UpdateTSIGKey(ctx context.Context, param1 *TSIGKey, param2 string) error { args := d.Called(ctx, param1, param2) return args.Error(0) @@ -251,30 +188,6 @@ func (d *Mock) GetNameServerRecordList(ctx context.Context, param string) ([]str return args.Get(0).([]string), args.Error(1) } -func (d *Mock) NewAuthorityResponse(ctx context.Context, param string) *AuthorityResponse { - args := d.Called(ctx, param) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(*AuthorityResponse) -} - -func (d *Mock) RecordToMap(ctx context.Context, param *RecordBody) map[string]interface{} { - args := d.Called(ctx, param) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(map[string]interface{}) -} - -func (d *Mock) NewRecordBody(ctx context.Context, param RecordBody) *RecordBody { - args := d.Called(ctx, param) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(*RecordBody) -} - func (d *Mock) GetRecordList(ctx context.Context, param string, param2 string, param3 string) (*RecordSetResponse, error) { args := d.Called(ctx, param, param2, param3) @@ -357,27 +270,7 @@ func (d *Mock) UpdateRecord(ctx context.Context, param *RecordBody, param2 strin return args.Error(0) } -func (d *Mock) FullIPv6(ctx context.Context, param1 net.IP) string { - args := d.Called(ctx, param1) - - return args.String(0) -} - -func (d *Mock) PadCoordinates(ctx context.Context, param1 string) string { - args := d.Called(ctx, param1) - - return args.String(0) -} - -func (d *Mock) NewRecordSetResponse(ctx context.Context, param string) *RecordSetResponse { - args := d.Called(ctx, param) - if args.Get(0) == nil { - return nil - } - return args.Get(0).(*RecordSetResponse) -} - -func (d *Mock) GetRecordsets(ctx context.Context, param string, param2 ...RecordsetQueryArgs) (*RecordSetResponse, error) { +func (d *Mock) GetRecordSets(ctx context.Context, param string, param2 ...RecordSetQueryArgs) (*RecordSetResponse, error) { var args mock.Arguments if len(param2) > 0 { @@ -393,7 +286,7 @@ func (d *Mock) GetRecordsets(ctx context.Context, param string, param2 ...Record return args.Get(0).(*RecordSetResponse), args.Error(1) } -func (d *Mock) CreateRecordsets(ctx context.Context, param *Recordsets, param2 string, param3 ...bool) error { +func (d *Mock) CreateRecordSets(ctx context.Context, param *RecordSets, param2 string, param3 ...bool) error { var args mock.Arguments if len(param3) > 0 { @@ -405,7 +298,7 @@ func (d *Mock) CreateRecordsets(ctx context.Context, param *Recordsets, param2 s return args.Error(0) } -func (d *Mock) UpdateRecordsets(ctx context.Context, param *Recordsets, param2 string, param3 ...bool) error { +func (d *Mock) UpdateRecordSets(ctx context.Context, param *RecordSets, param2 string, param3 ...bool) error { var args mock.Arguments if len(param3) > 0 { diff --git a/pkg/dns/record.go b/pkg/dns/record.go index 4492a911..cb72441f 100644 --- a/pkg/dns/record.go +++ b/pkg/dns/record.go @@ -5,16 +5,11 @@ import ( "fmt" "net/http" - "net" "sync" ) // Records contains operations available on a Record resource. type Records interface { - // RecordToMap returns a map containing record content. - RecordToMap(context.Context, *RecordBody) map[string]interface{} - // NewRecordBody returns bare bones tsig key struct. - NewRecordBody(context.Context, RecordBody) *RecordBody // GetRecordList retrieves recordset list based on type. // // See: https://techdocs.akamai.com/edge-dns/reference/get-zones-zone-recordsets @@ -41,20 +36,15 @@ type Records interface { // // See: https://techdocs.akamai.com/edge-dns/reference/put-zones-zone-names-name-types-type UpdateRecord(context.Context, *RecordBody, string, ...bool) error - // FullIPv6 is utility method to convert IP to string. - FullIPv6(context.Context, net.IP) string - // PadCoordinates is utility method to convert IP to normalize coordinates. - PadCoordinates(context.Context, string) string } // RecordBody contains request body for dns record type RecordBody struct { - Name string `json:"name,omitempty"` - RecordType string `json:"type,omitempty"` - TTL int `json:"ttl,omitempty"` - // Active field no longer used in v2 - Active bool `json:"active,omitempty"` - Target []string `json:"rdata,omitempty"` + Name string `json:"name,omitempty"` + RecordType string `json:"type,omitempty"` + TTL int `json:"ttl,omitempty"` + Active bool `json:"active,omitempty"` + Target []string `json:"rdata,omitempty"` } var ( @@ -63,68 +53,36 @@ var ( // Validate validates RecordBody func (rec *RecordBody) Validate() error { - if len(rec.Name) < 1 { - return fmt.Errorf("Record body is missing Name") + return fmt.Errorf("RecordBody is missing Name") } if len(rec.RecordType) < 1 { - return fmt.Errorf("Record body is missing RecordType") + return fmt.Errorf("RecordBody is missing RecordType") } if rec.TTL == 0 { - return fmt.Errorf("Record body is missing TTL") + return fmt.Errorf("RecordBody is missing TTL") } if rec.Target == nil || len(rec.Target) < 1 { - return fmt.Errorf("Record body is missing Target") + return fmt.Errorf("RecordBody is missing Target") } return nil } -func (p *dns) RecordToMap(ctx context.Context, record *RecordBody) map[string]interface{} { - - logger := p.Log(ctx) - logger.Debug("RecordToMap") - - if err := record.Validate(); err != nil { - logger.Errorf("Record to map failed. %w", err) - return nil - } - - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "recordtype": record.RecordType, - // active no longer used - "active": record.Active, - "target": record.Target, - } -} - -func (p *dns) NewRecordBody(ctx context.Context, params RecordBody) *RecordBody { - - logger := p.Log(ctx) - logger.Debug("NewRecordBody") - - recordbody := &RecordBody{Name: params.Name} - return recordbody -} - // Eval option lock arg passed into writable endpoints. Default is true, e.g. lock func localLock(lockArg []bool) bool { - for _, lock := range lockArg { // should only be one entry return lock } return true - } -func (p *dns) CreateRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { +func (d *dns) CreateRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which - // is required to be incremented for every subsequent update to a zone + // is required to be incremented for every subsequent update to a zone, // so we have to save just one request at a time to ensure this is always // incremented properly @@ -133,39 +91,38 @@ func (p *dns) CreateRecord(ctx context.Context, record *RecordBody, zone string, defer zoneRecordWriteLock.Unlock() } - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("CreateRecord") logger.Debugf("DNS Lib Create Record: [%v]", record) if err := record.Validate(); err != nil { logger.Errorf("Record content not valid: %w", err) - return fmt.Errorf("Record content not valid. [%w]", err) + return fmt.Errorf("CreateRecord content not valid. [%w]", err) } - reqbody, err := convertStructToReqBody(record) + reqBody, err := convertStructToReqBody(record) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } - var rec RecordBody postURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/%s", zone, record.Name, record.RecordType) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return fmt.Errorf("failed to create CreateRecord request: %w", err) } - resp, err := p.Exec(req, &rec) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("CreateRecord request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) UpdateRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { +func (d *dns) UpdateRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -177,39 +134,38 @@ func (p *dns) UpdateRecord(ctx context.Context, record *RecordBody, zone string, defer zoneRecordWriteLock.Unlock() } - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("UpdateRecord") logger.Debugf("DNS Lib Update Record: [%v]", record) if err := record.Validate(); err != nil { logger.Errorf("Record content not valid: %s", err.Error()) - return fmt.Errorf("Record content not valid. [%w]", err) + return fmt.Errorf("UpdateRecord content not valid. [%w]", err) } - reqbody, err := convertStructToReqBody(record) + reqBody, err := convertStructToReqBody(record) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } - var rec RecordBody putURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/%s", zone, record.Name, record.RecordType) - req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqBody) if err != nil { return fmt.Errorf("failed to create UpdateRecord request: %w", err) } - resp, err := p.Exec(req, &rec) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("UpdateRecord request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) DeleteRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { +func (d *dns) DeleteRecord(ctx context.Context, record *RecordBody, zone string, recLock ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -221,28 +177,27 @@ func (p *dns) DeleteRecord(ctx context.Context, record *RecordBody, zone string, defer zoneRecordWriteLock.Unlock() } - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("DeleteRecord") if err := record.Validate(); err != nil { logger.Errorf("Record content not valid: %w", err) - return fmt.Errorf("Record content not valid. [%w]", err) + return fmt.Errorf("DeleteRecord content not valid. [%w]", err) } - //var mtbody string deleteURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/%s", zone, record.Name, record.RecordType) req, err := http.NewRequestWithContext(ctx, http.MethodDelete, deleteURL, nil) if err != nil { return fmt.Errorf("failed to create DeleteRecord request: %w", err) } - resp, err := p.Exec(req, nil) //, &mtbody) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("DeleteRecord request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil diff --git a/pkg/dns/record_lookup.go b/pkg/dns/record_lookup.go index f833fc79..fdc15cee 100644 --- a/pkg/dns/record_lookup.go +++ b/pkg/dns/record_lookup.go @@ -11,10 +11,7 @@ import ( "strings" ) -func (p *dns) FullIPv6(ctx context.Context, ip net.IP) string { - - logger := p.Log(ctx) - logger.Debug("FullIPv6") +func fullIPv6(ip net.IP) string { dst := make([]byte, hex.EncodedLen(len(ip))) _ = hex.Encode(dst, ip) @@ -28,21 +25,17 @@ func (p *dns) FullIPv6(ctx context.Context, ip net.IP) string { string(dst[28:]) } -func padvalue(str string) string { - vstr := strings.Replace(str, "m", "", -1) - vfloat, err := strconv.ParseFloat(vstr, 32) +func padValue(str string) string { + newStr := strings.Replace(str, "m", "", -1) + float, err := strconv.ParseFloat(newStr, 32) if err != nil { return "FAIL" } - return fmt.Sprintf("%.2f", vfloat) + return fmt.Sprintf("%.2f", float) } -func (p *dns) PadCoordinates(ctx context.Context, str string) string { - - logger := p.Log(ctx) - logger.Debug("PadCoordinates") - +func padCoordinates(str string) string { s := strings.Split(str, " ") if len(s) < 12 { return "" @@ -50,233 +43,219 @@ func (p *dns) PadCoordinates(ctx context.Context, str string) string { latd, latm, lats, latDir, longd, longm, longs, longDir, altitude, size, horizPrecision, vertPrecision := s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], s[8], s[9], s[10], s[11] - return latd + " " + latm + " " + lats + " " + latDir + " " + longd + " " + longm + " " + longs + " " + longDir + " " + padvalue(altitude) + "m " + padvalue(size) + "m " + padvalue(horizPrecision) + "m " + padvalue(vertPrecision) + "m" - + return latd + " " + latm + " " + lats + " " + latDir + " " + longd + " " + longm + " " + longs + " " + longDir + " " + padValue(altitude) + "m " + padValue(size) + "m " + padValue(horizPrecision) + "m " + padValue(vertPrecision) + "m" } -func (p *dns) GetRecord(ctx context.Context, zone string, name string, recordType string) (*RecordBody, error) { - - logger := p.Log(ctx) +func (d *dns) GetRecord(ctx context.Context, zone, name, recordType string) (*RecordBody, error) { + logger := d.Log(ctx) logger.Debug("GetRecord") - var rec RecordBody getURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types/%s", zone, name, recordType) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetRecord request: %w", err) } - resp, err := p.Exec(req, &rec) + var result RecordBody + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetRecord request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &rec, nil + return &result, nil } -func (p *dns) GetRecordList(ctx context.Context, zone string, _ string, recordType string) (*RecordSetResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetRecordList(ctx context.Context, zone, _, recordType string) (*RecordSetResponse, error) { + logger := d.Log(ctx) logger.Debug("GetRecordList") - var records RecordSetResponse getURL := fmt.Sprintf("/config-dns/v2/zones/%s/recordsets?types=%s&showAll=true", zone, recordType) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetRecordList request: %w", err) } - resp, err := p.Exec(req, &records) + var result RecordSetResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetRecordList request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &records, nil + return &result, nil } -func (p *dns) GetRdata(ctx context.Context, zone string, name string, recordType string) ([]string, error) { - - logger := p.Log(ctx) - logger.Debug("GetRdata") +func (d *dns) GetRdata(ctx context.Context, zone, name, recordType string) ([]string, error) { + logger := d.Log(ctx) + logger.Debug("GetrData") - records, err := p.GetRecordList(ctx, zone, name, recordType) + records, err := d.GetRecordList(ctx, zone, name, recordType) if err != nil { return nil, err } - var arrLength int - for _, c := range records.Recordsets { - if c.Name == name { - arrLength = len(c.Rdata) - } - } - - rdata := make([]string, 0, arrLength) - - for _, r := range records.Recordsets { + var rData []string + for _, r := range records.RecordSets { if r.Name == name { for _, i := range r.Rdata { str := i if recordType == "AAAA" { addr := net.ParseIP(str) - result := p.FullIPv6(ctx, addr) + result := fullIPv6(addr) str = result } else if recordType == "LOC" { - str = p.PadCoordinates(ctx, str) + str = padCoordinates(str) } - rdata = append(rdata, str) + rData = append(rData, str) } } } - return rdata, nil + return rData, nil } -func (p *dns) ProcessRdata(ctx context.Context, rdata []string, rtype string) []string { - - logger := p.Log(ctx) - logger.Debug("ProcessRdata") +func (d *dns) ProcessRdata(ctx context.Context, rData []string, rType string) []string { + logger := d.Log(ctx) + logger.Debug("ProcessrData") - newrdata := make([]string, 0, len(rdata)) - for _, i := range rdata { + var newRData []string + for _, i := range rData { str := i - if rtype == "AAAA" { + if rType == "AAAA" { addr := net.ParseIP(str) - result := p.FullIPv6(ctx, addr) + result := fullIPv6(addr) str = result - } else if rtype == "LOC" { - str = p.PadCoordinates(ctx, str) + } else if rType == "LOC" { + str = padCoordinates(str) } - newrdata = append(newrdata, str) + newRData = append(newRData, str) } - return newrdata + return newRData } -func (p *dns) ParseRData(ctx context.Context, rtype string, rdata []string) map[string]interface{} { - - logger := p.Log(ctx) - logger.Debug("ParseRData") +func (d *dns) ParseRData(ctx context.Context, rType string, rData []string) map[string]interface{} { + logger := d.Log(ctx) + logger.Debug("ParserData") fieldMap := make(map[string]interface{}, 0) - if len(rdata) == 0 { + if len(rData) == 0 { return fieldMap } - newrdata := make([]string, 0, len(rdata)) - fieldMap["target"] = newrdata + newRData := make([]string, 0, len(rData)) + fieldMap["target"] = newRData - switch rtype { + switch rType { case "AFSDB": - resolveAFSDBType(rdata, newrdata, fieldMap) + resolveAFSDBType(rData, newRData, fieldMap) case "DNSKEY": - resolveDNSKEYType(rdata, fieldMap) + resolveDNSKEYType(rData, fieldMap) case "DS": - resolveDSType(rdata, fieldMap) + resolveDSType(rData, fieldMap) case "HINFO": - resolveHINFOType(rdata, fieldMap) + resolveHINFOType(rData, fieldMap) /* // too many variations to calculate pri and increment case "MX": - sort.Strings(rdata) - parts := strings.Split(rdata[0], " ") + sort.Strings(rData) + parts := strings.Split(rData[0], " ") fieldMap["priority"], _ = strconv.Atoi(parts[0]) - if len(rdata) > 1 { - parts = strings.Split(rdata[1], " ") + if len(rData) > 1 { + parts = strings.Split(rData[1], " ") tpri, _ := strconv.Atoi(parts[0]) fieldMap["priority_increment"] = tpri - fieldMap["priority"].(int) } - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") - newrdata = append(newrdata, parts[1]) + for _, rContent := range rData { + parts := strings.Split(rContent, " ") + newrData = append(newrData, parts[1]) } - fieldMap["target"] = newrdata + fieldMap["target"] = newrData */ case "NAPTR": - resolveNAPTRType(rdata, fieldMap) + resolveNAPTRType(rData, fieldMap) case "NSEC3": - resolveNSEC3Type(rdata, fieldMap) + resolveNSEC3Type(rData, fieldMap) case "NSEC3PARAM": - resolveNSEC3PARAMType(rdata, fieldMap) + resolveNSEC3PARAMType(rData, fieldMap) case "RP": - resolveRPType(rdata, fieldMap) + resolveRPType(rData, fieldMap) case "RRSIG": - resolveRRSIGType(rdata, fieldMap) + resolveRRSIGType(rData, fieldMap) case "SRV": - resolveSRVType(rdata, newrdata, fieldMap) + resolveSRVType(rData, newRData, fieldMap) case "SSHFP": - resolveSSHFPType(rdata, fieldMap) + resolveSSHFPType(rData, fieldMap) case "SOA": - resolveSOAType(rdata, fieldMap) + resolveSOAType(rData, fieldMap) case "AKAMAITLC": - resolveAKAMAITLCType(rdata, fieldMap) + resolveAKAMAITLCType(rData, fieldMap) case "SPF": - resolveSPFType(rdata, newrdata, fieldMap) + resolveSPFType(rData, newRData, fieldMap) case "TXT": - resolveTXTType(rdata, newrdata, fieldMap) + resolveTXTType(rData, newRData, fieldMap) case "AAAA": - resolveAAAAType(ctx, p, rdata, newrdata, fieldMap) + resolveAAAAType(rData, newRData, fieldMap) case "LOC": - resolveLOCType(ctx, p, rdata, newrdata, fieldMap) + resolveLOCType(rData, newRData, fieldMap) case "CERT": - resolveCERTType(rdata, fieldMap) + resolveCERTType(rData, fieldMap) case "TLSA": - resolveTLSAType(rdata, fieldMap) + resolveTLSAType(rData, fieldMap) case "SVCB": - resolveSVCBType(rdata, fieldMap) + resolveSVCBType(rData, fieldMap) case "HTTPS": - resolveHTTPSType(rdata, fieldMap) + resolveHTTPSType(rData, fieldMap) default: - for _, rcontent := range rdata { - newrdata = append(newrdata, rcontent) + for _, rContent := range rData { + newRData = append(newRData, rContent) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } return fieldMap } -func resolveAFSDBType(rdata, newrdata []string, fieldMap map[string]interface{}) { - parts := strings.Split(rdata[0], " ") +func resolveAFSDBType(rData, newRData []string, fieldMap map[string]interface{}) { + parts := strings.Split(rData[0], " ") fieldMap["subtype"], _ = strconv.Atoi(parts[0]) - for _, rcontent := range rdata { - parts = strings.Split(rcontent, " ") - newrdata = append(newrdata, parts[1]) + for _, rContent := range rData { + parts = strings.Split(rContent, " ") + newRData = append(newRData, parts[1]) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveDNSKEYType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveDNSKEYType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["flags"], _ = strconv.Atoi(parts[0]) fieldMap["protocol"], _ = strconv.Atoi(parts[1]) fieldMap["algorithm"], _ = strconv.Atoi(parts[2]) @@ -293,9 +272,9 @@ func resolveDNSKEYType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveSVCBType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.SplitN(rcontent, " ", 3) +func resolveSVCBType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.SplitN(rContent, " ", 3) // has to be at least two fields. if len(parts) < 2 { break @@ -309,9 +288,9 @@ func resolveSVCBType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveDSType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveDSType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["keytag"], _ = strconv.Atoi(parts[0]) fieldMap["digest_type"], _ = strconv.Atoi(parts[2]) fieldMap["algorithm"], _ = strconv.Atoi(parts[1]) @@ -328,18 +307,18 @@ func resolveDSType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveHINFOType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveHINFOType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["hardware"] = parts[0] fieldMap["software"] = parts[1] break } } -func resolveNAPTRType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveNAPTRType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["order"], _ = strconv.Atoi(parts[0]) fieldMap["preference"], _ = strconv.Atoi(parts[1]) fieldMap["flagsnaptr"] = parts[2] @@ -350,9 +329,9 @@ func resolveNAPTRType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveNSEC3Type(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveNSEC3Type(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["flags"], _ = strconv.Atoi(parts[1]) fieldMap["algorithm"], _ = strconv.Atoi(parts[0]) fieldMap["iterations"], _ = strconv.Atoi(parts[2]) @@ -363,9 +342,9 @@ func resolveNSEC3Type(rdata []string, fieldMap map[string]interface{}) { } } -func resolveNSEC3PARAMType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveNSEC3PARAMType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["flags"], _ = strconv.Atoi(parts[1]) fieldMap["algorithm"], _ = strconv.Atoi(parts[0]) fieldMap["iterations"], _ = strconv.Atoi(parts[2]) @@ -374,18 +353,18 @@ func resolveNSEC3PARAMType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveRPType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveRPType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["mailbox"] = parts[0] fieldMap["txt"] = parts[1] break } } -func resolveRRSIGType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveRRSIGType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["type_covered"] = parts[0] fieldMap["algorithm"], _ = strconv.Atoi(parts[1]) fieldMap["labels"], _ = strconv.Atoi(parts[2]) @@ -407,23 +386,23 @@ func resolveRRSIGType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveSRVType(rdata, newrdata []string, fieldMap map[string]interface{}) { +func resolveSRVType(rData, newRData []string, fieldMap map[string]interface{}) { // pull out some fields - parts := strings.Split(rdata[0], " ") + parts := strings.Split(rData[0], " ") fieldMap["priority"], _ = strconv.Atoi(parts[0]) fieldMap["weight"], _ = strconv.Atoi(parts[1]) fieldMap["port"], _ = strconv.Atoi(parts[2]) // populate target - for _, rcontent := range rdata { - parts = strings.Split(rcontent, " ") - newrdata = append(newrdata, parts[3]) + for _, rContent := range rData { + parts = strings.Split(rContent, " ") + newRData = append(newRData, parts[3]) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveSSHFPType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveSSHFPType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["algorithm"], _ = strconv.Atoi(parts[0]) fieldMap["fingerprint_type"], _ = strconv.Atoi(parts[1]) fieldMap["fingerprint"] = parts[2] @@ -431,9 +410,9 @@ func resolveSSHFPType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveSOAType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveSOAType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["name_server"] = parts[0] fieldMap["email_address"] = parts[1] fieldMap["serial"], _ = strconv.Atoi(parts[2]) @@ -445,49 +424,49 @@ func resolveSOAType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveAKAMAITLCType(rdata []string, fieldMap map[string]interface{}) { - parts := strings.Split(rdata[0], " ") +func resolveAKAMAITLCType(rData []string, fieldMap map[string]interface{}) { + parts := strings.Split(rData[0], " ") fieldMap["answer_type"] = parts[0] fieldMap["dns_name"] = parts[1] } -func resolveSPFType(rdata, newrdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - newrdata = append(newrdata, rcontent) +func resolveSPFType(rData, newRData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + newRData = append(newRData, rContent) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveTXTType(rdata, newrdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - newrdata = append(newrdata, rcontent) +func resolveTXTType(rData, newRData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + newRData = append(newRData, rContent) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveAAAAType(ctx context.Context, p *dns, rdata, newrdata []string, fieldMap map[string]interface{}) { - for _, i := range rdata { +func resolveAAAAType(rData, newRData []string, fieldMap map[string]interface{}) { + for _, i := range rData { str := i addr := net.ParseIP(str) - result := p.FullIPv6(ctx, addr) + result := fullIPv6(addr) str = result - newrdata = append(newrdata, str) + newRData = append(newRData, str) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveLOCType(ctx context.Context, p *dns, rdata, newrdata []string, fieldMap map[string]interface{}) { - for _, i := range rdata { +func resolveLOCType(rData, newRData []string, fieldMap map[string]interface{}) { + for _, i := range rData { str := i - str = p.PadCoordinates(ctx, str) - newrdata = append(newrdata, str) + str = padCoordinates(str) + newRData = append(newRData, str) } - fieldMap["target"] = newrdata + fieldMap["target"] = newRData } -func resolveCERTType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveCERTType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") val, err := strconv.Atoi(parts[0]) if err == nil { fieldMap["type_value"] = val @@ -501,9 +480,9 @@ func resolveCERTType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveTLSAType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.Split(rcontent, " ") +func resolveTLSAType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.Split(rContent, " ") fieldMap["usage"], _ = strconv.Atoi(parts[0]) fieldMap["selector"], _ = strconv.Atoi(parts[1]) fieldMap["match_type"], _ = strconv.Atoi(parts[2]) @@ -512,9 +491,9 @@ func resolveTLSAType(rdata []string, fieldMap map[string]interface{}) { } } -func resolveHTTPSType(rdata []string, fieldMap map[string]interface{}) { - for _, rcontent := range rdata { - parts := strings.SplitN(rcontent, " ", 3) +func resolveHTTPSType(rData []string, fieldMap map[string]interface{}) { + for _, rContent := range rData { + parts := strings.SplitN(rContent, " ", 3) // has to be at least two fields. if len(parts) < 2 { break diff --git a/pkg/dns/record_lookup_test.go b/pkg/dns/record_lookup_test.go index a08aa85e..8d939b58 100644 --- a/pkg/dns/record_lookup_test.go +++ b/pkg/dns/record_lookup_test.go @@ -7,12 +7,12 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestDns_GetRecord(t *testing.T) { +func TestDNS_GetRecord(t *testing.T) { tests := map[string]struct { zone string name string @@ -90,7 +90,7 @@ func TestDns_GetRecord(t *testing.T) { } } -func TestDns_GetRecordList(t *testing.T) { +func TestDNS_GetRecordList(t *testing.T) { tests := map[string]struct { zone string name string @@ -130,14 +130,14 @@ func TestDns_GetRecordList(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/example.com/recordsets?showAll=true&types=A", expectedResponse: &RecordSetResponse{ - Metadata: MetadataH{ + Metadata: Metadata{ LastPage: 0, Page: 1, PageSize: 25, ShowAll: false, TotalElements: 2, }, - Recordsets: []Recordset{ + RecordSets: []RecordSet{ { Name: "www.example.com", Type: "A", @@ -189,7 +189,7 @@ func TestDns_GetRecordList(t *testing.T) { } } -func TestDns_GetRdata(t *testing.T) { +func TestDNS_GetRdata(t *testing.T) { tests := map[string]struct { zone string name string @@ -302,7 +302,7 @@ func TestDns_GetRdata(t *testing.T) { } } -func TestDns_TestRdata(t *testing.T) { +func TestDNS_TestRdata(t *testing.T) { client := Client(session.Must(session.New())) out := client.ProcessRdata(context.Background(), []string{"2001:0db8:85a3:0000:0000:8a2e:0370:7334"}, "AAAA") @@ -314,7 +314,7 @@ func TestDns_TestRdata(t *testing.T) { assert.Equal(t, []string{"52 22 23.000 N 4 53 32.000 E -2.00m 0.00m 10000.00m 10.00m"}, out) } -func TestDns_ParseRData(t *testing.T) { +func TestDNS_ParseRData(t *testing.T) { client := Client(session.Must(session.New())) tests := map[string]struct { diff --git a/pkg/dns/record_test.go b/pkg/dns/record_test.go index 41324044..e3d9a4a9 100644 --- a/pkg/dns/record_test.go +++ b/pkg/dns/record_test.go @@ -7,12 +7,11 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestDns_CreateRecord(t *testing.T) { +func TestDNS_CreateRecord(t *testing.T) { tests := map[string]struct { body RecordBody responseStatus int @@ -86,7 +85,7 @@ func TestDns_CreateRecord(t *testing.T) { } } -func TestDns_UpdateRecord(t *testing.T) { +func TestDNS_UpdateRecord(t *testing.T) { tests := map[string]struct { body RecordBody responseStatus int @@ -160,7 +159,7 @@ func TestDns_UpdateRecord(t *testing.T) { } } -func TestDns_DeleteRecord(t *testing.T) { +func TestDNS_DeleteRecord(t *testing.T) { tests := map[string]struct { body RecordBody responseStatus int @@ -224,42 +223,3 @@ func TestDns_DeleteRecord(t *testing.T) { }) } } - -func TestDns_RecordToMap(t *testing.T) { - client := Client(session.Must(session.New())) - - data := client.RecordToMap(context.Background(), &RecordBody{ - Name: "www.example.com", - RecordType: "A", - TTL: 300, - Target: []string{"10.0.0.2", "10.0.0.3"}, - }) - - assert.Equal(t, map[string]interface{}{ - "active": false, - "name": "www.example.com", - "recordtype": "A", - "target": []string{"10.0.0.2", "10.0.0.3"}, - "ttl": 300, - }, data) - - data = client.RecordToMap(context.Background(), &RecordBody{ - RecordType: "A", - TTL: 300, - Target: []string{"10.0.0.2", "10.0.0.3"}, - }) - - assert.Nil(t, data) -} - -func TestDns_NewRecordBody(t *testing.T) { - client := Client(session.Must(session.New())) - - toCopy := RecordBody{ - Name: "www.example.com", - } - - newbody := client.NewRecordBody(context.Background(), toCopy) - - assert.Equal(t, toCopy, *newbody) -} diff --git a/pkg/dns/recordsets.go b/pkg/dns/recordsets.go index b6043d2f..3004e035 100644 --- a/pkg/dns/recordsets.go +++ b/pkg/dns/recordsets.go @@ -12,29 +12,27 @@ import ( ) var ( - zoneRecordsetsWriteLock sync.Mutex + zoneRecordSetsWriteLock sync.Mutex ) -// RecordSets contains operations available on a recordsets. -type RecordSets interface { - // NewRecordSetResponse returns new response object. - NewRecordSetResponse(context.Context, string) *RecordSetResponse - // GetRecordsets retrieves recordsets with Query Args. No formatting of arg values. +// Recordsets contains operations available on a record sets. +type Recordsets interface { + // GetRecordSets retrieves record sets with Query Args. No formatting of arg values. // - // See: See: https://techdocs.akamai.com/edge-dns/reference/get-zones-zone-recordsets - GetRecordsets(context.Context, string, ...RecordsetQueryArgs) (*RecordSetResponse, error) - // CreateRecordsets creates multiple recordsets. + // See: https://techdocs.akamai.com/edge-dns/reference/get-zones-zone-recordsets + GetRecordSets(context.Context, string, ...RecordSetQueryArgs) (*RecordSetResponse, error) + // CreateRecordSets creates multiple record sets. // // See: https://techdocs.akamai.com/edge-dns/reference/post-zones-zone-recordsets - CreateRecordsets(context.Context, *Recordsets, string, ...bool) error - // UpdateRecordsets replaces list of recordsets. + CreateRecordSets(context.Context, *RecordSets, string, ...bool) error + // UpdateRecordSets replaces list of record sets. // // See: https://techdocs.akamai.com/edge-dns/reference/put-zones-zone-recordsets - UpdateRecordsets(context.Context, *Recordsets, string, ...bool) error + UpdateRecordSets(context.Context, *RecordSets, string, ...bool) error } -// RecordsetQueryArgs contains query parameters for recordset request -type RecordsetQueryArgs struct { +// RecordSetQueryArgs contains query parameters for recordset request +type RecordSetQueryArgs struct { Page int PageSize int Search string @@ -43,41 +41,40 @@ type RecordsetQueryArgs struct { Types string } -// Recordsets Struct. Used for Create and Update Recordsets. Contains a list of Recordset objects -type Recordsets struct { - Recordsets []Recordset `json:"recordsets"` +// RecordSets Struct. Used for Create and Update record sets. Contains a list of RecordSet objects +type RecordSets struct { + RecordSets []RecordSet `json:"recordsets"` } -// Recordset contains recordset metadata -type Recordset struct { +// RecordSet contains record set metadata +type RecordSet struct { Name string `json:"name"` Type string `json:"type"` TTL int `json:"ttl"` Rdata []string `json:"rdata"` -} //`json:"recordsets"` +} -// MetadataH contains metadata of RecordSet response -type MetadataH struct { +// Metadata contains metadata of RecordSet response +type Metadata struct { LastPage int `json:"lastPage"` Page int `json:"page"` PageSize int `json:"pageSize"` ShowAll bool `json:"showAll"` TotalElements int `json:"totalElements"` -} //`json:"metadata"` +} -// RecordSetResponse contains a response with a list of recordsets +// RecordSetResponse contains a response with a list of record sets type RecordSetResponse struct { - Metadata MetadataH `json:"metadata"` - Recordsets []Recordset `json:"recordsets"` + Metadata Metadata `json:"metadata"` + RecordSets []RecordSet `json:"recordsets"` } -// Validate validates Recordsets -func (rs *Recordsets) Validate() error { - - if len(rs.Recordsets) < 1 { - return fmt.Errorf("Request initiated with empty recordsets list") +// Validate validates RecordSets +func (rs *RecordSets) Validate() error { + if len(rs.RecordSets) < 1 { + return fmt.Errorf("request initiated with empty recordsets list") } - for _, rec := range rs.Recordsets { + for _, rec := range rs.RecordSets { err := validation.Errors{ "Name": validation.Validate(rec.Name, validation.Required), "Type": validation.Validate(rec.Type, validation.Required), @@ -91,21 +88,14 @@ func (rs *Recordsets) Validate() error { return nil } -func (p *dns) NewRecordSetResponse(_ context.Context, _ string) *RecordSetResponse { - recordset := &RecordSetResponse{} - return recordset -} - -func (p *dns) GetRecordsets(ctx context.Context, zone string, queryArgs ...RecordsetQueryArgs) (*RecordSetResponse, error) { - - logger := p.Log(ctx) - logger.Debug("GetRecordsets") +func (d *dns) GetRecordSets(ctx context.Context, zone string, queryArgs ...RecordSetQueryArgs) (*RecordSetResponse, error) { + logger := d.Log(ctx) + logger.Debug("GetRecordSets") if len(queryArgs) > 1 { - return nil, fmt.Errorf("invalid arguments GetRecordsets QueryArgs") + return nil, fmt.Errorf("invalid arguments GetRecordSets QueryArgs") } - var recordsetResp RecordSetResponse getURL := fmt.Sprintf("/config-dns/v2/zones/%s/recordsets", zone) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) @@ -134,19 +124,20 @@ func (p *dns) GetRecordsets(ctx context.Context, zone string, queryArgs ...Recor req.URL.RawQuery = q.Encode() } - resp, err := p.Exec(req, &recordsetResp) + var result RecordSetResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetRecordsets request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &recordsetResp, nil + return &result, nil } -func (p *dns) CreateRecordsets(ctx context.Context, recordsets *Recordsets, zone string, recLock ...bool) error { +func (d *dns) CreateRecordSets(ctx context.Context, recordSets *RecordSets, zone string, recLock ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -154,41 +145,41 @@ func (p *dns) CreateRecordsets(ctx context.Context, recordsets *Recordsets, zone // incremented properly if localLock(recLock) { - zoneRecordsetsWriteLock.Lock() - defer zoneRecordsetsWriteLock.Unlock() + zoneRecordSetsWriteLock.Lock() + defer zoneRecordSetsWriteLock.Unlock() } - logger := p.Log(ctx) - logger.Debug("CreateRecordsets") + logger := d.Log(ctx) + logger.Debug("CreateRecordSets") - if err := recordsets.Validate(); err != nil { + if err := recordSets.Validate(); err != nil { return err } - reqbody, err := convertStructToReqBody(recordsets) + reqBody, err := convertStructToReqBody(recordSets) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } postURL := fmt.Sprintf("/config-dns/v2/zones/%s/recordsets", zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return fmt.Errorf("failed to create CreateRecordsets request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("CreateRecordsets request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) UpdateRecordsets(ctx context.Context, recordsets *Recordsets, zone string, recLock ...bool) error { +func (d *dns) UpdateRecordSets(ctx context.Context, recordSets *RecordSets, zone string, recLock ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -196,35 +187,35 @@ func (p *dns) UpdateRecordsets(ctx context.Context, recordsets *Recordsets, zone // incremented properly if localLock(recLock) { - zoneRecordsetsWriteLock.Lock() - defer zoneRecordsetsWriteLock.Unlock() + zoneRecordSetsWriteLock.Lock() + defer zoneRecordSetsWriteLock.Unlock() } - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("UpdateRecordsets") - if err := recordsets.Validate(); err != nil { + if err := recordSets.Validate(); err != nil { return err } - reqbody, err := convertStructToReqBody(recordsets) + reqBody, err := convertStructToReqBody(recordSets) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } putURL := fmt.Sprintf("/config-dns/v2/zones/%s/recordsets", zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqBody) if err != nil { return fmt.Errorf("failed to create UpdateRecordsets request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("UpdateRecordsets request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil diff --git a/pkg/dns/recordsets_test.go b/pkg/dns/recordsets_test.go index ecfbce6f..9d082db1 100644 --- a/pkg/dns/recordsets_test.go +++ b/pkg/dns/recordsets_test.go @@ -11,10 +11,10 @@ import ( "github.com/stretchr/testify/require" ) -func TestDns_GetRecordsets(t *testing.T) { +func TestDNS_GetRecordSets(t *testing.T) { tests := map[string]struct { zone string - args []RecordsetQueryArgs + args []RecordSetQueryArgs responseStatus int responseBody string expectedPath string @@ -23,7 +23,7 @@ func TestDns_GetRecordsets(t *testing.T) { }{ "200 OK": { zone: "example.com", - args: []RecordsetQueryArgs{}, + args: []RecordSetQueryArgs{}, responseStatus: http.StatusOK, responseBody: ` { @@ -50,14 +50,14 @@ func TestDns_GetRecordsets(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/example.com/recordsets", expectedResponse: &RecordSetResponse{ - Metadata: MetadataH{ + Metadata: Metadata{ LastPage: 0, Page: 1, PageSize: 25, ShowAll: false, TotalElements: 2, }, - Recordsets: []Recordset{ + RecordSets: []RecordSet{ { Name: "www.example.com", Type: "A", @@ -69,7 +69,7 @@ func TestDns_GetRecordsets(t *testing.T) { }, "500 internal server error": { zone: "example.com", - args: []RecordsetQueryArgs{}, + args: []RecordSetQueryArgs{}, responseStatus: http.StatusInternalServerError, responseBody: ` { @@ -98,7 +98,7 @@ func TestDns_GetRecordsets(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetRecordsets(context.Background(), test.zone, test.args...) + result, err := client.GetRecordSets(context.Background(), test.zone, test.args...) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -109,10 +109,10 @@ func TestDns_GetRecordsets(t *testing.T) { } } -func TestDns_CreateRecordsets(t *testing.T) { +func TestDNS_CreateRecordSets(t *testing.T) { tests := map[string]struct { zone string - sets *Recordsets + sets *RecordSets responseStatus int responseBody string expectedPath string @@ -121,8 +121,8 @@ func TestDns_CreateRecordsets(t *testing.T) { }{ "200 OK": { zone: "example.com", - sets: &Recordsets{ - []Recordset{ + sets: &RecordSets{ + []RecordSet{ { Name: "www.example.com", Type: "A", @@ -139,8 +139,8 @@ func TestDns_CreateRecordsets(t *testing.T) { }, "500 internal server error": { zone: "example.com", - sets: &Recordsets{ - []Recordset{ + sets: &RecordSets{ + []RecordSet{ { Name: "www.example.com", Type: "A", @@ -182,7 +182,7 @@ func TestDns_CreateRecordsets(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - err := client.CreateRecordsets(context.Background(), test.sets, test.zone) + err := client.CreateRecordSets(context.Background(), test.sets, test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -192,10 +192,10 @@ func TestDns_CreateRecordsets(t *testing.T) { } } -func TestDns_UpdateRecordsets(t *testing.T) { +func TestDNS_UpdateRecordSets(t *testing.T) { tests := map[string]struct { zone string - sets *Recordsets + sets *RecordSets responseStatus int responseBody string expectedPath string @@ -204,8 +204,8 @@ func TestDns_UpdateRecordsets(t *testing.T) { }{ "200 OK": { zone: "example.com", - sets: &Recordsets{ - []Recordset{ + sets: &RecordSets{ + []RecordSet{ { Name: "www.example.com", Type: "A", @@ -222,8 +222,8 @@ func TestDns_UpdateRecordsets(t *testing.T) { }, "500 internal server error": { zone: "example.com", - sets: &Recordsets{ - []Recordset{ + sets: &RecordSets{ + []RecordSet{ { Name: "www.example.com", Type: "A", @@ -265,7 +265,7 @@ func TestDns_UpdateRecordsets(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - err := client.UpdateRecordsets(context.Background(), test.sets, test.zone) + err := client.UpdateRecordSets(context.Background(), test.sets, test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return diff --git a/pkg/dns/tsig.go b/pkg/dns/tsig.go index 0e11aeba..19525f33 100644 --- a/pkg/dns/tsig.go +++ b/pkg/dns/tsig.go @@ -9,56 +9,47 @@ import ( "reflect" "strings" - "sync" -) - -var ( - tsigWriteLock sync.Mutex ) type ( // TSIGKeys contains operations available on TSIKeyG resource. TSIGKeys interface { - // NewTsigKey returns bare bones tsig key struct. - NewTsigKey(context.Context, string) *TSIGKey - // NewTsigQueryString returns empty query string struct. No elements required. - NewTsigQueryString(context.Context) *TSIGQueryString - // ListTsigKeys lists the TSIG keys used by zones that you are allowed to manage. + // ListTSIGKeys lists the TSIG keys used by zones that you are allowed to manage. // // See: https://techdocs.akamai.com/edge-dns/reference/get-keys - ListTsigKeys(context.Context, *TSIGQueryString) (*TSIGReportResponse, error) - // GetTsigKeyZones retrieves DNS Zones using tsig key. + ListTSIGKeys(context.Context, *TSIGQueryString) (*TSIGReportResponse, error) + // GetTSIGKeyZones retrieves DNS Zones using TSIG key. // // See: https://techdocs.akamai.com/edge-dns/reference/post-keys-used-by - GetTsigKeyZones(context.Context, *TSIGKey) (*ZoneNameListResponse, error) - // GetTsigKeyAliases retrieves a DNS Zone's aliases. + GetTSIGKeyZones(context.Context, *TSIGKey) (*ZoneNameListResponse, error) + // GetTSIGKeyAliases retrieves a DNS Zone's aliases. // // See: https://techdocs.akamai.com/edge-dns/reference/get-zones-zone-key-used-by - GetTsigKeyAliases(context.Context, string) (*ZoneNameListResponse, error) - // TsigKeyBulkUpdate updates Bulk Zones tsig key. + GetTSIGKeyAliases(context.Context, string) (*ZoneNameListResponse, error) + // TSIGKeyBulkUpdate updates Bulk Zones TSIG key. // // See: https://techdocs.akamai.com/edge-dns/reference/post-keys-bulk-update - TsigKeyBulkUpdate(context.Context, *TSIGKeyBulkPost) error - // GetTsigKey retrieves a Tsig key for zone. + TSIGKeyBulkUpdate(context.Context, *TSIGKeyBulkPost) error + // GetTSIGKey retrieves a TSIG key for zone. // // See: https://techdocs.akamai.com/edge-dns/reference/get-zones-zone-key - GetTsigKey(context.Context, string) (*TSIGKeyResponse, error) - // DeleteTsigKey deletes tsig key for zone. + GetTSIGKey(context.Context, string) (*TSIGKeyResponse, error) + // DeleteTSIGKey deletes TSIG key for zone. // // See: https://techdocs.akamai.com/edge-dns/reference/delete-zones-zone-key - DeleteTsigKey(context.Context, string) error - // UpdateTsigKey updates tsig key for zone. + DeleteTSIGKey(context.Context, string) error + // UpdateTSIGKey updates TSIG key for zone. // // See: https://techdocs.akamai.com/edge-dns/reference/put-zones-zone-key - UpdateTsigKey(context.Context, *TSIGKey, string) error + UpdateTSIGKey(context.Context, *TSIGKey, string) error } // TSIGQueryString contains TSIG query parameters TSIGQueryString struct { - ContractIds []string `json:"contractIds,omitempty"` + ContractIDs []string `json:"contractIds,omitempty"` Search string `json:"search,omitempty"` SortBy []string `json:"sortBy,omitempty"` - Gid int64 `json:"gid,omitempty"` + GID int64 `json:"gid,omitempty"` } // TSIGKey contains TSIG key POST response @@ -89,7 +80,7 @@ type ( TotalElements int64 `json:"totalElements"` Search string `json:"search,omitempty"` Contracts []string `json:"contracts,omitempty"` - Gid int64 `json:"gid,omitempty"` + GID int64 `json:"gid,omitempty"` SortBy []string `json:"sortBy,omitempty"` } @@ -100,9 +91,8 @@ type ( } ) -// Validate validates RecordBody +// Validate validates TSIGKey func (key *TSIGKey) Validate() error { - return validation.Errors{ "Name": validation.Validate(key.Name, validation.Required), "Algorithm": validation.Validate(key.Algorithm, validation.Required), @@ -118,34 +108,15 @@ func (bulk *TSIGKeyBulkPost) Validate() error { }.Filter() } -func (p *dns) NewTsigKey(ctx context.Context, name string) *TSIGKey { - - logger := p.Log(ctx) - logger.Debug("NewTsigKey") - - key := &TSIGKey{Name: name} - return key -} - -func (p *dns) NewTsigQueryString(ctx context.Context) *TSIGQueryString { - - logger := p.Log(ctx) - logger.Debug("NewTsigQueryString") - - tsigquerystring := &TSIGQueryString{} - return tsigquerystring -} - -func constructTsigQueryString(tsigquerystring *TSIGQueryString) string { - +func constructTSIGQueryString(tsigQueryString *TSIGQueryString) string { queryString := "" - qsElems := reflect.ValueOf(tsigquerystring).Elem() + qsElems := reflect.ValueOf(tsigQueryString).Elem() for i := 0; i < qsElems.NumField(); i++ { varName := qsElems.Type().Field(i).Name varValue := qsElems.Field(i).Interface() keyVal := fmt.Sprint(varValue) switch varName { - case "ContractIds": + case "ContractIDs": contractList := "" for j, id := range varValue.([]string) { contractList += id @@ -171,7 +142,7 @@ func constructTsigQueryString(tsigquerystring *TSIGQueryString) string { if keyVal != "" { queryString += "search=" + keyVal } - case "Gid": + case "GID": if varValue.(int64) != 0 { queryString += "gid=" + keyVal } @@ -187,149 +158,141 @@ func constructTsigQueryString(tsigquerystring *TSIGQueryString) string { return "" } -func (p *dns) ListTsigKeys(ctx context.Context, tsigquerystring *TSIGQueryString) (*TSIGReportResponse, error) { - - logger := p.Log(ctx) - logger.Debug("ListTsigKeys") +func (d *dns) ListTSIGKeys(ctx context.Context, tsigQueryString *TSIGQueryString) (*TSIGReportResponse, error) { + logger := d.Log(ctx) + logger.Debug("ListTSIGKeys") - var tsigList TSIGReportResponse - getURL := fmt.Sprintf("/config-dns/v2/keys%s", constructTsigQueryString(tsigquerystring)) + getURL := fmt.Sprintf("/config-dns/v2/keys%s", constructTSIGQueryString(tsigQueryString)) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListTsigKeyss request: %w", err) } - resp, err := p.Exec(req, &tsigList) + var result TSIGReportResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf(" ListTsigKeys request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &tsigList, nil - + return &result, nil } -func (p *dns) GetTsigKeyZones(ctx context.Context, tsigKey *TSIGKey) (*ZoneNameListResponse, error) { - - logger := p.Log(ctx) - logger.Debug("GetTsigKeyZones") +func (d *dns) GetTSIGKeyZones(ctx context.Context, tsigKey *TSIGKey) (*ZoneNameListResponse, error) { + logger := d.Log(ctx) + logger.Debug("GetTSIGKeyZones") if err := tsigKey.Validate(); err != nil { return nil, err } - reqbody, err := convertStructToReqBody(tsigKey) + reqBody, err := convertStructToReqBody(tsigKey) if err != nil { return nil, fmt.Errorf("failed to generate request body: %w", err) } - var zonesList ZoneNameListResponse postURL := "/config-dns/v2/keys/used-by" - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return nil, fmt.Errorf("failed to create GetTsigKeyZones request: %w", err) } - resp, err := p.Exec(req, &zonesList) + var result ZoneNameListResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetTsigKeyZones request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zonesList, nil + return &result, nil } -// TODO: Reconcile -func (p *dns) GetTsigKeyAliases(ctx context.Context, zone string) (*ZoneNameListResponse, error) { +func (d *dns) GetTSIGKeyAliases(ctx context.Context, zone string) (*ZoneNameListResponse, error) { + logger := d.Log(ctx) + logger.Debug("GetTSIGKeyAliases") - logger := p.Log(ctx) - logger.Debug("GetTsigKeyAliases") - - var zonesList ZoneNameListResponse getURL := fmt.Sprintf("/config-dns/v2/zones/%s/key/used-by", zone) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetTsigKeyAliases request: %w", err) } - resp, err := p.Exec(req, &zonesList) + var result ZoneNameListResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetTsigKeyAliases request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zonesList, nil + return &result, nil } -func (p *dns) TsigKeyBulkUpdate(ctx context.Context, tsigBulk *TSIGKeyBulkPost) error { - - logger := p.Log(ctx) - logger.Debug("TsigKeyBulkUpdate") +func (d *dns) TSIGKeyBulkUpdate(ctx context.Context, tsigBulk *TSIGKeyBulkPost) error { + logger := d.Log(ctx) + logger.Debug("TSIGKeyBulkUpdate") if err := tsigBulk.Validate(); err != nil { return err } - reqbody, err := convertStructToReqBody(tsigBulk) + reqBody, err := convertStructToReqBody(tsigBulk) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } postURL := "/config-dns/v2/keys/bulk-update" - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return fmt.Errorf("failed to create TsigKeyBulkUpdate request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("TsigKeyBulkUpdate request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) GetTsigKey(ctx context.Context, zone string) (*TSIGKeyResponse, error) { - - logger := p.Log(ctx) - logger.Debug("GetTsigKey") +func (d *dns) GetTSIGKey(ctx context.Context, zone string) (*TSIGKeyResponse, error) { + logger := d.Log(ctx) + logger.Debug("GetTSIGKey") - var zonekey TSIGKeyResponse getURL := fmt.Sprintf("/config-dns/v2/zones/%s/key", zone) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetTsigKey request: %w", err) } - resp, err := p.Exec(req, &zonekey) + var result TSIGKeyResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetTsigKey request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zonekey, nil + return &result, nil } -func (p *dns) DeleteTsigKey(ctx context.Context, zone string) error { - - logger := p.Log(ctx) - logger.Debug("DeleteTsigKey") +func (d *dns) DeleteTSIGKey(ctx context.Context, zone string) error { + logger := d.Log(ctx) + logger.Debug("DeleteTSIGKey") delURL := fmt.Sprintf("/config-dns/v2/zones/%s/key", zone) req, err := http.NewRequestWithContext(ctx, http.MethodDelete, delURL, nil) @@ -337,45 +300,44 @@ func (p *dns) DeleteTsigKey(ctx context.Context, zone string) error { return fmt.Errorf("failed to create DeleteTsigKey request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("DeleteTsigKey request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) UpdateTsigKey(ctx context.Context, tsigKey *TSIGKey, zone string) error { - - logger := p.Log(ctx) - logger.Debug("UpdateTsigKey") +func (d *dns) UpdateTSIGKey(ctx context.Context, tsigKey *TSIGKey, zone string) error { + logger := d.Log(ctx) + logger.Debug("UpdateTSIGKey") if err := tsigKey.Validate(); err != nil { return err } - reqbody, err := convertStructToReqBody(tsigKey) + reqBody, err := convertStructToReqBody(tsigKey) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } putURL := fmt.Sprintf("/config-dns/v2/zones/%s/key", zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqBody) if err != nil { return fmt.Errorf("failed to create UpdateTsigKey request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("UpdateTsigKey request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil diff --git a/pkg/dns/tsig_test.go b/pkg/dns/tsig_test.go index 0ae321a8..b9fa0ef5 100644 --- a/pkg/dns/tsig_test.go +++ b/pkg/dns/tsig_test.go @@ -7,20 +7,11 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func Test_NewTsigQueryString(t *testing.T) { - client := Client(session.Must(session.New())) - - str := client.NewTsigQueryString(context.Background()) - - assert.NotNil(t, str) -} - -func TestDns_ListTsigKeys(t *testing.T) { +func TestDNS_ListTSIGKeys(t *testing.T) { tests := map[string]struct { query TSIGQueryString responseStatus int @@ -31,7 +22,7 @@ func TestDns_ListTsigKeys(t *testing.T) { }{ "200 OK": { query: TSIGQueryString{ - ContractIds: []string{"1-1ABCD"}, + ContractIDs: []string{"1-1ABCD"}, }, responseStatus: http.StatusOK, responseBody: ` @@ -67,7 +58,7 @@ func TestDns_ListTsigKeys(t *testing.T) { }, "500 internal server error": { query: TSIGQueryString{ - ContractIds: []string{"1-1ABCD"}, + ContractIDs: []string{"1-1ABCD"}, }, responseStatus: http.StatusInternalServerError, responseBody: ` @@ -97,7 +88,7 @@ func TestDns_ListTsigKeys(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.ListTsigKeys(context.Background(), &test.query) + result, err := client.ListTSIGKeys(context.Background(), &test.query) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -108,7 +99,7 @@ func TestDns_ListTsigKeys(t *testing.T) { } } -func TestDns_GetTsigKeyZones(t *testing.T) { +func TestDNS_GetTSIGKeyZones(t *testing.T) { tests := map[string]struct { key TSIGKey responseStatus int @@ -170,7 +161,7 @@ func TestDns_GetTsigKeyZones(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetTsigKeyZones(context.Background(), &test.key) + result, err := client.GetTSIGKeyZones(context.Background(), &test.key) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -181,7 +172,7 @@ func TestDns_GetTsigKeyZones(t *testing.T) { } } -func TestDns_GetTsigKeyAliases(t *testing.T) { +func TestDNS_GetTSIGKeyAliases(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -237,7 +228,7 @@ func TestDns_GetTsigKeyAliases(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetTsigKeyAliases(context.Background(), test.zone) + result, err := client.GetTSIGKeyAliases(context.Background(), test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -248,7 +239,7 @@ func TestDns_GetTsigKeyAliases(t *testing.T) { } } -func TestDns_TsigKeyBulkUpdate(t *testing.T) { +func TestDNS_TSIGKeyBulkUpdate(t *testing.T) { tests := map[string]struct { bulk TSIGKeyBulkPost responseStatus int @@ -311,7 +302,7 @@ func TestDns_TsigKeyBulkUpdate(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - err := client.TsigKeyBulkUpdate(context.Background(), &test.bulk) + err := client.TSIGKeyBulkUpdate(context.Background(), &test.bulk) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -321,7 +312,7 @@ func TestDns_TsigKeyBulkUpdate(t *testing.T) { } } -func TestDns_GetTsigKey(t *testing.T) { +func TestDNS_GetTSIGKey(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -380,7 +371,7 @@ func TestDns_GetTsigKey(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetTsigKey(context.Background(), test.zone) + result, err := client.GetTSIGKey(context.Background(), test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -391,7 +382,7 @@ func TestDns_GetTsigKey(t *testing.T) { } } -func TestDns_DeleteTsigKey(t *testing.T) { +func TestDNS_DeleteTSIGKey(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -437,7 +428,7 @@ func TestDns_DeleteTsigKey(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - err := client.DeleteTsigKey(context.Background(), test.zone) + err := client.DeleteTSIGKey(context.Background(), test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -447,7 +438,7 @@ func TestDns_DeleteTsigKey(t *testing.T) { } } -func TestDns_UpdateTsigKey(t *testing.T) { +func TestDNS_UpdateTSIGKey(t *testing.T) { tests := map[string]struct { key TSIGKey zone string @@ -504,7 +495,7 @@ func TestDns_UpdateTsigKey(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - err := client.UpdateTsigKey(context.Background(), &test.key, test.zone) + err := client.UpdateTSIGKey(context.Background(), &test.key, test.zone) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return diff --git a/pkg/dns/zone.go b/pkg/dns/zone.go index 45e66041..5b567b89 100644 --- a/pkg/dns/zone.go +++ b/pkg/dns/zone.go @@ -26,14 +26,6 @@ type ( // // See: https://techdocs.akamai.com/edge-dns/reference/get-zones ListZones(context.Context, ...ZoneListQueryArgs) (*ZoneListResponse, error) - // NewZone returns a new ZoneCreate object. - NewZone(context.Context, ZoneCreate) *ZoneCreate - // NewZoneResponse returns a new ZoneResponse object. - NewZoneResponse(context.Context, string) *ZoneResponse - // NewChangeListResponse returns a new ChangeListResponse object. - NewChangeListResponse(context.Context, string) *ChangeListResponse - // NewZoneQueryString returns a new ZoneQueryString object. - NewZoneQueryString(context.Context, string, string) *ZoneQueryString // GetZone retrieves Zone metadata. // // See: https://techdocs.akamai.com/edge-dns/reference/get-zone @@ -66,12 +58,6 @@ type ( // // See: https://techdocs.akamai.com/edge-dns/reference/put-zone UpdateZone(context.Context, *ZoneCreate, ZoneQueryString) error - // DeleteZone deletes zone. - // - // See: N/A - DeleteZone(context.Context, *ZoneCreate, ZoneQueryString) error - // ValidateZone validates zone metadata based on type. - ValidateZone(context.Context, *ZoneCreate) error // GetZoneNames retrieves a list of a zone's record names. // // See: https://techdocs.akamai.com/edge-dns/reference/get-zone-names @@ -120,7 +106,7 @@ type ( Comment string `json:"comment,omitempty"` SignAndServe bool `json:"signAndServe"` SignAndServeAlgorithm string `json:"signAndServeAlgorithm,omitempty"` - TsigKey *TSIGKey `json:"tsigKey,omitempty"` + TSIGKey *TSIGKey `json:"tsigKey,omitempty"` Target string `json:"target,omitempty"` EndCustomerID string `json:"endCustomerId,omitempty"` ContractID string `json:"contractId,omitempty"` @@ -134,7 +120,7 @@ type ( Comment string `json:"comment,omitempty"` SignAndServe bool `json:"signAndServe"` SignAndServeAlgorithm string `json:"signAndServeAlgorithm,omitempty"` - TsigKey *TSIGKey `json:"tsigKey,omitempty"` + TSIGKey *TSIGKey `json:"tsigKey,omitempty"` Target string `json:"target,omitempty"` EndCustomerID string `json:"endCustomerId,omitempty"` ContractID string `json:"contractId,omitempty"` @@ -143,7 +129,7 @@ type ( LastActivationDate string `json:"lastActivationDate,omitempty"` LastModifiedBy string `json:"lastModifiedBy,omitempty"` LastModifiedDate string `json:"lastModifiedDate,omitempty"` - VersionId string `json:"versionId,omitempty"` + VersionID string `json:"versionId,omitempty"` } // ZoneListQueryArgs contains parameters for List Zones query @@ -164,7 +150,7 @@ type ( PageSize int `json:"pageSize"` ShowAll bool `json:"showAll"` TotalElements int `json:"totalElements"` - } //`json:"metadata"` + } // ZoneListResponse contains response for List Zones request ZoneListResponse struct { @@ -205,27 +191,24 @@ var zoneStructMap = map[string]string{ "Comment": "comment", "SignAndServe": "signAndServe", "SignAndServeAlgorithm": "signAndServeAlgorithm", - "TsigKey": "tsigKey", + "TSIGKey": "tsigKey", "Target": "target", "EndCustomerID": "endCustomerId", "ContractId": "contractId"} // Util to convert struct to http request body, eg. io.reader -func convertStructToReqBody(srcstruct interface{}) (io.Reader, error) { - - reqbody, err := json.Marshal(srcstruct) +func convertStructToReqBody(srcStruct interface{}) (io.Reader, error) { + reqBody, err := json.Marshal(srcStruct) if err != nil { return nil, err } - return bytes.NewBuffer(reqbody), nil + return bytes.NewBuffer(reqBody), nil } -func (p *dns) ListZones(ctx context.Context, queryArgs ...ZoneListQueryArgs) (*ZoneListResponse, error) { - - logger := p.Log(ctx) +func (d *dns) ListZones(ctx context.Context, queryArgs ...ZoneListQueryArgs) (*ZoneListResponse, error) { + logger := d.Log(ctx) logger.Debug("ListZones") - // construct GET url getURL := fmt.Sprintf("/config-dns/v2/zones") if len(queryArgs) > 1 { return nil, fmt.Errorf("ListZones QueryArgs invalid") @@ -260,118 +243,67 @@ func (p *dns) ListZones(ctx context.Context, queryArgs ...ZoneListQueryArgs) (*Z req.URL.RawQuery = q.Encode() } - var zonelist ZoneListResponse - resp, err := p.Exec(req, &zonelist) + var result ZoneListResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("listzones request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zonelist, nil -} - -func (p *dns) NewZone(ctx context.Context, params ZoneCreate) *ZoneCreate { - - logger := p.Log(ctx) - logger.Debug("NewZone") - - zone := &ZoneCreate{Zone: params.Zone, - Type: params.Type, - Masters: params.Masters, - TsigKey: params.TsigKey, - Target: params.Target, - EndCustomerID: params.EndCustomerID, - ContractID: params.ContractID, - Comment: params.Comment, - SignAndServe: params.SignAndServe, - SignAndServeAlgorithm: params.SignAndServeAlgorithm} - - logger.Debugf("Created zone: %v", zone) - return zone -} - -func (p *dns) NewZoneResponse(ctx context.Context, zonename string) *ZoneResponse { - - logger := p.Log(ctx) - logger.Debug("NewZoneResponse") - - zone := &ZoneResponse{Zone: zonename} - return zone -} - -func (p *dns) NewChangeListResponse(ctx context.Context, zone string) *ChangeListResponse { - - logger := p.Log(ctx) - logger.Debug("NewChangeListResponse") - - changelist := &ChangeListResponse{Zone: zone} - return changelist -} - -func (p *dns) NewZoneQueryString(ctx context.Context, contract string, group string) *ZoneQueryString { - - logger := p.Log(ctx) - logger.Debug("NewZoneQueryString") - - zonequerystring := &ZoneQueryString{Contract: contract, Group: group} - return zonequerystring + return &result, nil } -func (p *dns) GetZone(ctx context.Context, zonename string) (*ZoneResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetZone(ctx context.Context, zoneName string) (*ZoneResponse, error) { + logger := d.Log(ctx) logger.Debug("GetZone") - var zone ZoneResponse - - getURL := fmt.Sprintf("/config-dns/v2/zones/%s", zonename) + getURL := fmt.Sprintf("/config-dns/v2/zones/%s", zoneName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetZone request: %w", err) } - resp, err := p.Exec(req, &zone) + var result ZoneResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetZone request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zone, nil + return &result, nil } -func (p *dns) GetChangeList(ctx context.Context, zone string) (*ChangeListResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetChangeList(ctx context.Context, zone string) (*ChangeListResponse, error) { + logger := d.Log(ctx) logger.Debug("GetChangeList") - var changelist ChangeListResponse getURL := fmt.Sprintf("/config-dns/v2/changelists/%s", zone) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetChangeList request: %w", err) } - resp, err := p.Exec(req, &changelist) + var result ChangeListResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetChangeList request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &changelist, nil + return &result, nil } -func (p *dns) GetMasterZoneFile(ctx context.Context, zone string) (string, error) { - - logger := p.Log(ctx) +func (d *dns) GetMasterZoneFile(ctx context.Context, zone string) (string, error) { + logger := d.Log(ctx) logger.Debug("GetMasterZoneFile") getURL := fmt.Sprintf("/config-dns/v2/zones/%s/zone-file", zone) @@ -381,31 +313,30 @@ func (p *dns) GetMasterZoneFile(ctx context.Context, zone string) (string, error } req.Header.Add("Accept", "text/dns") - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return "", fmt.Errorf("GetMasterZoneFile request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return "", p.Error(resp) + return "", d.Error(resp) } - masterfile, err := ioutil.ReadAll(resp.Body) + masterFile, err := ioutil.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("GetMasterZoneFile request failed: %w", err) } - return string(masterfile), nil + return string(masterFile), nil } -func (p *dns) PostMasterZoneFile(ctx context.Context, zone string, filedata string) error { - - logger := p.Log(ctx) +func (d *dns) PostMasterZoneFile(ctx context.Context, zone string, fileData string) error { + logger := d.Log(ctx) logger.Debug("PostMasterZoneFile") - mtresp := "" + mtResp := "" pmzfURL := fmt.Sprintf("/config-dns/v2/zones/%s/zone-file", zone) - buf := bytes.NewReader([]byte(filedata)) + buf := bytes.NewReader([]byte(fileData)) req, err := http.NewRequestWithContext(ctx, http.MethodPost, pmzfURL, buf) if err != nil { return fmt.Errorf("failed to create PostMasterZoneFile request: %w", err) @@ -413,60 +344,60 @@ func (p *dns) PostMasterZoneFile(ctx context.Context, zone string, filedata stri req.Header.Set("Content-Type", "text/dns") - resp, err := p.Exec(req, &mtresp) + resp, err := d.Exec(req, &mtResp) if err != nil { return fmt.Errorf("Create PostMasterZoneFile failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) CreateZone(ctx context.Context, zone *ZoneCreate, zonequerystring ZoneQueryString, clearConn ...bool) error { +func (d *dns) CreateZone(ctx context.Context, zone *ZoneCreate, zoneQueryString ZoneQueryString, clearConn ...bool) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which - // is required to be incremented for every subsequent update to a zone + // is required to be incremented for every subsequent update to a zone, // so we have to save just one request at a time to ensure this is always // incremented properly zoneWriteLock.Lock() defer zoneWriteLock.Unlock() - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("Zone Create") - if err := p.ValidateZone(ctx, zone); err != nil { + if err := ValidateZone(zone); err != nil { return err } zoneMap := filterZoneCreate(zone) - var zoneresponse ZoneResponse - zoneURL := "/config-dns/v2/zones/?contractId=" + zonequerystring.Contract - if len(zonequerystring.Group) > 0 { - zoneURL += "&gid=" + zonequerystring.Group + var zoneResponse ZoneResponse + zoneURL := "/config-dns/v2/zones/?contractId=" + zoneQueryString.Contract + if len(zoneQueryString.Group) > 0 { + zoneURL += "&gid=" + zoneQueryString.Group } - reqbody, err := convertStructToReqBody(zoneMap) + reqBody, err := convertStructToReqBody(zoneMap) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, zoneURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, zoneURL, reqBody) if err != nil { return fmt.Errorf("failed to create Zone Create request: %w", err) } - resp, err := p.Exec(req, &zoneresponse) + resp, err := d.Exec(req, &zoneResponse) if err != nil { return fmt.Errorf("Create Zone request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return p.Error(resp) + return d.Error(resp) } if strings.ToUpper(zone.Type) == "PRIMARY" { @@ -475,7 +406,7 @@ func (p *dns) CreateZone(ctx context.Context, zone *ZoneCreate, zonequerystring // should only be one entry if clear { logger.Info("Clearing Idle Connections") - p.Client().CloseIdleConnections() + d.Client().CloseIdleConnections() } } } @@ -483,7 +414,7 @@ func (p *dns) CreateZone(ctx context.Context, zone *ZoneCreate, zonequerystring return nil } -func (p *dns) SaveChangelist(ctx context.Context, zone *ZoneCreate) error { +func (d *dns) SaveChangelist(ctx context.Context, zone *ZoneCreate) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -493,33 +424,33 @@ func (p *dns) SaveChangelist(ctx context.Context, zone *ZoneCreate) error { zoneWriteLock.Lock() defer zoneWriteLock.Unlock() - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("SaveChangeList") - reqbody, err := convertStructToReqBody("") + reqBody, err := convertStructToReqBody("") if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } postURL := fmt.Sprintf("/config-dns/v2/changelists/?zone=%s", zone.Zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return fmt.Errorf("failed to create SaveChangeList request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("SaveChangeList request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) SubmitChangelist(ctx context.Context, zone *ZoneCreate) error { +func (d *dns) SubmitChangelist(ctx context.Context, zone *ZoneCreate) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -529,33 +460,33 @@ func (p *dns) SubmitChangelist(ctx context.Context, zone *ZoneCreate) error { zoneWriteLock.Lock() defer zoneWriteLock.Unlock() - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("SubmitChangeList") - reqbody, err := convertStructToReqBody("") + reqBody, err := convertStructToReqBody("") if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } postURL := fmt.Sprintf("/config-dns/v2/changelists/%s/submit", zone.Zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, postURL, reqBody) if err != nil { return fmt.Errorf("failed to create SubmitChangeList request: %w", err) } - resp, err := p.Exec(req, nil) + resp, err := d.Exec(req, nil) if err != nil { return fmt.Errorf("SubmitChangeList request failed: %w", err) } if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil } -func (p *dns) UpdateZone(ctx context.Context, zone *ZoneCreate, _ ZoneQueryString) error { +func (d *dns) UpdateZone(ctx context.Context, zone *ZoneCreate, _ ZoneQueryString) error { // This lock will restrict the concurrency of API calls // to 1 save request at a time. This is needed for the Soa.Serial value which // is required to be incremented for every subsequent update to a zone @@ -565,78 +496,39 @@ func (p *dns) UpdateZone(ctx context.Context, zone *ZoneCreate, _ ZoneQueryStrin zoneWriteLock.Lock() defer zoneWriteLock.Unlock() - logger := p.Log(ctx) + logger := d.Log(ctx) logger.Debug("Zone Update") - if err := p.ValidateZone(ctx, zone); err != nil { + if err := ValidateZone(zone); err != nil { return err } zoneMap := filterZoneCreate(zone) - reqbody, err := convertStructToReqBody(zoneMap) + reqBody, err := convertStructToReqBody(zoneMap) if err != nil { return fmt.Errorf("failed to generate request body: %w", err) } putURL := fmt.Sprintf("/config-dns/v2/zones/%s", zone.Zone) - req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqbody) + req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, reqBody) if err != nil { return fmt.Errorf("failed to create Get Update request: %w", err) } - var zoneresp ZoneResponse - resp, err := p.Exec(req, &zoneresp) + var result ZoneResponse + resp, err := d.Exec(req, &result) if err != nil { return fmt.Errorf("Zone Update request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return p.Error(resp) - } - - return nil - -} - -func (p *dns) DeleteZone(ctx context.Context, zone *ZoneCreate, _ ZoneQueryString) error { - // remove all the records except for SOA - // which is required and save the zone - - zoneWriteLock.Lock() - defer zoneWriteLock.Unlock() - - logger := p.Log(ctx) - logger.Debug("Zone Delete") - - if zone.Zone == "" { - return fmt.Errorf("Zone name missing") - } - - deleteURL := fmt.Sprintf("/config-dns/v2/zones/%s", zone.Zone) - req, err := http.NewRequestWithContext(ctx, http.MethodDelete, deleteURL, nil) - if err != nil { - return fmt.Errorf("failed to create Zone Delete request: %w", err) - } - - resp, err := p.Exec(req, nil) - if err != nil { - return fmt.Errorf("Zone Delete request failed: %w", err) - } - - if resp.StatusCode == http.StatusNotFound { - return nil - } - - if resp.StatusCode != http.StatusNoContent { - return p.Error(resp) + return d.Error(resp) } return nil - } func filterZoneCreate(zone *ZoneCreate) map[string]interface{} { - zoneType := strings.ToUpper(zone.Type) filteredZone := make(map[string]interface{}) zoneElems := reflect.ValueOf(zone).Elem() @@ -674,22 +566,18 @@ func filterZoneCreate(zone *ZoneCreate) map[string]interface{} { } // ValidateZone validates ZoneCreate Object -func (p *dns) ValidateZone(ctx context.Context, zone *ZoneCreate) error { - - logger := p.Log(ctx) - logger.Debug("ValidateZone") - +func ValidateZone(zone *ZoneCreate) error { if len(zone.Zone) == 0 { return fmt.Errorf("Zone name is required") } - ztype := strings.ToUpper(zone.Type) - if ztype != "PRIMARY" && ztype != "SECONDARY" && ztype != "ALIAS" { + zType := strings.ToUpper(zone.Type) + if zType != "PRIMARY" && zType != "SECONDARY" && zType != "ALIAS" { return fmt.Errorf("Invalid zone type") } - if ztype != "SECONDARY" && zone.TsigKey != nil { - return fmt.Errorf("TsigKey is invalid for %s zone type", ztype) + if zType != "SECONDARY" && zone.TSIGKey != nil { + return fmt.Errorf("TsigKey is invalid for %s zone type", zType) } - if ztype == "ALIAS" { + if zType == "ALIAS" { if len(zone.Target) == 0 { return fmt.Errorf("Target is required for Alias zone type") } @@ -706,59 +594,57 @@ func (p *dns) ValidateZone(ctx context.Context, zone *ZoneCreate) error { } // Primary or Secondary if len(zone.Target) > 0 { - return fmt.Errorf("Target is invalid for %s zone type", ztype) + return fmt.Errorf("Target is invalid for %s zone type", zType) } - if zone.Masters != nil && len(zone.Masters) > 0 && ztype == "PRIMARY" { + if zone.Masters != nil && len(zone.Masters) > 0 && zType == "PRIMARY" { return fmt.Errorf("Masters is invalid for Primary zone type") } return nil } -func (p *dns) GetZoneNames(ctx context.Context, zone string) (*ZoneNamesResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetZoneNames(ctx context.Context, zone string) (*ZoneNamesResponse, error) { + logger := d.Log(ctx) logger.Debug("GetZoneNames") - var znresponse ZoneNamesResponse getURL := fmt.Sprintf("/config-dns/v2/zones/%s/names", zone) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetZoneNames request: %w", err) } - resp, err := p.Exec(req, &znresponse) + var result ZoneNamesResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetZoneNames request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &znresponse, nil + return &result, nil } -func (p *dns) GetZoneNameTypes(ctx context.Context, zname string, zone string) (*ZoneNameTypesResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetZoneNameTypes(ctx context.Context, zName, zone string) (*ZoneNameTypesResponse, error) { + logger := d.Log(ctx) logger.Debug(" GetZoneNameTypes") - var zntypes ZoneNameTypesResponse - getURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types", zone, zname) + getURL := fmt.Sprintf("/config-dns/v2/zones/%s/names/%s/types", zone, zName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetZoneNameTypes request: %w", err) } - resp, err := p.Exec(req, &zntypes) + var result ZoneNameTypesResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetZoneNameTypes request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &zntypes, nil + return &result, nil } diff --git a/pkg/dns/zone_test.go b/pkg/dns/zone_test.go index efe852bd..e9e9b0e6 100644 --- a/pkg/dns/zone_test.go +++ b/pkg/dns/zone_test.go @@ -7,12 +7,12 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestDns_ListZones(t *testing.T) { +func TestDNS_ListZones(t *testing.T) { tests := map[string]struct { args []ZoneListQueryArgs @@ -80,7 +80,7 @@ func TestDns_ListZones(t *testing.T) { Type: "primary", AliasCount: 1, SignAndServe: false, - VersionId: "ae02357c-693d-4ac4-b33d-8352d9b7c786", + VersionID: "ae02357c-693d-4ac4-b33d-8352d9b7c786", LastModifiedDate: "2017-01-03T12:00:00Z", LastModifiedBy: "user28", LastActivationDate: "2017-01-03T12:00:00Z", @@ -121,7 +121,6 @@ func TestDns_ListZones(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - //assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) @@ -142,45 +141,7 @@ func TestDns_ListZones(t *testing.T) { } } -func TestDns_NewZone(t *testing.T) { - client := Client(session.Must(session.New())) - - inp := ZoneCreate{ - Type: "A", - Target: "10.0.0.1", - } - - out := client.NewZone(context.Background(), inp) - - assert.Equal(t, &inp, out) -} - -func TestDns_NewZoneResponse(t *testing.T) { - client := Client(session.Must(session.New())) - - out := client.NewZoneResponse(context.Background(), "example.com") - - assert.Equal(t, out.Zone, "example.com") -} - -func TestDns_NewChangeListResponse(t *testing.T) { - client := Client(session.Must(session.New())) - - out := client.NewChangeListResponse(context.Background(), "example.com") - - assert.Equal(t, out.Zone, "example.com") -} - -func TestDns_NewZoneQueryString(t *testing.T) { - client := Client(session.Must(session.New())) - - out := client.NewZoneQueryString(context.Background(), "foo", "bar") - - assert.Equal(t, out.Contract, "foo") - assert.Equal(t, out.Group, "bar") -} - -func TestDns_GetZone(t *testing.T) { +func TestDNS_GetZone(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -214,7 +175,7 @@ func TestDns_GetZone(t *testing.T) { AliasCount: 1, SignAndServe: true, SignAndServeAlgorithm: "RSA_SHA256", - VersionId: "ae02357c-693d-4ac4-b33d-8352d9b7c786", + VersionID: "ae02357c-693d-4ac4-b33d-8352d9b7c786", LastModifiedDate: "2017-01-03T12:00:00Z", LastModifiedBy: "user28", LastActivationDate: "2017-01-03T12:00:00Z", @@ -262,7 +223,7 @@ func TestDns_GetZone(t *testing.T) { } } -func TestDns_GetZoneMasterFile(t *testing.T) { +func TestDNS_GetZoneMasterFile(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -331,7 +292,7 @@ www.example.com. 300 IN A 10.0.0.2"`, } } -func TestDns_UpdateZoneMasterFile(t *testing.T) { +func TestDNS_UpdateZoneMasterFile(t *testing.T) { tests := map[string]struct { zone string masterfile string @@ -401,7 +362,7 @@ www.example.com. 300 IN A 10.0.0.2"`, } } -func TestDns_GetChangeList(t *testing.T) { +func TestDNS_GetChangeList(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -471,7 +432,7 @@ func TestDns_GetChangeList(t *testing.T) { } } -func TestDns_GetMasterZoneFile(t *testing.T) { +func TestDNS_GetMasterZoneFile(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -544,7 +505,7 @@ func TestDns_GetMasterZoneFile(t *testing.T) { } } -func TestDns_CreateZone(t *testing.T) { +func TestDNS_CreateZone(t *testing.T) { tests := map[string]struct { zone ZoneCreate query ZoneQueryString @@ -630,7 +591,7 @@ func TestDns_CreateZone(t *testing.T) { } } -func TestDns_SaveChangelist(t *testing.T) { +func TestDNS_SaveChangelist(t *testing.T) { tests := map[string]struct { zone ZoneCreate responseStatus int @@ -692,7 +653,7 @@ func TestDns_SaveChangelist(t *testing.T) { } } -func TestDns_SubmitChangelist(t *testing.T) { +func TestDNS_SubmitChangelist(t *testing.T) { tests := map[string]struct { zone ZoneCreate responseStatus int @@ -754,7 +715,7 @@ func TestDns_SubmitChangelist(t *testing.T) { } } -func TestDns_UpdateZone(t *testing.T) { +func TestDNS_UpdateZone(t *testing.T) { tests := map[string]struct { zone ZoneCreate query ZoneQueryString @@ -840,70 +801,7 @@ func TestDns_UpdateZone(t *testing.T) { } } -func TestDns_DeleteZone(t *testing.T) { - tests := map[string]struct { - zone ZoneCreate - query ZoneQueryString - responseStatus int - responseBody string - expectedPath string - withError error - }{ - "204 No Content": { - zone: ZoneCreate{ - Zone: "example.com", - ContractID: "1-2ABCDE", - Type: "primary", - }, - responseStatus: http.StatusNoContent, - expectedPath: "/config-dns/v2/zones?contractId=1-2ABCDE", - }, - "500 internal server error": { - zone: ZoneCreate{ - Zone: "example.com", - ContractID: "1-2ABCDE", - Type: "secondary", - }, - responseStatus: http.StatusInternalServerError, - responseBody: ` -{ - "type": "internal_error", - "title": "Internal Server Error", - "detail": "Error creating zone", - "status": 500 -}`, - expectedPath: "/config-dns/v2/zones?contractId=1-2ABCDE", - withError: &Error{ - Type: "internal_error", - Title: "Internal Server Error", - Detail: "Error creating zone", - StatusCode: http.StatusInternalServerError, - }, - }, - } - - for name, test := range tests { - t.Run(name, func(t *testing.T) { - mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - assert.Equal(t, http.MethodDelete, r.Method) - w.WriteHeader(test.responseStatus) - if len(test.responseBody) > 0 { - _, err := w.Write([]byte(test.responseBody)) - assert.NoError(t, err) - } - })) - client := mockAPIClient(t, mockServer) - err := client.DeleteZone(context.Background(), &test.zone, test.query) - if test.withError != nil { - assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) - return - } - require.NoError(t, err) - }) - } -} - -func TestDns_GetZoneNames(t *testing.T) { +func TestDNS_GetZoneNames(t *testing.T) { tests := map[string]struct { zone string responseStatus int @@ -971,7 +869,7 @@ func TestDns_GetZoneNames(t *testing.T) { } } -func TestDns_GetZoneNameTypes(t *testing.T) { +func TestDNS_GetZoneNameTypes(t *testing.T) { tests := map[string]struct { zone string zname string @@ -1041,8 +939,6 @@ func TestDns_GetZoneNameTypes(t *testing.T) { } func Test_ValidateZoneErrors(t *testing.T) { - client := Client(session.Must(session.New())) - tests := map[string]ZoneCreate{ "empty zone": {}, "bad type": { @@ -1052,7 +948,7 @@ func Test_ValidateZoneErrors(t *testing.T) { "secondary tsig": { Zone: "example.com", Type: "PRIMARY", - TsigKey: &TSIGKey{ + TSIGKey: &TSIGKey{ Name: "example.com", }, }, @@ -1094,7 +990,7 @@ func Test_ValidateZoneErrors(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { - err := client.ValidateZone(context.Background(), &test) + err := ValidateZone(&test) assert.NotNil(t, err) }) } diff --git a/pkg/dns/zonebulk.go b/pkg/dns/zonebulk.go index 51991eca..0751112e 100644 --- a/pkg/dns/zonebulk.go +++ b/pkg/dns/zonebulk.go @@ -13,13 +13,13 @@ type BulkZonesCreate struct { // BulkZonesResponse contains response from bulk-create request type BulkZonesResponse struct { - RequestId string `json:"requestId"` + RequestID string `json:"requestId"` ExpirationDate string `json:"expirationDate"` } // BulkStatusResponse contains current status of a running or completed bulk-create request type BulkStatusResponse struct { - RequestId string `json:"requestId"` + RequestID string `json:"requestId"` ZonesSubmitted int `json:"zonesSubmitted"` SuccessCount int `json:"successCount"` FailureCount int `json:"failureCount"` @@ -35,172 +35,164 @@ type BulkFailedZone struct { // BulkCreateResultResponse contains the response from a completed bulk-create request type BulkCreateResultResponse struct { - RequestId string `json:"requestId"` + RequestID string `json:"requestId"` SuccessfullyCreatedZones []string `json:"successfullyCreatedZones"` FailedZones []*BulkFailedZone `json:"failedZones"` } // BulkDeleteResultResponse contains the response from a completed bulk-delete request type BulkDeleteResultResponse struct { - RequestId string `json:"requestId"` + RequestID string `json:"requestId"` SuccessfullyDeletedZones []string `json:"successfullyDeletedZones"` FailedZones []*BulkFailedZone `json:"failedZones"` } -func (p *dns) GetBulkZoneCreateStatus(ctx context.Context, requestid string) (*BulkStatusResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetBulkZoneCreateStatus(ctx context.Context, requestID string) (*BulkStatusResponse, error) { + logger := d.Log(ctx) logger.Debug("GetBulkZoneCreateStatus") - bulkzonesURL := fmt.Sprintf("/config-dns/v2/zones/create-requests/%s", requestid) - var status BulkStatusResponse + bulkZonesURL := fmt.Sprintf("/config-dns/v2/zones/create-requests/%s", requestID) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetBulkZoneCreateStatus request: %w", err) } - resp, err := p.Exec(req, &status) + var result BulkStatusResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetBulkZoneCreateStatus request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &status, nil + return &result, nil } -func (p *dns) GetBulkZoneDeleteStatus(ctx context.Context, requestid string) (*BulkStatusResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetBulkZoneDeleteStatus(ctx context.Context, requestID string) (*BulkStatusResponse, error) { + logger := d.Log(ctx) logger.Debug("GetBulkZoneDeleteStatus") - bulkzonesURL := fmt.Sprintf("/config-dns/v2/zones/delete-requests/%s", requestid) - var status BulkStatusResponse + bulkZonesURL := fmt.Sprintf("/config-dns/v2/zones/delete-requests/%s", requestID) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetBulkZoneDeleteStatus request: %w", err) } - resp, err := p.Exec(req, &status) + var result BulkStatusResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetBulkZoneDeleteStatus request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &status, nil + return &result, nil } -func (p *dns) GetBulkZoneCreateResult(ctx context.Context, requestid string) (*BulkCreateResultResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetBulkZoneCreateResult(ctx context.Context, requestID string) (*BulkCreateResultResponse, error) { + logger := d.Log(ctx) logger.Debug("GetBulkZoneCreateResult") - bulkzonesURL := fmt.Sprintf("/config-dns/v2/zones/create-requests/%s/result", requestid) + bulkZonesURL := fmt.Sprintf("/config-dns/v2/zones/create-requests/%s/result", requestID) var status BulkCreateResultResponse - req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetBulkZoneCreateResult request: %w", err) } - resp, err := p.Exec(req, &status) + resp, err := d.Exec(req, &status) if err != nil { return nil, fmt.Errorf("GetBulkZoneCreateResult request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } return &status, nil } -func (p *dns) GetBulkZoneDeleteResult(ctx context.Context, requestid string) (*BulkDeleteResultResponse, error) { - - logger := p.Log(ctx) +func (d *dns) GetBulkZoneDeleteResult(ctx context.Context, requestID string) (*BulkDeleteResultResponse, error) { + logger := d.Log(ctx) logger.Debug("GetBulkZoneDeleteResult") - bulkzonesURL := fmt.Sprintf("/config-dns/v2/zones/delete-requests/%s/result", requestid) - var status BulkDeleteResultResponse + bulkZonesURL := fmt.Sprintf("/config-dns/v2/zones/delete-requests/%s/result", requestID) - req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetBulkZoneDeleteResult request: %w", err) } - resp, err := p.Exec(req, &status) + var result BulkDeleteResultResponse + resp, err := d.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetBulkZoneDeleteResult request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &status, nil + return &result, nil } -func (p *dns) CreateBulkZones(ctx context.Context, bulkzones *BulkZonesCreate, zonequerystring ZoneQueryString) (*BulkZonesResponse, error) { - - logger := p.Log(ctx) +func (d *dns) CreateBulkZones(ctx context.Context, bulkZones *BulkZonesCreate, zoneQueryString ZoneQueryString) (*BulkZonesResponse, error) { + logger := d.Log(ctx) logger.Debug("CreateBulkZones") - bulkzonesURL := "/config-dns/v2/zones/create-requests?contractId=" + zonequerystring.Contract - if len(zonequerystring.Group) > 0 { - bulkzonesURL += "&gid=" + zonequerystring.Group + bulkZonesURL := "/config-dns/v2/zones/create-requests?contractId=" + zoneQueryString.Contract + if len(zoneQueryString.Group) > 0 { + bulkZonesURL += "&gid=" + zoneQueryString.Group } - var status BulkZonesResponse - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create CreateBulkZones request: %w", err) } - resp, err := p.Exec(req, &status, bulkzones) + var result BulkZonesResponse + resp, err := d.Exec(req, &result, bulkZones) if err != nil { return nil, fmt.Errorf("CreateBulkZones request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &status, nil + return &result, nil } -func (p *dns) DeleteBulkZones(ctx context.Context, zoneslist *ZoneNameListResponse, bypassSafetyChecks ...bool) (*BulkZonesResponse, error) { - - logger := p.Log(ctx) +func (d *dns) DeleteBulkZones(ctx context.Context, zonesList *ZoneNameListResponse, bypassSafetyChecks ...bool) (*BulkZonesResponse, error) { + logger := d.Log(ctx) logger.Debug("DeleteBulkZones") - bulkzonesURL := "/config-dns/v2/zones/delete-requests" + bulkZonesURL := "/config-dns/v2/zones/delete-requests" if len(bypassSafetyChecks) > 0 { - bulkzonesURL += fmt.Sprintf("?bypassSafetyChecks=%t", bypassSafetyChecks[0]) + bulkZonesURL += fmt.Sprintf("?bypassSafetyChecks=%t", bypassSafetyChecks[0]) } - var status BulkZonesResponse - - req, err := http.NewRequestWithContext(ctx, http.MethodPost, bulkzonesURL, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, bulkZonesURL, nil) if err != nil { return nil, fmt.Errorf("failed to create DeleteBulkZones request: %w", err) } - resp, err := p.Exec(req, &status, zoneslist) + var result BulkZonesResponse + resp, err := d.Exec(req, &result, zonesList) if err != nil { return nil, fmt.Errorf("DeleteBulkZones request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, d.Error(resp) } - return &status, nil + return &result, nil } diff --git a/pkg/dns/zonebulk_test.go b/pkg/dns/zonebulk_test.go index feee6cb7..5c5d32d2 100644 --- a/pkg/dns/zonebulk_test.go +++ b/pkg/dns/zonebulk_test.go @@ -11,9 +11,9 @@ import ( "github.com/stretchr/testify/require" ) -func TestDns_GetBulkZoneCreateStatus(t *testing.T) { +func TestDNS_GetBulkZoneCreateStatus(t *testing.T) { tests := map[string]struct { - requestid string + requestID string responseStatus int responseBody string expectedPath string @@ -21,7 +21,7 @@ func TestDns_GetBulkZoneCreateStatus(t *testing.T) { withError error }{ "200 OK": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusOK, responseBody: ` { @@ -34,7 +34,7 @@ func TestDns_GetBulkZoneCreateStatus(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/create-requests/15bc138f-8d82-451b-80b7-a56b88ffc474", expectedResponse: &BulkStatusResponse{ - RequestId: "15bc138f-8d82-451b-80b7-a56b88ffc474", + RequestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", ZonesSubmitted: 2, SuccessCount: 0, FailureCount: 2, @@ -43,7 +43,7 @@ func TestDns_GetBulkZoneCreateStatus(t *testing.T) { }, }, "500 internal server error": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusInternalServerError, responseBody: ` { @@ -65,14 +65,13 @@ func TestDns_GetBulkZoneCreateStatus(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - //assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetBulkZoneCreateStatus(context.Background(), test.requestid) + result, err := client.GetBulkZoneCreateStatus(context.Background(), test.requestID) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -83,9 +82,9 @@ func TestDns_GetBulkZoneCreateStatus(t *testing.T) { } } -func TestDns_GetBulkZoneCreateResult(t *testing.T) { +func TestDNS_GetBulkZoneCreateResult(t *testing.T) { tests := map[string]struct { - requestid string + requestID string responseStatus int responseBody string expectedPath string @@ -93,7 +92,7 @@ func TestDns_GetBulkZoneCreateResult(t *testing.T) { withError error }{ "200 OK": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusOK, responseBody: ` { @@ -108,7 +107,7 @@ func TestDns_GetBulkZoneCreateResult(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/create-requests/15bc138f-8d82-451b-80b7-a56b88ffc474/result", expectedResponse: &BulkCreateResultResponse{ - RequestId: "15bc138f-8d82-451b-80b7-a56b88ffc474", + RequestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", SuccessfullyCreatedZones: make([]string, 0), FailedZones: []*BulkFailedZone{ { @@ -119,7 +118,7 @@ func TestDns_GetBulkZoneCreateResult(t *testing.T) { }, }, "500 internal server error": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusInternalServerError, responseBody: ` { @@ -141,14 +140,13 @@ func TestDns_GetBulkZoneCreateResult(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - //assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetBulkZoneCreateResult(context.Background(), test.requestid) + result, err := client.GetBulkZoneCreateResult(context.Background(), test.requestID) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -159,7 +157,7 @@ func TestDns_GetBulkZoneCreateResult(t *testing.T) { } } -func TestDns_CreateBulkZones(t *testing.T) { +func TestDNS_CreateBulkZones(t *testing.T) { tests := map[string]struct { zones BulkZonesCreate query ZoneQueryString @@ -194,7 +192,7 @@ func TestDns_CreateBulkZones(t *testing.T) { "expirationDate": "2020-10-28T19:50:36.272668Z" }`, expectedResponse: &BulkZonesResponse{ - RequestId: "93e97a28-4e05-45f4-8b9a-cebd71155949", + RequestID: "93e97a28-4e05-45f4-8b9a-cebd71155949", ExpirationDate: "2020-10-28T19:50:36.272668Z", }, expectedPath: "/config-dns/v2/zones/create-requests?contractId=1-2ABCDE&gid=testgroup", @@ -258,9 +256,9 @@ func TestDns_CreateBulkZones(t *testing.T) { } // Bulk Delete tests -func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { +func TestDNS_GetBulkZoneDeleteStatus(t *testing.T) { tests := map[string]struct { - requestid string + requestID string responseStatus int responseBody string expectedPath string @@ -268,7 +266,7 @@ func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { withError error }{ "200 OK": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusOK, responseBody: ` { @@ -281,7 +279,7 @@ func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/delete-requests/15bc138f-8d82-451b-80b7-a56b88ffc474", expectedResponse: &BulkStatusResponse{ - RequestId: "15bc138f-8d82-451b-80b7-a56b88ffc474", + RequestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", ZonesSubmitted: 2, SuccessCount: 0, FailureCount: 2, @@ -290,7 +288,7 @@ func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { }, }, "500 internal server error": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusInternalServerError, responseBody: ` { @@ -312,14 +310,13 @@ func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - //assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetBulkZoneDeleteStatus(context.Background(), test.requestid) + result, err := client.GetBulkZoneDeleteStatus(context.Background(), test.requestID) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -330,9 +327,9 @@ func TestDns_GetBulkZoneDeleteStatus(t *testing.T) { } } -func TestDns_GetBulkZoneDeleteResult(t *testing.T) { +func TestDNS_GetBulkZoneDeleteResult(t *testing.T) { tests := map[string]struct { - requestid string + requestID string responseStatus int responseBody string expectedPath string @@ -340,7 +337,7 @@ func TestDns_GetBulkZoneDeleteResult(t *testing.T) { withError error }{ "200 OK": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusOK, responseBody: ` { @@ -355,7 +352,7 @@ func TestDns_GetBulkZoneDeleteResult(t *testing.T) { }`, expectedPath: "/config-dns/v2/zones/delete-requests/15bc138f-8d82-451b-80b7-a56b88ffc474/result", expectedResponse: &BulkDeleteResultResponse{ - RequestId: "15bc138f-8d82-451b-80b7-a56b88ffc474", + RequestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", SuccessfullyDeletedZones: make([]string, 0), FailedZones: []*BulkFailedZone{ { @@ -366,7 +363,7 @@ func TestDns_GetBulkZoneDeleteResult(t *testing.T) { }, }, "500 internal server error": { - requestid: "15bc138f-8d82-451b-80b7-a56b88ffc474", + requestID: "15bc138f-8d82-451b-80b7-a56b88ffc474", responseStatus: http.StatusInternalServerError, responseBody: ` { @@ -388,14 +385,13 @@ func TestDns_GetBulkZoneDeleteResult(t *testing.T) { for name, test := range tests { t.Run(name, func(t *testing.T) { mockServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - //assert.Equal(t, test.expectedPath, r.URL.String()) assert.Equal(t, http.MethodGet, r.Method) w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetBulkZoneDeleteResult(context.Background(), test.requestid) + result, err := client.GetBulkZoneDeleteResult(context.Background(), test.requestID) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -406,9 +402,9 @@ func TestDns_GetBulkZoneDeleteResult(t *testing.T) { } } -func TestDns_DeleteBulkZones(t *testing.T) { +func TestDNS_DeleteBulkZones(t *testing.T) { tests := map[string]struct { - zoneslist ZoneNameListResponse + zonesList ZoneNameListResponse bypassSafety bool responseStatus int responseBody string @@ -417,7 +413,7 @@ func TestDns_DeleteBulkZones(t *testing.T) { withError error }{ "200 Created": { - zoneslist: ZoneNameListResponse{ + zonesList: ZoneNameListResponse{ Zones: []string{"one.testbulk.net", "two.testbulk.net"}, }, bypassSafety: true, @@ -428,13 +424,13 @@ func TestDns_DeleteBulkZones(t *testing.T) { "expirationDate": "2020-10-28T19:50:36.272668Z" }`, expectedResponse: &BulkZonesResponse{ - RequestId: "93e97a28-4e05-45f4-8b9a-cebd71155949", + RequestID: "93e97a28-4e05-45f4-8b9a-cebd71155949", ExpirationDate: "2020-10-28T19:50:36.272668Z", }, expectedPath: "/config-dns/v2/zones/delete-requests?bypassSafetyChecks=true", }, "500 internal server error": { - zoneslist: ZoneNameListResponse{ + zonesList: ZoneNameListResponse{ Zones: []string{"one.testbulk.net", "two.testbulk.net"}, }, bypassSafety: true, @@ -467,7 +463,7 @@ func TestDns_DeleteBulkZones(t *testing.T) { } })) client := mockAPIClient(t, mockServer) - result, err := client.DeleteBulkZones(context.Background(), &test.zoneslist, test.bypassSafety) + result, err := client.DeleteBulkZones(context.Background(), &test.zonesList, test.bypassSafety) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return diff --git a/pkg/edgeworkers/edgekv_groups.go b/pkg/edgeworkers/edgekv_groups.go index e100f900..a951ee80 100644 --- a/pkg/edgeworkers/edgekv_groups.go +++ b/pkg/edgeworkers/edgekv_groups.go @@ -6,7 +6,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/edgeworkers/edgekv_namespaces_test.go b/pkg/edgeworkers/edgekv_namespaces_test.go index 7620b85b..8b18321a 100644 --- a/pkg/edgeworkers/edgekv_namespaces_test.go +++ b/pkg/edgeworkers/edgekv_namespaces_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/edgeworkers/edgeworker_version.go b/pkg/edgeworkers/edgeworker_version.go index ff80315c..11ec997c 100644 --- a/pkg/edgeworkers/edgeworker_version.go +++ b/pkg/edgeworkers/edgeworker_version.go @@ -209,7 +209,7 @@ func (e *edgeworkers) GetEdgeWorkerVersionContent(ctx context.Context, params Ge return nil, fmt.Errorf("%w: failed to create request: %s", ErrGetEdgeWorkerVersionContent, err) } - req.Header.Add("Content-Type", "application/gzip") + req.Header.Add("Accept", "application/gzip") resp, err := e.Exec(req, nil) if err != nil { return nil, fmt.Errorf("%w: request failed: %s", ErrGetEdgeWorkerVersionContent, err) diff --git a/pkg/edgeworkers/edgeworkers.go b/pkg/edgeworkers/edgeworkers.go index 5d915a4d..2d643ac8 100644 --- a/pkg/edgeworkers/edgeworkers.go +++ b/pkg/edgeworkers/edgeworkers.go @@ -4,7 +4,7 @@ package edgeworkers import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/edgeworkers/edgeworkers_test.go b/pkg/edgeworkers/edgeworkers_test.go index 4dd9b5ff..3f26db9c 100644 --- a/pkg/edgeworkers/edgeworkers_test.go +++ b/pkg/edgeworkers/edgeworkers_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/edgeworkers/errors.go b/pkg/edgeworkers/errors.go index 70aa883a..b26e913e 100644 --- a/pkg/edgeworkers/errors.go +++ b/pkg/edgeworkers/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/edgeworkers/errors_test.go b/pkg/edgeworkers/errors_test.go index ff8910cb..c39e3272 100644 --- a/pkg/edgeworkers/errors_test.go +++ b/pkg/edgeworkers/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/edgeworkers/report_test.go b/pkg/edgeworkers/report_test.go index 4ec8a7fc..4ca380cc 100644 --- a/pkg/edgeworkers/report_test.go +++ b/pkg/edgeworkers/report_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/gtm/asmap.go b/pkg/gtm/asmap.go index 6e45526b..0a98c254 100644 --- a/pkg/gtm/asmap.go +++ b/pkg/gtm/asmap.go @@ -6,156 +6,122 @@ import ( "net/http" ) -// -// Handle Operations on gtm asmaps -// Based on 1.4 schema -// - // ASMaps contains operations available on a ASmap resource. -type ASMaps interface { - // NewAsMap creates a new AsMap object. - NewAsMap(context.Context, string) *AsMap - // NewASAssignment instantiates new Assignment struct. - NewASAssignment(context.Context, *AsMap, int, string) *AsAssignment - // ListAsMaps retrieves all AsMaps. - // - // See: https://techdocs.akamai.com/gtm/reference/get-as-maps - ListAsMaps(context.Context, string) ([]*AsMap, error) - // GetAsMap retrieves a AsMap with the given name. - // - // See: https://techdocs.akamai.com/gtm/reference/get-as-map - GetAsMap(context.Context, string, string) (*AsMap, error) - // CreateAsMap creates the datacenter identified by the receiver argument in the specified domain. - // - // See: https://techdocs.akamai.com/gtm/reference/put-as-map - CreateAsMap(context.Context, *AsMap, string) (*AsMapResponse, error) - // DeleteAsMap deletes the datacenter identified by the receiver argument from the domain specified. - // - // See: https://techdocs.akamai.com/gtm/reference/delete-as-map - DeleteAsMap(context.Context, *AsMap, string) (*ResponseStatus, error) - // UpdateAsMap updates the datacenter identified in the receiver argument in the provided domain. - // - // See: https://techdocs.akamai.com/gtm/reference/put-as-map - UpdateAsMap(context.Context, *AsMap, string) (*ResponseStatus, error) -} - -// AsAssignment represents a GTM asmap assignment structure -type AsAssignment struct { - DatacenterBase - AsNumbers []int64 `json:"asNumbers"` -} - -// AsMap represents a GTM AsMap -type AsMap struct { - DefaultDatacenter *DatacenterBase `json:"defaultDatacenter"` - Assignments []*AsAssignment `json:"assignments,omitempty"` - Name string `json:"name"` - Links []*Link `json:"links,omitempty"` -} - -// AsMapList represents the returned GTM AsMap List body -type AsMapList struct { - AsMapItems []*AsMap `json:"items"` -} - -// Validate validates AsMap -func (asm *AsMap) Validate() error { +type ( + ASMaps interface { + // ListASMaps retrieves all AsMaps. + // + // See: https://techdocs.akamai.com/gtm/reference/get-as-maps + ListASMaps(context.Context, string) ([]*ASMap, error) + // GetASMap retrieves a AsMap with the given name. + // + // See: https://techdocs.akamai.com/gtm/reference/get-as-map + GetASMap(context.Context, string, string) (*ASMap, error) + // CreateASMap creates the datacenter identified by the receiver argument in the specified domain. + // + // See: https://techdocs.akamai.com/gtm/reference/put-as-map + CreateASMap(context.Context, *ASMap, string) (*ASMapResponse, error) + // DeleteASMap deletes the datacenter identified by the receiver argument from the domain specified. + // + // See: https://techdocs.akamai.com/gtm/reference/delete-as-map + DeleteASMap(context.Context, *ASMap, string) (*ResponseStatus, error) + // UpdateASMap updates the datacenter identified in the receiver argument in the provided domain. + // + // See: https://techdocs.akamai.com/gtm/reference/put-as-map + UpdateASMap(context.Context, *ASMap, string) (*ResponseStatus, error) + } + // ASAssignment represents a GTM as map assignment structure + ASAssignment struct { + DatacenterBase + ASNumbers []int64 `json:"asNumbers"` + } + + // ASMap represents a GTM ASMap + ASMap struct { + DefaultDatacenter *DatacenterBase `json:"defaultDatacenter"` + Assignments []*ASAssignment `json:"assignments,omitempty"` + Name string `json:"name"` + Links []*Link `json:"links,omitempty"` + } + + // ASMapList represents the returned GTM ASMap List body + ASMapList struct { + ASMapItems []*ASMap `json:"items"` + } +) - if len(asm.Name) < 1 { - return fmt.Errorf("AsMap is missing Name") +// Validate validates ASMap +func (a *ASMap) Validate() error { + if len(a.Name) < 1 { + return fmt.Errorf("ASMap is missing Name") } - if asm.DefaultDatacenter == nil { - return fmt.Errorf("AsMap is missing DefaultDatacenter") + if a.DefaultDatacenter == nil { + return fmt.Errorf("ASMap is missing DefaultDatacenter") } return nil } -func (p *gtm) NewAsMap(ctx context.Context, name string) *AsMap { - - logger := p.Log(ctx) - logger.Debug("NewAsMap") - - asmap := &AsMap{Name: name} - return asmap -} - -func (p *gtm) ListAsMaps(ctx context.Context, domainName string) ([]*AsMap, error) { - - logger := p.Log(ctx) - logger.Debug("ListAsMaps") +func (g *gtm) ListASMaps(ctx context.Context, domainName string) ([]*ASMap, error) { + logger := g.Log(ctx) + logger.Debug("ListASMaps") - var aslist AsMapList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create ListAsMaps request: %w", err) + return nil, fmt.Errorf("failed to create ListASMaps request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &aslist) + + var result ASMapList + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("ListAsMaps request failed: %w", err) + return nil, fmt.Errorf("ListASMaps request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return aslist.AsMapItems, nil + return result.ASMapItems, nil } -func (p *gtm) GetAsMap(ctx context.Context, name, domainName string) (*AsMap, error) { - - logger := p.Log(ctx) - logger.Debug("GetAsMap") +func (g *gtm) GetASMap(ctx context.Context, asMapName, domainName string) (*ASMap, error) { + logger := g.Log(ctx) + logger.Debug("GetASMap") - var as AsMap - getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, name) + getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, asMapName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create GetAsMap request: %w", err) + return nil, fmt.Errorf("failed to create GetASMap request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &as) + + var result ASMap + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("GetAsMap request failed: %w", err) + return nil, fmt.Errorf("GetASMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &as, nil -} - -func (p *gtm) NewASAssignment(ctx context.Context, _ *AsMap, dcID int, nickname string) *AsAssignment { - - logger := p.Log(ctx) - logger.Debug("NewAssignment") - - asAssign := &AsAssignment{} - asAssign.DatacenterId = dcID - asAssign.Nickname = nickname - - return asAssign + return &result, nil } -func (p *gtm) CreateAsMap(ctx context.Context, as *AsMap, domainName string) (*AsMapResponse, error) { +func (g *gtm) CreateASMap(ctx context.Context, asMap *ASMap, domainName string) (*ASMapResponse, error) { + logger := g.Log(ctx) + logger.Debug("CreateASMap") - logger := p.Log(ctx) - logger.Debug("CreateAsMap") - - // Use common code. Any specific validation needed? - return as.save(ctx, p, domainName) + return asMap.save(ctx, g, domainName) } -func (p *gtm) UpdateAsMap(ctx context.Context, as *AsMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) - logger.Debug("UpdateAsMap") +func (g *gtm) UpdateASMap(ctx context.Context, asMap *ASMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) + logger.Debug("UpdateASMap") - // common code - stat, err := as.save(ctx, p, domainName) + stat, err := asMap.save(ctx, g, domainName) if err != nil { return nil, err } @@ -163,57 +129,55 @@ func (p *gtm) UpdateAsMap(ctx context.Context, as *AsMap, domainName string) (*R } // save AsMap in given domain. Common path for Create and Update. -func (asm *AsMap) save(ctx context.Context, p *gtm, domainName string) (*AsMapResponse, error) { - - if err := asm.Validate(); err != nil { - return nil, fmt.Errorf("AsMap validation failed. %w", err) +func (a *ASMap) save(ctx context.Context, g *gtm, domainName string) (*ASMapResponse, error) { + if err := a.Validate(); err != nil { + return nil, fmt.Errorf("ASMap validation failed. %w", err) } - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, asm.Name) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, a.Name) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create AsMap request: %w", err) + return nil, fmt.Errorf("failed to create ASMap request: %w", err) } - - var mapresp AsMapResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp, asm) + + var result ASMapResponse + resp, err := g.Exec(req, &result, a) if err != nil { - return nil, fmt.Errorf("AsMap request failed: %w", err) + return nil, fmt.Errorf("ASMap request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &mapresp, nil + return &result, nil } -func (p *gtm) DeleteAsMap(ctx context.Context, as *AsMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) - logger.Debug("DeleteAsMap") +func (g *gtm) DeleteASMap(ctx context.Context, asMap *ASMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) + logger.Debug("DeleteASMap") - if err := as.Validate(); err != nil { - return nil, fmt.Errorf("Resource validation failed. %w", err) + if err := asMap.Validate(); err != nil { + return nil, fmt.Errorf("resource validation failed: %w", err) } - delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, as.Name) + delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/as-maps/%s", domainName, asMap.Name) req, err := http.NewRequestWithContext(ctx, http.MethodDelete, delURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Delete request: %w", err) } - - var mapresp ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp) + + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("AsMap request failed: %w", err) + return nil, fmt.Errorf("ASMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return mapresp.Status, nil + return result.Status, nil } diff --git a/pkg/gtm/asmap_test.go b/pkg/gtm/asmap_test.go index 2b423be3..7a322f30 100644 --- a/pkg/gtm/asmap_test.go +++ b/pkg/gtm/asmap_test.go @@ -9,23 +9,15 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewAsMap(t *testing.T) { - client := Client(session.Must(session.New())) +func TestGTM_ListASMap(t *testing.T) { + var result ASMapList - asmap := client.NewAsMap(context.Background(), "foo") - - assert.Equal(t, "foo", asmap.Name) -} - -func TestGtm_ListAsMap(t *testing.T) { - var result AsMapList - - respData, err := loadTestData("TestGtm_ListAsMap.resp.json") + respData, err := loadTestData("TestGTM_ListASMap.resp.json") if err != nil { t.Fatal(err) } @@ -39,7 +31,7 @@ func TestGtm_ListAsMap(t *testing.T) { responseStatus int responseBody string expectedPath string - expectedResponse []*AsMap + expectedResponse []*ASMap withError error headers http.Header }{ @@ -51,7 +43,7 @@ func TestGtm_ListAsMap(t *testing.T) { responseStatus: http.StatusOK, responseBody: string(respData), expectedPath: "/config-gtm/v1/domains/example.akadns.net/as-maps", - expectedResponse: result.AsMapItems, + expectedResponse: result.ASMapItems, }, "500 internal server error": { domainName: "example.akadns.net", @@ -84,7 +76,7 @@ func TestGtm_ListAsMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.ListAsMaps( + result, err := client.ListASMaps( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.domainName) @@ -98,10 +90,10 @@ func TestGtm_ListAsMap(t *testing.T) { } } -func TestGtm_GetAsMap(t *testing.T) { - var result AsMap +func TestGTM_GetASMap(t *testing.T) { + var result ASMap - respData, err := loadTestData("TestGtm_GetAsMap.resp.json") + respData, err := loadTestData("TestGTM_GetASMap.resp.json") if err != nil { t.Fatal(err) } @@ -116,7 +108,7 @@ func TestGtm_GetAsMap(t *testing.T) { responseStatus int responseBody string expectedPath string - expectedResponse *AsMap + expectedResponse *ASMap withError error headers http.Header }{ @@ -163,7 +155,7 @@ func TestGtm_GetAsMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetAsMap( + result, err := client.GetASMap( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.name, test.domainName) @@ -177,20 +169,11 @@ func TestGtm_GetAsMap(t *testing.T) { } } -func TestGtm_NewASAssignment(t *testing.T) { - client := Client(session.Must(session.New())) - - asn := client.NewASAssignment(context.Background(), nil, 100, "foo") - - assert.Equal(t, 100, asn.DatacenterId) - assert.Equal(t, "foo", asn.Nickname) -} - -func TestGtm_CreateAsMap(t *testing.T) { - var result AsMapResponse - var req AsMap +func TestGTM_CreateASMap(t *testing.T) { + var result ASMapResponse + var req ASMap - respData, err := loadTestData("TestGtm_CreateAsMap.resp.json") + respData, err := loadTestData("TestGTM_CreateASMap.resp.json") if err != nil { t.Fatal(err) } @@ -199,7 +182,7 @@ func TestGtm_CreateAsMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateAsMap.req.json") + reqData, err := loadTestData("TestGTM_CreateASMap.req.json") if err != nil { t.Fatal(err) } @@ -209,17 +192,17 @@ func TestGtm_CreateAsMap(t *testing.T) { } tests := map[string]struct { - asmap *AsMap + asMap *ASMap domainName string responseStatus int responseBody string expectedPath string - expectedResponse *AsMapResponse + expectedResponse *ASMapResponse withError error headers http.Header }{ "200 OK": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -230,7 +213,7 @@ func TestGtm_CreateAsMap(t *testing.T) { expectedResponse: &result, }, "500 internal server error": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -260,10 +243,10 @@ func TestGtm_CreateAsMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.CreateAsMap( + result, err := client.CreateASMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.asmap, test.domainName) + session.WithContextHeaders(test.headers)), test.asMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -274,11 +257,11 @@ func TestGtm_CreateAsMap(t *testing.T) { } } -func TestGtm_UpdateAsMap(t *testing.T) { - var result AsMapResponse - var req AsMap +func TestGTM_UpdateASMap(t *testing.T) { + var result ASMapResponse + var req ASMap - respData, err := loadTestData("TestGtm_CreateAsMap.resp.json") + respData, err := loadTestData("TestGTM_CreateASMap.resp.json") if err != nil { t.Fatal(err) } @@ -287,7 +270,7 @@ func TestGtm_UpdateAsMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateAsMap.req.json") + reqData, err := loadTestData("TestGTM_CreateASMap.req.json") if err != nil { t.Fatal(err) } @@ -297,7 +280,7 @@ func TestGtm_UpdateAsMap(t *testing.T) { } tests := map[string]struct { - asmap *AsMap + asMap *ASMap domainName string responseStatus int responseBody string @@ -307,7 +290,7 @@ func TestGtm_UpdateAsMap(t *testing.T) { headers http.Header }{ "200 OK": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -318,7 +301,7 @@ func TestGtm_UpdateAsMap(t *testing.T) { expectedResponse: result.Status, }, "500 internal server error": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -348,10 +331,10 @@ func TestGtm_UpdateAsMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.UpdateAsMap( + result, err := client.UpdateASMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.asmap, test.domainName) + session.WithContextHeaders(test.headers)), test.asMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -362,11 +345,11 @@ func TestGtm_UpdateAsMap(t *testing.T) { } } -func TestGtm_DeleteAsMap(t *testing.T) { - var result AsMapResponse - var req AsMap +func TestGTM_DeleteASMap(t *testing.T) { + var result ASMapResponse + var req ASMap - respData, err := loadTestData("TestGtm_CreateAsMap.resp.json") + respData, err := loadTestData("TestGTM_CreateASMap.resp.json") if err != nil { t.Fatal(err) } @@ -375,7 +358,7 @@ func TestGtm_DeleteAsMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateAsMap.req.json") + reqData, err := loadTestData("TestGTM_CreateASMap.req.json") if err != nil { t.Fatal(err) } @@ -385,7 +368,7 @@ func TestGtm_DeleteAsMap(t *testing.T) { } tests := map[string]struct { - asmap *AsMap + asMap *ASMap domainName string responseStatus int responseBody string @@ -395,7 +378,7 @@ func TestGtm_DeleteAsMap(t *testing.T) { headers http.Header }{ "200 OK": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -406,7 +389,7 @@ func TestGtm_DeleteAsMap(t *testing.T) { expectedResponse: result.Status, }, "500 internal server error": { - asmap: &req, + asMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -436,10 +419,10 @@ func TestGtm_DeleteAsMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.DeleteAsMap( + result, err := client.DeleteASMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.asmap, test.domainName) + session.WithContextHeaders(test.headers)), test.asMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return diff --git a/pkg/gtm/cidrmap.go b/pkg/gtm/cidrmap.go index c4fc65cb..2f56e5c8 100644 --- a/pkg/gtm/cidrmap.go +++ b/pkg/gtm/cidrmap.go @@ -6,196 +6,160 @@ import ( "net/http" ) -// -// Handle Operations on gtm cidrmaps -// Based on 1.4 schema -// - -// CidrMaps contains operations available on a Cidrmap resource. -type CidrMaps interface { - // NewCidrMap creates a new CidrMap object. - NewCidrMap(context.Context, string) *CidrMap - // NewCidrAssignment instantiates new Assignment struct. - NewCidrAssignment(context.Context, *CidrMap, int, string) *CidrAssignment - // ListCidrMaps retreieves all CidrMaps. +// CIDRMaps contains operations available on a CIDR map resource. +type CIDRMaps interface { + // ListCIDRMaps retrieves all CIDRMaps. // // See: https://techdocs.akamai.com/gtm/reference/get-cidr-maps - ListCidrMaps(context.Context, string) ([]*CidrMap, error) - // GetCidrMap retrieves a CidrMap with the given name. + ListCIDRMaps(context.Context, string) ([]*CIDRMap, error) + // GetCIDRMap retrieves a CIDRMap with the given name. // // See: https://techdocs.akamai.com/gtm/reference/get-cidr-map - GetCidrMap(context.Context, string, string) (*CidrMap, error) - // CreateCidrMap creates the datacenter identified by the receiver argument in the specified domain. + GetCIDRMap(context.Context, string, string) (*CIDRMap, error) + // CreateCIDRMap creates the datacenter identified by the receiver argument in the specified domain. // // See: https://techdocs.akamai.com/gtm/reference/put-cidr-map - CreateCidrMap(context.Context, *CidrMap, string) (*CidrMapResponse, error) - // DeleteCidrMap deletes the datacenter identified by the receiver argument from the domain specified. + CreateCIDRMap(context.Context, *CIDRMap, string) (*CIDRMapResponse, error) + // DeleteCIDRMap deletes the datacenter identified by the receiver argument from the domain specified. // // See: https://techdocs.akamai.com/gtm/reference/delete-cidr-maps - DeleteCidrMap(context.Context, *CidrMap, string) (*ResponseStatus, error) - // UpdateCidrMap updates the datacenter identified in the receiver argument in the provided domain. + DeleteCIDRMap(context.Context, *CIDRMap, string) (*ResponseStatus, error) + // UpdateCIDRMap updates the datacenter identified in the receiver argument in the provided domain. // // See: https://techdocs.akamai.com/gtm/reference/put-cidr-map - UpdateCidrMap(context.Context, *CidrMap, string) (*ResponseStatus, error) + UpdateCIDRMap(context.Context, *CIDRMap, string) (*ResponseStatus, error) } -// CidrAssignment represents a GTM cidr assignment element -type CidrAssignment struct { +// CIDRAssignment represents a GTM CIDR assignment element +type CIDRAssignment struct { DatacenterBase Blocks []string `json:"blocks"` } -// CidrMap represents a GTM cidrMap element -type CidrMap struct { +// CIDRMap represents a GTM CIDRMap element +type CIDRMap struct { DefaultDatacenter *DatacenterBase `json:"defaultDatacenter"` - Assignments []*CidrAssignment `json:"assignments,omitempty"` + Assignments []*CIDRAssignment `json:"assignments,omitempty"` Name string `json:"name"` Links []*Link `json:"links,omitempty"` } -// CidrMapList represents a GTM returned cidrmap list body -type CidrMapList struct { - CidrMapItems []*CidrMap `json:"items"` +// CIDRMapList represents a GTM returned CIDRMap list body +type CIDRMapList struct { + CIDRMapItems []*CIDRMap `json:"items"` } -// Validate validates CidrMap -func (cidr *CidrMap) Validate() error { - if len(cidr.Name) < 1 { - return fmt.Errorf("CidrMap is missing Name") +// Validate validates CIDRMap +func (c *CIDRMap) Validate() error { + if len(c.Name) < 1 { + return fmt.Errorf("CIDRMap is missing Name") } - if cidr.DefaultDatacenter == nil { - return fmt.Errorf("CidrMap is missing DefaultDatacenter") + if c.DefaultDatacenter == nil { + return fmt.Errorf("CIDRMap is missing DefaultDatacenter") } return nil } -func (p *gtm) NewCidrMap(ctx context.Context, name string) *CidrMap { +func (g *gtm) ListCIDRMaps(ctx context.Context, domainName string) ([]*CIDRMap, error) { + logger := g.Log(ctx) + logger.Debug("ListCIDRMaps") - logger := p.Log(ctx) - logger.Debug("NewCidrMap") - - cidrmap := &CidrMap{Name: name} - return cidrmap -} - -func (p *gtm) ListCidrMaps(ctx context.Context, domainName string) ([]*CidrMap, error) { - - logger := p.Log(ctx) - logger.Debug("ListCidrMaps") - - var cidrs CidrMapList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create ListCidrMaps request: %w", err) + return nil, fmt.Errorf("failed to create ListCIDRMaps request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &cidrs) + + var result CIDRMapList + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("ListCidrMaps request failed: %w", err) + return nil, fmt.Errorf("ListCIDRMaps request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return cidrs.CidrMapItems, nil + return result.CIDRMapItems, nil } -func (p *gtm) GetCidrMap(ctx context.Context, name, domainName string) (*CidrMap, error) { +func (g *gtm) GetCIDRMap(ctx context.Context, mapName, domainName string) (*CIDRMap, error) { + logger := g.Log(ctx) + logger.Debug("GetCIDRMap") - logger := p.Log(ctx) - logger.Debug("GetCidrMap") - - var cidr CidrMap - getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps/%s", domainName, name) + getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps/%s", domainName, mapName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create GetCidrMap request: %w", err) + return nil, fmt.Errorf("failed to create GetCIDRMap request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &cidr) + + var result CIDRMap + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("GetCidrMap request failed: %w", err) + return nil, fmt.Errorf("GetCIDRMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &cidr, nil + return &result, nil } -func (p *gtm) NewCidrAssignment(ctx context.Context, _ *CidrMap, dcid int, nickname string) *CidrAssignment { - - logger := p.Log(ctx) - logger.Debug("NewCidrAssignment") +func (g *gtm) CreateCIDRMap(ctx context.Context, cidr *CIDRMap, domainName string) (*CIDRMapResponse, error) { + logger := g.Log(ctx) + logger.Debug("CreateCIDRMap") - cidrAssign := &CidrAssignment{} - cidrAssign.DatacenterId = dcid - cidrAssign.Nickname = nickname - - return cidrAssign + return cidr.save(ctx, g, domainName) } -func (p *gtm) CreateCidrMap(ctx context.Context, cidr *CidrMap, domainName string) (*CidrMapResponse, error) { - - logger := p.Log(ctx) - logger.Debug("CreateCidrMap") +func (g *gtm) UpdateCIDRMap(ctx context.Context, cidr *CIDRMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) + logger.Debug("UpdateCIDRMap") - // Use common code. Any specific validation needed? - return cidr.save(ctx, p, domainName) -} - -func (p *gtm) UpdateCidrMap(ctx context.Context, cidr *CidrMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) - logger.Debug("UpdateCidrMap") - - // common code - stat, err := cidr.save(ctx, p, domainName) + stat, err := cidr.save(ctx, g, domainName) if err != nil { return nil, err } return stat.Status, err } -// Save CidrMap in given domain. Common path for Create and Update. -func (cidr *CidrMap) save(ctx context.Context, p *gtm, domainName string) (*CidrMapResponse, error) { +// Save CIDRMap in given domain. Common path for Create and Update. +func (c *CIDRMap) save(ctx context.Context, g *gtm, domainName string) (*CIDRMapResponse, error) { - if err := cidr.Validate(); err != nil { - return nil, fmt.Errorf("CidrMap validation failed. %w", err) + if err := c.Validate(); err != nil { + return nil, fmt.Errorf("CIDRMap validation failed. %w", err) } - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps/%s", domainName, cidr.Name) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps/%s", domainName, c.Name) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { - return nil, fmt.Errorf("failed to create AsMap request: %w", err) + return nil, fmt.Errorf("failed to create CIDRMap request: %w", err) } - - var mapresp CidrMapResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp, cidr) + + var result CIDRMapResponse + resp, err := g.Exec(req, &result, c) if err != nil { - return nil, fmt.Errorf("CidrMap request failed: %w", err) + return nil, fmt.Errorf("CIDRMap request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &mapresp, nil + return &result, nil } -func (p *gtm) DeleteCidrMap(ctx context.Context, cidr *CidrMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) - logger.Debug("DeleteCidrMap") +func (g *gtm) DeleteCIDRMap(ctx context.Context, cidr *CIDRMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) + logger.Debug("DeleteCIDRMap") if err := cidr.Validate(); err != nil { - logger.Errorf("CidrMap validation failed. %w", err) - return nil, fmt.Errorf("CidrMap validation failed. %w", err) + return nil, fmt.Errorf("CIDRMap validation failed. %w", err) } delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/cidr-maps/%s", domainName, cidr.Name) @@ -203,17 +167,17 @@ func (p *gtm) DeleteCidrMap(ctx context.Context, cidr *CidrMap, domainName strin if err != nil { return nil, fmt.Errorf("failed to create Delete request: %w", err) } - - var mapresp ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp) + + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("CidrMap request failed: %w", err) + return nil, fmt.Errorf("CIDRMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return mapresp.Status, nil + return result.Status, nil } diff --git a/pkg/gtm/cidrmap_test.go b/pkg/gtm/cidrmap_test.go index 04835061..17fa558d 100644 --- a/pkg/gtm/cidrmap_test.go +++ b/pkg/gtm/cidrmap_test.go @@ -9,23 +9,15 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewCidrMap(t *testing.T) { - client := Client(session.Must(session.New())) +func TestGTM_ListCIDRMaps(t *testing.T) { + var result CIDRMapList - cmap := client.NewCidrMap(context.Background(), "foo") - - assert.Equal(t, "foo", cmap.Name) -} - -func TestGtm_ListCidrMaps(t *testing.T) { - var result CidrMapList - - respData, err := loadTestData("TestGtm_ListCidrMap.resp.json") + respData, err := loadTestData("TestGTM_ListCIDRMap.resp.json") if err != nil { t.Fatal(err) } @@ -39,7 +31,7 @@ func TestGtm_ListCidrMaps(t *testing.T) { responseStatus int responseBody string expectedPath string - expectedResponse []*CidrMap + expectedResponse []*CIDRMap withError error headers http.Header }{ @@ -51,7 +43,7 @@ func TestGtm_ListCidrMaps(t *testing.T) { responseStatus: http.StatusOK, responseBody: string(respData), expectedPath: "/config-gtm/v1/domains/example.akadns.net/cidr-maps", - expectedResponse: result.CidrMapItems, + expectedResponse: result.CIDRMapItems, }, "500 internal server error": { domainName: "example.akadns.net", @@ -84,7 +76,7 @@ func TestGtm_ListCidrMaps(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.ListCidrMaps( + result, err := client.ListCIDRMaps( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.domainName) @@ -98,10 +90,10 @@ func TestGtm_ListCidrMaps(t *testing.T) { } } -func TestGtm_GetCidrMap(t *testing.T) { - var result CidrMap +func TestGTM_GetCIDRMap(t *testing.T) { + var result CIDRMap - respData, err := loadTestData("TestGtm_GetCidrMap.resp.json") + respData, err := loadTestData("TestGTM_GetCIDRMap.resp.json") if err != nil { t.Fatal(err) } @@ -116,7 +108,7 @@ func TestGtm_GetCidrMap(t *testing.T) { responseStatus int responseBody string expectedPath string - expectedResponse *CidrMap + expectedResponse *CIDRMap withError error headers http.Header }{ @@ -163,7 +155,7 @@ func TestGtm_GetCidrMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.GetCidrMap( + result, err := client.GetCIDRMap( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.name, test.domainName) @@ -177,20 +169,11 @@ func TestGtm_GetCidrMap(t *testing.T) { } } -func TestGtm_NewCidrAssignment(t *testing.T) { - client := Client(session.Must(session.New())) - - asn := client.NewCidrAssignment(context.Background(), nil, 100, "foo") - - assert.Equal(t, 100, asn.DatacenterId) - assert.Equal(t, "foo", asn.Nickname) -} - -func TestGtm_CreateCidrMap(t *testing.T) { - var result CidrMapResponse - var req CidrMap +func TestGTM_CreateCIDRMap(t *testing.T) { + var result CIDRMapResponse + var req CIDRMap - respData, err := loadTestData("TestGtm_CreateCidrMap.resp.json") + respData, err := loadTestData("TestGTM_CreateCIDRMap.resp.json") if err != nil { t.Fatal(err) } @@ -199,7 +182,7 @@ func TestGtm_CreateCidrMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateCidrMap.req.json") + reqData, err := loadTestData("TestGTM_CreateCIDRMap.req.json") if err != nil { t.Fatal(err) } @@ -209,12 +192,12 @@ func TestGtm_CreateCidrMap(t *testing.T) { } tests := map[string]struct { - cmap *CidrMap + cmap *CIDRMap domainName string responseStatus int responseBody string expectedPath string - expectedResponse *CidrMapResponse + expectedResponse *CIDRMapResponse withError error headers http.Header }{ @@ -260,7 +243,7 @@ func TestGtm_CreateCidrMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.CreateCidrMap( + result, err := client.CreateCIDRMap( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.cmap, test.domainName) @@ -274,11 +257,11 @@ func TestGtm_CreateCidrMap(t *testing.T) { } } -func TestGtm_UpdateCidrMap(t *testing.T) { - var result CidrMapResponse - var req CidrMap +func TestGTM_UpdateCIDRMap(t *testing.T) { + var result CIDRMapResponse + var req CIDRMap - respData, err := loadTestData("TestGtm_CreateCidrMap.resp.json") + respData, err := loadTestData("TestGTM_CreateCIDRMap.resp.json") if err != nil { t.Fatal(err) } @@ -287,7 +270,7 @@ func TestGtm_UpdateCidrMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateCidrMap.req.json") + reqData, err := loadTestData("TestGTM_CreateCIDRMap.req.json") if err != nil { t.Fatal(err) } @@ -297,7 +280,7 @@ func TestGtm_UpdateCidrMap(t *testing.T) { } tests := map[string]struct { - cmap *CidrMap + cmap *CIDRMap domainName string responseStatus int responseBody string @@ -348,7 +331,7 @@ func TestGtm_UpdateCidrMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.UpdateCidrMap( + result, err := client.UpdateCIDRMap( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.cmap, test.domainName) @@ -362,11 +345,11 @@ func TestGtm_UpdateCidrMap(t *testing.T) { } } -func TestGtm_DeleteCidrMap(t *testing.T) { - var result CidrMapResponse - var req CidrMap +func TestGTM_DeleteCIDRMap(t *testing.T) { + var result CIDRMapResponse + var req CIDRMap - respData, err := loadTestData("TestGtm_CreateCidrMap.resp.json") + respData, err := loadTestData("TestGTM_CreateCIDRMap.resp.json") if err != nil { t.Fatal(err) } @@ -375,7 +358,7 @@ func TestGtm_DeleteCidrMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateCidrMap.req.json") + reqData, err := loadTestData("TestGTM_CreateCIDRMap.req.json") if err != nil { t.Fatal(err) } @@ -385,7 +368,7 @@ func TestGtm_DeleteCidrMap(t *testing.T) { } tests := map[string]struct { - cmap *CidrMap + cmap *CIDRMap domainName string responseStatus int responseBody string @@ -436,7 +419,7 @@ func TestGtm_DeleteCidrMap(t *testing.T) { assert.NoError(t, err) })) client := mockAPIClient(t, mockServer) - result, err := client.DeleteCidrMap( + result, err := client.DeleteCIDRMap( session.ContextWithOptions( context.Background(), session.WithContextHeaders(test.headers)), test.cmap, test.domainName) diff --git a/pkg/gtm/common.go b/pkg/gtm/common.go index 3b0a7b3d..c83c5858 100644 --- a/pkg/gtm/common.go +++ b/pkg/gtm/common.go @@ -5,28 +5,8 @@ import ( "net/http" ) -// -// Common data types and methods -// Based on 1.3 schemas -// - -// Append url args to req -func appendReqArgs(req *http.Request, queryArgs map[string]string) { - - // Look for optional args - if len(queryArgs) > 0 { - q := req.URL.Query() - for argName, argVal := range queryArgs { - q.Add(argName, argVal) - } - req.URL.RawQuery = q.Encode() - } - -} - // default schema version -// TODO: retrieve from environment or elsewhere in Service Init -var schemaVersion = "1.4" +var schemaVersion = "1.6" // internal method to set version. passed in as string func setVersionHeader(req *http.Request, version string) { @@ -41,14 +21,9 @@ func setVersionHeader(req *http.Request, version string) { } -// NewDefaultDatacenter instantiates new Default Datacenter Struct -func (p *gtm) NewDefaultDatacenter(dcid int) *DatacenterBase { - return &DatacenterBase{DatacenterId: dcid} -} - // ResponseStatus is returned on Create, Update or Delete operations for all entity types type ResponseStatus struct { - ChangeId string `json:"changeId,omitempty"` + ChangeID string `json:"changeId,omitempty"` Links *[]Link `json:"links,omitempty"` Message string `json:"message,omitempty"` PassingValidation bool `json:"passingValidation,omitempty"` @@ -56,13 +31,6 @@ type ResponseStatus struct { PropagationStatusDate string `json:"propagationStatusDate,omitempty"` } -// NewResponseStatus returns a new ResponseStatus struct -func NewResponseStatus() *ResponseStatus { - - return &ResponseStatus{} - -} - // ResponseBody is a generic response struct type ResponseBody struct { Resource interface{} `json:"resource"` @@ -93,9 +61,9 @@ type ResourceResponse struct { Status *ResponseStatus `json:"status"` } -// CidrMapResponse contains a response after creating or updating CidrMap -type CidrMapResponse struct { - Resource *CidrMap `json:"resource"` +// CIDRMapResponse contains a response after creating or updating CIDRMap +type CIDRMapResponse struct { + Resource *CIDRMap `json:"resource"` Status *ResponseStatus `json:"status"` } @@ -105,9 +73,9 @@ type GeoMapResponse struct { Status *ResponseStatus `json:"status"` } -// AsMapResponse contains a response after creating or updating AsMap -type AsMapResponse struct { - Resource *AsMap `json:"resource"` +// ASMapResponse contains a response after creating or updating ASMap +type ASMapResponse struct { + Resource *ASMap `json:"resource"` Status *ResponseStatus `json:"status"` } @@ -124,18 +92,8 @@ type LoadObject struct { LoadServers []string `json:"loadServers,omitempty"` } -// NewLoadObject returns a new LoadObject structure -func NewLoadObject() *LoadObject { - return &LoadObject{} -} - // DatacenterBase is a placeholder for default Datacenter type DatacenterBase struct { Nickname string `json:"nickname,omitempty"` - DatacenterId int `json:"datacenterId"` -} - -// NewDatacenterBase returns a new DatacenterBase structure -func NewDatacenterBase() *DatacenterBase { - return &DatacenterBase{} + DatacenterID int `json:"datacenterId"` } diff --git a/pkg/gtm/datacenter.go b/pkg/gtm/datacenter.go index 20e43e95..39b52078 100644 --- a/pkg/gtm/datacenter.go +++ b/pkg/gtm/datacenter.go @@ -8,17 +8,8 @@ import ( "strconv" ) -// -// Handle Operations on gtm datacenters -// Based on 1.4 schema -// - // Datacenters contains operations available on a Datacenter resource. type Datacenters interface { - // NewDatacenterResponse instantiates a new DatacenterResponse structure. - NewDatacenterResponse(context.Context) *DatacenterResponse - // NewDatacenter creates a new Datacenter object. - NewDatacenter(context.Context) *Datacenter // ListDatacenters retrieves all Datacenters. // // See: https://techdocs.akamai.com/gtm/reference/get-datacenters @@ -62,7 +53,7 @@ type Datacenter struct { Nickname string `json:"nickname,omitempty"` PingInterval int `json:"pingInterval,omitempty"` PingPacketSize int `json:"pingPacketSize,omitempty"` - DatacenterId int `json:"datacenterId,omitempty"` + DatacenterID int `json:"datacenterId,omitempty"` ScorePenalty int `json:"scorePenalty,omitempty"` ServermonitorLivenessCount int `json:"servermonitorLivenessCount,omitempty"` ServermonitorLoadCount int `json:"servermonitorLoadCount,omitempty"` @@ -76,75 +67,56 @@ type DatacenterList struct { DatacenterItems []*Datacenter `json:"items"` } -func (p *gtm) NewDatacenterResponse(ctx context.Context) *DatacenterResponse { - - logger := p.Log(ctx) - logger.Debug("NewDatacenterResponse") - - dcResp := &DatacenterResponse{} - return dcResp -} - -func (p *gtm) NewDatacenter(ctx context.Context) *Datacenter { - - logger := p.Log(ctx) - logger.Debug("NewDatacenter") - - dc := &Datacenter{} - return dc -} - -func (p *gtm) ListDatacenters(ctx context.Context, domainName string) ([]*Datacenter, error) { - - logger := p.Log(ctx) +func (g *gtm) ListDatacenters(ctx context.Context, domainName string) ([]*Datacenter, error) { + logger := g.Log(ctx) logger.Debug("ListDatacenters") - var dcs DatacenterList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListDatacenters request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dcs) + + var result DatacenterList + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListDatacenters request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return dcs.DatacenterItems, nil + return result.DatacenterItems, nil } -func (p *gtm) GetDatacenter(ctx context.Context, dcID int, domainName string) (*Datacenter, error) { - - logger := p.Log(ctx) +func (g *gtm) GetDatacenter(ctx context.Context, dcID int, domainName string) (*Datacenter, error) { + logger := g.Log(ctx) logger.Debug("GetDatacenter") - var dc Datacenter getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters/%s", domainName, strconv.Itoa(dcID)) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetDatacenter request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dc) + + var result Datacenter + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetDatacenter request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &dc, nil + return &result, nil } -func (p *gtm) CreateDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*DatacenterResponse, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*DatacenterResponse, error) { + logger := g.Log(ctx) logger.Debug("CreateDatacenter") postURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters", domainName) @@ -152,18 +124,18 @@ func (p *gtm) CreateDatacenter(ctx context.Context, dc *Datacenter, domainName s if err != nil { return nil, fmt.Errorf("failed to create Datacenter request: %w", err) } - - var dcresp DatacenterResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dcresp, dc) + + var result DatacenterResponse + resp, err := g.Exec(req, &result, dc) if err != nil { - return nil, fmt.Errorf("Datacenter request failed: %w", err) + return nil, fmt.Errorf("CreateDatacenter request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &dcresp, nil + return &result, nil } var ( @@ -175,43 +147,38 @@ var ( Ipv6DefaultDC = 5402 ) -func (p *gtm) CreateMapsDefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateMapsDefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { + logger := g.Log(ctx) logger.Debug("CreateMapsDefaultDatacenter") - return createDefaultDC(ctx, p, MapDefaultDC, domainName) + return createDefaultDC(ctx, g, MapDefaultDC, domainName) } -func (p *gtm) CreateIPv4DefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateIPv4DefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { + logger := g.Log(ctx) logger.Debug("CreateIPv4DefaultDatacenter") - return createDefaultDC(ctx, p, Ipv4DefaultDC, domainName) + return createDefaultDC(ctx, g, Ipv4DefaultDC, domainName) } -func (p *gtm) CreateIPv6DefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateIPv6DefaultDatacenter(ctx context.Context, domainName string) (*Datacenter, error) { + logger := g.Log(ctx) logger.Debug("CreateIPv6DefaultDatacenter") - return createDefaultDC(ctx, p, Ipv6DefaultDC, domainName) + return createDefaultDC(ctx, g, Ipv6DefaultDC, domainName) } // createDefaultDC is worker function used to create Default Datacenter identified id in the specified domain. -func createDefaultDC(ctx context.Context, p *gtm, defaultID int, domainName string) (*Datacenter, error) { - +func createDefaultDC(ctx context.Context, g *gtm, defaultID int, domainName string) (*Datacenter, error) { if defaultID != MapDefaultDC && defaultID != Ipv4DefaultDC && defaultID != Ipv6DefaultDC { - return nil, fmt.Errorf("Invalid default datacenter id provided for creation") + return nil, fmt.Errorf("invalid default datacenter id provided for creation") } // check if already exists - dc, err := p.GetDatacenter(ctx, defaultID, domainName) + dc, err := g.GetDatacenter(ctx, defaultID, domainName) if err == nil { return dc, err } apiError, ok := err.(*Error) - //if !strings.Contains(err.Error(), "not found") || !strings.Contains(err.Error(), "Datacenter") { if !ok || apiError.StatusCode != http.StatusNotFound { return nil, err } @@ -231,64 +198,61 @@ func createDefaultDC(ctx context.Context, p *gtm, defaultID int, domainName stri return nil, fmt.Errorf("failed to create Default Datacenter request: %w", err) } - var dcresp DatacenterResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dcresp, "") + var result DatacenterResponse + resp, err := g.Exec(req, &result, "") if err != nil { - return nil, fmt.Errorf("Default Datacenter request failed: %w", err) + return nil, fmt.Errorf("DefaultDatacenter request failed: %w", err) } if resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return dcresp.Resource, nil - + return result.Resource, nil } -func (p *gtm) UpdateDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) UpdateDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("UpdateDatacenter") - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters/%s", domainName, strconv.Itoa(dc.DatacenterId)) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters/%s", domainName, strconv.Itoa(dc.DatacenterID)) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Update Datacenter request: %w", err) } - var dcresp DatacenterResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dcresp, dc) + var result DatacenterResponse + resp, err := g.Exec(req, &result, dc) if err != nil { - return nil, fmt.Errorf("Datacenter request failed: %w", err) + return nil, fmt.Errorf("UpdateDatacenter request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return dcresp.Status, nil + return result.Status, nil } -func (p *gtm) DeleteDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) DeleteDatacenter(ctx context.Context, dc *Datacenter, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("DeleteDatacenter") - delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters/%s", domainName, strconv.Itoa(dc.DatacenterId)) + delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/datacenters/%s", domainName, strconv.Itoa(dc.DatacenterID)) req, err := http.NewRequestWithContext(ctx, http.MethodDelete, delURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Delete Datacenter request: %w", err) } - - var dcresp DatacenterResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &dcresp) + + var result DatacenterResponse + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("Datacenter request failed: %w", err) + return nil, fmt.Errorf("DeleteDatacenter request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return dcresp.Status, nil + return result.Status, nil } diff --git a/pkg/gtm/datacenter_test.go b/pkg/gtm/datacenter_test.go index bed698ed..b6f894c8 100644 --- a/pkg/gtm/datacenter_test.go +++ b/pkg/gtm/datacenter_test.go @@ -9,31 +9,15 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewDatacenterResponse(t *testing.T) { - client := Client(session.Must(session.New())) - - dcr := client.NewDatacenterResponse(context.Background()) - - assert.NotNil(t, dcr) -} - -func TestGtm_NewDatacenter(t *testing.T) { - client := Client(session.Must(session.New())) - - dc := client.NewDatacenter(context.Background()) - - assert.NotNil(t, dc) -} - -func TestGtm_ListDatacenters(t *testing.T) { +func TestGTM_ListDatacenters(t *testing.T) { var result DatacenterList - respData, err := loadTestData("TestGtm_ListDatacenters.resp.json") + respData, err := loadTestData("TestGTM_ListDatacenters.resp.json") if err != nil { t.Fatal(err) } @@ -105,10 +89,10 @@ func TestGtm_ListDatacenters(t *testing.T) { } } -func TestGtm_GetDatacenter(t *testing.T) { +func TestGTM_GetDatacenter(t *testing.T) { var result Datacenter - respData, err := loadTestData("TestGtm_GetDatacenter.resp.json") + respData, err := loadTestData("TestGTM_GetDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -183,11 +167,11 @@ func TestGtm_GetDatacenter(t *testing.T) { } } -func TestGtm_CreateDatacenter(t *testing.T) { +func TestGTM_CreateDatacenter(t *testing.T) { var result DatacenterResponse var req Datacenter - respData, err := loadTestData("TestGtm_CreateDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -196,7 +180,7 @@ func TestGtm_CreateDatacenter(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateDatacenter.req.json") + reqData, err := loadTestData("TestGTM_CreateDatacenter.req.json") if err != nil { t.Fatal(err) } @@ -271,10 +255,10 @@ func TestGtm_CreateDatacenter(t *testing.T) { } } -func TestGtm_CreateMapsDefaultDatacenter(t *testing.T) { +func TestGTM_CreateMapsDefaultDatacenter(t *testing.T) { var result DatacenterResponse - respData, err := loadTestData("TestGtm_CreateMapsDefaultDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateMapsDefaultDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -356,10 +340,10 @@ func TestGtm_CreateMapsDefaultDatacenter(t *testing.T) { } } -func TestGtm_CreateIPv4DefaultDatacenter(t *testing.T) { +func TestGTM_CreateIPv4DefaultDatacenter(t *testing.T) { var result DatacenterResponse - respData, err := loadTestData("TestGtm_CreateIPv4DefaultDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateIPv4DefaultDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -441,10 +425,10 @@ func TestGtm_CreateIPv4DefaultDatacenter(t *testing.T) { } } -func TestGtm_CreateIPv6DefaultDatacenter(t *testing.T) { +func TestGTM_CreateIPv6DefaultDatacenter(t *testing.T) { var result DatacenterResponse - respData, err := loadTestData("TestGtm_CreateIPv6DefaultDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateIPv6DefaultDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -526,11 +510,11 @@ func TestGtm_CreateIPv6DefaultDatacenter(t *testing.T) { } } -func TestGtm_UpdateDatacenter(t *testing.T) { +func TestGTM_UpdateDatacenter(t *testing.T) { var result DatacenterResponse var req Datacenter - respData, err := loadTestData("TestGtm_CreateDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -539,7 +523,7 @@ func TestGtm_UpdateDatacenter(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateDatacenter.req.json") + reqData, err := loadTestData("TestGTM_CreateDatacenter.req.json") if err != nil { t.Fatal(err) } @@ -614,11 +598,11 @@ func TestGtm_UpdateDatacenter(t *testing.T) { } } -func TestGtm_DeleteDatacenter(t *testing.T) { +func TestGTM_DeleteDatacenter(t *testing.T) { var result DatacenterResponse var req Datacenter - respData, err := loadTestData("TestGtm_CreateDatacenter.resp.json") + respData, err := loadTestData("TestGTM_CreateDatacenter.resp.json") if err != nil { t.Fatal(err) } @@ -627,7 +611,7 @@ func TestGtm_DeleteDatacenter(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateDatacenter.req.json") + reqData, err := loadTestData("TestGTM_CreateDatacenter.req.json") if err != nil { t.Fatal(err) } diff --git a/pkg/gtm/domain.go b/pkg/gtm/domain.go index 8ef30417..2ea8af34 100644 --- a/pkg/gtm/domain.go +++ b/pkg/gtm/domain.go @@ -10,18 +10,11 @@ import ( "unicode" ) -// -// Support gtm domains thru Edgegrid -// Based on 1.4 Schema -// - // Domains contains operations available on a Domain resource. type Domains interface { // NullFieldMap retrieves map of null fields. NullFieldMap(context.Context, *Domain) (*NullFieldMapStruct, error) - // NewDomain is a utility function that creates a new Domain object. - NewDomain(context.Context, string, string) *Domain - // GetDomainStatus retrieves current status for the given domainname. + // GetDomainStatus retrieves current status for the given domain name. // // See: https://techdocs.akamai.com/gtm/reference/get-status-current GetDomainStatus(context.Context, string) (*ResponseStatus, error) @@ -51,7 +44,7 @@ type Domains interface { type Domain struct { Name string `json:"name"` Type string `json:"type"` - AsMaps []*AsMap `json:"asMaps,omitempty"` + ASMaps []*ASMap `json:"asMaps,omitempty"` Resources []*Resource `json:"resources,omitempty"` DefaultUnreachableThreshold float32 `json:"defaultUnreachableThreshold,omitempty"` EmailNotificationList []string `json:"emailNotificationList,omitempty"` @@ -70,26 +63,28 @@ type Domain struct { MapUpdateInterval int `json:"mapUpdateInterval,omitempty"` MaxProperties int `json:"maxProperties,omitempty"` MaxResources int `json:"maxResources,omitempty"` - DefaultSslClientPrivateKey string `json:"defaultSslClientPrivateKey,omitempty"` + DefaultSSLClientPrivateKey string `json:"defaultSslClientPrivateKey,omitempty"` DefaultErrorPenalty int `json:"defaultErrorPenalty,omitempty"` Links []*Link `json:"links,omitempty"` Properties []*Property `json:"properties,omitempty"` MaxTestTimeout float64 `json:"maxTestTimeout,omitempty"` - CnameCoalescingEnabled bool `json:"cnameCoalescingEnabled"` + CNameCoalescingEnabled bool `json:"cnameCoalescingEnabled"` DefaultHealthMultiplier float64 `json:"defaultHealthMultiplier,omitempty"` ServermonitorPool string `json:"servermonitorPool,omitempty"` LoadFeedback bool `json:"loadFeedback"` MinTTL int64 `json:"minTTL,omitempty"` GeographicMaps []*GeoMap `json:"geographicMaps,omitempty"` - CidrMaps []*CidrMap `json:"cidrMaps,omitempty"` + CIDRMaps []*CIDRMap `json:"cidrMaps,omitempty"` DefaultMaxUnreachablePenalty int `json:"defaultMaxUnreachablePenalty"` DefaultHealthThreshold float64 `json:"defaultHealthThreshold,omitempty"` LastModifiedBy string `json:"lastModifiedBy,omitempty"` ModificationComments string `json:"modificationComments,omitempty"` MinTestInterval int `json:"minTestInterval,omitempty"` PingPacketSize int `json:"pingPacketSize,omitempty"` - DefaultSslClientCertificate string `json:"defaultSslClientCertificate,omitempty"` + DefaultSSLClientCertificate string `json:"defaultSslClientCertificate,omitempty"` EndUserMappingEnabled bool `json:"endUserMappingEnabled"` + SignAndServe bool `json:"signAndServe"` + SignAndServeAlgorithm *string `json:"signAndServeAlgorithm"` } // DomainsList contains a list of domain items @@ -99,7 +94,7 @@ type DomainsList struct { // DomainItem is a DomainsList item type DomainItem struct { - AcgId string `json:"acgId"` + AcgID string `json:"acgId"` LastModified string `json:"lastModified"` Links []*Link `json:"links"` Name string `json:"name"` @@ -114,104 +109,91 @@ type DomainItem struct { } // Validate validates Domain -func (dom *Domain) Validate() error { - - if len(dom.Name) < 1 { +func (d *Domain) Validate() error { + if len(d.Name) < 1 { return fmt.Errorf("Domain is missing Name") } - if len(dom.Type) < 1 { + if len(d.Type) < 1 { return fmt.Errorf("Domain is missing Type") } return nil } -func (p *gtm) NewDomain(ctx context.Context, domainName, domainType string) *Domain { - - logger := p.Log(ctx) - logger.Debug("NewDomain") - - domain := &Domain{} - domain.Name = domainName - domain.Type = domainType - return domain -} - -func (p *gtm) GetDomainStatus(ctx context.Context, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) GetDomainStatus(ctx context.Context, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("GetDomainStatus") - var stat ResponseStatus getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/status/current", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetDomain request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &stat) + + var result ResponseStatus + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetDomain request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &stat, nil + return &result, nil } -func (p *gtm) ListDomains(ctx context.Context) ([]*DomainItem, error) { - - logger := p.Log(ctx) +func (g *gtm) ListDomains(ctx context.Context) ([]*DomainItem, error) { + logger := g.Log(ctx) logger.Debug("ListDomains") - var domains DomainsList getURL := fmt.Sprintf("/config-gtm/v1/domains") req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListDomains request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &domains) + + var result DomainsList + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListDomains request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return domains.DomainItems, nil + return result.DomainItems, nil } -func (p *gtm) GetDomain(ctx context.Context, domainName string) (*Domain, error) { - - logger := p.Log(ctx) +func (g *gtm) GetDomain(ctx context.Context, domainName string) (*Domain, error) { + logger := g.Log(ctx) logger.Debug("GetDomain") - var domain Domain getURL := fmt.Sprintf("/config-gtm/v1/domains/%s", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetDomain request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &domain) + + var result Domain + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetDomain request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &domain, nil + return &result, nil } // save method; Create or Update -func (dom *Domain) save(_ context.Context, p *gtm, queryArgs map[string]string, req *http.Request) (*DomainResponse, error) { - +func (d *Domain) save(_ context.Context, g *gtm, queryArgs map[string]string, req *http.Request) (*DomainResponse, error) { // set schema version setVersionHeader(req, schemaVersion) @@ -227,28 +209,25 @@ func (dom *Domain) save(_ context.Context, p *gtm, queryArgs map[string]string, req.URL.RawQuery = q.Encode() } - var dresp DomainResponse - resp, err := p.Exec(req, &dresp, dom) + var result DomainResponse + resp, err := g.Exec(req, &result, d) if err != nil { - return nil, fmt.Errorf("Domain request failed: %w", err) + return nil, fmt.Errorf("domain request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &dresp, nil - + return &result, nil } -func (p *gtm) CreateDomain(ctx context.Context, domain *Domain, queryArgs map[string]string) (*DomainResponse, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateDomain(ctx context.Context, domain *Domain, queryArgs map[string]string) (*DomainResponse, error) { + logger := g.Log(ctx) logger.Debug("CreateDomain") if err := domain.Validate(); err != nil { - logger.Errorf("Domain validation failed. %w", err) - return nil, fmt.Errorf("Domain validation failed. %w", err) + return nil, fmt.Errorf("CreateDomain validation failed. %w", err) } postURL := fmt.Sprintf("/config-gtm/v1/domains/") @@ -257,18 +236,15 @@ func (p *gtm) CreateDomain(ctx context.Context, domain *Domain, queryArgs map[st return nil, fmt.Errorf("failed to create CreateDomain request: %w", err) } - return domain.save(ctx, p, queryArgs, req) - + return domain.save(ctx, g, queryArgs, req) } -func (p *gtm) UpdateDomain(ctx context.Context, domain *Domain, queryArgs map[string]string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) UpdateDomain(ctx context.Context, domain *Domain, queryArgs map[string]string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("UpdateDomain") if err := domain.Validate(); err != nil { - logger.Errorf("Domain validation failed. %w", err) - return nil, fmt.Errorf("Domain validation failed. %w", err) + return nil, fmt.Errorf("UpdateDomain validation failed. %w", err) } putURL := fmt.Sprintf("/config-gtm/v1/domains/%s", domain.Name) @@ -277,16 +253,15 @@ func (p *gtm) UpdateDomain(ctx context.Context, domain *Domain, queryArgs map[st return nil, fmt.Errorf("failed to create UpdateDomain request: %w", err) } - stat, err := domain.save(ctx, p, queryArgs, req) + stat, err := domain.save(ctx, g, queryArgs, req) if err != nil { return nil, err } return stat.Status, err } -func (p *gtm) DeleteDomain(ctx context.Context, domain *Domain) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) DeleteDomain(ctx context.Context, domain *Domain) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("DeleteDomain") delURL := fmt.Sprintf("/config-gtm/v1/domains/%s", domain.Name) @@ -294,20 +269,19 @@ func (p *gtm) DeleteDomain(ctx context.Context, domain *Domain) (*ResponseStatus if err != nil { return nil, fmt.Errorf("failed to create DeleteDomain request: %w", err) } - - var responseBody ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &responseBody) + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("Delete Domain request failed: %w", err) + return nil, fmt.Errorf("DeleteDomain request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return responseBody.Status, nil + return result.Status, nil } // NullPerObjectAttributeStruct represents core and child null object attributes @@ -330,14 +304,12 @@ type NullFieldMapStruct struct { // ObjectMap represents ObjectMap datatype type ObjectMap map[string]interface{} -func (p *gtm) NullFieldMap(ctx context.Context, domain *Domain) (*NullFieldMapStruct, error) { - - logger := p.Log(ctx) +func (g *gtm) NullFieldMap(ctx context.Context, domain *Domain) (*NullFieldMapStruct, error) { + logger := g.Log(ctx) logger.Debug("NullFieldMap") if err := domain.Validate(); err != nil { - logger.Errorf("Domain validation failed. %w", err) - return nil, fmt.Errorf("Domain validation failed. %w", err) + return nil, fmt.Errorf("domain validation failed. %w", err) } var nullFieldMap = &NullFieldMapStruct{} @@ -351,19 +323,19 @@ func (p *gtm) NullFieldMap(ctx context.Context, domain *Domain) (*NullFieldMapSt return nil, fmt.Errorf("failed to create GetDomain request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &objMap) + resp, err := g.Exec(req, &objMap) if err != nil { return nil, fmt.Errorf("GetDomain request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } for i, d := range objMap { - objval := fmt.Sprint(d) + objVal := fmt.Sprint(d) if fmt.Sprintf("%T", d) == "" { - if objval == "" { + if objVal == "" { domainMap[makeFirstCharUpperCase(i)] = "" } continue @@ -397,7 +369,6 @@ func (p *gtm) NullFieldMap(ctx context.Context, domain *Domain) (*NullFieldMapSt } func makeFirstCharUpperCase(origString string) string { - a := []rune(origString) a[0] = unicode.ToUpper(a[0]) // hack @@ -408,7 +379,6 @@ func makeFirstCharUpperCase(origString string) string { } func processObjectList(objectList []interface{}) map[string]NullPerObjectAttributeStruct { - nullObjectsList := make(map[string]NullPerObjectAttributeStruct) for _, obj := range objectList { nullObjectFields := NullPerObjectAttributeStruct{} @@ -416,31 +386,31 @@ func processObjectList(objectList []interface{}) map[string]NullPerObjectAttribu objectDCID := "" objectMap := make(map[string]string) objectChildList := make(map[string]interface{}) - for objf, objd := range obj.(map[string]interface{}) { - objval := fmt.Sprint(objd) - switch fmt.Sprintf("%T", objd) { + for objF, objD := range obj.(map[string]interface{}) { + objVal := fmt.Sprint(objD) + switch fmt.Sprintf("%T", objD) { case "": - if objval == "" { - objectMap[makeFirstCharUpperCase(objf)] = "" + if objVal == "" { + objectMap[makeFirstCharUpperCase(objF)] = "" } case "map[string]interface {}": // include null stand alone struct elements in core - for moname, movalue := range objd.(map[string]interface{}) { - if fmt.Sprintf("%T", movalue) == "" { - objectMap[makeFirstCharUpperCase(moname)] = "" + for moName, moValue := range objD.(map[string]interface{}) { + if fmt.Sprintf("%T", moValue) == "" { + objectMap[makeFirstCharUpperCase(moName)] = "" } } case "[]interface {}": - iSlice := objd.([]interface{}) + iSlice := objD.([]interface{}) if len(iSlice) > 0 && reflect.TypeOf(iSlice[0]).Kind() != reflect.String && reflect.TypeOf(iSlice[0]).Kind() != reflect.Int64 && reflect.TypeOf(iSlice[0]).Kind() != reflect.Float64 && reflect.TypeOf(iSlice[0]).Kind() != reflect.Int32 { - objectChildList[makeFirstCharUpperCase(objf)] = processObjectList(objd.([]interface{})) + objectChildList[makeFirstCharUpperCase(objF)] = processObjectList(objD.([]interface{})) } default: - if objf == "name" { - objectName = objval + if objF == "name" { + objectName = objVal } - if objf == "datacenterId" { - objectDCID = objval + if objF == "datacenterId" { + objectDCID = objVal } } } @@ -459,5 +429,4 @@ func processObjectList(objectList []interface{}) map[string]NullPerObjectAttribu } return nullObjectsList - } diff --git a/pkg/gtm/domain_test.go b/pkg/gtm/domain_test.go index 98fcd220..ec0f8ef6 100644 --- a/pkg/gtm/domain_test.go +++ b/pkg/gtm/domain_test.go @@ -10,21 +10,12 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewDomain(t *testing.T) { - client := Client(session.Must(session.New())) - - dom := client.NewDomain(context.Background(), "example.com", "primary") - - assert.Equal(t, "example.com", dom.Name) - assert.Equal(t, "primary", dom.Type) -} - -func TestGtm_ListDomains(t *testing.T) { +func TestGTM_ListDomains(t *testing.T) { tests := map[string]struct { responseStatus int responseBody string @@ -75,7 +66,7 @@ func TestGtm_ListDomains(t *testing.T) { }]}`, expectedPath: "/config-gtm/v1/domains", expectedResponse: []*DomainItem{{ - AcgId: "1-2345", + AcgID: "1-2345", LastModified: "2014-03-03T16:02:45.000+0000", Name: "example.akadns.net", Status: "2014-02-20 22:56 GMT: Current configuration has been propagated to all GTM name servers", @@ -92,7 +83,7 @@ func TestGtm_ListDomains(t *testing.T) { }}, }, { - AcgId: "1-2345", + AcgID: "1-2345", LastModified: "2013-11-09T12:04:45.000+0000", Name: "demo.akadns.net", Status: "2014-02-20 22:56 GMT: Current configuration has been propagated to all GTM name servers", @@ -188,17 +179,17 @@ func TestGtm_ListDomains(t *testing.T) { } } -func TestGtm_NullFieldMap(t *testing.T) { +func TestGTM_NullFieldMap(t *testing.T) { var result NullFieldMapStruct gob.Register(map[string]NullPerObjectAttributeStruct{}) - respData, err := loadTestData("TestGtm_NullFieldMap.resp.json") + respData, err := loadTestData("TestGTM_NullFieldMap.resp.json") if err != nil { t.Fatal(err) } - resultData, err := loadTestData("TestGtm_NullFieldMap.result.gob") + resultData, err := loadTestData("TestGTM_NullFieldMap.result.gob") if err != nil { t.Fatal(err) } @@ -269,12 +260,10 @@ func TestGtm_NullFieldMap(t *testing.T) { } } -// Test GetDomain -// GetDomain(context.Context, string) (*Domain, error) -func TestGtm_GetDomain(t *testing.T) { +func TestGTM_GetDomain(t *testing.T) { var result Domain - respData, err := loadTestData("TestGtm_GetDomain.resp.json") + respData, err := loadTestData("TestGTM_GetDomain.resp.json") if err != nil { t.Fatal(err) } @@ -338,12 +327,10 @@ func TestGtm_GetDomain(t *testing.T) { } } -// Test Create domain. -// CreateDomain(context.Context, *Domain, map[string]string) (*DomainResponse, error) -func TestGtm_CreateDomain(t *testing.T) { +func TestGTM_CreateDomain(t *testing.T) { var result DomainResponse - respData, err := loadTestData("TestGtm_GetDomain.resp.json") + respData, err := loadTestData("TestGTM_GetDomain.resp.json") if err != nil { t.Fatal(err) } @@ -424,12 +411,10 @@ func TestGtm_CreateDomain(t *testing.T) { } } -// Test Update domain. -// UpdateDomain(context.Context, *Domain, map[string]string) (*DomainResponse, error) -func TestGtm_UpdateDomain(t *testing.T) { +func TestGTM_UpdateDomain(t *testing.T) { var result DomainResponse - respData, err := loadTestData("TestGtm_UpdateDomain.resp.json") + respData, err := loadTestData("TestGTM_UpdateDomain.resp.json") if err != nil { t.Fatal(err) } @@ -510,41 +495,3 @@ func TestGtm_UpdateDomain(t *testing.T) { }) } } - -/* Future. Presently no domain Delete endpoint. -func TestGtm_DeleteDomain(t *testing.T) { - - defer gock.Off() - - mock := gock.New("https://akaa-baseurl-xxxxxxxxxxx-xxxxxxxxxxxxx.luna.akamaiapis.net/config-gtm/v1/domains/"+gtmTestDomain) - mock. - Delete("/config-gtm/v1/domains/"+gtmTestDomain). - HeaderPresent("Authorization"). - Reply(200). - SetHeader("Content-Type", "application/vnd.config-gtm.v1.4+json;charset=UTF-8"). - BodyString(`{ - "resource" : null, - "status" : { - "changeId": "40e36abd-bfb2-4635-9fca-62175cf17007", - "links": [ - { - "href": "https://akab-ymtebc45gco3ypzj-apz4yxpek55y7fyv.luna.akamaiapis.net/config-gtm/v1/domains/gtmdomtest.akadns.net/status/current", - "rel": "self" - } - ], - "message": "Change Pending", - "passingValidation": true, - "propagationStatus": "PENDING", - "propagationStatusDate": "2019-04-25T14:54:00.000+00:00" - }, - }`) - - Init(config) - - getDomain := instantiateDomain() - - _, err := getDomain.Delete() - assert.NoError(t, err) - -} -*/ diff --git a/pkg/gtm/errors.go b/pkg/gtm/errors.go index cf46564c..0f956b6d 100644 --- a/pkg/gtm/errors.go +++ b/pkg/gtm/errors.go @@ -7,12 +7,10 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) var ( - // ErrBadRequest is returned when a required parameter is missing - ErrBadRequest = errors.New("missing argument") // ErrNotFound used when status code is 404 Not Found ErrNotFound = errors.New("404 Not Found") ) @@ -20,25 +18,26 @@ var ( type ( // Error is a gtm error interface Error struct { - Type string `json:"type"` - Title string `json:"title"` - Detail string `json:"detail"` - Instance string `json:"instance,omitempty"` - BehaviorName string `json:"behaviorName,omitempty"` - ErrorLocation string `json:"errorLocation,omitempty"` - StatusCode int `json:"-"` + Type string `json:"type"` + Title string `json:"title"` + Detail string `json:"detail"` + Instance string `json:"instance,omitempty"` + BehaviorName string `json:"behaviorName,omitempty"` + ErrorLocation string `json:"errorLocation,omitempty"` + StatusCode int `json:"-"` + Errors []Error `json:"errors"` } ) // Error parses an error from the response -func (p *gtm) Error(r *http.Response) error { +func (g *gtm) Error(r *http.Response) error { var e Error var body []byte body, err := ioutil.ReadAll(r.Body) if err != nil { - p.Log(r.Request.Context()).Errorf("reading error response body: %s", err) + g.Log(r.Request.Context()).Errorf("reading error response body: %s", err) e.StatusCode = r.StatusCode e.Title = fmt.Sprintf("Failed to read error body") e.Detail = err.Error() @@ -46,7 +45,7 @@ func (p *gtm) Error(r *http.Response) error { } if err := json.Unmarshal(body, &e); err != nil { - p.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) + g.Log(r.Request.Context()).Errorf("could not unmarshal API error: %s", err) e.Title = fmt.Sprintf("Failed to unmarshal error body. GTM API failed. Check details for more information.") e.Detail = errs.UnescapeContent(string(body)) } diff --git a/pkg/gtm/errors_test.go b/pkg/gtm/errors_test.go index eccc91c3..354b2f97 100644 --- a/pkg/gtm/errors_test.go +++ b/pkg/gtm/errors_test.go @@ -7,13 +7,13 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) -func TestJsonErrorUnmarshalling(t *testing.T) { +func TestJSONErrorUnmarshalling(t *testing.T) { req, err := http.NewRequestWithContext( context.TODO(), http.MethodHead, @@ -27,7 +27,6 @@ func TestJsonErrorUnmarshalling(t *testing.T) { "API failure with HTML response": { input: &http.Response{ Request: req, - Status: "OK", StatusCode: http.StatusServiceUnavailable, Body: ioutil.NopCloser(strings.NewReader(`......`))}, expected: &Error{ @@ -40,7 +39,6 @@ func TestJsonErrorUnmarshalling(t *testing.T) { "API failure with plain text response": { input: &http.Response{ Request: req, - Status: "OK", StatusCode: http.StatusServiceUnavailable, Body: ioutil.NopCloser(strings.NewReader("Your request did not succeed as this operation has reached the limit for your account. Please try after 2024-01-16T15:20:55.945Z"))}, expected: &Error{ @@ -53,7 +51,6 @@ func TestJsonErrorUnmarshalling(t *testing.T) { "API failure with XML response": { input: &http.Response{ Request: req, - Status: "OK", StatusCode: http.StatusServiceUnavailable, Body: ioutil.NopCloser(strings.NewReader(``))}, expected: &Error{ @@ -63,6 +60,41 @@ func TestJsonErrorUnmarshalling(t *testing.T) { StatusCode: http.StatusServiceUnavailable, }, }, + "API failure nested error": { + input: &http.Response{ + Request: req, + StatusCode: http.StatusBadRequest, + Body: ioutil.NopCloser(strings.NewReader(` +{ + "type": "https://problems.luna.akamaiapis.net/config-gtm/v1/propertyValidationFailed", + "title": "Property Validation Failure", + "detail": "", + "instance": "https://akaa-ouijhfns55qwgfuc-knsod5nrjl2w2gmt.luna-dev.akamaiapis.net/config-gtm-api/v1/domains/ddzh-test-1.akadns.net/properties/property_test#d290ddf7-53da-4509-be5a-ba582614f883", + "errors": [ + { + "type": "https://problems.luna.akamaiapis.net/config-gtm/v1/propertyValidationError", + "title": "Property Validation Error", + "detail": "In Property \"property_test\", there are no enabled traffic targets that have any traffic allowed to go to them", + "errors": null + } + ] +}`))}, + expected: &Error{ + Type: "https://problems.luna.akamaiapis.net/config-gtm/v1/propertyValidationFailed", + Title: "Property Validation Failure", + Detail: "", + StatusCode: http.StatusBadRequest, + Instance: "https://akaa-ouijhfns55qwgfuc-knsod5nrjl2w2gmt.luna-dev.akamaiapis.net/config-gtm-api/v1/domains/ddzh-test-1.akadns.net/properties/property_test#d290ddf7-53da-4509-be5a-ba582614f883", + Errors: []Error{ + { + Type: "https://problems.luna.akamaiapis.net/config-gtm/v1/propertyValidationError", + Title: "Property Validation Error", + Detail: "In Property \"property_test\", there are no enabled traffic targets that have any traffic allowed to go to them", + Errors: nil, + }, + }, + }, + }, } for name, test := range tests { diff --git a/pkg/gtm/geomap.go b/pkg/gtm/geomap.go index ade65df1..5a776efa 100644 --- a/pkg/gtm/geomap.go +++ b/pkg/gtm/geomap.go @@ -6,17 +6,8 @@ import ( "net/http" ) -// -// Handle Operations on gtm geomaps -// Based on 1.4 schema -// - // GeoMaps contains operations available on a GeoMap resource. type GeoMaps interface { - // NewGeoMap creates a new GeoMap object. - NewGeoMap(context.Context, string) *GeoMap - // NewGeoAssignment instantiates new Assignment struct. - NewGeoAssignment(context.Context, *GeoMap, int, string) *GeoAssignment // ListGeoMaps retrieves all GeoMaps. // // See: https://techdocs.akamai.com/gtm/reference/get-geographic-maps @@ -39,13 +30,13 @@ type GeoMaps interface { UpdateGeoMap(context.Context, *GeoMap, string) (*ResponseStatus, error) } -// GeoAssignment represents a GTM geo assignment element +// GeoAssignment represents a GTM Geo assignment element type GeoAssignment struct { DatacenterBase Countries []string `json:"countries"` } -// GeoMap represents a GTM GeoMap +// GeoMap represents a GTM GeoMap type GeoMap struct { DefaultDatacenter *DatacenterBase `json:"defaultDatacenter"` Assignments []*GeoAssignment `json:"assignments,omitempty"` @@ -59,103 +50,77 @@ type GeoMapList struct { } // Validate validates GeoMap -func (geo *GeoMap) Validate() error { - - if len(geo.Name) < 1 { +func (m *GeoMap) Validate() error { + if len(m.Name) < 1 { return fmt.Errorf("GeoMap is missing Name") } - if geo.DefaultDatacenter == nil { + if m.DefaultDatacenter == nil { return fmt.Errorf("GeoMap is missing DefaultDatacenter") } return nil } -func (p *gtm) NewGeoMap(ctx context.Context, name string) *GeoMap { - - logger := p.Log(ctx) - logger.Debug("NewGeoMap") - - geomap := &GeoMap{Name: name} - return geomap -} - -func (p *gtm) ListGeoMaps(ctx context.Context, domainName string) ([]*GeoMap, error) { - - logger := p.Log(ctx) +func (g *gtm) ListGeoMaps(ctx context.Context, domainName string) ([]*GeoMap, error) { + logger := g.Log(ctx) logger.Debug("ListGeoMaps") - var geos GeoMapList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/geographic-maps", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListGeoMaps request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &geos) + + var result GeoMapList + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListGeoMaps request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return geos.GeoMapItems, nil + return result.GeoMapItems, nil } -func (p *gtm) GetGeoMap(ctx context.Context, name, domainName string) (*GeoMap, error) { - - logger := p.Log(ctx) +func (g *gtm) GetGeoMap(ctx context.Context, mapName, domainName string) (*GeoMap, error) { + logger := g.Log(ctx) logger.Debug("GetGeoMap") - var geo GeoMap - getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/geographic-maps/%s", domainName, name) + getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/geographic-maps/%s", domainName, mapName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetGeoMap request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &geo) + + var result GeoMap + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetGeoMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &geo, nil -} - -func (p *gtm) NewGeoAssignment(ctx context.Context, _ *GeoMap, dcID int, nickname string) *GeoAssignment { - - logger := p.Log(ctx) - logger.Debug("NewGeoAssignment") - - geoAssign := &GeoAssignment{} - geoAssign.DatacenterId = dcID - geoAssign.Nickname = nickname - - return geoAssign + return &result, nil } -func (p *gtm) CreateGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*GeoMapResponse, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*GeoMapResponse, error) { + logger := g.Log(ctx) logger.Debug("CreateGeoMap") - // Use common code. Any specific validation needed? - return geo.save(ctx, p, domainName) + return geo.save(ctx, g, domainName) } -func (p *gtm) UpdateGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) UpdateGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("UpdateGeoMap") - // common code - stat, err := geo.save(ctx, p, domainName) + stat, err := geo.save(ctx, g, domainName) if err != nil { return nil, err } @@ -163,35 +128,33 @@ func (p *gtm) UpdateGeoMap(ctx context.Context, geo *GeoMap, domainName string) } // Save GeoMap in given domain. Common path for Create and Update. -func (geo *GeoMap) save(ctx context.Context, p *gtm, domainName string) (*GeoMapResponse, error) { - - if err := geo.Validate(); err != nil { +func (m *GeoMap) save(ctx context.Context, g *gtm, domainName string) (*GeoMapResponse, error) { + if err := m.Validate(); err != nil { return nil, fmt.Errorf("GeoMap validation failed. %w", err) } - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/geographic-maps/%s", domainName, geo.Name) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/geographic-maps/%s", domainName, m.Name) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GeoMap request: %w", err) } - - var mapresp GeoMapResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp, geo) + + var result GeoMapResponse + resp, err := g.Exec(req, &result, m) if err != nil { return nil, fmt.Errorf("GeoMap request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &mapresp, nil + return &result, nil } -func (p *gtm) DeleteGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) DeleteGeoMap(ctx context.Context, geo *GeoMap, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("DeleteGeoMap") if err := geo.Validate(); err != nil { @@ -204,17 +167,17 @@ func (p *gtm) DeleteGeoMap(ctx context.Context, geo *GeoMap, domainName string) if err != nil { return nil, fmt.Errorf("failed to create Delete request: %w", err) } - - var mapresp ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &mapresp) + + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GeoMap request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return mapresp.Status, nil + return result.Status, nil } diff --git a/pkg/gtm/geomap_test.go b/pkg/gtm/geomap_test.go index 1c0ee3b4..6c00645b 100644 --- a/pkg/gtm/geomap_test.go +++ b/pkg/gtm/geomap_test.go @@ -9,23 +9,15 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewGeoMap(t *testing.T) { - client := Client(session.Must(session.New())) - - geomap := client.NewGeoMap(context.Background(), "foo") - - assert.Equal(t, "foo", geomap.Name) -} - -func TestGtm_ListGeoMap(t *testing.T) { +func TestGTM_ListGeoMap(t *testing.T) { var result GeoMapList - respData, err := loadTestData("TestGtm_ListGeoMap.resp.json") + respData, err := loadTestData("TestGTM_ListGeoMap.resp.json") if err != nil { t.Fatal(err) } @@ -61,14 +53,14 @@ func TestGtm_ListGeoMap(t *testing.T) { { "type": "internal_error", "title": "Internal Server Error", - "detail": "Error fetching geomap", + "detail": "Error fetching GeoMap", "status": 500 }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net/geographic-maps", withError: &Error{ Type: "internal_error", Title: "Internal Server Error", - Detail: "Error fetching geomap", + Detail: "Error fetching GeoMap", StatusCode: http.StatusInternalServerError, }, }, @@ -98,10 +90,10 @@ func TestGtm_ListGeoMap(t *testing.T) { } } -func TestGtm_GetGeoMap(t *testing.T) { +func TestGTM_GetGeoMap(t *testing.T) { var result GeoMap - respData, err := loadTestData("TestGtm_GetGeoMap.resp.json") + respData, err := loadTestData("TestGTM_GetGeoMap.resp.json") if err != nil { t.Fatal(err) } @@ -140,14 +132,14 @@ func TestGtm_GetGeoMap(t *testing.T) { { "type": "internal_error", "title": "Internal Server Error", - "detail": "Error fetching geomap", + "detail": "Error fetching GeoMap", "status": 500 }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net/geographic-maps/Software-rollout", withError: &Error{ Type: "internal_error", Title: "Internal Server Error", - Detail: "Error fetching geomap", + Detail: "Error fetching GeoMap", StatusCode: http.StatusInternalServerError, }, }, @@ -177,20 +169,11 @@ func TestGtm_GetGeoMap(t *testing.T) { } } -func TestGtm_NewGeoAssignment(t *testing.T) { - client := Client(session.Must(session.New())) - - asn := client.NewGeoAssignment(context.Background(), nil, 100, "foo") - - assert.Equal(t, 100, asn.DatacenterId) - assert.Equal(t, "foo", asn.Nickname) -} - -func TestGtm_CreateGeoMap(t *testing.T) { +func TestGTM_CreateGeoMap(t *testing.T) { var result GeoMapResponse var req GeoMap - respData, err := loadTestData("TestGtm_CreateGeoMap.resp.json") + respData, err := loadTestData("TestGTM_CreateGeoMap.resp.json") if err != nil { t.Fatal(err) } @@ -199,7 +182,7 @@ func TestGtm_CreateGeoMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateGeoMap.req.json") + reqData, err := loadTestData("TestGTM_CreateGeoMap.req.json") if err != nil { t.Fatal(err) } @@ -209,7 +192,7 @@ func TestGtm_CreateGeoMap(t *testing.T) { } tests := map[string]struct { - geomap *GeoMap + GeoMap *GeoMap domainName string responseStatus int responseBody string @@ -219,7 +202,7 @@ func TestGtm_CreateGeoMap(t *testing.T) { headers http.Header }{ "200 OK": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -230,7 +213,7 @@ func TestGtm_CreateGeoMap(t *testing.T) { expectedResponse: &result, }, "500 internal server error": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -238,13 +221,13 @@ func TestGtm_CreateGeoMap(t *testing.T) { { "type": "internal_error", "title": "Internal Server Error", - "detail": "Error creating geomap" + "detail": "Error creating GeoMap" }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net/geographic-maps/UK%20Delivery", withError: &Error{ Type: "internal_error", Title: "Internal Server Error", - Detail: "Error creating geomap", + Detail: "Error creating GeoMap", StatusCode: http.StatusInternalServerError, }, }, @@ -263,7 +246,7 @@ func TestGtm_CreateGeoMap(t *testing.T) { result, err := client.CreateGeoMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.geomap, test.domainName) + session.WithContextHeaders(test.headers)), test.GeoMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -274,11 +257,11 @@ func TestGtm_CreateGeoMap(t *testing.T) { } } -func TestGtm_UpdateGeoMap(t *testing.T) { +func TestGTM_UpdateGeoMap(t *testing.T) { var result GeoMapResponse var req GeoMap - respData, err := loadTestData("TestGtm_CreateGeoMap.resp.json") + respData, err := loadTestData("TestGTM_CreateGeoMap.resp.json") if err != nil { t.Fatal(err) } @@ -287,7 +270,7 @@ func TestGtm_UpdateGeoMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateGeoMap.req.json") + reqData, err := loadTestData("TestGTM_CreateGeoMap.req.json") if err != nil { t.Fatal(err) } @@ -297,7 +280,7 @@ func TestGtm_UpdateGeoMap(t *testing.T) { } tests := map[string]struct { - geomap *GeoMap + GeoMap *GeoMap domainName string responseStatus int responseBody string @@ -307,7 +290,7 @@ func TestGtm_UpdateGeoMap(t *testing.T) { headers http.Header }{ "200 OK": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -318,7 +301,7 @@ func TestGtm_UpdateGeoMap(t *testing.T) { expectedResponse: result.Status, }, "500 internal server error": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -326,13 +309,13 @@ func TestGtm_UpdateGeoMap(t *testing.T) { { "type": "internal_error", "title": "Internal Server Error", - "detail": "Error updating geomap" + "detail": "Error updating GeoMap" }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net/geographic-maps/UK%20Delivery", withError: &Error{ Type: "internal_error", Title: "Internal Server Error", - Detail: "Error updating geomap", + Detail: "Error updating GeoMap", StatusCode: http.StatusInternalServerError, }, }, @@ -351,7 +334,7 @@ func TestGtm_UpdateGeoMap(t *testing.T) { result, err := client.UpdateGeoMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.geomap, test.domainName) + session.WithContextHeaders(test.headers)), test.GeoMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return @@ -362,11 +345,11 @@ func TestGtm_UpdateGeoMap(t *testing.T) { } } -func TestGtm_DeleteGeoMap(t *testing.T) { +func TestGTM_DeleteGeoMap(t *testing.T) { var result GeoMapResponse var req GeoMap - respData, err := loadTestData("TestGtm_CreateGeoMap.resp.json") + respData, err := loadTestData("TestGTM_CreateGeoMap.resp.json") if err != nil { t.Fatal(err) } @@ -375,7 +358,7 @@ func TestGtm_DeleteGeoMap(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateGeoMap.req.json") + reqData, err := loadTestData("TestGTM_CreateGeoMap.req.json") if err != nil { t.Fatal(err) } @@ -385,7 +368,7 @@ func TestGtm_DeleteGeoMap(t *testing.T) { } tests := map[string]struct { - geomap *GeoMap + GeoMap *GeoMap domainName string responseStatus int responseBody string @@ -395,7 +378,7 @@ func TestGtm_DeleteGeoMap(t *testing.T) { headers http.Header }{ "200 OK": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, @@ -406,7 +389,7 @@ func TestGtm_DeleteGeoMap(t *testing.T) { expectedResponse: result.Status, }, "500 internal server error": { - geomap: &req, + GeoMap: &req, domainName: "example.akadns.net", headers: http.Header{}, responseStatus: http.StatusInternalServerError, @@ -414,13 +397,13 @@ func TestGtm_DeleteGeoMap(t *testing.T) { { "type": "internal_error", "title": "Internal Server Error", - "detail": "Error updating geomap" + "detail": "Error updating GeoMap" }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net/geographic-maps/UK%20Delivery", withError: &Error{ Type: "internal_error", Title: "Internal Server Error", - Detail: "Error updating geomap", + Detail: "Error updating GeoMap", StatusCode: http.StatusInternalServerError, }, }, @@ -439,7 +422,7 @@ func TestGtm_DeleteGeoMap(t *testing.T) { result, err := client.DeleteGeoMap( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.geomap, test.domainName) + session.WithContextHeaders(test.headers)), test.GeoMap, test.domainName) if test.withError != nil { assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) return diff --git a/pkg/gtm/gtm.go b/pkg/gtm/gtm.go index badead07..5903788c 100644 --- a/pkg/gtm/gtm.go +++ b/pkg/gtm/gtm.go @@ -4,15 +4,9 @@ package gtm import ( - "errors" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" -) - -var ( - // ErrStructValidation is returned returned when given struct validation failed - ErrStructValidation = errors.New("struct validation") + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) type ( @@ -24,7 +18,7 @@ type ( Resources ASMaps GeoMaps - CidrMaps + CIDRMaps } gtm struct { @@ -51,7 +45,6 @@ func Client(sess session.Session, opts ...Option) GTM { } // Exec overrides the session.Exec to add dns options -func (p *gtm) Exec(r *http.Request, out interface{}, in ...interface{}) (*http.Response, error) { - - return p.Session.Exec(r, out, in...) +func (g *gtm) Exec(r *http.Request, out interface{}, in ...interface{}) (*http.Response, error) { + return g.Session.Exec(r, out, in...) } diff --git a/pkg/gtm/gtm_test.go b/pkg/gtm/gtm_test.go index e0510143..813e7383 100644 --- a/pkg/gtm/gtm_test.go +++ b/pkg/gtm/gtm_test.go @@ -10,8 +10,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/gtm/mocks.go b/pkg/gtm/mocks.go index ac9f1798..c9ecbd66 100644 --- a/pkg/gtm/mocks.go +++ b/pkg/gtm/mocks.go @@ -24,16 +24,6 @@ func (p *Mock) NullFieldMap(ctx context.Context, domain *Domain) (*NullFieldMapS return args.Get(0).(*NullFieldMapStruct), args.Error(1) } -func (p *Mock) NewDomain(ctx context.Context, _ string, _ string) *Domain { - args := p.Called(ctx) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*Domain) -} - func (p *Mock) GetDomainStatus(ctx context.Context, domain string) (*ResponseStatus, error) { args := p.Called(ctx, domain) @@ -134,46 +124,6 @@ func (p *Mock) UpdateProperty(ctx context.Context, prop *Property, domain string return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewTrafficTarget(ctx context.Context) *TrafficTarget { - args := p.Called(ctx) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*TrafficTarget) -} - -func (p *Mock) NewStaticRRSet(ctx context.Context) *StaticRRSet { - args := p.Called(ctx) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*StaticRRSet) -} - -func (p *Mock) NewLivenessTest(ctx context.Context, a string, b string, c int, d float32) *LivenessTest { - args := p.Called(ctx, a, b, c, d) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*LivenessTest) -} - -func (p *Mock) NewProperty(ctx context.Context, prop string) *Property { - args := p.Called(ctx, prop) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*Property) -} - func (p *Mock) ListProperties(ctx context.Context, domain string) ([]*Property, error) { args := p.Called(ctx, domain) @@ -184,8 +134,8 @@ func (p *Mock) ListProperties(ctx context.Context, domain string) ([]*Property, return args.Get(0).([]*Property), args.Error(1) } -func (p *Mock) GetDatacenter(ctx context.Context, dcid int, domain string) (*Datacenter, error) { - args := p.Called(ctx, dcid, domain) +func (p *Mock) GetDatacenter(ctx context.Context, dcID int, domain string) (*Datacenter, error) { + args := p.Called(ctx, dcID, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -224,26 +174,6 @@ func (p *Mock) UpdateDatacenter(ctx context.Context, dc *Datacenter, domain stri return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewDatacenterResponse(ctx context.Context) *DatacenterResponse { - args := p.Called(ctx) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*DatacenterResponse) -} - -func (p *Mock) NewDatacenter(ctx context.Context) *Datacenter { - args := p.Called(ctx) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*Datacenter) -} - func (p *Mock) ListDatacenters(ctx context.Context, domain string) ([]*Datacenter, error) { args := p.Called(ctx, domain) @@ -284,8 +214,8 @@ func (p *Mock) CreateMapsDefaultDatacenter(ctx context.Context, domainName strin return args.Get(0).(*Datacenter), args.Error(1) } -func (p *Mock) GetResource(ctx context.Context, rsrc string, domain string) (*Resource, error) { - args := p.Called(ctx, rsrc, domain) +func (p *Mock) GetResource(ctx context.Context, resource string, domain string) (*Resource, error) { + args := p.Called(ctx, resource, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -294,8 +224,8 @@ func (p *Mock) GetResource(ctx context.Context, rsrc string, domain string) (*Re return args.Get(0).(*Resource), args.Error(1) } -func (p *Mock) CreateResource(ctx context.Context, rsrc *Resource, domain string) (*ResourceResponse, error) { - args := p.Called(ctx, rsrc, domain) +func (p *Mock) CreateResource(ctx context.Context, resource *Resource, domain string) (*ResourceResponse, error) { + args := p.Called(ctx, resource, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -304,8 +234,8 @@ func (p *Mock) CreateResource(ctx context.Context, rsrc *Resource, domain string return args.Get(0).(*ResourceResponse), args.Error(1) } -func (p *Mock) DeleteResource(ctx context.Context, rsrc *Resource, domain string) (*ResponseStatus, error) { - args := p.Called(ctx, rsrc, domain) +func (p *Mock) DeleteResource(ctx context.Context, resource *Resource, domain string) (*ResponseStatus, error) { + args := p.Called(ctx, resource, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -314,8 +244,8 @@ func (p *Mock) DeleteResource(ctx context.Context, rsrc *Resource, domain string return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) UpdateResource(ctx context.Context, rsrc *Resource, domain string) (*ResponseStatus, error) { - args := p.Called(ctx, rsrc, domain) +func (p *Mock) UpdateResource(ctx context.Context, resource *Resource, domain string) (*ResponseStatus, error) { + args := p.Called(ctx, resource, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -324,26 +254,6 @@ func (p *Mock) UpdateResource(ctx context.Context, rsrc *Resource, domain string return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewResourceInstance(ctx context.Context, ri *Resource, a int) *ResourceInstance { - args := p.Called(ctx, ri, a) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*ResourceInstance) -} - -func (p *Mock) NewResource(ctx context.Context, rname string) *Resource { - args := p.Called(ctx, rname) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*Resource) -} - func (p *Mock) ListResources(ctx context.Context, domain string) ([]*Resource, error) { args := p.Called(ctx, domain) @@ -354,28 +264,28 @@ func (p *Mock) ListResources(ctx context.Context, domain string) ([]*Resource, e return args.Get(0).([]*Resource), args.Error(1) } -func (p *Mock) GetAsMap(ctx context.Context, asmap string, domain string) (*AsMap, error) { - args := p.Called(ctx, asmap, domain) +func (p *Mock) GetASMap(ctx context.Context, asMap string, domain string) (*ASMap, error) { + args := p.Called(ctx, asMap, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).(*AsMap), args.Error(1) + return args.Get(0).(*ASMap), args.Error(1) } -func (p *Mock) CreateAsMap(ctx context.Context, asmap *AsMap, domain string) (*AsMapResponse, error) { - args := p.Called(ctx, asmap, domain) +func (p *Mock) CreateASMap(ctx context.Context, asMap *ASMap, domain string) (*ASMapResponse, error) { + args := p.Called(ctx, asMap, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).(*AsMapResponse), args.Error(1) + return args.Get(0).(*ASMapResponse), args.Error(1) } -func (p *Mock) DeleteAsMap(ctx context.Context, asmap *AsMap, domain string) (*ResponseStatus, error) { - args := p.Called(ctx, asmap, domain) +func (p *Mock) DeleteASMap(ctx context.Context, asMap *ASMap, domain string) (*ResponseStatus, error) { + args := p.Called(ctx, asMap, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -384,9 +294,9 @@ func (p *Mock) DeleteAsMap(ctx context.Context, asmap *AsMap, domain string) (*R return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) UpdateAsMap(ctx context.Context, asmap *AsMap, domain string) (*ResponseStatus, error) { +func (p *Mock) UpdateASMap(ctx context.Context, asMap *ASMap, domain string) (*ResponseStatus, error) { - args := p.Called(ctx, asmap, domain) + args := p.Called(ctx, asMap, domain) if args.Get(0) == nil { return nil, args.Error(1) @@ -395,34 +305,14 @@ func (p *Mock) UpdateAsMap(ctx context.Context, asmap *AsMap, domain string) (*R return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewAsMap(ctx context.Context, mname string) *AsMap { - args := p.Called(ctx, mname) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*AsMap) -} - -func (p *Mock) NewASAssignment(ctx context.Context, as *AsMap, a int, b string) *AsAssignment { - args := p.Called(ctx, as, a, b) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*AsAssignment) -} - -func (p *Mock) ListAsMaps(ctx context.Context, domain string) ([]*AsMap, error) { +func (p *Mock) ListASMaps(ctx context.Context, domain string) ([]*ASMap, error) { args := p.Called(ctx, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).([]*AsMap), args.Error(1) + return args.Get(0).([]*ASMap), args.Error(1) } func (p *Mock) GetGeoMap(ctx context.Context, geo string, domain string) (*GeoMap, error) { @@ -465,26 +355,6 @@ func (p *Mock) UpdateGeoMap(ctx context.Context, geo *GeoMap, domain string) (*R return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewGeoMap(ctx context.Context, mname string) *GeoMap { - args := p.Called(ctx, mname) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*GeoMap) -} - -func (p *Mock) NewGeoAssignment(ctx context.Context, as *GeoMap, a int, b string) *GeoAssignment { - args := p.Called(ctx, as, a, b) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*GeoAssignment) -} - func (p *Mock) ListGeoMaps(ctx context.Context, domain string) ([]*GeoMap, error) { args := p.Called(ctx, domain) @@ -495,27 +365,27 @@ func (p *Mock) ListGeoMaps(ctx context.Context, domain string) ([]*GeoMap, error return args.Get(0).([]*GeoMap), args.Error(1) } -func (p *Mock) GetCidrMap(ctx context.Context, cidr string, domain string) (*CidrMap, error) { +func (p *Mock) GetCIDRMap(ctx context.Context, cidr string, domain string) (*CIDRMap, error) { args := p.Called(ctx, cidr, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).(*CidrMap), args.Error(1) + return args.Get(0).(*CIDRMap), args.Error(1) } -func (p *Mock) CreateCidrMap(ctx context.Context, cidr *CidrMap, domain string) (*CidrMapResponse, error) { +func (p *Mock) CreateCIDRMap(ctx context.Context, cidr *CIDRMap, domain string) (*CIDRMapResponse, error) { args := p.Called(ctx, cidr, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).(*CidrMapResponse), args.Error(1) + return args.Get(0).(*CIDRMapResponse), args.Error(1) } -func (p *Mock) DeleteCidrMap(ctx context.Context, cidr *CidrMap, domain string) (*ResponseStatus, error) { +func (p *Mock) DeleteCIDRMap(ctx context.Context, cidr *CIDRMap, domain string) (*ResponseStatus, error) { args := p.Called(ctx, cidr, domain) if args.Get(0) == nil { @@ -525,7 +395,7 @@ func (p *Mock) DeleteCidrMap(ctx context.Context, cidr *CidrMap, domain string) return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) UpdateCidrMap(ctx context.Context, cidr *CidrMap, domain string) (*ResponseStatus, error) { +func (p *Mock) UpdateCIDRMap(ctx context.Context, cidr *CIDRMap, domain string) (*ResponseStatus, error) { args := p.Called(ctx, cidr, domain) if args.Get(0) == nil { @@ -535,32 +405,12 @@ func (p *Mock) UpdateCidrMap(ctx context.Context, cidr *CidrMap, domain string) return args.Get(0).(*ResponseStatus), args.Error(1) } -func (p *Mock) NewCidrMap(ctx context.Context, mname string) *CidrMap { - args := p.Called(ctx, mname) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*CidrMap) -} - -func (p *Mock) NewCidrAssignment(ctx context.Context, as *CidrMap, a int, b string) *CidrAssignment { - args := p.Called(ctx, as, a, b) - - if args.Get(0) == nil { - return nil - } - - return args.Get(0).(*CidrAssignment) -} - -func (p *Mock) ListCidrMaps(ctx context.Context, domain string) ([]*CidrMap, error) { +func (p *Mock) ListCIDRMaps(ctx context.Context, domain string) ([]*CIDRMap, error) { args := p.Called(ctx, domain) if args.Get(0) == nil { return nil, args.Error(1) } - return args.Get(0).([]*CidrMap), args.Error(1) + return args.Get(0).([]*CIDRMap), args.Error(1) } diff --git a/pkg/gtm/property.go b/pkg/gtm/property.go index eead7af4..86bb5322 100644 --- a/pkg/gtm/property.go +++ b/pkg/gtm/property.go @@ -4,24 +4,14 @@ import ( "context" "fmt" "net/http" -) -// -// Support gtm domain properties thru Edgegrid -// Based on 1.4 Schema -// + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" + validation "github.com/go-ozzo/ozzo-validation/v4" +) // Properties contains operations available on a Property resource. type Properties interface { - // NewTrafficTarget is a method applied to a property object that instantiates a TrafficTarget object. - NewTrafficTarget(context.Context) *TrafficTarget - // NewStaticRRSet is a method applied to a property object that instantiates a StaticRRSet object. - NewStaticRRSet(context.Context) *StaticRRSet - // NewLivenessTest is a method applied to a property object that instantiates a LivenessTest object. - NewLivenessTest(context.Context, string, string, int, float32) *LivenessTest - // NewProperty creates a new Property object. - NewProperty(context.Context, string) *Property - // ListProperties retreieves all Properties for the provided domainName. + // ListProperties retrieves all Properties for the provided domainName. // // See: https://techdocs.akamai.com/gtm/reference/get-properties ListProperties(context.Context, string) ([]*Property, error) @@ -45,16 +35,17 @@ type Properties interface { // TrafficTarget struct contains information about where to direct data center traffic type TrafficTarget struct { - DatacenterId int `json:"datacenterId"` + DatacenterID int `json:"datacenterId"` Enabled bool `json:"enabled"` Weight float64 `json:"weight,omitempty"` Servers []string `json:"servers,omitempty"` Name string `json:"name,omitempty"` HandoutCName string `json:"handoutCName,omitempty"` + Precedence *int `json:"precedence,omitempty"` } -// HttpHeader struct contains HTTP headers to send if the testObjectProtocol is http or https -type HttpHeader struct { +// HTTPHeader struct contains HTTP headers to send if the testObjectProtocol is http or https +type HTTPHeader struct { Name string `json:"name"` Value string `json:"value"` } @@ -69,23 +60,27 @@ type LivenessTest struct { Links []*Link `json:"links,omitempty"` RequestString string `json:"requestString,omitempty"` ResponseString string `json:"responseString,omitempty"` - HttpError3xx bool `json:"httpError3xx"` - HttpError4xx bool `json:"httpError4xx"` - HttpError5xx bool `json:"httpError5xx"` + HTTPError3xx bool `json:"httpError3xx"` + HTTPError4xx bool `json:"httpError4xx"` + HTTPError5xx bool `json:"httpError5xx"` + HTTPMethod *string `json:"httpMethod"` + HTTPRequestBody *string `json:"httpRequestBody"` Disabled bool `json:"disabled"` TestObjectProtocol string `json:"testObjectProtocol,omitempty"` TestObjectPassword string `json:"testObjectPassword,omitempty"` TestObjectPort int `json:"testObjectPort,omitempty"` - SslClientPrivateKey string `json:"sslClientPrivateKey,omitempty"` - SslClientCertificate string `json:"sslClientCertificate,omitempty"` + SSLClientPrivateKey string `json:"sslClientPrivateKey,omitempty"` + SSLClientCertificate string `json:"sslClientCertificate,omitempty"` + Pre2023SecurityPosture bool `json:"pre2023SecurityPosture"` DisableNonstandardPortWarning bool `json:"disableNonstandardPortWarning"` - HttpHeaders []*HttpHeader `json:"httpHeaders,omitempty"` + HTTPHeaders []*HTTPHeader `json:"httpHeaders,omitempty"` TestObjectUsername string `json:"testObjectUsername,omitempty"` TestTimeout float32 `json:"testTimeout,omitempty"` TimeoutPenalty float64 `json:"timeoutPenalty,omitempty"` AnswersRequired bool `json:"answersRequired"` ResourceType string `json:"resourceType,omitempty"` RecursionRequested bool `json:"recursionRequested"` + AlternateCACertificates []string `json:"alternateCACertificates"` } // StaticRRSet contains static recordset @@ -99,13 +94,13 @@ type StaticRRSet struct { type Property struct { Name string `json:"name"` Type string `json:"type"` - Ipv6 bool `json:"ipv6"` + IPv6 bool `json:"ipv6"` ScoreAggregationType string `json:"scoreAggregationType"` StickinessBonusPercentage int `json:"stickinessBonusPercentage,omitempty"` StickinessBonusConstant int `json:"stickinessBonusConstant,omitempty"` HealthThreshold float64 `json:"healthThreshold,omitempty"` UseComputedTargets bool `json:"useComputedTargets"` - BackupIp string `json:"backupIp,omitempty"` + BackupIP string `json:"backupIp,omitempty"` BalanceByDownloadScore bool `json:"balanceByDownloadScore"` StaticTTL int `json:"staticTTL,omitempty"` StaticRRSets []*StaticRRSet `json:"staticRRSets,omitempty"` @@ -139,176 +134,144 @@ type PropertyList struct { } // Validate validates Property -func (prop *Property) Validate() error { +func (p *Property) Validate() error { + return edgegriderr.ParseValidationErrors(validation.Errors{ + "Name": validation.Validate(p.Name, validation.Required), + "Type": validation.Validate(p.Type, validation.Required), + "ScoreAggregationTypes": validation.Validate(p.ScoreAggregationType, validation.Required), + "HandoutMode": validation.Validate(p.HandoutMode, validation.Required), + "TrafficTargets": validation.Validate(p.TrafficTargets, validation.When(p.Type == "ranked-failover", validation.By(validateRankedFailoverTrafficTargets))), + }) +} - if len(prop.Name) < 1 { - return fmt.Errorf("Property is missing Name") +// validateRankedFailoverTrafficTargets validates traffic targets when property type is 'ranked-failover' +func validateRankedFailoverTrafficTargets(value interface{}) error { + tt := value.([]*TrafficTarget) + if len(tt) == 0 { + return fmt.Errorf("no traffic targets are enabled") } - if len(prop.Type) < 1 { - return fmt.Errorf("Property is missing Type") + precedenceCounter := map[int]int{} + minPrecedence := 256 + for _, t := range tt { + if t.Precedence == nil { + precedenceCounter[0]++ + minPrecedence = 0 + } else { + if *t.Precedence > 255 || *t.Precedence < 0 { + return fmt.Errorf("'Precedence' value has to be between 0 and 255") + } + precedenceCounter[*t.Precedence]++ + if *t.Precedence < minPrecedence { + minPrecedence = *t.Precedence + } + } } - if len(prop.ScoreAggregationType) < 1 { - return fmt.Errorf("Property is missing ScoreAggregationType") + if precedenceCounter[minPrecedence] > 1 { + return fmt.Errorf("property cannot have multiple primary traffic targets (targets with lowest precedence)") } - if len(prop.HandoutMode) < 1 { - return fmt.Errorf("Property is missing HandoutMode") - } - // is zero a valid value? need to check and uncomment - //if prop.HandoutLimit == 0 { - // return fmt.Errorf("Property is missing handoutLimit" - //} return nil } -func (p *gtm) NewTrafficTarget(ctx context.Context) *TrafficTarget { - - logger := p.Log(ctx) - logger.Debug("NewTrafficTarget") - - return &TrafficTarget{} - -} - -func (p *gtm) NewStaticRRSet(ctx context.Context) *StaticRRSet { - - logger := p.Log(ctx) - logger.Debug("NewStaticRRSet") - - return &StaticRRSet{} - -} - -// NewHttpHeader is a method applied to a livenesstest object that instantiates an HttpHeader object. -func (lt *LivenessTest) NewHttpHeader() *HttpHeader { - - return &HttpHeader{} - -} -func (p *gtm) NewLivenessTest(ctx context.Context, name string, objproto string, interval int, timeout float32) *LivenessTest { - - logger := p.Log(ctx) - logger.Debug("NewLivenessTest") - - return &LivenessTest{Name: name, TestInterval: interval, TestObjectProtocol: objproto, TestTimeout: timeout} - -} - -func (p *gtm) NewProperty(ctx context.Context, name string) *Property { - - logger := p.Log(ctx) - logger.Debug("NewProperty") - - property := &Property{Name: name} - return property -} - -func (p *gtm) ListProperties(ctx context.Context, domainName string) ([]*Property, error) { - - logger := p.Log(ctx) +func (g *gtm) ListProperties(ctx context.Context, domainName string) ([]*Property, error) { + logger := g.Log(ctx) logger.Debug("ListProperties") - var properties PropertyList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListProperties request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &properties) + + var result PropertyList + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListProperties request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return properties.PropertyItems, nil + return result.PropertyItems, nil } -func (p *gtm) GetProperty(ctx context.Context, name, domainName string) (*Property, error) { - - logger := p.Log(ctx) +func (g *gtm) GetProperty(ctx context.Context, propertyName, domainName string) (*Property, error) { + logger := g.Log(ctx) logger.Debug("GetProperty") - var property Property - getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties/%s", domainName, name) + getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties/%s", domainName, propertyName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetProperty request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &property) + + var result Property + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetProperty request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &property, nil + return &result, nil } -func (p *gtm) CreateProperty(ctx context.Context, property *Property, domainName string) (*PropertyResponse, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateProperty(ctx context.Context, property *Property, domainName string) (*PropertyResponse, error) { + logger := g.Log(ctx) logger.Debug("CreateProperty") - // Need do any validation? - return property.save(ctx, p, domainName) + return property.save(ctx, g, domainName) } -func (p *gtm) UpdateProperty(ctx context.Context, property *Property, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) UpdateProperty(ctx context.Context, property *Property, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("UpdateProperty") - // Need do any validation? - stat, err := property.save(ctx, p, domainName) + stat, err := property.save(ctx, g, domainName) if err != nil { return nil, err } return stat.Status, err - } // Save Property updates method -func (prop *Property) save(ctx context.Context, p *gtm, domainName string) (*PropertyResponse, error) { +func (p *Property) save(ctx context.Context, g *gtm, domainName string) (*PropertyResponse, error) { - if err := prop.Validate(); err != nil { - return nil, fmt.Errorf("Property validation failed. %w", err) + if err := p.Validate(); err != nil { + return nil, fmt.Errorf("property validation failed. %w", err) } - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties/%s", domainName, prop.Name) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties/%s", domainName, p.Name) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Property request: %w", err) } - - var presp PropertyResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &presp, prop) + + var result PropertyResponse + resp, err := g.Exec(req, &result, p) if err != nil { - return nil, fmt.Errorf("Property request failed: %w", err) + return nil, fmt.Errorf("property request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &presp, nil + return &result, nil } -func (p *gtm) DeleteProperty(ctx context.Context, property *Property, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) DeleteProperty(ctx context.Context, property *Property, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("DeleteProperty") if err := property.Validate(); err != nil { - logger.Errorf("Property validation failed. %w", err) - return nil, fmt.Errorf("Property validation failed. %w", err) + return nil, fmt.Errorf("DeleteProperty validation failed. %w", err) } delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/properties/%s", domainName, property.Name) @@ -316,17 +279,17 @@ func (p *gtm) DeleteProperty(ctx context.Context, property *Property, domainName if err != nil { return nil, fmt.Errorf("failed to create Property request: %w", err) } - - var presp ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &presp) + + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("Property request failed: %w", err) + return nil, fmt.Errorf("DeleteProperty request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return presp.Status, nil + return result.Status, nil } diff --git a/pkg/gtm/property_test.go b/pkg/gtm/property_test.go index e2eb9db5..90e7beeb 100644 --- a/pkg/gtm/property_test.go +++ b/pkg/gtm/property_test.go @@ -9,52 +9,16 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewTrafficTarget(t *testing.T) { - client := Client(session.Must(session.New())) - - tgt := client.NewTrafficTarget(context.Background()) - - assert.NotNil(t, tgt) -} - -func TestGtm_NewStaticRRSet(t *testing.T) { - client := Client(session.Must(session.New())) - - set := client.NewStaticRRSet(context.Background()) - - assert.NotNil(t, set) -} - -func TestGtm_NewLivenessTest(t *testing.T) { - client := Client(session.Must(session.New())) - - test := client.NewLivenessTest(context.Background(), "foo", "bar", 1, 1000) - - assert.NotNil(t, test) - assert.Equal(t, "foo", test.Name) - assert.Equal(t, "bar", test.TestObjectProtocol) - assert.Equal(t, 1, test.TestInterval) - assert.Equal(t, float32(1000), test.TestTimeout) -} - -func TestGtm_NewProperty(t *testing.T) { - client := Client(session.Must(session.New())) - - prop := client.NewProperty(context.Background(), "foo") - - assert.NotNil(t, prop) - assert.Equal(t, prop.Name, "foo") -} - -func TestGtm_ListProperties(t *testing.T) { +func TestGTM_ListProperties(t *testing.T) { var result PropertyList - respData, err := loadTestData("TestGtm_ListProperties.resp.json") + respData, err := loadTestData("TestGTM_ListProperties.resp.json") if err != nil { t.Fatal(err) } @@ -127,12 +91,10 @@ func TestGtm_ListProperties(t *testing.T) { } } -// Test GetProperty -// GetProperty(context.Context, string) (*Property, error) -func TestGtm_GetProperty(t *testing.T) { +func TestGTM_GetProperty(t *testing.T) { var result Property - respData, err := loadTestData("TestGtm_GetProperty.resp.json") + respData, err := loadTestData("TestGTM_GetProperty.resp.json") if err != nil { t.Fatal(err) } @@ -199,67 +161,507 @@ func TestGtm_GetProperty(t *testing.T) { } } -// Test Create domain. -// CreateProperty(context.Context, *Property, map[string]string) (*PropertyResponse, error) -func TestGtm_CreateProperty(t *testing.T) { - var result PropertyResponse - var req Property - - respData, err := loadTestData("TestGtm_CreateProperty.resp.json") - if err != nil { - t.Fatal(err) - } - - if err := json.NewDecoder(bytes.NewBuffer(respData)).Decode(&result); err != nil { - t.Fatal(err) - } - - reqData, err := loadTestData("TestGtm_CreateProperty.req.json") - if err != nil { - t.Fatal(err) - } - - if err := json.NewDecoder(bytes.NewBuffer(reqData)).Decode(&req); err != nil { - t.Fatal(err) - } - +func TestGTM_CreateProperty(t *testing.T) { tests := map[string]struct { domain string - prop *Property + property *Property responseStatus int - responseBody []byte + responseBody string expectedPath string expectedResponse *PropertyResponse - withError error + withError bool + assertError func(*testing.T, error) headers http.Header }{ "201 Created": { - prop: &req, + property: &Property{ + BalanceByDownloadScore: false, + HandoutMode: "normal", + IPv6: false, + Name: "origin", + ScoreAggregationType: "mean", + StaticTTL: 600, + Type: "weighted-round-robin", + UseComputedTargets: false, + LivenessTests: []*LivenessTest{ + { + DisableNonstandardPortWarning: false, + HTTPError3xx: true, + HTTPError4xx: true, + HTTPError5xx: true, + Name: "health-check", + TestInterval: 60, + TestObject: "/status", + TestObjectPort: 80, + TestObjectProtocol: "HTTP", + TestTimeout: 25.0, + }, + }, + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 3134, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.5"}, + }, + { + DatacenterID: 3133, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.4"}, + Precedence: nil, + }, + }, + }, domain: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, }, - responseStatus: http.StatusCreated, - responseBody: respData, - expectedResponse: &result, - expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", + responseStatus: http.StatusCreated, + responseBody: ` +{ + "resource": { + "backupCName": null, + "backupIp": null, + "balanceByDownloadScore": false, + "cname": null, + "comments": null, + "dynamicTTL": 300, + "failbackDelay": 0, + "failoverDelay": 0, + "handoutMode": "normal", + "healthMax": null, + "healthMultiplier": null, + "healthThreshold": null, + "ipv6": false, + "lastModified": null, + "loadImbalancePercentage": null, + "mapName": null, + "maxUnreachablePenalty": null, + "name": "origin", + "scoreAggregationType": "mean", + "staticTTL": 600, + "stickinessBonusConstant": 0, + "stickinessBonusPercentage": 0, + "type": "weighted-round-robin", + "unreachableThreshold": null, + "useComputedTargets": false, + "mxRecords": [], + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/properties/origin", + "rel": "self" + } + ], + "livenessTests": [ + { + "disableNonstandardPortWarning": false, + "hostHeader": "foo.example.com", + "httpError3xx": true, + "httpError4xx": true, + "httpError5xx": true, + "name": "health-check", + "requestString": null, + "responseString": null, + "sslClientCertificate": null, + "sslClientPrivateKey": null, + "testInterval": 60, + "testObject": "/status", + "testObjectPassword": null, + "testObjectPort": 80, + "testObjectProtocol": "HTTP", + "testObjectUsername": null, + "testTimeout": 25.0 + } + ], + "trafficTargets": [ + { + "datacenterId": 3134, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.5" + ], + "precedence": null + }, + { + "datacenterId": 3133, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.4" + ], + "precedence": null + } + ] + }, + "status": { + "changeId": "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + "message": "Change Pending", + "passingValidation": true, + "propagationStatus": "PENDING", + "propagationStatusDate": "2014-04-15T11:30:27.000+0000", + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/status/current", + "rel": "self" + } + ] + } +} +`, + expectedResponse: &PropertyResponse{ + Resource: &Property{ + BalanceByDownloadScore: false, + HandoutMode: "normal", + IPv6: false, + Name: "origin", + ScoreAggregationType: "mean", + StaticTTL: 600, + DynamicTTL: 300, + Type: "weighted-round-robin", + UseComputedTargets: false, + LivenessTests: []*LivenessTest{ + { + DisableNonstandardPortWarning: false, + HTTPError3xx: true, + HTTPError4xx: true, + HTTPError5xx: true, + Name: "health-check", + TestInterval: 60, + TestObject: "/status", + TestObjectPort: 80, + TestObjectProtocol: "HTTP", + TestTimeout: 25.0, + }, + }, + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 3134, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.5"}, + }, + { + DatacenterID: 3133, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.4"}, + }, + }, + Links: []*Link{ + { + Href: "/config-gtm/v1/domains/example.akadns.net/properties/origin", + Rel: "self", + }, + }, + }, + Status: &ResponseStatus{ + ChangeID: "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + Message: "Change Pending", + PassingValidation: true, + PropagationStatus: "PENDING", + PropagationStatusDate: "2014-04-15T11:30:27.000+0000", + Links: &[]Link{ + { + Href: "/config-gtm/v1/domains/example.akadns.net/status/current", + Rel: "self", + }, + }, + }, + }, + expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", + }, + "201 Created - ranked-failover": { + property: &Property{ + BalanceByDownloadScore: false, + HandoutMode: "normal", + IPv6: false, + Name: "origin", + ScoreAggregationType: "mean", + StaticTTL: 600, + Type: "ranked-failover", + UseComputedTargets: false, + LivenessTests: []*LivenessTest{ + { + DisableNonstandardPortWarning: false, + HTTPError3xx: true, + HTTPError4xx: true, + HTTPError5xx: true, + HTTPMethod: tools.StringPtr("GET"), + HTTPRequestBody: tools.StringPtr("TestBody"), + Name: "health-check", + TestInterval: 60, + TestObject: "/status", + TestObjectPort: 80, + TestObjectProtocol: "HTTP", + TestTimeout: 25.0, + Pre2023SecurityPosture: true, + AlternateCACertificates: []string{"test1"}, + }, + }, + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 3134, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.5"}, + Precedence: tools.IntPtr(255), + }, + { + DatacenterID: 3133, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.4"}, + Precedence: nil, + }, + }, + }, + domain: "example.akadns.net", + headers: http.Header{ + "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, + }, + responseStatus: http.StatusCreated, + responseBody: ` +{ + "resource": { + "backupCName": null, + "backupIp": null, + "balanceByDownloadScore": false, + "cname": null, + "comments": null, + "dynamicTTL": 300, + "failbackDelay": 0, + "failoverDelay": 0, + "handoutMode": "normal", + "healthMax": null, + "healthMultiplier": null, + "healthThreshold": null, + "ipv6": false, + "lastModified": null, + "loadImbalancePercentage": null, + "mapName": null, + "maxUnreachablePenalty": null, + "name": "origin", + "scoreAggregationType": "mean", + "staticTTL": 600, + "stickinessBonusConstant": 0, + "stickinessBonusPercentage": 0, + "type": "weighted-round-robin", + "unreachableThreshold": null, + "useComputedTargets": false, + "mxRecords": [], + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/properties/origin", + "rel": "self" + } + ], + "livenessTests": [ + { + "disableNonstandardPortWarning": false, + "hostHeader": "foo.example.com", + "httpError3xx": true, + "httpError4xx": true, + "httpError5xx": true, + "httpMethod": "GET", + "httpRequestBody": "TestBody", + "pre2023SecurityPosture": true, + "alternateCACertificates": ["test1"], + "name": "health-check", + "requestString": null, + "responseString": null, + "sslClientCertificate": null, + "sslClientPrivateKey": null, + "testInterval": 60, + "testObject": "/status", + "testObjectPassword": null, + "testObjectPort": 80, + "testObjectProtocol": "HTTP", + "testObjectUsername": null, + "testTimeout": 25.0 + } + ], + "trafficTargets": [ + { + "datacenterId": 3134, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.5" + ], + "precedence": 255 + }, + { + "datacenterId": 3133, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.4" + ], + "precedence": null + } + ] + }, + "status": { + "changeId": "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + "message": "Change Pending", + "passingValidation": true, + "propagationStatus": "PENDING", + "propagationStatusDate": "2014-04-15T11:30:27.000+0000", + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/status/current", + "rel": "self" + } + ] + } +} +`, + expectedResponse: &PropertyResponse{ + Resource: &Property{ + BalanceByDownloadScore: false, + HandoutMode: "normal", + IPv6: false, + Name: "origin", + ScoreAggregationType: "mean", + StaticTTL: 600, + DynamicTTL: 300, + Type: "weighted-round-robin", + UseComputedTargets: false, + LivenessTests: []*LivenessTest{ + { + DisableNonstandardPortWarning: false, + HTTPError3xx: true, + HTTPError4xx: true, + HTTPError5xx: true, + HTTPMethod: tools.StringPtr("GET"), + HTTPRequestBody: tools.StringPtr("TestBody"), + Pre2023SecurityPosture: true, + AlternateCACertificates: []string{"test1"}, + Name: "health-check", + TestInterval: 60, + TestObject: "/status", + TestObjectPort: 80, + TestObjectProtocol: "HTTP", + TestTimeout: 25.0, + }, + }, + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 3134, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.5"}, + Precedence: tools.IntPtr(255), + }, + { + DatacenterID: 3133, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.4"}, + Precedence: nil, + }, + }, + Links: []*Link{ + { + Href: "/config-gtm/v1/domains/example.akadns.net/properties/origin", + Rel: "self", + }, + }, + }, + Status: &ResponseStatus{ + ChangeID: "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + Message: "Change Pending", + PassingValidation: true, + PropagationStatus: "PENDING", + PropagationStatusDate: "2014-04-15T11:30:27.000+0000", + Links: &[]Link{ + { + Href: "/config-gtm/v1/domains/example.akadns.net/status/current", + Rel: "self", + }, + }, + }, + }, + expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", + }, + "validation error - missing precedence for ranked-failover property type": { + property: &Property{ + Type: "ranked-failover", + Name: "property", + HandoutMode: "normal", + ScoreAggregationType: "mean", + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 1, + Enabled: false, + Precedence: nil, + }, + { + DatacenterID: 2, + Enabled: false, + Precedence: nil, + }, + }, + }, + withError: true, + assertError: func(t *testing.T, err error) { + assert.ErrorContains(t, err, "TrafficTargets: property cannot have multiple primary traffic targets (targets with lowest precedence)") + }, + }, + "validation error - precedence value over the limit": { + property: &Property{ + Type: "ranked-failover", + Name: "property", + HandoutMode: "normal", + ScoreAggregationType: "mean", + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 1, + Enabled: false, + Precedence: tools.IntPtr(256), + }, + }, + }, + withError: true, + assertError: func(t *testing.T, err error) { + assert.ErrorContains(t, err, "property validation failed. TrafficTargets: 'Precedence' value has to be between 0 and 255") + }, }, "500 internal server error": { - prop: &req, + property: &Property{ + Name: "testName", + HandoutMode: "normal", + ScoreAggregationType: "mean", + Type: "failover", + }, domain: "example.akadns.net", responseStatus: http.StatusInternalServerError, - responseBody: []byte(` -{ - "type": "internal_error", - "title": "Internal Server Error", - "detail": "Error creating domain" -}`), + responseBody: ` + { + "type": "internal_error", + "title": "Internal Server Error", + "detail": "Error creating domain" + }`, expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", - withError: &Error{ - Type: "internal_error", - Title: "Internal Server Error", - Detail: "Error creating domain", - StatusCode: http.StatusInternalServerError, + withError: true, + assertError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error creating domain", + StatusCode: http.StatusInternalServerError, + } + assert.ErrorIs(t, err, want) }, }, } @@ -270,7 +672,7 @@ func TestGtm_CreateProperty(t *testing.T) { assert.Equal(t, http.MethodPut, r.Method) w.WriteHeader(test.responseStatus) if len(test.responseBody) > 0 { - _, err := w.Write(test.responseBody) + _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) } })) @@ -278,9 +680,9 @@ func TestGtm_CreateProperty(t *testing.T) { result, err := client.CreateProperty( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.prop, test.domain) - if test.withError != nil { - assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) + session.WithContextHeaders(test.headers)), test.property, test.domain) + if test.withError { + test.assertError(t, err) return } require.NoError(t, err) @@ -289,67 +691,236 @@ func TestGtm_CreateProperty(t *testing.T) { } } -// Test Update domain. -// UpdateProperty(context.Context, *Property, map[string]string) (*PropertyResponse, error) -func TestGtm_UpdateProperty(t *testing.T) { - var result PropertyResponse - var req Property - - respData, err := loadTestData("TestGtm_CreateProperty.resp.json") - if err != nil { - t.Fatal(err) - } - - if err := json.NewDecoder(bytes.NewBuffer(respData)).Decode(&result); err != nil { - t.Fatal(err) - } - - reqData, err := loadTestData("TestGtm_CreateProperty.req.json") - if err != nil { - t.Fatal(err) - } - - if err := json.NewDecoder(bytes.NewBuffer(reqData)).Decode(&req); err != nil { - t.Fatal(err) - } - +func TestGTM_UpdateProperty(t *testing.T) { tests := map[string]struct { - prop *Property + property *Property domain string responseStatus int - responseBody []byte + responseBody string expectedPath string expectedResponse *ResponseStatus - withError error + withError bool + assertError func(*testing.T, error) headers http.Header }{ "200 Success": { - prop: &req, + property: &Property{ + BalanceByDownloadScore: false, + HandoutMode: "normal", + IPv6: false, + Name: "origin", + ScoreAggregationType: "mean", + StaticTTL: 600, + Type: "weighted-round-robin", + UseComputedTargets: false, + LivenessTests: []*LivenessTest{ + { + DisableNonstandardPortWarning: false, + HTTPError3xx: true, + HTTPError4xx: true, + HTTPError5xx: true, + Name: "health-check", + TestInterval: 60, + TestObject: "/status", + TestObjectPort: 80, + TestObjectProtocol: "HTTP", + TestTimeout: 25.0, + }, + }, + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 3134, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.5"}, + Precedence: tools.IntPtr(255), + }, + { + DatacenterID: 3133, + Enabled: true, + Weight: 50.0, + Servers: []string{"1.2.3.4"}, + Precedence: nil, + }, + }, + }, domain: "example.akadns.net", headers: http.Header{ "Content-Type": []string{"application/vnd.config-gtm.v1.4+json;charset=UTF-8"}, }, - responseStatus: http.StatusCreated, - responseBody: respData, - expectedResponse: result.Status, - expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", + responseStatus: http.StatusCreated, + responseBody: ` +{ + "resource": { + "backupCName": null, + "backupIp": null, + "balanceByDownloadScore": false, + "cname": null, + "comments": null, + "dynamicTTL": 300, + "failbackDelay": 0, + "failoverDelay": 0, + "handoutMode": "normal", + "healthMax": null, + "healthMultiplier": null, + "healthThreshold": null, + "ipv6": false, + "lastModified": null, + "loadImbalancePercentage": null, + "mapName": null, + "maxUnreachablePenalty": null, + "name": "origin", + "scoreAggregationType": "mean", + "staticTTL": 600, + "stickinessBonusConstant": 0, + "stickinessBonusPercentage": 0, + "type": "weighted-round-robin", + "unreachableThreshold": null, + "useComputedTargets": false, + "mxRecords": [], + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/properties/origin", + "rel": "self" + } + ], + "livenessTests": [ + { + "disableNonstandardPortWarning": false, + "hostHeader": "foo.example.com", + "httpError3xx": true, + "httpError4xx": true, + "httpError5xx": true, + "name": "health-check", + "requestString": null, + "responseString": null, + "sslClientCertificate": null, + "sslClientPrivateKey": null, + "testInterval": 60, + "testObject": "/status", + "testObjectPassword": null, + "testObjectPort": 80, + "testObjectProtocol": "HTTP", + "testObjectUsername": null, + "testTimeout": 25.0 + } + ], + "trafficTargets": [ + { + "datacenterId": 3134, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.5" + ], + "precedence": 255 + }, + { + "datacenterId": 3133, + "enabled": true, + "handoutCName": null, + "name": null, + "weight": 50.0, + "servers": [ + "1.2.3.4" + ], + "precedence": null + } + ] + }, + "status": { + "changeId": "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + "message": "Change Pending", + "passingValidation": true, + "propagationStatus": "PENDING", + "propagationStatusDate": "2014-04-15T11:30:27.000+0000", + "links": [ + { + "href": "/config-gtm/v1/domains/example.akadns.net/status/current", + "rel": "self" + } + ] + } +} +`, + expectedResponse: &ResponseStatus{ + ChangeID: "eee0c3b4-0e45-4f4b-822c-7dbc60764d18", + Message: "Change Pending", + PassingValidation: true, + PropagationStatus: "PENDING", + PropagationStatusDate: "2014-04-15T11:30:27.000+0000", + Links: &[]Link{ + { + Href: "/config-gtm/v1/domains/example.akadns.net/status/current", + Rel: "self", + }, + }, + }, + expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", + }, + "validation error - missing precedence for ranked-failover property type": { + property: &Property{ + Type: "ranked-failover", + Name: "property", + HandoutMode: "normal", + ScoreAggregationType: "mean", + TrafficTargets: []*TrafficTarget{ + { + DatacenterID: 1, + Enabled: false, + Precedence: nil, + }, + { + DatacenterID: 2, + Enabled: false, + Precedence: nil, + }, + }, + }, + withError: true, + assertError: func(t *testing.T, err error) { + assert.ErrorContains(t, err, "TrafficTargets: property cannot have multiple primary traffic targets (targets with lowest precedence)") + }, + }, + "validation error - no traffic targets": { + property: &Property{ + Type: "ranked-failover", + Name: "property", + HandoutMode: "normal", + ScoreAggregationType: "mean", + }, + withError: true, + assertError: func(t *testing.T, err error) { + assert.ErrorContains(t, err, "property validation failed. TrafficTargets: no traffic targets are enabled") + }, }, "500 internal server error": { - prop: &req, + property: &Property{ + Name: "testName", + HandoutMode: "normal", + ScoreAggregationType: "mean", + Type: "failover", + }, domain: "example.akadns.net", responseStatus: http.StatusInternalServerError, - responseBody: []byte(` + responseBody: ` { "type": "internal_error", "title": "Internal Server Error", "detail": "Error creating zone" -}`), +}`, expectedPath: "/config-gtm/v1/domains/example.akadns.net?contractId=1-2ABCDE", - withError: &Error{ - Type: "internal_error", - Title: "Internal Server Error", - Detail: "Error creating zone", - StatusCode: http.StatusInternalServerError, + withError: true, + assertError: func(t *testing.T, err error) { + want := &Error{ + Type: "internal_error", + Title: "Internal Server Error", + Detail: "Error creating zone", + StatusCode: http.StatusInternalServerError, + } + assert.ErrorIs(t, err, want) }, }, } @@ -360,7 +931,7 @@ func TestGtm_UpdateProperty(t *testing.T) { assert.Equal(t, http.MethodPut, r.Method) w.WriteHeader(test.responseStatus) if len(test.responseBody) > 0 { - _, err := w.Write(test.responseBody) + _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) } })) @@ -368,9 +939,9 @@ func TestGtm_UpdateProperty(t *testing.T) { result, err := client.UpdateProperty( session.ContextWithOptions( context.Background(), - session.WithContextHeaders(test.headers)), test.prop, test.domain) - if test.withError != nil { - assert.True(t, errors.Is(err, test.withError), "want: %s; got: %s", test.withError, err) + session.WithContextHeaders(test.headers)), test.property, test.domain) + if test.withError { + test.assertError(t, err) return } require.NoError(t, err) @@ -379,11 +950,11 @@ func TestGtm_UpdateProperty(t *testing.T) { } } -func TestGtm_DeleteProperty(t *testing.T) { +func TestGTM_DeleteProperty(t *testing.T) { var result PropertyResponse var req Property - respData, err := loadTestData("TestGtm_CreateProperty.resp.json") + respData, err := loadTestData("TestGTM_CreateProperty.resp.json") if err != nil { t.Fatal(err) } @@ -392,7 +963,7 @@ func TestGtm_DeleteProperty(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateProperty.req.json") + reqData, err := loadTestData("TestGTM_CreateProperty.req.json") if err != nil { t.Fatal(err) } diff --git a/pkg/gtm/resource.go b/pkg/gtm/resource.go index 2efb9dd2..92a7d8c9 100644 --- a/pkg/gtm/resource.go +++ b/pkg/gtm/resource.go @@ -6,18 +6,9 @@ import ( "net/http" ) -// -// Handle Operations on gtm resources -// Based on 1.4 schema -// - // Resources contains operations available on a Resource resource. type Resources interface { - // NewResourceInstance instantiates a new ResourceInstance. - NewResourceInstance(context.Context, *Resource, int) *ResourceInstance - // NewResource creates a new Resource object. - NewResource(context.Context, string) *Resource - // ListResources retreieves all Resources + // ListResources retrieves all Resources // // See: https://techdocs.akamai.com/gtm/reference/get-resources ListResources(context.Context, string) ([]*Resource, error) @@ -41,7 +32,7 @@ type Resources interface { // ResourceInstance contains information about the resources that constrain the properties within the data center type ResourceInstance struct { - DatacenterId int `json:"datacenterId"` + DatacenterID int `json:"datacenterId"` UseDefaultLoadObject bool `json:"useDefaultLoadObject"` LoadObject } @@ -70,163 +61,134 @@ type ResourceList struct { } // Validate validates Resource -func (rsrc *Resource) Validate() error { - - if len(rsrc.Name) < 1 { - return fmt.Errorf("Resource is missing Name") +func (r *Resource) Validate() error { + if len(r.Name) < 1 { + return fmt.Errorf("resource is missing Name") } - if len(rsrc.Type) < 1 { - return fmt.Errorf("Resource is missing Type") + if len(r.Type) < 1 { + return fmt.Errorf("resource is missing Type") } return nil } -func (p *gtm) NewResourceInstance(ctx context.Context, _ *Resource, dcID int) *ResourceInstance { - - logger := p.Log(ctx) - logger.Debug("NewResourceInstance") - - return &ResourceInstance{DatacenterId: dcID} - -} - -func (p *gtm) NewResource(ctx context.Context, name string) *Resource { - - logger := p.Log(ctx) - logger.Debug("NewResource") - - resource := &Resource{Name: name} - return resource -} - -func (p *gtm) ListResources(ctx context.Context, domainName string) ([]*Resource, error) { - - logger := p.Log(ctx) +func (g *gtm) ListResources(ctx context.Context, domainName string) ([]*Resource, error) { + logger := g.Log(ctx) logger.Debug("ListResources") - var rsrcs ResourceList getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources", domainName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create ListResources request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &rsrcs) + + var result ResourceList + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("ListResources request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return rsrcs.ResourceItems, nil + return result.ResourceItems, nil } -func (p *gtm) GetResource(ctx context.Context, name, domainName string) (*Resource, error) { - - logger := p.Log(ctx) +func (g *gtm) GetResource(ctx context.Context, resourceName, domainName string) (*Resource, error) { + logger := g.Log(ctx) logger.Debug("GetResource") - var rsc Resource - getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, name) + getURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, resourceName) req, err := http.NewRequestWithContext(ctx, http.MethodGet, getURL, nil) if err != nil { return nil, fmt.Errorf("failed to create GetResource request: %w", err) } setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &rsc) + + var result Resource + resp, err := g.Exec(req, &result) if err != nil { return nil, fmt.Errorf("GetResource request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &rsc, nil + return &result, nil } -func (p *gtm) CreateResource(ctx context.Context, rsrc *Resource, domainName string) (*ResourceResponse, error) { - - logger := p.Log(ctx) +func (g *gtm) CreateResource(ctx context.Context, resource *Resource, domainName string) (*ResourceResponse, error) { + logger := g.Log(ctx) logger.Debug("CreateResource") - // Use common code. Any specific validation needed? - return rsrc.save(ctx, p, domainName) - + return resource.save(ctx, g, domainName) } -func (p *gtm) UpdateResource(ctx context.Context, rsrc *Resource, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) UpdateResource(ctx context.Context, resource *Resource, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("UpdateResource") - // common code - stat, err := rsrc.save(ctx, p, domainName) + stat, err := resource.save(ctx, g, domainName) if err != nil { return nil, err } return stat.Status, err - } // save is a function that saves Resource in given domain. Common path for Create and Update. -func (rsrc *Resource) save(ctx context.Context, p *gtm, domainName string) (*ResourceResponse, error) { - - if err := rsrc.Validate(); err != nil { - return nil, fmt.Errorf("Resource validation failed. %w", err) +func (r *Resource) save(ctx context.Context, g *gtm, domainName string) (*ResourceResponse, error) { + if err := r.Validate(); err != nil { + return nil, fmt.Errorf("resource validation failed. %w", err) } - putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, rsrc.Name) + putURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, r.Name) req, err := http.NewRequestWithContext(ctx, http.MethodPut, putURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Resource request: %w", err) } - - var rscresp ResourceResponse setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &rscresp, rsrc) + + var result ResourceResponse + resp, err := g.Exec(req, &result, r) if err != nil { - return nil, fmt.Errorf("Resource request failed: %w", err) + return nil, fmt.Errorf("resource request failed: %w", err) } if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return &rscresp, nil - + return &result, nil } -func (p *gtm) DeleteResource(ctx context.Context, rsrc *Resource, domainName string) (*ResponseStatus, error) { - - logger := p.Log(ctx) +func (g *gtm) DeleteResource(ctx context.Context, resource *Resource, domainName string) (*ResponseStatus, error) { + logger := g.Log(ctx) logger.Debug("DeleteResource") - if err := rsrc.Validate(); err != nil { + if err := resource.Validate(); err != nil { logger.Errorf("Resource validation failed. %w", err) - return nil, fmt.Errorf("Resource validation failed. %w", err) + return nil, fmt.Errorf("DeleteResource validation failed. %w", err) } - delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, rsrc.Name) + delURL := fmt.Sprintf("/config-gtm/v1/domains/%s/resources/%s", domainName, resource.Name) req, err := http.NewRequestWithContext(ctx, http.MethodDelete, delURL, nil) if err != nil { return nil, fmt.Errorf("failed to create Delete request: %w", err) } - - var rscresp ResponseBody setVersionHeader(req, schemaVersion) - resp, err := p.Exec(req, &rscresp) + + var result ResponseBody + resp, err := g.Exec(req, &result) if err != nil { - return nil, fmt.Errorf("Resource request failed: %w", err) + return nil, fmt.Errorf("DeleteResource request failed: %w", err) } if resp.StatusCode != http.StatusOK { - return nil, p.Error(resp) + return nil, g.Error(resp) } - return rscresp.Status, nil - + return result.Status, nil } diff --git a/pkg/gtm/resource_test.go b/pkg/gtm/resource_test.go index 5e6df887..56bae885 100644 --- a/pkg/gtm/resource_test.go +++ b/pkg/gtm/resource_test.go @@ -9,31 +9,15 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) -func TestGtm_NewResourceInstance(t *testing.T) { - client := Client(session.Must(session.New())) - - inst := client.NewResourceInstance(context.Background(), nil, 0) - - assert.NotNil(t, inst) -} - -func TestGtm_NewResource(t *testing.T) { - client := Client(session.Must(session.New())) - - res := client.NewResource(context.Background(), "foo") - - assert.NotNil(t, res) -} - -func TestGtm_ListResources(t *testing.T) { +func TestGTM_ListResources(t *testing.T) { var result ResourceList - respData, err := loadTestData("TestGtm_ListResources.resp.json") + respData, err := loadTestData("TestGTM_ListResources.resp.json") if err != nil { t.Fatal(err) } @@ -106,12 +90,10 @@ func TestGtm_ListResources(t *testing.T) { } } -// Test GetResource -// GetResource(context.Context, string) (*Resource, error) -func TestGtm_GetResource(t *testing.T) { +func TestGTM_GetResource(t *testing.T) { var result Resource - respData, err := loadTestData("TestGtm_GetResource.resp.json") + respData, err := loadTestData("TestGTM_GetResource.resp.json") if err != nil { t.Fatal(err) } @@ -178,13 +160,11 @@ func TestGtm_GetResource(t *testing.T) { } } -// Test Create domain. -// CreateResource(context.Context, *Resource, map[string]string) (*ResourceResponse, error) -func TestGtm_CreateResource(t *testing.T) { +func TestGTM_CreateResource(t *testing.T) { var result ResourceResponse var req Resource - respData, err := loadTestData("TestGtm_CreateResource.resp.json") + respData, err := loadTestData("TestGTM_CreateResource.resp.json") if err != nil { t.Fatal(err) } @@ -193,7 +173,7 @@ func TestGtm_CreateResource(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateResource.req.json") + reqData, err := loadTestData("TestGTM_CreateResource.req.json") if err != nil { t.Fatal(err) } @@ -268,13 +248,11 @@ func TestGtm_CreateResource(t *testing.T) { } } -// Test Update domain. -// UpdateResource(context.Context, *Resource, map[string]string) (*ResourceResponse, error) -func TestGtm_UpdateResource(t *testing.T) { +func TestGTM_UpdateResource(t *testing.T) { var result ResourceResponse var req Resource - respData, err := loadTestData("TestGtm_CreateResource.resp.json") + respData, err := loadTestData("TestGTM_CreateResource.resp.json") if err != nil { t.Fatal(err) } @@ -283,7 +261,7 @@ func TestGtm_UpdateResource(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateResource.req.json") + reqData, err := loadTestData("TestGTM_CreateResource.req.json") if err != nil { t.Fatal(err) } @@ -358,11 +336,11 @@ func TestGtm_UpdateResource(t *testing.T) { } } -func TestGtm_DeleteResource(t *testing.T) { +func TestGTM_DeleteResource(t *testing.T) { var result ResourceResponse var req Resource - respData, err := loadTestData("TestGtm_CreateResource.resp.json") + respData, err := loadTestData("TestGTM_CreateResource.resp.json") if err != nil { t.Fatal(err) } @@ -371,7 +349,7 @@ func TestGtm_DeleteResource(t *testing.T) { t.Fatal(err) } - reqData, err := loadTestData("TestGtm_CreateResource.req.json") + reqData, err := loadTestData("TestGTM_CreateResource.req.json") if err != nil { t.Fatal(err) } diff --git a/pkg/gtm/testdata/TestGtm_CreateAsMap.req.json b/pkg/gtm/testdata/TestGTM_CreateASMap.req.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateAsMap.req.json rename to pkg/gtm/testdata/TestGTM_CreateASMap.req.json diff --git a/pkg/gtm/testdata/TestGtm_CreateAsMap.resp.json b/pkg/gtm/testdata/TestGTM_CreateASMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateAsMap.resp.json rename to pkg/gtm/testdata/TestGTM_CreateASMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateCidrMap.req.json b/pkg/gtm/testdata/TestGTM_CreateCIDRMap.req.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateCidrMap.req.json rename to pkg/gtm/testdata/TestGTM_CreateCIDRMap.req.json diff --git a/pkg/gtm/testdata/TestGtm_CreateCidrMap.resp.json b/pkg/gtm/testdata/TestGTM_CreateCIDRMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateCidrMap.resp.json rename to pkg/gtm/testdata/TestGTM_CreateCIDRMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateDatacenter.req.json b/pkg/gtm/testdata/TestGTM_CreateDatacenter.req.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateDatacenter.req.json rename to pkg/gtm/testdata/TestGTM_CreateDatacenter.req.json diff --git a/pkg/gtm/testdata/TestGtm_CreateDatacenter.resp.json b/pkg/gtm/testdata/TestGTM_CreateDatacenter.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateDatacenter.resp.json rename to pkg/gtm/testdata/TestGTM_CreateDatacenter.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateDomain.resp.json b/pkg/gtm/testdata/TestGTM_CreateDomain.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateDomain.resp.json rename to pkg/gtm/testdata/TestGTM_CreateDomain.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateGeoMap.req.json b/pkg/gtm/testdata/TestGTM_CreateGeoMap.req.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateGeoMap.req.json rename to pkg/gtm/testdata/TestGTM_CreateGeoMap.req.json diff --git a/pkg/gtm/testdata/TestGtm_CreateGeoMap.resp.json b/pkg/gtm/testdata/TestGTM_CreateGeoMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateGeoMap.resp.json rename to pkg/gtm/testdata/TestGTM_CreateGeoMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateIPv4DefaultDatacenter.resp.json b/pkg/gtm/testdata/TestGTM_CreateIPv4DefaultDatacenter.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateIPv4DefaultDatacenter.resp.json rename to pkg/gtm/testdata/TestGTM_CreateIPv4DefaultDatacenter.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateIPv6DefaultDatacenter.resp.json b/pkg/gtm/testdata/TestGTM_CreateIPv6DefaultDatacenter.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateIPv6DefaultDatacenter.resp.json rename to pkg/gtm/testdata/TestGTM_CreateIPv6DefaultDatacenter.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateMapsDefaultDatacenter.resp.json b/pkg/gtm/testdata/TestGTM_CreateMapsDefaultDatacenter.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateMapsDefaultDatacenter.resp.json rename to pkg/gtm/testdata/TestGTM_CreateMapsDefaultDatacenter.resp.json diff --git a/pkg/gtm/testdata/TestGtm_CreateResource.req.json b/pkg/gtm/testdata/TestGTM_CreateProperty.req.json similarity index 97% rename from pkg/gtm/testdata/TestGtm_CreateResource.req.json rename to pkg/gtm/testdata/TestGTM_CreateProperty.req.json index 6f4727ce..576ff4a8 100644 --- a/pkg/gtm/testdata/TestGtm_CreateResource.req.json +++ b/pkg/gtm/testdata/TestGTM_CreateProperty.req.json @@ -43,7 +43,8 @@ "weight": 50.0, "servers": [ "1.2.3.5" - ] + ], + "precedence": 255 }, { "datacenterId": 3133, diff --git a/pkg/gtm/testdata/TestGtm_CreateResource.resp.json b/pkg/gtm/testdata/TestGTM_CreateProperty.resp.json similarity index 96% rename from pkg/gtm/testdata/TestGtm_CreateResource.resp.json rename to pkg/gtm/testdata/TestGTM_CreateProperty.resp.json index d4afe3d1..a4707498 100644 --- a/pkg/gtm/testdata/TestGtm_CreateResource.resp.json +++ b/pkg/gtm/testdata/TestGTM_CreateProperty.resp.json @@ -62,7 +62,8 @@ "weight": 50.0, "servers": [ "1.2.3.5" - ] + ], + "precedence": 255 }, { "datacenterId": 3133, @@ -72,7 +73,8 @@ "weight": 50.0, "servers": [ "1.2.3.4" - ] + ], + "precedence": null } ] }, diff --git a/pkg/gtm/testdata/TestGtm_CreateProperty.req.json b/pkg/gtm/testdata/TestGTM_CreateResource.req.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateProperty.req.json rename to pkg/gtm/testdata/TestGTM_CreateResource.req.json diff --git a/pkg/gtm/testdata/TestGtm_CreateProperty.resp.json b/pkg/gtm/testdata/TestGTM_CreateResource.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_CreateProperty.resp.json rename to pkg/gtm/testdata/TestGTM_CreateResource.resp.json diff --git a/pkg/gtm/testdata/TestGtm_GetAsMap.resp.json b/pkg/gtm/testdata/TestGTM_GetASMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_GetAsMap.resp.json rename to pkg/gtm/testdata/TestGTM_GetASMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_GetCidrMap.resp.json b/pkg/gtm/testdata/TestGTM_GetCIDRMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_GetCidrMap.resp.json rename to pkg/gtm/testdata/TestGTM_GetCIDRMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_GetDatacenter.resp.json b/pkg/gtm/testdata/TestGTM_GetDatacenter.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_GetDatacenter.resp.json rename to pkg/gtm/testdata/TestGTM_GetDatacenter.resp.json diff --git a/pkg/gtm/testdata/TestGtm_GetDomain.resp.json b/pkg/gtm/testdata/TestGTM_GetDomain.resp.json similarity index 99% rename from pkg/gtm/testdata/TestGtm_GetDomain.resp.json rename to pkg/gtm/testdata/TestGTM_GetDomain.resp.json index 3fe293ed..8b9eeeec 100644 --- a/pkg/gtm/testdata/TestGtm_GetDomain.resp.json +++ b/pkg/gtm/testdata/TestGTM_GetDomain.resp.json @@ -13,6 +13,8 @@ "roundRobinPrefix": null, "servermonitorLivenessCount": null, "servermonitorLoadCount": null, + "signAndServe": true, + "signAndServeAlgorithm": "RSA-SHA1", "type": "full", "emailNotificationList": [], "status": { diff --git a/pkg/gtm/testdata/TestGtm_GetGeoMap.resp.json b/pkg/gtm/testdata/TestGTM_GetGeoMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_GetGeoMap.resp.json rename to pkg/gtm/testdata/TestGTM_GetGeoMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_GetProperty.resp.json b/pkg/gtm/testdata/TestGTM_GetProperty.resp.json similarity index 95% rename from pkg/gtm/testdata/TestGtm_GetProperty.resp.json rename to pkg/gtm/testdata/TestGTM_GetProperty.resp.json index 9c874e11..c0a2d53d 100644 --- a/pkg/gtm/testdata/TestGtm_GetProperty.resp.json +++ b/pkg/gtm/testdata/TestGTM_GetProperty.resp.json @@ -61,7 +61,8 @@ "weight": 0.0, "servers": [ "1.2.3.5" - ] + ], + "precedence": 255 }, { "datacenterId": 3133, @@ -71,7 +72,8 @@ "weight": 1.0, "servers": [ "1.2.3.4" - ] + ], + "precedence": null } ] } \ No newline at end of file diff --git a/pkg/gtm/testdata/TestGtm_GetResource.resp.json b/pkg/gtm/testdata/TestGTM_GetResource.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_GetResource.resp.json rename to pkg/gtm/testdata/TestGTM_GetResource.resp.json diff --git a/pkg/gtm/testdata/TestGtm_ListAsMap.resp.json b/pkg/gtm/testdata/TestGTM_ListASMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_ListAsMap.resp.json rename to pkg/gtm/testdata/TestGTM_ListASMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_ListCidrMap.resp.json b/pkg/gtm/testdata/TestGTM_ListCIDRMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_ListCidrMap.resp.json rename to pkg/gtm/testdata/TestGTM_ListCIDRMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_ListDatacenters.resp.json b/pkg/gtm/testdata/TestGTM_ListDatacenters.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_ListDatacenters.resp.json rename to pkg/gtm/testdata/TestGTM_ListDatacenters.resp.json diff --git a/pkg/gtm/testdata/TestGtm_ListGeoMap.resp.json b/pkg/gtm/testdata/TestGTM_ListGeoMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_ListGeoMap.resp.json rename to pkg/gtm/testdata/TestGTM_ListGeoMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_ListProperties.resp.json b/pkg/gtm/testdata/TestGTM_ListProperties.resp.json similarity index 92% rename from pkg/gtm/testdata/TestGtm_ListProperties.resp.json rename to pkg/gtm/testdata/TestGTM_ListProperties.resp.json index 6669bc97..4ca89f9a 100644 --- a/pkg/gtm/testdata/TestGtm_ListProperties.resp.json +++ b/pkg/gtm/testdata/TestGTM_ListProperties.resp.json @@ -44,7 +44,8 @@ "weight": 0.0, "servers": [ "1.2.3.5" - ] + ], + "precedence": 255 }, { "datacenterId": 3133, @@ -52,7 +53,8 @@ "weight": 1.0, "servers": [ "1.2.3.4" - ] + ], + "precedence": null } ] }, @@ -86,7 +88,8 @@ "weight": 1.0, "servers": [ "2001:4878::5043:4078" - ] + ], + "precedence": 255 }, { "datacenterId": 3133, @@ -95,7 +98,8 @@ "servers": [ "2001:4878::5043:4072", "2001:4878::5043:4071" - ] + ], + "precedence": null } ] } diff --git a/pkg/gtm/testdata/TestGtm_ListResources.resp.json b/pkg/gtm/testdata/TestGTM_ListResources.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_ListResources.resp.json rename to pkg/gtm/testdata/TestGTM_ListResources.resp.json diff --git a/pkg/gtm/testdata/TestGtm_NullFieldMap.resp.json b/pkg/gtm/testdata/TestGTM_NullFieldMap.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_NullFieldMap.resp.json rename to pkg/gtm/testdata/TestGTM_NullFieldMap.resp.json diff --git a/pkg/gtm/testdata/TestGtm_NullFieldMap.result.gob b/pkg/gtm/testdata/TestGTM_NullFieldMap.result.gob similarity index 100% rename from pkg/gtm/testdata/TestGtm_NullFieldMap.result.gob rename to pkg/gtm/testdata/TestGTM_NullFieldMap.result.gob diff --git a/pkg/gtm/testdata/TestGtm_UpdateDomain.resp.json b/pkg/gtm/testdata/TestGTM_UpdateDomain.resp.json similarity index 100% rename from pkg/gtm/testdata/TestGtm_UpdateDomain.resp.json rename to pkg/gtm/testdata/TestGTM_UpdateDomain.resp.json diff --git a/pkg/hapi/edgehostname.go b/pkg/hapi/edgehostname.go index bb9ed7cc..05dc1d2b 100644 --- a/pkg/hapi/edgehostname.go +++ b/pkg/hapi/edgehostname.go @@ -10,7 +10,7 @@ import ( "net/http" "strings" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/hapi/errors.go b/pkg/hapi/errors.go index 41c1077b..bd00273b 100644 --- a/pkg/hapi/errors.go +++ b/pkg/hapi/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/hapi/errors_test.go b/pkg/hapi/errors_test.go index df779f4e..5145e184 100644 --- a/pkg/hapi/errors_test.go +++ b/pkg/hapi/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/hapi/hapi.go b/pkg/hapi/hapi.go index 69396b09..d3959ac0 100644 --- a/pkg/hapi/hapi.go +++ b/pkg/hapi/hapi.go @@ -6,7 +6,7 @@ package hapi import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/hapi/hapi_test.go b/pkg/hapi/hapi_test.go index c4679afa..723a152f 100644 --- a/pkg/hapi/hapi_test.go +++ b/pkg/hapi/hapi_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/iam/errors.go b/pkg/iam/errors.go index b14bb58d..b2563e96 100644 --- a/pkg/iam/errors.go +++ b/pkg/iam/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/iam/errors_test.go b/pkg/iam/errors_test.go index 48233bb4..b1e435b7 100644 --- a/pkg/iam/errors_test.go +++ b/pkg/iam/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/iam/iam.go b/pkg/iam/iam.go index 88c9423e..622ef8c0 100644 --- a/pkg/iam/iam.go +++ b/pkg/iam/iam.go @@ -4,7 +4,7 @@ package iam import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/iam/iam_test.go b/pkg/iam/iam_test.go index 8109e652..84a3a631 100644 --- a/pkg/iam/iam_test.go +++ b/pkg/iam/iam_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/iam/user_test.go b/pkg/iam/user_test.go index 269abd2d..ff5ce976 100644 --- a/pkg/iam/user_test.go +++ b/pkg/iam/user_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/imaging/errors.go b/pkg/imaging/errors.go index be7b8e5b..9eb00c6d 100644 --- a/pkg/imaging/errors.go +++ b/pkg/imaging/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/imaging/errors_test.go b/pkg/imaging/errors_test.go index cd516b43..19001aa2 100644 --- a/pkg/imaging/errors_test.go +++ b/pkg/imaging/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/imaging/imaging.go b/pkg/imaging/imaging.go index 0616c248..f8e701b7 100644 --- a/pkg/imaging/imaging.go +++ b/pkg/imaging/imaging.go @@ -4,7 +4,7 @@ package imaging import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/imaging/imaging_test.go b/pkg/imaging/imaging_test.go index e3f01757..94138655 100644 --- a/pkg/imaging/imaging_test.go +++ b/pkg/imaging/imaging_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/imaging/policy.go b/pkg/imaging/policy.go index 8f9b4f34..58365590 100644 --- a/pkg/imaging/policy.go +++ b/pkg/imaging/policy.go @@ -7,7 +7,7 @@ import ( "fmt" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/imaging/policy_test.go b/pkg/imaging/policy_test.go index 8684cdf2..5be95c58 100644 --- a/pkg/imaging/policy_test.go +++ b/pkg/imaging/policy_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/imaging/policyset.go b/pkg/imaging/policyset.go index ba0d82ec..5e846a56 100644 --- a/pkg/imaging/policyset.go +++ b/pkg/imaging/policyset.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/networklists/activations_test.go b/pkg/networklists/activations_test.go index a04740fe..507f24dc 100644 --- a/pkg/networklists/activations_test.go +++ b/pkg/networklists/activations_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/networklists/errors.go b/pkg/networklists/errors.go index 3e439796..d6e0c900 100644 --- a/pkg/networklists/errors.go +++ b/pkg/networklists/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) var ( diff --git a/pkg/networklists/errors_test.go b/pkg/networklists/errors_test.go index b6a4f28c..c49cb97e 100644 --- a/pkg/networklists/errors_test.go +++ b/pkg/networklists/errors_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/networklists/network_list_description_test.go b/pkg/networklists/network_list_description_test.go index 340d8bbe..a2487030 100644 --- a/pkg/networklists/network_list_description_test.go +++ b/pkg/networklists/network_list_description_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/networklists/network_list_subscription_test.go b/pkg/networklists/network_list_subscription_test.go index 92fb5111..215ef255 100644 --- a/pkg/networklists/network_list_subscription_test.go +++ b/pkg/networklists/network_list_subscription_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/networklists/network_list_test.go b/pkg/networklists/network_list_test.go index 860ff695..27b5ffcf 100644 --- a/pkg/networklists/network_list_test.go +++ b/pkg/networklists/network_list_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/networklists/networklists.go b/pkg/networklists/networklists.go index a136b163..752a5044 100644 --- a/pkg/networklists/networklists.go +++ b/pkg/networklists/networklists.go @@ -6,7 +6,7 @@ package networklists import ( "errors" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" ) var ( diff --git a/pkg/networklists/networklists_test.go b/pkg/networklists/networklists_test.go index 46172087..4e9a9a2d 100644 --- a/pkg/networklists/networklists_test.go +++ b/pkg/networklists/networklists_test.go @@ -12,8 +12,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/papi/cpcode_test.go b/pkg/papi/cpcode_test.go index 10e86492..45c09406 100644 --- a/pkg/papi/cpcode_test.go +++ b/pkg/papi/cpcode_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/papi/edgehostname.go b/pkg/papi/edgehostname.go index 2c4bd5b4..6fce8a78 100644 --- a/pkg/papi/edgehostname.go +++ b/pkg/papi/edgehostname.go @@ -7,7 +7,7 @@ import ( "net/http" "strings" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/errors.go b/pkg/papi/errors.go index c3c73023..5e04a1da 100644 --- a/pkg/papi/errors.go +++ b/pkg/papi/errors.go @@ -7,7 +7,7 @@ import ( "io/ioutil" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/errs" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/errs" ) type ( diff --git a/pkg/papi/errors_test.go b/pkg/papi/errors_test.go index 0fa936d8..94b53934 100644 --- a/pkg/papi/errors_test.go +++ b/pkg/papi/errors_test.go @@ -8,8 +8,8 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/require" "github.com/tj/assert" ) diff --git a/pkg/papi/include.go b/pkg/papi/include.go index 2e2a457f..47c73df2 100644 --- a/pkg/papi/include.go +++ b/pkg/papi/include.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/include_activations.go b/pkg/papi/include_activations.go index 2de7fad2..09a68eb0 100644 --- a/pkg/papi/include_activations.go +++ b/pkg/papi/include_activations.go @@ -9,8 +9,8 @@ import ( "net/url" "strings" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/include_rule.go b/pkg/papi/include_rule.go index 445ab36c..7fcdd21a 100644 --- a/pkg/papi/include_rule.go +++ b/pkg/papi/include_rule.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/include_rule_test.go b/pkg/papi/include_rule_test.go index 3bed2942..b47ed227 100644 --- a/pkg/papi/include_rule_test.go +++ b/pkg/papi/include_rule_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/papi/include_test.go b/pkg/papi/include_test.go index a544aaa9..d47b2658 100644 --- a/pkg/papi/include_test.go +++ b/pkg/papi/include_test.go @@ -8,7 +8,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/papi/include_versions.go b/pkg/papi/include_versions.go index 8c57d886..e0a6b829 100644 --- a/pkg/papi/include_versions.go +++ b/pkg/papi/include_versions.go @@ -8,7 +8,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/papi.go b/pkg/papi/papi.go index ae52104c..6c31b961 100644 --- a/pkg/papi/papi.go +++ b/pkg/papi/papi.go @@ -5,7 +5,7 @@ import ( "errors" "net/http" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/spf13/cast" ) diff --git a/pkg/papi/papi_test.go b/pkg/papi/papi_test.go index c2cbed7c..eb4b55f1 100644 --- a/pkg/papi/papi_test.go +++ b/pkg/papi/papi_test.go @@ -8,8 +8,8 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/session" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/session" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/papi/property.go b/pkg/papi/property.go index ed15baca..88d8280f 100644 --- a/pkg/papi/property.go +++ b/pkg/papi/property.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) @@ -16,7 +16,7 @@ type ( Properties interface { // GetProperties lists properties available for the current contract and group // - // https://techdocs.akamai.com/property-mgr/reference/get-products + // https://techdocs.akamai.com/property-mgr/reference/get-properties GetProperties(ctx context.Context, r GetPropertiesRequest) (*GetPropertiesResponse, error) // CreateProperty creates a new property from scratch or bases one on another property's rule tree and optionally its set of assigned hostnames diff --git a/pkg/papi/property_test.go b/pkg/papi/property_test.go index ebce8867..83bf1236 100644 --- a/pkg/papi/property_test.go +++ b/pkg/papi/property_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/papi/propertyversion.go b/pkg/papi/propertyversion.go index 66dd9bbc..8c881fea 100644 --- a/pkg/papi/propertyversion.go +++ b/pkg/papi/propertyversion.go @@ -9,7 +9,7 @@ import ( "net/url" "strconv" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/propertyversion_test.go b/pkg/papi/propertyversion_test.go index 347fb729..5730570b 100644 --- a/pkg/papi/propertyversion_test.go +++ b/pkg/papi/propertyversion_test.go @@ -7,7 +7,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/papi/rule.go b/pkg/papi/rule.go index 81ee2d19..dd5de22e 100644 --- a/pkg/papi/rule.go +++ b/pkg/papi/rule.go @@ -7,7 +7,7 @@ import ( "net/http" "regexp" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegriderr" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegriderr" validation "github.com/go-ozzo/ozzo-validation/v4" ) diff --git a/pkg/papi/rule_test.go b/pkg/papi/rule_test.go index eb83f266..a33e795d 100644 --- a/pkg/papi/rule_test.go +++ b/pkg/papi/rule_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/tools" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/tools" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/session/request.go b/pkg/session/request.go index 1ac46b63..3eec71a8 100644 --- a/pkg/session/request.go +++ b/pkg/session/request.go @@ -42,6 +42,10 @@ func (s *session) Exec(r *http.Request, out interface{}, in ...interface{}) (*ht r.Header.Set("Content-Type", "application/json") } + if r.Header.Get("Accept") == "" { + r.Header.Set("Accept", "application/json") + } + if r.URL.Scheme == "" { r.URL.Scheme = "https" } diff --git a/pkg/session/request_test.go b/pkg/session/request_test.go index 26980e42..7e32c057 100644 --- a/pkg/session/request_test.go +++ b/pkg/session/request_test.go @@ -9,7 +9,7 @@ import ( "net/url" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -31,6 +31,7 @@ func TestSession_Exec(t *testing.T) { responseBody string responseStatus int expectedContentType string + expectedAccept string expectedUserAgent string expectedMethod string expectedPath string @@ -69,12 +70,13 @@ func TestSession_Exec(t *testing.T) { B: 1, }, }, - "GET request, custom content type and user agent": { + "GET request, custom content type, accept and user agent": { request: func() *http.Request { req, err := http.NewRequest(http.MethodGet, "/test/path", nil) require.NoError(t, err) req.Header.Set("Content-Type", "text/plain") req.Header.Set("User-Agent", "other user agent") + req.Header.Set("Accept", "text/html") return req }(), out: testStruct{}, @@ -83,18 +85,20 @@ func TestSession_Exec(t *testing.T) { expectedMethod: http.MethodGet, expectedPath: "/test/path", expectedContentType: "text/plain", + expectedAccept: "text/html", expectedUserAgent: "other user agent", expected: testStruct{ A: "text", B: 1, }, }, - "POST request, custom content type and user agent": { + "POST request, custom content type, accept and user agent": { request: func() *http.Request { req, err := http.NewRequest(http.MethodPost, "/test/path", nil) require.NoError(t, err) req.Header.Set("Content-Type", "text/plain") req.Header.Set("User-Agent", "other user agent") + req.Header.Set("Accept", "text/html") return req }(), in: []interface{}{&testStruct{ @@ -108,6 +112,7 @@ func TestSession_Exec(t *testing.T) { expectedPath: "/test/path", expectedContentType: "text/plain", expectedUserAgent: "other user agent", + expectedAccept: "text/html", expected: testStruct{ A: "text", B: 1, @@ -167,6 +172,11 @@ func TestSession_Exec(t *testing.T) { } else { assert.Equal(t, test.expectedUserAgent, r.Header.Get("User-Agent")) } + if test.expectedAccept == "" { + assert.Equal(t, "application/json", r.Header.Get("Accept")) + } else { + assert.Equal(t, test.expectedAccept, r.Header.Get("Accept")) + } w.WriteHeader(test.responseStatus) _, err := w.Write([]byte(test.responseBody)) assert.NoError(t, err) diff --git a/pkg/session/session.go b/pkg/session/session.go index 041779df..02c1913e 100644 --- a/pkg/session/session.go +++ b/pkg/session/session.go @@ -7,7 +7,7 @@ import ( "runtime" "strings" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" "github.com/apex/log" "github.com/apex/log/handlers/discard" ) @@ -63,7 +63,7 @@ var ( const ( // Version is the client version - Version = "7.0.0" + Version = "8.0.0" ) // New returns a new session diff --git a/pkg/session/session_test.go b/pkg/session/session_test.go index 38a79931..1802bee4 100644 --- a/pkg/session/session_test.go +++ b/pkg/session/session_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/v7/pkg/edgegrid" + "github.com/akamai/AkamaiOPEN-edgegrid-golang/v8/pkg/edgegrid" "github.com/apex/log" "github.com/apex/log/handlers/discard" "github.com/stretchr/testify/require" @@ -28,7 +28,7 @@ func TestNew(t *testing.T) { signer: &edgegrid.Config{}, log: log.Log, trace: false, - userAgent: "Akamai-Open-Edgegrid-golang/7.0.0 golang/" + strings.TrimPrefix(runtime.Version(), "go"), + userAgent: "Akamai-Open-Edgegrid-golang/8.0.0 golang/" + strings.TrimPrefix(runtime.Version(), "go"), }, }, "with options provided": {