mirror of
https://github.com/netbirdio/netbird.git
synced 2026-10-03 20:19:07 +02:00
* [agent-network] Shared proto, OpenAPI schema, and generated types * [agent-network] Management: store, manager, synthesizer, policy engine, provider catalog, HTTP/gRPC API Adds the account-scoped agent-network module: provider/policy/budget CRUD and store, the reverse-proxy service synthesizer, policy selection + limit enforcement, the provider catalog (incl. Vertex AI and AWS Bedrock entries), and the management HTTP + proxy gRPC surfaces. * [management] Fix agent-network proxy-peer fan-out on affected-peer recompute The affected-peers resolver loaded only persisted reverse-proxy services, but agent-network services are synthesized on demand and never persisted. As a result the embedded proxy peer was never folded into the affected set when a client's group changed, so the proxy received no network-map update for a newly authorised client and rejected its handshake until a full resync (restart). loadProxyServices now merges the synthesized agent-network services (injected via a registration hook to avoid an import cycle), so proxy peers learn newly authorised clients immediately. * [proxy] Reverse-proxy middleware framework, chain, and request plumbing The per-target middleware chain (slots, dispatcher, mutation gate, metadata merger), body capture, access-log terminal sink, and the proxy wiring that builds + runs chains for synthesized agent-network services. * [proxy] LLM parsers, pricing, and builtin middlewares (OpenAI, Anthropic, Vertex AI, AWS Bedrock) Request/response parsers and SSE/event-stream metering, the embedded pricing table, and the builtin middleware set: request parser, router, policy limit-check/record, cost meter, guardrail, identity inject, response parser. Includes the path-routed providers — Google Vertex AI (keyfile:: service-account OAuth minting) and AWS Bedrock (bearer auth, invoke/converse/streaming, optional /bedrock prefix) — plus the Models allowlist and unmeterable-publisher deny. * [proxy] IPv6 in-place apply and TCP accept-loop hardening on netstack listeners * [agent-network] End-to-end test suite, module docs, and deployment preset * [agent-network] Fix codespell typos and exclude false positives - labelgen word pool: vermillion -> vermilion, racoon -> raccoon. - codespell ignore list: add flate (Go compress/flate package), recordin (a test-local identifier), and unparseable (a valid alternative spelling used consistently across identifiers + a metadata-value constant). * [management] Set LastSeen on injected proxy peer in realstack test (MySQL strict-mode) The injected embedded proxy peer had a PeerStatus with a zero LastSeen, which serializes to '0000-00-00' and is rejected by MySQL in strict mode (SQLite tolerates it). Set LastSeen to a valid time so SaveAccount succeeds on both engines. * [agent-network] Remove e2e shell-script suite from this branch The end-to-end shell scripts under scripts/e2e/ are maintained in a separate testing suite and are not part of this change set. * [agent-network] Polish module docs: remove internal review scaffolding, fix links, verify diagrams Strip PR-review framing, commit references, absolute paths, and stale internal references from the agent-network module docs; fix broken relative links; verify all diagrams against the current architecture. Remove the internal AI-reviewer prompt file. * [management] Refine session expiration handling to support 3-state encoding for SSO deadlines * [agent-network] Relocate agentnetwork package to internals/modules Move management/server/agentnetwork (and its catalog/, labelgen/, types/ subpackages) to management/internals/modules/agentnetwork, alongside the reverse-proxy module, and rewrite all importers. Pure relocation: package names, the synthesizer + affectedpeers registration hook, and store access (shared store.Store) are unchanged, so no import cycle is introduced (affectedpeers still depends only on the agentnetwork/types leaf). * [agent-network] Co-locate HTTP handlers in the module (RegisterEndpoints) Move the agent-network HTTP handlers from server/http/handlers/agentnetwork into the module at internals/modules/agentnetwork/handlers (package handlers) and rename the entrypoint AddEndpoints -> RegisterEndpoints, matching the reverse-proxy module convention. Wiring in http/handler.go updated accordingly.
233 lines
8.4 KiB
Go
233 lines
8.4 KiB
Go
package agentnetwork
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
|
|
"github.com/golang/mock/gomock"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/netbirdio/netbird/management/internals/modules/agentnetwork/types"
|
|
"github.com/netbirdio/netbird/management/internals/modules/reverseproxy/proxy"
|
|
"github.com/netbirdio/netbird/management/server/store"
|
|
"github.com/netbirdio/netbird/shared/management/proto"
|
|
)
|
|
|
|
func newReconcileMgr(t *testing.T, ctrl *gomock.Controller) (*managerImpl, *store.MockStore, *proxy.MockController) {
|
|
t.Helper()
|
|
mockStore := store.NewMockStore(ctrl)
|
|
mockProxy := proxy.NewMockController(ctrl)
|
|
return &managerImpl{
|
|
store: mockStore,
|
|
proxyController: mockProxy,
|
|
reconcileCache: make(map[string]map[string]*proto.ProxyMapping),
|
|
}, mockStore, mockProxy
|
|
}
|
|
|
|
func newReconcileTestProvider() *types.Provider {
|
|
return &types.Provider{
|
|
ID: "prov-1",
|
|
AccountID: "acct-1",
|
|
ProviderID: "openai_api",
|
|
Name: "OpenAI",
|
|
UpstreamURL: "https://api.openai.com",
|
|
APIKey: "sk-test-key",
|
|
Enabled: true,
|
|
SessionPrivateKey: "test-priv-key",
|
|
SessionPublicKey: "test-pub-key",
|
|
}
|
|
}
|
|
|
|
func newReconcileTestPolicy(providerID, sourceGroupID string) *types.Policy {
|
|
return &types.Policy{
|
|
ID: "pol-1",
|
|
AccountID: "acct-1",
|
|
Name: "engineers",
|
|
Enabled: true,
|
|
SourceGroups: []string{sourceGroupID},
|
|
DestinationProviderIDs: []string{providerID},
|
|
}
|
|
}
|
|
|
|
func newReconcileTestSettings() *types.Settings {
|
|
return &types.Settings{
|
|
AccountID: "acct-1",
|
|
Cluster: "eu.proxy.netbird.io",
|
|
Subdomain: "violet",
|
|
}
|
|
}
|
|
|
|
func expectReconcileSynthInputs(mockStore *store.MockStore, ctx context.Context, providers []*types.Provider, policies []*types.Policy, guardrails []*types.Guardrail) {
|
|
mockStore.EXPECT().
|
|
GetAgentNetworkSettings(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return(newReconcileTestSettings(), nil)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkProviders(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return(providers, nil)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkPolicies(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return(policies, nil)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkGuardrails(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return(guardrails, nil)
|
|
}
|
|
|
|
func TestReconcile_FirstSynth_EmitsCreate(t *testing.T) {
|
|
ctx := context.Background()
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
mgr, mockStore, mockProxy := newReconcileMgr(t, ctrl)
|
|
provider := newReconcileTestProvider()
|
|
policy := newReconcileTestPolicy(provider.ID, "grp-eng")
|
|
|
|
expectReconcileSynthInputs(mockStore, ctx, []*types.Provider{provider}, []*types.Policy{policy}, []*types.Guardrail{})
|
|
mockProxy.EXPECT().GetOIDCValidationConfig().Return(proxy.OIDCValidationConfig{})
|
|
|
|
var sentMappings []*proto.ProxyMapping
|
|
mockProxy.EXPECT().
|
|
SendServiceUpdateToCluster(ctx, "acct-1", gomock.Any(), "eu.proxy.netbird.io").
|
|
Do(func(_ context.Context, _ string, m *proto.ProxyMapping, _ string) {
|
|
sentMappings = append(sentMappings, m)
|
|
})
|
|
|
|
mgr.reconcile(ctx, "acct-1")
|
|
|
|
require.Len(t, sentMappings, 1, "first synth must emit one mapping")
|
|
assert.Equal(t, proto.ProxyMappingUpdateType_UPDATE_TYPE_CREATED, sentMappings[0].Type, "first synth is a Create")
|
|
assert.Equal(t, "agent-net-svc-acct-1", sentMappings[0].Id, "stable account-scoped virtual service id")
|
|
assert.Equal(t, "violet.eu.proxy.netbird.io", sentMappings[0].Domain, "domain comes from settings (subdomain.cluster)")
|
|
|
|
mgr.reconcileMu.Lock()
|
|
cached := mgr.reconcileCache["acct-1"]
|
|
mgr.reconcileMu.Unlock()
|
|
require.Len(t, cached, 1, "cache must hold the synth result for next diff")
|
|
}
|
|
|
|
func TestReconcile_NoChange_EmitsNothingExtra(t *testing.T) {
|
|
ctx := context.Background()
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
mgr, mockStore, mockProxy := newReconcileMgr(t, ctrl)
|
|
provider := newReconcileTestProvider()
|
|
policy := newReconcileTestPolicy(provider.ID, "grp-eng")
|
|
|
|
// Two identical synth runs.
|
|
mockStore.EXPECT().
|
|
GetAgentNetworkSettings(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return(newReconcileTestSettings(), nil).Times(2)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkProviders(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return([]*types.Provider{provider}, nil).Times(2)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkPolicies(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return([]*types.Policy{policy}, nil).Times(2)
|
|
mockStore.EXPECT().
|
|
GetAccountAgentNetworkGuardrails(ctx, store.LockingStrengthNone, "acct-1").
|
|
Return([]*types.Guardrail{}, nil).Times(2)
|
|
mockProxy.EXPECT().GetOIDCValidationConfig().Return(proxy.OIDCValidationConfig{}).Times(2)
|
|
|
|
createCalls := 0
|
|
updateCalls := 0
|
|
mockProxy.EXPECT().
|
|
SendServiceUpdateToCluster(ctx, "acct-1", gomock.Any(), gomock.Any()).
|
|
Do(func(_ context.Context, _ string, m *proto.ProxyMapping, _ string) {
|
|
switch m.Type {
|
|
case proto.ProxyMappingUpdateType_UPDATE_TYPE_CREATED:
|
|
createCalls++
|
|
case proto.ProxyMappingUpdateType_UPDATE_TYPE_MODIFIED:
|
|
updateCalls++
|
|
}
|
|
}).
|
|
AnyTimes()
|
|
|
|
mgr.reconcile(ctx, "acct-1")
|
|
mgr.reconcile(ctx, "acct-1")
|
|
|
|
assert.Equal(t, 1, createCalls, "first reconcile creates")
|
|
assert.Equal(t, 1, updateCalls, "second reconcile re-pushes as Modified (no semantic change but mapping fields refresh)")
|
|
}
|
|
|
|
func TestReconcile_PolicyRemoved_EmitsDelete(t *testing.T) {
|
|
ctx := context.Background()
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
mgr, mockStore, mockProxy := newReconcileMgr(t, ctrl)
|
|
provider := newReconcileTestProvider()
|
|
policy := newReconcileTestPolicy(provider.ID, "grp-eng")
|
|
|
|
gomock.InOrder(
|
|
// First reconcile: provider + policy, synthesised.
|
|
mockStore.EXPECT().GetAgentNetworkSettings(ctx, store.LockingStrengthNone, "acct-1").Return(newReconcileTestSettings(), nil),
|
|
mockStore.EXPECT().GetAccountAgentNetworkProviders(ctx, store.LockingStrengthNone, "acct-1").Return([]*types.Provider{provider}, nil),
|
|
mockStore.EXPECT().GetAccountAgentNetworkPolicies(ctx, store.LockingStrengthNone, "acct-1").Return([]*types.Policy{policy}, nil),
|
|
mockStore.EXPECT().GetAccountAgentNetworkGuardrails(ctx, store.LockingStrengthNone, "acct-1").Return([]*types.Guardrail{}, nil),
|
|
// Second reconcile: policy gone, provider stays but no longer referenced.
|
|
mockStore.EXPECT().GetAgentNetworkSettings(ctx, store.LockingStrengthNone, "acct-1").Return(newReconcileTestSettings(), nil),
|
|
mockStore.EXPECT().GetAccountAgentNetworkProviders(ctx, store.LockingStrengthNone, "acct-1").Return([]*types.Provider{provider}, nil),
|
|
mockStore.EXPECT().GetAccountAgentNetworkPolicies(ctx, store.LockingStrengthNone, "acct-1").Return([]*types.Policy{}, nil),
|
|
)
|
|
mockProxy.EXPECT().GetOIDCValidationConfig().Return(proxy.OIDCValidationConfig{}).AnyTimes()
|
|
|
|
var seenTypes []proto.ProxyMappingUpdateType
|
|
mockProxy.EXPECT().
|
|
SendServiceUpdateToCluster(ctx, "acct-1", gomock.Any(), "eu.proxy.netbird.io").
|
|
Do(func(_ context.Context, _ string, m *proto.ProxyMapping, _ string) {
|
|
seenTypes = append(seenTypes, m.Type)
|
|
}).
|
|
AnyTimes()
|
|
|
|
mgr.reconcile(ctx, "acct-1")
|
|
mgr.reconcile(ctx, "acct-1")
|
|
|
|
require.Len(t, seenTypes, 2, "create then delete")
|
|
assert.Equal(t, proto.ProxyMappingUpdateType_UPDATE_TYPE_CREATED, seenTypes[0])
|
|
assert.Equal(t, proto.ProxyMappingUpdateType_UPDATE_TYPE_REMOVED, seenTypes[1])
|
|
|
|
mgr.reconcileMu.Lock()
|
|
_, present := mgr.reconcileCache["acct-1"]
|
|
mgr.reconcileMu.Unlock()
|
|
assert.False(t, present, "cache for the account must be cleared once nothing is synthesised")
|
|
}
|
|
|
|
func TestReconcile_NilProxyController_NoOp(t *testing.T) {
|
|
ctx := context.Background()
|
|
mgr := &managerImpl{
|
|
reconcileCache: make(map[string]map[string]*proto.ProxyMapping),
|
|
}
|
|
// Must not panic; must not query the store.
|
|
mgr.reconcile(ctx, "acct-1")
|
|
}
|
|
|
|
func TestReconcile_EmptyAccountID_NoOp(t *testing.T) {
|
|
ctx := context.Background()
|
|
ctrl := gomock.NewController(t)
|
|
defer ctrl.Finish()
|
|
|
|
mgr, _, _ := newReconcileMgr(t, ctrl)
|
|
// Empty accountID short-circuits before any store call.
|
|
mgr.reconcile(ctx, "")
|
|
}
|
|
|
|
func TestClusterFromMapping(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
domain string
|
|
want string
|
|
}{
|
|
{"simple", "openai.eu.proxy.netbird.io", "eu.proxy.netbird.io"},
|
|
{"deeply nested", "a.b.c.d", "b.c.d"},
|
|
{"no dot", "openai", ""},
|
|
{"empty", "", ""},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
got := clusterFromMapping(&proto.ProxyMapping{Domain: tt.domain})
|
|
assert.Equal(t, tt.want, got)
|
|
})
|
|
}
|
|
}
|