api

package
v0.1.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 25, 2026 License: Apache-2.0 Imports: 51 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNetworkNotFound is returned when a network cannot be found
	ErrNetworkNotFound = errors.New("network not found")

	// ErrNetworkAlreadyExists is returned when attempting to create a duplicate network
	ErrNetworkAlreadyExists = errors.New("network already exists")

	// ErrPolicyNotFound is returned when a policy index is out of range
	ErrPolicyNotFound = errors.New("policy not found")

	// ErrInvalidJSON is returned when request body cannot be decoded
	ErrInvalidJSON = errors.New("invalid JSON")

	// ErrInvalidCIDR is returned when CIDR notation is invalid
	ErrInvalidCIDR = errors.New("invalid CIDR notation")

	// ErrInvalidIP is returned when IP address is invalid
	ErrInvalidIP = errors.New("invalid IP address")

	// ErrInvalidPattern is returned when hostname pattern is invalid
	ErrInvalidPattern = errors.New("invalid hostname pattern")
)

Sentinel errors for API operations

View Source
var ShuttingDown atomic.Bool

ShuttingDown is set to true on SIGTERM to trigger health endpoint 503 response. This allows graceful shutdown by signaling load balancers to stop sending traffic. Exported for use by cmd/root.go signal handler.

Functions

func StartRingBufferReader

func StartRingBufferReader(ctx context.Context, auditEvents *ebpf.Map, resolvedHosts cluster.DMap, hub *WiretapHub, auditStore *audit.Store) error

StartRingBufferReader reads from eBPF ring buffer and broadcasts to hub

Types

type CertificateInfo

type CertificateInfo struct {
	SerialNumber string    `json:"serialNumber"`
	SubjectCN    string    `json:"subjectCN"`
	Issuer       string    `json:"issuer"`
	NotBefore    time.Time `json:"notBefore"`
	NotAfter     time.Time `json:"notAfter"`
}

CertificateInfo represents certificate metadata

type CertificateManager

type CertificateManager struct {
	// contains filtered or unexported fields
}

CertificateManager manages TLS certificates for the API server with hot-reload capability. Implements GetCertificate callback pattern for zero-downtime certificate rotation.

func NewCertificateManager

func NewCertificateManager(certFile, keyFile string, logger logr.Logger) *CertificateManager

NewCertificateManager creates a certificate manager for API server.

func (*CertificateManager) GetCertificate

func (cm *CertificateManager) GetCertificate(chi *tls.ClientHelloInfo) (*tls.Certificate, error)

GetCertificate returns the current certificate for TLS handshakes. This method is called for each TLS handshake, so it must be fast (read-only operation). Implements tls.Config.GetCertificate callback interface.

func (*CertificateManager) Load

func (cm *CertificateManager) Load() error

Load loads and validates the initial certificate from filesystem. Must be called before starting the HTTPS server. Validates file permissions (0600 for key, 0644 for cert) and certificate validity.

func (*CertificateManager) Reload

func (cm *CertificateManager) Reload() error

Reload reloads the certificate from filesystem with validation. Validates the new certificate before swapping (pre-swap validation). If validation fails, keeps the old certificate and returns error. This ensures the server continues operating with a valid certificate.

type CreateNetworkRequest

type CreateNetworkRequest struct {
	Name string `json:"name"`
	CIDR string `json:"cidr"`
}

CreateNetworkRequest represents a network creation request

type CreatePolicyRequest

type CreatePolicyRequest struct {
	Hostname string   `json:"hostname,omitempty"`
	IP       string   `json:"ip,omitempty"`
	Ports    []uint16 `json:"ports"`
}

CreatePolicyRequest represents a policy creation request

type CreateServiceAccountRequest

type CreateServiceAccountRequest struct {
	Name       string `json:"name"`
	Role       string `json:"role"`
	Expiration string `json:"expiration"`
}

CreateServiceAccountRequest represents a request to create a service account

type CreateServiceAccountResponse

type CreateServiceAccountResponse struct {
	ID        string    `json:"id"`
	Token     string    `json:"token"` // Full JWT token (displayed once)
	Name      string    `json:"name"`
	Role      string    `json:"role"`
	CreatedAt time.Time `json:"created_at"`
	ExpiresAt time.Time `json:"expires_at"`
}

CreateServiceAccountResponse represents the response from creating a service account

type DNSCacheEntry

type DNSCacheEntry struct {
	Hostname  string `json:"hostname"`
	IP        string `json:"ip"`
	Timestamp int64  `json:"timestamp"` // Unix nano
}

DNSCacheEntry represents a DNS cache entry

type DNSCacheResponse

type DNSCacheResponse struct {
	Entries []DNSCacheEntry `json:"entries"`
}

DNSCacheResponse represents the DNS cache query response

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
}

ErrorResponse represents an error response

type FirewallModeResponse

type FirewallModeResponse struct {
	Mode string `json:"mode"` // "audit" or "enforce"
}

FirewallModeResponse represents the firewall mode

type JWTMiddleware

type JWTMiddleware interface {
	JWTVerifier(next http.Handler) http.Handler
	JWTAuthenticator(next http.Handler) http.Handler
	RequireRole(roles ...string) func(http.Handler) http.Handler
}

JWTMiddleware is the interface for JWT authentication middleware

type ListRevokedResponse

type ListRevokedResponse struct {
	Revocations []RevokedCertificate `json:"revocations"`
	CertType    string               `json:"certType"`
}

ListRevokedResponse represents the list of revoked certificates

type ListServiceAccountsResponse

type ListServiceAccountsResponse struct {
	ServiceAccounts []ServiceAccountListItem `json:"service_accounts"`
	Total           int                      `json:"total"`
}

ListServiceAccountsResponse represents the response from listing service accounts

type PrebootHealthServer

type PrebootHealthServer struct {
	// contains filtered or unexported fields
}

PrebootHealthServer is a minimal health check server that runs before the full application starts. Used by Azure GWLB integration to pass health checks while waiting for tunnel interface.

func StartPrebootHealthServer

func StartPrebootHealthServer(addr string) (*PrebootHealthServer, error)

StartPrebootHealthServer starts a minimal HTTP server on the specified address that responds with 200 OK to /health requests. This allows GWLB health checks to pass before the full application is initialized.

Call Stop() to shut down the preboot server when the full server is ready.

func (*PrebootHealthServer) Stop

Stop gracefully shuts down the preboot health server. Should be called after the full API server is ready to take over.

type PublicIntegration added in v0.1.4

type PublicIntegration struct {
	ID             string                `json:"id"`
	Name           string                `json:"name"`
	Endpoint       string                `json:"endpoint"`
	CACert         string                `json:"ca_cert"`
	Status         k8s.IntegrationStatus `json:"status"`
	LastError      string                `json:"last_error,omitempty"`
	LastErrorPhase string                `json:"last_error_phase,omitempty"`
	CreatedAt      time.Time             `json:"created_at"`
	UpdatedAt      time.Time             `json:"updated_at"`
}

PublicIntegration represents an integration without sensitive credentials

type RevokeCertificateRequest

type RevokeCertificateRequest struct {
	CertType     string `json:"certType"`     // "nats", "api-server", "api-client"
	SerialNumber string `json:"serialNumber"` // base 10 string
	ReasonCode   string `json:"reasonCode"`   // "unspecified", "key-compromise", etc.
}

RevokeCertificateRequest represents a certificate revocation request

type RevokeCertificateResponse

type RevokeCertificateResponse struct {
	Success     bool      `json:"success"`
	Message     string    `json:"message"`
	ConfirmedBy []string  `json:"confirmedBy"` // List of node names
	Timestamp   time.Time `json:"timestamp"`
	Error       string    `json:"error,omitempty"`
}

RevokeCertificateResponse represents the revocation response

type RevokedCertificate

type RevokedCertificate struct {
	SerialNumber string    `json:"serialNumber"`
	RevokedAt    time.Time `json:"revokedAt"`
	ReasonCode   string    `json:"reasonCode"`
}

RevokedCertificate represents a single revoked certificate entry

type RotateCertificateResult

type RotateCertificateResult struct {
	CertType  string    `json:"certType"`
	Success   bool      `json:"success"`
	Error     string    `json:"error,omitempty"`
	Timestamp time.Time `json:"timestamp"`
}

RotateCertificateResult represents the result of rotating a single certificate

type RotateCertificatesRequest

type RotateCertificatesRequest struct {
	CertTypes []string `json:"certTypes,omitempty"` // Optional filter: ["nats", "api-server", "api-client"]
}

RotateCertificatesRequest represents a manual rotation request

type RotateCertificatesResponse

type RotateCertificatesResponse struct {
	Results []RotateCertificateResult `json:"results"`
	Message string                    `json:"message"`
}

RotateCertificatesResponse represents the response from a rotation request

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server is the HTTP API server

func NewServer

func NewServer(addr string, rp *ruleset.APIRuleProvider, ctrl *controller.Controller, as *audit.Store, tlsAddr string, certFile string, keyFile string, crlVerifier *crl.Verifier) (*Server, error)

NewServer creates a new API server. TLS parameters are optional - if tlsAddr is empty, server runs in HTTP-only mode. If TLS is enabled, certificates are loaded and validated before returning. crlVerifier is optional - if nil, CRL checking is disabled.

func (*Server) CreateIntegration added in v0.1.4

func (s *Server) CreateIntegration(w http.ResponseWriter, r *http.Request)

CreateIntegration creates a new Kubernetes integration It validates credentials, tests the connection, and stores the integration in NATS KV

func (*Server) CreateNetwork

func (s *Server) CreateNetwork(w http.ResponseWriter, r *http.Request)

CreateNetwork creates a new network

func (*Server) CreatePolicy

func (s *Server) CreatePolicy(w http.ResponseWriter, r *http.Request)

CreatePolicy creates a new policy for a network

func (*Server) DeleteIntegration added in v0.1.4

func (s *Server) DeleteIntegration(w http.ResponseWriter, r *http.Request)

DeleteIntegration deletes a Kubernetes integration

func (*Server) DeleteNetwork

func (s *Server) DeleteNetwork(w http.ResponseWriter, r *http.Request)

DeleteNetwork deletes a network

func (*Server) DeletePolicy

func (s *Server) DeletePolicy(w http.ResponseWriter, r *http.Request)

DeletePolicy deletes a policy

func (*Server) EnableAuth

func (s *Server) EnableAuth(jwtMiddleware, oidcHandler, sessionMiddleware interface{}, js jetstream.JetStream) error

EnableAuth configures JWT authentication for the API server This must be called before Start() - authentication is always required Parameters:

  • jwtMiddleware: *auth.Middleware for JWT verification (required)
  • oidcHandler: *oidc.AuthHandler for OAuth2/OIDC flows (optional, can be nil)
  • sessionMiddleware: *session.Middleware for cookie-based session auth
  • js: jetstream.JetStream for rate limiting storage

After calling this, routes will be reconfigured with authentication middleware

func (*Server) GetAuditLogs

func (s *Server) GetAuditLogs(w http.ResponseWriter, r *http.Request)

GetAuditLogs handles GET /api/v1/audit-logs

func (*Server) GetDNSCache

func (s *Server) GetDNSCache(w http.ResponseWriter, r *http.Request)

GetDNSCache returns DNS cache entries

func (*Server) GetIntegration added in v0.1.4

func (s *Server) GetIntegration(w http.ResponseWriter, r *http.Request)

GetIntegration returns a single integration by ID (without bearer token)

func (*Server) GetMode

func (s *Server) GetMode(w http.ResponseWriter, r *http.Request)

GetMode returns the current firewall mode

func (*Server) GetNetwork

func (s *Server) GetNetwork(w http.ResponseWriter, r *http.Request)

GetNetwork returns a single network by name

func (*Server) GetStats

func (s *Server) GetStats(w http.ResponseWriter, r *http.Request)

GetStats returns dashboard statistics

func (*Server) HandleCreateServiceAccount

func (s *Server) HandleCreateServiceAccount(w http.ResponseWriter, r *http.Request)

HandleCreateServiceAccount creates a new service account with a generated JWT token. Admin-only endpoint - RequireRole middleware enforces authorization.

Request body: CreateServiceAccountRequest (name, role, expiration) Response: CreateServiceAccountResponse with token (displayed once)

Per CONTEXT.md: "Service account names must be unique (error if name exists)" Per CONTEXT.md: "Fixed choices only: 30 days, 90 days, 1 year (no custom date picker)"

func (*Server) HandleDiagnosticsDownload

func (s *Server) HandleDiagnosticsDownload(w http.ResponseWriter, r *http.Request)

HandleDiagnosticsDownload handles POST /api/v1/diagnostics Triggers cluster-wide diagnostic collection and streams .zip archive to client. Admin-only endpoint - RequireRole("admin") middleware enforces authorization.

Response: application/zip with Content-Disposition header for download Returns 409 Conflict if collection already in progress Returns 500 Internal Server Error if coordinator not configured or collection fails

func (*Server) HandleDiagnosticsProgress

func (s *Server) HandleDiagnosticsProgress(w http.ResponseWriter, r *http.Request)

HandleDiagnosticsProgress handles GET /api/v1/diagnostics/progress Server-Sent Events (SSE) stream for real-time collection progress. Admin-only endpoint - RequireRole("admin") middleware enforces authorization.

Streams JSON events in SSE format: data: {"phase": "...", "node": "...", "status": "..."}\n\n Phases: collecting, redacting, archiving, complete, error Status: in-progress, complete, failed

func (*Server) HandleGetCertificate

func (s *Server) HandleGetCertificate(w http.ResponseWriter, r *http.Request)

HandleGetCertificate returns certificate metadata by serial number GET /api/v1/certificates/{serial}?certType=nats|api-server|api-client

func (*Server) HandleListRevokedCertificates

func (s *Server) HandleListRevokedCertificates(w http.ResponseWriter, r *http.Request)

HandleListRevokedCertificates returns all revoked certificates for a CA GET /api/v1/certificates/revoked?certType=nats|api-server|api-client

func (*Server) HandleListServiceAccounts

func (s *Server) HandleListServiceAccounts(w http.ResponseWriter, r *http.Request)

HandleListServiceAccounts returns all service accounts with usage stats and expiry status. Admin-only endpoint - RequireRole middleware enforces authorization.

Response: ListServiceAccountsResponse with array of ServiceAccountListItem

Per CONTEXT.md: Expiry warnings at 14 days (yellow) and 7 days (red)

func (*Server) HandleRevokeCertificate

func (s *Server) HandleRevokeCertificate(w http.ResponseWriter, r *http.Request)

HandleRevokeCertificate revokes a certificate by adding it to the CRL POST /api/v1/certificates/revoke

func (*Server) HandleRevokeServiceAccount

func (s *Server) HandleRevokeServiceAccount(w http.ResponseWriter, r *http.Request)

HandleRevokeServiceAccount revokes a service account (hard delete, immediate invalidation). Admin-only endpoint - RequireRole middleware enforces authorization.

URL parameter: {id} - service account ID Response: 204 No Content on success

Per CONTEXT.md: "Hard delete: record removed entirely, not soft delete" Per CONTEXT.md: "Immediate invalidation: token stops working instantly, no grace period" Per RESEARCH Pattern 2: Idempotent - revoking non-existent account returns 204

func (*Server) HandleRotateCertificates

func (s *Server) HandleRotateCertificates(w http.ResponseWriter, r *http.Request)

HandleRotateCertificates handles manual certificate rotation requests. POST /api/v1/certificates/rotate

Request body: RotateCertificatesRequest with optional CertTypes filter. Response: RotateCertificatesResponse with per-cert results.

If CertTypes is empty, rotates all three certificate types (nats, api-server, api-client). Returns HTTP 200 if any rotation succeeded, HTTP 500 if all failed.

func (*Server) HandleTokenLogin

func (s *Server) HandleTokenLogin(w http.ResponseWriter, r *http.Request)

HandleTokenLogin accepts a service account token and creates a browser session POST /auth/token-login

Request body:

{
  "token": "nw_sa_..."
}

Returns:

  • 200: User information (id, email, role) and sets neuwerk_session cookie
  • 400: Invalid request format
  • 401: Invalid or revoked token
  • 500: Server error (session creation failure)

func (*Server) HandleWhoami

func (s *Server) HandleWhoami(w http.ResponseWriter, r *http.Request)

HandleWhoami returns current user information from the authenticated session GET /api/v1/auth/whoami

Returns:

  • 200: User information (id, email, role)
  • 401: Not authenticated (no valid session or token)

func (*Server) HandleWiretap

func (s *Server) HandleWiretap(w http.ResponseWriter, r *http.Request)

HandleWiretap handles SSE streaming for wiretap events

func (*Server) IsTLSEnabled

func (s *Server) IsTLSEnabled() bool

IsTLSEnabled returns whether TLS is enabled for the server. Used to determine if session cookies should have the Secure flag set.

func (*Server) ListIntegrations added in v0.1.4

func (s *Server) ListIntegrations(w http.ResponseWriter, r *http.Request)

ListIntegrations returns all Kubernetes integrations (without bearer tokens)

func (*Server) ListNetworks

func (s *Server) ListNetworks(w http.ResponseWriter, r *http.Request)

ListNetworks returns all networks

func (*Server) ListPolicies

func (s *Server) ListPolicies(w http.ResponseWriter, r *http.Request)

ListPolicies returns all policies for a network

func (*Server) SetIntegrationStorage added in v0.1.4

func (s *Server) SetIntegrationStorage(storage interface{})

SetIntegrationStorage configures the Kubernetes integration storage. This must be called before Start() if integration endpoints are needed. The storage parameter should be *k8s.Storage. Routes are re-initialized to include integration endpoints.

func (*Server) SetMode

func (s *Server) SetMode(w http.ResponseWriter, r *http.Request)

SetMode sets the firewall mode

func (*Server) SetServiceAccountStore

func (s *Server) SetServiceAccountStore(store, privateKey interface{})

SetServiceAccountStore configures service account management for the API server. This must be called after EnableAuth() or EnableTokenAuth() if service account endpoints are needed. Parameters:

  • store: ServiceAccountStore for CRUD operations
  • privateKey: *rsa.PrivateKey for token generation

This method also sets the service account store on the JWT middleware for revocation checking. Routes are re-initialized to include service account endpoints.

func (*Server) SetSysdumpCoordinator

func (s *Server) SetSysdumpCoordinator(coordinator interface{})

SetSysdumpCoordinator configures the multi-node diagnostic coordinator. This must be called before Start() if diagnostics endpoints are needed. The coordinator parameter should be *sysdump.MultiNodeCoordinator. Routes are re-initialized to include diagnostics endpoints.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start starts the HTTP server (and HTTPS if TLS enabled)

func (*Server) TestPattern

func (s *Server) TestPattern(w http.ResponseWriter, r *http.Request)

TestPattern tests if a hostname matches a pattern

func (*Server) TriggerReconcile

func (s *Server) TriggerReconcile(w http.ResponseWriter, r *http.Request)

TriggerReconcile triggers an immediate synchronization of network rules to BPF maps This is useful for tests to avoid waiting for the periodic reconcile interval

func (*Server) UpdateIntegration added in v0.1.4

func (s *Server) UpdateIntegration(w http.ResponseWriter, r *http.Request)

UpdateIntegration updates an existing Kubernetes integration Bearer token is preserved if not provided in the request (nil pointer pattern)

func (*Server) UpdateNetwork

func (s *Server) UpdateNetwork(w http.ResponseWriter, r *http.Request)

UpdateNetwork updates an existing network

func (*Server) UpdatePolicy

func (s *Server) UpdatePolicy(w http.ResponseWriter, r *http.Request)

UpdatePolicy updates an existing policy

type ServiceAccountListItem

type ServiceAccountListItem struct {
	ID            string     `json:"id"`
	Name          string     `json:"name"`
	Role          string     `json:"role"`
	CreatedAt     time.Time  `json:"created_at"`
	CreatedBy     string     `json:"created_by"`
	ExpiresAt     time.Time  `json:"expires_at"`
	ExpiryStatus  string     `json:"expiry_status"`       // "active", "expiring-soon", "expired"
	LastUsed      *time.Time `json:"last_used,omitempty"` // Null if never used
	LastIP        string     `json:"last_ip,omitempty"`
	LastEndpoints []string   `json:"last_endpoints,omitempty"`
}

ServiceAccountListItem represents a service account in the list view

type SetModeRequest

type SetModeRequest struct {
	Mode string `json:"mode"` // "audit" or "enforce"
}

SetModeRequest represents a request to set the firewall mode

type SuccessResponse

type SuccessResponse struct {
	Status  string      `json:"status"`
	Message string      `json:"message,omitempty"`
	Data    interface{} `json:"data,omitempty"`
}

SuccessResponse represents a success response

type SystemStatusResponse

type SystemStatusResponse struct {
	Mode           string `json:"mode"`
	NetworkCount   int    `json:"network_count"`
	PolicyCount    int    `json:"policy_count"`
	PacketCounters struct {
		Allowed    uint64 `json:"allowed"`
		Blocked    uint64 `json:"blocked"`
		Redirected uint64 `json:"redirected"`
	} `json:"packet_counters"`
}

SystemStatusResponse contains dashboard statistics

type TestPatternRequest

type TestPatternRequest struct {
	Pattern  string `json:"pattern"`
	Hostname string `json:"hostname"`
}

TestPatternRequest represents a pattern test request

type TestPatternResponse

type TestPatternResponse struct {
	Pattern  string `json:"pattern"`
	Hostname string `json:"hostname"`
	Matches  bool   `json:"matches"`
}

TestPatternResponse represents a pattern test response

type TokenLoginRequest

type TokenLoginRequest struct {
	Token string `json:"token"` // Service account token (nw_sa_...)
}

TokenLoginRequest represents a request to login with a service account token

type UpdateNetworkRequest

type UpdateNetworkRequest struct {
	Name string `json:"name"`
	CIDR string `json:"cidr"`
}

UpdateNetworkRequest represents a network update request

type UpdatePolicyRequest

type UpdatePolicyRequest struct {
	Hostname string   `json:"hostname,omitempty"`
	IP       string   `json:"ip,omitempty"`
	Ports    []uint16 `json:"ports"`
}

UpdatePolicyRequest represents a policy update request

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError represents a validation error with field context

func (*ValidationError) Error

func (e *ValidationError) Error() string

type WhoamiResponse

type WhoamiResponse struct {
	ID    string `json:"id"`    // User email (same as Email for consistency)
	Email string `json:"email"` // User email address
	Role  string `json:"role"`  // User role: "admin" or "readonly"
}

WhoamiResponse represents the current user information

type WiretapEvent

type WiretapEvent struct {
	Timestamp  int64  `json:"timestamp"`
	SourceIP   string `json:"source_ip"`
	DestIP     string `json:"dest_ip"`
	SourcePort uint16 `json:"source_port"`
	DestPort   uint16 `json:"dest_port"`
	Protocol   string `json:"protocol"`
	Hostname   string `json:"hostname,omitempty"`
	Action     string `json:"action"` // "blocked" or "audited"
}

WiretapEvent is the JSON-serializable event for SSE

type WiretapHub

type WiretapHub struct {
	// contains filtered or unexported fields
}

WiretapHub manages SSE client connections

func NewWiretapHub

func NewWiretapHub() *WiretapHub

NewWiretapHub creates a new WiretapHub

func (*WiretapHub) Run

func (h *WiretapHub) Run(ctx context.Context)

Run starts the hub's goroutine for managing clients

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL