From 9a1f8d748a6e8c02865262599583621175d19d9f Mon Sep 17 00:00:00 2001 From: Fernandez Ludovic Date: Mon, 28 May 2018 18:31:28 +0200 Subject: [PATCH] refactor: linting. --- account.go | 5 +- acme/client.go | 16 +- acme/crypto.go | 14 +- acme/crypto_test.go | 2 +- acme/jws.go | 16 +- acme/messages.go | 3 - acme/pop_challenge.go | 1 - cli_handlers.go | 70 +++++--- crypto.go | 2 +- providers/dns/auroradns/auroradns.go | 16 +- providers/dns/auroradns/auroradns_test.go | 6 +- providers/dns/azure/azure.go | 63 +++---- providers/dns/bluecat/bluecat.go | 119 ++++++------- providers/dns/bluecat/bluecat_test.go | 14 +- providers/dns/cloudflare/cloudflare.go | 15 +- providers/dns/cloudxns/cloudxns.go | 10 +- providers/dns/digitalocean/digitalocean.go | 47 ++--- .../dns/digitalocean/digitalocean_test.go | 2 +- providers/dns/dns_providers.go | 6 +- providers/dns/dnsimple/dnsimple.go | 15 +- providers/dns/dnsimple/dnsimple_test.go | 16 +- providers/dns/dnsmadeeasy/dnsmadeeasy.go | 8 +- providers/dns/dnsmadeeasy/dnsmadeeasy_test.go | 1 + providers/dns/duckdns/duckdns.go | 163 +++++++++--------- providers/dns/duckdns/duckdns_test.go | 130 +++++++------- providers/dns/dyn/dyn.go | 27 +-- providers/dns/exoscale/exoscale.go | 14 +- providers/dns/gandi/gandi.go | 41 ++++- providers/dns/gandi/gandi_test.go | 23 --- providers/dns/gandiv5/gandiv5.go | 19 +- providers/dns/gandiv5/gandiv5_test.go | 23 --- providers/dns/glesys/glesys.go | 28 +-- providers/dns/godaddy/godaddy.go | 10 +- providers/dns/googlecloud/googlecloud.go | 3 +- providers/dns/googlecloud/googlecloud_test.go | 1 + providers/dns/linode/linode.go | 10 +- providers/dns/namecheap/namecheap.go | 4 +- providers/dns/otc/mock.go | 12 +- providers/dns/otc/otc.go | 30 +--- providers/dns/ovh/ovh.go | 2 +- providers/dns/pdns/pdns.go | 15 +- providers/dns/rackspace/rackspace.go | 49 +++--- providers/dns/rackspace/rackspace_test.go | 9 +- providers/dns/rfc2136/rfc2136.go | 30 ++-- providers/dns/route53/route53.go | 14 +- .../dns/route53/route53_integration_test.go | 14 +- providers/dns/route53/route53_test.go | 2 +- providers/http/memcached/memcached.go | 20 +-- providers/http/memcached/memcached_test.go | 2 +- providers/http/webroot/webroot.go | 9 +- 50 files changed, 570 insertions(+), 601 deletions(-) delete mode 100644 acme/pop_challenge.go diff --git a/account.go b/account.go index e13ec0c8..938f886f 100644 --- a/account.go +++ b/account.go @@ -72,7 +72,10 @@ func NewAccount(email string, conf *Configuration) *Account { } acc.Registration = reg - acc.Save() + err = acc.Save() + if err != nil { + log.Fatalf("Could not save account for %s. Registration is nil -> %#v", email, err) + } } if acc.conf == nil { diff --git a/acme/client.go b/acme/client.go index bcab4645..786e5b2d 100644 --- a/acme/client.go +++ b/acme/client.go @@ -72,9 +72,6 @@ func NewClient(caDirURL string, user User, keyType KeyType) (*Client, error) { if dir.NewOrderURL == "" { return nil, errors.New("directory missing new order URL") } - /*if dir.RevokeCertURL == "" { - return nil, errors.New("directory missing revoke certificate URL") - }*/ jws := &jws{privKey: privKey, getNonceURL: dir.NewNonceURL} if reg := user.GetRegistration(); reg != nil { @@ -179,7 +176,7 @@ func (c *Client) RegisterWithExternalAccountBinding(tosAgreed bool, kid string, if c == nil || c.user == nil { return nil, errors.New("acme: cannot register a nil client or user") } - logf("[INFO] acme: Registering account (EAB) for %s", c.user.GetEmail()) + log.Printf("[INFO] acme: Registering account (EAB) for %s", c.user.GetEmail()) accMsg := accountMessage{} if c.user.GetEmail() != "" { @@ -240,7 +237,7 @@ func (c *Client) ResolveAccountByKey() (*RegistrationResource, error) { var retAccount accountMessage c.jws.kid = accountLink - hdr, err = postJSON(c.jws, accountLink, accountMessage{}, &retAccount) + _, err = postJSON(c.jws, accountLink, accountMessage{}, &retAccount) if err != nil { return nil, err } @@ -261,11 +258,7 @@ func (c *Client) DeleteRegistration() error { } _, err := postJSON(c.jws, c.user.GetRegistration().URI, accMsg, nil) - if err != nil { - return err - } - - return nil + return err } // QueryRegistration runs a POST request on the client's registration and @@ -829,11 +822,10 @@ func validate(j *jws, domain, uri string, c challenge) error { log.Printf("[INFO][%s] The server validated our request", domain) return nil case "pending": - break case "invalid": return handleChallengeError(chlng) default: - return errors.New("The server returned an unexpected state") + return errors.New("the server returned an unexpected state") } ra, err := strconv.Atoi(hdr.Get("Retry-After")) diff --git a/acme/crypto.go b/acme/crypto.go index 7adc34d4..7d4f4425 100644 --- a/acme/crypto.go +++ b/acme/crypto.go @@ -117,6 +117,10 @@ func GetOCSPForCert(bundle []byte) ([]byte, *ocsp.Response, error) { defer req.Body.Close() ocspResBytes, err := ioutil.ReadAll(limitReader(req.Body, 1024*1024)) + if err != nil { + return nil, nil, err + } + ocspRes, err := ocsp.ParseResponse(ocspResBytes, issuerCert) if err != nil { return nil, nil, err @@ -137,7 +141,7 @@ func getKeyAuthorization(token string, key interface{}) (string, error) { // Generate the Key Authorization for the challenge jwk := &jose.JSONWebKey{Key: publicKey} if jwk == nil { - return "", errors.New("Could not generate JWK from key") + return "", errors.New("could not generate JWK from key") } thumbBytes, err := jwk.Thumbprint(crypto.SHA256) if err != nil { @@ -172,7 +176,7 @@ func parsePEMBundle(bundle []byte) ([]*x509.Certificate, error) { } if len(certificates) == 0 { - return nil, errors.New("No certificates were found while parsing the bundle") + return nil, errors.New("no certificates were found while parsing the bundle") } return certificates, nil @@ -187,7 +191,7 @@ func parsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) { case "EC PRIVATE KEY": return x509.ParseECPrivateKey(keyBlock.Bytes) default: - return nil, errors.New("Unknown PEM header value") + return nil, errors.New("unknown PEM header value") } } @@ -206,7 +210,7 @@ func generatePrivateKey(keyType KeyType) (crypto.PrivateKey, error) { return rsa.GenerateKey(rand.Reader, 8192) } - return nil, fmt.Errorf("Invalid KeyType: %s", keyType) + return nil, fmt.Errorf("invalid KeyType: %s", keyType) } func generateCsr(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) { @@ -238,10 +242,8 @@ func pemEncode(data interface{}) []byte { pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes} case *rsa.PrivateKey: pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)} - break case *x509.CertificateRequest: pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw} - break case derCertificateBytes: pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.(derCertificateBytes))} } diff --git a/acme/crypto_test.go b/acme/crypto_test.go index 6f43835f..3ddf5d01 100644 --- a/acme/crypto_test.go +++ b/acme/crypto_test.go @@ -28,7 +28,7 @@ func TestGenerateCSR(t *testing.T) { if err != nil { t.Error("Error generating CSR:", err) } - if csr == nil || len(csr) == 0 { + if len(csr) == 0 { t.Error("Expected CSR with data, but it was nil or length 0") } } diff --git a/acme/jws.go b/acme/jws.go index 8c06baa5..bea76210 100644 --- a/acme/jws.go +++ b/acme/jws.go @@ -26,13 +26,13 @@ type jws struct { func (j *jws) post(url string, content []byte) (*http.Response, error) { signedContent, err := j.signContent(url, content) if err != nil { - return nil, fmt.Errorf("Failed to sign content -> %s", err.Error()) + return nil, fmt.Errorf("failed to sign content -> %s", err.Error()) } data := bytes.NewBuffer([]byte(signedContent.FullSerialize())) resp, err := httpPost(url, "application/jose+json", data) if err != nil { - return nil, fmt.Errorf("Failed to HTTP POST to %s -> %s", url, err.Error()) + return nil, fmt.Errorf("failed to HTTP POST to %s -> %s", url, err.Error()) } nonce, nonceErr := getNonceFromResponse(resp) @@ -77,12 +77,12 @@ func (j *jws) signContent(url string, content []byte) (*jose.JSONWebSignature, e signer, err := jose.NewSigner(signKey, &options) if err != nil { - return nil, fmt.Errorf("Failed to create jose signer -> %s", err.Error()) + return nil, fmt.Errorf("failed to create jose signer -> %s", err.Error()) } signed, err := signer.Sign(content) if err != nil { - return nil, fmt.Errorf("Failed to sign content -> %s", err.Error()) + return nil, fmt.Errorf("failed to sign content -> %s", err.Error()) } return signed, nil } @@ -105,12 +105,12 @@ func (j *jws) signEABContent(url, kid string, hmac []byte) (*jose.JSONWebSignatu }, ) if err != nil { - return nil, fmt.Errorf("Failed to create External Account Binding jose signer -> %s", err.Error()) + return nil, fmt.Errorf("failed to create External Account Binding jose signer -> %s", err.Error()) } signed, err := signer.Sign(jwkJSON) if err != nil { - return nil, fmt.Errorf("Failed to External Account Binding sign content -> %s", err.Error()) + return nil, fmt.Errorf("failed to External Account Binding sign content -> %s", err.Error()) } return signed, nil @@ -151,7 +151,7 @@ func (n *nonceManager) Push(nonce string) { func getNonce(url string) (string, error) { resp, err := httpHead(url) if err != nil { - return "", fmt.Errorf("Failed to get nonce from HTTP HEAD -> %s", err.Error()) + return "", fmt.Errorf("failed to get nonce from HTTP HEAD -> %s", err.Error()) } return getNonceFromResponse(resp) @@ -160,7 +160,7 @@ func getNonce(url string) (string, error) { func getNonceFromResponse(resp *http.Response) (string, error) { nonce := resp.Header.Get("Replay-Nonce") if nonce == "" { - return "", fmt.Errorf("Server did not respond with a proper nonce header") + return "", fmt.Errorf("server did not respond with a proper nonce header") } return nonce, nil diff --git a/acme/messages.go b/acme/messages.go index b5c60a24..6946cc15 100644 --- a/acme/messages.go +++ b/acme/messages.go @@ -78,9 +78,6 @@ type csrMessage struct { Csr string `json:"csr"` } -type emptyObjectMessage struct { -} - type revokeCertMessage struct { Certificate string `json:"certificate"` } diff --git a/acme/pop_challenge.go b/acme/pop_challenge.go deleted file mode 100644 index 8d2a213b..00000000 --- a/acme/pop_challenge.go +++ /dev/null @@ -1 +0,0 @@ -package acme diff --git a/cli_handlers.go b/cli_handlers.go index 374fb6b9..c5aaafe8 100644 --- a/cli_handlers.go +++ b/cli_handlers.go @@ -52,7 +52,7 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { err := checkFolder(c.GlobalString("path")) if err != nil { - log.Fatalf("Could not check/create path: %s", err.Error()) + log.Fatalf("Could not check/create path: %v", err) } conf := NewConfiguration(c) @@ -72,7 +72,7 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { client, err := acme.NewClient(c.GlobalString("server"), acc, keyType) if err != nil { - log.Fatalf("Could not create client: %s", err.Error()) + log.Fatalf("Could not create client: %v", err) } if len(c.GlobalStringSlice("exclude")) > 0 { @@ -85,7 +85,10 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { log.Fatal(err) } - client.SetChallengeProvider(acme.HTTP01, provider) + err = client.SetChallengeProvider(acme.HTTP01, provider) + if err != nil { + log.Fatal(err) + } // --webroot=foo indicates that the user specifically want to do a HTTP challenge // infer that the user also wants to exclude all other challenges @@ -97,17 +100,24 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { log.Fatal(err) } - client.SetChallengeProvider(acme.HTTP01, provider) + err = client.SetChallengeProvider(acme.HTTP01, provider) + if err != nil { + log.Fatal(err) + } // --memcached-host=foo:11211 indicates that the user specifically want to do a HTTP challenge // infer that the user also wants to exclude all other challenges client.ExcludeChallenges([]acme.Challenge{acme.DNS01}) } if c.GlobalIsSet("http") { - if strings.Index(c.GlobalString("http"), ":") == -1 { + if !strings.Contains(c.GlobalString("http"), ":") { log.Fatalf("The --http switch only accepts interface:port or :port for its argument.") } - client.SetHTTPAddress(c.GlobalString("http")) + + err = client.SetHTTPAddress(c.GlobalString("http")) + if err != nil { + log.Fatal(err) + } } if c.GlobalIsSet("dns") { @@ -116,7 +126,10 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { log.Fatal(err) } - client.SetChallengeProvider(acme.DNS01, provider) + err = client.SetChallengeProvider(acme.DNS01, provider) + if err != nil { + log.Fatal(err) + } // --dns=foo indicates that the user specifically want to do a DNS challenge // infer that the user also wants to exclude all other challenges @@ -124,7 +137,7 @@ func setup(c *cli.Context) (*Configuration, *Account, *acme.Client) { } if client.GetExternalAccountRequired() && !c.GlobalIsSet("eab") { - logger().Fatal("Server requires External Account Binding. Use --eab with --kid and --hmac.") + log.Fatal("Server requires External Account Binding. Use --eab with --kid and --hmac.") } return conf, acc, client @@ -144,13 +157,13 @@ func saveCertRes(certRes *acme.CertificateResource, conf *Configuration) { err := ioutil.WriteFile(certOut, certRes.Certificate, 0600) if err != nil { - log.Fatalf("Unable to save Certificate for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to save Certificate for domain %s\n\t%v", certRes.Domain, err) } if certRes.IssuerCertificate != nil { err = ioutil.WriteFile(issuerOut, certRes.IssuerCertificate, 0600) if err != nil { - log.Fatalf("Unable to save IssuerCertificate for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to save IssuerCertificate for domain %s\n\t%v", certRes.Domain, err) } } @@ -158,29 +171,29 @@ func saveCertRes(certRes *acme.CertificateResource, conf *Configuration) { // if we were given a CSR, we don't know the private key err = ioutil.WriteFile(privOut, certRes.PrivateKey, 0600) if err != nil { - log.Fatalf("Unable to save PrivateKey for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to save PrivateKey for domain %s\n\t%v", certRes.Domain, err) } if conf.context.GlobalBool("pem") { err = ioutil.WriteFile(pemOut, bytes.Join([][]byte{certRes.Certificate, certRes.PrivateKey}, nil), 0600) if err != nil { - log.Fatalf("Unable to save Certificate and PrivateKey in .pem for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to save Certificate and PrivateKey in .pem for domain %s\n\t%v", certRes.Domain, err) } } } else if conf.context.GlobalBool("pem") { // we don't have the private key; can't write the .pem file - log.Fatalf("Unable to save pem without private key for domain %s\n\t%s; are you using a CSR?", certRes.Domain, err.Error()) + log.Fatalf("Unable to save pem without private key for domain %s\n\t%v; are you using a CSR?", certRes.Domain, err) } jsonBytes, err := json.MarshalIndent(certRes, "", "\t") if err != nil { - log.Fatalf("Unable to marshal CertResource for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to marshal CertResource for domain %s\n\t%v", certRes.Domain, err) } err = ioutil.WriteFile(metaOut, jsonBytes, 0600) if err != nil { - log.Fatalf("Unable to save CertResource for domain %s\n\t%s", certRes.Domain, err.Error()) + log.Fatalf("Unable to save CertResource for domain %s\n\t%v", certRes.Domain, err) } } @@ -197,7 +210,7 @@ func handleTOS(c *cli.Context, client *acme.Client) bool { log.Println("Do you accept the TOS? Y/n") text, err := reader.ReadString('\n') if err != nil { - log.Fatalf("Could not read from console: %s", err.Error()) + log.Fatalf("Could not read from console: %v", err) } text = strings.Trim(text, "\r\n") @@ -262,7 +275,7 @@ func run(c *cli.Context) error { hmacEncoded := c.GlobalString("hmac") if kid == "" || hmacEncoded == "" { - logger().Fatalf("Requires arguments --kid and --hmac.") + log.Fatalf("Requires arguments --kid and --hmac.") } reg, err = client.RegisterWithExternalAccountBinding( @@ -275,7 +288,7 @@ func run(c *cli.Context) error { } if err != nil { - log.Fatalf("Could not complete registration\n\t%s", err.Error()) + log.Fatalf("Could not complete registration\n\t%v", err) } acc.Registration = reg @@ -317,7 +330,7 @@ func run(c *cli.Context) error { } if err != nil { - log.Printf("Could not obtain certificates\n\t%s", err.Error()) + log.Printf("Could not obtain certificates\n\t%v", err) // Make sure to return a non-zero exit code if ObtainSANCertificate // returned at least one error. Due to us not returning partial @@ -326,7 +339,7 @@ func run(c *cli.Context) error { } if err = checkFolder(conf.CertPath()); err != nil { - log.Fatalf("Could not check/create path: %s", err.Error()) + log.Fatalf("Could not check/create path: %v", err) } saveCertRes(cert, conf) @@ -341,7 +354,7 @@ func revoke(c *cli.Context) error { } if err := checkFolder(conf.CertPath()); err != nil { - log.Fatalf("Could not check/create path: %s", err.Error()) + log.Fatalf("Could not check/create path: %v", err) } for _, domain := range c.GlobalStringSlice("domains") { @@ -349,12 +362,15 @@ func revoke(c *cli.Context) error { certPath := path.Join(conf.CertPath(), domain+".crt") certBytes, err := ioutil.ReadFile(certPath) + if err != nil { + log.Println(err) + } err = client.RevokeCertificate(certBytes) if err != nil { - log.Fatalf("Error while revoking the certificate for domain %s\n\t%s", domain, err.Error()) + log.Fatalf("Error while revoking the certificate for domain %s\n\t%v", domain, err) } else { - log.Print("Certificate was revoked.") + log.Println("Certificate was revoked.") } } @@ -383,7 +399,7 @@ func renew(c *cli.Context) error { certBytes, err := ioutil.ReadFile(certPath) if err != nil { - log.Fatalf("Error while loading the certificate for domain %s\n\t%s", domain, err.Error()) + log.Fatalf("Error while loading the certificate for domain %s\n\t%v", domain, err) } if c.IsSet("days") { @@ -399,18 +415,18 @@ func renew(c *cli.Context) error { metaBytes, err := ioutil.ReadFile(metaPath) if err != nil { - log.Fatalf("Error while loading the meta data for domain %s\n\t%s", domain, err.Error()) + log.Fatalf("Error while loading the meta data for domain %s\n\t%v", domain, err) } var certRes acme.CertificateResource if err := json.Unmarshal(metaBytes, &certRes); err != nil { - log.Fatalf("Error while marshalling the meta data for domain %s\n\t%s", domain, err.Error()) + log.Fatalf("Error while marshalling the meta data for domain %s\n\t%v", domain, err) } if c.Bool("reuse-key") { keyBytes, err := ioutil.ReadFile(privPath) if err != nil { - log.Fatalf("Error while loading the private key for domain %s\n\t%s", domain, err.Error()) + log.Fatalf("Error while loading the private key for domain %s\n\t%v", domain, err) } certRes.PrivateKey = keyBytes } diff --git a/crypto.go b/crypto.go index 8b23e2fc..0d42b173 100644 --- a/crypto.go +++ b/crypto.go @@ -52,5 +52,5 @@ func loadPrivateKey(file string) (crypto.PrivateKey, error) { return x509.ParseECPrivateKey(keyBlock.Bytes) } - return nil, errors.New("Unknown private key type.") + return nil, errors.New("unknown private key type") } diff --git a/providers/dns/auroradns/auroradns.go b/providers/dns/auroradns/auroradns.go index 55b48f9b..03d31754 100644 --- a/providers/dns/auroradns/auroradns.go +++ b/providers/dns/auroradns/auroradns.go @@ -2,12 +2,13 @@ package auroradns import ( "fmt" + "os" + "sync" + "github.com/edeckers/auroradnsclient" "github.com/edeckers/auroradnsclient/records" "github.com/edeckers/auroradnsclient/zones" "github.com/xenolf/lego/acme" - "os" - "sync" ) // DNSProvider describes a provider for AuroraDNS @@ -59,7 +60,7 @@ func (provider *DNSProvider) getZoneInformationByName(name string) (zones.ZoneRe } } - return zones.ZoneRecord{}, fmt.Errorf("Could not find Zone record") + return zones.ZoneRecord{}, fmt.Errorf("could not find Zone record") } // Present creates a record with a secret @@ -83,6 +84,9 @@ func (provider *DNSProvider) Present(domain, token, keyAuth string) error { authZone = acme.UnFqdn(authZone) zoneRecord, err := provider.getZoneInformationByName(authZone) + if err != nil { + return fmt.Errorf("could not create record: %v", err) + } reqData := records.CreateRecordRequest{ @@ -94,7 +98,7 @@ func (provider *DNSProvider) Present(domain, token, keyAuth string) error { respData, err := provider.client.CreateRecord(zoneRecord.ID, reqData) if err != nil { - return fmt.Errorf("Could not create record: '%s'.", err) + return fmt.Errorf("could not create record: %v", err) } provider.recordIDsMu.Lock() @@ -113,12 +117,12 @@ func (provider *DNSProvider) CleanUp(domain, token, keyAuth string) error { provider.recordIDsMu.Unlock() if !ok { - return fmt.Errorf("Unknown recordID for '%s'", fqdn) + return fmt.Errorf("unknown recordID for %q", fqdn) } authZone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers) if err != nil { - return fmt.Errorf("Could not determine zone for domain: '%s'. %s", domain, err) + return fmt.Errorf("could not determine zone for domain: %q. %v", domain, err) } authZone = acme.UnFqdn(authZone) diff --git a/providers/dns/auroradns/auroradns_test.go b/providers/dns/auroradns/auroradns_test.go index f4df7fa6..f93bc95d 100644 --- a/providers/dns/auroradns/auroradns_test.go +++ b/providers/dns/auroradns/auroradns_test.go @@ -8,7 +8,7 @@ import ( "testing" ) -var fakeAuroraDNSUserId = "asdf1234" +var fakeAuroraDNSUserID = "asdf1234" var fakeAuroraDNSKey = "key" func TestAuroraDNSPresent(t *testing.T) { @@ -60,7 +60,7 @@ func TestAuroraDNSPresent(t *testing.T) { defer mock.Close() - auroraProvider, err := NewDNSProviderCredentials(mock.URL, fakeAuroraDNSUserId, fakeAuroraDNSKey) + auroraProvider, err := NewDNSProviderCredentials(mock.URL, fakeAuroraDNSUserID, fakeAuroraDNSKey) if auroraProvider == nil { t.Fatal("Expected non-nil AuroraDNS provider, but was nil") } @@ -123,7 +123,7 @@ func TestAuroraDNSCleanUp(t *testing.T) { })) defer mock.Close() - auroraProvider, err := NewDNSProviderCredentials(mock.URL, fakeAuroraDNSUserId, fakeAuroraDNSKey) + auroraProvider, err := NewDNSProviderCredentials(mock.URL, fakeAuroraDNSUserID, fakeAuroraDNSKey) if auroraProvider == nil { t.Fatal("Expected non-nil AuroraDNS provider, but was nil") } diff --git a/providers/dns/azure/azure.go b/providers/dns/azure/azure.go index 6a360cd2..b26d8526 100644 --- a/providers/dns/azure/azure.go +++ b/providers/dns/azure/azure.go @@ -20,10 +20,10 @@ import ( // DNSProvider is an implementation of the acme.ChallengeProvider interface type DNSProvider struct { - clientId string + clientID string clientSecret string - subscriptionId string - tenantId string + subscriptionID string + tenantID string resourceGroup string context context.Context } @@ -32,19 +32,19 @@ type DNSProvider struct { // Credentials must be passed in the environment variables: AZURE_CLIENT_ID, // AZURE_CLIENT_SECRET, AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_RESOURCE_GROUP func NewDNSProvider() (*DNSProvider, error) { - clientId := os.Getenv("AZURE_CLIENT_ID") + clientID := os.Getenv("AZURE_CLIENT_ID") clientSecret := os.Getenv("AZURE_CLIENT_SECRET") - subscriptionId := os.Getenv("AZURE_SUBSCRIPTION_ID") - tenantId := os.Getenv("AZURE_TENANT_ID") + subscriptionID := os.Getenv("AZURE_SUBSCRIPTION_ID") + tenantID := os.Getenv("AZURE_TENANT_ID") resourceGroup := os.Getenv("AZURE_RESOURCE_GROUP") - return NewDNSProviderCredentials(clientId, clientSecret, subscriptionId, tenantId, resourceGroup) + return NewDNSProviderCredentials(clientID, clientSecret, subscriptionID, tenantID, resourceGroup) } // NewDNSProviderCredentials uses the supplied credentials to return a // DNSProvider instance configured for azure. -func NewDNSProviderCredentials(clientId, clientSecret, subscriptionId, tenantId, resourceGroup string) (*DNSProvider, error) { - if clientId == "" || clientSecret == "" || subscriptionId == "" || tenantId == "" || resourceGroup == "" { - missingEnvVars := []string{} +func NewDNSProviderCredentials(clientID, clientSecret, subscriptionID, tenantID, resourceGroup string) (*DNSProvider, error) { + if clientID == "" || clientSecret == "" || subscriptionID == "" || tenantID == "" || resourceGroup == "" { + var missingEnvVars []string for _, envVar := range []string{"AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SUBSCRIPTION_ID", "AZURE_TENANT_ID", "AZURE_RESOURCE_GROUP"} { if os.Getenv(envVar) == "" { missingEnvVars = append(missingEnvVars, envVar) @@ -54,10 +54,10 @@ func NewDNSProviderCredentials(clientId, clientSecret, subscriptionId, tenantId, } return &DNSProvider{ - clientId: clientId, + clientID: clientID, clientSecret: clientSecret, - subscriptionId: subscriptionId, - tenantId: tenantId, + subscriptionID: subscriptionID, + tenantID: tenantID, resourceGroup: resourceGroup, // TODO: A timeout can be added here for cancellation purposes. context: context.Background(), @@ -78,8 +78,12 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { return err } - rsc := dns.NewRecordSetsClient(c.subscriptionId) + rsc := dns.NewRecordSetsClient(c.subscriptionID) spt, err := c.newServicePrincipalTokenFromCredentials(azure.PublicCloud.ResourceManagerEndpoint) + if err != nil { + return err + } + rsc.Authorizer = autorest.NewBearerAuthorizer(spt) relative := toRelativeRecord(fqdn, acme.ToFqdn(zone)) @@ -87,16 +91,12 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { Name: &relative, RecordSetProperties: &dns.RecordSetProperties{ TTL: to.Int64Ptr(60), - TxtRecords: &[]dns.TxtRecord{dns.TxtRecord{Value: &[]string{value}}}, + TxtRecords: &[]dns.TxtRecord{{Value: &[]string{value}}}, }, } + _, err = rsc.CreateOrUpdate(c.context, c.resourceGroup, zone, relative, dns.TXT, rec, "", "") - - if err != nil { - return err - } - - return nil + return err } // Returns the relative record to the domain @@ -114,15 +114,16 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { } relative := toRelativeRecord(fqdn, acme.ToFqdn(zone)) - rsc := dns.NewRecordSetsClient(c.subscriptionId) + rsc := dns.NewRecordSetsClient(c.subscriptionID) spt, err := c.newServicePrincipalTokenFromCredentials(azure.PublicCloud.ResourceManagerEndpoint) - rsc.Authorizer = autorest.NewBearerAuthorizer(spt) - _, err = rsc.Delete(c.context, c.resourceGroup, zone, relative, dns.TXT, "") if err != nil { return err } - return nil + rsc.Authorizer = autorest.NewBearerAuthorizer(spt) + + _, err = rsc.Delete(c.context, c.resourceGroup, zone, relative, dns.TXT, "") + return err } // Checks that azure has a zone for this domain name. @@ -134,12 +135,14 @@ func (c *DNSProvider) getHostedZoneID(fqdn string) (string, error) { // Now we want to to Azure and get the zone. spt, err := c.newServicePrincipalTokenFromCredentials(azure.PublicCloud.ResourceManagerEndpoint) + if err != nil { + return "", err + } - dc := dns.NewZonesClient(c.subscriptionId) + dc := dns.NewZonesClient(c.subscriptionID) dc.Authorizer = autorest.NewBearerAuthorizer(spt) zone, err := dc.Get(c.context, c.resourceGroup, acme.UnFqdn(authZone)) - if err != nil { return "", err } @@ -151,9 +154,9 @@ func (c *DNSProvider) getHostedZoneID(fqdn string) (string, error) { // NewServicePrincipalTokenFromCredentials creates a new ServicePrincipalToken using values of the // passed credentials map. func (c *DNSProvider) newServicePrincipalTokenFromCredentials(scope string) (*adal.ServicePrincipalToken, error) { - oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, c.tenantId) + oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, c.tenantID) if err != nil { - panic(err) + return nil, err } - return adal.NewServicePrincipalToken(*oauthConfig, c.clientId, c.clientSecret, scope) + return adal.NewServicePrincipalToken(*oauthConfig, c.clientID, c.clientSecret, scope) } diff --git a/providers/dns/bluecat/bluecat.go b/providers/dns/bluecat/bluecat.go index 92b8a21d..b0374b7e 100644 --- a/providers/dns/bluecat/bluecat.go +++ b/providers/dns/bluecat/bluecat.go @@ -13,18 +13,19 @@ import ( "strings" "time" - "github.com/xenolf/lego/acme" "io/ioutil" + + "github.com/xenolf/lego/acme" ) -const bluecatUrlTemplate = "%s/Services/REST/v1" +const bluecatURLTemplate = "%s/Services/REST/v1" const configType = "Configuration" const viewType = "View" const txtType = "TXTRecord" const zoneType = "Zone" type entityResponse struct { - Id uint `json:"id"` + ID uint `json:"id"` Name string `json:"name"` Type string `json:"type"` Properties string `json:"properties"` @@ -33,7 +34,7 @@ type entityResponse struct { // DNSProvider is an implementation of the acme.ChallengeProvider interface that uses // Bluecat's Address Manager REST API to manage TXT records for a domain. type DNSProvider struct { - baseUrl string + baseURL string userName string password string configName string @@ -55,7 +56,7 @@ func NewDNSProvider() (*DNSProvider, error) { password := os.Getenv("BLUECAT_PASSWORD") configName := os.Getenv("BLUECAT_CONFIG_NAME") dnsView := os.Getenv("BLUECAT_DNS_VIEW") - httpClient := http.Client{Timeout: time.Duration(30 * time.Second)} + httpClient := http.Client{Timeout: 30 * time.Second} return NewDNSProviderCredentials(server, userName, password, configName, dnsView, httpClient) } @@ -67,7 +68,7 @@ func NewDNSProviderCredentials(server, userName, password, configName, dnsView s } return &DNSProvider{ - baseUrl: fmt.Sprintf(bluecatUrlTemplate, server), + baseURL: fmt.Sprintf(bluecatURLTemplate, server), userName: userName, password: password, configName: configName, @@ -79,7 +80,7 @@ func NewDNSProviderCredentials(server, userName, password, configName, dnsView s // Send a REST request, using query parameters specified. The Authorization // header will be set if we have an active auth token func (d *DNSProvider) sendRequest(method, resource string, payload interface{}, queryArgs map[string]string) (*http.Response, error) { - url := fmt.Sprintf("%s/%s", d.baseUrl, resource) + url := fmt.Sprintf("%s/%s", d.baseURL, resource) body, err := json.Marshal(payload) if err != nil { @@ -159,14 +160,14 @@ func (d *DNSProvider) logout() error { if resp.StatusCode != 200 { return fmt.Errorf("Bluecat API request failed to delete session with HTTP status code %d", resp.StatusCode) - } else { - authBytes, _ := ioutil.ReadAll(resp.Body) - authResp := string(authBytes) + } - if !strings.Contains(authResp, "successfully") { - msg := strings.Trim(authResp, "\"") - return fmt.Errorf("Bluecat API request failed to delete session: %s", msg) - } + authBytes, _ := ioutil.ReadAll(resp.Body) + authResp := string(authBytes) + + if !strings.Contains(authResp, "successfully") { + msg := strings.Trim(authResp, "\"") + return fmt.Errorf("Bluecat API request failed to delete session: %s", msg) } d.token = "" @@ -175,7 +176,7 @@ func (d *DNSProvider) logout() error { } // Lookup the entity ID of the configuration named in our properties -func (d *DNSProvider) lookupConfId() (uint, error) { +func (d *DNSProvider) lookupConfID() (uint, error) { queryArgs := map[string]string{ "parentId": strconv.Itoa(0), "name": d.configName, @@ -193,18 +194,18 @@ func (d *DNSProvider) lookupConfId() (uint, error) { if err != nil { return 0, err } - return conf.Id, nil + return conf.ID, nil } // Find the DNS view with the given name within -func (d *DNSProvider) lookupViewId(viewName string) (uint, error) { - confId, err := d.lookupConfId() +func (d *DNSProvider) lookupViewID(viewName string) (uint, error) { + confID, err := d.lookupConfID() if err != nil { return 0, err } queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(confId), 10), + "parentId": strconv.FormatUint(uint64(confID), 10), "name": d.dnsView, "type": viewType, } @@ -221,13 +222,13 @@ func (d *DNSProvider) lookupViewId(viewName string) (uint, error) { return 0, err } - return view.Id, nil + return view.ID, nil } // Return the entityId of the parent zone by recursing from the root view // Also return the simple name of the host -func (d *DNSProvider) lookupParentZoneId(viewId uint, fqdn string) (uint, string, error) { - parentViewId := viewId +func (d *DNSProvider) lookupParentZoneID(viewID uint, fqdn string) (uint, string, error) { + parentViewID := viewID name := "" if fqdn != "" { @@ -236,25 +237,24 @@ func (d *DNSProvider) lookupParentZoneId(viewId uint, fqdn string) (uint, string name = zones[0] for i := last; i > -1; i-- { - zoneId, err := d.getZone(parentViewId, zones[i]) - if err != nil || zoneId == 0 { - return parentViewId, name, err + zoneID, err := d.getZone(parentViewID, zones[i]) + if err != nil || zoneID == 0 { + return parentViewID, name, err } - if (i > 0) { - name = strings.Join(zones[0:i],".") + if i > 0 { + name = strings.Join(zones[0:i], ".") } - parentViewId = zoneId + parentViewID = zoneID } } - return parentViewId, name, nil + return parentViewID, name, nil } // Get the DNS zone with the specified name under the parentId -func (d *DNSProvider) getZone(parentId uint, name string) (uint, error) { - +func (d *DNSProvider) getZone(parentID uint, name string) (uint, error) { queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentId), 10), + "parentId": strconv.FormatUint(uint64(parentID), 10), "name": name, "type": zoneType, } @@ -275,7 +275,7 @@ func (d *DNSProvider) getZone(parentId uint, name string) (uint, error) { return 0, err } - return zone.Id, nil + return zone.ID, nil } // Present creates a TXT record using the specified parameters @@ -289,21 +289,24 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { return err } - viewId, err := d.lookupViewId(d.dnsView) + viewID, err := d.lookupViewID(d.dnsView) if err != nil { return err } - parentZoneId, name, err := d.lookupParentZoneId(viewId, fqdn) + parentZoneID, name, err := d.lookupParentZoneID(viewID, fqdn) + if err != nil { + return err + } queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentZoneId), 10), + "parentId": strconv.FormatUint(uint64(parentZoneID), 10), } body := bluecatEntity{ - Name: name, - Type: "TXTRecord", - Properties: fmt.Sprintf("ttl=%d|absoluteName=%s|txt=%s|", ttl, fqdn, value), + Name: name, + Type: "TXTRecord", + Properties: fmt.Sprintf("ttl=%d|absoluteName=%s|txt=%s|", ttl, fqdn, value), } resp, err := d.sendRequest("POST", "addEntity", body, queryArgs) @@ -321,23 +324,18 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { return fmt.Errorf("Bluecat API addEntity request failed: %s", addTxtResp) } - err = d.deploy(uint(parentZoneId)) + err = d.deploy(parentZoneID) if err != nil { return err } - err = d.logout() - if err != nil { - return err - } - - return nil + return d.logout() } // Deploy the DNS config for the specified entity to the authoritative servers -func (d *DNSProvider) deploy(entityId uint) error { +func (d *DNSProvider) deploy(entityID uint) error { queryArgs := map[string]string{ - "entityId": strconv.FormatUint(uint64(entityId), 10), + "entityId": strconv.FormatUint(uint64(entityID), 10), } resp, err := d.sendRequest("POST", "quickDeploy", nil, queryArgs) @@ -359,18 +357,18 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { return err } - viewId, err := d.lookupViewId(d.dnsView) + viewID, err := d.lookupViewID(d.dnsView) if err != nil { return err } - parentId, name, err := d.lookupParentZoneId(viewId, fqdn) + parentID, name, err := d.lookupParentZoneID(viewID, fqdn) if err != nil { return err } queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentId), 10), + "parentId": strconv.FormatUint(uint64(parentID), 10), "name": name, "type": txtType, } @@ -387,7 +385,7 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { return err } queryArgs = map[string]string{ - "objectId": strconv.FormatUint(uint64(txtRec.Id), 10), + "objectId": strconv.FormatUint(uint64(txtRec.ID), 10), } resp, err = d.sendRequest("DELETE", "delete", nil, queryArgs) @@ -396,23 +394,18 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { } defer resp.Body.Close() - err = d.deploy(parentId) + err = d.deploy(parentID) if err != nil { return err } - err = d.logout() - if err != nil { - return err - } - - return nil + return d.logout() } -//JSON body for Bluecat entity requests and responses +// JSON body for Bluecat entity requests and responses type bluecatEntity struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` + ID string `json:"id,omitempty"` + Name string `json:"name"` + Type string `json:"type"` Properties string `json:"properties"` } diff --git a/providers/dns/bluecat/bluecat_test.go b/providers/dns/bluecat/bluecat_test.go index c1138ffc..0362e58a 100644 --- a/providers/dns/bluecat/bluecat_test.go +++ b/providers/dns/bluecat/bluecat_test.go @@ -4,8 +4,9 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" "time" + + "github.com/stretchr/testify/assert" ) var ( @@ -14,7 +15,7 @@ var ( bluecatUserName string bluecatPassword string bluecatConfigName string - bluecatDnsView string + bluecatDNSView string bluecatDomain string ) @@ -24,8 +25,13 @@ func init() { bluecatPassword = os.Getenv("BLUECAT_PASSWORD") bluecatDomain = os.Getenv("BLUECAT_DOMAIN") bluecatConfigName = os.Getenv("BLUECAT_CONFIG_NAME") - bluecatDnsView = os.Getenv("BLUECAT_DNS_VIEW") - if len(bluecatServer) > 0 && len(bluecatDomain) > 0 && len(bluecatUserName) > 0 && len(bluecatPassword) > 0 && len(bluecatConfigName) > 0 && len(bluecatDnsView) > 0 { + bluecatDNSView = os.Getenv("BLUECAT_DNS_VIEW") + if len(bluecatServer) > 0 && + len(bluecatDomain) > 0 && + len(bluecatUserName) > 0 && + len(bluecatPassword) > 0 && + len(bluecatConfigName) > 0 && + len(bluecatDNSView) > 0 { bluecatLiveTest = true } } diff --git a/providers/dns/cloudflare/cloudflare.go b/providers/dns/cloudflare/cloudflare.go index d62b26f0..7cc32faf 100644 --- a/providers/dns/cloudflare/cloudflare.go +++ b/providers/dns/cloudflare/cloudflare.go @@ -81,11 +81,7 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { } _, err = c.makeRequest("POST", fmt.Sprintf("/zones/%s/dns_records", zoneID), bytes.NewReader(body)) - if err != nil { - return err - } - - return nil + return err } // CleanUp removes the TXT record matching the specified parameters @@ -98,11 +94,7 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { } _, err = c.makeRequest("DELETE", fmt.Sprintf("/zones/%s/dns_records/%s", record.ZoneID, record.ID), nil) - if err != nil { - return err - } - - return nil + return err } func (c *DNSProvider) getHostedZoneID(fqdn string) (string, error) { @@ -162,7 +154,7 @@ func (c *DNSProvider) findTxtRecord(fqdn string) (*cloudFlareRecord, error) { } } - return nil, fmt.Errorf("No existing record found for %s", fqdn) + return nil, fmt.Errorf("no existing record found for %s", fqdn) } func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) { @@ -187,7 +179,6 @@ func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawM req.Header.Set("X-Auth-Email", c.authEmail) req.Header.Set("X-Auth-Key", c.authKey) - //req.Header.Set("User-Agent", userAgent()) client := http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) diff --git a/providers/dns/cloudxns/cloudxns.go b/providers/dns/cloudxns/cloudxns.go index 57efdeae..1204af14 100644 --- a/providers/dns/cloudxns/cloudxns.go +++ b/providers/dns/cloudxns/cloudxns.go @@ -101,7 +101,7 @@ func (c *DNSProvider) getHostedZoneID(fqdn string) (string, error) { } } - return "", fmt.Errorf("Zone %s not found in cloudxns for domain %s", authZone, fqdn) + return "", fmt.Errorf("zone %s not found in cloudxns for domain %s", authZone, fqdn) } func (c *DNSProvider) findTxtRecord(zoneID, fqdn string) (string, error) { @@ -122,7 +122,7 @@ func (c *DNSProvider) findTxtRecord(zoneID, fqdn string) (string, error) { } } - return "", fmt.Errorf("No existing record found for %s", fqdn) + return "", fmt.Errorf("no existing record found for %s", fqdn) } func (c *DNSProvider) addTxtRecord(zoneID, fqdn, value string, ttl int) error { @@ -146,11 +146,7 @@ func (c *DNSProvider) addTxtRecord(zoneID, fqdn, value string, ttl int) error { } _, err = c.makeRequest("POST", "record", body) - if err != nil { - return err - } - - return nil + return err } func (c *DNSProvider) delTxtRecord(recordID, zoneID string) error { diff --git a/providers/dns/digitalocean/digitalocean.go b/providers/dns/digitalocean/digitalocean.go index da261b39..ef749e6f 100644 --- a/providers/dns/digitalocean/digitalocean.go +++ b/providers/dns/digitalocean/digitalocean.go @@ -22,6 +22,12 @@ type DNSProvider struct { recordIDsMu sync.Mutex } +// Timeout returns the timeout and interval to use when checking for DNS +// propagation. Adjusting here to cope with spikes in propagation times. +func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { + return 60 * time.Second, 5 * time.Second +} + // NewDNSProvider returns a DNSProvider instance configured for Digital // Ocean. Credentials must be passed in the environment variable: // DO_AUTH_TOKEN. @@ -44,34 +50,17 @@ func NewDNSProviderCredentials(apiAuthToken string) (*DNSProvider, error) { // Present creates a TXT record using the specified parameters func (d *DNSProvider) Present(domain, token, keyAuth string) error { - // txtRecordRequest represents the request body to DO's API to make a TXT record - type txtRecordRequest struct { - RecordType string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - } - - // txtRecordResponse represents a response from DO's API after making a TXT record - type txtRecordResponse struct { - DomainRecord struct { - ID int `json:"id"` - Type string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - } `json:"domain_record"` - } - fqdn, value, _ := acme.DNS01Record(domain, keyAuth) authZone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers) if err != nil { - return fmt.Errorf("Could not determine zone for domain: '%s'. %s", domain, err) + return fmt.Errorf("could not determine zone for domain: '%s'. %s", domain, err) } authZone = acme.UnFqdn(authZone) reqURL := fmt.Sprintf("%s/v2/domains/%s/records", digitalOceanBaseURL, authZone) - reqData := txtRecordRequest{RecordType: "TXT", Name: fqdn, Data: value} + reqData := txtRecordRequest{RecordType: "TXT", Name: fqdn, Data: value, TTL: 30} body, err := json.Marshal(reqData) if err != nil { return err @@ -124,7 +113,7 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { authZone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers) if err != nil { - return fmt.Errorf("Could not determine zone for domain: '%s'. %s", domain, err) + return fmt.Errorf("could not determine zone for domain: '%s'. %s", domain, err) } authZone = acme.UnFqdn(authZone) @@ -164,3 +153,21 @@ type digitalOceanAPIError struct { } var digitalOceanBaseURL = "https://api.digitalocean.com" + +// txtRecordRequest represents the request body to DO's API to make a TXT record +type txtRecordRequest struct { + RecordType string `json:"type"` + Name string `json:"name"` + Data string `json:"data"` + TTL int `json:"ttl"` +} + +// txtRecordResponse represents a response from DO's API after making a TXT record +type txtRecordResponse struct { + DomainRecord struct { + ID int `json:"id"` + Type string `json:"type"` + Name string `json:"name"` + Data string `json:"data"` + } `json:"domain_record"` +} diff --git a/providers/dns/digitalocean/digitalocean_test.go b/providers/dns/digitalocean/digitalocean_test.go index 7498508b..c2bef08b 100644 --- a/providers/dns/digitalocean/digitalocean_test.go +++ b/providers/dns/digitalocean/digitalocean_test.go @@ -33,7 +33,7 @@ func TestDigitalOceanPresent(t *testing.T) { if err != nil { t.Fatalf("Error reading request body: %v", err) } - if got, want := string(reqBody), `{"type":"TXT","name":"_acme-challenge.example.com.","data":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI"}`; got != want { + if got, want := string(reqBody), `{"type":"TXT","name":"_acme-challenge.example.com.","data":"w6uP8Tcg6K2QR905Rms8iXTlksL6OD1KOWBxTK7wxPI","ttl":30}`; got != want { t.Errorf("Expected body data to be: `%s` but got `%s`", want, got) } diff --git a/providers/dns/dns_providers.go b/providers/dns/dns_providers.go index 72ab0d8c..83693d20 100644 --- a/providers/dns/dns_providers.go +++ b/providers/dns/dns_providers.go @@ -1,4 +1,3 @@ -// Factory for DNS providers package dns import ( @@ -7,6 +6,7 @@ import ( "github.com/xenolf/lego/acme" "github.com/xenolf/lego/providers/dns/auroradns" "github.com/xenolf/lego/providers/dns/azure" + "github.com/xenolf/lego/providers/dns/bluecat" "github.com/xenolf/lego/providers/dns/cloudflare" "github.com/xenolf/lego/providers/dns/cloudxns" "github.com/xenolf/lego/providers/dns/digitalocean" @@ -35,9 +35,9 @@ import ( "github.com/xenolf/lego/providers/dns/rfc2136" "github.com/xenolf/lego/providers/dns/route53" "github.com/xenolf/lego/providers/dns/vultr" - "github.com/xenolf/lego/providers/dns/bluecat" ) +// NewDNSChallengeProviderByName Factory for DNS providers func NewDNSChallengeProviderByName(name string) (acme.ChallengeProvider, error) { var err error var provider acme.ChallengeProvider @@ -107,7 +107,7 @@ func NewDNSChallengeProviderByName(name string) (acme.ChallengeProvider, error) case "exec": provider, err = exec.NewDNSProvider() default: - err = fmt.Errorf("Unrecognised DNS provider: %s", name) + err = fmt.Errorf("unrecognised DNS provider: %s", name) } return provider, err } diff --git a/providers/dns/dnsimple/dnsimple.go b/providers/dns/dnsimple/dnsimple.go index df76a241..30c7fc2f 100644 --- a/providers/dns/dnsimple/dnsimple.go +++ b/providers/dns/dnsimple/dnsimple.go @@ -23,14 +23,14 @@ type DNSProvider struct { // See: https://developer.dnsimple.com/v2/#authentication func NewDNSProvider() (*DNSProvider, error) { accessToken := os.Getenv("DNSIMPLE_OAUTH_TOKEN") - baseUrl := os.Getenv("DNSIMPLE_BASE_URL") + baseURL := os.Getenv("DNSIMPLE_BASE_URL") - return NewDNSProviderCredentials(accessToken, baseUrl) + return NewDNSProviderCredentials(accessToken, baseURL) } // NewDNSProviderCredentials uses the supplied credentials to return a // DNSProvider instance configured for dnsimple. -func NewDNSProviderCredentials(accessToken, baseUrl string) (*DNSProvider, error) { +func NewDNSProviderCredentials(accessToken, baseURL string) (*DNSProvider, error) { if accessToken == "" { return nil, fmt.Errorf("DNSimple OAuth token is missing") } @@ -38,8 +38,8 @@ func NewDNSProviderCredentials(accessToken, baseUrl string) (*DNSProvider, error client := dnsimple.NewClient(dnsimple.NewOauthTokenCredentials(accessToken)) client.UserAgent = "lego" - if baseUrl != "" { - client.BaseURL = baseUrl + if baseURL != "" { + client.BaseURL = baseURL } return &DNSProvider{client: client}, nil @@ -119,8 +119,7 @@ func (c *DNSProvider) getHostedZone(domain string) (string, error) { } if hostedZone.ID == 0 { - return "", fmt.Errorf("Zone %s not found in DNSimple for domain %s", authZone, domain) - + return "", fmt.Errorf("zone %s not found in DNSimple for domain %s", authZone, domain) } return hostedZone.Name, nil @@ -173,7 +172,7 @@ func (c *DNSProvider) getAccountID() (string, error) { } if whoamiResponse.Data.Account == nil { - return "", fmt.Errorf("DNSimple user tokens are not supported, please use an account token.") + return "", fmt.Errorf("DNSimple user tokens are not supported, please use an account token") } return strconv.FormatInt(whoamiResponse.Data.Account.ID, 10), nil diff --git a/providers/dns/dnsimple/dnsimple_test.go b/providers/dns/dnsimple/dnsimple_test.go index bd35790d..0d44410f 100644 --- a/providers/dns/dnsimple/dnsimple_test.go +++ b/providers/dns/dnsimple/dnsimple_test.go @@ -12,19 +12,19 @@ var ( dnsimpleLiveTest bool dnsimpleOauthToken string dnsimpleDomain string - dnsimpleBaseUrl string + dnsimpleBaseURL string ) func init() { dnsimpleOauthToken = os.Getenv("DNSIMPLE_OAUTH_TOKEN") dnsimpleDomain = os.Getenv("DNSIMPLE_DOMAIN") - dnsimpleBaseUrl = "https://api.sandbox.dnsimple.com" + dnsimpleBaseURL = "https://api.sandbox.dnsimple.com" if len(dnsimpleOauthToken) > 0 && len(dnsimpleDomain) > 0 { - baseUrl := os.Getenv("DNSIMPLE_BASE_URL") + baseURL := os.Getenv("DNSIMPLE_BASE_URL") - if baseUrl != "" { - dnsimpleBaseUrl = baseUrl + if baseURL != "" { + dnsimpleBaseURL = baseURL } dnsimpleLiveTest = true @@ -33,7 +33,7 @@ func init() { func restoreDNSimpleEnv() { os.Setenv("DNSIMPLE_OAUTH_TOKEN", dnsimpleOauthToken) - os.Setenv("DNSIMPLE_BASE_URL", dnsimpleBaseUrl) + os.Setenv("DNSIMPLE_BASE_URL", dnsimpleBaseURL) } // @@ -114,7 +114,7 @@ func TestLiveDNSimplePresent(t *testing.T) { t.Skip("skipping live test") } - provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseUrl) + provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseURL) assert.NoError(t, err) err = provider.Present(dnsimpleDomain, "", "123d==") @@ -132,7 +132,7 @@ func TestLiveDNSimpleCleanUp(t *testing.T) { time.Sleep(time.Second * 1) - provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseUrl) + provider, err := NewDNSProviderCredentials(dnsimpleOauthToken, dnsimpleBaseURL) assert.NoError(t, err) err = provider.CleanUp(dnsimpleDomain, "", "123d==") diff --git a/providers/dns/dnsmadeeasy/dnsmadeeasy.go b/providers/dns/dnsmadeeasy/dnsmadeeasy.go index c4363a4e..11b1ac44 100644 --- a/providers/dns/dnsmadeeasy/dnsmadeeasy.go +++ b/providers/dns/dnsmadeeasy/dnsmadeeasy.go @@ -95,11 +95,7 @@ func (d *DNSProvider) Present(domainName, token, keyAuth string) error { record := &Record{Type: "TXT", Name: name, Value: value, TTL: ttl} err = d.createRecord(domain, record) - if err != nil { - return err - } - - return nil + return err } // CleanUp removes the TXT records matching the specified parameters @@ -226,7 +222,7 @@ func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) } client := &http.Client{ Transport: transport, - Timeout: time.Duration(10 * time.Second), + Timeout: 10 * time.Second, } resp, err := client.Do(req) if err != nil { diff --git a/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go b/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go index e860ecb6..8d6e27ac 100644 --- a/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go +++ b/providers/dns/dnsmadeeasy/dnsmadeeasy_test.go @@ -28,6 +28,7 @@ func TestPresentAndCleanup(t *testing.T) { } provider, err := NewDNSProvider() + assert.NoError(t, err) err = provider.Present(testDomain, "", "123d==") assert.NoError(t, err) diff --git a/providers/dns/duckdns/duckdns.go b/providers/dns/duckdns/duckdns.go index 6e2102a7..855838ae 100644 --- a/providers/dns/duckdns/duckdns.go +++ b/providers/dns/duckdns/duckdns.go @@ -1,82 +1,81 @@ -// Adds lego support for http://duckdns.org . -// -// See http://www.duckdns.org/spec.jsp for more info on updating TXT records. -package duckdns - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - - "github.com/xenolf/lego/acme" -) - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - // The duckdns api token - token string -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DUCKDNS_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - duckdnsToken := os.Getenv("DUCKDNS_TOKEN") - - return NewDNSProviderCredentials(duckdnsToken) -} - -// NewDNSProviderCredentials uses the supplied credentials to return a -// DNSProvider instance configured for http://duckdns.org . -func NewDNSProviderCredentials(duckdnsToken string) (*DNSProvider, error) { - if duckdnsToken == "" { - return nil, errors.New("environment variable DUCKDNS_TOKEN not set") - } - - return &DNSProvider{token: duckdnsToken}, nil -} - -// makeDuckdnsURL creates a url to clear the set or unset the TXT record. -// txt == "" will clear the TXT record. -func makeDuckdnsURL(domain, token, txt string) string { - requestBase := fmt.Sprintf("https://www.duckdns.org/update?domains=%s&token=%s", domain, token) - if txt == "" { - return requestBase + "&clear=true" - } - return requestBase + "&txt=" + txt -} - -func issueDuckdnsRequest(url string) error { - response, err := acme.HTTPClient.Get(url) - if err != nil { - return err - } - defer response.Body.Close() - - bodyBytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - body := string(bodyBytes) - if body != "OK" { - return fmt.Errorf("Request to change TXT record for duckdns returned the following result (%s) this does not match expectation (OK) used url [%s]", body, url) - } - return nil -} - -// Present creates a TXT record to fulfil the dns-01 challenge. -// In duckdns you only have one TXT record shared with -// the domain and all sub domains. -// -// To update the TXT record we just need to make one simple get request. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, txtRecord, _ := acme.DNS01Record(domain, keyAuth) - url := makeDuckdnsURL(domain, d.token, txtRecord) - return issueDuckdnsRequest(url) -} - -// CleanUp clears duckdns TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - url := makeDuckdnsURL(domain, d.token, "") - return issueDuckdnsRequest(url) -} +// Package duckdns Adds lego support for http://duckdns.org . +// See http://www.duckdns.org/spec.jsp for more info on updating TXT records. +package duckdns + +import ( + "errors" + "fmt" + "io/ioutil" + "os" + + "github.com/xenolf/lego/acme" +) + +// DNSProvider adds and removes the record for the DNS challenge +type DNSProvider struct { + // The duckdns api token + token string +} + +// NewDNSProvider returns a new DNS provider using +// environment variable DUCKDNS_TOKEN for adding and removing the DNS record. +func NewDNSProvider() (*DNSProvider, error) { + duckdnsToken := os.Getenv("DUCKDNS_TOKEN") + + return NewDNSProviderCredentials(duckdnsToken) +} + +// NewDNSProviderCredentials uses the supplied credentials to return a +// DNSProvider instance configured for http://duckdns.org . +func NewDNSProviderCredentials(duckdnsToken string) (*DNSProvider, error) { + if duckdnsToken == "" { + return nil, errors.New("environment variable DUCKDNS_TOKEN not set") + } + + return &DNSProvider{token: duckdnsToken}, nil +} + +// makeDuckdnsURL creates a url to clear the set or unset the TXT record. +// txt == "" will clear the TXT record. +func makeDuckdnsURL(domain, token, txt string) string { + requestBase := fmt.Sprintf("https://www.duckdns.org/update?domains=%s&token=%s", domain, token) + if txt == "" { + return requestBase + "&clear=true" + } + return requestBase + "&txt=" + txt +} + +func issueDuckdnsRequest(url string) error { + response, err := acme.HTTPClient.Get(url) + if err != nil { + return err + } + defer response.Body.Close() + + bodyBytes, err := ioutil.ReadAll(response.Body) + if err != nil { + return err + } + body := string(bodyBytes) + if body != "OK" { + return fmt.Errorf("Request to change TXT record for duckdns returned the following result (%s) this does not match expectation (OK) used url [%s]", body, url) + } + return nil +} + +// Present creates a TXT record to fulfil the dns-01 challenge. +// In duckdns you only have one TXT record shared with +// the domain and all sub domains. +// +// To update the TXT record we just need to make one simple get request. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + _, txtRecord, _ := acme.DNS01Record(domain, keyAuth) + url := makeDuckdnsURL(domain, d.token, txtRecord) + return issueDuckdnsRequest(url) +} + +// CleanUp clears duckdns TXT record +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + url := makeDuckdnsURL(domain, d.token, "") + return issueDuckdnsRequest(url) +} diff --git a/providers/dns/duckdns/duckdns_test.go b/providers/dns/duckdns/duckdns_test.go index f1afed4f..aefc0943 100644 --- a/providers/dns/duckdns/duckdns_test.go +++ b/providers/dns/duckdns/duckdns_test.go @@ -1,65 +1,65 @@ -package duckdns - -import ( - "os" - "testing" - "time" - - "github.com/stretchr/testify/assert" -) - -var ( - duckdnsLiveTest bool - duckdnsToken string - duckdnsDomain string -) - -func init() { - duckdnsToken = os.Getenv("DUCKDNS_TOKEN") - duckdnsDomain = os.Getenv("DUCKDNS_DOMAIN") - if len(duckdnsDomain) > 0 && len(duckdnsDomain) > 0 { - duckdnsLiveTest = true - } -} - -func restoreDuckdnsEnv() { - os.Setenv("DUCKDNS_TOKEN", duckdnsToken) -} - -func TestNewDNSProviderValidEnv(t *testing.T) { - os.Setenv("DUCKDNS_TOKEN", "123") - _, err := NewDNSProvider() - assert.NoError(t, err) - restoreDuckdnsEnv() -} -func TestNewDNSProviderMissingCredErr(t *testing.T) { - os.Setenv("DUCKDNS_TOKEN", "") - _, err := NewDNSProvider() - assert.EqualError(t, err, "environment variable DUCKDNS_TOKEN not set") - restoreDuckdnsEnv() -} -func TestLiveDuckdnsPresent(t *testing.T) { - if !duckdnsLiveTest { - t.Skip("skipping live test") - } - - provider, err := NewDNSProvider() - assert.NoError(t, err) - - err = provider.Present(duckdnsDomain, "", "123d==") - assert.NoError(t, err) -} - -func TestLiveDuckdnsCleanUp(t *testing.T) { - if !duckdnsLiveTest { - t.Skip("skipping live test") - } - - time.Sleep(time.Second * 10) - - provider, err := NewDNSProvider() - assert.NoError(t, err) - - err = provider.CleanUp(duckdnsDomain, "", "123d==") - assert.NoError(t, err) -} +package duckdns + +import ( + "os" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +var ( + duckdnsLiveTest bool + duckdnsToken string + duckdnsDomain string +) + +func init() { + duckdnsToken = os.Getenv("DUCKDNS_TOKEN") + duckdnsDomain = os.Getenv("DUCKDNS_DOMAIN") + if len(duckdnsToken) > 0 && len(duckdnsDomain) > 0 { + duckdnsLiveTest = true + } +} + +func restoreDuckdnsEnv() { + os.Setenv("DUCKDNS_TOKEN", duckdnsToken) +} + +func TestNewDNSProviderValidEnv(t *testing.T) { + os.Setenv("DUCKDNS_TOKEN", "123") + _, err := NewDNSProvider() + assert.NoError(t, err) + restoreDuckdnsEnv() +} +func TestNewDNSProviderMissingCredErr(t *testing.T) { + os.Setenv("DUCKDNS_TOKEN", "") + _, err := NewDNSProvider() + assert.EqualError(t, err, "environment variable DUCKDNS_TOKEN not set") + restoreDuckdnsEnv() +} +func TestLiveDuckdnsPresent(t *testing.T) { + if !duckdnsLiveTest { + t.Skip("skipping live test") + } + + provider, err := NewDNSProvider() + assert.NoError(t, err) + + err = provider.Present(duckdnsDomain, "", "123d==") + assert.NoError(t, err) +} + +func TestLiveDuckdnsCleanUp(t *testing.T) { + if !duckdnsLiveTest { + t.Skip("skipping live test") + } + + time.Sleep(time.Second * 10) + + provider, err := NewDNSProvider() + assert.NoError(t, err) + + err = provider.CleanUp(duckdnsDomain, "", "123d==") + assert.NoError(t, err) +} diff --git a/providers/dns/dyn/dyn.go b/providers/dns/dyn/dyn.go index 277dffb9..ad65fab6 100644 --- a/providers/dns/dyn/dyn.go +++ b/providers/dns/dyn/dyn.go @@ -80,7 +80,7 @@ func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) req.Header.Set("Auth-Token", d.token) } - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return nil, err @@ -158,7 +158,7 @@ func (d *DNSProvider) logout() error { req.Header.Set("Content-Type", "application/json") req.Header.Set("Auth-Token", d.token) - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return err @@ -206,12 +206,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { return err } - err = d.logout() - if err != nil { - return err - } - - return nil + return d.logout() } func (d *DNSProvider) publish(zone, notes string) error { @@ -222,12 +217,9 @@ func (d *DNSProvider) publish(zone, notes string) error { pub := &publish{Publish: true, Notes: notes} resource := fmt.Sprintf("Zone/%s/", zone) - _, err := d.sendRequest("PUT", resource, pub) - if err != nil { - return err - } - return nil + _, err := d.sendRequest("PUT", resource, pub) + return err } // CleanUp removes the TXT record matching the specified parameters @@ -253,7 +245,7 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { req.Header.Set("Content-Type", "application/json") req.Header.Set("Auth-Token", d.token) - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return err @@ -269,10 +261,5 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { return err } - err = d.logout() - if err != nil { - return err - } - - return nil + return d.logout() } diff --git a/providers/dns/exoscale/exoscale.go b/providers/dns/exoscale/exoscale.go index 4b125e8d..1467e8d7 100644 --- a/providers/dns/exoscale/exoscale.go +++ b/providers/dns/exoscale/exoscale.go @@ -16,7 +16,7 @@ type DNSProvider struct { client *egoscale.Client } -// Credentials must be passed in the environment variables: +// NewDNSProvider Credentials must be passed in the environment variables: // EXOSCALE_API_KEY, EXOSCALE_API_SECRET, EXOSCALE_ENDPOINT. func NewDNSProvider() (*DNSProvider, error) { key := os.Getenv("EXOSCALE_API_KEY") @@ -25,7 +25,7 @@ func NewDNSProvider() (*DNSProvider, error) { return NewDNSProviderClient(key, secret, endpoint) } -// Uses the supplied parameters to return a DNSProvider instance +// NewDNSProviderClient Uses the supplied parameters to return a DNSProvider instance // configured for Exoscale. func NewDNSProviderClient(key, secret, endpoint string) (*DNSProvider, error) { if key == "" || secret == "" { @@ -48,7 +48,7 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { return err } - recordID, err := c.FindExistingRecordId(zone, recordName) + recordID, err := c.FindExistingRecordID(zone, recordName) if err != nil { return err } @@ -84,7 +84,7 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { return err } - recordID, err := c.FindExistingRecordId(zone, recordName) + recordID, err := c.FindExistingRecordID(zone, recordName) if err != nil { return err } @@ -99,9 +99,9 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { return nil } -// Query Exoscale to find an existing record for this name. +// FindExistingRecordID Query Exoscale to find an existing record for this name. // Returns nil if no record could be found -func (c *DNSProvider) FindExistingRecordId(zone, recordName string) (int64, error) { +func (c *DNSProvider) FindExistingRecordID(zone, recordName string) (int64, error) { records, err := c.client.GetRecords(zone) if err != nil { return -1, errors.New("Error while retrievening DNS records: " + err.Error()) @@ -114,7 +114,7 @@ func (c *DNSProvider) FindExistingRecordId(zone, recordName string) (int64, erro return 0, nil } -// Extract DNS zone and DNS entry name +// FindZoneAndRecordName Extract DNS zone and DNS entry name func (c *DNSProvider) FindZoneAndRecordName(fqdn, domain string) (string, string, error) { zone, err := acme.FindZoneByFqdn(acme.ToFqdn(domain), acme.RecursiveNameservers) if err != nil { diff --git a/providers/dns/gandi/gandi.go b/providers/dns/gandi/gandi.go index 422b02a2..750bc8b4 100644 --- a/providers/dns/gandi/gandi.go +++ b/providers/dns/gandi/gandi.go @@ -74,15 +74,18 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { if ttl < 300 { ttl = 300 // 300 is gandi minimum value for ttl } + // find authZone and Gandi zone_id for fqdn authZone, err := findZoneByFqdn(fqdn, acme.RecursiveNameservers) if err != nil { return fmt.Errorf("Gandi DNS: findZoneByFqdn failure: %v", err) } + zoneID, err := d.getZoneID(authZone) if err != nil { return err } + // determine name of TXT record if !strings.HasSuffix( strings.ToLower(fqdn), strings.ToLower("."+authZone)) { @@ -90,40 +93,49 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { "Gandi DNS: unexpected authZone %s for fqdn %s", authZone, fqdn) } name := fqdn[:len(fqdn)-len("."+authZone)] + // acquire lock and check there is not a challenge already in // progress for this value of authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() + if _, ok := d.inProgressAuthZones[authZone]; ok { return fmt.Errorf( "Gandi DNS: challenge already in progress for authZone %s", authZone) } + // perform API actions to create and activate new gandi zone // containing the required TXT record newZoneName := fmt.Sprintf( "%s [ACME Challenge %s]", acme.UnFqdn(authZone), time.Now().Format(time.RFC822Z)) + newZoneID, err := d.cloneZone(zoneID, newZoneName) if err != nil { return err } + newZoneVersion, err := d.newZoneVersion(newZoneID) if err != nil { return err } + err = d.addTXTRecord(newZoneID, newZoneVersion, name, value, ttl) if err != nil { return err } + err = d.setZoneVersion(newZoneID, newZoneVersion) if err != nil { return err } + err = d.setZone(authZone, newZoneID) if err != nil { return err } + // save data necessary for CleanUp d.inProgressFQDNs[fqdn] = inProgressInfo{ zoneID: zoneID, @@ -142,25 +154,25 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { // acquire lock and retrieve zoneID, newZoneID and authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() + if _, ok := d.inProgressFQDNs[fqdn]; !ok { // if there is no cleanup information then just return return nil } + zoneID := d.inProgressFQDNs[fqdn].zoneID newZoneID := d.inProgressFQDNs[fqdn].newZoneID authZone := d.inProgressFQDNs[fqdn].authZone delete(d.inProgressFQDNs, fqdn) delete(d.inProgressAuthZones, authZone) + // perform API actions to restore old gandi zone for authZone err := d.setZone(authZone, zoneID) if err != nil { return err } - err = d.deleteZone(newZoneID) - if err != nil { - return err - } - return nil + + return d.deleteZone(newZoneID) } // Timeout returns the values (40*time.Minute, 60*time.Second) which @@ -259,15 +271,18 @@ func (e rpcError) Error() string { func httpPost(url string, bodyType string, body io.Reader) ([]byte, error) { client := http.Client{Timeout: 60 * time.Second} + resp, err := client.Post(url, bodyType, body) if err != nil { return nil, fmt.Errorf("Gandi DNS: HTTP Post Error: %v", err) } defer resp.Body.Close() + b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("Gandi DNS: HTTP Post Error: %v", err) } + return b, nil } @@ -281,12 +296,14 @@ func rpcCall(call *methodCall, resp response) error { if err != nil { return fmt.Errorf("Gandi DNS: Marshal Error: %v", err) } + // post b = append([]byte(``+"\n"), b...) respBody, err := httpPost(endpoint, "text/xml", bytes.NewReader(b)) if err != nil { return err } + // unmarshal err = xml.Unmarshal(respBody, resp) if err != nil { @@ -313,12 +330,14 @@ func (d *DNSProvider) getZoneID(domain string) (int, error) { if err != nil { return 0, err } + var zoneID int for _, member := range resp.StructMembers { if member.Name == "zone_id" { zoneID = member.ValueInt } } + if zoneID == 0 { return 0, fmt.Errorf( "Gandi DNS: Could not determine zone_id for %s", domain) @@ -346,12 +365,14 @@ func (d *DNSProvider) cloneZone(zoneID int, name string) (int, error) { if err != nil { return 0, err } + var newZoneID int for _, member := range resp.StructMembers { if member.Name == "id" { newZoneID = member.ValueInt } } + if newZoneID == 0 { return 0, fmt.Errorf("Gandi DNS: Could not determine cloned zone_id") } @@ -370,6 +391,7 @@ func (d *DNSProvider) newZoneVersion(zoneID int) (int, error) { if err != nil { return 0, err } + if resp.Value == 0 { return 0, fmt.Errorf("Gandi DNS: Could not create new zone version") } @@ -402,10 +424,7 @@ func (d *DNSProvider) addTXTRecord(zoneID int, version int, name string, value s }, }, }, resp) - if err != nil { - return err - } - return nil + return err } func (d *DNSProvider) setZoneVersion(zoneID int, version int) error { @@ -421,6 +440,7 @@ func (d *DNSProvider) setZoneVersion(zoneID int, version int) error { if err != nil { return err } + if !resp.Value { return fmt.Errorf("Gandi DNS: could not set zone version") } @@ -440,12 +460,14 @@ func (d *DNSProvider) setZone(domain string, zoneID int) error { if err != nil { return err } + var respZoneID int for _, member := range resp.StructMembers { if member.Name == "zone_id" { respZoneID = member.ValueInt } } + if respZoneID != zoneID { return fmt.Errorf( "Gandi DNS: Could not set new zone_id for %s", domain) @@ -465,6 +487,7 @@ func (d *DNSProvider) deleteZone(zoneID int) error { if err != nil { return err } + if !resp.Value { return fmt.Errorf("Gandi DNS: could not delete zone_id") } diff --git a/providers/dns/gandi/gandi_test.go b/providers/dns/gandi/gandi_test.go index c3899bd5..520c7e37 100644 --- a/providers/dns/gandi/gandi_test.go +++ b/providers/dns/gandi/gandi_test.go @@ -1,7 +1,6 @@ package gandi import ( - "crypto" "io" "io/ioutil" "net/http" @@ -9,30 +8,8 @@ import ( "regexp" "strings" "testing" - - "github.com/xenolf/lego/acme" ) -// stagingServer is the Let's Encrypt staging server used by the live test -const stagingServer = "https://acme-staging.api.letsencrypt.org/directory" - -// user implements acme.User and is used by the live test -type user struct { - Email string - Registration *acme.RegistrationResource - key crypto.PrivateKey -} - -func (u *user) GetEmail() string { - return u.Email -} -func (u *user) GetRegistration() *acme.RegistrationResource { - return u.Registration -} -func (u *user) GetPrivateKey() crypto.PrivateKey { - return u.key -} - // TestDNSProvider runs Present and CleanUp against a fake Gandi RPC // Server, whose responses are predetermined for particular requests. func TestDNSProvider(t *testing.T) { diff --git a/providers/dns/gandiv5/gandiv5.go b/providers/dns/gandiv5/gandiv5.go index 86cc7bf3..4614723a 100644 --- a/providers/dns/gandiv5/gandiv5.go +++ b/providers/dns/gandiv5/gandiv5.go @@ -21,6 +21,7 @@ var ( // endpoint is the Gandi API endpoint used by Present and // CleanUp. It is overridden during tests. endpoint = "https://dns.api.gandi.net/api/v5" + // findZoneByFqdn determines the DNS zone of an fqdn. It is overridden // during tests. findZoneByFqdn = acme.FindZoneByFqdn @@ -66,11 +67,13 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { if ttl < 300 { ttl = 300 // 300 is gandi minimum value for ttl } + // find authZone authZone, err := findZoneByFqdn(fqdn, acme.RecursiveNameservers) if err != nil { return fmt.Errorf("Gandi DNS: findZoneByFqdn failure: %v", err) } + // determine name of TXT record if !strings.HasSuffix( strings.ToLower(fqdn), strings.ToLower("."+authZone)) { @@ -78,15 +81,18 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { "Gandi DNS: unexpected authZone %s for fqdn %s", authZone, fqdn) } name := fqdn[:len(fqdn)-len("."+authZone)] + // acquire lock and check there is not a challenge already in // progress for this value of authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() + // add TXT record into authZone err = d.addTXTRecord(acme.UnFqdn(authZone), name, value, ttl) if err != nil { return err } + // save data necessary for CleanUp d.inProgressFQDNs[fqdn] = inProgressInfo{ authZone: authZone, @@ -98,6 +104,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { // CleanUp removes the TXT record matching the specified parameters. func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { fqdn, _, _ := acme.DNS01Record(domain, keyAuth) + // acquire lock and retrieve authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() @@ -105,15 +112,13 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { // if there is no cleanup information then just return return nil } + fieldName := d.inProgressFQDNs[fqdn].fieldName authZone := d.inProgressFQDNs[fqdn].authZone delete(d.inProgressFQDNs, fqdn) + // delete TXT record from authZone - err := d.deleteTXTRecord(acme.UnFqdn(authZone), fieldName) - if err != nil { - return err - } - return nil + return d.deleteTXTRecord(acme.UnFqdn(authZone), fieldName) } // Timeout returns the values (20*time.Minute, 20*time.Second) which @@ -149,16 +154,18 @@ func (d *DNSProvider) sendRequest(method string, resource string, payload interf if err != nil { return nil, err } + req, err := http.NewRequest(method, url, bytes.NewReader(body)) if err != nil { return nil, err } + req.Header.Set("Content-Type", "application/json") if len(d.apiKey) > 0 { req.Header.Set("X-Api-Key", d.apiKey) } - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return nil, err diff --git a/providers/dns/gandiv5/gandiv5_test.go b/providers/dns/gandiv5/gandiv5_test.go index 888ef92f..f6fa779f 100644 --- a/providers/dns/gandiv5/gandiv5_test.go +++ b/providers/dns/gandiv5/gandiv5_test.go @@ -1,7 +1,6 @@ package gandiv5 import ( - "crypto" "io" "io/ioutil" "net/http" @@ -9,30 +8,8 @@ import ( "regexp" "strings" "testing" - - "github.com/xenolf/lego/acme" ) -// stagingServer is the Let's Encrypt staging server used by the live test -const stagingServer = "https://acme-staging.api.letsencrypt.org/directory" - -// user implements acme.User and is used by the live test -type user struct { - Email string - Registration *acme.RegistrationResource - key crypto.PrivateKey -} - -func (u *user) GetEmail() string { - return u.Email -} -func (u *user) GetRegistration() *acme.RegistrationResource { - return u.Registration -} -func (u *user) GetPrivateKey() crypto.PrivateKey { - return u.key -} - // TestDNSProvider runs Present and CleanUp against a fake Gandi RPC // Server, whose responses are predetermined for particular requests. func TestDNSProvider(t *testing.T) { diff --git a/providers/dns/glesys/glesys.go b/providers/dns/glesys/glesys.go index 19560d28..7623b564 100644 --- a/providers/dns/glesys/glesys.go +++ b/providers/dns/glesys/glesys.go @@ -64,6 +64,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { if err != nil { return fmt.Errorf("GleSYS DNS: findZoneByFqdn failure: %v", err) } + // determine name of TXT record if !strings.HasSuffix( strings.ToLower(fqdn), strings.ToLower("."+authZone)) { @@ -71,23 +72,27 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { "GleSYS DNS: unexpected authZone %s for fqdn %s", authZone, fqdn) } name := fqdn[:len(fqdn)-len("."+authZone)] + // acquire lock and check there is not a challenge already in // progress for this value of authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() + // add TXT record into authZone - recordId, err := d.addTXTRecord(domain, acme.UnFqdn(authZone), name, value, ttl) + recordID, err := d.addTXTRecord(domain, acme.UnFqdn(authZone), name, value, ttl) if err != nil { return err } + // save data necessary for CleanUp - d.activeRecords[fqdn] = recordId + d.activeRecords[fqdn] = recordID return nil } // CleanUp removes the TXT record matching the specified parameters. func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { fqdn, _, _ := acme.DNS01Record(domain, keyAuth) + // acquire lock and retrieve authZone d.inProgressMu.Lock() defer d.inProgressMu.Unlock() @@ -95,14 +100,12 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { // if there is no cleanup information then just return return nil } - recordId := d.activeRecords[fqdn] + + recordID := d.activeRecords[fqdn] delete(d.activeRecords, fqdn) + // delete TXT record from authZone - err := d.deleteTXTRecord(domain, recordId) - if err != nil { - return err - } - return nil + return d.deleteTXTRecord(domain, recordID) } // Timeout returns the values (20*time.Minute, 20*time.Second) which @@ -119,7 +122,7 @@ type addRecordRequest struct { Host string `json:"host"` Type string `json:"type"` Data string `json:"data"` - Ttl int `json:"ttl,omitempty"` + TTL int `json:"ttl,omitempty"` } type deleteRecordRequest struct { @@ -144,14 +147,16 @@ func (d *DNSProvider) sendRequest(method string, resource string, payload interf if err != nil { return nil, err } + req, err := http.NewRequest(method, url, bytes.NewReader(body)) if err != nil { return nil, err } + req.Header.Set("Content-Type", "application/json") req.SetBasicAuth(d.apiUser, d.apiKey) - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return nil, err @@ -161,6 +166,7 @@ func (d *DNSProvider) sendRequest(method string, resource string, payload interf if resp.StatusCode >= 400 { return nil, fmt.Errorf("GleSYS DNS: request failed with HTTP status code %d", resp.StatusCode) } + var response responseStruct err = json.NewDecoder(resp.Body).Decode(&response) @@ -175,7 +181,7 @@ func (d *DNSProvider) addTXTRecord(fqdn string, domain string, name string, valu Host: name, Type: "TXT", Data: value, - Ttl: ttl, + TTL: ttl, }) if response != nil && response.Response.Status.Code == 200 { log.Printf("[INFO][%s] GleSYS DNS: Successfully created recordid %d", fqdn, response.Response.Record.Recordid) diff --git a/providers/dns/godaddy/godaddy.go b/providers/dns/godaddy/godaddy.go index 4112f662..54fbad03 100644 --- a/providers/dns/godaddy/godaddy.go +++ b/providers/dns/godaddy/godaddy.go @@ -10,9 +10,10 @@ import ( "bytes" "encoding/json" - "github.com/xenolf/lego/acme" "io/ioutil" "strings" + + "github.com/xenolf/lego/acme" ) // GoDaddyAPIURL represents the API endpoint to call. @@ -75,7 +76,7 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { Type: "TXT", Name: recordName, Data: value, - Ttl: ttl, + TTL: ttl, }, } @@ -98,7 +99,7 @@ func (c *DNSProvider) updateRecords(records []DNSRecord, domainZone string, reco if resp.StatusCode != http.StatusOK { bodyBytes, _ := ioutil.ReadAll(resp.Body) - return fmt.Errorf("Could not create record %v; Status: %v; Body: %s\n", string(body), resp.StatusCode, string(bodyBytes)) + return fmt.Errorf("could not create record %v; Status: %v; Body: %s", string(body), resp.StatusCode, string(bodyBytes)) } return nil } @@ -146,10 +147,11 @@ func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (*http.Res return client.Do(req) } +// DNSRecord a DNS record type DNSRecord struct { Type string `json:"type"` Name string `json:"name"` Data string `json:"data"` Priority int `json:"priority,omitempty"` - Ttl int `json:"ttl,omitempty"` + TTL int `json:"ttl,omitempty"` } diff --git a/providers/dns/googlecloud/googlecloud.go b/providers/dns/googlecloud/googlecloud.go index ba753f6d..dc46152f 100644 --- a/providers/dns/googlecloud/googlecloud.go +++ b/providers/dns/googlecloud/googlecloud.go @@ -11,7 +11,6 @@ import ( "github.com/xenolf/lego/acme" "golang.org/x/net/context" - "golang.org/x/oauth2" "golang.org/x/oauth2/google" "google.golang.org/api/dns/v1" @@ -74,7 +73,7 @@ func NewDNSProviderServiceAccount(project string, saFile string) (*DNSProvider, if err != nil { return nil, fmt.Errorf("Unable to acquire config: %v", err) } - client := conf.Client(oauth2.NoContext) + client := conf.Client(context.Background()) svc, err := dns.New(client) if err != nil { diff --git a/providers/dns/googlecloud/googlecloud_test.go b/providers/dns/googlecloud/googlecloud_test.go index 75a10d9a..70b0e730 100644 --- a/providers/dns/googlecloud/googlecloud_test.go +++ b/providers/dns/googlecloud/googlecloud_test.go @@ -80,6 +80,7 @@ func TestLiveGoogleCloudPresentMultiple(t *testing.T) { // Check that we're able to create multiple entries err = provider.Present(gcloudDomain, "1", "123d==") + assert.NoError(t, err) err = provider.Present(gcloudDomain, "2", "123d==") assert.NoError(t, err) } diff --git a/providers/dns/linode/linode.go b/providers/dns/linode/linode.go index a91d2b48..1e8cbc50 100644 --- a/providers/dns/linode/linode.go +++ b/providers/dns/linode/linode.go @@ -19,7 +19,7 @@ const ( ) type hostedZoneInfo struct { - domainId int + domainID int resourceName string } @@ -72,7 +72,7 @@ func (p *DNSProvider) Present(domain, token, keyAuth string) error { return err } - if _, err = p.linode.CreateDomainResourceTXT(zone.domainId, acme.UnFqdn(fqdn), value, 60); err != nil { + if _, err = p.linode.CreateDomainResourceTXT(zone.domainID, acme.UnFqdn(fqdn), value, 60); err != nil { return err } @@ -88,7 +88,7 @@ func (p *DNSProvider) CleanUp(domain, token, keyAuth string) error { } // Get all TXT records for the specified domain. - resources, err := p.linode.GetResourcesByType(zone.domainId, "TXT") + resources, err := p.linode.GetResourcesByType(zone.domainID, "TXT") if err != nil { return err } @@ -101,7 +101,7 @@ func (p *DNSProvider) CleanUp(domain, token, keyAuth string) error { return err } if resp.ResourceID != resource.ResourceID { - return errors.New("Error deleting resource: resource IDs do not match!") + return errors.New("error deleting resource: resource IDs do not match") } break } @@ -125,7 +125,7 @@ func (p *DNSProvider) getHostedZoneInfo(fqdn string) (*hostedZoneInfo, error) { } return &hostedZoneInfo{ - domainId: domain.DomainID, + domainID: domain.DomainID, resourceName: resourceName, }, nil } diff --git a/providers/dns/namecheap/namecheap.go b/providers/dns/namecheap/namecheap.go index d7eb4093..2991d817 100644 --- a/providers/dns/namecheap/namecheap.go +++ b/providers/dns/namecheap/namecheap.go @@ -144,7 +144,7 @@ func newChallenge(domain, keyAuth string, tlds map[string]string) (*challenge, e } } if longest < 1 { - return nil, fmt.Errorf("Invalid domain name '%s'", domain) + return nil, fmt.Errorf("invalid domain name %q", domain) } tld := strings.Join(parts[longest:], ".") @@ -318,7 +318,7 @@ func (d *DNSProvider) setHosts(ch *challenge, hosts []host) error { shr.Errors[0].Description, shr.Errors[0].Number) } if shr.Result.IsSuccess != "true" { - return fmt.Errorf("Namecheap setHosts failed.") + return fmt.Errorf("Namecheap setHosts failed") } return nil diff --git a/providers/dns/otc/mock.go b/providers/dns/otc/mock.go index 0f2acb4b..babc2b3a 100644 --- a/providers/dns/otc/mock.go +++ b/providers/dns/otc/mock.go @@ -2,11 +2,12 @@ package otc import ( "fmt" - "github.com/stretchr/testify/assert" "io/ioutil" "net/http" "net/http/httptest" "testing" + + "github.com/stretchr/testify/assert" ) var fakeOTCUserName = "test" @@ -15,12 +16,14 @@ var fakeOTCDomainName = "test" var fakeOTCProjectName = "test" var fakeOTCToken = "62244bc21da68d03ebac94e6636ff01f" +// DNSMock mock type DNSMock struct { t *testing.T Server *httptest.Server Mux *http.ServeMux } +// NewDNSMock create a new DNSMock func NewDNSMock(t *testing.T) *DNSMock { return &DNSMock{ t: t, @@ -38,6 +41,7 @@ func (m *DNSMock) ShutdownServer() { m.Server.Close() } +// HandleAuthSuccessfully Handle auth successfully func (m *DNSMock) HandleAuthSuccessfully() { m.Mux.HandleFunc("/v3/auth/token", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Subject-Token", fakeOTCToken) @@ -64,6 +68,7 @@ func (m *DNSMock) HandleAuthSuccessfully() { }) } +// HandleListZonesSuccessfully Handle list zones successfully func (m *DNSMock) HandleListZonesSuccessfully() { m.Mux.HandleFunc("/v2/zones", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{ @@ -79,6 +84,7 @@ func (m *DNSMock) HandleListZonesSuccessfully() { }) } +// HandleListZonesEmpty Handle list zones empty func (m *DNSMock) HandleListZonesEmpty() { m.Mux.HandleFunc("/v2/zones", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{ @@ -93,6 +99,7 @@ func (m *DNSMock) HandleListZonesEmpty() { }) } +// HandleDeleteRecordsetsSuccessfully Handle delete recordsets successfully func (m *DNSMock) HandleDeleteRecordsetsSuccessfully() { m.Mux.HandleFunc("/v2/zones/123123/recordsets/321321", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{ @@ -107,6 +114,7 @@ func (m *DNSMock) HandleDeleteRecordsetsSuccessfully() { }) } +// HandleListRecordsetsEmpty Handle list recordsets empty func (m *DNSMock) HandleListRecordsetsEmpty() { m.Mux.HandleFunc("/v2/zones/123123/recordsets", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `{ @@ -118,6 +126,8 @@ func (m *DNSMock) HandleListRecordsetsEmpty() { assert.Equal(m.t, r.URL.RawQuery, "type=TXT&name=_acme-challenge.example.com.") }) } + +// HandleListRecordsetsSuccessfully Handle list recordsets successfully func (m *DNSMock) HandleListRecordsetsSuccessfully() { m.Mux.HandleFunc("/v2/zones/123123/recordsets", func(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { diff --git a/providers/dns/otc/otc.go b/providers/dns/otc/otc.go index 86bcaa9b..86918730 100644 --- a/providers/dns/otc/otc.go +++ b/providers/dns/otc/otc.go @@ -59,6 +59,7 @@ func NewDNSProviderCredentials(domainName, userName, password, projectName, iden }, nil } +// SendRequest send request func (d *DNSProvider) SendRequest(method, resource string, payload interface{}) (io.Reader, error) { url := fmt.Sprintf("%s/%s", d.otcBaseURL, resource) @@ -81,7 +82,7 @@ func (d *DNSProvider) SendRequest(method, resource string, payload interface{}) tr.DisableKeepAlives = true client := &http.Client{ - Timeout: time.Duration(10 * time.Second), + Timeout: 10 * time.Second, Transport: tr, } resp, err := client.Do(req) @@ -168,7 +169,7 @@ func (d *DNSProvider) loginRequest() error { } req.Header.Set("Content-Type", "application/json") - client := &http.Client{Timeout: time.Duration(10 * time.Second)} + client := &http.Client{Timeout: 10 * time.Second} resp, err := client.Do(req) if err != nil { return err @@ -221,12 +222,7 @@ func (d *DNSProvider) loginRequest() error { // Starts a new OTC API Session. Authenticates using userName, password // and receives a token to be used in for subsequent requests. func (d *DNSProvider) login() error { - err := d.loginRequest() - if err != nil { - return err - } - - return nil + return d.loginRequest() } func (d *DNSProvider) getZoneID(zone string) (string, error) { @@ -305,10 +301,7 @@ func (d *DNSProvider) deleteRecordSet(zoneID, recordID string) error { resource := fmt.Sprintf("zones/%s/recordsets/%s", zoneID, recordID) _, err := d.SendRequest("DELETE", resource, nil) - if err != nil { - return err - } - return nil + return err } // Present creates a TXT record using the specified parameters @@ -340,7 +333,7 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { Name string `json:"name"` Description string `json:"description"` Type string `json:"type"` - Ttl int `json:"ttl"` + TTL int `json:"ttl"` Records []string `json:"records"` } @@ -348,16 +341,11 @@ func (d *DNSProvider) Present(domain, token, keyAuth string) error { Name: fqdn, Description: "Added TXT record for ACME dns-01 challenge using lego client", Type: "TXT", - Ttl: 300, + TTL: ttl, Records: []string{fmt.Sprintf("\"%s\"", value)}, } _, err = d.SendRequest("POST", resource, r1) - - if err != nil { - return err - } - - return nil + return err } // CleanUp removes the TXT record matching the specified parameters @@ -375,7 +363,6 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { } zoneID, err := d.getZoneID(authZone) - if err != nil { return err } @@ -384,5 +371,6 @@ func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { if err != nil { return fmt.Errorf("unable go get record %s for zone %s: %s", fqdn, domain, err) } + return d.deleteRecordSet(zoneID, recordID) } diff --git a/providers/dns/ovh/ovh.go b/providers/dns/ovh/ovh.go index 290a8d7d..a49fc774 100644 --- a/providers/dns/ovh/ovh.go +++ b/providers/dns/ovh/ovh.go @@ -1,4 +1,4 @@ -// Package OVH implements a DNS provider for solving the DNS-01 +// Package ovh implements a DNS provider for solving the DNS-01 // challenge using OVH DNS. package ovh diff --git a/providers/dns/pdns/pdns.go b/providers/dns/pdns/pdns.go index a7856e6d..10124ae2 100644 --- a/providers/dns/pdns/pdns.go +++ b/providers/dns/pdns/pdns.go @@ -29,12 +29,12 @@ type DNSProvider struct { // PDNS_API_URL and PDNS_API_KEY. func NewDNSProvider() (*DNSProvider, error) { key := os.Getenv("PDNS_API_KEY") - hostUrl, err := url.Parse(os.Getenv("PDNS_API_URL")) + hostURL, err := url.Parse(os.Getenv("PDNS_API_URL")) if err != nil { return nil, err } - return NewDNSProviderCredentials(hostUrl, key) + return NewDNSProviderCredentials(hostURL, key) } // NewDNSProviderCredentials uses the supplied credentials to return a @@ -107,12 +107,7 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { } _, err = c.makeRequest("PATCH", zone.URL, bytes.NewReader(body)) - if err != nil { - fmt.Println("here") - return err - } - - return nil + return err } // CleanUp removes the TXT record matching the specified parameters @@ -131,7 +126,7 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { rrsets := rrSets{ RRSets: []rrSet{ - rrSet{ + { Name: set.Name, Type: set.Type, ChangeType: "DELETE", @@ -220,7 +215,7 @@ func (c *DNSProvider) findTxtRecord(fqdn string) (*rrSet, error) { } } - return nil, fmt.Errorf("No existing record found for %s", fqdn) + return nil, fmt.Errorf("no existing record found for %s", fqdn) } func (c *DNSProvider) getAPIVersion() { diff --git a/providers/dns/rackspace/rackspace.go b/providers/dns/rackspace/rackspace.go index 13daa8c8..d30e582b 100644 --- a/providers/dns/rackspace/rackspace.go +++ b/providers/dns/rackspace/rackspace.go @@ -92,7 +92,7 @@ func NewDNSProviderCredentials(user, key string) (*DNSProvider, error) { client := http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { - return nil, fmt.Errorf("Error querying Rackspace Identity API: %v", err) + return nil, fmt.Errorf("error querying Rackspace Identity API: %v", err) } defer resp.Body.Close() @@ -115,7 +115,7 @@ func NewDNSProviderCredentials(user, key string) (*DNSProvider, error) { } } if dnsEndpoint == "" { - return nil, fmt.Errorf("Failed to populate DNS endpoint, check Rackspace API for changes.") + return nil, fmt.Errorf("failed to populate DNS endpoint, check Rackspace API for changes") } return &DNSProvider{ @@ -132,8 +132,8 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { return err } - rec := RackspaceRecords{ - RackspaceRecord: []RackspaceRecord{{ + rec := Records{ + Record: []Record{{ Name: acme.UnFqdn(fqdn), Type: "TXT", Data: value, @@ -147,11 +147,7 @@ func (c *DNSProvider) Present(domain, token, keyAuth string) error { } _, err = c.makeRequest("POST", fmt.Sprintf("/domains/%d/records", zoneID), bytes.NewReader(body)) - if err != nil { - return err - } - - return nil + return err } // CleanUp removes the TXT record matching the specified parameters @@ -168,11 +164,7 @@ func (c *DNSProvider) CleanUp(domain, token, keyAuth string) error { } _, err = c.makeRequest("DELETE", fmt.Sprintf("/domains/%d/records?id=%s", zoneID, record.ID), nil) - if err != nil { - return err - } - - return nil + return err } // getHostedZoneID performs a lookup to get the DNS zone which needs @@ -205,36 +197,35 @@ func (c *DNSProvider) getHostedZoneID(fqdn string) (int, error) { // If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur) if zoneSearchResponse.TotalEntries != 1 { - return 0, fmt.Errorf("Found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn) + return 0, fmt.Errorf("found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn) } return zoneSearchResponse.HostedZones[0].ID, nil } // findTxtRecord searches a DNS zone for a TXT record with a specific name -func (c *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*RackspaceRecord, error) { +func (c *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) { result, err := c.makeRequest("GET", fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, acme.UnFqdn(fqdn)), nil) if err != nil { return nil, err } - var records RackspaceRecords + var records Records err = json.Unmarshal(result, &records) if err != nil { return nil, err } - recordsLength := len(records.RackspaceRecord) + recordsLength := len(records.Record) switch recordsLength { case 1: - break case 0: - return nil, fmt.Errorf("No TXT record found for %s", fqdn) + return nil, fmt.Errorf("no TXT record found for %s", fqdn) default: - return nil, fmt.Errorf("More than 1 TXT record found for %s", fqdn) + return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn) } - return &records.RackspaceRecord[0], nil + return &records.Record[0], nil } // makeRequest is a wrapper function used for making DNS API requests @@ -251,13 +242,13 @@ func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawM client := http.Client{Timeout: 30 * time.Second} resp, err := client.Do(req) if err != nil { - return nil, fmt.Errorf("Error querying DNS API: %v", err) + return nil, fmt.Errorf("error querying DNS API: %v", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted { - return nil, fmt.Errorf("Request failed for %s %s. Response code: %d", method, url, resp.StatusCode) + return nil, fmt.Errorf("request failed for %s %s. Response code: %d", method, url, resp.StatusCode) } var r json.RawMessage @@ -269,13 +260,13 @@ func (c *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawM return r, nil } -// RackspaceRecords is the list of records sent/received from the DNS API -type RackspaceRecords struct { - RackspaceRecord []RackspaceRecord `json:"records"` +// Records is the list of records sent/received from the DNS API +type Records struct { + Record []Record `json:"records"` } -// RackspaceRecord represents a Rackspace DNS record -type RackspaceRecord struct { +// Record represents a Rackspace DNS record +type Record struct { Name string `json:"name"` Type string `json:"type"` Data string `json:"data"` diff --git a/providers/dns/rackspace/rackspace_test.go b/providers/dns/rackspace/rackspace_test.go index 22c979ca..ed7a12f9 100644 --- a/providers/dns/rackspace/rackspace_test.go +++ b/providers/dns/rackspace/rackspace_test.go @@ -42,13 +42,14 @@ func liveRackspaceEnv() { os.Setenv("RACKSPACE_API_KEY", rackspaceAPIKey) } -func startTestServers() (identityAPI, dnsAPI *httptest.Server) { - dnsAPI = httptest.NewServer(dnsMux()) +func startTestServers() (*httptest.Server, *httptest.Server) { + dnsAPI := httptest.NewServer(dnsMux()) dnsEndpoint := dnsAPI.URL + "/123456" - identityAPI = httptest.NewServer(identityHandler(dnsEndpoint)) + identityAPI := httptest.NewServer(identityHandler(dnsEndpoint)) testAPIURL = identityAPI.URL + "/" - return + + return identityAPI, dnsAPI } func closeTestServers(identityAPI, dnsAPI *httptest.Server) { diff --git a/providers/dns/rfc2136/rfc2136.go b/providers/dns/rfc2136/rfc2136.go index dde42ddf..8f4231df 100644 --- a/providers/dns/rfc2136/rfc2136.go +++ b/providers/dns/rfc2136/rfc2136.go @@ -27,7 +27,7 @@ type DNSProvider struct { // dynamic update. Configured with environment variables: // RFC2136_NAMESERVER: Network address in the form "host" or "host:port". // RFC2136_TSIG_ALGORITHM: Defaults to hmac-md5.sig-alg.reg.int. (HMAC-MD5). -// See https://github.com/miekg/dns/blob/master/tsig.go for supported values. +// See https://github.com/miekg/dns/blob/master/tsig.go for supported values. // RFC2136_TSIG_KEY: Name of the secret key as defined in DNS server configuration. // RFC2136_TSIG_SECRET: Secret key payload. // RFC2136_TIMEOUT: DNS propagation timeout in time.ParseDuration format. (60s) @@ -77,7 +77,7 @@ func NewDNSProviderCredentials(nameserver, tsigAlgorithm, tsigKey, tsigSecret, t if err != nil { return nil, err } else if t < 0 { - return nil, fmt.Errorf("Invalid/negative RFC2136_TIMEOUT: %v", timeout) + return nil, fmt.Errorf("invalid/negative RFC2136_TIMEOUT: %v", timeout) } else { d.timeout = t } @@ -86,26 +86,26 @@ func NewDNSProviderCredentials(nameserver, tsigAlgorithm, tsigKey, tsigSecret, t return d, nil } -// Returns the timeout configured with RFC2136_TIMEOUT, or 60s. +// Timeout Returns the timeout configured with RFC2136_TIMEOUT, or 60s. func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.timeout, 2 * time.Second + return d.timeout, 2 * time.Second } // Present creates a TXT record using the specified parameters -func (r *DNSProvider) Present(domain, token, keyAuth string) error { +func (d *DNSProvider) Present(domain, token, keyAuth string) error { fqdn, value, ttl := acme.DNS01Record(domain, keyAuth) - return r.changeRecord("INSERT", fqdn, value, ttl) + return d.changeRecord("INSERT", fqdn, value, ttl) } // CleanUp removes the TXT record matching the specified parameters -func (r *DNSProvider) CleanUp(domain, token, keyAuth string) error { +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { fqdn, value, ttl := acme.DNS01Record(domain, keyAuth) - return r.changeRecord("REMOVE", fqdn, value, ttl) + return d.changeRecord("REMOVE", fqdn, value, ttl) } -func (r *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { +func (d *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { // Find the zone for the given fqdn - zone, err := acme.FindZoneByFqdn(fqdn, []string{r.nameserver}) + zone, err := acme.FindZoneByFqdn(fqdn, []string{d.nameserver}) if err != nil { return err } @@ -127,20 +127,20 @@ func (r *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { case "REMOVE": m.Remove(rrs) default: - return fmt.Errorf("Unexpected action: %s", action) + return fmt.Errorf("unexpected action: %s", action) } // Setup client c := new(dns.Client) c.SingleInflight = true // TSIG authentication / msg signing - if len(r.tsigKey) > 0 && len(r.tsigSecret) > 0 { - m.SetTsig(dns.Fqdn(r.tsigKey), r.tsigAlgorithm, 300, time.Now().Unix()) - c.TsigSecret = map[string]string{dns.Fqdn(r.tsigKey): r.tsigSecret} + if len(d.tsigKey) > 0 && len(d.tsigSecret) > 0 { + m.SetTsig(dns.Fqdn(d.tsigKey), d.tsigAlgorithm, 300, time.Now().Unix()) + c.TsigSecret = map[string]string{dns.Fqdn(d.tsigKey): d.tsigSecret} } // Send the query - reply, _, err := c.Exchange(m, r.nameserver) + reply, _, err := c.Exchange(m, d.nameserver) if err != nil { return fmt.Errorf("DNS update failed: %v", err) } diff --git a/providers/dns/route53/route53.go b/providers/dns/route53/route53.go index e16e12f0..adc15401 100644 --- a/providers/dns/route53/route53.go +++ b/providers/dns/route53/route53.go @@ -99,7 +99,7 @@ func (r *DNSProvider) CleanUp(domain, token, keyAuth string) error { func (r *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { hostedZoneID, err := r.getHostedZoneID(fqdn) if err != nil { - return fmt.Errorf("Failed to determine Route 53 hosted zone ID: %v", err) + return fmt.Errorf("failed to determine Route 53 hosted zone ID: %v", err) } recordSet := newTXTRecordSet(fqdn, value, ttl) @@ -118,7 +118,7 @@ func (r *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { resp, err := r.client.ChangeResourceRecordSets(reqParams) if err != nil { - return fmt.Errorf("Failed to change Route 53 record set: %v", err) + return fmt.Errorf("failed to change Route 53 record set: %v", err) } statusID := resp.ChangeInfo.Id @@ -129,9 +129,9 @@ func (r *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { } resp, err := r.client.GetChange(reqParams) if err != nil { - return false, fmt.Errorf("Failed to query Route 53 change status: %v", err) + return false, fmt.Errorf("failed to query Route 53 change status: %v", err) } - if *resp.ChangeInfo.Status == route53.ChangeStatusInsync { + if aws.StringValue(resp.ChangeInfo.Status) == route53.ChangeStatusInsync { return true, nil } return false, nil @@ -160,14 +160,14 @@ func (r *DNSProvider) getHostedZoneID(fqdn string) (string, error) { var hostedZoneID string for _, hostedZone := range resp.HostedZones { // .Name has a trailing dot - if !*hostedZone.Config.PrivateZone && *hostedZone.Name == authZone { - hostedZoneID = *hostedZone.Id + if !aws.BoolValue(hostedZone.Config.PrivateZone) && aws.StringValue(hostedZone.Name) == authZone { + hostedZoneID = aws.StringValue(hostedZone.Id) break } } if len(hostedZoneID) == 0 { - return "", fmt.Errorf("Zone %s not found in Route 53 for domain %s", authZone, fqdn) + return "", fmt.Errorf("zone %s not found in Route 53 for domain %s", authZone, fqdn) } if strings.HasPrefix(hostedZoneID, "/hostedzone/") { diff --git a/providers/dns/route53/route53_integration_test.go b/providers/dns/route53/route53_integration_test.go index 17ba4a08..6ece1888 100644 --- a/providers/dns/route53/route53_integration_test.go +++ b/providers/dns/route53/route53_integration_test.go @@ -11,7 +11,6 @@ import ( ) func TestRoute53TTL(t *testing.T) { - m, err := testGetAndPreCheck() if err != nil { t.Skip(err.Error()) @@ -19,13 +18,14 @@ func TestRoute53TTL(t *testing.T) { provider, err := NewDNSProvider() if err != nil { - t.Fatalf("Fatal: %s", err.Error()) + t.Fatal(err) } err = provider.Present(m["route53Domain"], "foo", "bar") if err != nil { - t.Fatalf("Fatal: %s", err.Error()) + t.Fatal(err) } + // we need a separate R53 client here as the one in the DNS provider is // unexported. fqdn := "_acme-challenge." + m["route53Domain"] + "." @@ -33,23 +33,25 @@ func TestRoute53TTL(t *testing.T) { zoneID, err := provider.getHostedZoneID(fqdn) if err != nil { provider.CleanUp(m["route53Domain"], "foo", "bar") - t.Fatalf("Fatal: %s", err.Error()) + t.Fatal(err) } + params := &route53.ListResourceRecordSetsInput{ HostedZoneId: aws.String(zoneID), } resp, err := svc.ListResourceRecordSets(params) if err != nil { provider.CleanUp(m["route53Domain"], "foo", "bar") - t.Fatalf("Fatal: %s", err.Error()) + t.Fatal(err) } for _, v := range resp.ResourceRecordSets { - if *v.Name == fqdn && *v.Type == "TXT" && *v.TTL == 10 { + if aws.StringValue(v.Name) == fqdn && aws.StringValue(v.Type) == "TXT" && aws.Int64Value(v.TTL) == 10 { provider.CleanUp(m["route53Domain"], "foo", "bar") return } } + provider.CleanUp(m["route53Domain"], "foo", "bar") t.Fatalf("Could not find a TXT record for _acme-challenge.%s with a TTL of 10", m["route53Domain"]) } diff --git a/providers/dns/route53/route53_test.go b/providers/dns/route53/route53_test.go index de4e28f3..e1505470 100644 --- a/providers/dns/route53/route53_test.go +++ b/providers/dns/route53/route53_test.go @@ -65,7 +65,7 @@ func TestRegionFromEnv(t *testing.T) { os.Setenv("AWS_REGION", "us-east-1") sess := session.New(aws.NewConfig()) - assert.Equal(t, "us-east-1", *sess.Config.Region, "Expected Region to be set from environment") + assert.Equal(t, "us-east-1", aws.StringValue(sess.Config.Region), "Expected Region to be set from environment") restoreRoute53Env() } diff --git a/providers/http/memcached/memcached.go b/providers/http/memcached/memcached.go index 9ac8b811..fc625bc5 100644 --- a/providers/http/memcached/memcached.go +++ b/providers/http/memcached/memcached.go @@ -10,18 +10,18 @@ import ( "github.com/xenolf/lego/acme" ) -// HTTPProvider implements ChallengeProvider for `http-01` challenge -type MemcachedProvider struct { +// HTTPProvider implements HTTPProvider for `http-01` challenge +type HTTPProvider struct { hosts []string } -// NewHTTPProvider returns a HTTPProvider instance with a configured webroot path -func NewMemcachedProvider(hosts []string) (*MemcachedProvider, error) { +// NewMemcachedProvider returns a HTTPProvider instance with a configured webroot path +func NewMemcachedProvider(hosts []string) (*HTTPProvider, error) { if len(hosts) == 0 { - return nil, fmt.Errorf("No memcached hosts provided") + return nil, fmt.Errorf("no memcached hosts provided") } - c := &MemcachedProvider{ + c := &HTTPProvider{ hosts: hosts, } @@ -29,7 +29,7 @@ func NewMemcachedProvider(hosts []string) (*MemcachedProvider, error) { } // Present makes the token available at `HTTP01ChallengePath(token)` by creating a file in the given webroot path -func (w *MemcachedProvider) Present(domain, token, keyAuth string) error { +func (w *HTTPProvider) Present(domain, token, keyAuth string) error { var errs []error challengePath := path.Join("/", acme.HTTP01ChallengePath(token)) @@ -39,7 +39,7 @@ func (w *MemcachedProvider) Present(domain, token, keyAuth string) error { errs = append(errs, err) continue } - mc.Add(&memcache.Item{ + _ = mc.Add(&memcache.Item{ Key: challengePath, Value: []byte(keyAuth), Expiration: 60, @@ -47,14 +47,14 @@ func (w *MemcachedProvider) Present(domain, token, keyAuth string) error { } if len(errs) == len(w.hosts) { - return fmt.Errorf("Unable to store key in any of the memcache hosts -> %v", errs) + return fmt.Errorf("unable to store key in any of the memcache hosts -> %v", errs) } return nil } // CleanUp removes the file created for the challenge -func (w *MemcachedProvider) CleanUp(domain, token, keyAuth string) error { +func (w *HTTPProvider) CleanUp(domain, token, keyAuth string) error { // Memcached will clean up itself, that's what expiration is for. return nil } diff --git a/providers/http/memcached/memcached_test.go b/providers/http/memcached/memcached_test.go index 287a3330..f9488a1d 100644 --- a/providers/http/memcached/memcached_test.go +++ b/providers/http/memcached/memcached_test.go @@ -31,7 +31,7 @@ func init() { func TestNewMemcachedProviderEmpty(t *testing.T) { emptyHosts := make([]string, 0) _, err := NewMemcachedProvider(emptyHosts) - assert.EqualError(t, err, "No memcached hosts provided") + assert.EqualError(t, err, "no memcached hosts provided") } func TestNewMemcachedProviderValid(t *testing.T) { diff --git a/providers/http/webroot/webroot.go b/providers/http/webroot/webroot.go index 4bf211f3..f9dce06d 100644 --- a/providers/http/webroot/webroot.go +++ b/providers/http/webroot/webroot.go @@ -35,12 +35,12 @@ func (w *HTTPProvider) Present(domain, token, keyAuth string) error { challengeFilePath := path.Join(w.path, acme.HTTP01ChallengePath(token)) err = os.MkdirAll(path.Dir(challengeFilePath), 0755) if err != nil { - return fmt.Errorf("Could not create required directories in webroot for HTTP challenge -> %v", err) + return fmt.Errorf("could not create required directories in webroot for HTTP challenge -> %v", err) } err = ioutil.WriteFile(challengeFilePath, []byte(keyAuth), 0644) if err != nil { - return fmt.Errorf("Could not write file in webroot for HTTP challenge -> %v", err) + return fmt.Errorf("could not write file in webroot for HTTP challenge -> %v", err) } return nil @@ -48,10 +48,9 @@ func (w *HTTPProvider) Present(domain, token, keyAuth string) error { // CleanUp removes the file created for the challenge func (w *HTTPProvider) CleanUp(domain, token, keyAuth string) error { - var err error - err = os.Remove(path.Join(w.path, acme.HTTP01ChallengePath(token))) + err := os.Remove(path.Join(w.path, acme.HTTP01ChallengePath(token))) if err != nil { - return fmt.Errorf("Could not remove file in webroot after HTTP challenge -> %v", err) + return fmt.Errorf("could not remove file in webroot after HTTP challenge -> %v", err) } return nil