Split the console from the resolver: fancy-dns-console writes the cluster
fancy-dns-console is a second binary holding the web UI, authentication and every edit. It writes ClientGroup, BlockList and DNSZone objects through the new kubeedit package and forwards all other /api routes to a running resolver with its own key, dropping the browser's credentials, so it can run in the cluster or on a workstation with a kubeconfig and nothing about the resolver's placement matters. The resolver never imports kubeedit and the console is not on the DNS path. kubeedit validates every spec with the runtime's own converters (kubesource.CheckGroup/CheckList/CheckZone) before writing, so the console cannot store an object the resolver would reject. Zone edits keep the file-based writer's behaviour: duplicate and below-a-delegation records are refused, a delegation in a new zone also gives the zone its servers, and a zone with no apex NS is never stored. Each object records the editing user in an annotation; updates retry on conflict. The resolver reports groups from ClientGroup objects as source "kubernetes" and counter-only rows (the "(default)" bucket, or a group removed since) as "history", and lists DNSZone zones as the editable ones. The console uses that to leave the YAML's groups alone and to drop history rows, which the UI would otherwise send back on save. Its GET /api/clients overlays the cluster's current objects on the resolver's list, because the resolver only sees an edit after its watch fires and a save made just after another would delete the first. An end-to-end test runs both halves against one fake apiserver: a group saved through the console refuses queries, a zone built record by record answers authoritatively, and a request with the resolver's own key is rejected by the console. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4d38945d94
commit
1a536e7d0e
25 files changed
+1950
-8
No files matched your search
@@ -0,0 +1,120 @@
|
||||
// Package console is the editing and viewing half of fancy-dns, split from the
|
||||
// resolver so that it can run somewhere else. It owns authentication and the
|
||||
// web UI, writes ClientGroup, BlockList and DNSZone objects to the cluster, and
|
||||
// forwards everything the resolver owns (statistics, the query log, the cache)
|
||||
// to the resolver's admin API.
|
||||
//
|
||||
// The resolver never calls the console and the console is never on the DNS
|
||||
// path: stopping it cannot affect a query.
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/api"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/kubeedit"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/web"
|
||||
)
|
||||
|
||||
// Options configure a Console.
|
||||
type Options struct {
|
||||
Config *config.Store
|
||||
Runtime *Runtime
|
||||
Editor *kubeedit.Editor
|
||||
Logger *slog.Logger
|
||||
Version string
|
||||
}
|
||||
|
||||
// Console serves the UI and the edit API.
|
||||
type Console struct {
|
||||
opt Options
|
||||
log *slog.Logger
|
||||
api *api.Server
|
||||
started time.Time
|
||||
}
|
||||
|
||||
// New builds a Console.
|
||||
func New(opt Options) (*Console, error) {
|
||||
if opt.Config == nil || opt.Runtime == nil || opt.Editor == nil {
|
||||
return nil, errors.New("console: config, runtime and editor are required")
|
||||
}
|
||||
if opt.Logger == nil {
|
||||
opt.Logger = slog.Default()
|
||||
}
|
||||
c := &Console{opt: opt, log: opt.Logger.With("component", "console"), started: time.Now()}
|
||||
srv, err := api.New(c.hooks())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.api = srv
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// actor names who is making a request, for the object annotation.
|
||||
func actor(ctx context.Context) string {
|
||||
if p, ok := api.PrincipalFrom(ctx); ok && p.Name != "" {
|
||||
return p.Name
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Handler is the whole HTTP surface: the console's own routes, the resolver's
|
||||
// API behind the same authentication, and the single-page app.
|
||||
func (c *Console) Handler() (http.Handler, error) {
|
||||
cfg := c.opt.Config.Get()
|
||||
base := strings.TrimSuffix(cfg.API.BasePath, "/")
|
||||
own := c.api.Handler()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
// Handled by the shared API server: authentication, the identity of the
|
||||
// caller, and the edits whose hooks write to the cluster.
|
||||
for _, p := range []string{
|
||||
base + "/auth/",
|
||||
"GET " + base + "/whoami",
|
||||
"GET " + base + "/healthz",
|
||||
"PUT " + base + "/clients",
|
||||
"POST " + base + "/zones/records",
|
||||
"PUT " + base + "/zones/records",
|
||||
"DELETE " + base + "/zones/records",
|
||||
"POST " + base + "/zones/delegations",
|
||||
"DELETE " + base + "/zones/delegations",
|
||||
"DELETE " + base + "/zones",
|
||||
"POST " + base + "/blocklists/toggle",
|
||||
} {
|
||||
mux.Handle(p, own)
|
||||
}
|
||||
|
||||
// Reads that combine the cluster's objects with the resolver's view.
|
||||
mux.Handle("GET "+base+"/zones", c.api.Protect(http.HandlerFunc(c.handleZones), false))
|
||||
mux.Handle("GET "+base+"/clients", c.api.Protect(http.HandlerFunc(c.handleClients), false))
|
||||
mux.Handle("GET "+base+"/blocklist-sources", c.api.Protect(http.HandlerFunc(c.handleListSources), false))
|
||||
mux.Handle("PUT "+base+"/blocklist-sources/{name}", c.api.Protect(http.HandlerFunc(c.handleListSourcePut), true))
|
||||
mux.Handle("DELETE "+base+"/blocklist-sources/{name}", c.api.Protect(http.HandlerFunc(c.handleListSourceDelete), true))
|
||||
|
||||
// Everything else under the API belongs to the resolver.
|
||||
proxy := c.opt.Runtime.Proxy()
|
||||
read, write := c.api.Protect(proxy, false), c.api.Protect(proxy, true)
|
||||
mux.Handle(base+"/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodGet || r.Method == http.MethodHead {
|
||||
read.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
write.ServeHTTP(w, r)
|
||||
}))
|
||||
|
||||
if cfg.API.UI {
|
||||
ui, err := web.Handler("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("web console: %w", err)
|
||||
}
|
||||
mux.Handle("/", ui)
|
||||
}
|
||||
return mux, nil
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/api"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/config"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/kubeedit"
|
||||
"git.k8s-git-k6n.net/mats/fancy-dns/internal/kubesource"
|
||||
)
|
||||
|
||||
// hooks wires the api package's edit endpoints to the cluster. Only the hooks
|
||||
// the console owns are set: the api server never sees the others, because the
|
||||
// router sends those routes to the resolver.
|
||||
func (c *Console) hooks() api.Hooks {
|
||||
return api.Hooks{
|
||||
Store: c.opt.Config,
|
||||
Logger: c.log,
|
||||
Version: c.opt.Version,
|
||||
StartedAt: c.started,
|
||||
Health: c.health,
|
||||
|
||||
PutACL: c.putACL,
|
||||
ToggleBlocklist: c.toggleBlocklist,
|
||||
AddZoneRecord: c.addZoneRecord,
|
||||
PutZoneRecord: c.putZoneRecord,
|
||||
DeleteZoneRecord: c.deleteZoneRecord,
|
||||
AddZoneDelegation: c.addZoneDelegation,
|
||||
DeleteZoneDelegation: c.deleteZoneDelegation,
|
||||
DeleteZone: c.deleteZone,
|
||||
}
|
||||
}
|
||||
|
||||
// health reports the console itself. The resolver has its own /healthz; a dead
|
||||
// resolver must not make the console look dead, because the console is how an
|
||||
// operator finds out.
|
||||
func (c *Console) health() any {
|
||||
return map[string]any{"status": "ok", "component": "console", "version": c.opt.Version}
|
||||
}
|
||||
|
||||
// clientsView is the part of the resolver's /api/clients answer the console
|
||||
// reads.
|
||||
type clientsView struct {
|
||||
Groups []struct {
|
||||
Name string `json:"name"`
|
||||
Source string `json:"source"`
|
||||
} `json:"groups"`
|
||||
DefaultPolicy string `json:"default_policy"`
|
||||
}
|
||||
|
||||
func (c *Console) putACL(ctx context.Context, groups []config.Group, def string) (int64, error) {
|
||||
var view clientsView
|
||||
if err := c.opt.Runtime.Get(ctx, "/api/clients", &view); err != nil {
|
||||
// Without the resolver's list the console cannot tell the groups that
|
||||
// live in the resolver's YAML from its own, and guessing would create
|
||||
// objects that shadow them.
|
||||
return 0, err
|
||||
}
|
||||
if def != "" && def != view.DefaultPolicy {
|
||||
return 0, fmt.Errorf("default_policy is resolver configuration (currently %q), not a ClientGroup; change it in the resolver's config", view.DefaultPolicy)
|
||||
}
|
||||
inFile := map[string]bool{}
|
||||
for _, g := range view.Groups {
|
||||
if g.Source == "" {
|
||||
inFile[g.Name] = true
|
||||
}
|
||||
}
|
||||
res, err := c.opt.Editor.SyncGroups(ctx, groups, func(n string) bool { return inFile[n] }, actor(ctx))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
c.log.Info("client groups saved", "by", actor(ctx), "created", res.Created, "updated", res.Updated, "deleted", res.Deleted)
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (c *Console) toggleBlocklist(name string, enabled bool) error {
|
||||
// The api hook has no context; an edit is short and bounded by the client.
|
||||
err := c.opt.Editor.SetListDisabled(context.Background(), name, !enabled, "")
|
||||
if errors.Is(err, kubeedit.ErrNotFound) {
|
||||
return fmt.Errorf("no BlockList named %q (a list defined in the resolver's config is toggled there)", name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func recordInput(in api.ZoneRecordInput) kubeedit.RecordInput {
|
||||
return kubeedit.RecordInput{Name: in.Name, Type: in.Type, TTL: in.TTL, Value: in.Value}
|
||||
}
|
||||
|
||||
func zoneResponse(res kubeedit.WriteResult) api.ZoneWriteResponse {
|
||||
return api.ZoneWriteResponse{OK: true, Zone: res.Zone, Serial: res.Serial}
|
||||
}
|
||||
|
||||
func (c *Console) addZoneRecord(ctx context.Context, in api.ZoneRecordInput) (any, error) {
|
||||
res, err := c.opt.Editor.AddRecord(ctx, in.Zone, recordInput(in), actor(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zoneResponse(res), nil
|
||||
}
|
||||
|
||||
func (c *Console) putZoneRecord(ctx context.Context, in api.ZoneRecordInput) (any, error) {
|
||||
res, err := c.opt.Editor.PutRecord(ctx, in.Zone, recordInput(in), actor(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zoneResponse(res), nil
|
||||
}
|
||||
|
||||
func (c *Console) deleteZoneRecord(ctx context.Context, zone, name, rrtype, value string) error {
|
||||
_, err := c.opt.Editor.DeleteRecord(ctx, zone, name, rrtype, value, actor(ctx))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Console) addZoneDelegation(ctx context.Context, in api.ZoneDelegationInput) (any, error) {
|
||||
targets := make([]string, 0, len(in.Targets))
|
||||
for _, t := range in.Targets {
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
targets = append(targets, t)
|
||||
}
|
||||
}
|
||||
res, err := c.opt.Editor.SetDelegation(ctx, in.Zone, in.Name, targets, in.TTL, actor(ctx))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zoneResponse(res), nil
|
||||
}
|
||||
|
||||
func (c *Console) deleteZoneDelegation(ctx context.Context, zone, name string) error {
|
||||
_, err := c.opt.Editor.RemoveDelegation(ctx, zone, name, actor(ctx))
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Console) deleteZone(ctx context.Context, zone string) error {
|
||||
return c.opt.Editor.DeleteZone(ctx, zone)
|
||||
}
|
||||
|
||||
// handleZones is the resolver's zone view with the console's editing
|
||||
// capability stated truthfully: the resolver cannot write DNSZone objects, so
|
||||
// it reports its zones read-only, and it is the console that can.
|
||||
func (c *Console) handleZones(w http.ResponseWriter, r *http.Request) {
|
||||
var view map[string]any
|
||||
if err := c.opt.Runtime.Get(r.Context(), "/api/zones", &view); err != nil {
|
||||
api.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
view["writable"] = true
|
||||
view["managed_dir"] = "kubernetes namespace " + c.opt.Editor.Namespace()
|
||||
api.WriteJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
// handleClients is the resolver's group list (with its live counters), made
|
||||
// consistent with the cluster. A ClientGroup the resolver has not picked up
|
||||
// yet is added; one that has just been deleted is dropped. Without this a
|
||||
// save made a moment after another would not see the first one and would
|
||||
// delete it.
|
||||
func (c *Console) handleClients(w http.ResponseWriter, r *http.Request) {
|
||||
var view map[string]any
|
||||
if err := c.opt.Runtime.Get(r.Context(), "/api/clients", &view); err != nil {
|
||||
api.WriteError(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
objs, err := c.opt.Editor.Groups(r.Context())
|
||||
if err != nil {
|
||||
api.WriteError(w, http.StatusBadGateway, "cluster: "+err.Error())
|
||||
return
|
||||
}
|
||||
inCluster := make(map[string]kubeedit.GroupObject, len(objs))
|
||||
for _, o := range objs {
|
||||
inCluster[o.Name] = o
|
||||
}
|
||||
groups, _ := view["groups"].([]any)
|
||||
var merged []any
|
||||
seen := map[string]bool{}
|
||||
for _, g := range groups {
|
||||
m, _ := g.(map[string]any)
|
||||
name, _ := m["name"].(string)
|
||||
src, _ := m["source"].(string)
|
||||
if src == "history" {
|
||||
// Counters for a name that is not a group (the default bucket, or
|
||||
// one removed since). Saving it back would try to create it.
|
||||
continue
|
||||
}
|
||||
if src == "kubernetes" {
|
||||
if _, still := inCluster[name]; !still {
|
||||
continue // deleted a moment ago; the resolver has not noticed
|
||||
}
|
||||
}
|
||||
seen[name] = true
|
||||
merged = append(merged, g)
|
||||
}
|
||||
// The resolver's list is in evaluation order: its file's groups, then the
|
||||
// cluster's by priority. Groups it has not seen yet go at the end, in
|
||||
// priority order.
|
||||
for _, o := range objs {
|
||||
if seen[o.Name] {
|
||||
continue
|
||||
}
|
||||
merged = append(merged, groupJSON(o))
|
||||
}
|
||||
view["groups"] = merged
|
||||
api.WriteJSON(w, http.StatusOK, view)
|
||||
}
|
||||
|
||||
// groupJSON renders a ClientGroup in the shape the resolver reports groups.
|
||||
func groupJSON(o kubeedit.GroupObject) map[string]any {
|
||||
s := o.Spec
|
||||
nz := func(v []string) []string {
|
||||
if v == nil {
|
||||
return []string{}
|
||||
}
|
||||
return v
|
||||
}
|
||||
return map[string]any{
|
||||
"name": o.Name, "comment": s.Comment, "policy": s.Policy,
|
||||
"match": map[string]any{
|
||||
"cidrs": nz(s.Match.CIDRs), "ptr_suffixes": nz(s.Match.PTRSuffixes),
|
||||
"tags": nz(s.Match.Tags), "any": s.Match.Any,
|
||||
},
|
||||
"allow_domains": nz(s.AllowDomains), "deny_domains": nz(s.DenyDomains),
|
||||
"skip_blocklist": s.SkipBlocklist, "skip_cache": s.SkipCache,
|
||||
"rate_limit": s.RateLimit, "max_concurrent": s.MaxConcurrent,
|
||||
"log_queries": s.LogQueries, "upstreams": nz(s.Upstreams),
|
||||
"client_count": 0, "query_count": 0, "blocked_count": 0, "matched": false,
|
||||
"source": "kubernetes",
|
||||
}
|
||||
}
|
||||
|
||||
// listSourceView is a BlockList as the console reports it.
|
||||
type listSourceView struct {
|
||||
Name string `json:"name"`
|
||||
Spec kubesource.BlockListSpec `json:"spec"`
|
||||
}
|
||||
|
||||
func (c *Console) handleListSources(w http.ResponseWriter, r *http.Request) {
|
||||
ls, err := c.opt.Editor.Lists(r.Context())
|
||||
if err != nil {
|
||||
api.WriteError(w, http.StatusBadGateway, "cluster: "+err.Error())
|
||||
return
|
||||
}
|
||||
out := make([]listSourceView, 0, len(ls))
|
||||
for _, l := range ls {
|
||||
out = append(out, listSourceView{Name: l.Name, Spec: l.Spec})
|
||||
}
|
||||
api.WriteJSON(w, http.StatusOK, map[string]any{"sources": out})
|
||||
}
|
||||
|
||||
func (c *Console) handleListSourcePut(w http.ResponseWriter, r *http.Request) {
|
||||
var spec kubesource.BlockListSpec
|
||||
if err := api.DecodeJSON(r, &spec); err != nil {
|
||||
api.WriteError(w, http.StatusBadRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
name := r.PathValue("name")
|
||||
if err := c.opt.Editor.PutList(r.Context(), name, spec, actor(r.Context())); err != nil {
|
||||
api.WriteError(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
api.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name})
|
||||
}
|
||||
|
||||
func (c *Console) handleListSourceDelete(w http.ResponseWriter, r *http.Request) {
|
||||
name := r.PathValue("name")
|
||||
if err := c.opt.Editor.DeleteList(r.Context(), name); err != nil {
|
||||
code := http.StatusBadRequest
|
||||
if errors.Is(err, kubeedit.ErrNotFound) {
|
||||
code = http.StatusNotFound
|
||||
}
|
||||
api.WriteError(w, code, err.Error())
|
||||
return
|
||||
}
|
||||
api.WriteJSON(w, http.StatusOK, map[string]any{"ok": true, "name": name})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package console
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Runtime is the resolver's admin API as the console sees it. The console never
|
||||
// reads the resolver's state any other way: everything it shows that the
|
||||
// resolver owns (statistics, query log, cache, health) comes through here.
|
||||
type Runtime struct {
|
||||
base *url.URL
|
||||
key string
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
// NewRuntime points at a resolver's admin API, e.g. http://fancy-dns.dns:9053.
|
||||
// key is sent as X-API-Key; the console's own users never see it.
|
||||
func NewRuntime(rawURL, key string) (*Runtime, error) {
|
||||
u, err := url.Parse(rawURL)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
|
||||
return nil, fmt.Errorf("runtime URL %q must be http(s)://host[:port]", rawURL)
|
||||
}
|
||||
u.Path = strings.TrimSuffix(u.Path, "/")
|
||||
return &Runtime{base: u, key: key, hc: &http.Client{Timeout: 10 * time.Second}}, nil
|
||||
}
|
||||
|
||||
// Get fetches path (e.g. "/api/zones") and decodes the JSON answer into v.
|
||||
func (r *Runtime) Get(ctx context.Context, path string, v any) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.base.String()+path, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.key != "" {
|
||||
req.Header.Set("X-API-Key", r.key)
|
||||
}
|
||||
res, err := r.hc.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolver unreachable: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
body, _ := io.ReadAll(io.LimitReader(res.Body, 32<<20))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("resolver answered %d: %s", res.StatusCode, strings.TrimSpace(string(body)))
|
||||
}
|
||||
return json.Unmarshal(body, v)
|
||||
}
|
||||
|
||||
// Proxy forwards a request to the resolver unchanged except for credentials:
|
||||
// whatever the browser sent is dropped and the console's own key is used.
|
||||
// Streaming responses (the live query log) are flushed as they arrive.
|
||||
func (r *Runtime) Proxy() http.Handler {
|
||||
p := &httputil.ReverseProxy{
|
||||
Rewrite: func(pr *httputil.ProxyRequest) {
|
||||
pr.SetURL(r.base)
|
||||
h := pr.Out.Header
|
||||
for _, k := range []string{"Cookie", "Authorization", "X-Api-Key", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "Forwarded", "Origin", "Referer"} {
|
||||
h.Del(k)
|
||||
}
|
||||
if r.key != "" {
|
||||
h.Set("X-API-Key", r.key)
|
||||
}
|
||||
},
|
||||
FlushInterval: -1,
|
||||
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": "resolver unreachable: " + err.Error()})
|
||||
},
|
||||
}
|
||||
return p
|
||||
}
|
||||
Reference in new issue
Block a user