Documentation
¶
Overview ¶
Package mockapi provides a mock Central API server for end-to-end testing. It returns fixture responses for each endpoint and tracks call counters that can be queried via the GET /test/assertions endpoint.
Index ¶
- Constants
- func GenerateCATLSConfig() (*tls.Config, []byte)
- type AssertionCounters
- type DNSStub
- type Server
- func (s *Server) Assertions() AssertionCounters
- func (s *Server) BearerEnvelope() string
- func (s *Server) BroadcastSSE(envelope api.Envelope)
- func (s *Server) ExpectedBearerToken() string
- func (s *Server) GetState() api.NodeStateSnapshot
- func (s *Server) Handler() http.Handler
- func (s *Server) LastRequestBody(endpoint string) ([]byte, bool)
- func (s *Server) NSK() []byte
- func (s *Server) SetEndpointTTL(d time.Duration)
- func (s *Server) SetHeartbeatResponse(resp api.HeartbeatResponse)
- func (s *Server) SetState(state api.NodeStateSnapshot)
- func (s *Server) SetTLSCA(caPEM []byte)
- func (s *Server) TLSHandler() http.Handler
Constants ¶
const DNSStubAddress = "198.51.100.53"
DNSStubAddress is the address the DNS stub answers every A query with. It comes from TEST-NET-2, so nothing answers it, and a suite that resolves a name to it knows the answer came from the stub.
const DefaultKeepAliveInterval = 15 * time.Second
DefaultKeepAliveInterval is the default interval between SSE keep-alive comments.
const DefaultSessionConnectWait = 10 * time.Second
DefaultSessionConnectWait is how long a relay waits for the node's connection by default: the control plane's default PLEXSPHERE_ACCESS_ATTACH_DIAL_TIMEOUT.
Variables ¶
This section is empty.
Functions ¶
func GenerateCATLSConfig ¶ added in v0.38.0
GenerateCATLSConfig creates an ECDSA P-256 CA and a leaf it signed. It returns a TLS configuration that presents the leaf, and the CA certificate as PEM. The leaf is valid for "mock-api" and "plexd-e2e-mockapi", the names the Docker and systemd suites reach the mock by, and for "localhost". The Kubernetes suite's name for the mock is not among them; that suite skips verification. The configuration sends the leaf only, as a control plane behind a private CA does, so a client accepts it only when it trusts the CA or skips verification.
Types ¶
type AssertionCounters ¶
type AssertionCounters struct {
RegisterCount int64 `json:"registration_count"`
HeartbeatCount int64 `json:"heartbeat_count"`
StateCount int64 `json:"state_count"`
KeyRotateCount int64 `json:"key_rotate_count"`
CapabilitiesCount int64 `json:"capabilities_count"`
EndpointCount int64 `json:"endpoint_count"`
EndpointCandidatesCount int64 `json:"endpoint_candidates_count"`
SecretsCount int64 `json:"secrets_count"`
SecretsRateLimitedCount int64 `json:"secrets_rate_limited_count"`
ReportPutCount int64 `json:"report_put_count"`
ReportDeleteCount int64 `json:"report_delete_count"`
ExecutionCallbackCount int64 `json:"execution_callback_count"`
ExecutionUploadCount int64 `json:"execution_upload_count"`
MetricsCount int64 `json:"metrics_count"`
LogsCount int64 `json:"logs_count"`
AuditCount int64 `json:"audit_count"`
SessionActivityCount int64 `json:"session_activity_count"`
// SessionActivityRejectedCount counts the liveness refusals (404/409) of the
// session activity endpoint. A structural 400 counts nowhere.
SessionActivityRejectedCount int64 `json:"session_activity_rejected_count"`
// RegisterRateLimitedCount counts the registrations an armed token rate
// limit refused (POST /test/configure-register).
RegisterRateLimitedCount int64 `json:"registration_rate_limited_count"`
// SessionActiveCount counts the accepted tcp session_active rows. They count
// on no other counter, because the control plane records them only as a
// last-active touch.
SessionActiveCount int64 `json:"session_active_count"`
// SessionConnectionCount counts the connections the session connection
// route handed to a waiting relay.
SessionConnectionCount int64 `json:"session_connection_count"`
// SessionConnectionRejectedCount counts the session connection route's
// 404, 409 and 426 answers. Its 403 for another node's path counts nowhere.
SessionConnectionRejectedCount int64 `json:"session_connection_rejected_count"`
// SessionConnectionTimeoutCount counts the relays that waited out their
// expires_at without the node's connection.
SessionConnectionTimeoutCount int64 `json:"session_connection_timeout_count"`
IntegrityViolationCount int64 `json:"integrity_violation_count"`
HandshakeReportCount int64 `json:"handshake_report_count"`
PolicyStatusCount int64 `json:"policy_status_count"`
IngressStatusCount int64 `json:"ingress_status_count"`
UserAccessStatusCount int64 `json:"user_access_status_count"`
SiteToSiteStatusCount int64 `json:"site_to_site_status_count"`
EdgePSKCount int64 `json:"edge_psk_count"`
HookFetchCount int64 `json:"hook_fetch_count"`
InjectEventCount int64 `json:"inject_event_count"`
EventsRequestCount int64 `json:"events_request_count"`
LocalMetricsCount int64 `json:"local_metrics_count"`
LocalLogsCount int64 `json:"local_logs_count"`
LocalAuditCount int64 `json:"local_audit_count"`
// node that presents the wrong credential drives this above zero, which is
// exactly the defect the suite failed to catch before the gate existed.
UnauthorizedCount int64 `json:"unauthorized_count"`
}
AssertionCounters holds call counters for each tracked endpoint.
type DNSStub ¶ added in v0.29.0
type DNSStub struct {
// contains filtered or unexported fields
}
DNSStub is a DNS server that stands in for the resolvers a forwarding setting names, so the e2e suites can prove a query reaches them through the agent. It answers over UDP and TCP on one address, from any source:
- a name whose first label is "nx", in any case, gets NXDOMAIN;
- a name whose first label is "drop", in any case, gets no reply at all;
- any other A query gets one A record, DNSStubAddress with a TTL of 10;
- any other query gets NOERROR with no record.
Every reply carries the query's ID, opcode, RD bit and question, with QR and RA set, and an OPT record when the query carried one.
func ListenDNS ¶ added in v0.29.0
ListenDNS binds UDP and TCP on addr, a host:port as net.Listen takes it, and returns the stub that serves them once Serve runs. A failure of either bind fails ListenDNS and closes the socket that did bind. With port 0, UDP binds first on a port the kernel chooses and TCP takes that number. When TCP refuses it, each later try draws a port from the dynamic ports at random and binds both on it, up to ten tries in all: a fresh port from the kernel would be the neighbour of the refused one on Windows, which keeps runs of 100 and more neighbouring ports reserved for one protocol and still hands them out to the other on port 0.
func (*DNSStub) Addr ¶ added in v0.29.0
Addr returns the address the stub is bound to, with the port the kernel chose when addr named port 0. It is the same for UDP and TCP.
func (*DNSStub) Serve ¶ added in v0.29.0
Serve answers queries until ctx ends, then closes both sockets and every open TCP connection, waits for the goroutine of each to finish, and returns nil. A UDP read or a TCP accept that fails while ctx is live stops serving the same way and is returned. A stub serves once: a second Serve finds the sockets closed and serves nothing.
type Server ¶
type Server struct {
// KeepAliveInterval controls the SSE keep-alive comment interval.
// Defaults to DefaultKeepAliveInterval (15s). Set before calling Handler().
KeepAliveInterval time.Duration
// SessionConnectWait is how long a relay opened through
// POST /test/session-connect waits for the node's connection once it has
// published session_connect, and so how far ahead the event's expires_at
// lies. Defaults to DefaultSessionConnectWait (10s). Set before calling
// Handler().
SessionConnectWait time.Duration
// contains filtered or unexported fields
}
Server is a mock Central API server that returns fixture data.
func (*Server) Assertions ¶
func (s *Server) Assertions() AssertionCounters
Assertions returns a snapshot of the current call counters.
func (*Server) BearerEnvelope ¶ added in v0.4.0
BearerEnvelope returns the credential every authenticated route admits, in the exact form a client must present it. The e2e scripts fetch it from GET /test/bearer so the fixture keeps one source of truth for the node id and the nsk, and the `<env>` segment is deliberately not the agent's `plexd`: the gate gets its authority from the payload, not from the tag.
func (*Server) BroadcastSSE ¶
BroadcastSSE assigns the next stream sequence to the envelope, records it in the replay ring (dropping the oldest beyond eventRingCap), and fans it out to every connected client non-blocking. Recording happens even with zero clients and while descoped, so a later reconnect can replay from a cursor. A client whose channel is full is skipped to avoid blocking the broadcaster.
func (*Server) ExpectedBearerToken ¶
ExpectedBearerToken returns the expected bearer token (for testing).
func (*Server) GetState ¶
func (s *Server) GetState() api.NodeStateSnapshot
GetState returns the current state fixture with the peers, executions, sessions, secrets, and shared_subnets slices normalized to non-nil so they always serialize as [] rather than null; the contract never sends null for shared_subnets. The fifteen envelope members carry no omitempty, so all keys are emitted (null for unpopulated blocks). The hooks block is left as configured: a fixture without one serves null, which keeps every hook a rollout installed. The dns block is left as configured too: a fixture without one serves null, which keeps the names the node holds. So is the failure_detection block: a fixture without one serves null, which keeps the failure-detection time the node holds.
The result is a SHALLOW copy: the policy, bridge, state, reports, and dns pointers and the peers, executions, sessions, secrets, and shared_subnets backing arrays alias the live fixture, and so do the failure_detection bytes. Reading is safe — SetState replaces the whole struct under the mutex, so no caller observes a half-written fixture — but callers must NOT mutate through the returned pointers or slices, which would race the state handler serving a concurrent request. Change the fixture with SetState instead.
func (*Server) Handler ¶
Handler returns the http.Handler for use with httptest or a real listener. Every authenticated route is served behind the bearer-envelope gate, so the suite exercises the credential contract rather than assuming it.
func (*Server) LastRequestBody ¶
LastRequestBody returns the last captured request body for the given endpoint.
func (*Server) SetEndpointTTL ¶ added in v0.2.0
SetEndpointTTL updates the stale_after TTL applied by the endpoint handler.
func (*Server) SetHeartbeatResponse ¶
func (s *Server) SetHeartbeatResponse(resp api.HeartbeatResponse)
SetHeartbeatResponse updates the mutable heartbeat response fixture.
func (*Server) SetState ¶
func (s *Server) SetState(state api.NodeStateSnapshot)
SetState updates the mutable state fixture returned by GET /v1/nodes/{id}/state and seeds the execution state machine from the configured executions block, so an entry configured mid-flight resumes on the callback roster: a configured ack or started status seeds that state, while pending seeds nothing and the first legal callback for it stays ack. Seeding is skip-if-present — a re-posted snapshot must never regress an execution the node has already advanced. The two locks are never held at once: execMu is taken only after stateFixtureMu is released.
An entry carrying cancel_requested_at models the control plane's cancel of the Execution. The control plane ends a target that is still waiting at once, so when the entry's status is pending or ack the mock records it as cancelled: the entry drains from the next pull, and the node's late ack or started is answered 409 execution_already_terminal. The status checked is the tracked one when the mock tracks the id, otherwise the configured one, because the node may have advanced past what a re-posted fixture says. This is the one case in which SetState overwrites a tracked state. A started entry keeps its state and is served with the field, so the node can stop the run and report cancelled itself. A terminal one is left alone.
Every configured session carrying a session_id is also recorded in the session registry, which is never pruned, so an id drained by a later snapshot stays distinguishable from one that was never configured.
func (*Server) SetTLSCA ¶ added in v0.38.0
SetTLSCA sets the CA certificate GET /test/tls-ca serves: the PEM that GenerateCATLSConfig returns beside its configuration. The bytes are copied, so the caller may reuse its slice.
func (*Server) TLSHandler ¶
TLSHandler returns an http.Handler for the local endpoint TLS listener. It registers local endpoint routes plus test assertion/last-request routes.