Add backups, token expiry warnings and name server checks
- Daily database backups: jarl-backup.timer runs 'jarld backup', which writes jarl-<UTC time>.db into backup.dir, checks it before naming it, and prunes by the time in the name while always keeping the newest keep_at_least. New backup: section in jarl.yaml; the dashboard and 'jarl status' show the newest backup and warn when it is stale or failed. The Debian package enables the timer. - 'jarld restore [FILE | latest]': checks the backup, shows it next to the current database, keeps the current one aside and records the restore. 'jarld serve' holds a database lock, so a restore can't run under a live jarld and two jarlds can't share a database. - Token expiry warnings from 14 days ahead: dashboard, token lists, a daily log line, and a CLI warning via the Jarl-Token-Expires header; 'jarl token list --expiring'. - 'jarl zone serials' and the zone page's Name servers tab: compare the serial on a primary zone's secondaries (NS records, also-notify) or a secondary zone's primaries with this server's. - 'jarl zone delegation': for zones on the internet, check the parent's delegation and glue against the zone; an undelegated zone gets a note. - Server: Jarl/<version> header; CLI exit code 2 for failed checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1afed741bf
commit
293e6ddd33
47 files changed
+3717
-95
No files matched your search
@@ -6,10 +6,12 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"jarl/internal/api"
|
||||
"jarl/internal/auth"
|
||||
"jarl/internal/model"
|
||||
"jarl/internal/store"
|
||||
@@ -79,11 +81,12 @@ func (l *rateLimiter) cleanup() {
|
||||
}
|
||||
}
|
||||
|
||||
// throttle allows an event once a minute per key (for log lines that
|
||||
// could otherwise repeat on every request).
|
||||
// throttle allows an event once per interval (every, a minute if unset)
|
||||
// per key, for log lines that could otherwise repeat on every request.
|
||||
type throttle struct {
|
||||
mu sync.Mutex
|
||||
last map[string]time.Time
|
||||
every time.Duration
|
||||
mu sync.Mutex
|
||||
last map[string]time.Time
|
||||
}
|
||||
|
||||
func (t *throttle) allow(key string, now time.Time) bool {
|
||||
@@ -92,11 +95,15 @@ func (t *throttle) allow(key string, now time.Time) bool {
|
||||
if t.last == nil {
|
||||
t.last = map[string]time.Time{}
|
||||
}
|
||||
if now.Sub(t.last[key]) < time.Minute {
|
||||
every := t.every
|
||||
if every == 0 {
|
||||
every = time.Minute
|
||||
}
|
||||
if now.Sub(t.last[key]) < every {
|
||||
return false
|
||||
}
|
||||
for k, v := range t.last {
|
||||
if now.Sub(v) > time.Hour {
|
||||
if now.Sub(v) > every+time.Hour {
|
||||
delete(t.last, k)
|
||||
}
|
||||
}
|
||||
@@ -206,12 +213,46 @@ func (s *Server) tokenPrincipal(ctx context.Context, tok, ip, agent string) (*au
|
||||
if t.LastUsedAt == nil || now.Sub(*t.LastUsedAt) > time.Minute || t.LastUsedIP != ip {
|
||||
s.store.TouchToken(ctx, t.ID, ip)
|
||||
}
|
||||
s.warnTokenExpiry(t, ip, now)
|
||||
if previous && s.oldSecretWarn.allow(fmt.Sprintf("%d %s", t.ID, ip), now) {
|
||||
s.log.Warn("token used with its old secret; update this client before the grace period ends", "token_id", t.ID, "token", t.Username+"/"+t.Name, "ip", ip, "valid_until", t.PrevExpiresAt.Format(time.RFC3339))
|
||||
}
|
||||
return &auth.Principal{User: u, Token: t, Method: "token", IP: ip, Agent: agent}, nil
|
||||
}
|
||||
|
||||
// warnTokenExpiry logs, at most once a day per token, that a token in use
|
||||
// expires soon (or has expired). ip is where it was used ("" when found by
|
||||
// the daily check).
|
||||
func (s *Server) warnTokenExpiry(t *model.Token, ip string, now time.Time) {
|
||||
if !t.ExpiresWithin(now, model.TokenExpiryWarning) || !s.expiryWarn.allow(strconv.FormatInt(t.ID, 10), now) {
|
||||
return
|
||||
}
|
||||
args := []any{"token_id", t.ID, "token", t.Username + "/" + t.Name, "expires_at", t.ExpiresAt.Format(time.RFC3339)}
|
||||
if ip != "" {
|
||||
args = append(args, "ip", ip)
|
||||
}
|
||||
msg := "API token expires soon; give it a new lifetime with 'jarl token rotate'"
|
||||
if now.After(*t.ExpiresAt) {
|
||||
msg = "API token has expired; anything still using it is refused (rotate it with 'jarl token rotate')"
|
||||
}
|
||||
s.log.Warn(msg, args...)
|
||||
}
|
||||
|
||||
// warnExpiringTokens runs warnTokenExpiry for every token (from
|
||||
// housekeeping), so tokens that are rarely used are reported too. Tokens
|
||||
// that expired more than TokenExpiryWarning ago are no longer reported.
|
||||
func (s *Server) warnExpiringTokens(ctx context.Context, now time.Time) {
|
||||
ts, err := s.store.ListTokens(ctx, 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
for _, t := range ts {
|
||||
if t.ExpiresAt != nil && now.Sub(*t.ExpiresAt) < model.TokenExpiryWarning {
|
||||
s.warnTokenExpiry(t, "", now)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// authed wraps a handler with authentication and error handling.
|
||||
func (s *Server) authed(h handler) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -221,6 +262,10 @@ func (s *Server) authed(h handler) http.HandlerFunc {
|
||||
s.writeErr(w, r, err, nil)
|
||||
return
|
||||
}
|
||||
if p.Token != nil && p.Token.ExpiresWithin(time.Now(), model.TokenExpiryWarning) {
|
||||
// The CLI warns its user when it sees this.
|
||||
w.Header().Set(api.TokenExpiresHeader, p.Token.ExpiresAt.UTC().Format(time.RFC3339))
|
||||
}
|
||||
ctx := context.WithValue(r.Context(), keyPrincipal, p)
|
||||
if se != nil {
|
||||
ctx = context.WithValue(ctx, keySession, se)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"jarl/internal/api"
|
||||
"jarl/internal/store"
|
||||
)
|
||||
|
||||
// header sends a GET with a token and returns a response header.
|
||||
func (e *apiEnv) header(path, token, name string) string {
|
||||
e.t.Helper()
|
||||
r, _ := http.NewRequest("GET", e.ts.URL+api.Prefix+path, nil)
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := http.DefaultClient.Do(r)
|
||||
if err != nil {
|
||||
e.t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
e.t.Fatalf("GET %s = %d", path, resp.StatusCode)
|
||||
}
|
||||
return resp.Header.Get(name)
|
||||
}
|
||||
|
||||
func TestTokenExpiryWarnings(t *testing.T) {
|
||||
e := newAPIEnv(t)
|
||||
e.do("POST", "/users", e.token, map[string]any{"username": "certbot", "password": "", "grant_strings": []string{"records:write"}}, 201)
|
||||
var uid int64
|
||||
for _, u := range e.list("/users", e.token) {
|
||||
if u["username"] == "certbot" {
|
||||
uid = int64(u["id"].(float64))
|
||||
}
|
||||
}
|
||||
soon := e.do("POST", "/users/"+itoa(uid)+"/tokens", e.token, map[string]any{"name": "soon", "expires_in": "5d"}, 201)
|
||||
later := e.do("POST", "/users/"+itoa(uid)+"/tokens", e.token, map[string]any{"name": "later", "expires_in": "90d"}, 201)
|
||||
revoked := e.do("POST", "/users/"+itoa(uid)+"/tokens", e.token, map[string]any{"name": "gone", "expires_in": "1d"}, 201)
|
||||
e.do("DELETE", "/tokens/"+itoa(int64(revoked["id"].(float64))), e.token, nil, 204)
|
||||
|
||||
// The dashboard lists the expiring token for the administrator...
|
||||
names := func(token string) []string {
|
||||
var out []string
|
||||
for _, t := range e.do("GET", "/status", token, nil, 200)["expiring_tokens"].([]any) {
|
||||
out = append(out, t.(map[string]any)["name"].(string))
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := names(e.token); len(got) != 1 || got[0] != "soon" {
|
||||
t.Errorf("admin's expiring tokens = %v", got)
|
||||
}
|
||||
// ...and for its own user.
|
||||
if got := names(soon["token"].(string)); len(got) != 1 || got[0] != "soon" {
|
||||
t.Errorf("certbot's expiring tokens = %v", got)
|
||||
}
|
||||
|
||||
// Requests with the expiring token say so (the CLI warns); others don't.
|
||||
if h := e.header("/auth/whoami", soon["token"].(string), api.TokenExpiresHeader); h == "" {
|
||||
t.Error("no expiry header for a token that expires in 5 days")
|
||||
} else if exp, err := time.Parse(time.RFC3339, h); err != nil || time.Until(exp) < 4*24*time.Hour {
|
||||
t.Errorf("expiry header %q", h)
|
||||
}
|
||||
if h := e.header("/auth/whoami", later["token"].(string), api.TokenExpiresHeader); h != "" {
|
||||
t.Errorf("expiry header for a 90-day token: %q", h)
|
||||
}
|
||||
if h := e.header("/auth/whoami", e.token, api.TokenExpiresHeader); h != "" {
|
||||
t.Errorf("expiry header for a token without expiry: %q", h)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBackupStatus(t *testing.T) {
|
||||
e := newAPIEnvConfig(t, Config{Version: "test", BackupDir: "/var/backups/jarl", BackupWarnAfter: 48 * time.Hour})
|
||||
backup := func() map[string]any {
|
||||
b, _ := e.do("GET", "/status", e.token, nil, 200)["backup"].(map[string]any)
|
||||
return b
|
||||
}
|
||||
if b := backup(); b == nil || b["last_at"] != nil || b["stale"] != false || b["dir"] != "/var/backups/jarl" {
|
||||
t.Errorf("before any backup: %v", b)
|
||||
}
|
||||
ctx := context.Background()
|
||||
now := time.Now()
|
||||
e.st.RecordBackup(ctx, store.BackupRecord{At: now.Add(-3 * time.Hour), File: "/var/backups/jarl/jarl-x.db", Size: 1234})
|
||||
if b := backup(); b["last_file"] != "/var/backups/jarl/jarl-x.db" || b["stale"] != false || b["last_error"] != nil {
|
||||
t.Errorf("fresh backup: %v", b)
|
||||
}
|
||||
// A failure newer than the last success is reported; an older one isn't.
|
||||
e.st.RecordBackup(ctx, store.BackupRecord{At: now.Add(-time.Hour), Error: "disk full"})
|
||||
if b := backup(); b["last_error"] != "disk full" {
|
||||
t.Errorf("failed backup: %v", b)
|
||||
}
|
||||
e.st.RecordBackup(ctx, store.BackupRecord{At: now.Add(-72 * time.Hour), File: "/var/backups/jarl/jarl-y.db"})
|
||||
e.st.RecordBackup(ctx, store.BackupRecord{At: now.Add(-80 * time.Hour), Error: "old"})
|
||||
if b := backup(); b["stale"] != true || b["last_error"] != nil {
|
||||
t.Errorf("old backup: %v", b)
|
||||
}
|
||||
// Only administrators see it.
|
||||
e.do("POST", "/users", e.token, map[string]any{"username": "viewer", "password": "", "role": "readonly"}, 201)
|
||||
var uid int64
|
||||
for _, u := range e.list("/users", e.token) {
|
||||
if u["username"] == "viewer" {
|
||||
uid = int64(u["id"].(float64))
|
||||
}
|
||||
}
|
||||
tok := e.do("POST", "/users/"+itoa(uid)+"/tokens", e.token, map[string]any{"name": "t"}, 201)["token"].(string)
|
||||
if st := e.do("GET", "/status", tok, nil, 200); st["backup"] != nil {
|
||||
t.Errorf("non-admin sees backups: %v", st["backup"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerHeader(t *testing.T) {
|
||||
e := newAPIEnv(t)
|
||||
if h := e.header("/auth/whoami", e.token, "Server"); h != "Jarl/test" {
|
||||
t.Errorf("Server: %q", h)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
@@ -271,10 +272,55 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request, p *auth.Principa
|
||||
st.Named.Raw = ""
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, api.StatusResponse{Version: s.cfg.Version, Engine: raw(st), Time: time.Now()})
|
||||
now := time.Now()
|
||||
resp := api.StatusResponse{Version: s.cfg.Version, Engine: raw(st), Time: now, ExpiringTokens: s.expiringTokens(r.Context(), p, now)}
|
||||
if p.IsAdmin() {
|
||||
resp.Backup = s.backupStatus(r.Context(), now)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// backupStatus reports the newest backup, as 'jarld backup' recorded it,
|
||||
// and whether it is older than backup.warn_after. No backup at all is
|
||||
// reported but not flagged: backups may be made some other way.
|
||||
func (s *Server) backupStatus(ctx context.Context, now time.Time) *api.BackupStatus {
|
||||
ok, failed := s.store.LastBackups(ctx)
|
||||
bs := &api.BackupStatus{Dir: s.cfg.BackupDir, WarnAfter: int64(s.cfg.BackupWarnAfter / time.Second)}
|
||||
if ok != nil {
|
||||
bs.LastAt, bs.LastFile, bs.LastSize = &ok.At, ok.File, ok.Size
|
||||
bs.Stale = s.cfg.BackupWarnAfter > 0 && now.Sub(ok.At) > s.cfg.BackupWarnAfter
|
||||
}
|
||||
if failed != nil && (ok == nil || failed.At.After(ok.At)) {
|
||||
bs.LastError, bs.LastErrorAt = failed.Error, &failed.At
|
||||
}
|
||||
return bs
|
||||
}
|
||||
|
||||
// expiringTokens lists the tokens the dashboard warns about: those that
|
||||
// expire within model.TokenExpiryWarning or expired less than that long
|
||||
// ago. Administrators see everyone's, others their own.
|
||||
func (s *Server) expiringTokens(ctx context.Context, p *auth.Principal, now time.Time) []api.Token {
|
||||
out := []api.Token{}
|
||||
uid := p.User.ID
|
||||
if p.IsAdmin() {
|
||||
uid = 0
|
||||
} else if uid == 0 {
|
||||
return out
|
||||
}
|
||||
ts, err := s.store.ListTokens(ctx, uid)
|
||||
if err != nil {
|
||||
s.log.Warn("listing tokens failed", "err", err)
|
||||
return out
|
||||
}
|
||||
for _, t := range ts {
|
||||
if t.ExpiresWithin(now, model.TokenExpiryWarning) && now.Sub(*t.ExpiresAt) < model.TokenExpiryWarning {
|
||||
out = append(out, presentToken(t))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Server) systemCheck(w http.ResponseWriter, r *http.Request, p *auth.Principal) error {
|
||||
if err := require(p, auth.Action{Resource: auth.ResOptions}); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
package server
|
||||
|
||||
// Name server checks (internal/nscheck): GET /zones/{zone}/serials and
|
||||
// GET /zones/{zone}/delegation. Both only run when asked for (the zone
|
||||
// page's Name servers tab, 'jarl zone serials' and 'jarl zone
|
||||
// delegation'); nothing checks in the background.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"jarl/internal/api"
|
||||
"jarl/internal/auth"
|
||||
"jarl/internal/dnsname"
|
||||
"jarl/internal/model"
|
||||
"jarl/internal/namedconf"
|
||||
"jarl/internal/nscheck"
|
||||
)
|
||||
|
||||
// checker is the nscheck.Checker the handlers use (tests replace it).
|
||||
func (s *Server) checker() *nscheck.Checker {
|
||||
if s.nsChecker != nil {
|
||||
c := *s.nsChecker
|
||||
return &c
|
||||
}
|
||||
return &nscheck.Checker{}
|
||||
}
|
||||
|
||||
func (s *Server) zoneSerials(w http.ResponseWriter, r *http.Request, p *auth.Principal) error {
|
||||
st, err := s.state(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
z, err := s.zoneByPath(r, st, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp := api.SerialsResponse{Zone: z.Name, View: st.ViewName(z), Type: z.Type, Servers: []nscheck.Result{}, Notes: []string{}}
|
||||
var targets []nscheck.Target
|
||||
switch z.Type {
|
||||
case model.ZonePrimary:
|
||||
targets = append(targets, nsTargets(st, z)...)
|
||||
an, notes := remoteTargets(st, inheritedOption(st, z, "also-notify"), "also-notify")
|
||||
targets = append(targets, an...)
|
||||
resp.Notes = append(resp.Notes, notes...)
|
||||
case model.ZoneSecondary, model.ZoneMirror:
|
||||
pr, notes := remoteTargets(st, st.FindOption(model.ScopeZone, z.ID, "primaries"), "primaries")
|
||||
targets = append(targets, pr...)
|
||||
resp.Notes = append(resp.Notes, notes...)
|
||||
default:
|
||||
return badRequest("only primary, secondary and mirror zones have serials to compare (this is a %s zone)", z.Type)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second)
|
||||
defer cancel()
|
||||
resp.Serial, resp.SerialSource, err = s.localSerial(ctx, st, z)
|
||||
if err != nil {
|
||||
resp.Notes = append(resp.Notes, "named on this server didn't report the zone's serial: "+err.Error())
|
||||
}
|
||||
if len(targets) == 0 {
|
||||
if z.Type == model.ZonePrimary {
|
||||
resp.Notes = append(resp.Notes, "The zone has no NS records or also-notify targets to check.")
|
||||
} else {
|
||||
resp.Notes = append(resp.Notes, "The zone has no primaries to check.")
|
||||
}
|
||||
}
|
||||
if resp.View != "" {
|
||||
resp.Notes = append(resp.Notes, fmt.Sprintf("The zone is in view %s. Other servers answer from the view that matches this server's address (or key), as they do for its zone transfers and NOTIFYs.", resp.View))
|
||||
}
|
||||
resp.Servers = s.checker().Serials(ctx, z.Name, resp.Serial, targets)
|
||||
if len(resp.Servers) > 0 && !hasOther(resp.Servers) {
|
||||
resp.Notes = append(resp.Notes, "Only this server is listed, so there is nothing to compare with.")
|
||||
}
|
||||
resp.CheckedAt = time.Now()
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) zoneDelegation(w http.ResponseWriter, r *http.Request, p *auth.Principal) error {
|
||||
st, err := s.state(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
z, err := s.zoneByPath(r, st, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if z.Type != model.ZonePrimary {
|
||||
return badRequest("the delegation check compares the parent's delegation with the zone's NS records, so it needs a primary zone (this is a %s zone; check it where its primary is)", z.Type)
|
||||
}
|
||||
c := s.checker()
|
||||
if v := r.URL.Query().Get("resolver"); v != "" {
|
||||
// An address only, always port 53: this is a DNS resolver.
|
||||
a, err := netip.ParseAddr(v)
|
||||
if err != nil {
|
||||
return badRequest("resolver must be an IP address, e.g. 1.1.1.1 or 9.9.9.9")
|
||||
}
|
||||
c.Resolver = net.JoinHostPort(a.String(), "53")
|
||||
}
|
||||
var ns []string
|
||||
for _, rec := range st.ZoneRecords(z.ID) {
|
||||
if rec.Type == "NS" && rec.Name == z.Name {
|
||||
ns = append(ns, rec.Data)
|
||||
}
|
||||
}
|
||||
addrs := map[string][]string{}
|
||||
for _, n := range ns {
|
||||
if a := jarlAddresses(st, z.ViewID, dnsname.Fqdn(n)); len(a) > 0 {
|
||||
addrs[dnsname.Fqdn(n)] = a
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
ref, _, _ := s.localSerial(ctx, st, z)
|
||||
resp := api.DelegationResponse{DelegationReport: c.Delegation(ctx, z.Name, ns, addrs, ref), View: st.ViewName(z), Notes: []string{}, CheckedAt: time.Now()}
|
||||
if resp.View != "" {
|
||||
resp.Notes = append(resp.Notes, fmt.Sprintf("Compared with the zone in view %s. Resolvers on the internet get the view that matches their address; make sure that's this one.", resp.View))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
|
||||
// localSerial is the serial this server serves for z: named's, or for a
|
||||
// primary zone Jarl's when named isn't asked.
|
||||
func (s *Server) localSerial(ctx context.Context, st *model.State, z *model.Zone) (*uint32, string, error) {
|
||||
serial, ok, err := s.eng.LoadedSerial(ctx, st, z)
|
||||
if ok {
|
||||
return &serial, "named", nil
|
||||
}
|
||||
if z.Type == model.ZonePrimary {
|
||||
v := z.SOA.Serial
|
||||
return &v, "jarl", err
|
||||
}
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// nsTargets are the name servers in the zone's apex NS records, with the
|
||||
// addresses Jarl has for them in the same view (or nil, to be looked up).
|
||||
func nsTargets(st *model.State, z *model.Zone) []nscheck.Target {
|
||||
var out []nscheck.Target
|
||||
for _, rec := range st.ZoneRecords(z.ID) {
|
||||
if rec.Type != "NS" || rec.Name != z.Name {
|
||||
continue
|
||||
}
|
||||
name := dnsname.Fqdn(rec.Data)
|
||||
out = append(out, nscheck.Target{Name: name, Addresses: jarlAddresses(st, z.ViewID, name), Source: "NS record"})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// jarlAddresses returns the A and AAAA records for name in the primary
|
||||
// zones of a view (nil when Jarl has none).
|
||||
func jarlAddresses(st *model.State, viewID int64, name string) []string {
|
||||
var out []string
|
||||
for _, z := range st.ZonesInView(viewID) {
|
||||
if !z.HasRecords() || !dnsname.IsSubdomain(name, z.Name) {
|
||||
continue
|
||||
}
|
||||
for _, rec := range st.ZoneRecords(z.ID) {
|
||||
if rec.Name == name && (rec.Type == "A" || rec.Type == "AAAA") {
|
||||
out = append(out, rec.Data)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// inheritedOption finds an option for z as named does: the zone's own,
|
||||
// else its view's, else the server's.
|
||||
func inheritedOption(st *model.State, z *model.Zone, name string) *model.Option {
|
||||
if o := st.FindOption(model.ScopeZone, z.ID, name); o != nil {
|
||||
return o
|
||||
}
|
||||
if z.ViewID != 0 {
|
||||
if o := st.FindOption(model.ScopeView, z.ViewID, name); o != nil {
|
||||
return o
|
||||
}
|
||||
}
|
||||
return st.FindOption(model.ScopeOptions, 0, name)
|
||||
}
|
||||
|
||||
// remoteTargets turns an also-notify or primaries option into targets:
|
||||
// addresses with their port and key, following named remote-servers
|
||||
// lists.
|
||||
func remoteTargets(st *model.State, o *model.Option, source string) ([]nscheck.Target, []string) {
|
||||
if o == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var out []nscheck.Target
|
||||
var notes []string
|
||||
var walk func(name, value string, port string, depth int)
|
||||
walk = func(name, value, port string, depth int) {
|
||||
stmt, err := namedconf.ParseOptionValue(name, value)
|
||||
if err != nil {
|
||||
notes = append(notes, fmt.Sprintf("couldn't read %s: %v", name, err))
|
||||
return
|
||||
}
|
||||
vals := stmt.Values()
|
||||
for i := 0; i+1 < len(vals); i++ {
|
||||
if strings.EqualFold(vals[i], "port") {
|
||||
port = vals[i+1]
|
||||
}
|
||||
}
|
||||
blk := stmt.FirstBlock()
|
||||
if blk == nil {
|
||||
return
|
||||
}
|
||||
for _, el := range blk.Stmts {
|
||||
if len(el.Items) == 0 || el.Items[0].Value == nil {
|
||||
continue
|
||||
}
|
||||
first := el.Items[0].Value.Text
|
||||
t := nscheck.Target{Source: source, Port: port}
|
||||
words := el.Values()
|
||||
for i := 0; i+1 < len(words); i++ {
|
||||
switch strings.ToLower(words[i]) {
|
||||
case "port":
|
||||
t.Port = words[i+1]
|
||||
case "key":
|
||||
if k := st.KeyByName(words[i+1]); k != nil {
|
||||
t.Key = &nscheck.Key{Name: k.Name, Algorithm: k.Algorithm, Secret: k.Secret}
|
||||
}
|
||||
}
|
||||
}
|
||||
if a, err := netip.ParseAddr(first); err == nil {
|
||||
t.Addresses = []string{a.String()}
|
||||
out = append(out, t)
|
||||
continue
|
||||
}
|
||||
// A named list of servers.
|
||||
if depth >= 5 {
|
||||
continue
|
||||
}
|
||||
if lo := remoteList(st, first); lo != nil {
|
||||
walk(lo.Name, lo.Value, port, depth+1)
|
||||
} else {
|
||||
notes = append(notes, fmt.Sprintf("%s refers to %q, which isn't an address or a server list Jarl knows", source, first))
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(o.Name, o.Value, "", 0)
|
||||
return out, notes
|
||||
}
|
||||
|
||||
// remoteList finds a top-level remote-servers (or primaries) list.
|
||||
func remoteList(st *model.State, name string) *model.Option {
|
||||
for _, o := range st.ScopedOptions(model.ScopeTopLevel, 0) {
|
||||
switch o.Name {
|
||||
case "remote-servers", "primaries", "masters":
|
||||
if f := strings.Fields(o.Value); len(f) > 0 && strings.Trim(f[0], `"`) == name {
|
||||
return o
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func hasOther(rs []nscheck.Result) bool {
|
||||
for _, r := range rs {
|
||||
if r.Status != "self" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"jarl/internal/nscheck"
|
||||
)
|
||||
|
||||
func TestZoneSerialsTargets(t *testing.T) {
|
||||
e := newAPIEnv(t)
|
||||
// Nothing listens on these addresses' DNS port: every server is
|
||||
// "unreachable" quickly, and the test checks who is asked.
|
||||
e.srv.nsChecker = &nscheck.Checker{Timeout: 200 * time.Millisecond, Port: "1", IsLocal: func(a netip.Addr) bool { return a.String() == "127.0.0.21" }}
|
||||
e.do("POST", "/tsig-keys", e.token, map[string]any{"name": "xfer"}, 201)
|
||||
e.do("POST", "/options", e.token, map[string]any{"scope": "toplevel", "name": "remote-servers", "value": "upstream port 5353 { 127.0.0.31; 127.0.0.32 key xfer; }"}, 201)
|
||||
e.do("POST", "/zones", e.token, map[string]any{
|
||||
"name": "example.com",
|
||||
"nameservers": []string{"ns1.example.com.", "ns2.example.com."},
|
||||
"records": []map[string]any{{"name": "ns1", "type": "A", "data": "127.0.0.21"}, {"name": "ns2", "type": "A", "data": "127.0.0.22"}},
|
||||
"options": []map[string]any{{"name": "also-notify", "value": "{ 127.0.0.23; 127.0.0.24 port 5300 key xfer; }"}},
|
||||
}, 201)
|
||||
e.do("POST", "/zones", e.token, map[string]any{"name": "copy.example", "type": "secondary", "options": []map[string]any{{"name": "primaries", "value": "{ upstream; 127.0.0.33; }"}}}, 201)
|
||||
|
||||
type row struct{ source, status, port string }
|
||||
servers := func(zone string) map[string]row {
|
||||
out := map[string]row{}
|
||||
for _, s := range e.do("GET", "/zones/"+zone+"/serials", e.token, nil, 200)["servers"].([]any) {
|
||||
m := s.(map[string]any)
|
||||
port, _ := m["port"].(string)
|
||||
out[m["address"].(string)] = row{m["source"].(string), m["status"].(string), port}
|
||||
}
|
||||
return out
|
||||
}
|
||||
got := servers("example.com")
|
||||
want := map[string]row{
|
||||
"127.0.0.21": {"NS record", "self", ""},
|
||||
"127.0.0.22": {"NS record", "unreachable", ""},
|
||||
"127.0.0.23": {"also-notify", "unreachable", ""},
|
||||
"127.0.0.24": {"also-notify", "unreachable", "5300"},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("primary zone: %v", got)
|
||||
}
|
||||
for a, w := range want {
|
||||
if got[a] != w {
|
||||
t.Errorf("primary zone, %s: %+v, want %+v", a, got[a], w)
|
||||
}
|
||||
}
|
||||
got = servers("copy.example")
|
||||
want = map[string]row{
|
||||
"127.0.0.31": {"primaries", "unreachable", "5353"},
|
||||
"127.0.0.32": {"primaries", "unreachable", "5353"},
|
||||
"127.0.0.33": {"primaries", "unreachable", ""},
|
||||
}
|
||||
if len(got) != len(want) {
|
||||
t.Errorf("secondary zone: %v", got)
|
||||
}
|
||||
for a, w := range want {
|
||||
if got[a] != w {
|
||||
t.Errorf("secondary zone, %s: %+v, want %+v", a, got[a], w)
|
||||
}
|
||||
}
|
||||
|
||||
// Zone types without serials, and the delegation check's limits.
|
||||
e.do("POST", "/zones", e.token, map[string]any{"name": "fwd.example", "type": "forward", "options": []map[string]any{{"name": "forwarders", "value": "{ 192.0.2.1; }"}}}, 201)
|
||||
e.do("GET", "/zones/fwd.example/serials", e.token, nil, 400)
|
||||
e.do("GET", "/zones/copy.example/delegation", e.token, nil, 400)
|
||||
e.do("GET", "/zones/example.com/delegation?resolver=not-an-ip", e.token, nil, 400)
|
||||
}
|
||||
@@ -65,6 +65,8 @@ func (s *Server) routes() {
|
||||
m.HandleFunc("GET "+p+"/zones/{zone}", s.authed(s.getZone))
|
||||
m.HandleFunc("PATCH "+p+"/zones/{zone}", s.authed(s.updateZone))
|
||||
m.HandleFunc("DELETE "+p+"/zones/{zone}", s.authed(s.deleteZone))
|
||||
m.HandleFunc("GET "+p+"/zones/{zone}/serials", s.authed(s.zoneSerials))
|
||||
m.HandleFunc("GET "+p+"/zones/{zone}/delegation", s.authed(s.zoneDelegation))
|
||||
m.HandleFunc("GET "+p+"/zones/{zone}/file", s.authed(s.zoneFile))
|
||||
m.HandleFunc("POST "+p+"/zones/{zone}/import", s.authed(s.importZoneFile))
|
||||
m.HandleFunc("GET "+p+"/zones/{zone}/records", s.authed(s.listRecords))
|
||||
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"jarl/internal/api"
|
||||
"jarl/internal/auth"
|
||||
"jarl/internal/engine"
|
||||
"jarl/internal/nscheck"
|
||||
"jarl/internal/stats"
|
||||
"jarl/internal/store"
|
||||
)
|
||||
@@ -42,6 +43,10 @@ type Config struct {
|
||||
HTTPReq HTTPReq
|
||||
// Socket is the local unix socket's path ("" for none); see socket.go.
|
||||
Socket string
|
||||
// BackupDir and BackupWarnAfter are the backup settings the dashboard
|
||||
// reports on (backup.dir and backup.warn_after).
|
||||
BackupDir string
|
||||
BackupWarnAfter time.Duration
|
||||
}
|
||||
|
||||
// Server is the HTTP server.
|
||||
@@ -57,6 +62,11 @@ type Server struct {
|
||||
statsQ *stats.Querier
|
||||
// oldSecretWarn limits warnings about rotated tokens' old secrets.
|
||||
oldSecretWarn throttle
|
||||
// expiryWarn limits warnings about expiring tokens to one a day each.
|
||||
expiryWarn throttle
|
||||
// nsChecker, when set, replaces the default name server checker
|
||||
// (tests point it at local DNS servers).
|
||||
nsChecker *nscheck.Checker
|
||||
|
||||
mu sync.Mutex
|
||||
srvs []*http.Server
|
||||
@@ -80,6 +90,7 @@ func New(cfg Config, eng *engine.Engine, log *slog.Logger, web fs.FS) *Server {
|
||||
log = slog.Default()
|
||||
}
|
||||
s := &Server{cfg: cfg, eng: eng, store: eng.Store(), log: log, mux: http.NewServeMux(), limiter: newRateLimiter(), web: web}
|
||||
s.expiryWarn.every = 24 * time.Hour
|
||||
if cfg.Stats != nil {
|
||||
s.statsQ = stats.NewQuerier(cfg.Stats)
|
||||
}
|
||||
@@ -236,6 +247,7 @@ func (s *Server) housekeeping(ctx context.Context) {
|
||||
s.log.Warn("purging sessions failed", "err", err)
|
||||
}
|
||||
s.limiter.cleanup()
|
||||
s.warnExpiringTokens(ctx, time.Now())
|
||||
if s.certs != nil {
|
||||
s.certs.reloadIfChanged()
|
||||
}
|
||||
@@ -330,6 +342,8 @@ func (s *Server) recoverer(next http.Handler) http.Handler {
|
||||
func (s *Server) securityHeaders(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
h := w.Header()
|
||||
// The version is no secret: /healthz reports it too.
|
||||
h.Set("Server", "Jarl/"+s.cfg.Version)
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "no-referrer")
|
||||
|
||||
Reference in new issue
Block a user