From ac26e370568358d7a387cf38147b9022d92399b3 Mon Sep 17 00:00:00 2001 From: xhess Date: Fri, 30 Oct 2026 12:18:28 +0100 Subject: [PATCH] Add opt-in records endpoint with CNAME and SRV support Adds POST /records/present and /records/cleanup taking JSON fqdn, type and value for A, AAAA, TXT, CNAME and SRV records. CNAME/SRV targets are validated and made absolute. SRV records are added to an existing RRSet instead of replacing it, so several targets can share one name. The endpoint group is not enabled by default. Co-Authored-By: Claude Opus 5.5 Signed-off-by: xhess --- README.md | 5 +- pkg/app/app.go | 6 + pkg/config/config.go | 7 + pkg/config/config_test.go | 29 ++++ pkg/hetzner/hcloud.go | 4 +- pkg/middleware/bind.go | 120 ++++++++++++++ pkg/middleware/bind_test.go | 64 ++++++++ pkg/middleware/update/cloud/cloud.go | 62 ++++++-- tests/libcloudapi/libcloudapi.go | 47 ++++++ tests/libserver/consts.go | 10 ++ tests/libserver/libserver.go | 10 +- tests/records_test.go | 224 +++++++++++++++++++++++++++ 12 files changed, 572 insertions(+), 16 deletions(-) create mode 100644 tests/records_test.go diff --git a/README.md b/README.md index f2f84c0..39bb409 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ Get the container image from [ghcr.io](https://github.com/0xFelix/hetzner-dnsapi | API | Endpoint | |--------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | lego HTTP request | POST `/httpreq/present`
POST `/httpreq/cleanup`
(see https://go-acme.github.io/lego/dns/httpreq/) | +| Generic records | POST `/records/present`
POST `/records/cleanup`
(JSON body `fqdn`, `type` (A, AAAA, TXT, CNAME or SRV) and `value`; SRV values are `priority weight port target` and are added to existing SRV records of the same name, all other types replace existing records; CNAME/SRV targets are made absolute; opt-in, see [Enabled endpoints](#enabled-endpoints)) | | ACMEDNS | POST `/acmedns/update`
(see https://github.com/joohoi/acme-dns#update-endpoint) | | DirectAdmin Legacy | GET `/directadmin/CMD_API_SHOW_DOMAINS`
GET `/directadmin/CMD_API_DNS_CONTROL` (only adding A/AAAA/TXT records, everything else always returns `200 OK`)
GET `/directadmin/CMD_API_DOMAIN_POINTER` (only a stub, always returns `200 OK`)
(see https://docs.directadmin.com/developer/api/legacy-api.html and https://www.directadmin.com/features.php?id=504) | | plain HTTP | GET `/plain/update` (query params `hostname` and `ip` (can be ipv4 for A or ipv6 for AAAA records), if auth method is `users` then HTTP Basic auth is used)
| @@ -98,6 +99,8 @@ active by listing only the ones you want: - `acmedns` - `/acmedns/update` - `httpreq` - `/httpreq/present`, `/httpreq/cleanup` - `directadmin` - `/directadmin/CMD_API_*` +- `records` - `/records/present`, `/records/cleanup` (supports CNAME and SRV, + **not** enabled by default, must be listed explicitly) Via config file set the `endpoints` key; via environment variable set `ENDPOINTS` to a comma-separated list (e.g. `ENDPOINTS=plain,nic`). Listing @@ -166,5 +169,5 @@ debug: false | `LOCKOUT_MAX_ATTEMPTS` | int | Failures before lockout | N | `10` | | `LOCKOUT_DURATION_SECONDS` | int | Lockout duration in seconds | N | `3600` | | `LOCKOUT_WINDOW_SECONDS` | int | Window in seconds during which consecutive failures accumulate | N | `900` | -| `ENDPOINTS` | string | Comma-separated list of endpoint groups to enable: `plain`, `nic`, `acmedns`, `httpreq`, `directadmin`. All enabled when unset. | N | All enabled | +| `ENDPOINTS` | string | Comma-separated list of endpoint groups to enable: `plain`, `nic`, `acmedns`, `httpreq`, `directadmin`, `records`. All but `records` enabled when unset. | N | All but `records` | | `DEBUG` | bool | Output debug logs of received requests | N | `false` | diff --git a/pkg/app/app.go b/pkg/app/app.go index a5b042d..b931222 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -63,6 +63,12 @@ func New(cfg *config.Config) http.Handler { mux.Handle("POST /httpreq/cleanup", handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindHTTPReq, authorizer, cleaner, middleware.StatusOk)) } + if cfg.Endpoints.Records { + mux.Handle("POST /records/present", + handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindRecords, authorizer, updater, middleware.StatusOk)) + mux.Handle("POST /records/cleanup", + handle(cfg, rl, middleware.ContentTypeJSON, middleware.BindRecords, authorizer, cleaner, middleware.StatusOk)) + } if cfg.Endpoints.DirectAdmin { mux.Handle("GET /directadmin/CMD_API_SHOW_DOMAINS", handle(cfg, rl, middleware.NewShowDomainsDirectAdmin(cfg, lockout))) diff --git a/pkg/config/config.go b/pkg/config/config.go index 5bad855..7632811 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -77,6 +77,7 @@ type Endpoints struct { AcmeDNS bool `yaml:"acmedns"` HTTPReq bool `yaml:"httpreq"` DirectAdmin bool `yaml:"directadmin"` + Records bool `yaml:"records"` } func (e *Endpoints) Enabled() []string { @@ -96,6 +97,9 @@ func (e *Endpoints) Enabled() []string { if e.DirectAdmin { names = append(names, EndpointDirectAdmin) } + if e.Records { + names = append(names, EndpointRecords) + } return names } @@ -121,6 +125,7 @@ const ( EndpointAcmeDNS = "acmedns" EndpointHTTPReq = "httpreq" EndpointDirectAdmin = "directadmin" + EndpointRecords = "records" ) const ( @@ -298,6 +303,8 @@ func envEndpoints(endpoints *Endpoints) error { endpoints.HTTPReq = true case EndpointDirectAdmin: endpoints.DirectAdmin = true + case EndpointRecords: + endpoints.Records = true default: return fmt.Errorf("invalid endpoint %q in ENDPOINTS", name) } diff --git a/pkg/config/config_test.go b/pkg/config/config_test.go index 29c81e6..14a5fea 100644 --- a/pkg/config/config_test.go +++ b/pkg/config/config_test.go @@ -127,6 +127,7 @@ var _ = Describe("Config", func() { envDebug = "DEBUG" envRateLimitRPS = "RATE_LIMIT_RPS" envLockoutMaxAtt = "LOCKOUT_MAX_ATTEMPTS" + envEndpoints = "ENDPOINTS" ) BeforeEach(func() { @@ -146,6 +147,7 @@ var _ = Describe("Config", func() { Expect(os.Unsetenv(envDebug)).To(Succeed()) Expect(os.Unsetenv(envRateLimitRPS)).To(Succeed()) Expect(os.Unsetenv(envLockoutMaxAtt)).To(Succeed()) + Expect(os.Unsetenv(envEndpoints)).To(Succeed()) }) It("should parse environment successfully", func() { @@ -187,6 +189,28 @@ var _ = Describe("Config", func() { })) }) + It("should enable all endpoints but records when ENDPOINTS is unset", func() { + Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed()) + Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed()) + + cfg, err := config.ParseEnv() + Expect(err).ToNot(HaveOccurred()) + Expect(cfg.Endpoints).To(Equal(config.Endpoints{ + Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true, + })) + }) + + It("should enable only the endpoints listed in ENDPOINTS", func() { + Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed()) + Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed()) + Expect(os.Setenv(envEndpoints, "plain, records")).To(Succeed()) + + cfg, err := config.ParseEnv() + Expect(err).ToNot(HaveOccurred()) + Expect(cfg.Endpoints).To(Equal(config.Endpoints{Plain: true, Records: true})) + Expect(cfg.Endpoints.Enabled()).To(Equal([]string{config.EndpointPlain, config.EndpointRecords})) + }) + It("should lowercase domains of ALLOWED_DOMAINS", func() { Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed()) Expect(os.Setenv(envAllowedDomains, "Example.COM,127.0.0.1/32")).To(Succeed()) @@ -243,6 +267,11 @@ var _ = Describe("Config", func() { Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed()) Expect(os.Setenv(envLockoutMaxAtt, "0")).To(Succeed()) }, "lockout.maxAttempts must be > 0"), + Entry("ENDPOINTS contains an unknown endpoint", func() { + Expect(os.Setenv(envAPIToken, apiToken)).To(Succeed()) + Expect(os.Setenv(envAllowedDomains, allowedDomainsStr)).To(Succeed()) + Expect(os.Setenv(envEndpoints, "plain,unknown")).To(Succeed()) + }, `invalid endpoint "unknown" in ENDPOINTS`), ) }) diff --git a/pkg/hetzner/hcloud.go b/pkg/hetzner/hcloud.go index 9be62ff..1c85425 100644 --- a/pkg/hetzner/hcloud.go +++ b/pkg/hetzner/hcloud.go @@ -51,10 +51,11 @@ func RRSetTypeFromString(rType string) (hcloud.ZoneRRSetType, error) { switch rrType := hcloud.ZoneRRSetType(rType); rrType { case hcloud.ZoneRRSetTypeA, hcloud.ZoneRRSetTypeAAAA, + hcloud.ZoneRRSetTypeCNAME, + hcloud.ZoneRRSetTypeSRV, hcloud.ZoneRRSetTypeTXT: return rrType, nil case hcloud.ZoneRRSetTypeCAA, - hcloud.ZoneRRSetTypeCNAME, hcloud.ZoneRRSetTypeDS, hcloud.ZoneRRSetTypeHINFO, hcloud.ZoneRRSetTypeHTTPS, @@ -63,7 +64,6 @@ func RRSetTypeFromString(rType string) (hcloud.ZoneRRSetType, error) { hcloud.ZoneRRSetTypePTR, hcloud.ZoneRRSetTypeRP, hcloud.ZoneRRSetTypeSOA, - hcloud.ZoneRRSetTypeSRV, hcloud.ZoneRRSetTypeSVCB, hcloud.ZoneRRSetTypeTLSA: return "", fmt.Errorf("unsupported resource record set type %s", rrType) diff --git a/pkg/middleware/bind.go b/pkg/middleware/bind.go index baefeef..a088342 100644 --- a/pkg/middleware/bind.go +++ b/pkg/middleware/bind.go @@ -7,6 +7,8 @@ import ( "log" "net/http" "net/netip" + "regexp" + "strconv" "strings" "golang.org/x/net/publicsuffix" @@ -18,10 +20,16 @@ const ( recordTypeA = "A" recordTypeAAAA = "AAAA" recordTypeTXT = "TXT" + recordTypeCNAME = "CNAME" + recordTypeSRV = "SRV" failedParseRequestFmt = "failed to parse request: %v" maxRequestBodySize = 1 << 10 // 1 KB + maxHostnameLength = 253 + srvFieldCount = 4 ) +var hostnameRegexp = regexp.MustCompile(`^([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?\.)*[a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?$`) + func BindPlain(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize) @@ -180,6 +188,67 @@ func BindHTTPReq(next http.Handler) http.Handler { }) } +// BindRecords binds requests of the generic records endpoint, which in +// addition to A, AAAA and TXT also supports CNAME and SRV records. +func BindRecords(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize) + d := &struct { + FQDN string `json:"fqdn"` + Type string `json:"type"` + Value string `json:"value"` + }{} + if err := json.UnmarshalRead(r.Body, d); err != nil { + log.Printf(failedParseRequestFmt, err) + w.WriteHeader(http.StatusBadRequest) + return + } + + if d.FQDN == "" || d.Type == "" || d.Value == "" { + http.Error(w, "fqdn, type or value is missing", http.StatusBadRequest) + return + } + + recordType := strings.ToUpper(d.Type) + fqdn := NormalizeFQDN(d.FQDN) + name, zone, err := SplitFQDN(fqdn) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + if recordType == recordTypeCNAME && name == "" { + http.Error(w, "a CNAME record is not allowed at the zone apex", http.StatusBadRequest) + return + } + + value, err := normalizeRecordValue(d.Value, recordType) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + username, password, _ := r.BasicAuth() + next.ServeHTTP( + w, r.WithContext( + data.NewContextWithReqData( + r.Context(), + &data.ReqData{ + FullName: fqdn, + Name: name, + Zone: zone, + Value: value, + Type: recordType, + Username: username, + Password: password, + BasicAuth: true, + }, + ), + ), + ) + }) +} + func BindDirectAdmin(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize) @@ -262,6 +331,57 @@ func validateValue(value, recordType string) error { return nil } +// normalizeRecordValue validates the value for the given record type and +// returns it in the form expected by the API. Hostnames in CNAME and SRV +// values are made absolute by appending a trailing dot. +func normalizeRecordValue(value, recordType string) (string, error) { + switch recordType { + case recordTypeA, recordTypeAAAA: + return value, validateValue(value, recordType) + case recordTypeTXT: + return value, nil + case recordTypeCNAME: + target, err := normalizeHostname(value) + if err != nil { + return "", err + } + return target + ".", nil + case recordTypeSRV: + // priority weight port target + fields := strings.Fields(value) + if len(fields) != srvFieldCount { + return "", errors.New("srv value must be 'priority weight port target'") + } + for i, f := range fields[:srvFieldCount-1] { + n, err := strconv.ParseUint(f, 10, 16) + if err != nil { + return "", errors.New("srv priority, weight and port must be numbers between 0 and 65535") + } + // Canonicalize, e.g. strip leading zeros, so values compare equal + fields[i] = strconv.FormatUint(n, 10) + } + // A target of '.' means that the service is not available. + if fields[srvFieldCount-1] != "." { + target, err := normalizeHostname(fields[srvFieldCount-1]) + if err != nil { + return "", err + } + fields[srvFieldCount-1] = target + "." + } + return strings.Join(fields, " "), nil + default: + return "", errors.New("type can only be A, AAAA, TXT, CNAME or SRV") + } +} + +func normalizeHostname(host string) (string, error) { + host = NormalizeFQDN(host) + if len(host) > maxHostnameLength || !hostnameRegexp.MatchString(host) { + return "", errors.New("invalid hostname") + } + return host, nil +} + // NormalizeFQDN strips trailing dots and lowercases the name, so that // comparisons against configured domains are case-insensitive. func NormalizeFQDN(fqdn string) string { diff --git a/pkg/middleware/bind_test.go b/pkg/middleware/bind_test.go index 3306191..1a8943d 100644 --- a/pkg/middleware/bind_test.go +++ b/pkg/middleware/bind_test.go @@ -152,6 +152,70 @@ var _ = Describe("Binding of names", func() { Entry("trailing dot", "example.com.", "sub"), Entry("upper case", "Example.COM", "SUB"), ) + + DescribeTable( + "should bind records requests", func(fqdn, recordType, value, expectedName, expectedType, expectedValue string) { + reqData, code := bind(middleware.BindRecords, newJSONRequest( + `{"fqdn":"`+fqdn+`","type":"`+recordType+`","value":"`+value+`"}`, + )) + Expect(code).To(Equal(http.StatusOK)) + Expect(reqData.Name).To(Equal(expectedName)) + Expect(reqData.Zone).To(Equal("example.com")) + Expect(reqData.Type).To(Equal(expectedType)) + Expect(reqData.Value).To(Equal(expectedValue)) + }, + Entry("A", "sub.example.com", "A", "127.0.0.1", "sub", "A", "127.0.0.1"), + Entry("AAAA", "sub.example.com", "AAAA", "::1", "sub", "AAAA", "::1"), + Entry("TXT at the zone apex", "example.com", "TXT", "some text", "", "TXT", "some text"), + Entry("lower case type", "sub.example.com", "cname", "target.example.com", "sub", "CNAME", "target.example.com."), + Entry("CNAME", "sub.example.com", "CNAME", "target.example.com", "sub", "CNAME", "target.example.com."), + Entry( + "CNAME with absolute upper case target", "SUB.example.com.", "CNAME", "Target.Example.COM.", + "sub", "CNAME", "target.example.com.", + ), + Entry("CNAME with underscore", "sub.example.com", "CNAME", "_dkim.example.com", "sub", "CNAME", "_dkim.example.com."), + Entry("SRV", "_sip._tcp.example.com", "SRV", "10 5 5060 sip.example.com", "_sip._tcp", "SRV", "10 5 5060 sip.example.com."), + Entry( + "SRV with extra whitespace", "_sip._tcp.example.com", "SRV", ` 10 5 5060\tSIP.example.com. `, + "_sip._tcp", "SRV", "10 5 5060 sip.example.com.", + ), + Entry( + "SRV with maximum values", "_sip._tcp.example.com", "SRV", "65535 65535 65535 sip.example.com", + "_sip._tcp", "SRV", "65535 65535 65535 sip.example.com.", + ), + Entry( + "SRV with leading zeros", "_sip._tcp.example.com", "SRV", "00 05 05060 sip.example.com", + "_sip._tcp", "SRV", "0 5 5060 sip.example.com.", + ), + Entry("SRV with unavailable service", "_sip._tcp.example.com", "SRV", "0 0 0 .", "_sip._tcp", "SRV", "0 0 0 ."), + ) + + DescribeTable( + "should reject invalid records requests", func(body string) { + reqData, code := bind(middleware.BindRecords, newJSONRequest(body)) + Expect(code).To(Equal(http.StatusBadRequest)) + Expect(reqData).To(BeNil()) + }, + Entry("missing fqdn", `{"type":"A","value":"127.0.0.1"}`), + Entry("missing type", `{"fqdn":"sub.example.com","value":"127.0.0.1"}`), + Entry("missing value", `{"fqdn":"sub.example.com","type":"A"}`), + Entry("unsupported type", `{"fqdn":"sub.example.com","type":"MX","value":"10 mx.example.com"}`), + Entry("invalid fqdn", `{"fqdn":"com","type":"A","value":"127.0.0.1"}`), + Entry("A with ipv6 address", `{"fqdn":"sub.example.com","type":"A","value":"::1"}`), + Entry("AAAA with ipv4 address", `{"fqdn":"sub.example.com","type":"AAAA","value":"127.0.0.1"}`), + Entry("CNAME at the zone apex", `{"fqdn":"example.com","type":"CNAME","value":"target.example.com"}`), + Entry("CNAME with space in target", `{"fqdn":"sub.example.com","type":"CNAME","value":"a b.example.com"}`), + Entry("CNAME with empty label", `{"fqdn":"sub.example.com","type":"CNAME","value":"a..example.com"}`), + Entry("CNAME with leading hyphen", `{"fqdn":"sub.example.com","type":"CNAME","value":"-a.example.com"}`), + Entry("CNAME with too long label", `{"fqdn":"sub.example.com","type":"CNAME","value":"`+strings.Repeat("a", 64)+`.example.com"}`), + Entry("CNAME with too long target", `{"fqdn":"sub.example.com","type":"CNAME","value":"`+strings.Repeat("a.", 127)+`com"}`), + Entry("SRV with too few fields", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 sip.example.com"}`), + Entry("SRV with too many fields", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 5060 sip.example.com x"}`), + Entry("SRV with negative priority", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"-1 5 5060 sip.example.com"}`), + Entry("SRV with non-numeric weight", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 x 5060 sip.example.com"}`), + Entry("SRV with port out of range", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 65536 sip.example.com"}`), + Entry("SRV with invalid target", `{"fqdn":"_sip._tcp.example.com","type":"SRV","value":"10 5 5060 sip..example.com"}`), + ) }) var _ = Describe("JSON binding", func() { diff --git a/pkg/middleware/update/cloud/cloud.go b/pkg/middleware/update/cloud/cloud.go index a7978c9..8064ab7 100644 --- a/pkg/middleware/update/cloud/cloud.go +++ b/pkg/middleware/update/cloud/cloud.go @@ -2,6 +2,7 @@ package cloud import ( "context" + "strings" "github.com/hetznercloud/hcloud-go/v2/hcloud" @@ -40,24 +41,37 @@ func (u *updater) Update(ctx context.Context, reqData *data.ReqData) error { } if rrSet != nil { + // SRV records are commonly spread over several records with the + // same name, so they are added to the RRSet instead of replacing it. + if rrSetType == hcloud.ZoneRRSetTypeSRV { + return u.addRecord(ctx, rrSet, reqData.Value) + } return u.updateRRSet(ctx, rrSet, reqData.Value) } return u.createRRSet(ctx, zone, rrSetType, name, reqData.Value) } +func (u *updater) changeTTL(ctx context.Context, rrSet *hcloud.ZoneRRSet) error { + if rrSet.TTL != nil && *rrSet.TTL == u.cfg.RecordTTL { + return nil + } + + opts := hcloud.ZoneRRSetChangeTTLOpts{TTL: &u.cfg.RecordTTL} + action, _, err := u.client.Zone.ChangeRRSetTTL(ctx, rrSet, opts) + if err != nil { + return err + } + if action != nil { + return u.client.Action.WaitFor(ctx, action) + } + + return nil +} + func (u *updater) updateRRSet(ctx context.Context, rrSet *hcloud.ZoneRRSet, val string) error { - if rrSet.TTL == nil || *rrSet.TTL != u.cfg.RecordTTL { - opts := hcloud.ZoneRRSetChangeTTLOpts{TTL: &u.cfg.RecordTTL} - action, _, err := u.client.Zone.ChangeRRSetTTL(ctx, rrSet, opts) - if err != nil { - return err - } - if action != nil { - if err := u.client.Action.WaitFor(ctx, action); err != nil { - return err - } - } + if err := u.changeTTL(ctx, rrSet); err != nil { + return err } opts := hcloud.ZoneRRSetSetRecordsOpts{ @@ -76,6 +90,32 @@ func (u *updater) updateRRSet(ctx context.Context, rrSet *hcloud.ZoneRRSet, val return nil } +func (u *updater) addRecord(ctx context.Context, rrSet *hcloud.ZoneRRSet, val string) error { + if err := u.changeTTL(ctx, rrSet); err != nil { + return err + } + + val = hetzner.QuoteIfRequired(val, rrSet.Type) + for _, record := range rrSet.Records { + if strings.EqualFold(record.Value, val) { + return nil + } + } + + opts := hcloud.ZoneRRSetAddRecordsOpts{ + Records: []hcloud.ZoneRRSetRecord{{Value: val}}, + } + action, _, err := u.client.Zone.AddRRSetRecords(ctx, rrSet, opts) + if err != nil { + return err + } + if action != nil { + return u.client.Action.WaitFor(ctx, action) + } + + return nil +} + func (u *updater) createRRSet(ctx context.Context, zone *hcloud.Zone, rrSetType hcloud.ZoneRRSetType, name, val string) error { opts := hcloud.ZoneRRSetCreateOpts{ Name: name, diff --git a/tests/libcloudapi/libcloudapi.go b/tests/libcloudapi/libcloudapi.go index bf04d5b..911d4ec 100644 --- a/tests/libcloudapi/libcloudapi.go +++ b/tests/libcloudapi/libcloudapi.go @@ -176,6 +176,40 @@ func UpdatedRRSetTXT() schema.ZoneRRSet { return r } +func NewRRSetCNAME() schema.ZoneRRSet { + return schema.ZoneRRSet{ + Name: libserver.CNAMERecordName, + Type: libserver.RecordTypeCNAME, + TTL: new(libserver.DefaultTTL), + Records: []schema.ZoneRRSetRecord{{Value: libserver.CNAMETarget}}, + Zone: mustParseInt(libserver.ZoneID), + } +} + +func NewRRSetSRV() schema.ZoneRRSet { + return schema.ZoneRRSet{ + Name: libserver.SRVRecordName, + Type: libserver.RecordTypeSRV, + TTL: new(libserver.DefaultTTL), + Records: []schema.ZoneRRSetRecord{{Value: libserver.SRVValue}}, + Zone: mustParseInt(libserver.ZoneID), + } +} + +func ExistingRRSetCNAME() schema.ZoneRRSet { + r := NewRRSetCNAME() + r.ID = libserver.CNAMERecordName + "/" + libserver.RecordTypeCNAME + r.Records = []schema.ZoneRRSetRecord{{Value: libserver.CNAMEExisting}} + return r +} + +func ExistingRRSetSRV() schema.ZoneRRSet { + r := NewRRSetSRV() + r.ID = libserver.SRVRecordName + "/" + libserver.RecordTypeSRV + r.Records = []schema.ZoneRRSetRecord{{Value: libserver.SRVExisting}} + return r +} + func GetZone(token string, zone schema.Zone) http.HandlerFunc { return ghttp.CombineHandlers( ghttp.VerifyRequest(http.MethodGet, "/v1/zones/"+zone.Name), @@ -256,6 +290,19 @@ func SetRRSetRecords(token string, zone schema.Zone, rrSet schema.ZoneRRSet) htt ) } +func AddRRSetRecords(token string, zone schema.Zone, rrSet schema.ZoneRRSet, records []schema.ZoneRRSetRecord) http.HandlerFunc { + return ghttp.CombineHandlers( + ghttp.VerifyRequest(http.MethodPost, fmt.Sprintf("/v1/zones/%d/rrsets/%s/%s/actions/add_records", zone.ID, rrSet.Name, rrSet.Type)), + ghttp.VerifyHeader(http.Header{ + headerAuthorization: []string{authBearerPrefix + token}, + }), + ghttp.VerifyJSONRepresenting(schema.ZoneRRSetAddRecordsRequest{ + Records: records, + }), + getResponseSuccess(), + ) +} + func RemoveRRSetRecords(token string, zone schema.Zone, rrSet schema.ZoneRRSet, records []schema.ZoneRRSetRecord) http.HandlerFunc { return ghttp.CombineHandlers( ghttp.VerifyRequest(http.MethodPost, fmt.Sprintf("/v1/zones/%d/rrsets/%s/%s/actions/remove_records", zone.ID, rrSet.Name, rrSet.Type)), diff --git a/tests/libserver/consts.go b/tests/libserver/consts.go index 46bf7f4..30ef096 100644 --- a/tests/libserver/consts.go +++ b/tests/libserver/consts.go @@ -11,6 +11,16 @@ const ( TXTRecordNameNoPrefix = "txtsub.test.tld" TXTRecordName = "_acme-challenge.txtsub" TXTRecordNameFull = "_acme-challenge.txtsub.test.tld" + CNAMERecordName = "cnamesub" + CNAMERecordNameFull = "cnamesub.test.tld" + CNAMETarget = "target.test.tld." + CNAMEExisting = "old.test.tld." + SRVExisting = "10 5 25567 mc2.test.tld." + SRVRecordName = "_minecraft._tcp.survival" + SRVRecordNameFull = "_minecraft._tcp.survival.test.tld" + SRVValue = "0 5 25567 mc.test.tld." + RecordTypeCNAME = "CNAME" + RecordTypeSRV = "SRV" DefaultTTL = 60 AExisting = "127.0.0.1" AUpdated = "1.2.3.4" diff --git a/tests/libserver/libserver.go b/tests/libserver/libserver.go index b33684b..7bc208e 100644 --- a/tests/libserver/libserver.go +++ b/tests/libserver/libserver.go @@ -10,6 +10,12 @@ import ( ) func New(url string, ttl int) (server *httptest.Server, token, username, password string) { + return NewWithEndpoints(url, ttl, config.Endpoints{ + Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true, Records: true, + }) +} + +func NewWithEndpoints(url string, ttl int, endpoints config.Endpoints) (server *httptest.Server, token, username, password string) { token = rand.Text() username = rand.Text() password = rand.Text() @@ -29,7 +35,7 @@ func New(url string, ttl int) (server *httptest.Server, token, username, passwor Domains: []string{"*"}, }}, }, - Endpoints: config.Endpoints{Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true}, + Endpoints: endpoints, RecordTTL: ttl, RateLimit: config.RateLimit{RPS: 1000, Burst: 1000, IdleSeconds: 600}, Lockout: config.Lockout{MaxAttempts: 1000, DurationSeconds: 3600, WindowSeconds: 900}, @@ -44,7 +50,7 @@ func NewNoAllowedDomains(url string) *httptest.Server { Auth: config.Auth{ Method: config.AuthMethodAllowedDomains, }, - Endpoints: config.Endpoints{Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true}, + Endpoints: config.Endpoints{Plain: true, Nic: true, AcmeDNS: true, HTTPReq: true, DirectAdmin: true, Records: true}, RateLimit: config.RateLimit{RPS: 1000, Burst: 1000, IdleSeconds: 600}, Lockout: config.Lockout{MaxAttempts: 1000, DurationSeconds: 3600, WindowSeconds: 900}, } diff --git a/tests/records_test.go b/tests/records_test.go new file mode 100644 index 0000000..9202395 --- /dev/null +++ b/tests/records_test.go @@ -0,0 +1,224 @@ +package tests + +import ( + "bytes" + "context" + "encoding/json/v2" + "net/http" + "net/http/httptest" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" + "github.com/onsi/gomega/ghttp" + + "github.com/hetznercloud/hcloud-go/v2/hcloud/schema" + + "github.com/0xfelix/hetzner-dnsapi-proxy/pkg/config" + "github.com/0xfelix/hetzner-dnsapi-proxy/tests/libcloudapi" + "github.com/0xfelix/hetzner-dnsapi-proxy/tests/libserver" +) + +const ( + typeCNAME = "CNAME" + typeSRV = "SRV" + otherHost = "a.test.tld" + srvInput = "0 5 25567 mc.test.tld" +) + +func rec(fqdn, typ, value string) map[string]string { + return map[string]string{keyFQDN: fqdn, "type": typ, keyValue: value} +} + +var _ = Describe("Records", func() { + var ( + api *ghttp.Server + server *httptest.Server + token string + username string + password string + ) + + BeforeEach(func() { + api = ghttp.NewServer() + server, token, username, password = libserver.New(api.URL(), libserver.DefaultTTL) + }) + + AfterEach(func() { + server.Close() + api.Close() + }) + + Context("should succeed", func() { + DescribeTable( + "creating a new record", func(ctx context.Context, rrSet schema.ZoneRRSet, fqdn, value string) { + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), rrSet, false), + libcloudapi.CreateRRSet(token, libcloudapi.Zone(), rrSet), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/present", username, password, + rec(fqdn, rrSet.Type, value), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(3)) + }, + Entry("CNAME", libcloudapi.NewRRSetCNAME(), libserver.CNAMERecordNameFull, "target.test.tld"), + Entry("CNAME with dot suffix", libcloudapi.NewRRSetCNAME(), libserver.CNAMERecordNameFull+".", "target.test.tld."), + Entry("SRV", libcloudapi.NewRRSetSRV(), libserver.SRVRecordNameFull, srvInput), + Entry("SRV with dot suffix", libcloudapi.NewRRSetSRV(), libserver.SRVRecordNameFull+".", "0 5 25567 MC.test.tld."), + ) + + It("replacing an existing CNAME record", func(ctx context.Context) { + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), libcloudapi.ExistingRRSetCNAME(), true), + libcloudapi.SetRRSetRecords(token, libcloudapi.Zone(), libcloudapi.NewRRSetCNAME()), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/present", username, password, + rec(libserver.CNAMERecordNameFull, typeCNAME, "target.test.tld"), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(3)) + }) + + DescribeTable( + "adding a SRV record to an existing RRSet", func(ctx context.Context, ttl, expectedRequests int) { + rrSet := libcloudapi.ExistingRRSetSRV() + rrSet.TTL = &ttl + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), rrSet, true), + ) + if ttl != libserver.DefaultTTL { + api.AppendHandlers(libcloudapi.ChangeRRSetTTL(token, libcloudapi.Zone(), libcloudapi.ExistingRRSetSRV())) + } + api.AppendHandlers( + libcloudapi.AddRRSetRecords(token, libcloudapi.Zone(), rrSet, []schema.ZoneRRSetRecord{ + {Value: libserver.SRVValue}, + }), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/present", username, password, + rec(libserver.SRVRecordNameFull, typeSRV, srvInput), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(expectedRequests)) + }, + Entry("with matching TTL", libserver.DefaultTTL, 3), + Entry("with different TTL", libserver.DefaultTTL+1, 4), + ) + + It("not adding a SRV record that already exists", func(ctx context.Context) { + rrSet := libcloudapi.ExistingRRSetSRV() + rrSet.Records = append(rrSet.Records, schema.ZoneRRSetRecord{Value: libserver.SRVValue}) + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), rrSet, true), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/present", username, password, + rec(libserver.SRVRecordNameFull, typeSRV, srvInput), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(2)) + }) + + DescribeTable( + "cleaning up a record", func(ctx context.Context, rrSet schema.ZoneRRSet, fqdn, value string) { + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), rrSet, true), + libcloudapi.RemoveRRSetRecords(token, libcloudapi.Zone(), rrSet, rrSet.Records), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/cleanup", username, password, + rec(fqdn, rrSet.Type, value), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(3)) + }, + Entry("CNAME", libcloudapi.NewRRSetCNAME(), libserver.CNAMERecordNameFull, "target.test.tld"), + Entry("SRV", libcloudapi.NewRRSetSRV(), libserver.SRVRecordNameFull, srvInput), + ) + + It("cleaning up a record that does not exist", func(ctx context.Context) { + api.AppendHandlers( + libcloudapi.GetZone(token, libcloudapi.Zone()), + libcloudapi.GetRRSet(token, libcloudapi.Zone(), libcloudapi.NewRRSetCNAME(), false), + ) + + Expect(doRecordsRequest( + ctx, server.URL+"/records/cleanup", username, password, + rec(libserver.CNAMERecordNameFull, typeCNAME, "target.test.tld"), + )).To(Equal(http.StatusOK)) + Expect(api.ReceivedRequests()).To(HaveLen(2)) + }) + }) + + Context("should make no api calls and should fail", func() { + AfterEach(func() { + Expect(api.ReceivedRequests()).To(BeEmpty()) + }) + + DescribeTable( + "on invalid input", func(ctx context.Context, data map[string]string) { + Expect(doRecordsRequest( + ctx, server.URL+"/records/present", username, password, data, + )).To(Equal(http.StatusBadRequest)) + }, + Entry("missing type", map[string]string{"fqdn": libserver.CNAMERecordNameFull, "value": otherHost}), + Entry("unsupported type", rec(libserver.CNAMERecordNameFull, "MX", otherHost)), + Entry("CNAME at the zone apex", rec(libserver.ZoneName, typeCNAME, otherHost)), + Entry("CNAME with invalid target", rec(libserver.CNAMERecordNameFull, typeCNAME, "a b.test.tld")), + Entry("SRV with missing field", rec(libserver.SRVRecordNameFull, typeSRV, "0 5 mc.test.tld")), + Entry("SRV with port out of range", rec(libserver.SRVRecordNameFull, typeSRV, "0 5 70000 mc.test.tld")), + Entry("A with invalid address", rec(libserver.ARecordNameFull, "A", "nope")), + ) + + DescribeTable( + "when access is denied", func(ctx context.Context, path string) { + server.Close() + server = libserver.NewNoAllowedDomains(api.URL()) + Expect(doRecordsRequest( + ctx, server.URL+path, username, password, + rec(libserver.CNAMERecordNameFull, typeCNAME, otherHost), + )).To(Equal(http.StatusUnauthorized)) + }, + Entry("present", "/records/present"), + Entry("cleanup", "/records/cleanup"), + ) + + DescribeTable( + "when the endpoint is not enabled", func(ctx context.Context, path string) { + server.Close() + server, _, username, password = libserver.NewWithEndpoints( + api.URL(), libserver.DefaultTTL, config.NewConfig().Endpoints, + ) + Expect(doRecordsRequest( + ctx, server.URL+path, username, password, + rec(libserver.CNAMERecordNameFull, typeCNAME, otherHost), + )).To(Equal(http.StatusNotFound)) + }, + Entry("present", "/records/present"), + Entry("cleanup", "/records/cleanup"), + ) + }) +}) + +func doRecordsRequest(ctx context.Context, serverURL, username, password string, data map[string]string) int { + body, err := json.Marshal(data) + Expect(err).ToNot(HaveOccurred()) + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, serverURL, bytes.NewReader(body)) + Expect(err).ToNot(HaveOccurred()) + req.Header.Add("Content-Type", "application/json") + req.SetBasicAuth(username, password) + + res, err := (&http.Client{}).Do(req) + Expect(err).ToNot(HaveOccurred()) + Expect(res.Body.Close()).To(Succeed()) + + return res.StatusCode +}