Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,12 +74,12 @@ cloudAPI: false

| Variable | Type | Description | Required | Default |
|:------------------|--------|--------------------------------------------------------------------------------------------------------------------------------------------|----------|----------------------------------|
| `API_BASE_URL` | string | Base URL of the DNS API | n | `https://dns.hetzner.com/api/v1` |
| `API_BASE_URL` | string | Base URL of the API. Defaults to `https://dns.hetzner.com/api/v1` for DNS API or `https://api.hetzner.cloud/v1` when `CLOUD_API` is `true`. | n | (Depends on API selection) |
| `API_TOKEN` | string | Auth token for the API | Y | |
| `API_TIMEOUT` | int | Timeout for calls to the API in seconds | N | 15 seconds |
| `RECORD_TTL` | int | TTL that is set when creating/updating records | N | 60 seconds |
| `ALLOWED_DOMAINS` | string | Combination of domains and CIDRs allowed to update them, example:<br>`example1.com,127.0.0.1/32;_acme-challenge.example2.com,127.0.0.1/32` | Y | |
| `LISTEN_ADDR` | string | Listen address of hetzner-dnsapi-proxy | N | `:8081` |
| `TRUSTED_PROXIES` | string | List of trusted proxy host addresses separated by comma | N | Trust all proxies |
| `CLOUD_API` | bool | Use the Hetzner Cloud API instead of the DNS API. When enabled, `API_BASE_URL` is ignored. | N | `false` |
| `CLOUD_API` | bool | Use the Hetzner Cloud API instead of the DNS API. | N | `false` |
| `DEBUG` | bool | Output debug logs of received requests | N | `false` |
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ require (
github.com/hetznercloud/hcloud-go/v2 v2.33.0
github.com/onsi/ginkgo/v2 v2.27.3
github.com/onsi/gomega v1.38.3
golang.org/x/net v0.48.0
)

require (
Expand All @@ -25,7 +26,6 @@ require (
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/mod v0.31.0 // indirect
golang.org/x/net v0.48.0 // indirect
golang.org/x/sync v0.19.0 // indirect
golang.org/x/sys v0.39.0 // indirect
golang.org/x/text v0.32.0 // indirect
Expand Down
28 changes: 20 additions & 8 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@ type User struct {

func NewConfig() *Config {
return &Config{
BaseURL: "https://dns.hetzner.com/api/v1",
Timeout: 15,
Auth: Auth{
Method: AuthMethodBoth,
Expand All @@ -84,6 +83,14 @@ func ParseEnv() (*Config, error) {
cfg := NewConfig()
cfg.Auth.Method = AuthMethodAllowedDomains

if cloudAPI, ok := os.LookupEnv("CLOUD_API"); ok {
cloudAPIBool, err := strconv.ParseBool(cloudAPI)
if err != nil {
return nil, fmt.Errorf("failed to parse CLOUD_API: %v", err)
}
cfg.CloudAPI = cloudAPIBool
}

if baseURL, ok := os.LookupEnv("API_BASE_URL"); ok {
cfg.BaseURL = baseURL
}
Expand Down Expand Up @@ -140,13 +147,7 @@ func ParseEnv() (*Config, error) {
cfg.Debug = debugBool
}

if cloudAPI, ok := os.LookupEnv("CLOUD_API"); ok {
cloudAPIBool, err := strconv.ParseBool(cloudAPI)
if err != nil {
return nil, fmt.Errorf("failed to parse CLOUD_API: %v", err)
}
cfg.CloudAPI = cloudAPIBool
}
setDefaultBaseURL(cfg)

return cfg, nil
}
Expand Down Expand Up @@ -183,6 +184,7 @@ func ReadFile(path string) (*Config, error) {
}

setDefaultIPMask(cfg.Auth.AllowedDomains)
setDefaultBaseURL(cfg)

return cfg, nil
}
Expand All @@ -194,6 +196,16 @@ func AuthMethodIsValid(authMethod string) bool {
authMethod == AuthMethodAny
}

func setDefaultBaseURL(c *Config) {
if c.BaseURL == "" {
if c.CloudAPI {
c.BaseURL = "https://api.hetzner.cloud/v1"
} else {
c.BaseURL = "https://dns.hetzner.com/api/v1"
}
}
}

func setDefaultIPMask(allowedDomains AllowedDomains) {
const ff = 255
for _, allowedDomain := range allowedDomains {
Expand Down
29 changes: 27 additions & 2 deletions pkg/hetzner/hetzner.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package hetzner

import (
"fmt"
"net/http"
"runtime/debug"
"time"

"github.com/hetznercloud/hcloud-go/v2/hcloud"
)

const RequestTimeout = 60 * time.Second
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/config"
)

type Zone struct {
ID string `json:"id"`
Expand All @@ -31,6 +33,29 @@ type Records struct {
Records []Record `json:"records"`
}

func NewHCloudClient(cfg *config.Config) *hcloud.Client {
version := "dev"
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
version = setting.Value
break
}
}
}

opts := []hcloud.ClientOption{
hcloud.WithToken(cfg.Token),
hcloud.WithHTTPClient(&http.Client{
Timeout: time.Duration(cfg.Timeout) * time.Second,
}),
hcloud.WithApplication("hetzner-dnsapi-proxy", version),
hcloud.WithEndpoint(cfg.BaseURL),
}

return hcloud.NewClient(opts...)
}

func RRSetTypeFromString(rType string) (hcloud.ZoneRRSetType, error) {
switch rrType := hcloud.ZoneRRSetType(rType); rrType {
case hcloud.ZoneRRSetTypeA,
Expand Down
15 changes: 8 additions & 7 deletions pkg/middleware/bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"net/http"
"strings"

"golang.org/x/net/publicsuffix"

"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/data"
)

Expand Down Expand Up @@ -204,16 +206,15 @@ func BindDirectAdmin(next http.Handler) http.Handler {
}

func SplitFQDN(fqdn string) (name, zone string, err error) {
parts := strings.Split(fqdn, ".")
length := len(parts)

const zoneParts = 2
if length < zoneParts {
zone, err = publicsuffix.EffectiveTLDPlusOne(fqdn)
if err != nil {
return "", "", fmt.Errorf("invalid fqdn: %s", fqdn)
}

name = strings.Join(parts[:length-zoneParts], ".")
zone = strings.Join(parts[length-zoneParts:], ".")
if fqdn == zone {
return "", zone, nil
}

name = strings.TrimSuffix(fqdn, "."+zone)
return name, zone, nil
}
12 changes: 8 additions & 4 deletions pkg/middleware/bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,20 @@ import (
)

var _ = Describe("SplitFQDN", func() {
DescribeTable("should split successfully a", func(fullName, expectedName, expectedZone string) {
name, zone, err := middleware.SplitFQDN("test.example.com")
DescribeTable("should split successfully", func(fullName, expectedName, expectedZone string) {
name, zone, err := middleware.SplitFQDN(fullName)
Expect(err).ToNot(HaveOccurred())
Expect(name).To(Equal("test"))
Expect(zone).To(Equal("example.com"))
Expect(name).To(Equal(expectedName))
Expect(zone).To(Equal(expectedZone))
},
Entry("simple domain", "example.com", "", "example.com"),
Entry("single subdomain", "test.example.com", "test", "example.com"),
Entry("double subdomain", "sub.test.example.com", "sub.test", "example.com"),
Entry("triple subdomain", "subsub.sub.test.example.com", "subsub.sub.test", "example.com"),
Entry("multi-part TLD (co.uk)", "example.co.uk", "", "example.co.uk"),
Entry("subdomain on multi-part TLD (co.uk)", "test.example.co.uk", "test", "example.co.uk"),
Entry("multi-part TLD (com.au)", "example.com.au", "", "example.com.au"),
Entry("subdomain on multi-part TLD (com.au)", "test.example.com.au", "test", "example.com.au"),
)

It("should fail on TLD", func() {
Expand Down
6 changes: 1 addition & 5 deletions pkg/middleware/clean/clean.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (

"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/config"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/data"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/hetzner"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/middleware/clean/cloud"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/middleware/clean/dns"
)
Expand All @@ -34,11 +33,8 @@ func New(cfg *config.Config, m *sync.Mutex) func(http.Handler) http.Handler {
return
}

ctx, cancel := context.WithTimeout(context.Background(), hetzner.RequestTimeout)
defer cancel()

log.Printf("received request to clean '%s' data of '%s'", reqData.Type, reqData.FullName)
if err := c.Clean(ctx, reqData); err != nil {
if err := c.Clean(r.Context(), reqData); err != nil {
log.Printf("failed to clean record: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
Expand Down
2 changes: 1 addition & 1 deletion pkg/middleware/clean/cloud/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type cleaner struct {
func New(cfg *config.Config, m *sync.Mutex) *cleaner {
return &cleaner{
cfg: cfg,
client: hcloud.NewClient(hcloud.WithToken(cfg.Token)),
client: hetzner.NewHCloudClient(cfg),
m: m,
}
}
Expand Down
20 changes: 14 additions & 6 deletions pkg/middleware/update/cloud/cloud.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type updater struct {
func New(cfg *config.Config, m *sync.Mutex) *updater {
return &updater{
cfg: cfg,
client: hcloud.NewClient(hcloud.WithToken(cfg.Token)),
client: hetzner.NewHCloudClient(cfg),
m: m,
}
}
Expand Down Expand Up @@ -54,11 +54,19 @@ func (u *updater) Update(ctx context.Context, reqData *data.ReqData) error {
}

func (u *updater) updateRRSet(ctx context.Context, rrSet *hcloud.ZoneRRSet, val string) error {
rrSet.TTL = &u.cfg.RecordTTL
rrSet.Records = []hcloud.ZoneRRSetRecord{{
Value: strconv.Quote(val),
}}
_, _, err := u.client.Zone.UpdateRRSet(ctx, rrSet, hcloud.ZoneRRSetUpdateOpts{})
if rrSet.TTL == nil || *rrSet.TTL != u.cfg.RecordTTL {
opts := hcloud.ZoneRRSetChangeTTLOpts{TTL: &u.cfg.RecordTTL}
if _, _, err := u.client.Zone.ChangeRRSetTTL(ctx, rrSet, opts); err != nil {
return err
}
}

opts := hcloud.ZoneRRSetSetRecordsOpts{
Records: []hcloud.ZoneRRSetRecord{{
Value: strconv.Quote(val),
}},
}
_, _, err := u.client.Zone.SetRRSetRecords(ctx, rrSet, opts)
return err
}

Expand Down
6 changes: 3 additions & 3 deletions pkg/middleware/update/dns/dns.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func (u *updater) Update(ctx context.Context, reqData *data.ReqData) error {
return u.createRecord(ctx, &r)
}

func (u *updater) getRequest(ctx context.Context, url string) ([]byte, error) {
func (u *updater) getRequest(ctx context.Context, url string) (body []byte, err error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody)
if err != nil {
return nil, err
Expand All @@ -94,15 +94,15 @@ func (u *updater) getRequest(ctx context.Context, url string) ([]byte, error) {
return nil, fmt.Errorf(requestFailedFmt, http.MethodGet, res.StatusCode)
}

body, err := io.ReadAll(res.Body)
body, err = io.ReadAll(res.Body)
if err != nil {
return nil, err
}

return body, err
}

func (u *updater) jsonRequest(ctx context.Context, method, url string, body []byte) error {
func (u *updater) jsonRequest(ctx context.Context, method, url string, body []byte) (err error) {
req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
if err != nil {
return err
Expand Down
6 changes: 1 addition & 5 deletions pkg/middleware/update/update.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (

"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/config"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/data"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/hetzner"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/middleware/update/cloud"
"github.com/0xfelix/hetzner-dnsapi-proxy/pkg/middleware/update/dns"
)
Expand All @@ -34,11 +33,8 @@ func New(cfg *config.Config, m *sync.Mutex) func(http.Handler) http.Handler {
return
}

ctx, cancel := context.WithTimeout(context.Background(), hetzner.RequestTimeout)
defer cancel()

log.Printf("received request to update '%s' data of '%s' to '%s'", reqData.Type, reqData.FullName, reqData.Value)
if err := u.Update(ctx, reqData); err != nil {
if err := u.Update(r.Context(), reqData); err != nil {
log.Printf("failed to update record: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
Expand Down
Loading