Files
rollcall/cmd/rollcall/infoblox_test.go
T
Ilker ManapandClaude Opus 5.5 008fa3f66f
CI / agent (push) Successful in 3s
CI / site (push) Successful in 2s
CI / go (push) Successful in 41s
Infoblox WAPI driver for the IPAM authority
ipam.provider infoblox: one record:host per address, named by its DNS
name and configured for DNS in dns_view ("-" = IPAM only); ownership is
the rollcall_machine extensible attribute, changed with extattrs+ so a
host's other attributes stay. Anything else on the address (a host, a
lease, a fixed address, a DHCP or reserved range, network/broadcast) makes
it taken. Delegated networks carry the rollcall attribute. WAPI paging.

The reconcile no longer compares fields an authority does not keep
(Infoblox has no prefix length or status on a host). Built from the WAPI
reference and tested against a fake WAPI; no real grid yet.

Closes #11

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 23:22:17 +01:00

337 lines
11 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"testing"
)
// fakeWAPI implements the slice of Infoblox WAPI v2.12 the driver uses:
// record:host (search, create, read, update with extattrs+, delete), address
// usage (ipv4address/ipv6address), networks and paging.
type fakeWAPI struct {
mu sync.Mutex
next int
hosts map[string]map[string]any // ref -> host
uses map[string][]string // ip -> other objects using it (leases, fixed addresses)
types map[string][]string // ip -> address types (DHCP_RANGE, ...)
networks []map[string]any
pages map[string][]any
writes []string
}
func newFakeWAPI() *fakeWAPI {
return &fakeWAPI{hosts: map[string]map[string]any{}, uses: map[string][]string{}, types: map[string][]string{}, pages: map[string][]any{}}
}
func (f *fakeWAPI) host(name, ip string, ea map[string]any, dns bool) string {
f.next++
ref := fmt.Sprintf("record:host/ZG5zLmhvc3Qk%d:%s/default", f.next, name)
k := "ipv4addrs"
addr := map[string]any{"ipv4addr": ip}
if strings.Contains(ip, ":") {
k, addr = "ipv6addrs", map[string]any{"ipv6addr": ip}
}
eas := map[string]any{}
for n, v := range ea {
eas[n] = map[string]any{"value": v}
}
f.hosts[ref] = map[string]any{"_ref": ref, "name": name, "comment": "", "configure_for_dns": dns, k: []any{addr}, "extattrs": eas}
return ref
}
func hostIPs(h map[string]any) []string {
var out []string
for _, k := range []string{"ipv4addrs", "ipv6addrs"} {
for _, a := range toList(h[k]) {
out = append(out, str(asObj(a)["ipv4addr"])+str(asObj(a)["ipv6addr"]))
}
}
return out
}
func (f *fakeWAPI) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
write := func(code int, v any) { w.WriteHeader(code); _ = json.NewEncoder(w).Encode(v) }
if u, p, ok := r.BasicAuth(); !ok || u != "rollcall" || p != "s3cret" {
write(401, map[string]any{"text": "Authorization Required"})
return
}
path := strings.TrimPrefix(r.URL.Path, "/wapi/v2.12/")
q := r.URL.Query()
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
if r.Method != "GET" {
f.writes = append(f.writes, r.Method+" "+path)
}
page := func(res []any) {
if id := q.Get("_page_id"); id != "" {
res = f.pages[id]
}
const size = 2 // small pages so paging is exercised
out := map[string]any{"result": res}
if len(res) > size {
id := strconv.Itoa(len(f.pages) + 1)
f.pages[id] = res[size:]
out = map[string]any{"result": res[:size], "next_page_id": id}
}
write(200, out)
}
switch {
case path == "record:host" && r.Method == "GET":
refs := []string{}
for ref := range f.hosts {
refs = append(refs, ref)
}
sort.Strings(refs)
res := []any{}
for _, ref := range refs {
h := f.hosts[ref]
ok := true
for k, v := range q {
switch {
case k == "ipv4addr" || k == "ipv6addr":
ok = ok && strings.Contains(" "+strings.Join(hostIPs(h), " ")+" ", " "+v[0]+" ")
case strings.HasPrefix(k, "*") && strings.HasSuffix(k, "~"):
_, has := asObj(h["extattrs"])[strings.TrimSuffix(k[1:], "~")]
ok = ok && has
}
}
if ok {
res = append(res, h)
}
}
page(res)
case path == "record:host" && r.Method == "POST":
ea := map[string]any{}
for k, v := range asObj(body["extattrs"]) {
ea[k] = asObj(v)["value"]
}
ip := ""
if a := toList(body["ipv4addrs"]); len(a) > 0 {
ip = str(asObj(a[0])["ipv4addr"])
} else if a := toList(body["ipv6addrs"]); len(a) > 0 {
ip = str(asObj(a[0])["ipv6addr"])
}
if body["configure_for_dns"] == true && body["view"] != "default" {
write(400, map[string]any{"Error": "AdmConDataNotFoundError", "code": "Client.Ibap.Data.NotFound", "text": "view not found"})
return
}
ref := f.host(str(body["name"]), ip, ea, body["configure_for_dns"] == true)
f.hosts[ref]["comment"] = body["comment"]
write(201, ref)
case path == "ipv4address" || path == "ipv6address":
ip := q.Get("ip_address")
objs := append([]string{}, f.uses[ip]...)
for ref, h := range f.hosts {
for _, x := range hostIPs(h) {
if x == ip {
objs = append(objs, ref)
}
}
}
status := "UNUSED"
if len(objs) > 0 {
status = "USED"
}
write(200, []any{map[string]any{"ip_address": ip, "status": status, "objects": objs, "types": f.types[ip]}})
case path == "network" || path == "ipv6network":
res := []any{}
for _, n := range f.networks {
if strings.Contains(str(n["network"]), ":") == (path == "ipv6network") {
res = append(res, n)
}
}
page(res)
case strings.HasPrefix(path, "record:host/"):
h, ok := f.hosts[path]
if !ok {
write(400, map[string]any{"Error": "AdmConProtoError: Unknown object", "text": "Unknown object"})
return
}
switch r.Method {
case "GET":
write(200, h)
case "PUT":
for k, v := range body {
if k == "extattrs+" {
for n, x := range asObj(v) {
asObj(h["extattrs"])[n] = x
}
continue
}
h[k] = v
}
write(200, path)
case "DELETE":
delete(f.hosts, path)
write(200, path)
}
default:
write(400, map[string]any{"text": "unknown " + path})
}
}
func testInfoblox(t *testing.T, dnsView string) (*App, *fakeWAPI) {
t.Helper()
f := newFakeWAPI()
srv := httptest.NewServer(f)
t.Cleanup(srv.Close)
pw := filepath.Join(t.TempDir(), "pw")
if err := os.WriteFile(pw, []byte("s3cret\n"), 0o600); err != nil {
t.Fatal(err)
}
cfg := &Config{IPAM: IPAMConfig{Provider: "infoblox", URL: srv.URL, User: "rollcall", PasswordFile: pw, DNSZone: "int.example", DNSView: dnsView}}
p, err := newIPAMProvider(cfg.IPAM)
if err != nil {
t.Fatal(err)
}
a := &App{cfg: cfg, ipam: p, ipamSt: &ipamState{kick: make(chan struct{}, 1)}}
a.subnets = []Subnet{{CIDR: "10.213.77.0/24", Purpose: "provisioning"}, {CIDR: "fd00:213:77::/64", Purpose: "provisioning"}}
return a, f
}
func TestInfobloxReserve(t *testing.T) {
a, f := testInfoblox(t, "")
ctx := context.Background()
f.host("printer.int.example", "10.213.77.20", nil, true) // someone else's host
f.uses["10.213.77.21"] = []string{"lease/ZG5zLmxlYXNl:10.213.77.21/default"} // a lease
f.types["10.213.77.22"] = []string{"DHCP_RANGE"} // inside a DHCP range
mine := f.host("old.int.example", "10.213.77.23", map[string]any{"rollcall_machine": "m-1", "Owner": "ops"}, true)
f.uses["10.213.77.24"] = []string{"fixedaddress/ZG5z:10.213.77.24/default"} // a fixed address
for ip, want := range map[string]bool{"10.213.77.20": true, "10.213.77.21": true, "10.213.77.22": true, "10.213.77.23": false, "10.213.77.24": true, "10.213.77.25": false} {
taken, err := a.ipam.Reserve(ctx, a.extFor(IPAddr{IP: ip, Subnet: "10.213.77.0/24", MachineID: "m-2", Hostname: "node002", Iface: "eth0"}, &a.subnets[0]))
if err != nil {
t.Fatal(ip, err)
}
if taken != want {
t.Errorf("%s: taken=%v want %v", ip, taken, want)
}
}
h := f.hosts[mine]
if h["name"] != "node002.int.example" || asObj(asObj(h["extattrs"])["rollcall_machine"])["value"] != "m-2" ||
asObj(asObj(h["extattrs"])["Owner"])["value"] != "ops" {
t.Errorf("re-owned host %v (other extensible attributes must stay)", h)
}
var made map[string]any
for _, x := range f.hosts {
if hostIPs(x)[0] == "10.213.77.25" {
made = x
}
}
if made == nil || made["name"] != "node002.int.example" || made["configure_for_dns"] != true || made["comment"] != "rollcall m-2 eth0" {
t.Fatalf("new host %v", made)
}
// v6 and a name-less reservation
if _, err := a.ipam.Reserve(ctx, a.extFor(IPAddr{IP: "fd00:213:77::50", Subnet: "fd00:213:77::/64", Kind: "reserved", Hostname: "core switch"}, &a.subnets[1])); err != nil {
t.Fatal(err)
}
var v6 map[string]any
for _, x := range f.hosts {
if hostIPs(x)[0] == "fd00:213:77::50" {
v6 = x
}
}
if v6 == nil || v6["name"] != "rollcall-fd00-213-77--50" || v6["configure_for_dns"] != false {
t.Fatalf("v6 reservation %v", v6)
}
}
func TestInfobloxReconcile(t *testing.T) {
a, f := testInfoblox(t, "")
ctx := context.Background()
foreign := f.host("printer.int.example", "10.213.77.20", nil, true)
f.host("gone.int.example", "10.213.77.30", map[string]any{"rollcall_machine": "m-9"}, true)
f.host("wrong.int.example", "10.213.77.50", map[string]any{"rollcall_machine": "m-1"}, true)
f.host("a.int.example", "10.213.77.60", map[string]any{"rollcall_machine": "m-5"}, true)
f.host("b.int.example", "10.213.77.61", map[string]any{"rollcall_machine": "m-5"}, true) // paging: 5 hosts, pages of 2
local := []IPAddr{
{IP: "10.213.77.20", Subnet: "10.213.77.0/24", MachineID: "m-2", Hostname: "node002", Kind: "auto"},
{IP: "10.213.77.50", Subnet: "10.213.77.0/24", MachineID: "m-1", Hostname: "node001", Kind: "auto"},
{IP: "10.213.77.51", Subnet: "10.213.77.0/24", MachineID: "m-4", Hostname: "node004", Kind: "static"},
{IP: "10.213.77.60", Subnet: "10.213.77.0/24", MachineID: "m-5", Hostname: "a", Kind: "auto"},
{IP: "10.213.77.61", Subnet: "10.213.77.0/24", MachineID: "m-5", Hostname: "b", Kind: "auto"},
}
for _, x := range f.hosts { // descriptions as Rollcall writes them
if m := ib(a).owner(x); m != "" {
x["comment"] = "rollcall " + m
}
}
rep := ipamReport{}
a.reconcileAddrs(ctx, local, &rep)
if rep.Error != "" {
t.Fatal(rep.Error)
}
if fmt.Sprint(rep.Created, rep.Updated, rep.Deleted, len(rep.Conflicts)) != "[10.213.77.51] [10.213.77.50] [10.213.77.30] 1" {
t.Errorf("report: %+v", rep)
}
if f.hosts[foreign]["name"] != "printer.int.example" {
t.Error("foreign host touched")
}
f.writes = nil
again := ipamReport{}
a.reconcileAddrs(ctx, local, &again)
if len(f.writes) != 0 || again.Error != "" {
t.Errorf("second pass wrote %v (%+v): bits and status are not kept by Infoblox and must not count", f.writes, again)
}
// the delete re-checks ownership
for ref, x := range f.hosts {
if x["name"] == "node004.int.example" {
delete(asObj(x["extattrs"]), "rollcall_machine")
if err := a.ipam.Delete(ctx, extAddr{ID: ref}); err != nil || f.hosts[ref] == nil {
t.Fatalf("deleted a host that is no longer Rollcall's: %v", err)
}
}
}
if err := a.ipam.Delete(ctx, extAddr{ID: "record:host/gone:x/default"}); err != nil {
t.Errorf("deleting a vanished host: %v", err)
}
}
func TestInfobloxDNSView(t *testing.T) {
a, f := testInfoblox(t, "internal")
_, err := a.ipam.Reserve(context.Background(), a.extFor(IPAddr{IP: "10.213.77.40", Subnet: "10.213.77.0/24", MachineID: "m-1", Hostname: "n1"}, &a.subnets[0]))
if err == nil || !strings.Contains(err.Error(), "view not found") {
t.Fatalf("WAPI error not passed on: %v", err)
}
if len(f.hosts) != 0 {
t.Fatal("host made")
}
}
func TestInfobloxPrefixes(t *testing.T) {
a, f := testInfoblox(t, "")
f.networks = []map[string]any{
{"network": "10.213.80.0/24", "comment": "new hall", "extattrs": map[string]any{"Site": map[string]any{"value": "DC1"}, "VLAN": map[string]any{"value": "300"}}},
{"network": "fd00:213:80::/64", "comment": "new hall v6", "extattrs": map[string]any{}},
}
ps, err := a.ipam.Prefixes(context.Background())
if err != nil {
t.Fatal(err)
}
if fmt.Sprint(ps) != "[{10.213.80.0/24 new hall 300 DC1 false } {fd00:213:80::/64 new hall v6 0 false }]" {
t.Errorf("%v", ps)
}
}
func TestInfobloxAuth(t *testing.T) {
a, _ := testInfoblox(t, "")
ib(a).pass = "wrong"
_, err := a.ipam.Owned(context.Background())
if err == nil || !strings.Contains(err.Error(), "401") {
t.Fatalf("%v", err)
}
}
func ib(a *App) *infoblox { return a.ipam.(*infoblox) }