Initial bootapi: NetBox-driven PXE/kickstart boot service
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful

bootapi replaces Cobbler's PXE/kickstart side. It resolves a PXE-booting host
from NetBox (by MAC or hostname), renders an iPXE boot script and a kickstart
from Go text/templates, and serves them over HTTP. The ENC half already moved to
encapi; this covers the provisioning/boot half.

What's here:
- cmd/bootapi + internal/{config,model,netbox,render,server}; embedded default
  templates under templates/ (AlmaLinux 9 + Fedora kickstarts, iPXE boot +
  unknown-MAC fallbacks) ported from Cobbler's boot/bootstrap contract.
- NetBox client (v4.x API) behind a Resolver interface with a short-TTL cache;
  tested against httptest fixtures using real NetBox JSON shapes.
- chi HTTP server: /ipxe/{mac}, /boot/ipxe?mac=, /ks/{ident}, healthz/readyz,
  Prometheus /metrics. Unknown MAC -> safe fallback iPXE (200), unknown KS -> 404.
- Secrets (root pw hash, ssh keys) injected at render time from env/Vault, never
  NetBox. Config is env-based per estate convention.
- Makefile (build/test/lint/docker + patch/minor/major), Dockerfile (distroless),
  .woodpecker (pre-commit, golangci-lint v2 + go test -race, docker build on PR;
  image push + Gitea binary release on v* tag), docs/ and example config.

go build/vet clean, go test -race green, golangci-lint v2 clean, pre-commit clean.

Claude-Session: https://claude.ai/code/session_015ur3i7D2azsMAWTSVABApv
This commit is contained in:
2026-07-28 17:20:06 +10:00
parent 98e69d2fcb
commit 274c480b09
37 changed files with 3290 additions and 1 deletions
+89
View File
@@ -0,0 +1,89 @@
package netbox
import (
"context"
"sync"
"sync/atomic"
"time"
"git.unkin.net/unkin/bootapi/internal/model"
)
// Cache wraps a Resolver with a short-TTL in-memory cache. PXE boots come in
// bursts (iPXE fetches the boot script, then the kickstart, then package repos
// hit repeatedly), so even a 30s TTL collapses many NetBox lookups per host
// while keeping the data fresh enough that a re-provisioned host picks up
// changes on its next boot.
type Cache struct {
inner Resolver
ttl time.Duration
now func() time.Time // injectable for tests
mu sync.Mutex
entries map[string]cacheEntry
hits atomic.Int64
misses atomic.Int64
}
// Hits returns the cumulative cache-hit count (published as a metric).
func (c *Cache) Hits() int64 { return c.hits.Load() }
// Misses returns the cumulative cache-miss count (published as a metric).
func (c *Cache) Misses() int64 { return c.misses.Load() }
type cacheEntry struct {
host *model.Host
exp time.Time
}
// NewCache wraps inner with a TTL cache. A non-positive ttl disables caching.
func NewCache(inner Resolver, ttl time.Duration) *Cache {
return &Cache{
inner: inner,
ttl: ttl,
now: time.Now,
entries: map[string]cacheEntry{},
}
}
// HostByMAC returns a cached host or resolves and caches one.
func (c *Cache) HostByMAC(ctx context.Context, mac string) (*model.Host, error) {
return c.lookup(ctx, "mac:"+normalizeMAC(mac), func() (*model.Host, error) {
return c.inner.HostByMAC(ctx, mac)
})
}
// HostByName returns a cached host or resolves and caches one.
func (c *Cache) HostByName(ctx context.Context, name string) (*model.Host, error) {
return c.lookup(ctx, "name:"+name, func() (*model.Host, error) {
return c.inner.HostByName(ctx, name)
})
}
func (c *Cache) lookup(_ context.Context, key string, resolve func() (*model.Host, error)) (*model.Host, error) {
if c.ttl <= 0 {
return resolve()
}
now := c.now()
c.mu.Lock()
if e, ok := c.entries[key]; ok && now.Before(e.exp) {
c.mu.Unlock()
c.hits.Add(1)
return e.host, nil
}
c.mu.Unlock()
c.misses.Add(1)
// Resolve outside the lock so a slow NetBox call doesn't block cache hits.
host, err := resolve()
if err != nil {
return nil, err
}
c.mu.Lock()
c.entries[key] = cacheEntry{host: host, exp: now.Add(c.ttl)}
c.mu.Unlock()
return host, nil
}
+87
View File
@@ -0,0 +1,87 @@
package netbox
import (
"context"
"errors"
"sync"
"testing"
"time"
"git.unkin.net/unkin/bootapi/internal/model"
)
// countingResolver records how many times the underlying resolver is hit.
type countingResolver struct {
mu sync.Mutex
calls int
host *model.Host
err error
}
func (c *countingResolver) HostByMAC(context.Context, string) (*model.Host, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.calls++
return c.host, c.err
}
func (c *countingResolver) HostByName(context.Context, string) (*model.Host, error) {
return c.HostByMAC(context.Background(), "")
}
func TestCacheHitAndExpiry(t *testing.T) {
inner := &countingResolver{host: &model.Host{Hostname: "web01"}}
cache := NewCache(inner, time.Minute)
now := time.Unix(1000, 0)
cache.now = func() time.Time { return now }
// First call misses and resolves.
if _, err := cache.HostByMAC(context.Background(), "aa:bb:cc:00:11:22"); err != nil {
t.Fatal(err)
}
// Second call within TTL is a hit; the inner resolver is not called again.
if _, err := cache.HostByMAC(context.Background(), "AA:BB:CC:00:11:22"); err != nil {
t.Fatal(err)
}
if inner.calls != 1 {
t.Fatalf("inner calls = %d, want 1 (second served from cache)", inner.calls)
}
if cache.Hits() != 1 || cache.Misses() != 1 {
t.Fatalf("hits=%d misses=%d, want 1/1", cache.Hits(), cache.Misses())
}
// Advance past the TTL -> next call misses and re-resolves.
now = now.Add(2 * time.Minute)
if _, err := cache.HostByMAC(context.Background(), "aa:bb:cc:00:11:22"); err != nil {
t.Fatal(err)
}
if inner.calls != 2 {
t.Fatalf("inner calls = %d, want 2 after expiry", inner.calls)
}
}
func TestCacheDisabled(t *testing.T) {
inner := &countingResolver{host: &model.Host{Hostname: "web01"}}
cache := NewCache(inner, 0) // ttl <= 0 disables caching
for i := 0; i < 3; i++ {
if _, err := cache.HostByMAC(context.Background(), "aa:bb:cc:00:11:22"); err != nil {
t.Fatal(err)
}
}
if inner.calls != 3 {
t.Fatalf("inner calls = %d, want 3 (cache disabled)", inner.calls)
}
}
func TestCacheDoesNotCacheErrors(t *testing.T) {
inner := &countingResolver{err: ErrNotFound}
cache := NewCache(inner, time.Minute)
for i := 0; i < 2; i++ {
if _, err := cache.HostByMAC(context.Background(), "de:ad:be:ef:00:00"); !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
if inner.calls != 2 {
t.Fatalf("inner calls = %d, want 2 (errors are not cached)", inner.calls)
}
}
+423
View File
@@ -0,0 +1,423 @@
// Package netbox resolves a PXE-booting machine (by MAC or hostname) into the
// normalized model.Host that bootapi renders templates against. It talks to the
// NetBox REST API (v4.x) behind the Resolver interface so the server can be
// tested with an httptest fake.
package netbox
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strings"
"time"
"git.unkin.net/unkin/bootapi/internal/model"
)
// ErrNotFound is returned when NetBox has no device matching the query. The
// server maps it to an HTTP 404 (and, for iPXE, a safe fallback boot script).
var ErrNotFound = errors.New("netbox: device not found")
// Resolver turns a MAC or hostname into a fully-resolved Host.
type Resolver interface {
HostByMAC(ctx context.Context, mac string) (*model.Host, error)
HostByName(ctx context.Context, name string) (*model.Host, error)
}
// Client is the HTTP-backed Resolver.
type Client struct {
baseURL string
token string
http *http.Client
}
// Options configures a Client.
type Options struct {
BaseURL string
Token string
Timeout time.Duration
Insecure bool
// HTTPClient overrides the constructed client (used by tests).
HTTPClient *http.Client
}
// New builds a NetBox Client.
func New(o Options) *Client {
hc := o.HTTPClient
if hc == nil {
tr := &http.Transport{}
if o.Insecure {
tr.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} //nolint:gosec // opt-in dev flag
}
timeout := o.Timeout
if timeout == 0 {
timeout = 5 * time.Second
}
hc = &http.Client{Timeout: timeout, Transport: tr}
}
return &Client{
baseURL: strings.TrimRight(o.BaseURL, "/"),
token: o.Token,
http: hc,
}
}
// --- NetBox API JSON shapes (only the fields bootapi consumes) ---
type nbList[T any] struct {
Count int `json:"count"`
Results []T `json:"results"`
}
type nbRef struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
}
type nbVLAN struct {
VID int `json:"vid"`
Name string `json:"name"`
}
type nbMAC struct {
MACAddress string `json:"mac_address"`
}
type nbDevice struct {
ID int `json:"id"`
Name string `json:"name"`
Platform *nbRef `json:"platform"`
Role *nbRef `json:"role"`
Site *nbRef `json:"site"`
PrimaryIP *nbIPRef `json:"primary_ip"`
CustomFields map[string]any `json:"custom_fields"`
}
type nbIPRef struct {
Address string `json:"address"`
}
type nbInterface struct {
ID int `json:"id"`
Name string `json:"name"`
MACAddress string `json:"mac_address"`
PrimaryMACAddress *nbMAC `json:"primary_mac_address"`
UntaggedVLAN *nbVLAN `json:"untagged_vlan"`
Device *nbRef `json:"device"`
}
func (i nbInterface) mac() string {
if i.MACAddress != "" {
return normalizeMAC(i.MACAddress)
}
if i.PrimaryMACAddress != nil {
return normalizeMAC(i.PrimaryMACAddress.MACAddress)
}
return ""
}
type nbIPAddress struct {
Address string `json:"address"`
AssignedObjectID int `json:"assigned_object_id"`
CustomFields map[string]any `json:"custom_fields"`
}
// --- Resolver implementation ---
// HostByMAC finds the device owning an interface with the given MAC and
// resolves it to a Host.
func (c *Client) HostByMAC(ctx context.Context, mac string) (*model.Host, error) {
mac = normalizeMAC(mac)
if mac == "" {
return nil, fmt.Errorf("netbox: empty MAC")
}
var list nbList[nbInterface]
if err := c.get(ctx, "/api/dcim/interfaces/", url.Values{"mac_address": {mac}}, &list); err != nil {
return nil, err
}
var dev *nbRef
for _, i := range list.Results {
if i.mac() == mac && i.Device != nil {
dev = i.Device
break
}
}
if dev == nil {
return nil, ErrNotFound
}
return c.resolveDevice(ctx, dev.ID)
}
// HostByName finds a device by its NetBox name and resolves it to a Host.
func (c *Client) HostByName(ctx context.Context, name string) (*model.Host, error) {
// Strip any domain suffix: NetBox device names are short hostnames.
short := name
if i := strings.IndexByte(short, '.'); i >= 0 {
short = short[:i]
}
var list nbList[nbDevice]
if err := c.get(ctx, "/api/dcim/devices/", url.Values{"name": {short}}, &list); err != nil {
return nil, err
}
if len(list.Results) == 0 {
return nil, ErrNotFound
}
return c.resolveDevice(ctx, list.Results[0].ID)
}
// resolveDevice fetches the device, its interfaces and IP addresses, and
// assembles a Host. It performs three bounded API calls.
func (c *Client) resolveDevice(ctx context.Context, id int) (*model.Host, error) {
var dev nbDevice
if err := c.get(ctx, fmt.Sprintf("/api/dcim/devices/%d/", id), nil, &dev); err != nil {
return nil, err
}
devID := url.Values{"device_id": {fmt.Sprint(id)}}
var ifaces nbList[nbInterface]
if err := c.get(ctx, "/api/dcim/interfaces/", devID, &ifaces); err != nil {
return nil, err
}
var ips nbList[nbIPAddress]
if err := c.get(ctx, "/api/ipam/ip-addresses/", devID, &ips); err != nil {
return nil, err
}
return buildHost(&dev, ifaces.Results, ips.Results), nil
}
// buildHost assembles the normalized Host from raw NetBox objects. It is pure
// (no I/O) so it can be unit-tested directly against fixture structs.
func buildHost(dev *nbDevice, ifaces []nbInterface, ips []nbIPAddress) *model.Host {
cf := dev.CustomFields
domain := cfString(cf, "domain")
h := &model.Host{
Hostname: dev.Name,
Domain: domain,
Custom: cf,
Nameservers: cfStringList(cf, "nameservers"),
TemplateOverride: cfString(cf, "provision_template"),
Arch: "x86_64",
}
if dev.Platform != nil {
h.Platform = dev.Platform.Slug
h.OSFamily, h.OSVersion = splitPlatform(dev.Platform.Slug)
}
if dev.Role != nil {
h.Role = dev.Role.Slug
}
// Index IP addresses by the interface they are assigned to.
ipByIface := map[int]nbIPAddress{}
for _, ip := range ips {
if _, seen := ipByIface[ip.AssignedObjectID]; !seen {
ipByIface[ip.AssignedObjectID] = ip
}
}
primaryAddr := ""
if dev.PrimaryIP != nil {
primaryAddr = dev.PrimaryIP.Address
h.PrimaryIP = addrOnly(primaryAddr)
}
deviceGateway := cfString(cf, "gateway")
for _, in := range ifaces {
iface := model.Interface{
Name: in.Name,
MAC: in.mac(),
}
if in.UntaggedVLAN != nil {
iface.VLAN = in.UntaggedVLAN.VID
}
if ip, ok := ipByIface[in.ID]; ok {
iface.IP = addrOnly(ip.Address)
iface.PrefixLen = prefixLen(ip.Address)
iface.Netmask = netmaskFor(iface.PrefixLen)
if g := cfString(ip.CustomFields, "gateway"); g != "" {
iface.Gateway = g
}
if iface.IP != "" && iface.IP == h.PrimaryIP {
iface.Primary = true
}
}
if iface.Gateway == "" {
iface.Gateway = deviceGateway
}
h.Interfaces = append(h.Interfaces, iface)
}
sortPrimaryFirst(h.Interfaces)
if h.Domain != "" {
h.FQDN = h.Hostname + "." + h.Domain
} else {
h.FQDN = h.Hostname
}
return h
}
// sortPrimaryFirst moves the primary interface to the front, preserving the
// relative order of the rest.
func sortPrimaryFirst(ifaces []model.Interface) {
for i := range ifaces {
if ifaces[i].Primary && i != 0 {
p := ifaces[i]
copy(ifaces[1:i+1], ifaces[0:i])
ifaces[0] = p
return
}
}
}
// get performs a GET against the NetBox API and decodes the JSON body into out.
func (c *Client) get(ctx context.Context, path string, q url.Values, out any) error {
u := c.baseURL + path
if len(q) > 0 {
u += "?" + q.Encode()
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
if c.token != "" {
req.Header.Set("Authorization", "Token "+c.token)
}
resp, err := c.http.Do(req)
if err != nil {
return fmt.Errorf("netbox request %s: %w", path, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode == http.StatusNotFound {
return ErrNotFound
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("netbox %s: HTTP %d", path, resp.StatusCode)
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return fmt.Errorf("netbox decode %s: %w", path, err)
}
return nil
}
// --- helpers ---
func normalizeMAC(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
// Drop common separators then re-insert colons every 2 hex chars.
var hex strings.Builder
for _, r := range strings.ToLower(s) {
if (r >= '0' && r <= '9') || (r >= 'a' && r <= 'f') {
hex.WriteRune(r)
}
}
h := hex.String()
if len(h) != 12 {
// Not a canonical 48-bit MAC; return lower-cased trimmed input.
return strings.ToLower(s)
}
var b strings.Builder
for i := 0; i < 12; i += 2 {
if i > 0 {
b.WriteByte(':')
}
b.WriteString(h[i : i+2])
}
return b.String()
}
func addrOnly(cidr string) string {
if i := strings.IndexByte(cidr, '/'); i >= 0 {
return cidr[:i]
}
return cidr
}
func prefixLen(cidr string) int {
_, ipnet, err := net.ParseCIDR(cidr)
if err != nil {
return 0
}
ones, _ := ipnet.Mask.Size()
return ones
}
func netmaskFor(prefix int) string {
if prefix <= 0 || prefix > 32 {
return ""
}
mask := net.CIDRMask(prefix, 32)
return fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
}
// splitPlatform derives (family, majorVersion) from a NetBox platform slug such
// as "almalinux9" -> ("almalinux","9") or "fedora42" -> ("fedora","42").
func splitPlatform(slug string) (family, version string) {
slug = strings.ToLower(slug)
i := strings.IndexFunc(slug, func(r rune) bool { return r >= '0' && r <= '9' })
if i < 0 {
return slug, ""
}
family = strings.Trim(slug[:i], "-_")
version = slug[i:]
if d := strings.IndexByte(version, '.'); d >= 0 {
version = version[:d]
}
return family, version
}
func cfString(cf map[string]any, key string) string {
if cf == nil {
return ""
}
switch v := cf[key].(type) {
case string:
return v
case map[string]any: // NetBox object custom fields serialize as {value,label}
if s, ok := v["value"].(string); ok {
return s
}
}
return ""
}
func cfStringList(cf map[string]any, key string) []string {
if cf == nil {
return nil
}
switch v := cf[key].(type) {
case string:
return splitComma(v)
case []any:
var out []string
for _, e := range v {
if s, ok := e.(string); ok && s != "" {
out = append(out, s)
}
}
return out
}
return nil
}
func splitComma(v string) []string {
var out []string
for _, p := range strings.Split(v, ",") {
if p = strings.TrimSpace(p); p != "" {
out = append(out, p)
}
}
return out
}
+220
View File
@@ -0,0 +1,220 @@
package netbox
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// fakeNetBox serves canned NetBox v4.x JSON for the endpoints bootapi calls.
// The payloads are trimmed but structurally faithful to real API responses.
func fakeNetBox(t *testing.T) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
// Interfaces filtered by MAC -> the interface (with nested device brief).
mux.HandleFunc("/api/dcim/interfaces/", func(w http.ResponseWriter, r *http.Request) {
if got := r.Header.Get("Authorization"); got != "Token testtoken" {
http.Error(w, `{"detail":"auth"}`, http.StatusForbidden)
return
}
q := r.URL.Query()
switch {
case q.Get("mac_address") == "aa:bb:cc:00:11:22":
writeJSON(w, `{"count":1,"results":[
{"id":40,"name":"eth0","mac_address":"AA:BB:CC:00:11:22",
"untagged_vlan":{"vid":100,"name":"prod"},
"device":{"id":12,"name":"web01","slug":""}}]}`)
case q.Get("device_id") == "12":
// Full interface list for the device (two NICs).
writeJSON(w, `{"count":2,"results":[
{"id":40,"name":"eth0","mac_address":"AA:BB:CC:00:11:22","untagged_vlan":{"vid":100,"name":"prod"}},
{"id":41,"name":"eth1","mac_address":"AA:BB:CC:00:11:33"}]}`)
default:
writeJSON(w, `{"count":0,"results":[]}`)
}
})
// Device detail.
mux.HandleFunc("/api/dcim/devices/", func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/12/") {
writeJSON(w, `{
"id":12,"name":"web01",
"platform":{"id":3,"name":"AlmaLinux 9","slug":"almalinux9"},
"role":{"id":2,"name":"K8s Worker","slug":"kubernetes-worker"},
"site":{"slug":"syd1"},
"primary_ip":{"address":"10.0.1.20/24"},
"custom_fields":{"domain":"syd1.au.unkin.net","gateway":"10.0.1.254","nameservers":"10.0.0.1,10.0.0.2","provision_template":null}}`)
return
}
// name= query (HostByName)
if r.URL.Query().Get("name") == "web01" {
writeJSON(w, `{"count":1,"results":[{"id":12,"name":"web01"}]}`)
return
}
writeJSON(w, `{"count":0,"results":[]}`)
})
// IP addresses for the device: eth0 has the primary, eth1 a second addr.
mux.HandleFunc("/api/ipam/ip-addresses/", func(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, `{"count":2,"results":[
{"address":"10.0.1.20/24","assigned_object_id":40,"custom_fields":{"gateway":null}},
{"address":"10.9.9.5/24","assigned_object_id":41,"custom_fields":{"gateway":"10.9.9.1"}}]}`)
})
return httptest.NewServer(mux)
}
func writeJSON(w http.ResponseWriter, body string) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(body))
}
func newTestClient(t *testing.T, base string) *Client {
t.Helper()
return New(Options{BaseURL: base, Token: "testtoken"})
}
func TestHostByMAC(t *testing.T) {
srv := fakeNetBox(t)
defer srv.Close()
c := newTestClient(t, srv.URL)
h, err := c.HostByMAC(context.Background(), "AA-BB-CC-00-11-22")
if err != nil {
t.Fatalf("HostByMAC: %v", err)
}
if h.Hostname != "web01" {
t.Errorf("hostname = %q, want web01", h.Hostname)
}
if h.FQDN != "web01.syd1.au.unkin.net" {
t.Errorf("fqdn = %q", h.FQDN)
}
if h.Platform != "almalinux9" || h.OSFamily != "almalinux" || h.OSVersion != "9" {
t.Errorf("platform=%q family=%q version=%q", h.Platform, h.OSFamily, h.OSVersion)
}
if h.Role != "kubernetes-worker" {
t.Errorf("role = %q", h.Role)
}
if h.PrimaryIP != "10.0.1.20" {
t.Errorf("primaryIP = %q", h.PrimaryIP)
}
if len(h.Nameservers) != 2 || h.Nameservers[0] != "10.0.0.1" {
t.Errorf("nameservers = %v", h.Nameservers)
}
if len(h.Interfaces) != 2 {
t.Fatalf("interfaces = %d, want 2", len(h.Interfaces))
}
// Primary interface (eth0, carrying the primary IP) must sort first.
pi := h.PrimaryInterface()
if pi == nil || pi.Name != "eth0" || !pi.Primary {
t.Fatalf("primary interface = %+v", pi)
}
if pi.MAC != "aa:bb:cc:00:11:22" {
t.Errorf("primary MAC = %q (want normalized lower-colon)", pi.MAC)
}
if pi.IP != "10.0.1.20" || pi.Netmask != "255.255.255.0" || pi.PrefixLen != 24 {
t.Errorf("primary iface addr = %+v", pi)
}
// eth0 gateway comes from the device custom field (its IP had none).
if pi.Gateway != "10.0.1.254" {
t.Errorf("primary gateway = %q, want device CF 10.0.1.254", pi.Gateway)
}
if pi.VLAN != 100 {
t.Errorf("primary vlan = %d", pi.VLAN)
}
// eth1's IP custom field gateway wins over the device default.
for i := range h.Interfaces {
if h.Interfaces[i].Name == "eth1" {
if h.Interfaces[i].Gateway != "10.9.9.1" {
t.Errorf("eth1 gateway = %q, want per-IP CF 10.9.9.1", h.Interfaces[i].Gateway)
}
}
}
}
func TestHostByMACNotFound(t *testing.T) {
srv := fakeNetBox(t)
defer srv.Close()
c := newTestClient(t, srv.URL)
_, err := c.HostByMAC(context.Background(), "de:ad:be:ef:00:00")
if !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
func TestHostByName(t *testing.T) {
srv := fakeNetBox(t)
defer srv.Close()
c := newTestClient(t, srv.URL)
// FQDN input should be reduced to the short name for the NetBox query.
h, err := c.HostByName(context.Background(), "web01.syd1.au.unkin.net")
if err != nil {
t.Fatalf("HostByName: %v", err)
}
if h.Hostname != "web01" || h.PrimaryIP != "10.0.1.20" {
t.Errorf("host = %+v", h)
}
}
func TestHostByNameNotFound(t *testing.T) {
srv := fakeNetBox(t)
defer srv.Close()
c := newTestClient(t, srv.URL)
if _, err := c.HostByName(context.Background(), "nope"); !errors.Is(err, ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
func TestAuthTokenRequired(t *testing.T) {
srv := fakeNetBox(t)
defer srv.Close()
// Client with the wrong token -> NetBox 403 -> surfaced as an error.
c := New(Options{BaseURL: srv.URL, Token: "wrong"})
if _, err := c.HostByMAC(context.Background(), "aa:bb:cc:00:11:22"); err == nil {
t.Fatal("expected an auth error, got nil")
}
}
func TestNormalizeMAC(t *testing.T) {
cases := map[string]string{
"AA:BB:CC:00:11:22": "aa:bb:cc:00:11:22",
"aa-bb-cc-00-11-22": "aa:bb:cc:00:11:22",
"aabb.cc00.1122": "aa:bb:cc:00:11:22",
"AABBCC001122": "aa:bb:cc:00:11:22",
}
for in, want := range cases {
if got := normalizeMAC(in); got != want {
t.Errorf("normalizeMAC(%q) = %q, want %q", in, got, want)
}
}
}
func TestSplitPlatform(t *testing.T) {
cases := []struct{ in, fam, ver string }{
{"almalinux9", "almalinux", "9"},
{"fedora42", "fedora", "42"},
{"rocky9.4", "rocky", "9"},
{"debian", "debian", ""},
}
for _, c := range cases {
f, v := splitPlatform(c.in)
if f != c.fam || v != c.ver {
t.Errorf("splitPlatform(%q) = (%q,%q), want (%q,%q)", c.in, f, v, c.fam, c.ver)
}
}
}
func TestNetmaskFor(t *testing.T) {
cases := map[int]string{24: "255.255.255.0", 16: "255.255.0.0", 25: "255.255.255.128", 0: ""}
for prefix, want := range cases {
if got := netmaskFor(prefix); got != want {
t.Errorf("netmaskFor(%d) = %q, want %q", prefix, got, want)
}
}
}