fix: harden config loading and ssh addresses, stop resolver on API errors
- read netssh.yaml from the user config directory only, not from the working directory - refuse addresses from NetBox or the cache that are neither an IP address nor a hostname (ssh read "-oProxyCommand=…" as an option) - resolver chain stops at an API failure; only "no address" falls through to the next strategy - netssh --help and -h show netssh's help - start at most one background cache refresh per 5 minutes - validate the legacy netbox.url - page through all IP addresses of a host - CI: run format check, vet, and tests on pull requests and main - changelog for v0.0.25 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
6e80b733dc
commit
4287b7b650
19 files changed
+317
-30
No files matched your search
+33
-24
@@ -176,24 +176,32 @@ func (c *Client) GetIPs(ctx context.Context, entry HostEntry) ([]string, error)
|
||||
}
|
||||
return source.GetIPs(ctx, host)
|
||||
}
|
||||
var apiURL string
|
||||
switch entry.Kind {
|
||||
case "device":
|
||||
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?device_id=%d&limit=100", c.baseURL, entry.ID)
|
||||
return c.fetchAllIPs(ctx, fmt.Sprintf("device_id=%d", entry.ID))
|
||||
case "vm":
|
||||
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?virtual_machine_id=%d&limit=100", c.baseURL, entry.ID)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
|
||||
return c.fetchAllIPs(ctx, fmt.Sprintf("virtual_machine_id=%d", entry.ID))
|
||||
}
|
||||
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
|
||||
}
|
||||
|
||||
var resp netboxIPListResponse
|
||||
if err := c.get(ctx, apiURL, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ips := make([]string, 0, len(resp.Results))
|
||||
for _, r := range resp.Results {
|
||||
ips = append(ips, stripPrefix(r.Address))
|
||||
// fetchAllIPs pages through the IP addresses matching filterParams, so hosts
|
||||
// with more addresses than one page do not lose their management address.
|
||||
func (c *Client) fetchAllIPs(ctx context.Context, filterParams string) ([]string, error) {
|
||||
const pageSize = 100
|
||||
var ips []string
|
||||
for offset := 0; ; offset += pageSize {
|
||||
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filterParams, pageSize, offset)
|
||||
var resp netboxIPListResponse
|
||||
if err := c.get(ctx, apiURL, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, r := range resp.Results {
|
||||
ips = append(ips, stripPrefix(r.Address))
|
||||
}
|
||||
if len(resp.Results) < pageSize || len(ips) >= resp.Count {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ips, nil
|
||||
}
|
||||
@@ -203,16 +211,7 @@ func (c *Client) GetIPsWithFilter(ctx context.Context, filterParams string) ([]s
|
||||
if c.sources != nil {
|
||||
return nil, fmt.Errorf("IP filters require a host instance; use GetIPsWithFilterForHost")
|
||||
}
|
||||
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=100", c.baseURL, filterParams)
|
||||
var resp netboxIPListResponse
|
||||
if err := c.get(ctx, apiURL, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ips := make([]string, 0, len(resp.Results))
|
||||
for _, r := range resp.Results {
|
||||
ips = append(ips, stripPrefix(r.Address))
|
||||
}
|
||||
return ips, nil
|
||||
return c.fetchAllIPs(ctx, filterParams)
|
||||
}
|
||||
|
||||
func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEntry, error) {
|
||||
@@ -348,7 +347,7 @@ func (c *Client) request(ctx context.Context, method, apiURL string, body io.Rea
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("netbox returned %d for %s", resp.StatusCode, apiURL)
|
||||
return "", &StatusError{Code: resp.StatusCode, URL: apiURL}
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
|
||||
@@ -399,6 +398,16 @@ func stripPrefix(cidr string) string {
|
||||
return cidr
|
||||
}
|
||||
|
||||
// StatusError is an unexpected HTTP status from NetBox.
|
||||
type StatusError struct {
|
||||
Code int
|
||||
URL string
|
||||
}
|
||||
|
||||
func (e *StatusError) Error() string {
|
||||
return fmt.Sprintf("netbox returned %d for %s", e.Code, e.URL)
|
||||
}
|
||||
|
||||
// ErrHostNotFound distinguishes a missing exact match from API failures or ambiguity.
|
||||
var ErrHostNotFound = errors.New("host not found")
|
||||
|
||||
|
||||
@@ -3,8 +3,11 @@ package netbox
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -499,3 +502,45 @@ func TestCommentConflictIsReported(t *testing.T) {
|
||||
t.Fatal("conflict ignored")
|
||||
}
|
||||
}
|
||||
|
||||
// Hosts with more addresses than one page must not lose the later ones.
|
||||
func TestGetIPs_Paginates(t *testing.T) {
|
||||
const total = 230
|
||||
var offsets []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
offsets = append(offsets, r.URL.Query().Get("offset"))
|
||||
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
|
||||
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
|
||||
var addrs []string
|
||||
for i := offset; i < offset+limit && i < total; i++ {
|
||||
addrs = append(addrs, fmt.Sprintf("10.0.%d.%d/24", i/250, i%250+1))
|
||||
}
|
||||
resp := ipListResponse(addrs...)
|
||||
resp.Count = total
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ips, err := NewClient(srv.URL, "token", 0).GetIPs(context.Background(), HostEntry{ID: 1, Kind: "device"})
|
||||
if err != nil {
|
||||
t.Fatalf("GetIPs: %v", err)
|
||||
}
|
||||
if len(ips) != total || ips[total-1] != "10.0.0.230" {
|
||||
t.Errorf("got %d IPs (last %q), want %d", len(ips), ips[len(ips)-1], total)
|
||||
}
|
||||
if strings.Join(offsets, ",") != "0,100,200" {
|
||||
t.Errorf("offsets %v, want 0,100,200", offsets)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequest_StatusErrorCarriesCode(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
}))
|
||||
defer srv.Close()
|
||||
_, err := NewClient(srv.URL, "token", 0).GetIPsWithFilter(context.Background(), "device_id=1&interface=nope")
|
||||
var status *StatusError
|
||||
if !errors.As(err, &status) || status.Code != http.StatusBadRequest {
|
||||
t.Fatalf("got %v, want a StatusError with code 400", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user