dns

package
v0.5.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package dns manages domains and their records (Phase 28). SynCloud manages and instructs: with a provider connected (Cloudflare) it writes the records itself, without one it shows which records to create and checks them live. It is not a name server.

Index

Constants

View Source
const (
	ActionCreate = "create"
	ActionKeep   = "keep"
	ActionUpdate = "update"
	ActionDelete = "delete"

	ReasonMissing   = "missing"   // wanted, not there
	ReasonOK        = "ok"        // already right
	ReasonDuplicate = "duplicate" // the same record twice
	ReasonStale     = "stale"     // the platform made it, nobody wants it any more
	ReasonConflict  = "conflict"  // somebody else's record that is in the way
	ReasonSettings  = "settings"  // wanted, but with other TTL/proxy settings
)

Plan actions and reasons.

View Source
const AcmePrefix = "_acme-challenge."

AcmePrefix is the label every DNS-01 challenge lives under.

View Source
const AllProjects = "*"

AllProjects is the grant project that means every project.

View Source
const DefaultCloudflareAPI = "https://api.cloudflare.com/client/v4"

DefaultCloudflareAPI is Cloudflare's API.

Variables

View Source
var (
	ErrNotFound   = errors.New("not found")
	ErrNotGranted = errors.New("this project may not use that name")
	ErrInUse      = errors.New("in use")
	ErrInvalid    = errors.New("invalid")
	ErrConflict   = errors.New("conflict")
)

Errors a caller maps to HTTP statuses.

View Source
var DefaultResolvers = []string{"1.1.1.1:53", "8.8.8.8:53", "9.9.9.9:53"}

DefaultResolvers are the public resolvers the lookup tool asks.

View Source
var ErrNoProvider = errors.New("this domain has no DNS provider connected: create the records at your DNS host")

ErrNoProvider means the domain has no provider: its records are manual.

View Source
var RecordTypes = []string{"A", "AAAA", "CNAME", "TXT", "MX", "SRV", "CAA", "NS"}

Types of records the panel handles.

Functions

func AuthoritativeServers

func AuthoritativeServers(ctx context.Context, resolvers []string, name string) (zone string, servers []string)

AuthoritativeServers finds the name servers of the zone a name is in, walking up the labels until some resolver names them.

func BuiltinTarget

func BuiltinTarget(challengeName, zone string) string

BuiltinTarget is the name in the challenge server's zone a challenge name is delegated to.

func ChallengeName

func ChallengeName(host string) string

ChallengeName is the name the authority looks up for a host.

func DefaultNS

func DefaultNS(zone string) string

DefaultNS names the name server host of a challenge zone: acme.example.com → acme-ns.example.com.

func DelegationTarget

func DelegationTarget(challengeName, targetZone string) string

DelegationTarget is the name a challenge name is delegated to inside the validation domain: stable per name, one label, so every name gets its own.

func Fqdn

func Fqdn(name string) string

Fqdn lowercases a name and drops a trailing dot.

func HasTXT

func HasTXT(ctx context.Context, resolvers []string, name string, values []string) (missing []string, err error)

HasTXT reports whether every value is among the TXT answers at name, asking each resolver given: a value must be visible to all of them.

func InZone

func InZone(name, zone string) bool

InZone reports whether name is the zone or below it.

func Qualify

func Qualify(zone, name string) string

Qualify turns a record name as a person types it into its full name: @ is the domain, a name already in the domain stays, any other name is relative to it (as at the DNS providers themselves).

func QueryTypes

func QueryTypes() []string

QueryTypes lists the types Lookup knows.

func ValidZoneName

func ValidZoneName(name string) error

ValidZoneName checks a registered domain's name: lowercase labels, at least two of them, no wildcard.

Types

type AddZoneInput

type AddZoneInput struct {
	Name             string
	ProviderID       string // "" = manual
	Grants           []store.ZoneGrant
	WildcardPolicy   string
	AuthorityID      string
	ChallengeZone    string // delegate _acme-challenge to this domain (needs a provider)
	ChallengeBuiltin bool
}

AddZoneInput registers a domain.

type Answer

type Answer struct {
	Server string   `json:"server"`
	Kind   string   `json:"kind"` // public | authoritative
	Rcode  string   `json:"rcode"`
	Values []string `json:"values"`
	TTL    uint32   `json:"ttl,omitempty"`
	Error  string   `json:"error,omitempty"`
}

Answer is what one server said.

func Lookup

func Lookup(ctx context.Context, resolvers []string, name, qtype, via string) []Answer

Lookup asks public resolvers, the zone's authoritative servers, or both.

func Query

func Query(ctx context.Context, server, name, qtype string) Answer

Query asks one server for one name and type.

type Applied

type Applied struct {
	Created, Updated, Deleted int
	Skipped                   []Step // conflicts left because they were not confirmed
}

Applied is what an apply did.

func Apply

func Apply(ctx context.Context, p Provider, zoneID string, plan PlanResult, confirmed bool, tr Tracker) (Applied, error)

Apply carries a plan out. Steps that need confirmation are skipped unless confirmed. A failure stops the run: the zone stays usable and the next run finishes the job.

type CNAMEState

type CNAMEState struct {
	Name    string   `json:"name"`
	Target  string   `json:"target"`
	Present bool     `json:"present"`        // public resolvers answer with the target
	Seen    []string `json:"seen,omitempty"` // what they answer instead
	// Managed: SynCloud creates and keeps the CNAME (the domain has a provider).
	Managed bool `json:"managed"`
}

CNAMEState says whether the delegating CNAME is in place.

type CertHost

type CertHost struct{ *Service }

CertHost gives the certificates what they need from the domains.

func (CertHost) Challenge

func (d CertHost) Challenge(ctx context.Context, name string) certs.ChallengeInfo

Challenge adapts the route for the certificates.

func (CertHost) EnsureDelegation

func (d CertHost) EnsureDelegation(ctx context.Context, name string) error

EnsureDelegation makes the CNAME when SynCloud can, without replacing records of others.

func (CertHost) HasTXT

func (d CertHost) HasTXT(ctx context.Context, name string, values []string) ([]string, error)

func (CertHost) OriginCertificate

func (d CertHost) OriginCertificate(ctx context.Context, providerID, csrPEM string, names []string, days int) (string, error)

func (CertHost) WildcardZones

func (d CertHost) WildcardZones(ctx context.Context) []certs.ZonePolicy

func (CertHost) ZoneOf

func (d CertHost) ZoneOf(ctx context.Context, host string) (string, string, bool)

type ChallengeRoute

type ChallengeRoute struct {
	Name       string      `json:"name"`           // _acme-challenge.<host>: what the authority asks for
	Host       string      `json:"host"`           // the host or domain it proves
	Zone       string      `json:"zone,omitempty"` // the registered domain, empty outside every one
	Mode       string      `json:"mode"`           // direct | delegated | builtin | manual
	Auto       bool        `json:"auto"`           // SynCloud writes the TXT record
	Target     string      `json:"target,omitempty"`
	TargetZone string      `json:"targetZone,omitempty"`
	CNAME      *CNAMEState `json:"cname,omitempty"`
	Note       string      `json:"note,omitempty"`
}

ChallengeRoute is where the challenge for a host is answered.

type Check

type Check struct {
	Name   string `json:"name"`
	OK     bool   `json:"ok"`
	Detail string `json:"detail"`
}

Check is one result of testing the challenge server.

type CleanupResult

type CleanupResult struct {
	Duplicates []Record `json:"duplicates"`
	Challenges []Record `json:"challenges"`
	Removed    int      `json:"removed"`
}

Cleanup lists duplicates and leftover challenge records of a domain's zone; with apply it removes the exact duplicates and the leftovers the platform created. Other tools' records are only listed.

type Cloudflare

type Cloudflare struct {
	Token string
	Base  string
	HTTP  *http.Client
	// Sleep waits between retries (tests replace it).
	Sleep func(time.Duration)
}

Cloudflare is the Cloudflare DNS API with an API token. The recommended token has Zone:Zone:Read and Zone:DNS:Edit on the chosen zones only.

func NewCloudflare

func NewCloudflare(token, base string, hc *http.Client) *Cloudflare

func (*Cloudflare) Create

func (c *Cloudflare) Create(ctx context.Context, zoneID string, r Record) (Record, error)

func (*Cloudflare) Delete

func (c *Cloudflare) Delete(ctx context.Context, zoneID, id string) error

func (*Cloudflare) OriginCertificate

func (c *Cloudflare) OriginCertificate(ctx context.Context, csrPEM string, hostnames []string, validityDays int) (string, error)

OriginCertificate asks Cloudflare to sign an origin certificate (not publicly trusted: good only behind Cloudflare's proxy in Full (strict)).

func (*Cloudflare) Records

func (c *Cloudflare) Records(ctx context.Context, zoneID string) ([]Record, error)

func (*Cloudflare) Update

func (c *Cloudflare) Update(ctx context.Context, zoneID, id string, r Record) (Record, error)

func (*Cloudflare) Verify

func (c *Cloudflare) Verify(ctx context.Context) error

func (*Cloudflare) Zones

func (c *Cloudflare) Zones(ctx context.Context) ([]ZoneInfo, error)

type ConflictError

type ConflictError struct {
	Msg    string
	Record *Record
}

ConflictError carries the record that is in the way.

func (*ConflictError) Error

func (e *ConflictError) Error() string

func (*ConflictError) Is

func (e *ConflictError) Is(target error) bool

type Error

type Error struct {
	Provider string
	Status   int
	Message  string
}

Error is a provider failure with the provider's own message.

func (*Error) Error

func (e *Error) Error() string

type Mem

type Mem struct {
	Zone ZoneInfo

	Calls []string
	// Fail, when set, makes the named call ("create", "delete", "update", "records") fail.
	Fail map[string]error
	// contains filtered or unexported fields
}

Mem is an in-memory provider with one zone, for tests of everything that uses a Provider (the real ones are exercised against fake HTTP servers).

func NewMem

func NewMem(zone string, records ...Record) *Mem

func (*Mem) Create

func (m *Mem) Create(_ context.Context, _ string, r Record) (Record, error)

func (*Mem) Delete

func (m *Mem) Delete(_ context.Context, _, id string) error

func (*Mem) Records

func (m *Mem) Records(_ context.Context, _ string) ([]Record, error)

func (*Mem) Snapshot

func (m *Mem) Snapshot() []string

Snapshot lists the records as "TYPE name content", sorted by insertion.

func (*Mem) Update

func (m *Mem) Update(_ context.Context, _, id string, r Record) (Record, error)

func (*Mem) Verify

func (m *Mem) Verify(context.Context) error

func (*Mem) Zones

func (m *Mem) Zones(context.Context) ([]ZoneInfo, error)

type NeededRecord

type NeededRecord struct {
	Type    string `json:"type"`
	Name    string `json:"name"`
	Content string `json:"content"`
	// Zone is the registered domain the record belongs in ("" when none of yours).
	Zone string `json:"zone,omitempty"`
	// Managed: that domain has a provider, so SynCloud can create the record.
	Managed bool `json:"managed"`
}

NeededRecord is a record to create at the DNS of the domain the challenge zone sits under, so that the internet reaches SynCloud's challenge server.

type OriginCA

type OriginCA interface {
	OriginCertificate(ctx context.Context, csrPEM string, hostnames []string, validityDays int) (certPEM string, err error)
}

OriginCA is implemented by providers that issue origin certificates (Cloudflare): the certificate is signed for a CSR and is trusted only behind the provider's proxy.

type Owner

type Owner struct {
	Kind, ID, Purpose string
}

Owner says what a record is for.

type PlanResult

type PlanResult struct {
	Steps []Step `json:"steps"`
}

PlanResult is what a reconcile would do.

func Plan

func Plan(existing []Record, wants []Want, managed map[string]bool) PlanResult

Plan works out what to do to make existing match wants. managed is the set of record IDs the platform created (and so may remove when stale). Only names that appear in wants are touched.

func (PlanResult) Changes

func (p PlanResult) Changes() int

Changes counts the steps that change the zone.

func (PlanResult) Conflicts

func (p PlanResult) Conflicts() []Step

Conflicts lists the steps that need a person's confirmation.

type PointInput

type PointInput struct {
	Name    string
	Targets []string // IPv4 and IPv6 addresses
	Proxied *bool
	TTL     int
	Owner   Owner
}

PointInput asks for the records that make a name reach some addresses.

type PointResult

type PointResult struct {
	Plan    PlanResult `json:"plan"`
	Applied *Applied   `json:"applied,omitempty"`
	// Manual lists the records to create by hand when the domain has no provider.
	Manual []Record `json:"manual,omitempty"`
}

PointResult is the plan, and what was done when it was applied.

type Provider

type Provider interface {
	// Verify checks that the credentials work.
	Verify(ctx context.Context) error
	Zones(ctx context.Context) ([]ZoneInfo, error)
	Records(ctx context.Context, zoneID string) ([]Record, error)
	Create(ctx context.Context, zoneID string, r Record) (Record, error)
	Update(ctx context.Context, zoneID, id string, r Record) (Record, error)
	Delete(ctx context.Context, zoneID, id string) error
}

Provider is a DNS API. Cloudflare is the first; others (Route 53, DigitalOcean, Hetzner) can follow without changing the rest.

type ProviderView

type ProviderView struct {
	ID        string    `json:"id"`
	Name      string    `json:"name"`
	Type      string    `json:"type"`
	Status    string    `json:"status"`
	LastError string    `json:"lastError,omitempty"`
	Domains   int       `json:"domains"`
	CreatedAt time.Time `json:"createdAt"`
}

ProviderView is a provider as shown: never the credentials.

type Record

type Record struct {
	ID       string `json:"id"`
	Type     string `json:"type"`
	Name     string `json:"name"` // the full name, no trailing dot
	Content  string `json:"content"`
	TTL      int    `json:"ttl"` // seconds; 1 = automatic
	Proxied  bool   `json:"proxied"`
	Priority *int   `json:"priority,omitempty"` // MX, SRV
	Comment  string `json:"comment,omitempty"`
}

Record is one DNS record as a provider holds it.

type RecordFilter

type RecordFilter struct{ Type, Name, Q string }

RecordFilter narrows a listing.

type RecordView

type RecordView struct {
	Record
	Managed bool `json:"managed"`
}

RecordView is a record with whether the platform created it.

type RemoteZone

type RemoteZone struct {
	ZoneInfo
	Registered bool `json:"registered"`
}

RemoteZone is a zone a provider can manage.

type ServerView

type ServerView struct {
	acmedns.Status
	Needed []NeededRecord `json:"needed"`
	// Domains are the registered domains whose challenges it answers.
	Domains []string `json:"domains"`
}

ServerView is the challenge server as shown.

type Service

type Service struct {

	// CloudflareBase overrides Cloudflare's API address (tests, a lab).
	CloudflareBase string
	HTTPClient     *http.Client
	// Resolvers answer lookups and the challenge checks (default: public ones).
	Resolvers []string
	// Factory builds a provider; tests replace it.
	Factory func(typ, token string) (Provider, error)
	// Builtin is SynCloud's own challenge server (nil in tests that do not need it).
	Builtin *acmedns.Server
	// OnChange runs after a domain is added, changed or removed.
	OnChange func()
	// contains filtered or unexported fields
}

Service is the domains and DNS manager.

func NewService

func NewService(st *store.Store, box *secrets.Box, log *slog.Logger) *Service

func (*Service) AddProvider

func (s *Service) AddProvider(ctx context.Context, name, typ, token string) (ProviderView, error)

AddProvider connects a provider after checking that its token works.

func (*Service) AddZone

func (s *Service) AddZone(ctx context.Context, in AddZoneInput) (ZoneView, error)

func (*Service) Allowed

func (s *Service) Allowed(ctx context.Context, project, host string) error

Allowed says whether a project may use a host (a wildcard host starts with "*."). Names outside every registered domain are free, as before.

func (*Service) Challenge

func (s *Service) Challenge(ctx context.Context, host string) ChallengeRoute

Challenge is Route plus what public resolvers show of the delegating CNAME.

func (*Service) ChallengeServer

func (s *Service) ChallengeServer(ctx context.Context) (ServerView, error)

ChallengeServer shows SynCloud's own challenge server.

func (*Service) CheckChallengeServer

func (s *Service) CheckChallengeServer(ctx context.Context) ([]Check, error)

CheckChallengeServer tests the server from the outside, as far as it can: it listens, the zone's NS record and its glue are visible, and a probe TXT value comes back through public resolvers (which proves port 53 is open).

func (*Service) Cleanup

func (s *Service) Cleanup(ctx context.Context, zone string, apply bool) (CleanupResult, error)

func (*Service) ConfigureChallengeServer

func (s *Service) ConfigureChallengeServer(ctx context.Context, zone, ns, ip string) (ServerView, error)

ConfigureChallengeServer sets the challenge zone (empty switches the server off). ns defaults from the zone; ip must be given (the API fills it with the controller's address).

func (*Service) CreateChallengeServerRecords

func (s *Service) CreateChallengeServerRecords(ctx context.Context, replace bool) (int, error)

CreateChallengeServerRecords makes the records that point the internet at the server, in the domains that have a provider. Others are left to you.

func (*Service) CreateRecord

func (s *Service) CreateRecord(ctx context.Context, zone string, r Record) (Record, error)

CreateRecord adds a record. An exact duplicate is refused, and so is a CNAME beside other records, with the record that is in the way.

func (*Service) DeleteRecord

func (s *Service) DeleteRecord(ctx context.Context, zone, id string) error

func (*Service) DeleteTXT

func (s *Service) DeleteTXT(ctx context.Context, name, id string) error

DeleteTXT removes a challenge record the platform created.

func (*Service) EnsureDelegation

func (s *Service) EnsureDelegation(ctx context.Context, host string, replace bool) (ChallengeRoute, error)

EnsureDelegation creates the CNAME of a delegated name when the domain has a provider (a manual domain's CNAME is made by hand). It keeps the CNAME: it is set once. Somebody else's records on the name are left alone unless replace is true.

func (*Service) ListProviders

func (s *Service) ListProviders(ctx context.Context) ([]ProviderView, error)

func (*Service) Lookup

func (s *Service) Lookup(ctx context.Context, name, qtype, via string) ([]Answer, error)

Lookup answers a query from public and authoritative servers.

func (*Service) LookupResolvers

func (s *Service) LookupResolvers() []string

LookupResolvers are what propagation checks ask.

func (*Service) Managed

func (s *Service) Managed(ctx context.Context, name string) bool

Managed reports whether the platform can write records for a name (its domain has a provider).

func (*Service) OriginCA

func (s *Service) OriginCA(ctx context.Context, providerID string) (OriginCA, error)

OriginCA returns the origin-certificate API of a provider, if it has one.

func (*Service) Point

func (s *Service) Point(ctx context.Context, zone string, in PointInput, plan, replace bool) (PointResult, error)

Point reconciles the A and AAAA records of a name to targets. plan only computes; replace lets it remove records the platform did not create.

func (*Service) ProviderZones

func (s *Service) ProviderZones(ctx context.Context, id string) ([]RemoteZone, error)

ProviderZones lists the zones a provider can manage and which are registered.

func (*Service) PutTXT

func (s *Service) PutTXT(ctx context.Context, name, value string) (string, error)

PutTXT creates a TXT record for a challenge and returns what to hand to DeleteTXT. A record that is already there is reused.

func (*Service) Records

func (s *Service) Records(ctx context.Context, zone string, f RecordFilter) ([]RecordView, error)

func (*Service) RemoveProvider

func (s *Service) RemoveProvider(ctx context.Context, id string) error

RemoveProvider disconnects a provider. Its domains stay, as manual ones, and certificates are kept.

func (*Service) RemoveZone

func (s *Service) RemoveZone(ctx context.Context, name string) error

RemoveZone unregisters a domain. Its records at the provider stay as they are. Hosts of services under it keep working: grants only matter when adding.

func (*Service) ReplaceToken

func (s *Service) ReplaceToken(ctx context.Context, id, token string) error

ReplaceToken sends a new token for a provider (the old one is never shown).

func (*Service) Route

func (s *Service) Route(ctx context.Context, host string) ChallengeRoute

Route decides where the TXT record of a host's challenge goes. It asks the provider only to follow a CNAME the person already made.

func (*Service) SyncProvider

func (s *Service) SyncProvider(ctx context.Context, id string) (ProviderView, error)

SyncProvider re-checks the token and refreshes its domains' name servers.

func (*Service) UpdateRecord

func (s *Service) UpdateRecord(ctx context.Context, zone, id string, r Record) (Record, error)

func (*Service) UpdateZone

func (s *Service) UpdateZone(ctx context.Context, name string, in UpdateZoneInput) (ZoneView, error)

func (*Service) Zone

func (s *Service) Zone(ctx context.Context, name string) (ZoneView, error)

func (*Service) ZoneFor

func (s *Service) ZoneFor(ctx context.Context, host string) (store.Zone, bool)

ZoneFor returns the registered domain a name is in (the longest match).

func (*Service) Zones

func (s *Service) Zones(ctx context.Context) ([]ZoneView, error)

type Step

type Step struct {
	Action string `json:"action"`
	Reason string `json:"reason"`
	Record Record `json:"record"`
	Detail string `json:"detail,omitempty"`
	// NeedsConfirm is true for removing a record the platform did not create.
	NeedsConfirm bool `json:"needsConfirm,omitempty"`
	// contains filtered or unexported fields
}

Step is one thing the plan does.

type Tracker

type Tracker interface {
	Created(r Record, o Owner) error
	Removed(id string) error
}

Tracker remembers the records the platform created.

type UpdateZoneInput

type UpdateZoneInput struct {
	Provider         *string // provider id, "" to unlink
	WildcardPolicy   *string
	AuthorityID      *string
	ChallengeZone    *string // a registered domain with a provider, "" to stop delegating
	ChallengeBuiltin *bool   // answer with SynCloud's own server
	Grants           *[]store.ZoneGrant
}

UpdateZoneInput changes a domain; nil fields stay.

type Want

type Want struct {
	Type     string
	Name     string
	Content  string
	TTL      int   // 0: automatic
	Proxied  *bool // nil: leave as it is
	Priority *int
	// Exclusive: the platform owns the whole (type, name) set, so other
	// contents there are stale or in the way. Additive records (the
	// challenge TXT values) only need to be present: others stay.
	Exclusive bool
	Owner     Owner
}

Want is a record the platform wants to exist.

type ZoneInfo

type ZoneInfo struct {
	ID          string   `json:"id"`
	Name        string   `json:"name"`
	Status      string   `json:"status,omitempty"`
	NameServers []string `json:"nameServers,omitempty"`
}

ZoneInfo is a zone a provider can manage.

type ZoneView

type ZoneView struct {
	Name           string   `json:"name"`
	Mode           string   `json:"mode"` // managed | manual
	ProviderID     string   `json:"providerId,omitempty"`
	Provider       string   `json:"provider,omitempty"`
	NameServers    []string `json:"nameServers,omitempty"`
	WildcardPolicy string   `json:"wildcardPolicy"`
	AuthorityID    string   `json:"authorityId,omitempty"`
	// ChallengeZone is the domain whose provider holds this domain's
	// _acme-challenge records (a CNAME delegates them there).
	ChallengeZone string `json:"challengeZone,omitempty"`
	// ChallengeBuiltin: answered by SynCloud's own server although the domain has a provider.
	ChallengeBuiltin bool              `json:"challengeBuiltin,omitempty"`
	Grants           []store.ZoneGrant `json:"grants"`
	CreatedAt        time.Time         `json:"createdAt"`
}

ZoneView is a registered domain as shown.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL