mirror of
https://github.com/netbirdio/netbird.git
synced 2026-07-19 04:59:56 +00: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.
190 lines
5.2 KiB
Go
190 lines
5.2 KiB
Go
package bodytap
|
|
|
|
import (
|
|
"bytes"
|
|
"net/http"
|
|
"sync"
|
|
|
|
"github.com/netbirdio/netbird/proxy/internal/responsewriter"
|
|
)
|
|
|
|
// CapturingResponseWriter wraps an http.ResponseWriter, forwards bytes
|
|
// immediately to the client, and tees a bounded copy into an internal
|
|
// buffer for middleware inspection. Streaming-aware in the sense that
|
|
// every byte the upstream emits flows to the client without queuing
|
|
// — the tee just sees a bounded prefix. SSE-aware parsing happens in
|
|
// the response middleware against the buffered prefix; this writer
|
|
// makes no attempt to demux event boundaries.
|
|
//
|
|
// Flusher and Hijacker are preserved via responsewriter.PassthroughWriter.
|
|
type CapturingResponseWriter struct {
|
|
*responsewriter.PassthroughWriter
|
|
mu sync.Mutex
|
|
buf bytes.Buffer
|
|
cap int64
|
|
status int
|
|
statusSet bool
|
|
written int64
|
|
truncated bool
|
|
stopped bool
|
|
releaseBuf func()
|
|
released sync.Once
|
|
bypassed bool
|
|
bypassReas string
|
|
acquiredCap int64
|
|
}
|
|
|
|
// NewCapturingResponseWriter returns a writer that tees up to maxBytes
|
|
// into a capped buffer while forwarding bytes to the underlying writer
|
|
// immediately. When budget is non-nil the writer pre-acquires maxBytes
|
|
// from it and the returned wrapper must be released by calling
|
|
// Release() once the response is fully forwarded. If the budget cannot
|
|
// be acquired the writer falls back to forwarding the response
|
|
// unmodified, exposes Bypassed()=true with reason BypassBudget, and
|
|
// releases nothing.
|
|
func NewCapturingResponseWriter(w http.ResponseWriter, maxBytes int64, b Budget) *CapturingResponseWriter {
|
|
cw := &CapturingResponseWriter{
|
|
PassthroughWriter: responsewriter.New(w),
|
|
cap: maxBytes,
|
|
status: http.StatusOK,
|
|
releaseBuf: func() {},
|
|
}
|
|
if maxBytes <= 0 {
|
|
// Capture disabled: mark stopped so Write never tees and never
|
|
// flags truncation (a zero cap means "don't capture", not
|
|
// "captured nothing").
|
|
cw.stopped = true
|
|
return cw
|
|
}
|
|
if b == nil {
|
|
return cw
|
|
}
|
|
if !b.Acquire(maxBytes) {
|
|
cw.bypassed = true
|
|
cw.bypassReas = BypassBudget
|
|
cw.cap = 0
|
|
cw.stopped = true
|
|
return cw
|
|
}
|
|
cw.acquiredCap = maxBytes
|
|
cw.releaseBuf = func() { b.Release(maxBytes) }
|
|
return cw
|
|
}
|
|
|
|
// Release returns the response capture budget acquired at construction
|
|
// back to the shared pool. Idempotent. Safe to call from a defer
|
|
// immediately after construction even when the writer ended up
|
|
// bypassing the budget.
|
|
func (c *CapturingResponseWriter) Release() {
|
|
if c == nil {
|
|
return
|
|
}
|
|
c.released.Do(func() {
|
|
if c.releaseBuf != nil {
|
|
c.releaseBuf()
|
|
}
|
|
})
|
|
}
|
|
|
|
// Bypassed reports whether the writer fell through to a no-tee
|
|
// passthrough because the response capture budget could not be
|
|
// acquired.
|
|
func (c *CapturingResponseWriter) Bypassed() bool {
|
|
if c == nil {
|
|
return false
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.bypassed
|
|
}
|
|
|
|
// BypassReason returns the bypass code recorded by the budget check.
|
|
// Empty when capture proceeded normally.
|
|
func (c *CapturingResponseWriter) BypassReason() string {
|
|
if c == nil {
|
|
return ""
|
|
}
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.bypassReas
|
|
}
|
|
|
|
// WriteHeader records the status code and forwards it to the underlying
|
|
// writer. Only the first call commits the status — matching HTTP semantics,
|
|
// where superfluous WriteHeader calls (and any call after the body has
|
|
// started) are ignored — so Status() reflects the code actually sent.
|
|
func (c *CapturingResponseWriter) WriteHeader(status int) {
|
|
c.mu.Lock()
|
|
if c.statusSet {
|
|
c.mu.Unlock()
|
|
return
|
|
}
|
|
c.status = status
|
|
c.statusSet = true
|
|
c.mu.Unlock()
|
|
c.PassthroughWriter.WriteHeader(status)
|
|
}
|
|
|
|
// Write forwards p to the underlying writer unmodified and copies up
|
|
// to the remaining buffer capacity into the tee buffer.
|
|
func (c *CapturingResponseWriter) Write(p []byte) (int, error) {
|
|
n, err := c.PassthroughWriter.Write(p)
|
|
if n > 0 {
|
|
c.mu.Lock()
|
|
// The first byte commits the status (implicit 200 if WriteHeader was
|
|
// never called); a later WriteHeader must not change Status().
|
|
c.statusSet = true
|
|
c.written += int64(n)
|
|
if !c.stopped {
|
|
remaining := c.cap - int64(c.buf.Len())
|
|
if remaining <= 0 {
|
|
c.truncated = true
|
|
c.stopped = true
|
|
} else {
|
|
take := int64(n)
|
|
if take > remaining {
|
|
take = remaining
|
|
c.truncated = true
|
|
c.stopped = true
|
|
}
|
|
c.buf.Write(p[:take])
|
|
}
|
|
}
|
|
c.mu.Unlock()
|
|
}
|
|
return n, err
|
|
}
|
|
|
|
// Status returns the captured status code (defaults to 200 when
|
|
// WriteHeader has not been called).
|
|
func (c *CapturingResponseWriter) Status() int {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.status
|
|
}
|
|
|
|
// Body returns a copy of the buffered response prefix.
|
|
func (c *CapturingResponseWriter) Body() []byte {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
out := make([]byte, c.buf.Len())
|
|
copy(out, c.buf.Bytes())
|
|
return out
|
|
}
|
|
|
|
// Truncated reports whether the buffered prefix stopped short of the
|
|
// full response stream.
|
|
func (c *CapturingResponseWriter) Truncated() bool {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.truncated
|
|
}
|
|
|
|
// BytesWritten returns the total number of bytes forwarded to the
|
|
// underlying writer.
|
|
func (c *CapturingResponseWriter) BytesWritten() int64 {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
return c.written
|
|
}
|