first commit
Go quality gates / test (push) Waiting to run

This commit is contained in:
Mateusz Gruszczyński committed 2026-11-30 11:37:40 +01:00
commit 8c4d463f1e
96 files changed
+3319

No files matched your search

+133
View File
@@ -0,0 +1,133 @@
package easydns
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strings"
"time"
)
const maxResponse = 16 << 20
type Client struct {
base string
tokenFile string
useSocket bool
http *http.Client
}
func New(base, tokenFile, socket string) (*Client, error) {
tr := &http.Transport{MaxIdleConnsPerHost: 8, IdleConnTimeout: 30 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
if socket != "" {
tr.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{Timeout: 5 * time.Second}).DialContext(ctx, "unix", socket)
}
base = "http://unix"
} else {
u, e := url.Parse(base)
if e != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return nil, errors.New("invalid EasyDNS API URL")
}
base = strings.TrimSuffix(base, "/")
}
return &Client{base: base, tokenFile: tokenFile, useSocket: socket != "", http: &http.Client{Transport: tr, Timeout: 65 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}, nil
}
type Error struct {
Status int
Message string
}
func (e *Error) Error() string {
if e.Status == 0 {
return e.Message
}
return fmt.Sprintf("EasyDNS HTTP %d: %s", e.Status, e.Message)
}
// Do uses ONLY paths explicitly built in the panel routes. It does not expose a generic API proxy.
func (c *Client) Do(ctx context.Context, method, path string, body any, etag string, out any) (string, error) {
if !strings.HasPrefix(path, "/api/v1/") && path != "/readyz" && path != "/healthz" {
return "", &Error{Message: "endpoint is not permitted"}
}
var src io.Reader
if body != nil {
b, e := json.Marshal(body)
if e != nil {
return "", e
}
src = bytes.NewReader(b)
}
req, e := http.NewRequestWithContext(ctx, method, c.base+path, src)
if e != nil {
return "", e
}
req.Header.Set("Accept", "application/json")
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if etag != "" {
req.Header.Set("If-Match", etag)
}
if !c.useSocket && path != "/readyz" && path != "/healthz" && path != "/api/v1/health" {
secret, e := os.ReadFile(c.tokenFile)
if e != nil {
return "", &Error{Message: "Unable to read EasyDNS generated control token; check token file permissions or configure the Unix socket"}
}
token := strings.TrimSpace(string(secret))
if token == "" {
return "", &Error{Message: "EasyDNS control token file is empty"}
}
req.Header.Set("Authorization", "Bearer "+token)
}
resp, e := c.http.Do(req)
if e != nil {
return "", &Error{Message: "EasyDNS API unavailable: " + e.Error()}
}
defer resp.Body.Close()
raw, e := io.ReadAll(io.LimitReader(resp.Body, maxResponse+1))
if e != nil {
return "", e
}
if len(raw) > maxResponse {
return "", &Error{Message: "EasyDNS API response exceeds 16 MiB"}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
var envelope struct {
Error struct {
Status int `json:"status"`
Message string `json:"message"`
} `json:"error"`
}
msg := http.StatusText(resp.StatusCode)
if json.Unmarshal(raw, &envelope) == nil && envelope.Error.Message != "" {
msg = envelope.Error.Message
}
if msg == "" {
msg = "Unexpected EasyDNS response"
}
return resp.Header.Get("ETag"), &Error{Status: resp.StatusCode, Message: msg}
}
if out != nil && len(raw) > 0 {
if e := json.Unmarshal(raw, out); e != nil {
return "", fmt.Errorf("decode EasyDNS response: %w", e)
}
}
return resp.Header.Get("ETag"), nil
}
func (c *Client) Get(ctx context.Context, path string, out any) (string, error) {
return c.Do(ctx, http.MethodGet, path, nil, "", out)
}
func (c *Client) Write(ctx context.Context, method, path string, payload any, etag string, out any) error {
_, e := c.Do(ctx, method, path, payload, etag, out)
return e
}
func Escape(v string) string { return url.PathEscape(v) }
+101
View File
@@ -0,0 +1,101 @@
package easydns
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
)
func TestGeneratedTokenAndETag(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
if e := os.WriteFile(file, []byte("generated-test-token\n"), 0600); e != nil {
t.Fatal(e)
}
var got string
var match string
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got = r.Header.Get("Authorization")
match = r.Header.Get("If-Match")
if r.Method != http.MethodPut || r.URL.Path != "/api/v1/zones/example.com./records/record-id" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
if got != "Bearer generated-test-token" {
t.Errorf("wrong bearer token: %q", got)
}
if match != "\"2026113001\"" {
t.Errorf("missing serial guard: %q", match)
}
var body struct {
Name string `json:"name"`
Type string `json:"type"`
TTL int `json:"ttl"`
Data string `json:"data"`
}
if e := json.NewDecoder(r.Body).Decode(&body); e != nil {
t.Error(e)
}
if body.Name != "www" || body.Type != "A" || body.TTL != 300 || body.Data != "192.0.2.10" {
t.Errorf("wrong payload: %+v", body)
}
w.Header().Set("ETag", "\"2026113002\"")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer ts.Close()
c, e := New(ts.URL, file, "")
if e != nil {
t.Fatal(e)
}
var out struct {
OK bool `json:"ok"`
}
e = c.Write(context.Background(), "PUT", "/api/v1/zones/example.com./records/record-id", map[string]any{"name": "www", "type": "A", "ttl": 300, "data": "192.0.2.10"}, "\"2026113001\"", &out)
if e != nil {
t.Fatal(e)
}
if !out.OK {
t.Fatal("response not decoded")
}
if got == "" || match == "" {
t.Fatal("request not received")
}
}
func TestErrorEnvelope(t *testing.T) {
dir := t.TempDir()
file := filepath.Join(dir, "control.token")
_ = os.WriteFile(file, []byte("a"), 0600)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(412)
_, _ = w.Write([]byte(`{"error":{"status":412,"message":"zone serial changed"}}`))
}))
defer ts.Close()
c, _ := New(ts.URL, file, "")
_, e := c.Get(context.Background(), "/api/v1/zones/example.com.", nil)
apiErr, ok := e.(*Error)
if !ok || apiErr.Status != 412 || !strings.Contains(apiErr.Message, "zone serial changed") {
t.Fatalf("wrong REST error: %#v", e)
}
}
func TestNoUnknownAPIPaths(t *testing.T) {
c, e := New("http://127.0.0.1:9953", "/does/not/matter", "")
if e != nil {
t.Fatal(e)
}
_, e = c.Get(context.Background(), "/new-not-real-endpoint", nil)
if e == nil || !strings.Contains(e.Error(), "not permitted") {
t.Fatalf("unexpected: %v", e)
}
}
func TestInvalidBaseURL(t *testing.T) {
_, e := New("file:///etc/shadow", "/tmp/token", "")
if e == nil {
t.Fatal("invalid URL accepted")
}
}
+207
View File
@@ -0,0 +1,207 @@
package easydns
import (
"fmt"
"strings"
"time"
)
type Pagination struct {
Page int `json:"page"`
PerPage int `json:"per_page"`
Total int `json:"total"`
}
type Page[T any] struct {
Items []T `json:"items"`
Pagination Pagination `json:"pagination"`
Serial uint32 `json:"serial"`
}
type Health struct {
Status string `json:"status"`
ExpiredZones []string `json:"expired_zones"`
}
type Roles struct {
Primary int `json:"primary"`
Secondary int `json:"secondary"`
Recursive bool `json:"recursive"`
Forwarder bool `json:"forwarder"`
ForwardZones int `json:"forward_zones"`
DefaultResolution string `json:"default_resolution"`
}
type Status struct {
Version string `json:"version"`
Mode string `json:"mode"`
UptimeSeconds uint64 `json:"uptime_seconds"`
Roles Roles `json:"roles"`
Listeners map[string]any `json:"listeners"`
Zones []Zone `json:"zones"`
DNSSECValidation any `json:"dnssec_validation"`
}
type Cache struct {
Entries uint64 `json:"entries"`
Capacity uint64 `json:"capacity"`
Hits uint64 `json:"hits"`
Misses uint64 `json:"misses"`
Inserts uint64 `json:"inserts"`
Evictions uint64 `json:"evictions"`
Expired uint64 `json:"expired"`
StaleServed uint64 `json:"stale_served"`
Prefetches uint64 `json:"prefetches"`
}
type Stats struct {
QueriesTotal uint64 `json:"queries_total"`
Responses map[string]uint64 `json:"responses"`
Sources map[string]uint64 `json:"sources"`
LatencyP50S float64 `json:"latency_p50_s"`
LatencyP95S float64 `json:"latency_p95_s"`
LatencyP99S float64 `json:"latency_p99_s"`
Cache Cache `json:"cache"`
CacheHitRate float64 `json:"cache_hit_rate"`
Blocked uint64 `json:"blocked"`
RateLimited uint64 `json:"rate_limited"`
UptimeSeconds uint64 `json:"uptime_seconds"`
}
type ZoneState struct {
Serial *uint32 `json:"serial"`
Loaded bool `json:"loaded"`
Expired bool `json:"expired"`
Records int `json:"records"`
Source *string `json:"source"`
LastRefreshUnix *int64 `json:"last_refresh_unix"`
LastSuccessUnix *int64 `json:"last_success_unix"`
NextRefreshUnix *int64 `json:"next_refresh_unix"`
ExpiresAtUnix *int64 `json:"expires_at_unix"`
LastError *string `json:"last_error"`
NotifiesSent uint64 `json:"notifies_sent"`
NotifiesFailed uint64 `json:"notifies_failed"`
}
type Zone struct {
Name string `json:"name"`
Kind string `json:"kind"`
Views []string `json:"views"`
Serial *uint32 `json:"serial"`
Loaded bool `json:"loaded"`
Expired bool `json:"expired"`
Records int `json:"records"`
Status ZoneState `json:"status"`
Config ZoneConfig `json:"config"`
JournalEntries int `json:"journal_entries"`
DNSSEC map[string]any `json:"dnssec"`
}
type ZoneConfig struct {
Name string `json:"name"`
Type string `json:"type"`
Notify []string `json:"notify"`
TransferACL []string `json:"transfer_acl"`
Primaries []string `json:"primaries"`
File *string `json:"file"`
DNSSEC map[string]any `json:"dnssec"`
Transfer any `json:"transfer"`
Views []string `json:"views"`
}
func (z Zone) IsPrimary() bool { return strings.EqualFold(z.Kind, "primary") }
func (z Zone) IsSecondary() bool { return strings.EqualFold(z.Kind, "secondary") }
func (z Zone) StateText() string {
if z.Expired {
return "Expired"
}
if !z.Loaded {
return "Not loaded"
}
return "Loaded"
}
func (z Zone) SerialText() string {
if z.Serial == nil {
return "—"
}
return fmt.Sprint(*z.Serial)
}
func (z Zone) SyncText() string {
if z.IsPrimary() {
return "Not applicable"
}
if z.Expired {
return "Expired"
}
if z.Status.LastError != nil && *z.Status.LastError != "" {
return "Error"
}
if z.Status.LastSuccessUnix != nil {
return "Last sync OK"
}
return "Not yet synced"
}
func (z Zone) LastSync() string {
if z.Status.LastSuccessUnix == nil {
return "—"
}
return time.Unix(*z.Status.LastSuccessUnix, 0).UTC().Format("2006-01-02 15:04:05 UTC")
}
type Record struct {
ID string `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
TTL uint32 `json:"ttl"`
Data string `json:"data"`
}
type Transfer struct {
TimeUnix int64 `json:"time_unix"`
Direction string `json:"direction"`
Kind string `json:"kind"`
Peer string `json:"peer"`
Serial *uint32 `json:"serial"`
Records int `json:"records"`
OK bool `json:"ok"`
Error *string `json:"error"`
DurationMS uint64 `json:"duration_ms"`
}
type UpstreamGroup struct {
Group string `json:"group"`
Strategy string `json:"strategy"`
Servers []Upstream `json:"servers"`
}
type Upstream struct {
Address string `json:"address"`
Stats UpstreamStats `json:"stats"`
}
type UpstreamStats struct {
Queries uint64 `json:"queries"`
Failures uint64 `json:"failures"`
ConsecutiveFailures uint32 `json:"consecutive_failures"`
EWMARTTMS *float64 `json:"ewma_rtt_ms"`
CircuitOpenForMS *uint64 `json:"circuit_open_for_ms"`
LastError *string `json:"last_error"`
Healthy bool `json:"healthy"`
}
type QueryResult struct {
RCode string `json:"rcode"`
AA bool `json:"aa"`
Answers []Record `json:"answers"`
Authority []Record `json:"authority"`
ElapsedMS float64 `json:"elapsed_ms"`
}
type AuditItem struct {
TimeUnix int64 `json:"time_unix"`
Actor string `json:"actor"`
Action string `json:"action"`
Target string `json:"target"`
Result string `json:"result"`
Detail string `json:"detail"`
}
type Blocklists struct {
Lists []map[string]any `json:"lists"`
Loaded []string `json:"loaded"`
Rules int `json:"rules"`
UpdateInterval string `json:"update_interval"`
State map[string]map[string]any `json:"state"`
}
type Policies struct {
RecursionAllowedClients []string `json:"recursion_allowed_clients"`
ACLs map[string]any `json:"acls"`
Views []map[string]any `json:"views"`
RateLimit map[string]any `json:"rate_limit"`
Policy map[string]any `json:"policy"`
APIAllowedClients []string `json:"api_allowed_clients"`
}