From 6ecdde77f0172cbfce33b37251b56d1f9b1b60e1 Mon Sep 17 00:00:00 2001 From: Marcus Grando Date: Sun, 29 Jun 2025 22:30:00 -0300 Subject: [PATCH] Add DNS provider for Azion (#2550) Co-authored-by: Fernandez Ludovic --- README.md | 77 ++++--- cmd/zz_gen_cmd_dnshelp.go | 21 ++ docs/content/dns/zz_gen_azion.md | 68 ++++++ docs/data/zz_cli_help.toml | 2 +- go.mod | 1 + go.sum | 3 + providers/dns/azion/azion.go | 309 ++++++++++++++++++++++++++ providers/dns/azion/azion.toml | 23 ++ providers/dns/azion/azion_test.go | 115 ++++++++++ providers/dns/zz_gen_dns_providers.go | 3 + 10 files changed, 585 insertions(+), 37 deletions(-) create mode 100644 docs/content/dns/zz_gen_azion.md create mode 100644 providers/dns/azion/azion.go create mode 100644 providers/dns/azion/azion.toml create mode 100644 providers/dns/azion/azion_test.go diff --git a/README.md b/README.md index 10791925c..f527a082d 100644 --- a/README.md +++ b/README.md @@ -65,188 +65,193 @@ Detailed documentation is available [here](https://go-acme.github.io/lego/dns). Autodns Axelname + Azion Azure (deprecated) - Azure DNS + Azure DNS Baidu Cloud Bindman Bluecat - BookMyName + BookMyName Brandit (deprecated) Bunny Checkdomain - Civo + Civo Cloud.ru CloudDNS Cloudflare - ClouDNS + ClouDNS CloudXNS (Deprecated) ConoHa v2 ConoHa v3 - Constellix + Constellix Core-Networks CPanel/WHM Derak Cloud - deSEC.io + deSEC.io Designate DNSaaS for Openstack Digital Ocean DirectAdmin - DNS Made Easy + DNS Made Easy dnsHome.de DNSimple DNSPod (deprecated) - Domain Offensive (do.de) + Domain Offensive (do.de) Domeneshop DreamHost Duck DNS - Dyn + Dyn DynDnsFree.de Dynu EasyDNS - Efficient IP + Efficient IP Epik Exoscale External program - F5 XC + F5 XC freemyip.com G-Core Gandi - Gandi Live DNS (v5) + Gandi Live DNS (v5) Glesys Go Daddy Google Cloud - Google Domains + Google Domains Hetzner Hosting.de Hosttech - HTTP request + HTTP request http.net Huawei Cloud Hurricane Electric DNS - HyperOne + HyperOne IBM Cloud (SoftLayer) IIJ DNS Platform Service Infoblox - Infomaniak + Infomaniak Internet Initiative Japan Internet.bs INWX - Ionos + Ionos IPv64 iwantmyname Joker - Joohoi's ACME-DNS + Joohoi's ACME-DNS Liara Lima-City Linode (v4) - Liquid Web + Liquid Web Loopia LuaDNS Mail-in-a-Box - ManageEngine CloudDNS + ManageEngine CloudDNS Manual Metaname Metaregistrar - mijn.host + mijn.host Mittwald myaddr.{tools,dev,io} MyDNS.jp - MythicBeasts + MythicBeasts Name.com Namecheap Namesilo - NearlyFreeSpeech.NET + NearlyFreeSpeech.NET Netcup Netlify Nicmanager - NIFCloud + NIFCloud Njalla Nodion NS1 - Open Telekom Cloud + Open Telekom Cloud Oracle Cloud OVH plesk.com - Porkbun + Porkbun PowerDNS Rackspace Rain Yun/雨云 - RcodeZero + RcodeZero reg.ru Regfish RFC2136 - RimuHosting + RimuHosting RU CENTER Sakura Cloud Scaleway - Selectel + Selectel Selectel v2 SelfHost.(de|eu) Servercow - Shellrent + Shellrent Simply.com Sonic Spaceship - Stackpath + Stackpath Technitium Tencent Cloud DNS Timeweb Cloud - TransIP + TransIP UKFast SafeDNS Ultradns Variomedia - VegaDNS + VegaDNS Vercel Versio.[nl|eu|uk] VinylDNS - VK Cloud + VK Cloud Volcano Engine/火山引擎 Vscale Vultr - Webnames + Webnames Websupport WEDOS West.cn/西部数码 - Yandex 360 + Yandex 360 Yandex Cloud Yandex PDD Zone.ee + Zonomi + + + diff --git a/cmd/zz_gen_cmd_dnshelp.go b/cmd/zz_gen_cmd_dnshelp.go index 79c768fe2..285e3cd80 100644 --- a/cmd/zz_gen_cmd_dnshelp.go +++ b/cmd/zz_gen_cmd_dnshelp.go @@ -21,6 +21,7 @@ func allDNSCodes() string { "auroradns", "autodns", "axelname", + "azion", "azure", "azuredns", "baiducloud", @@ -346,6 +347,26 @@ func displayDNSHelp(w io.Writer, name string) error { ew.writeln() ew.writeln(`More information: https://go-acme.github.io/lego/dns/axelname`) + case "azion": + // generated from: providers/dns/azion/azion.toml + ew.writeln(`Configuration for Azion.`) + ew.writeln(`Code: 'azion'`) + ew.writeln(`Since: 'v4.24.0'`) + ew.writeln() + + ew.writeln(`Credentials:`) + ew.writeln(` - "AZION_PERSONAL_TOKEN": Your Azion personal token.`) + ew.writeln() + + ew.writeln(`Additional Configuration:`) + ew.writeln(` - "AZION_HTTP_TIMEOUT": API request timeout in seconds (Default: 30)`) + ew.writeln(` - "AZION_POLLING_INTERVAL": Time between DNS propagation check in seconds (Default: 2)`) + ew.writeln(` - "AZION_PROPAGATION_TIMEOUT": Maximum waiting time for DNS propagation in seconds (Default: 60)`) + ew.writeln(` - "AZION_TTL": The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)`) + + ew.writeln() + ew.writeln(`More information: https://go-acme.github.io/lego/dns/azion`) + case "azure": // generated from: providers/dns/azure/azure.toml ew.writeln(`Configuration for Azure (deprecated).`) diff --git a/docs/content/dns/zz_gen_azion.md b/docs/content/dns/zz_gen_azion.md new file mode 100644 index 000000000..be1f5ca17 --- /dev/null +++ b/docs/content/dns/zz_gen_azion.md @@ -0,0 +1,68 @@ +--- +title: "Azion" +date: 2019-03-03T16:39:46+01:00 +draft: false +slug: azion +dnsprovider: + since: "v4.24.0" + code: "azion" + url: "https://www.azion.com/en/products/edge-dns/" +--- + + + + + + +Configuration for [Azion](https://www.azion.com/en/products/edge-dns/). + + + + +- Code: `azion` +- Since: v4.24.0 + + +Here is an example bash command using the Azion provider: + +```bash +AZION_PERSONAL_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxx \ +lego --email you@example.com --dns azion -d '*.example.com' -d example.com run +``` + + + + +## Credentials + +| Environment Variable Name | Description | +|-----------------------|-------------| +| `AZION_PERSONAL_TOKEN` | Your Azion personal token. | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here]({{% ref "dns#configuration-and-credentials" %}}). + + +## Additional Configuration + +| Environment Variable Name | Description | +|--------------------------------|-------------| +| `AZION_HTTP_TIMEOUT` | API request timeout in seconds (Default: 30) | +| `AZION_POLLING_INTERVAL` | Time between DNS propagation check in seconds (Default: 2) | +| `AZION_PROPAGATION_TIMEOUT` | Maximum waiting time for DNS propagation in seconds (Default: 60) | +| `AZION_TTL` | The TTL of the TXT record used for the DNS challenge in seconds (Default: 120) | + +The environment variable names can be suffixed by `_FILE` to reference a file instead of a value. +More information [here]({{% ref "dns#configuration-and-credentials" %}}). + + + + +## More information + +- [API documentation](https://api.azion.com/) +- [Go client](https://github.com/aziontech/azionapi-go-sdk) + + + + diff --git a/docs/data/zz_cli_help.toml b/docs/data/zz_cli_help.toml index 9bebcd31e..726392df5 100644 --- a/docs/data/zz_cli_help.toml +++ b/docs/data/zz_cli_help.toml @@ -150,7 +150,7 @@ To display the documentation for a specific DNS provider, run: $ lego dnshelp -c code Supported DNS providers: - acme-dns, active24, alidns, allinkl, arvancloud, auroradns, autodns, axelname, azure, azuredns, baiducloud, bindman, bluecat, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, conohav3, constellix, corenetworks, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, f5xc, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nicru, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, spaceship, stackpath, technitium, tencentcloud, timewebcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, vscale, vultr, webnames, websupport, wedos, westcn, yandex, yandex360, yandexcloud, zoneee, zonomi + acme-dns, active24, alidns, allinkl, arvancloud, auroradns, autodns, axelname, azion, azure, azuredns, baiducloud, bindman, bluecat, bookmyname, brandit, bunny, checkdomain, civo, clouddns, cloudflare, cloudns, cloudru, cloudxns, conoha, conohav3, constellix, corenetworks, cpanel, derak, desec, designate, digitalocean, directadmin, dnshomede, dnsimple, dnsmadeeasy, dnspod, dode, domeneshop, dreamhost, duckdns, dyn, dyndnsfree, dynu, easydns, edgedns, efficientip, epik, exec, exoscale, f5xc, freemyip, gandi, gandiv5, gcloud, gcore, glesys, godaddy, googledomains, hetzner, hostingde, hosttech, httpnet, httpreq, huaweicloud, hurricane, hyperone, ibmcloud, iij, iijdpf, infoblox, infomaniak, internetbs, inwx, ionos, ipv64, iwantmyname, joker, liara, lightsail, limacity, linode, liquidweb, loopia, luadns, mailinabox, manageengine, manual, metaname, metaregistrar, mijnhost, mittwald, myaddr, mydnsjp, mythicbeasts, namecheap, namedotcom, namesilo, nearlyfreespeech, netcup, netlify, nicmanager, nicru, nifcloud, njalla, nodion, ns1, oraclecloud, otc, ovh, pdns, plesk, porkbun, rackspace, rainyun, rcodezero, regfish, regru, rfc2136, rimuhosting, route53, safedns, sakuracloud, scaleway, selectel, selectelv2, selfhostde, servercow, shellrent, simply, sonic, spaceship, stackpath, technitium, tencentcloud, timewebcloud, transip, ultradns, variomedia, vegadns, vercel, versio, vinyldns, vkcloud, volcengine, vscale, vultr, webnames, websupport, wedos, westcn, yandex, yandex360, yandexcloud, zoneee, zonomi More information: https://go-acme.github.io/lego/dns """ diff --git a/go.mod b/go.mod index e39d268da..bf5a18e1b 100644 --- a/go.mod +++ b/go.mod @@ -24,6 +24,7 @@ require ( github.com/aws/aws-sdk-go-v2/service/route53 v1.50.0 github.com/aws/aws-sdk-go-v2/service/s3 v1.78.2 github.com/aws/aws-sdk-go-v2/service/sts v1.33.17 + github.com/aziontech/azionapi-go-sdk v0.142.0 github.com/baidubce/bce-sdk-go v0.9.223 github.com/cenkalti/backoff/v4 v4.3.0 github.com/civo/civogo v0.3.11 diff --git a/go.sum b/go.sum index 18a3f3616..7ee19cea2 100644 --- a/go.sum +++ b/go.sum @@ -166,6 +166,8 @@ github.com/aws/aws-sdk-go-v2/service/sts v1.33.17/go.mod h1:cQnB8CUnxbMU82JvlqjK github.com/aws/smithy-go v1.8.0/go.mod h1:SObp3lf9smib00L/v3U2eAKG8FyQ7iLrJnQiAmR5n+E= github.com/aws/smithy-go v1.22.2 h1:6D9hW43xKFrRx/tXXfAlIZc4JI+yQe6snnWcQyxSyLQ= github.com/aws/smithy-go v1.22.2/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg= +github.com/aziontech/azionapi-go-sdk v0.142.0 h1:1NOHXlC0/7VgbfbTIGVpsYn1THCugM4/SCOXVdUHQ+A= +github.com/aziontech/azionapi-go-sdk v0.142.0/go.mod h1:cA5DY/VP4X5Eu11LpQNzNn83ziKjja7QVMIl4J45feA= github.com/baidubce/bce-sdk-go v0.9.223 h1:vvDeIemf7ePPP59nLHCntQ/vS++ok2HKbRPgmz1VZKU= github.com/baidubce/bce-sdk-go v0.9.223/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= @@ -1068,6 +1070,7 @@ golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4Iltr golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= diff --git a/providers/dns/azion/azion.go b/providers/dns/azion/azion.go new file mode 100644 index 000000000..5ea9a0c60 --- /dev/null +++ b/providers/dns/azion/azion.go @@ -0,0 +1,309 @@ +// Package azion implements a DNS provider for solving the DNS-01 challenge using Azion Edge DNS. +package azion + +import ( + "context" + "errors" + "fmt" + "net/http" + "sync" + "time" + + "github.com/aziontech/azionapi-go-sdk/idns" + "github.com/go-acme/lego/v4/challenge/dns01" + "github.com/go-acme/lego/v4/platform/config/env" +) + +// Environment variables names. +const ( + envNamespace = "AZION_" + + EnvPersonalToken = envNamespace + "PERSONAL_TOKEN" + + EnvPropagationTimeout = envNamespace + "PROPAGATION_TIMEOUT" + EnvPollingInterval = envNamespace + "POLLING_INTERVAL" + EnvHTTPTimeout = envNamespace + "HTTP_TIMEOUT" + EnvTTL = envNamespace + "TTL" +) + +// Config is used to configure the creation of the DNSProvider. +type Config struct { + PersonalToken string + PropagationTimeout time.Duration + PollingInterval time.Duration + TTL int + HTTPClient *http.Client +} + +// NewDefaultConfig returns a default configuration for the DNSProvider. +func NewDefaultConfig() *Config { + return &Config{ + TTL: env.GetOrDefaultInt(EnvTTL, dns01.DefaultTTL), + PropagationTimeout: env.GetOrDefaultSecond(EnvPropagationTimeout, dns01.DefaultPropagationTimeout), + PollingInterval: env.GetOrDefaultSecond(EnvPollingInterval, dns01.DefaultPollingInterval), + HTTPClient: &http.Client{ + Timeout: env.GetOrDefaultSecond(EnvHTTPTimeout, 30*time.Second), + }, + } +} + +// DNSProvider implements the challenge.Provider interface. +type DNSProvider struct { + config *Config + client *idns.APIClient + + recordIDs map[string]int32 + recordIDsMu sync.Mutex +} + +// NewDNSProvider returns a DNSProvider instance configured for Azion. +// Credentials must be passed in the environment variable: AZION_PERSONAL_TOKEN. +func NewDNSProvider() (*DNSProvider, error) { + values, err := env.Get(EnvPersonalToken) + if err != nil { + return nil, fmt.Errorf("azion: %w", err) + } + + config := NewDefaultConfig() + config.PersonalToken = values[EnvPersonalToken] + + return NewDNSProviderConfig(config) +} + +// NewDNSProviderConfig return a DNSProvider instance configured for Azion. +func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { + if config == nil { + return nil, errors.New("azion: the configuration of the DNS provider is nil") + } + + if config.PersonalToken == "" { + return nil, errors.New("azion: missing credentials") + } + + clientConfig := idns.NewConfiguration() + clientConfig.AddDefaultHeader("Accept", "application/json; version=3") + clientConfig.UserAgent = "lego-dns/azion" + + if config.HTTPClient != nil { + clientConfig.HTTPClient = config.HTTPClient + } + + client := idns.NewAPIClient(clientConfig) + + return &DNSProvider{ + config: config, + client: client, + recordIDs: make(map[string]int32), + }, nil +} + +// Timeout returns the timeout and interval to use when checking for DNS propagation. +func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { + return d.config.PropagationTimeout, d.config.PollingInterval +} + +// Present creates a TXT record using the specified parameters. +func (d *DNSProvider) Present(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + ctxAuth := authContext(context.Background(), d.config.PersonalToken) + + zone, err := d.findZone(ctxAuth, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("azion: could not find zone for domain %q: %w", domain, err) + } + + subDomain, err := extractSubDomain(info, zone) + if err != nil { + return fmt.Errorf("azion: %w", err) + } + + // Check if a TXT record with the same name already exists + existingRecord, err := d.findExistingTXTRecord(ctxAuth, zone.GetId(), subDomain) + if err != nil { + return fmt.Errorf("azion: check existing records: %w", err) + } + + record := idns.NewRecordPostOrPut() + record.SetEntry(subDomain) + record.SetRecordType("TXT") + record.SetTtl(int32(d.config.TTL)) + + var resp *idns.PostOrPutRecordResponse + if existingRecord != nil { + // Update existing record by adding the new value to the existing ones + record.SetAnswersList(append(existingRecord.GetAnswersList(), info.Value)) + + // Use PUT to update the existing record + resp, _, err = d.client.RecordsAPI.PutZoneRecord(ctxAuth, zone.GetId(), existingRecord.GetRecordId()).RecordPostOrPut(*record).Execute() + if err != nil { + return fmt.Errorf("azion: update existing record: %w", err) + } + } else { + // Create a new record + record.SetAnswersList([]string{info.Value}) + + resp, _, err = d.client.RecordsAPI.PostZoneRecord(ctxAuth, zone.GetId()).RecordPostOrPut(*record).Execute() + if err != nil { + return fmt.Errorf("azion: create new zone record: %w", err) + } + } + + if resp == nil || resp.Results == nil { + return errors.New("azion: create zone record error") + } + + results := resp.GetResults() + d.recordIDsMu.Lock() + d.recordIDs[token] = results.GetId() + d.recordIDsMu.Unlock() + + return nil +} + +// CleanUp removes the TXT record matching the specified parameters. +func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { + info := dns01.GetChallengeInfo(domain, keyAuth) + + ctxAuth := authContext(context.Background(), d.config.PersonalToken) + + zone, err := d.findZone(ctxAuth, info.EffectiveFQDN) + if err != nil { + return fmt.Errorf("azion: could not find zone for domain %q: %w", domain, err) + } + + subDomain, err := extractSubDomain(info, zone) + if err != nil { + return fmt.Errorf("azion: %w", err) + } + + defer func() { + // Remove the record ID from our map + d.recordIDsMu.Lock() + delete(d.recordIDs, token) + d.recordIDsMu.Unlock() + }() + + // Find the existing TXT record + existingRecord, err := d.findExistingTXTRecord(ctxAuth, zone.GetId(), subDomain) + if err != nil { + return fmt.Errorf("azion: find existing record: %w", err) + } + + if existingRecord == nil { + return nil + } + + // Get current answers and remove the specific value + currentAnswers := existingRecord.GetAnswersList() + + var updatedAnswers []string + for _, answer := range currentAnswers { + if answer != info.Value { + updatedAnswers = append(updatedAnswers, answer) + } + } + + // If no answers remain, delete the entire record + if len(updatedAnswers) == 0 { + _, resp, errDelete := d.client.RecordsAPI.DeleteZoneRecord(ctxAuth, zone.GetId(), existingRecord.GetRecordId()).Execute() + if errDelete != nil { + // If a record doesn't exist (404), consider cleanup successful + if resp != nil && resp.StatusCode == http.StatusNotFound { + return nil + } + + return fmt.Errorf("azion: delete record: %w", errDelete) + } + + return nil + } + + // Update the record with remaining answers + record := idns.NewRecordPostOrPut() + record.SetEntry(subDomain) + record.SetRecordType("TXT") + record.SetAnswersList(updatedAnswers) + record.SetTtl(existingRecord.GetTtl()) + + _, _, err = d.client.RecordsAPI.PutZoneRecord(ctxAuth, zone.GetId(), existingRecord.GetRecordId()).RecordPostOrPut(*record).Execute() + if err != nil { + return fmt.Errorf("azion: update record: %w", err) + } + + return nil +} + +func (d *DNSProvider) findZone(ctx context.Context, fqdn string) (*idns.Zone, error) { + authZone, err := dns01.FindZoneByFqdn(fqdn) + if err != nil { + return nil, fmt.Errorf("could not find a zone for domain %q: %w", fqdn, err) + } + + resp, _, err := d.client.ZonesAPI.GetZones(ctx).Execute() + if err != nil { + return nil, fmt.Errorf("get zones: %w", err) + } + + if resp == nil { + return nil, errors.New("get zones: no results") + } + + targetZone := dns01.UnFqdn(authZone) + for _, zone := range resp.GetResults() { + if zone.GetName() == targetZone { + return &zone, nil + } + } + + return nil, fmt.Errorf("zone %q not found (fqdn: %q)", authZone, fqdn) +} + +// findExistingTXTRecord searches for an existing TXT record with the given name in the specified zone. +func (d *DNSProvider) findExistingTXTRecord(ctx context.Context, zoneID int32, recordName string) (*idns.RecordGet, error) { + resp, _, err := d.client.RecordsAPI.GetZoneRecords(ctx, zoneID).Execute() + if err != nil { + return nil, fmt.Errorf("get zone records: %w", err) + } + + if resp == nil { + return nil, errors.New("get zone records: no results") + } + + results, ok := resp.GetResultsOk() + if !ok || results == nil { + return nil, errors.New("get zone records: empty") + } + + // Search for existing TXT record with the same name + for _, record := range results.GetRecords() { + if record.GetRecordType() == "TXT" && record.GetEntry() == recordName { + return &record, nil + } + } + + // No existing record found + return nil, nil +} + +func authContext(ctx context.Context, key string) context.Context { + return context.WithValue(ctx, idns.ContextAPIKeys, map[string]idns.APIKey{ + "tokenAuth": { + Key: key, + Prefix: "Token", + }, + }) +} + +func extractSubDomain(info dns01.ChallengeInfo, zone *idns.Zone) (string, error) { + subDomain, err := dns01.ExtractSubDomain(info.EffectiveFQDN, zone.GetName()) + if err != nil { + return "", err + } + + if subDomain != "" { + return subDomain, nil + } + + return "@", nil +} diff --git a/providers/dns/azion/azion.toml b/providers/dns/azion/azion.toml new file mode 100644 index 000000000..c2ba510f2 --- /dev/null +++ b/providers/dns/azion/azion.toml @@ -0,0 +1,23 @@ +Name = "Azion" +Description = '''''' +Code = "azion" +Since = "v4.24.0" +URL = "https://www.azion.com/en/products/edge-dns/" + +Example = ''' +AZION_PERSONAL_TOKEN=xxxxxxxxxxxxxxxxxxxxxxxxxx \ +lego --email you@example.com --dns azion -d '*.example.com' -d example.com run +''' + +[Configuration] + [Configuration.Credentials] + AZION_PERSONAL_TOKEN = "Your Azion personal token." + [Configuration.Additional] + AZION_POLLING_INTERVAL = "Time between DNS propagation check in seconds (Default: 2)" + AZION_PROPAGATION_TIMEOUT = "Maximum waiting time for DNS propagation in seconds (Default: 60)" + AZION_TTL = "The TTL of the TXT record used for the DNS challenge in seconds (Default: 120)" + AZION_HTTP_TIMEOUT = "API request timeout in seconds (Default: 30)" + +[Links] + API = "https://api.azion.com/" + GoClient = "https://github.com/aziontech/azionapi-go-sdk" diff --git a/providers/dns/azion/azion_test.go b/providers/dns/azion/azion_test.go new file mode 100644 index 000000000..e96efb56e --- /dev/null +++ b/providers/dns/azion/azion_test.go @@ -0,0 +1,115 @@ +package azion + +import ( + "testing" + + "github.com/go-acme/lego/v4/platform/tester" + "github.com/stretchr/testify/require" +) + +const envDomain = envNamespace + "DOMAIN" + +var envTest = tester.NewEnvTest(EnvPersonalToken).WithDomain(envDomain) + +func TestNewDNSProvider(t *testing.T) { + testCases := []struct { + desc string + envVars map[string]string + expected string + }{ + { + desc: "success", + envVars: map[string]string{ + EnvPersonalToken: "token", + }, + }, + { + desc: "missing credentials", + envVars: map[string]string{ + EnvPersonalToken: "", + }, + expected: "azion: some credentials information are missing: AZION_PERSONAL_TOKEN", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + defer envTest.RestoreEnv() + envTest.ClearEnv() + + envTest.Apply(test.envVars) + + p, err := NewDNSProvider() + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestNewDNSProviderConfig(t *testing.T) { + testCases := []struct { + desc string + token string + expected string + }{ + { + desc: "success", + token: "token", + }, + { + desc: "missing credentials", + expected: "azion: missing credentials", + }, + } + + for _, test := range testCases { + t.Run(test.desc, func(t *testing.T) { + config := NewDefaultConfig() + config.PersonalToken = test.token + + p, err := NewDNSProviderConfig(config) + + if test.expected == "" { + require.NoError(t, err) + require.NotNil(t, p) + require.NotNil(t, p.config) + require.NotNil(t, p.client) + } else { + require.EqualError(t, err, test.expected) + } + }) + } +} + +func TestLivePresent(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.Present(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} + +func TestLiveCleanUp(t *testing.T) { + if !envTest.IsLiveTest() { + t.Skip("skipping live test") + } + + envTest.RestoreEnv() + provider, err := NewDNSProvider() + require.NoError(t, err) + + err = provider.CleanUp(envTest.GetDomain(), "", "123d==") + require.NoError(t, err) +} diff --git a/providers/dns/zz_gen_dns_providers.go b/providers/dns/zz_gen_dns_providers.go index ef9dcba28..5eee04faf 100644 --- a/providers/dns/zz_gen_dns_providers.go +++ b/providers/dns/zz_gen_dns_providers.go @@ -15,6 +15,7 @@ import ( "github.com/go-acme/lego/v4/providers/dns/auroradns" "github.com/go-acme/lego/v4/providers/dns/autodns" "github.com/go-acme/lego/v4/providers/dns/axelname" + "github.com/go-acme/lego/v4/providers/dns/azion" "github.com/go-acme/lego/v4/providers/dns/azure" "github.com/go-acme/lego/v4/providers/dns/azuredns" "github.com/go-acme/lego/v4/providers/dns/baiducloud" @@ -185,6 +186,8 @@ func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { return autodns.NewDNSProvider() case "axelname": return axelname.NewDNSProvider() + case "azion": + return azion.NewDNSProvider() case "azure": return azure.NewDNSProvider() case "azuredns":