Documentation
¶
Index ¶
- Constants
- Variables
- func CanonicalBytes(env Envelope) ([]byte, error)
- func IsEdgePSKNotServed(err error) bool
- func IsEndpointCandidatesNotServed(err error) bool
- func IsEventBusNotProvisioned(err error) bool
- func IsHandshakeReportNotServed(err error) bool
- func IsHookMetadataRefused(err error) bool
- func IsIngestNotProvisioned(err error) bool
- func IsIngestPermanentlyRefused(err error) bool
- func IsIngestTooLarge(err error) bool
- func IsIngressStatusNotServed(err error) bool
- func IsPolicyStatusNotProvisioned(err error) bool
- func IsPolicyStatusNotServed(err error) bool
- func IsRelayStatusNotServed(err error) bool
- func IsSecretAccessRevoked(err error) bool
- func IsSessionRevokedOrExpired(err error) bool
- func IsSiteToSiteStatusNotServed(err error) bool
- func IsTokenRateLimited(err error) bool
- func IsUserAccessStatusNotServed(err error) bool
- func LoadRootCAs(caFile string, logger *slog.Logger) (*x509.CertPool, error)
- func RedactURLError(err error) error
- func SignedMessage(env Envelope) ([]byte, error)
- func ValidHookName(name string) bool
- func ValidIngressReason(s string) bool
- func ValidIngressRuleID(s string) bool
- func ValidIngressTargetNodeID(s string) bool
- func ValidSecretName(name string) bool
- func ValidSiteToSiteTunnelID(s string) bool
- func ValidUserAccessProviderID(s string) bool
- type APIError
- type ActionInfo
- type ActionParam
- type AuditBatch
- type AuditEntry
- type AuditEvent
- type BinaryInfo
- type BridgeInfo
- type BridgeSnapshot
- type CapabilityManifestRequest
- type Clock
- type Config
- type ConnectFunc
- type ControlPlane
- func (c *ControlPlane) ConnectSSE(ctx context.Context, nodeID, lastEventID string) (*http.Response, error)
- func (c *ControlPlane) CredentialRefused() bool
- func (c *ControlPlane) DeleteStateReport(ctx context.Context, nodeID, key string) error
- func (c *ControlPlane) ExecutionCallback(ctx context.Context, nodeID, executionID string, req ExecutionCallbackRequest) (*ExecutionCallbackResponse, error)
- func (c *ControlPlane) FetchEdgePSK(ctx context.Context, nodeID, peerNodeID string) (*EdgePSKEnvelope, error)
- func (c *ControlPlane) FetchHookVersion(ctx context.Context, nodeID, name string, version int) (*NodeHookVersion, error)
- func (c *ControlPlane) FetchSecret(ctx context.Context, nodeID, name string, version int) (*SecretEnvelope, error)
- func (c *ControlPlane) FetchState(ctx context.Context, nodeID string) (*NodeStateSnapshot, error)
- func (c *ControlPlane) GetJSON(ctx context.Context, path string, result any) error
- func (c *ControlPlane) Heartbeat(ctx context.Context, nodeID string, req HeartbeatRequest) (*HeartbeatResponse, error)
- func (c *ControlPlane) OpenSessionConnection(ctx context.Context, nodeID, sessionID, connectionID string) (net.Conn, error)
- func (c *ControlPlane) PostJSON(ctx context.Context, path string, body any, result any) error
- func (c *ControlPlane) PutStateReport(ctx context.Context, nodeID, key string, req NodeStateReportRequest) (*NodeStateReportResponse, error)
- func (c *ControlPlane) Register(ctx context.Context, req RegisterRequest) (*RegisterResponse, error)
- func (c *ControlPlane) ReportAudit(ctx context.Context, nodeID string, events []AuditEvent) (*IngestReceipt, error)
- func (c *ControlPlane) ReportEndpoint(ctx context.Context, nodeID string, req EndpointRequest) (*EndpointResponse, error)
- func (c *ControlPlane) ReportEndpointCandidates(ctx context.Context, nodeID string, req EndpointCandidatesRequest) (*EndpointCandidatesResponse, error)
- func (c *ControlPlane) ReportHandshakes(ctx context.Context, nodeID string, req HandshakeReportRequest) (*HandshakeReportResponse, error)
- func (c *ControlPlane) ReportIngressStatus(ctx context.Context, nodeID string, req IngressStatusRequest) (*IngressStatusResponse, error)
- func (c *ControlPlane) ReportIntegrityViolations(ctx context.Context, nodeID string, req IntegrityViolationsRequest) error
- func (c *ControlPlane) ReportLogs(ctx context.Context, nodeID string, lines []LogLine) (*IngestReceipt, error)
- func (c *ControlPlane) ReportMetrics(ctx context.Context, nodeID string, samples []MetricSample) (*IngestReceipt, error)
- func (c *ControlPlane) ReportPolicyStatus(ctx context.Context, nodeID string, req PolicyStatusRequest) (*PolicyStatusResponse, error)
- func (c *ControlPlane) ReportRelayStatus(ctx context.Context, nodeID string, req RelayStatusRequest) (*RelayStatusResponse, error)
- func (c *ControlPlane) ReportSessionActivity(ctx context.Context, nodeID, sessionID string, req SessionActivityRequest) error
- func (c *ControlPlane) ReportSiteToSiteStatus(ctx context.Context, nodeID string, req SiteToSiteStatusRequest) (*SiteToSiteStatusResponse, error)
- func (c *ControlPlane) ReportUserAccessStatus(ctx context.Context, nodeID string, req UserAccessStatusRequest) (*UserAccessStatusResponse, error)
- func (c *ControlPlane) RotateKeys(ctx context.Context, req KeyRotateRequest) (*KeyRotateResponse, error)
- func (c *ControlPlane) SetAuthToken(token string)
- func (c *ControlPlane) SetCredentialRefused(refused bool)
- func (c *ControlPlane) UpdateCapabilities(ctx context.Context, nodeID string, caps CapabilityManifestRequest) error
- func (c *ControlPlane) UploadExecutionOutput(ctx context.Context, uploadURL string, output []byte) error
- type DataEntry
- type DeclaredHook
- type DeliveryMode
- type DiscoveredPlexdHook
- type Ed25519Verifier
- func (v *Ed25519Verifier) Install(key NodeStateSigningKey) (bool, error)
- func (v *Ed25519Verifier) Rotate(rot SigningKeyRotation) error
- func (v *Ed25519Verifier) TrustedKeys(now time.Time) []ed25519.PublicKey
- func (v *Ed25519Verifier) Verify(_ context.Context, env Envelope) error
- func (v *Ed25519Verifier) VerifySignature(env Envelope) error
- type EdgePSKEnvelope
- type EndpointCandidatesRequest
- type EndpointCandidatesResponse
- type EndpointRequest
- type EndpointResponse
- type Envelope
- type EventDispatcher
- type EventHandler
- type EventVerifier
- type ExecutionCallbackRequest
- type ExecutionCallbackResponse
- type ExecutionOutput
- type FailureAction
- type HandshakeReportPeer
- type HandshakeReportRequest
- type HandshakeReportResponse
- type HeartbeatRequest
- type HeartbeatResponse
- type HookInfo
- type HookRolloutError
- type HookVersionPayload
- type IngestReceipt
- type IngressACME
- type IngressClientAuth
- type IngressConditions
- type IngressConfig
- type IngressHeaderCondition
- type IngressInfo
- type IngressRule
- type IngressStatusClientRefusal
- type IngressStatusRequest
- type IngressStatusResponse
- type IngressStatusRule
- type IngressStatusTarget
- type IngressTarget
- type IntegrityDetector
- type IntegrityViolationKind
- type IntegrityViolationReport
- type IntegrityViolationsRequest
- type IntegrityViolationsResponse
- type K8sActivity
- type KeyRotateRequest
- type KeyRotateResponse
- type LocalEndpointConfig
- type LogBatch
- type LogEntry
- type LogLine
- type MetricBatch
- type MetricPoint
- type MetricSample
- type NoOpVerifier
- type NodeHookVersion
- type NodeStateBlock
- type NodeStateDNS
- type NodeStateDNSForwardZone
- type NodeStateDNSForwarding
- type NodeStateDNSHost
- type NodeStateDNSRecord
- type NodeStateExecution
- type NodeStateFailureDetection
- type NodeStateHook
- type NodeStateReportRequest
- type NodeStateReportResponse
- type NodeStateSecret
- type NodeStateSession
- type NodeStateSigningKey
- type NodeStateSnapshot
- type Peer
- type PolicyRevisionRef
- type PolicyRule
- type PolicySnapshot
- type PolicyStatusApplied
- type PolicyStatusDrops
- type PolicyStatusRejected
- type PolicyStatusRequest
- type PolicyStatusResponse
- type PollFunc
- type PortRange
- type ReachabilitySnapshot
- type ReconcileTrigger
- type ReconnectEngine
- func (r *ReconnectEngine) Mode() DeliveryMode
- func (r *ReconnectEngine) Run(ctx context.Context, connectFn ConnectFunc, pollFn PollFunc) error
- func (r *ReconnectEngine) SetBaseInterval(d time.Duration)
- func (r *ReconnectEngine) SetClock(c Clock)
- func (r *ReconnectEngine) SetIntervals(base, max time.Duration)
- func (r *ReconnectEngine) SetOnModeChange(fn func(DeliveryMode))
- func (r *ReconnectEngine) SetPollInterval(d time.Duration)
- func (r *ReconnectEngine) SetPollingFallbackConfig(fallbackAfter, pollInterval time.Duration)
- func (r *ReconnectEngine) SetReprobeInterval(d time.Duration)
- type RegisterPeer
- type RegisterRequest
- type RegisterResponse
- type RelayAssignment
- type RelayConfig
- type RelayStatusRequest
- type RelayStatusResponse
- type RetryCallback
- type SSEEvent
- type SSEManager
- func (m *SSEManager) Mode() DeliveryMode
- func (m *SSEManager) RegisterHandler(eventType string, handler EventHandler)
- func (m *SSEManager) SetIdleTimeout(d time.Duration)
- func (m *SSEManager) SetOnModeChange(fn func(DeliveryMode))
- func (m *SSEManager) SetPollFunc(fn PollFunc)
- func (m *SSEManager) SetPollingFallback(fallbackAfter, pollInterval time.Duration)
- func (m *SSEManager) SetReconcileTrigger(t ReconcileTrigger)
- func (m *SSEManager) SetReconnectIntervals(base, max time.Duration)
- func (m *SSEManager) SetReprobeInterval(d time.Duration)
- func (m *SSEManager) Shutdown()
- func (m *SSEManager) Start(ctx context.Context, nodeID string) error
- type SSEParser
- type SSEStream
- type SSHActivity
- type SecretEnvelope
- type SecretRef
- type SessionActivityRequest
- type SessionConnectRequest
- type SessionRevocation
- type SessionTarget
- type SessionTargetK8s
- type SessionTargetSSH
- type SessionTargetTCP
- type SigningKeyRotation
- type SiteToSiteConfig
- type SiteToSiteInfo
- type SiteToSiteStatusRequest
- type SiteToSiteStatusResponse
- type SiteToSiteStatusTunnel
- type SiteToSiteTunnel
- type SiteToSiteTunnelInfo
- type SnapshotPeer
- type StateEntry
- type TCPActivity
- type UserAccessConfig
- type UserAccessDevice
- type UserAccessInfo
- type UserAccessProvider
- type UserAccessProviderInfo
- type UserAccessStatusProvider
- type UserAccessStatusRequest
- type UserAccessStatusResponse
Constants ¶
const ( // Contract types are emitted by the control plane per the OpenAPI events // document. Their payloads are treated as opaque: the reconciler pull is // authoritative, so each of these events triggers a reconcile. EventNodeStateUpdated = "node_state_updated" EventPolicyUpdated = "policy_updated" EventBridgeConfigUpdated = "bridge_config_updated" // EventActionRequest exists as a push-latency optimisation: action // dispatches are delivered in the executions block of the state pull, so the // event's payload is opaque and it triggers a reconcile like the rest of the // tier — the resulting pull carries the dispatch. EventActionRequest = "action_request" // EventSessionSetup is the same push-latency optimisation for mediated // access: sessions are delivered in the sessions block of the state pull, so // the event's payload is opaque and it triggers a reconcile like the rest of // the tier — the resulting pull carries the session. EventSessionSetup = "session_setup" // EventNodeSecretsUpdated carries the node's full secret inventory, but the // inventory also rides the secrets block of the state pull, which is // authoritative: the payload is treated as opaque and the event triggers a // reconcile like the rest of the tier, so an event that arrives late can // never roll the node API's secret index back. EventNodeSecretsUpdated = "node_secrets_updated" // Documented-coming family: types that land with the platform's 14-type // taxonomy. They are already named so the agent can subscribe to them once // the control plane starts emitting them; every one triggers a reconcile. EventPeerRegistered = "peer_registered" EventPeerPSKAssigned = "peer_psk_assigned" EventPeerDeregistered = "peer_deregistered" EventPeerEndpointChanged = "peer_endpoint_changed" EventRotateKeys = "rotate_keys" EventPeerKeyRotated = "peer_key_rotated" EventSigningKeyRotated = "signing_key_rotated" // EventSessionRevoked names a session the control plane revoked, in a // SessionRevocation payload. tunnel.Dispatcher.SessionRevokedHandler closes // that session when it is live and reports the payload's revoke_reason as // its terminated_by, then triggers a reconcile. The session leaving the // pull's sessions block stays the teardown for a revocation whose event // never arrives. EventSessionRevoked = "session_revoked" // EventSessionConnect asks the node to open one connection for an ssh // session it serves, in a SessionConnectRequest payload. The control plane // sends it when a client attaches to the session, and // tunnel.Dispatcher.SessionConnectHandler opens the connection with // ControlPlane.OpenSessionConnection and serves the session's SSH login on // it. It carries no desired state, so it triggers no reconcile. EventSessionConnect = "session_connect" )
const ( // ReachabilityHealthy marks a node whose heartbeats arrive on schedule. ReachabilityHealthy = "healthy" // ReachabilityStale marks a node whose last admitted heartbeat is older than // the control plane's freshness window. ReachabilityStale = "stale" // ReachabilityUnreachable marks a node the control plane has given up on. ReachabilityUnreachable = "unreachable" // ReachabilityNeverReported marks a node whose first heartbeat was never // admitted. It is the verdict a freshly enrolled node is born with. ReachabilityNeverReported = "never_reported" )
Reachability verdicts the platform contract documents today. The set is open: these are the values plexd expects to see, not the values it accepts.
const ( RevokeReasonOperatorRequest = "operator_request" RevokeReasonPolicyViolation = "policy_violation" RevokeReasonIdentityCompromise = "identity_compromise" RevokeReasonResourceDecommissioned = "resource_decommissioned" RevokeReasonTTLExpired = "ttl_expired" RevokeReasonIdleTimeout = "idle_timeout" )
Reasons the control plane revokes a session, carried on SessionRevocation.RevokeReason. The first four are operator-driven, supplied on the explicit revoke call; the last two are set by the control plane's sweeper when the session reaches its hard expiry or its idle timeout.
const ( // ActionKindBuiltin dispatches an action built into plexd. ActionKindBuiltin = "builtin" // ActionKindHook dispatches a hook registered by the node. ActionKindHook = "hook" // ActionKindPlexdHook dispatches a PlexdHook resource of the node's // cluster. The entry's Action is the resource's metadata.name. ActionKindPlexdHook = "plexd_hook" )
The three legal values of a NodeStateExecution.Type.
const ( // ExecutionStatusAck acknowledges receipt of the action request. ExecutionStatusAck = "ack" // ExecutionStatusStarted reports that the action has begun running. ExecutionStatusStarted = "started" // ExecutionStatusSucceeded is the terminal callback for a successful run. ExecutionStatusSucceeded = "succeeded" // ExecutionStatusFailed is the terminal callback for a failed run. ExecutionStatusFailed = "failed" // ExecutionStatusCancelled is the terminal callback for a cancelled run. ExecutionStatusCancelled = "cancelled" )
Execution callback statuses a node reports on the v1 execution callback (POST /v1/nodes/{node_id}/executions/{execution_id}).
const ( // CodeNSKNodeMismatch (403) means the callback's node id does not match the // node identified by the NSK bearer credential. CodeNSKNodeMismatch = "nsk_node_mismatch" // CodeInvalidStateTransition (409) means the callback would advance the // invocation along an illegal edge of the execution state machine. CodeInvalidStateTransition = "invalid_state_transition" // CodeExecutionAlreadyTerminal (409) means the invocation has already // settled and accepts no further callbacks. CodeExecutionAlreadyTerminal = "execution_already_terminal" )
RFC 9457 problem codes with which the control plane refuses an execution callback. A refusal carrying one of these is deliberate and permanent: the node must stop driving the execution instead of retrying or double-reporting.
const ( // SessionKindSSH mediates an SSH session; Target.SSH is set. SessionKindSSH = "ssh" // SessionKindK8s mediates a Kubernetes API session; Target.K8s is set. SessionKindK8s = "k8s" // SessionKindTCP mediates a plain TCP forward; Target.TCP is set. SessionKindTCP = "tcp" )
The three legal values of a NodeStateSession.Kind.
const ( MetricGroupNodeResources = "node_resources" MetricGroupTunnelHealth = "tunnel_health" MetricGroupPeerLatency = "peer_latency" MetricGroupAgentStats = "agent_stats" )
Wire metric groups (closed set; out-of-set → 400 ingest_batch_malformed).
const ( // HookSourceLocal marks a hook placed on the node by other means than a // rollout, such as a script in hooks_dir. Its pin is the digest first seen. HookSourceLocal = "local" // HookSourceRollout marks a script installed from a published hook // version. Its pin is the checksum the pull delivered. HookSourceRollout = "rollout" )
Values of DeclaredHook.Source and HookInfo.Source: where a hook the agent runs came from. The wire treats an absent source as local, which is why a hand-placed hook is sent with no source key at all.
const ( // HookRolloutCodeCollision means hooks_dir holds a hook of the rollout's // name. The node leaves that hook in place, keeps reporting it as local, // and reports the collision rather than resolving it. HookRolloutCodeCollision = "collision" // HookRolloutCodeVerificationFailed means the node fetched the version, // and its signature or its checksum did not verify. HookRolloutCodeVerificationFailed = "verification_failed" // HookRolloutCodeFetchFailed means the node could not fetch the version. HookRolloutCodeFetchFailed = "fetch_failed" // HookRolloutCodeInstallFailed means the node could not install the // version, or will not on this platform or under this configuration. HookRolloutCodeInstallFailed = "install_failed" )
Codes of a HookRolloutError the contract documents. The control plane accepts any code that matches ^[a-z0-9_]{1,64}$ and shows it as sent, so a newer agent's code never refuses the manifest.
const ( // MaxHookRolloutErrors is the most entries one manifest may carry. MaxHookRolloutErrors = 64 // MaxHookRolloutDetailChars is the longest detail, in Unicode code points. MaxHookRolloutDetailChars = 1024 )
Limits the control plane puts on hook_rollout_errors. plexd keeps a copy so a manifest it builds stays inside them; IsHookMetadataRefused covers the case where the copies drift apart.
const ( // RelayStateRunning marks a relay whose socket is bound on ListenPort. RelayStateRunning = "running" // RelayStateStopped marks a relay that does not run: the pull does not // enable it, names a listen_port outside 1..65535, or plexd stops it // because it shuts down. RelayStateStopped = "stopped" // RelayStateBindFailed marks a relay whose socket could not be bound on // ListenPort. RelayStateBindFailed = "bind_failed" // RelayStateNotConsented marks a relay the pull enables while // bridge.relay_enabled does not consent to it. RelayStateNotConsented = "not_consented" )
Relay states of a RelayStatusRequest.
const ( // IngressStateEnabled marks a bridge whose local configuration serves the // public ingress rules the state pull enables. IngressStateEnabled = "enabled" // IngressStateOptedOut marks a bridge whose local configuration, // bridge.ingress_enabled: false, rules public ingress out: it opens no // public listener whatever the pull says. IngressStateOptedOut = "opted_out" )
Ingress states of an IngressStatusRequest.
const ( // IngressListenerListening marks a rule whose listen port is bound. IngressListenerListening = "listening" // IngressListenerNotListening marks a rule the bridge does not listen // for; ListenerReason says why. IngressListenerNotListening = "not_listening" // IngressCertificateNotRequired marks a passthrough rule, which needs no // certificate at the bridge. IngressCertificateNotRequired = "not_required" // IngressCertificateReady marks a terminate or acme rule whose // certificate is in place. IngressCertificateReady = "ready" // IngressCertificateNotReady marks a terminate or acme rule without its // certificate; CertificateReason says why. IngressCertificateNotReady = "not_ready" // IngressDialNone marks a rule for which the bridge has dialled no target // yet, or a target it has not dialled yet. For a udp rule a dial is a // send of a client's datagram. IngressDialNone = "none" // IngressDialSucceeded marks a rule whose last unit a target took, or a // target whose last dial succeeded. IngressDialSucceeded = "succeeded" // IngressDialFailed marks a rule whose last unit no target took, or a // target whose last dial failed; DialReason says why. IngressDialFailed = "failed" )
The facets of an IngressStatusRule.
const ( // UserAccessStateEnabled marks a bridge whose local configuration serves // the user access providers the state pull enables. UserAccessStateEnabled = "enabled" // UserAccessStateOptedOut marks a bridge whose local configuration, // bridge.user_access_enabled: false, rules user access out: it serves no // provider whatever the pull says. UserAccessStateOptedOut = "opted_out" )
User access states of a UserAccessStatusRequest.
const ( // UserAccessHealthUp marks a provider the bridge serves. UserAccessHealthUp = "up" // UserAccessHealthDown marks a provider the bridge does not serve; Reason // says why. UserAccessHealthDown = "down" )
The health values of a UserAccessStatusProvider.
const ( // SiteToSiteStateEnabled marks a bridge whose local configuration serves // the site-to-site tunnels the state pull enables. SiteToSiteStateEnabled = "enabled" // SiteToSiteStateOptedOut marks a bridge whose local configuration, // bridge.site_to_site_enabled: false, rules site-to-site tunnels out: it // serves no tunnel whatever the pull says. SiteToSiteStateOptedOut = "opted_out" )
Site-to-site states of a SiteToSiteStatusRequest.
const ( // SiteToSiteHealthUp marks a tunnel the bridge serves. SiteToSiteHealthUp = "up" // SiteToSiteHealthDown marks a tunnel the bridge does not serve; Reason // says why. SiteToSiteHealthDown = "down" )
The health values of a SiteToSiteStatusTunnel.
const ( // PolicyEnforcementEnforcing marks a node that programs the rulesets it // applies, with its default deny after them. PolicyEnforcementEnforcing = "enforcing" // PolicyEnforcementDisabled marks a node whose local configuration turned // enforcement off (policy.enabled: false). PolicyEnforcementDisabled = "disabled" // firewall backend that can program rules. PolicyEnforcementUnavailable = "unavailable" )
Enforcement values of a PolicyStatusRequest.
const ( // TCPPhaseSessionStarted marks the opening of a TCP session. TCPPhaseSessionStarted = "session_started" // TCPPhaseSessionActive reports that a TCP session forwarded bytes since its // previous session_active row. The row carries Phase alone. TCPPhaseSessionActive = "session_active" // TCPPhaseSessionEnded marks the close of a TCP session. TCPPhaseSessionEnded = "session_ended" )
TCP session lifecycle phases reported on a TCPActivity.
const ( // SSHPhaseSessionStarted marks an SSH session ready to serve the // connections the control plane asks for. SSHPhaseSessionStarted = "session_started" // SSHPhaseSessionEnded marks the close of an SSH session. SSHPhaseSessionEnded = "session_ended" )
SSH session lifecycle phases reported on an SSHActivity.
const ( // TerminatedByTTLExpired means the session reached its time-to-live. TerminatedByTTLExpired = "ttl_expired" // TerminatedByIdleTimeout means the session was idle past its timeout. TerminatedByIdleTimeout = "idle_timeout" // TerminatedByPlexdClose means plexd closed the session locally. TerminatedByPlexdClose = "plexd_close" // TerminatedByOperatorRevoke means the operator's access was revoked. TerminatedByOperatorRevoke = "operator_revoke" )
Reasons a TCP or SSH session was terminated, reported on a session_ended TCPActivity or SSHActivity.
const ( // UserAccessKindWireGuard is a WireGuard interface on the bridge that // admits the devices the operator registers by their public keys. UserAccessKindWireGuard = "wireguard" // UserAccessKindTailscale joins the bridge to a tailnet. UserAccessKindTailscale = "tailscale" // UserAccessKindNetbird joins the bridge to a NetBird network. UserAccessKindNetbird = "netbird" )
The kinds of a user access provider.
const ( IngressModePassthrough = "passthrough" IngressModeTerminate = "terminate" IngressModeACME = "acme" )
The modes of an ingress rule.
const ( IngressProtocolTCP = "tcp" IngressProtocolUDP = "udp" )
The protocols of an ingress rule. A tcp rule forwards the connections that reach its listen port, and a udp rule the datagrams.
const ( // SiteToSiteKindWireGuard is a WireGuard interface on the bridge with // one peer, the remote site. SiteToSiteKindWireGuard = "wireguard" // SiteToSiteKindIPsec is an IKE connection to the remote site, // authenticated with a pre-shared key. SiteToSiteKindIPsec = "ipsec" // SiteToSiteKindOpenVPN is a point-to-point OpenVPN connection to the // remote site with a static key. SiteToSiteKindOpenVPN = "openvpn" )
The kinds of a site-to-site tunnel.
const DefaultConnectTimeout = 10 * time.Second
DefaultConnectTimeout is the default TCP connect timeout.
const DefaultRequestTimeout = 30 * time.Second
DefaultRequestTimeout is the default HTTP request timeout.
const DefaultSSEIdleTimeout = 90 * time.Second
DefaultSSEIdleTimeout is the default SSE idle timeout.
const DefaultSSEReprobeInterval = 10 * time.Minute
DefaultSSEReprobeInterval is how often pull-only delivery mode re-probes the descoped SSE endpoint to detect that it has come back.
const DefaultStalenessWindow = 5 * time.Minute
DefaultStalenessWindow is the maximum age of an event before it is considered stale.
const EdgePSKEnvelopeSize = 60
EdgePSKEnvelopeSize is the exact length of an edge-PSK envelope: the 12-byte AES-256-GCM nonce, the 32-byte PSK and the 16-byte GCM tag.
const ( // ExecutionStatusPending marks an execution the control plane has dispatched // and the node has not yet acknowledged. It appears in the executions block // of the node state snapshot and is never reported by a node on the // execution callback. ExecutionStatusPending = "pending" )
Execution status observed only on the pull block.
const HookVersionEnvelopeType = "hook_version"
HookVersionEnvelopeType is the type of the envelope a published hook version is signed in. The envelope is not an event and never rides the event stream, so the type sits here rather than among the SSE event types.
const MaxEndpointCandidates = 8
MaxEndpointCandidates is the contract's ceiling on one candidate report.
const MaxHandshakeReportPeers = 4096
MaxHandshakeReportPeers is the contract's ceiling on the peers array of one handshake report. A longer array is refused whole with 400 malformed_handshake_report, taking every edge in it down, so ReportHandshakes refuses one before sending it.
const MaxIngressStatusClientRefusals = 8
MaxIngressStatusClientRefusals is the contract's ceiling on the refusal entries of one rule entry.
const MaxIngressStatusDialAgeSeconds = 2147483647
MaxIngressStatusDialAgeSeconds is the contract's ceiling on dial_age_seconds, the largest signed 32-bit integer.
const MaxIngressStatusRefusalAgeSeconds = 2147483647
MaxIngressStatusRefusalAgeSeconds is the contract's ceiling on a refusal's age_seconds, the largest signed 32-bit integer.
const MaxIngressStatusRules = 1024
MaxIngressStatusRules is the contract's ceiling on the entries of one ingress status report.
const MaxIngressStatusTargets = 8
MaxIngressStatusTargets is the contract's ceiling on the target entries of one rule entry, the most targets a rule holds.
const MaxIntegrityViolationsPerBatch = 128
MaxIntegrityViolationsPerBatch is the contract's per-request ceiling on the violations array. A larger batch is refused whole with 400 integrity_violations_too_many, and an empty one with integrity_violations_empty.
const MaxRelayStatusBoundSeconds = 315360000
MaxRelayStatusBoundSeconds is the contract's ceiling on bound_seconds.
const MaxSiteToSiteStatusTunnels = 256
MaxSiteToSiteStatusTunnels is the contract's ceiling on the entries of one site-to-site status report. A bridge with more tunnels reports the first ones in the order of the pull.
const MaxUserAccessStatusProviders = 256
MaxUserAccessStatusProviders is the contract's ceiling on the entries of one user access status report. A bridge with more providers reports the first ones in the order of the pull.
Variables ¶
var ( ErrBadRequest = &APIError{StatusCode: 400, Message: "bad request"} ErrForbidden = &APIError{StatusCode: 403, Message: "forbidden"} ErrNotFound = &APIError{StatusCode: 404, Message: "not found"} ErrConflict = &APIError{StatusCode: 409, Message: "conflict"} ErrPayloadTooLarge = &APIError{StatusCode: 413, Message: "payload too large"} ErrUnprocessable = &APIError{StatusCode: 422, Message: "unprocessable entity"} ErrRateLimit = &APIError{StatusCode: 429, Message: "rate limit exceeded"} ErrServer = &APIError{StatusCode: 500, Message: "server error"} )
Sentinel errors for common HTTP error status codes.
var ( ErrIntegrityViolationsEmpty = errors.New("integrity violation batch is empty") ErrIntegrityViolationsTooMany = fmt.Errorf("integrity violation batch exceeds %d entries", MaxIntegrityViolationsPerBatch) )
ErrIntegrityViolationsEmpty and ErrIntegrityViolationsTooMany are returned by ReportIntegrityViolations before any HTTP request when the batch is outside the contract's 1..MaxIntegrityViolationsPerBatch bounds.
var ErrCredentialRefused = errors.New("api: node credential refused by the control plane, requests suspended until a heartbeat is accepted")
ErrCredentialRefused is returned before any HTTP request by every call that presents the node's bearer credential while the client is marked refused (see ControlPlane.SetCredentialRefused). The heartbeat marks it after the control plane keeps answering 401, which is how a removed Node's agent stops calling at its usual rates. It is deliberately not an *APIError: no response was received, so errors.Is(err, ErrUnauthorized) stays false for it.
var ErrEndpointCandidatesTooMany = fmt.Errorf("endpoint candidate report exceeds %d candidates", MaxEndpointCandidates)
ErrEndpointCandidatesTooMany is returned by ReportEndpointCandidates before any HTTP request when the report carries more than MaxEndpointCandidates candidates.
var ErrHandshakeReportTooMany = fmt.Errorf("handshake report exceeds %d peers", MaxHandshakeReportPeers)
ErrHandshakeReportTooMany is returned by ReportHandshakes before any HTTP request when the report carries more than MaxHandshakeReportPeers peers.
var ErrHookNameInvalid = fmt.Errorf("hook name is outside the grammar %s", hookNamePattern)
ErrHookNameInvalid is returned by FetchHookVersion before any HTTP request when the requested hook name is outside the contract's published-hook name grammar.
var ErrSSEConnectTimeout = errors.New("api: SSE connect timeout")
ErrSSEConnectTimeout is returned when the SSE request does not reach its response headers within the client's request timeout.
var ErrSSEIdleTimeout = errors.New("api: SSE idle timeout")
ErrSSEIdleTimeout is returned when the SSE stream receives no data within the configured idle timeout period.
var ErrSecretNameInvalid = fmt.Errorf("secret name is outside the grammar %s", secretNamePattern)
ErrSecretNameInvalid is returned by FetchSecret before any HTTP request when the requested secret name is outside the contract's name grammar.
Functions ¶
func CanonicalBytes ¶ added in v0.2.0
CanonicalBytes returns the bytes an envelope's signature covers, as the "Signed event envelope" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) defines them: one JSON object with exactly the members id, issued_at, key_id, payload, scope and type in that order, no whitespace, and never the signature. issued_at is UTC with nine fractional digits, scope is an object rather than the wire string, and the payload is decoded and written again with sorted keys and normalised numbers. An absent or empty Payload is null.
The frame's data: line is not the signed message: its member order, time format and payload spelling are whatever the control plane's encoder wrote, so the bytes are rebuilt from the decoded values. This is the single canonical-form seam shared by the agent's verifier and the mock control plane, and it mirrors the control plane's own CanonicalBytes (internal/signing/envelope/canonical.go in plexsphere).
func IsEdgePSKNotServed ¶ added in v0.11.0
IsEdgePSKNotServed reports whether err says the control plane does not serve GET /v1/nodes/{node_id}/peers/{peer_node_id}/psk: a 404 with any code but peer_not_found, or a 501 carrying the psk_delivery_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is peer_not_found: the peer has not landed in the Domain yet, the post-registration lag the contract asks the agent to retry on its next reconcile, so it is not a missing surface.
func IsEndpointCandidatesNotServed ¶ added in v0.11.0
IsEndpointCandidatesNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node_id}/endpoint-candidates: a 404 with any code but endpoint_peer_not_found, or a 501 carrying the endpoint_candidates_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is endpoint_peer_not_found, the first-report race plexsphere/plexsphere#868 documents: the node reports before the control plane has registered it as a peer, and a later cycle heals it, so it is not a missing surface.
func IsEventBusNotProvisioned ¶ added in v0.2.0
IsEventBusNotProvisioned reports whether err is the control plane's long-term descope of the signed event stream for the node: a 501 carrying the signed_event_bus_not_provisioned problem code. Unlike a transient 5xx, this is a durable verdict — the endpoint stays unavailable until the node is re-provisioned — so it is answered by switching to pull-only delivery rather than by retrying against a channel that is not there.
func IsHandshakeReportNotServed ¶ added in v0.10.0
IsHandshakeReportNotServed reports whether err says the control plane does not serve POST /v1/nodes/{node_id}/handshakes: a 404 with any code or none, or a 501 carrying the handshakes_not_provisioned problem code.
The two statuses are one condition met on two control-plane generations. A control plane older than the operation has no route for it, and its router answers 404 with whatever body its not-found handler writes, so no code can be required of it. A control plane that has the route but not the recording service wired answers 501 handshakes_not_provisioned. Either way nothing stores the report until the control plane is upgraded or provisioned, so the reporter says so once and keeps sending on its interval instead of warning on every tick.
Taking every 404 is safe because the operation has none of its own: the contract answers it with 200, 400, 401, 403, 413, 500 or 501, and an entry naming an unknown or deregistered peer is counted as ignored rather than refused. A 501 with another code is a different surface's refusal and stays a failure.
func IsHookMetadataRefused ¶ added in v0.26.0
IsHookMetadataRefused reports whether err is a refusal of a capability manifest that the short form can answer: a 413 with any code or none, or a 400 carrying the malformed_capabilities_request, declared_hook_invalid, declared_hooks_too_many, hook_rollout_errors_too_many or hook_rollout_error_invalid problem code.
A control plane refuses a manifest whole, so the reporter answers each of these by dropping the hook metadata, which keeps a failure of the metadata from costing the manifest. The metadata is every declared-hook field past name and checksum, a rolled-out hook's source and version among them, and the hook_rollout_errors list. A 400 malformed_capabilities_request comes from a control plane that predates the fields and refuses them as unknown keys. A 400 declared_hook_invalid, declared_hooks_too_many, hook_rollout_errors_too_many or hook_rollout_error_invalid means plexd's copy of the limits has drifted from the control plane's. A 413 means the manifest is over budget. It ignores the code because any layer on the path can say so, and a proxy's own 413 carries no problem code.
Every other failure says nothing about the metadata and is not classified here. That includes a 400 with another code or none, such as binary_checksum_invalid, which the short entry would draw again.
func IsIngestNotProvisioned ¶ added in v0.2.0
IsIngestNotProvisioned reports whether err is the control plane's refusal to accept observability ingest because it is not provisioned for the node: a 501 carrying the observability_ingest_not_provisioned problem code.
func IsIngestPermanentlyRefused ¶ added in v0.2.0
IsIngestPermanentlyRefused reports whether err is a refusal of an observability ingest batch that no retry can fix: a 400 carrying the ingest_batch_malformed problem code, which is a verdict on the batch bytes themselves. Re-sending them would draw the identical status forever, so a PlatformReporter drops such a batch rather than returning it for re-buffering.
The sibling refusals are deliberately not permanent. A 400 ingest_sent_at_invalid faults the X-Plexsphere-Sent-At header, which is re-stamped from the wall clock on every attempt, so it clears once the node's clock converges. A 415 faults the Content-Encoding, a transport property of the deployment rather than of the batch, so it clears once the gateway that rejects gzip is fixed. Both are returned to the caller for re-buffering. A 413 is classified by IsIngestTooLarge and answered by splitting the batch, and a 501 not-provisioned refusal by IsIngestNotProvisioned.
func IsIngestTooLarge ¶ added in v0.2.0
IsIngestTooLarge reports whether err is the control plane's refusal of an observability ingest batch for exceeding its size limit: a 413. The batch content is acceptable, only its size is not, so the caller answers by splitting the batch and re-sending the halves rather than dropping it.
func IsIngressStatusNotServed ¶ added in v0.35.0
IsIngressStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node_id}/ingress-status: a 404 with any code but ingress_status_node_gone, or a 501 carrying the ingress_status_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is ingress_status_node_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.
func IsPolicyStatusNotProvisioned ¶ added in v0.31.0
IsPolicyStatusNotProvisioned reports whether err is the 501 carrying the policy_status_not_provisioned problem code: the control plane serves PUT /v1/nodes/{node_id}/policy-status, but its recording service is not wired, so a later report may be accepted.
func IsPolicyStatusNotServed ¶ added in v0.31.0
IsPolicyStatusNotServed reports whether err says the control plane has no route for PUT /v1/nodes/{node_id}/policy-status: a 404 with any code but policy_status_node_gone.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is policy_status_node_gone: the node was removed while the report was in flight. The contract asks the agent to stop reporting until it restarts on any other 404, which is why the 501 of a control plane that serves the route without its recording service is a separate classifier, IsPolicyStatusNotProvisioned.
func IsRelayStatusNotServed ¶ added in v0.23.0
IsRelayStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node_id}/relay-status: a 404 with any code but relay_status_node_gone, or a 501 carrying the relay_status_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is relay_status_node_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.
func IsSecretAccessRevoked ¶ added in v0.15.0
IsSecretAccessRevoked reports whether err is the secret fetch's verdict that the Node may not read the secret: a 403 (no read grant, or a revoked one) or a 404 (no such Secret, or no value at the version read), with any problem code or none. The local-endpoint reporters drop their cached bearer token on it. Every other failure, including a 401, ErrCredentialRefused, a 429 and any 5xx, says nothing about the grant and is not classified here.
func IsSessionRevokedOrExpired ¶ added in v0.8.0
IsSessionRevokedOrExpired reports whether err is the control plane's verdict that the session a session activity callback names has reached a terminal state: a 409 carrying session_already_revoked or session_expired. Like the not-provisioned refusals this is a durable verdict — neither state goes back to live, so re-sending the callback draws the identical status forever — and the node answers it by settling rather than by retrying.
What it settles on is a drain signal, not a teardown. The answer itself never closes a session: the entry leaves the sessions block on a following pull, and the block drain, or a verified session_revoked event naming the session, performs the teardown.
A 404 session_not_found is deliberately not classified here. It is not a terminal state but the sessions block and the session store disagreeing — a lagging read replica, a session record written after the block was rendered, a failover window — and the two are separate reads. The entry standing in the block is the control plane still asking for the session, so the callback stays retryable: settling on the 404 instead would strand a bound listener whose endpoint the control plane never learns, for the whole standing life of its entry.
A 501 access_session_not_provisioned is not classified here either. It faults the callback endpoint rather than the session, and the endpoint may be provisioned mid-session, so it stays retryable too.
func IsSiteToSiteStatusNotServed ¶ added in v0.36.0
IsSiteToSiteStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node_id}/site-to-site-status: a 404 with any code but site_to_site_status_node_gone, or a 501 carrying the site_to_site_status_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is site_to_site_status_node_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.
func IsTokenRateLimited ¶ added in v0.33.0
IsTokenRateLimited reports whether err is the control plane's refusal of a registration by the rate limit of the token's BootstrapToken policy: a 429 carrying the token_rate_limited problem code.
The answer is a verdict on the token, not on the caller: the token is valid, the refusal did not count as a redemption, and the same request succeeds once its Retry-After has passed. The per-IP limiter of the same route answers 429 rate_limited before any token is looked up, so that 429, and one without a code, is false here.
func IsUserAccessStatusNotServed ¶ added in v0.36.0
IsUserAccessStatusNotServed reports whether err says the control plane does not serve PUT /v1/nodes/{node_id}/user-access-status: a 404 with any code but user_access_status_node_gone, or a 501 carrying the user_access_status_not_provisioned problem code.
A control plane older than the operation has no route for it, and its router answers 404 with whatever its not-found handler writes, so no code can be required of it. The operation's own 404 is user_access_status_node_gone: the node was removed while the request ran, a verdict on the node rather than a missing surface.
func LoadRootCAs ¶ added in v0.38.0
LoadRootCAs returns the host's system roots plus the certificates in caFile. An empty caFile returns nil, which a tls.Config reads as the system roots.
The file is read once, when this is called, and its path is used as given, so a relative one resolves against the working directory. Blocks of the file that are not certificates are skipped, but a file without any certificate is an error: the operator named a CA, and trusting the system roots alone would fail later with an error that does not say why.
func RedactURLError ¶ added in v0.2.0
RedactURLError strips the request URL from a *url.Error, keeping only the operation and the underlying cause. url.Error.Error() renders the full URL including its query string, and a presigned upload URL carries its credential there — logging such an error verbatim would publish a live write capability against the object it points at. Errors of any other type pass through.
func SignedMessage ¶ added in v0.15.0
SignedMessage returns the message an envelope's Ed25519 signature is made over: the 64-byte SHA-512 digest of its CanonicalBytes. The control plane signs the digest, not the canonical bytes themselves, so verifying the bytes directly fails for every envelope.
func ValidHookName ¶ added in v0.28.0
ValidHookName reports whether name is inside the control plane's published-hook name grammar, so it names a hook FetchHookVersion can ask for.
func ValidIngressReason ¶ added in v0.35.0
ValidIngressReason reports whether s is a reason token of an ingress status report: a lowercase letter, then up to 62 lowercase letters, digits and underscores (^[a-z][a-z0-9_]{0,62}$).
func ValidIngressRuleID ¶ added in v0.35.0
ValidIngressRuleID reports whether s is a UUID in canonical form, groups of 8, 4, 4, 4 and 12 hex digits in either case joined by hyphens, other than the zero UUID: an id the control plane accepts in an ingress status report.
func ValidIngressTargetNodeID ¶ added in v0.37.0
ValidIngressTargetNodeID reports whether s is a node_id the control plane accepts in a target entry of an ingress status report: a UUID in canonical form other than the zero UUID, as ValidIngressRuleID.
func ValidSecretName ¶ added in v0.16.0
ValidSecretName reports whether name is inside the control plane's secret-name grammar, so it names a secret FetchSecret can ask for.
func ValidSiteToSiteTunnelID ¶ added in v0.36.0
ValidSiteToSiteTunnelID reports whether s is a UUID in canonical form, in either case, other than the zero UUID: the check of ValidUserAccessProviderID, and the id the control plane accepts in a site-to-site status report.
func ValidUserAccessProviderID ¶ added in v0.36.0
ValidUserAccessProviderID reports whether s is a UUID in canonical form, in either case, other than the zero UUID: the check of ValidIngressRuleID, and the id the control plane accepts in a user access status report.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
Message string
// Code carries the machine-readable code member of an RFC 9457
// problem+json response. It is empty when the response carries no
// code (or is not a problem+json body).
Code string
// CorrelationID carries the correlation_id member of an RFC 9457
// problem+json response, falling back to the X-Correlation-Id header
// of that same response. Both sources are read only from a response
// that presents itself as a problem document, and that is the whole
// of what the gate buys: a response an intermediary substituted for
// the control plane's contributes no id. It does not authenticate the
// header, so a tracing proxy that passes a genuine problem document
// through and stamps its own X-Correlation-Id on it is read by the
// fallback. It is empty when neither source carries a usable id.
CorrelationID string
RetryAfter time.Duration // only set for 429
}
APIError is the base error type for HTTP API errors. It supports errors.Is matching by status code and errors.As extraction.
type ActionInfo ¶
type ActionInfo struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters []ActionParam `json:"parameters,omitempty"`
}
type ActionParam ¶
type AuditBatch ¶
type AuditBatch = []AuditEntry
AuditBatch is the internal pipeline and local-endpoint payload for a batch of audit entries. The control-plane leg of POST /v1/nodes/{node_id}/audit sends AuditEvent instead.
type AuditEntry ¶
type AuditEntry struct {
Timestamp time.Time `json:"timestamp"`
Source string `json:"source"`
EventType string `json:"event_type"`
Subject json.RawMessage `json:"subject"`
Object json.RawMessage `json:"object"`
Action string `json:"action"`
Result string `json:"result"`
Hostname string `json:"hostname"`
Raw string `json:"raw"`
}
AuditEntry is the internal pipeline and local-endpoint format for a single audit record. The control-plane leg sends AuditEvent instead.
type AuditEvent ¶ added in v0.2.0
type AuditEvent struct {
Source string `json:"source"`
Action string `json:"action"`
Outcome string `json:"outcome"`
Timestamp time.Time `json:"timestamp"`
}
AuditEvent is the control-plane wire format for a single audit record in the body of POST /v1/nodes/{node_id}/audit.
type BinaryInfo ¶
BinaryInfo describes the running agent binary. It is reported through the node API's local surface; the control plane receives the same two values as the flat binary_version / binary_checksum fields of a capability manifest.
type BridgeInfo ¶
type BridgeInfo struct {
Enabled bool `json:"enabled"`
AccessInterface string `json:"access_interface"`
ActiveRoutes int `json:"active_routes"`
RelayEnabled bool `json:"relay_enabled"`
ActiveRelaySessions int `json:"active_relay_sessions"`
IngressEnabled bool `json:"ingress_enabled"`
ActiveIngressRules int `json:"active_ingress_rules"`
SiteToSiteEnabled bool `json:"site_to_site_enabled"`
ActiveSiteToSiteTunnels int `json:"active_site_to_site_tunnels"`
}
BridgeInfo is the bridge status reported by the node in heartbeats.
type BridgeSnapshot ¶ added in v0.2.0
type BridgeSnapshot struct {
Relay *RelayConfig `json:"relay"`
UserAccess *UserAccessConfig `json:"user_access"`
Ingress *IngressConfig `json:"ingress"`
SiteToSite *SiteToSiteConfig `json:"site_to_site"`
}
BridgeSnapshot carries the four bridge subtrees. Each child is present-but-nullable; there are no base fields on the wire.
type CapabilityManifestRequest ¶ added in v0.4.0
type CapabilityManifestRequest struct {
// BinaryVersion is the agent version string, non-empty after trimming.
BinaryVersion string `json:"binary_version"`
// BinaryChecksum is the running binary's SHA-256 as 32 raw bytes in
// standard-padded base64 (see integrity.WireChecksum). Anything that does
// not decode to exactly 32 bytes is refused with 400
// binary_checksum_invalid.
BinaryChecksum string `json:"binary_checksum"`
// SSHHostKeyFingerprint is the optional OpenSSH host-key fingerprint in the
// canonical `SHA256:<base64>` form. Omitted when the agent has none.
SSHHostKeyFingerprint string `json:"ssh_host_key_fingerprint,omitempty"`
// DeclaredHooks are the hooks the agent advertises, at most 128, with
// unique names. Omitted when empty rather than sent as null.
DeclaredHooks []DeclaredHook `json:"declared_hooks,omitempty"`
// PlexdHooks are the PlexdHook resources the agent found in its
// ServiceAccount's namespace, at most 128, with unique names. The agent
// reports the list again when those resources change. Omitted when the
// agent runs outside a cluster or found nothing it can report, rather than
// sent as null, and a missing key means none: every PUT replaces the stored
// list whole.
PlexdHooks []DiscoveredPlexdHook `json:"plexd_hooks,omitempty"`
// BuiltinActions is the inventory of builtin actions the agent implements,
// sorted by name, each with its parameters in registration order. Omitted
// when empty rather than sent as null.
BuiltinActions []ActionInfo `json:"builtin_actions,omitempty"`
// HookRolloutErrors are the published hook versions the node's last pull
// listed and the node could not install, at most MaxHookRolloutErrors.
// Omitted when nil rather than sent as null. The control plane stores an
// absent list as [], because every PUT replaces the whole snapshot, so the
// node clears an error by leaving it out. More than MaxHookRolloutErrors
// entries answer 400 hook_rollout_errors_too_many, and an entry that breaks
// a limit 400 hook_rollout_error_invalid.
HookRolloutErrors []HookRolloutError `json:"hook_rollout_errors,omitempty"`
}
CapabilityManifestRequest is the body of PUT /v1/nodes/{node_id}/capabilities: the agent's binary version and digest, the hooks it advertises, and two inventories of what it can run: the builtin actions it implements and the PlexdHook resources it discovered in its cluster.
The handler decodes it with DisallowUnknownFields, so this struct carries the contract's fields and nothing else. A manifest is refused whole, so one inventory entry that breaks an invariant (422) costs the binary version and checksum with it. The agent therefore sends only entries the contract accepts: at most 128 per inventory, unique names, at most 64 parameters per action, and a canonical image digest on every PlexdHook.
A declared hook's metadata has limits of its own: a description and each parameter text field at most 4096 characters, at most 64 parameters per hook, timeout_seconds 0 to 86400, sandbox_level at most 64 characters, and no NUL in any of them. Characters are Unicode code points. Those violations answer 400, not 422: declared_hooks_too_many past 64 parameters and declared_hook_invalid otherwise. A control plane that predates the fields refuses them with 400 malformed_capabilities_request.
type Config ¶
type Config struct {
// BaseURL is the control plane API base URL (required).
// Example: "https://api.plexsphere.com"
BaseURL string `yaml:"base_url"`
// TLSInsecureSkipVerify disables TLS certificate verification.
// WARNING: Only use for development/testing.
TLSInsecureSkipVerify bool `yaml:"tls_insecure_skip_verify"`
// TLSCAFile names a PEM file whose certificates the client trusts for the
// control plane in addition to the host's system roots, so a control plane
// behind a private CA needs neither that CA in the host's trust store nor
// disabled verification. NewControlPlane reads it once. Empty means the
// system roots alone.
TLSCAFile string `yaml:"tls_ca_file"`
// ConnectTimeout is the maximum time to wait for a TCP connection.
// Default: 10s
ConnectTimeout time.Duration `yaml:"connect_timeout"`
// RequestTimeout is the maximum time for a complete HTTP request/response cycle.
// Default: 30s
RequestTimeout time.Duration `yaml:"request_timeout"`
// SSEIdleTimeout is the maximum time to wait for any data on the SSE stream
// before considering the connection stale and reconnecting.
// Default: 90s
SSEIdleTimeout time.Duration `yaml:"sse_idle_timeout"`
// SSEReprobeInterval is how often pull-only delivery re-probes the SSE
// endpoint after the control plane descoped it.
// Default: 10m
SSEReprobeInterval time.Duration `yaml:"sse_reprobe_interval"`
}
Config holds the configuration for the ControlPlane client. Config is passed as a constructor argument: this package reads no configuration file, and the only files it opens are the CA bundles that LoadRootCAs reads.
func (*Config) ApplyDefaults ¶
func (c *Config) ApplyDefaults()
ApplyDefaults sets default values for zero-valued fields.
type ConnectFunc ¶
ConnectFunc is called to establish an SSE connection. It should block while the connection is active and return when it drops.
type ControlPlane ¶
type ControlPlane struct {
// contains filtered or unexported fields
}
ControlPlane is the client for the Plexsphere control plane API.
func NewControlPlane ¶
NewControlPlane creates a new ControlPlane client with the given configuration.
func (*ControlPlane) ConnectSSE ¶
func (c *ControlPlane) ConnectSSE(ctx context.Context, nodeID, lastEventID string) (*http.Response, error)
ConnectSSE opens an SSE connection to the node event stream. The caller is responsible for closing the response body.
The request timeout bounds only the setup: the wait for the response headers and, on a non-2xx answer, the read of its problem body. Headers that do not arrive in time fail with ErrSSEConnectTimeout; a problem body that stalls still yields the status as an *APIError, without whatever part of the body did not arrive. Once the stream is open, the request timeout no longer applies, and SSEStream bounds a silent stream with its idle timeout. GET /v1/nodes/{node_id}/events
func (*ControlPlane) CredentialRefused ¶ added in v0.11.0
func (c *ControlPlane) CredentialRefused() bool
CredentialRefused reports whether the credential is currently marked refused.
func (*ControlPlane) DeleteStateReport ¶ added in v0.2.0
func (c *ControlPlane) DeleteStateReport(ctx context.Context, nodeID, key string) error
DeleteStateReport removes a single per-key node state report. A 204 No Content returns nil; a 404 report_not_found (and any other non-2xx status) surfaces as an *APIError through errorFromResponse. DELETE /v1/nodes/{node_id}/state/reports/{key}
func (*ControlPlane) ExecutionCallback ¶ added in v0.2.0
func (c *ControlPlane) ExecutionCallback(ctx context.Context, nodeID, executionID string, req ExecutionCallbackRequest) (*ExecutionCallbackResponse, error)
ExecutionCallback posts a single execution lifecycle callback and returns the server's new invocation status, plus a presigned output upload URL when the callback declares an over-ceiling output. POST /v1/nodes/{node_id}/executions/{execution_id}
func (*ControlPlane) FetchEdgePSK ¶ added in v0.11.0
func (c *ControlPlane) FetchEdgePSK(ctx context.Context, nodeID, peerNodeID string) (*EdgePSKEnvelope, error)
FetchEdgePSK retrieves the pairwise WireGuard PSK for the edge between the node and peerNodeID as the raw envelope the control plane seals under the node's NSK. The body must be exactly EdgePSKEnvelopeSize bytes, and both the X-Plexsphere-PSK-KID and X-Plexsphere-PSK-Epoch headers must be present: the epoch is part of the additional authenticated data the envelope is opened with. A non-2xx answer returns the *APIError the problem body describes.
The body is key material, so no error this returns quotes it. GET /v1/nodes/{node_id}/peers/{peer_node_id}/psk
func (*ControlPlane) FetchHookVersion ¶ added in v0.28.0
func (c *ControlPlane) FetchHookVersion(ctx context.Context, nodeID, name string, version int) (*NodeHookVersion, error)
FetchHookVersion retrieves one published hook version as the control plane serves it: the signed hook_version envelope and the script in standard base64. It refuses a name outside the grammar and a version below 1 before any request, and a non-2xx answer returns the *APIError the problem body describes, such as 404 hook_not_assigned or 503 signing_unavailable.
It verifies nothing. The envelope names a key the caller has to hold, and the script has to match the checksum of the pull entry that listed the version, both of which only the caller knows, so verification is the installer's job. GET /v1/nodes/{node_id}/hooks/{name}/versions/{version}
func (*ControlPlane) FetchSecret ¶
func (c *ControlPlane) FetchSecret(ctx context.Context, nodeID, name string, version int) (*SecretEnvelope, error)
FetchSecret retrieves a specific secret for the node as the raw AES-256-GCM envelope served by the control plane: the octet-stream body carries <12-byte nonce> || <ciphertext + 16-byte GCM tag>, and the version and KID ride in the X-Plexsphere-Secret-Version and X-Plexsphere-Secret-KID headers. A version > 0 selects an older version via ?version=N; version == 0 is the current version. GET /v1/nodes/{node_id}/secrets/{name}
func (*ControlPlane) FetchState ¶
func (c *ControlPlane) FetchState(ctx context.Context, nodeID string) (*NodeStateSnapshot, error)
FetchState retrieves the desired-state snapshot for a node. GET /v1/nodes/{node_id}/state
func (*ControlPlane) Heartbeat ¶
func (c *ControlPlane) Heartbeat(ctx context.Context, nodeID string, req HeartbeatRequest) (*HeartbeatResponse, error)
Heartbeat sends a heartbeat to the control plane. POST /v1/nodes/{node_id}/heartbeat
The heartbeat is never stopped by the refused-credential gate: it is the probe whose acceptance clears the mark (see SetCredentialRefused).
func (*ControlPlane) OpenSessionConnection ¶ added in v0.20.0
func (c *ControlPlane) OpenSessionConnection(ctx context.Context, nodeID, sessionID, connectionID string) (net.Conn, error)
OpenSessionConnection opens the connection a session_connect event asked for: a WebSocket, authenticated with the node's bearer, whose binary messages carry the ssh session's SSH bytes in both directions. A refused upgrade comes back as an *APIError with the status and the problem code, such as 404 session_connection_not_found once the request expired or 409 session_not_active for a session that ended. ctx bounds the handshake only; the returned connection lives until Close. Read returns only the payload of binary messages: pings are answered inside it, a normal close reads as io.EOF, and a text message closes the connection and fails the read. GET /v1/nodes/{node_id}/sessions/{session_id}/connections/{connection_id}
DECISION: the handshake goes over the API client's own transport, so the connection reaches the control plane the way every other call does, with the same TLS settings, connect timeout and base URL. That transport sets its own TLSClientConfig without ForceAttemptHTTP2 and so speaks HTTP/1.1, which the WebSocket upgrade needs. The handshake context does not bound the connection, which lives as long as a client stays attached to the session.
func (*ControlPlane) PostJSON ¶
PostJSON sends a POST request with a JSON body and decodes the JSON response.
func (*ControlPlane) PutStateReport ¶ added in v0.2.0
func (c *ControlPlane) PutStateReport(ctx context.Context, nodeID, key string, req NodeStateReportRequest) (*NodeStateReportResponse, error)
PutStateReport publishes a single per-key node state report and returns the server's acknowledgement. PUT /v1/nodes/{node_id}/state/reports/{key}
func (*ControlPlane) Register ¶
func (c *ControlPlane) Register(ctx context.Context, req RegisterRequest) (*RegisterResponse, error)
Register sends a registration request to the control plane. POST /v1/register is security: [] — the bootstrap token travels in the body, so the request never carries the shared bearer token even if one is set.
func (*ControlPlane) ReportAudit ¶
func (c *ControlPlane) ReportAudit(ctx context.Context, nodeID string, events []AuditEvent) (*IngestReceipt, error)
ReportAudit posts a batch of audit events to the platform ingest endpoint as NDJSON (one JSON object per line) and returns the 202 ingest receipt. POST /v1/nodes/{node_id}/audit
func (*ControlPlane) ReportEndpoint ¶
func (c *ControlPlane) ReportEndpoint(ctx context.Context, nodeID string, req EndpointRequest) (*EndpointResponse, error)
ReportEndpoint reports the node's NAT endpoint information. PUT /v1/nodes/{node_id}/endpoint
func (*ControlPlane) ReportEndpointCandidates ¶ added in v0.11.0
func (c *ControlPlane) ReportEndpointCandidates(ctx context.Context, nodeID string, req EndpointCandidatesRequest) (*EndpointCandidatesResponse, error)
ReportEndpointCandidates reports the node's local endpoint candidates, which replace every candidate it reported before, and returns the control plane's receipt.
A nil Candidates is sent as an empty array: the contract refuses a null candidates with 400 malformed_endpoint_candidates, while an empty array withdraws the earlier set. The substitution is made on a copy, so the caller's request is left as passed. A report over MaxEndpointCandidates is refused here, before any request, as ReportHandshakes refuses an oversized report. PUT /v1/nodes/{node_id}/endpoint-candidates
func (*ControlPlane) ReportHandshakes ¶ added in v0.10.0
func (c *ControlPlane) ReportHandshakes(ctx context.Context, nodeID string, req HandshakeReportRequest) (*HandshakeReportResponse, error)
ReportHandshakes reports the age of the latest WireGuard handshake with each mesh peer and the endpoint WireGuard used for it, and returns the control plane's receipt.
A nil Peers is sent as an empty array: the contract answers a null peers with 400 malformed_handshake_report, while an empty array is a valid report that records nothing. The substitution is made on a copy, so the caller's request is left as passed.
The peer ceiling is checked here rather than left to the server, as ReportIntegrityViolations does for its bounds: an oversized report is refused whole, so sending it would cost every edge it carries. POST /v1/nodes/{node_id}/handshakes
func (*ControlPlane) ReportIngressStatus ¶ added in v0.35.0
func (c *ControlPlane) ReportIngressStatus(ctx context.Context, nodeID string, req IngressStatusRequest) (*IngressStatusResponse, error)
ReportIngressStatus reports whether the bridge's local configuration serves public ingress, and the state of each ingress rule, and returns the control plane's receipt.
It validates nothing and sends the request as passed: the ingress status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed_ingress_status or invalid_ingress_status. PUT /v1/nodes/{node_id}/ingress-status
func (*ControlPlane) ReportIntegrityViolations ¶ added in v0.4.0
func (c *ControlPlane) ReportIntegrityViolations(ctx context.Context, nodeID string, req IntegrityViolationsRequest) error
ReportIntegrityViolations reports a batch of integrity violations to the control plane. The 200 response carries a commit timestamp and an echo of the batch size; the agent keeps no replay queue to reconcile them against, so the body is not decoded and a non-2xx surfaces as an *APIError.
The batch bounds are checked here rather than left to the server: the two codes it answers with (integrity_violations_empty, integrity_violations_too_many) describe a caller mistake, and a refused request would take every violation in it down. POST /v1/nodes/{node_id}/integrity-violations
func (*ControlPlane) ReportLogs ¶
func (c *ControlPlane) ReportLogs(ctx context.Context, nodeID string, lines []LogLine) (*IngestReceipt, error)
ReportLogs posts a batch of log lines to the platform ingest endpoint as NDJSON (one JSON object per line) and returns the 202 ingest receipt. POST /v1/nodes/{node_id}/logs
func (*ControlPlane) ReportMetrics ¶
func (c *ControlPlane) ReportMetrics(ctx context.Context, nodeID string, samples []MetricSample) (*IngestReceipt, error)
ReportMetrics posts a batch of metric samples to the platform ingest endpoint as a JSON array and returns the 202 ingest receipt. POST /v1/nodes/{node_id}/metrics
func (*ControlPlane) ReportPolicyStatus ¶ added in v0.31.0
func (c *ControlPlane) ReportPolicyStatus(ctx context.Context, nodeID string, req PolicyStatusRequest) (*PolicyStatusResponse, error)
ReportPolicyStatus reports what the node did with the policy block of its pulls and returns the control plane's receipt.
The contract refuses a null revisions list, so a nil Revisions in Applied or Rejected is sent as [], on a copy: the caller's request is left as passed. It validates nothing else: the policy status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 invalid_policy_status or malformed_policy_status. PUT /v1/nodes/{node_id}/policy-status
func (*ControlPlane) ReportRelayStatus ¶ added in v0.23.0
func (c *ControlPlane) ReportRelayStatus(ctx context.Context, nodeID string, req RelayStatusRequest) (*RelayStatusResponse, error)
ReportRelayStatus reports the state of the bridge's relay and returns the control plane's receipt.
It validates nothing and sends the request as passed: the agent's request builder produces only the shapes the contract admits, and the control plane refuses any other with 400 invalid_relay_status or malformed_relay_status. PUT /v1/nodes/{node_id}/relay-status
func (*ControlPlane) ReportSessionActivity ¶ added in v0.2.0
func (c *ControlPlane) ReportSessionActivity(ctx context.Context, nodeID, sessionID string, req SessionActivityRequest) error
ReportSessionActivity posts a one-of session activity record (ssh, k8s, or tcp). Success is 204 No Content. POST /v1/nodes/{node_id}/sessions/{session_id}
func (*ControlPlane) ReportSiteToSiteStatus ¶ added in v0.36.0
func (c *ControlPlane) ReportSiteToSiteStatus(ctx context.Context, nodeID string, req SiteToSiteStatusRequest) (*SiteToSiteStatusResponse, error)
ReportSiteToSiteStatus reports whether the bridge's local configuration serves site-to-site tunnels, and whether each tunnel of its pull is up and answered by its remote site, and returns the control plane's receipt.
It validates nothing and sends the request as passed: the site-to-site status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed_site_to_site_status or invalid_site_to_site_status. PUT /v1/nodes/{node_id}/site-to-site-status
func (*ControlPlane) ReportUserAccessStatus ¶ added in v0.36.0
func (c *ControlPlane) ReportUserAccessStatus(ctx context.Context, nodeID string, req UserAccessStatusRequest) (*UserAccessStatusResponse, error)
ReportUserAccessStatus reports whether the bridge's local configuration serves user access, and whether each user access provider of its pull is up, and returns the control plane's receipt.
It validates nothing and sends the request as passed: the user access status reporter builds only the shapes the contract admits, and the control plane refuses any other with 400 malformed_user_access_status or invalid_user_access_status. PUT /v1/nodes/{node_id}/user-access-status
func (*ControlPlane) RotateKeys ¶
func (c *ControlPlane) RotateKeys(ctx context.Context, req KeyRotateRequest) (*KeyRotateResponse, error)
RotateKeys completes a pending mesh-key rotation; the server identifies the node from the NSK bearer credential. POST /v1/keys/rotate
func (*ControlPlane) SetAuthToken ¶
func (c *ControlPlane) SetAuthToken(token string)
SetAuthToken sets the bearer token used for API authentication.
func (*ControlPlane) SetCredentialRefused ¶ added in v0.11.0
func (c *ControlPlane) SetCredentialRefused(refused bool)
SetCredentialRefused marks the node's credential as refused by the control plane, or clears that mark. While it is set, every request that would present the bearer fails with ErrCredentialRefused before any I/O, so a removed Node stops calling the control plane. Two requests are exempt: POST /v1/register, which carries no bearer, and the heartbeat, which is the probe that decides when the mark is cleared again.
func (*ControlPlane) UpdateCapabilities ¶
func (c *ControlPlane) UpdateCapabilities(ctx context.Context, nodeID string, caps CapabilityManifestRequest) error
UpdateCapabilities publishes the node's capability manifest. PUT /v1/nodes/{node_id}/capabilities
func (*ControlPlane) UploadExecutionOutput ¶ added in v0.2.0
func (c *ControlPlane) UploadExecutionOutput(ctx context.Context, uploadURL string, output []byte) error
UploadExecutionOutput PUTs an over-ceiling execution output to a presigned URL. Presigned URLs carry their own authentication, so this request sends neither the bearer token nor gzip encoding; it uploads the raw bytes with a Content-Type of application/octet-stream.
The upload URL comes from the control plane, and captured action output routinely contains configuration and credentials, so the transport is pinned twice over: the URL may not be less secure than the configured control-plane base URL (an https control plane can never downgrade an upload to http), and redirects are not followed — a 3xx is surfaced as an error rather than re-sending the body to whatever host the redirect names.
type DeclaredHook ¶ added in v0.4.0
type DeclaredHook struct {
Name string `json:"name"`
// Checksum is the hook payload's SHA-256 as 32 raw bytes in
// standard-padded base64, same encoding as BinaryChecksum.
Checksum string `json:"checksum"`
// Description says what the hook does, at most 4096 characters. Omitted
// when the sidecar declares none.
Description string `json:"description,omitempty"`
// Parameters are the parameters the hook expects, in sidecar order, at most
// 64. Each name is non-empty after trimming and unique within the hook.
// Omitted when empty rather than sent as null.
Parameters []ActionParam `json:"parameters,omitempty"`
// TimeoutSeconds is the timeout the sidecar declares, in whole seconds from
// 0 to 86400. 0 means none declared, and the key stays off the wire.
TimeoutSeconds int64 `json:"timeout_seconds,omitempty"`
// SandboxLevel is the sandbox level the sidecar declares, at most 64
// characters. The contract keeps it free-form. Omitted when the sidecar
// declares none.
SandboxLevel string `json:"sandbox_level,omitempty"`
// Source is HookSourceRollout for a script installed from a published
// version. It is empty, and the key stays off the wire, for a hook placed
// on the node by other means: the contract reads an absent source as
// local, so a node with no rolled-out hook sends the manifest it sent
// before rollouts existed. The contract also accepts HookSourceLocal, and
// answers any value other than those two with 400 declared_hook_invalid.
Source string `json:"source,omitempty"`
// Version is the published version installed, 1 to 2147483647. It is
// required with Source HookSourceRollout and refused on any other entry,
// both with 400 declared_hook_invalid, so it is zero, and off the wire,
// for every other entry.
Version int `json:"version,omitempty"`
}
DeclaredHook is one hook the agent advertises. Its name and the digest of its payload let the integrity correlator see a hook change without re-fetching it. The four fields after them come from the hook's sidecar and describe the hook for an operator. They gate nothing at the control plane and sit outside its digest, so a sidecar edit changes them and leaves Checksum alone. plexd applies the sidecar's timeout and sandbox when it runs the hook. Source and Version, last, mark a hook a rollout installed and name its version. The control plane then takes that version's published checksum as the hook's baseline, so a rolled-out hook is never trusted on first use.
type DeliveryMode ¶ added in v0.2.0
type DeliveryMode string
DeliveryMode identifies which channel currently delivers control-plane state.
const ( // DeliveryModeStreaming means the SSE event stream is the live channel. DeliveryModeStreaming DeliveryMode = "streaming" // DeliveryModePullOnly means the event stream is descoped and the // reconciler's own loop is the only delivery channel; SSE is re-probed at // a low cadence to detect its return. DeliveryModePullOnly DeliveryMode = "pull_only" // DeliveryModeDegradedPolling means SSE has been failing transiently long // enough that the legacy polling fallback is driving state. DeliveryModeDegradedPolling DeliveryMode = "degraded_polling" )
type DiscoveredPlexdHook ¶ added in v0.8.0
type DiscoveredPlexdHook struct {
// Name is the resource name, unique within the namespace it was listed in.
Name string `json:"name"`
// ImageDigest is the hook image's digest in canonical
// `sha256:<64 lowercase hex>` form.
ImageDigest string `json:"image_digest"`
// Parameters is the spec's name/value list folded into a map.
Parameters map[string]string `json:"parameters,omitempty"`
// TimeoutSeconds is the execution timeout. The CRD has no timeout field,
// so the agent never sets it and the key stays off the wire.
TimeoutSeconds int64 `json:"timeout_seconds,omitempty"`
// Sandbox reports that the hook runs sandboxed: a read-only root
// filesystem with every capability dropped, which is how the controller
// runs any hook that is not privileged.
Sandbox bool `json:"sandbox,omitempty"`
}
DiscoveredPlexdHook is one PlexdHook resource as the manifest reports it (the contract's PlexdHook schema). It identifies the hook by its image digest rather than a payload checksum, so only a digest-pinned image can be reported.
type Ed25519Verifier ¶
type Ed25519Verifier struct {
// contains filtered or unexported fields
}
Ed25519Verifier verifies Envelope signatures using Ed25519 keys selected by key id. It supports rotation by holding a current key and an optional previous key that stays accepted until a transition deadline.
func NewEd25519Verifier ¶
func NewEd25519Verifier(keyID string, key ed25519.PublicKey) *Ed25519Verifier
NewEd25519Verifier returns a new verifier that accepts envelopes signed with the given key and carrying the given key id.
func (*Ed25519Verifier) Install ¶ added in v0.15.0
func (v *Ed25519Verifier) Install(key NodeStateSigningKey) (bool, error)
Install makes the signing key a state pull carried the current key. It reports whether anything changed: a key whose id and bytes both equal the current pair is a no-op that leaves a rotation's grace entry alone, while any other key replaces the current one and drops the grace entry, because the node trusts exactly one key of its Domain. Comparing the bytes as well as the id is what lets a pull repair a pair persisted torn. On any error the installed keys are left unchanged.
func (*Ed25519Verifier) Rotate ¶ added in v0.2.0
func (v *Ed25519Verifier) Rotate(rot SigningKeyRotation) error
Rotate installs a new current signing key from a signing_key_rotated event. The previous key is retained as a grace entry only when the rotation names a previous key id the verifier currently holds and a non-zero transition deadline; otherwise no grace entry is kept. On any error the installed keys are left unchanged.
func (*Ed25519Verifier) TrustedKeys ¶ added in v0.8.0
func (v *Ed25519Verifier) TrustedKeys(now time.Time) []ed25519.PublicKey
TrustedKeys returns the signing keys a session token may be signed with at now: the current key, plus the previous key while its rotation grace window is open. The slice is fresh on every call, so a caller may keep it. It is what tunnel.SigningKeySource asks for.
func (*Ed25519Verifier) Verify ¶
func (v *Ed25519Verifier) Verify(_ context.Context, env Envelope) error
Verify checks the freshness and Ed25519 signature of an event envelope. It refuses an envelope without issued_at, one issued more than DefaultStalenessWindow ago, and one issued more than that window ahead of now, and then checks the signature with VerifySignature.
func (*Ed25519Verifier) VerifySignature ¶ added in v0.28.0
func (v *Ed25519Verifier) VerifySignature(env Envelope) error
VerifySignature checks an envelope's Ed25519 signature and leaves issued_at alone. It selects the verifying key by the envelope's key id, honouring the rotation grace window for the previous key, and checks the signature over SignedMessage, the SHA-512 digest of the envelope's canonical bytes.
A hook_version envelope needs this without Verify's freshness window: its issued_at is the instant the version was signed, often days before the node fetches it, so Verify would refuse every one as stale. issued_at is still part of the canonical bytes, so a changed value fails the signature. What keeps an old version from being installed is the pull, which names the version and the script's checksum the installer has to find.
type EdgePSKEnvelope ¶ added in v0.11.0
EdgePSKEnvelope is the pairwise WireGuard PSK for one edge as GET /v1/nodes/{id}/peers/{peer_node_id}/psk serves it, sealed under the calling node's NSK: Data is <12-byte nonce> || <32-byte PSK + 16-byte GCM tag>, KID and Epoch come from the X-Plexsphere-PSK-KID and X-Plexsphere-PSK-Epoch headers. Epoch is part of the envelope's additional authenticated data and is used verbatim to open it. Data is key material and is never logged.
type EndpointCandidatesRequest ¶ added in v0.11.0
type EndpointCandidatesRequest struct {
// Candidates holds 0 to MaxEndpointCandidates distinct host:port strings,
// an IPv6 host in brackets and without a zone. A null array is refused,
// so ReportEndpointCandidates sends nil as [].
Candidates []string `json:"candidates"` // never null on the wire
// ReportedAt must lie within 60 seconds of server time, or the report is
// refused with 400 endpoint_clock_skew.
ReportedAt time.Time `json:"reported_at"`
}
EndpointCandidatesRequest is the body of PUT /v1/nodes/{node_id}/endpoint-candidates: the node's local interface addresses joined with its WireGuard listen port. Each report replaces the previous set, so an empty Candidates withdraws every earlier candidate.
type EndpointCandidatesResponse ¶ added in v0.11.0
type EndpointCandidatesResponse struct {
AcceptedAt time.Time `json:"accepted_at"`
// StaleAfter is the deadline after which the control plane drops the set.
StaleAfter time.Time `json:"stale_after"`
}
EndpointCandidatesResponse is the 200 body of PUT /v1/nodes/{node_id}/endpoint-candidates.
type EndpointRequest ¶ added in v0.2.0
type EndpointRequest struct {
Endpoint string `json:"endpoint"`
NATType string `json:"nat_type"`
// PortMapping is "preserved" or "translated": whether the NAT kept the
// STUN probe's source port, and so whether Endpoint was observed or
// assumed. Omitted when empty. A control plane that predates the member
// refuses it with 400 malformed_endpoint_request.
PortMapping string `json:"port_mapping,omitempty"`
ReportedAt time.Time `json:"reported_at"`
}
type EndpointResponse ¶
type Envelope ¶ added in v0.2.0
type Envelope struct {
ID string `json:"id"`
Type string `json:"type"`
Scope string `json:"scope"`
KeyID string `json:"key_id"`
IssuedAt time.Time `json:"issued_at"`
Payload json.RawMessage `json:"payload"`
Signature string `json:"signature"`
}
Envelope is the wire format for signed events the control plane streams over SSE. It matches the control plane's OpenAPI v1 events contract.
func ParseEnvelope ¶
ParseEnvelope unmarshals data into an Envelope and validates required fields.
type EventDispatcher ¶
type EventDispatcher struct {
// contains filtered or unexported fields
}
EventDispatcher routes verified events to registered handlers by event type.
func NewEventDispatcher ¶
func NewEventDispatcher(logger *slog.Logger) *EventDispatcher
NewEventDispatcher creates a new EventDispatcher.
func (*EventDispatcher) Dispatch ¶
func (d *EventDispatcher) Dispatch(ctx context.Context, envelope Envelope)
Dispatch invokes all handlers registered for the event's type. Handler errors are logged but do not stop processing of subsequent handlers. Events with no registered handler are logged at debug level and discarded.
func (*EventDispatcher) Register ¶
func (d *EventDispatcher) Register(eventType string, handler EventHandler)
Register adds a handler for the given event type. Multiple handlers can be registered for the same event type.
type EventHandler ¶
EventHandler is a function that handles a verified SSE event.
type EventVerifier ¶
EventVerifier verifies the signature of an Envelope.
type ExecutionCallbackRequest ¶ added in v0.2.0
type ExecutionCallbackRequest struct {
Status string `json:"status"`
ExitCode *int `json:"exit_code,omitempty"`
Error string `json:"error,omitempty"`
DeclaredOutputBytes int64 `json:"declared_output_bytes,omitempty"`
Output *ExecutionOutput `json:"output,omitempty"`
}
ExecutionCallbackRequest is the single callback a node posts to POST /v1/nodes/{node_id}/executions/{execution_id} to advance an execution through its lifecycle. Status is one of the ExecutionStatus* values. ExitCode is a pointer so a terminal callback can report an explicit zero. Error is set on failed terminals. DeclaredOutputBytes is the byte length of the captured output; a declaration over the 16 KiB inline ceiling drives the presign mint.
type ExecutionCallbackResponse ¶ added in v0.2.0
type ExecutionCallbackResponse struct {
Status string `json:"status"`
OutputUploadURL string `json:"output_upload_url,omitempty"`
}
ExecutionCallbackResponse is the 200 response to an execution callback. Status is the new invocation status. OutputUploadURL is a presigned PUT URL present only on the first callback that declares an over-ceiling output; the node derives the object key from the URL path and uploads the bytes there.
type ExecutionOutput ¶ added in v0.2.0
type ExecutionOutput struct {
Inline string `json:"inline,omitempty"`
ObjectKey string `json:"object_key,omitempty"`
SHA256 string `json:"sha256,omitempty"`
}
ExecutionOutput carries an execution's captured output on a terminal callback. Inline is the base64-encoded output body and is used only when it is at most 16 KiB. ObjectKey and SHA256 describe an already-uploaded over-ceiling output: ObjectKey is the object-store key and SHA256 is the lowercase-hex SHA-256 of the uploaded bytes.
type FailureAction ¶
type FailureAction int
FailureAction indicates how the reconnect engine should handle a failure.
const ( // RetryTransient means use exponential backoff (network errors, 5xx). RetryTransient FailureAction = iota // RetryAuth means the control plane refused the node credential: a 401, // or ErrCredentialRefused from the client's gate. Registration stops on // it; the reconnect engine backs off as on RetryTransient, so the stream // returns once the credential is accepted again. RetryAuth // RespectServer means use the server-provided Retry-After delay (429). RespectServer // PermanentFailure means stop reconnection entirely (403, 404). PermanentFailure // RetryDescoped means the endpoint is descoped long-term (a 501 // signed_event_bus_not_provisioned) — switch to pull-only delivery // immediately, with no backoff, rather than retrying a channel that is // not there. RetryDescoped )
func ClassifyError ¶
func ClassifyError(err error) FailureAction
ClassifyError determines the appropriate reconnection action for an error.
type HandshakeReportPeer ¶ added in v0.10.0
type HandshakeReportPeer struct {
// PeerNodeID is the peer's node_id, a non-zero UUID that no other entry of
// the report repeats. An id the control plane does not know as a live peer
// of the node's Domain is counted as ignored rather than refused.
PeerNodeID string `json:"peer_node_id"`
// LastHandshakeAgeSeconds is the whole seconds between the latest completed
// handshake and ObservedAt, in 0..2147483647 (the contract's int32).
LastHandshakeAgeSeconds int32 `json:"last_handshake_age_seconds"`
// Endpoint is the address WireGuard uses for the peer as host:port, with an
// IPv6 host in brackets ([2001:db8::7]:51820). A port of 0, an unspecified
// address or an IPv6 zone is refused with 400
// handshake_endpoint_unparseable, for the whole report.
Endpoint string `json:"endpoint"`
}
HandshakeReportPeer is one entry of a HandshakeReportRequest.
No field is omitempty: all three are required, and an age of 0 (a handshake within the last second) is as legitimate as any other, so it must reach the wire rather than be dropped as a zero value and refused as missing.
type HandshakeReportRequest ¶ added in v0.10.0
type HandshakeReportRequest struct {
// ObservedAt is the agent's wall clock when it assembled the report. It
// gates the request only: a value more than 60 seconds from server time is
// refused with 400 handshake_clock_skew.
ObservedAt time.Time `json:"observed_at"`
// Peers carries at most MaxHandshakeReportPeers entries and omits a peer
// with no handshake yet. An empty array is a valid report that records
// nothing; a null one is refused, so ReportHandshakes sends nil as [].
Peers []HandshakeReportPeer `json:"peers"` // never null on the wire
}
HandshakeReportRequest is the body of POST /v1/nodes/{node_id}/handshakes: for each mesh peer the node has completed a WireGuard handshake with, the age of the latest handshake and the endpoint WireGuard used for it.
The control plane anchors every age on its own receive time, so a body is only true for the attempt it was assembled for. The agent builds a fresh one, with a fresh ObservedAt and fresh ages, for every attempt and never replays one: a replayed age would make the handshake look newer than it was. The handler decodes with DisallowUnknownFields, so the struct carries the contract's fields and nothing else.
type HandshakeReportResponse ¶ added in v0.10.0
type HandshakeReportResponse struct {
// AcceptedAt is the server receive time every age was anchored on.
AcceptedAt time.Time `json:"accepted_at"`
// Recorded counts the entries stored as the latest observation of their
// directed edge.
Recorded int `json:"recorded"`
// Ignored counts the entries naming the node itself, an unknown node, a
// node of another Domain or a deregistered peer.
Ignored int `json:"ignored"`
}
HandshakeReportResponse is the 200 body of POST /v1/nodes/{node_id}/handshakes.
type HeartbeatRequest ¶
type HeartbeatResponse ¶
type HookInfo ¶
type HookInfo struct {
Name string `json:"name"`
Description string `json:"description"`
Source string `json:"source"`
Checksum string `json:"checksum"`
Parameters []ActionParam `json:"parameters"`
Timeout string `json:"timeout"`
Sandbox string `json:"sandbox"`
// Version is the published version a rolled-out hook was installed from.
// It is zero, and omitted, for a hook whose Source is HookSourceLocal,
// which has no version.
Version int `json:"version,omitempty"`
}
type HookRolloutError ¶ added in v0.28.0
type HookRolloutError struct {
Name string `json:"name"`
Version int `json:"version"`
// Code is one of the HookRolloutCode constants.
Code string `json:"code"`
// Detail explains the failure, at most MaxHookRolloutDetailChars code
// points with no NUL. Omitted when empty.
Detail string `json:"detail,omitempty"`
}
HookRolloutError is one published hook version the node could not install, as the "Published hooks" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. Name and Version are the pair the pull listed, so the operator's per-node rollout status can put the error beside the rollout that caused it.
type HookVersionPayload ¶ added in v0.28.0
type HookVersionPayload struct {
ProjectID string `json:"project_id"`
Name string `json:"name"`
Version int `json:"version"`
Checksum string `json:"checksum"`
Description string `json:"description,omitempty"`
Parameters []ActionParam `json:"parameters,omitempty"`
TimeoutSeconds int64 `json:"timeout_seconds,omitempty"`
SandboxLevel string `json:"sandbox_level"`
}
HookVersionPayload is the payload of a hook_version envelope, the contract's HookVersionPayload. Name and Version repeat the pair the node fetched, and Checksum is the script's SHA-256 in the encoding of NodeStateHook.Checksum. Description, Parameters, TimeoutSeconds and SandboxLevel are the hook's sidecar fields, signed together with its checksum, and the control plane sends the first three only when the version declares them.
type IngestReceipt ¶ added in v0.2.0
type IngestReceipt struct {
AcceptedAt time.Time `json:"accepted_at"`
Records int `json:"records"`
}
IngestReceipt is the 202 body of the three ingest operations (POST /v1/nodes/{node_id}/metrics|logs|audit). Records is the number of records the control plane accepted from the batch.
type IngressACME ¶ added in v0.35.0
type IngressACME struct {
DirectoryURL string `json:"directory_url"`
ContactEmail string `json:"contact_email,omitempty"`
}
IngressACME is the ACME account of a bridge's acme rules: the directory the bridge registers at, and the contact it registers with, empty for none.
type IngressClientAuth ¶ added in v0.37.0
type IngressClientAuth struct {
CABundle string `json:"ca_bundle"`
}
IngressClientAuth is the client certificate requirement of an ingress rule, the control plane's BridgeIngressRuleClientAuthBundle: CABundle holds the rule's client authorities, 1 to 8 CA certificates as PEM CERTIFICATE blocks.
type IngressConditions ¶ added in v0.36.0
type IngressConditions struct {
PathPrefix string `json:"path_prefix,omitempty"`
Headers []IngressHeaderCondition `json:"headers,omitempty"`
}
IngressConditions are the request conditions of an ingress rule, the control plane's NodeStateBridgeIngressConditions: a path prefix and up to 8 header conditions, all of which a request must match. The headers arrive in name order.
func (IngressConditions) IsZero ¶ added in v0.36.0
func (c IngressConditions) IsZero() bool
IsZero reports whether c names no path prefix and no header, which is a rule without conditions. encoding/json's omitzero calls it.
type IngressConfig ¶
type IngressConfig struct {
// Enabled is the control plane's switch: a bridge serves Rules only when
// it is true and its local configuration does not opt out. A block
// without the member decodes to false and opens no public listener. The
// control plane sends true on every block it delivers.
Enabled bool `json:"enabled"`
Rules []IngressRule `json:"rules"`
// ACME is the account the block's acme rules share, the control plane's
// NodeStateBridgeIngressACME. It is present exactly when a rule has mode
// acme.
ACME *IngressACME `json:"acme,omitempty"`
}
IngressConfig is the bridge.ingress block of the state pull, the control plane's NodeStateBridgeIngress.
type IngressHeaderCondition ¶ added in v0.36.0
IngressHeaderCondition is one header condition: a field of Name, a lowercase token, that carries exactly Value.
type IngressInfo ¶
type IngressInfo struct {
Enabled bool `json:"enabled"`
RuleCount int `json:"rule_count"`
// ConnectionCount counts the open client connections of the tcp rules
// and the open flows of the udp rules. A flow carries the datagrams of
// one client address and port and the target's answers to them.
ConnectionCount int `json:"connection_count"`
ACMEEnabled bool `json:"acme_enabled"`
}
IngressInfo is the ingress status reported by the node in heartbeats.
type IngressRule ¶
type IngressRule struct {
ID string `json:"id"`
Slug string `json:"slug"`
// Protocol is IngressProtocolTCP or IngressProtocolUDP. A rule of a
// control plane before plexsphere/plexsphere#1110 carries none and
// decodes to an empty Protocol, which a bridge serves as tcp.
Protocol string `json:"protocol,omitempty"`
// ListenPort is the public port the bridge listens on, TCP or UDP by
// Protocol.
ListenPort int `json:"listen_port"`
// Mode is IngressModePassthrough, IngressModeTerminate or IngressModeACME.
Mode string `json:"mode"`
// SNIHost is the server name the rule matches on a shared port, exact or
// a wildcard of one left-most label. A rule without it is the only rule on
// its port.
SNIHost string `json:"sni_host,omitempty"`
// Targets are the rule's targets, one to eight, in round-robin order, as
// a control plane since plexsphere/plexsphere#1120 sends them. A rule of
// an earlier control plane carries none and marshals without the key; an
// absent, null or empty member decodes to an empty Targets.
Targets []IngressTarget `json:"targets,omitempty"`
// TargetNodeID, TargetAddress and TargetPort name the rule's first
// target. They are deprecated: a bridge reads them only when Targets is
// empty, as a control plane before plexsphere/plexsphere#1120 sends a
// rule.
TargetNodeID string `json:"target_node_id"`
// TargetAddress is the target node's mesh address, IPv4 or IPv6, without
// brackets. Deprecated: see TargetNodeID.
TargetAddress string `json:"target_address"`
// TargetPort is the port on the target. Deprecated: see TargetNodeID.
TargetPort int `json:"target_port"`
// CertificateSecretName names the Secret of the bridge's Project that
// holds a terminate rule's certificate chain and key, one PEM document.
// It is empty on every other mode.
CertificateSecretName string `json:"certificate_secret_name,omitempty"`
// Conditions are the request conditions of a terminate or acme rule:
// rules with conditions share one listen port and SNI host, and the
// bridge hands each request to the rule they pick. A rule without
// conditions marshals without the key, and an absent, null or empty
// member decodes to a rule without conditions.
Conditions IngressConditions `json:"conditions,omitzero"`
// StripPathPrefix removes the matched path prefix from the front of the
// path the target receives. Only a rule whose path prefix is present
// and not "/" carries it.
StripPathPrefix bool `json:"strip_path_prefix,omitempty"`
// ClientAuth requires a client certificate that chains to one of the
// rule's client authorities; only a terminate or acme rule carries it.
// It is a pointer because presence is the requirement: an absent member
// and null decode to nil, which marshals without the key, and {} and
// {"ca_bundle": ""} decode to a value with an empty bundle, which the
// bridge cannot build its authorities from.
ClientAuth *IngressClientAuth `json:"client_auth,omitempty"`
}
IngressRule is one rule of the block, the control plane's NodeStateBridgeIngressRule. It is not comparable with ==; Equal compares two rules.
func (IngressRule) Equal ¶ added in v0.36.0
func (r IngressRule) Equal(o IngressRule) bool
Equal reports whether two rules carry the same members. A nil and an empty Conditions.Headers are equal, and so are a nil and an empty Targets; the order of the headers and of the targets counts. reflect.DeepEqual follows the ClientAuth pointer: a nil and a non-nil ClientAuth differ, and two bundles compare by their text, so a bundle that differs in one byte or in the order of its blocks makes another rule.
type IngressStatusClientRefusal ¶ added in v0.37.0
type IngressStatusClientRefusal struct {
// Reason is a reason token: no_certificate, unknown_authority,
// certificate_expired or certificate_invalid.
Reason string `json:"reason"`
// AgeSeconds is the whole seconds between the refusal and the report, in
// 0..MaxIngressStatusRefusalAgeSeconds. The contract requires the member,
// and 0 is a valid age, so it has no omitempty.
AgeSeconds int64 `json:"age_seconds"`
}
IngressStatusClientRefusal is one entry of a rule entry's client_refusals, the control plane's IngressStatusReportRuleClientRefusal: the last client the bridge refused for Reason. No two entries of one rule name the same Reason.
type IngressStatusRequest ¶ added in v0.35.0
type IngressStatusRequest struct {
// State is one of the IngressState* constants.
State string `json:"state"`
// Rules holds one entry per reported rule, in the order of the pull; nil
// omits the member, which the contract reads as no entries.
Rules []IngressStatusRule `json:"rules,omitempty"`
}
IngressStatusRequest is the body of PUT /v1/nodes/{node_id}/ingress-status: whether the bridge's local configuration serves public ingress, and how each ingress rule of its pull fares. The control plane keeps the latest state per node and never ages it, and refuses ingress rule creates and updates on the bridge while it reads opted_out. Each report replaces the rule entries of the one before it.
A missing, null or unknown state, an unknown member, data after the report, more than MaxIngressStatusRules entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed_ingress_status. An opted-out report with entries, an id that repeats an earlier entry, an entry that breaks the presence rules of IngressStatusRule, and a refusal whose reason an earlier refusal of its entry carries answer 400 invalid_ingress_status.
type IngressStatusResponse ¶ added in v0.35.0
type IngressStatusResponse struct {
// AcceptedAt is the server receive time of the report.
AcceptedAt time.Time `json:"accepted_at"`
}
IngressStatusResponse is the 200 body of PUT /v1/nodes/{node_id}/ingress-status.
type IngressStatusRule ¶ added in v0.35.0
type IngressStatusRule struct {
// ID is the rule's id from the pull, a UUID other than the zero UUID.
ID string `json:"id"`
// Listener is one of the IngressListener* constants.
Listener string `json:"listener"`
ListenerReason string `json:"listener_reason,omitempty"`
// Certificate is one of the IngressCertificate* constants.
Certificate string `json:"certificate,omitempty"`
CertificateReason string `json:"certificate_reason,omitempty"`
// Dial is one of the IngressDial* constants.
Dial string `json:"dial,omitempty"`
DialReason string `json:"dial_reason,omitempty"`
// DialAgeSeconds is the whole seconds between the dial and the report, in
// 0..MaxIngressStatusDialAgeSeconds. It is a pointer because 0 is a valid
// age, for a dial less than a second ago.
DialAgeSeconds *int64 `json:"dial_age_seconds,omitempty"`
// Targets holds at most MaxIngressStatusTargets entries, one per target
// of the rule, only beside a Listener of listening; nil omits the member,
// which the contract reads as no entries.
Targets []IngressStatusTarget `json:"targets,omitempty"`
// ClientAuthEnforced says that the bridge verifies every client of the
// rule against its client authorities, or serves no client of the rule.
// It is sent only for a listening rule whose pull entry carries
// client_auth; false omits the member, which the contract reads as false.
ClientAuthEnforced bool `json:"client_auth_enforced,omitempty"`
// ClientRefusals holds at most MaxIngressStatusClientRefusals entries,
// one per reason, only beside a ClientAuthEnforced of true; nil omits the
// member, which the contract reads as no entries.
ClientRefusals []IngressStatusClientRefusal `json:"client_refusals,omitempty"`
}
IngressStatusRule is one entry of rules, the control plane's IngressStatusReportRule. Each member after Listener is sent exactly when the facet before it calls for it: ListenerReason when Listener is not_listening; Certificate and Dial when it is listening; CertificateReason when Certificate is not_ready; DialReason when Dial is failed; DialAgeSeconds when Dial is succeeded or failed. ClientAuthEnforced is true only beside a Listener of listening, and ClientRefusals carries entries only beside a ClientAuthEnforced of true. omitempty drops an empty member, so a caller leaves every member it must not send empty.
type IngressStatusTarget ¶ added in v0.37.0
type IngressStatusTarget struct {
// NodeID is the target's node_id from the pull, a UUID other than the
// zero UUID.
NodeID string `json:"node_id"`
// Port is the target's port from the pull, in 1..65535.
Port int `json:"port"`
// Dial is one of the IngressDial* constants.
Dial string `json:"dial"`
DialReason string `json:"dial_reason,omitempty"`
// DialAgeSeconds is the whole seconds between the last dial to the target
// and the report, in 0..MaxIngressStatusDialAgeSeconds.
DialAgeSeconds *int64 `json:"dial_age_seconds,omitempty"`
}
IngressStatusTarget is one entry of a rule entry's targets, the control plane's IngressStatusReportRuleTarget: the target as the pull names it and the last dial the bridge made to it. DialReason is sent exactly when Dial is failed, and DialAgeSeconds exactly when Dial is succeeded or failed. No two entries of one rule name the same NodeID and Port.
type IngressTarget ¶ added in v0.37.0
type IngressTarget struct {
NodeID string `json:"node_id"`
Address string `json:"address"`
Port int `json:"port"`
}
IngressTarget is one target of an ingress rule, the control plane's NodeStateBridgeIngressRuleTarget: a target node, its mesh address, IPv4 or IPv6 without brackets, and a port on it.
type IntegrityDetector ¶ added in v0.4.0
type IntegrityDetector string
IntegrityDetector is the on-node detector that surfaced a violation. Like IntegrityViolationKind the set is closed; a value outside it is refused with 400 integrity_violation_detected_by_invalid.
const ( // IntegrityDetectorStartupScan is the agent's own sweep of the artifacts it // holds baselines for. The contract has no value for a periodic re-scan, so // the interval-driven sweep reports this one too. IntegrityDetectorStartupScan IntegrityDetector = "startup_scan" // IntegrityDetectorInotify is the hooks-directory watcher reacting to a // filesystem event. IntegrityDetectorInotify IntegrityDetector = "inotify" // IntegrityDetectorPreDispatch is the check that runs immediately before a // hook executes. IntegrityDetectorPreDispatch IntegrityDetector = "pre_dispatch" )
type IntegrityViolationKind ¶ added in v0.4.0
type IntegrityViolationKind string
IntegrityViolationKind is the artifact class a violation applies to. The control plane canonicalises every entry through a value-object constructor that refuses anything outside this set with 400 integrity_violation_kind_invalid, so the type exists to keep an unchecked string from reaching the wire in the first place.
const ( // IntegrityKindBinaryChecksum reports the agent's own binary. IntegrityKindBinaryChecksum IntegrityViolationKind = "binary_checksum" // IntegrityKindHookChecksum reports a hook script. IntegrityKindHookChecksum IntegrityViolationKind = "hook_checksum" // IntegrityKindSSHHostKey reports the mesh SSH host key. IntegrityKindSSHHostKey IntegrityViolationKind = "ssh_host_key" )
type IntegrityViolationReport ¶
type IntegrityViolationReport struct {
Kind IntegrityViolationKind `json:"kind"`
DetectedBy IntegrityDetector `json:"detected_by"`
// ArtifactID identifies the affected artifact — a hook path, the binary
// path, or the host-key file. Non-empty after trimming, at most 4096 bytes.
ArtifactID string `json:"artifact_id"`
// ObservedChecksum is the SHA-256 the agent computed, as 32 raw bytes in
// standard-padded base64 (see integrity.WireChecksum). Required for the
// checksum kinds; anything that does not decode to exactly 32 bytes is
// refused with 400 integrity_violation_checksum_invalid.
ObservedChecksum string `json:"observed_checksum,omitempty"`
// ExpectedChecksum is the baseline digest, same encoding as
// ObservedChecksum.
ExpectedChecksum string `json:"expected_checksum,omitempty"`
// ObservedFingerprint is the OpenSSH host-key fingerprint the agent
// observed, in the canonical `SHA256:<base64>` form. Required for the
// ssh_host_key kind.
ObservedFingerprint string `json:"observed_fingerprint,omitempty"`
// ExpectedFingerprint is the baseline fingerprint, same form as
// ObservedFingerprint.
ExpectedFingerprint string `json:"expected_fingerprint,omitempty"`
}
IntegrityViolationReport is one entry of an IntegrityViolationsRequest.
The handler decodes the envelope with DisallowUnknownFields, so this struct carries the contract's fields and nothing else — in particular there is no timestamp (the control plane stamps its own) and no free-text detail field.
Kind decides which digest pair is legal. A binary_checksum or hook_checksum entry carries the checksums and no fingerprint; an ssh_host_key entry carries the fingerprints and no checksum. Crossing them is refused with 400 integrity_violation_kind_mismatch, which is why the four digest fields are omitempty: an unset one must be absent from the JSON, not present and empty.
type IntegrityViolationsRequest ¶ added in v0.4.0
type IntegrityViolationsRequest struct {
// Violations carries between 1 and MaxIntegrityViolationsPerBatch entries.
Violations []IntegrityViolationReport `json:"violations"`
}
IntegrityViolationsRequest is the body of POST /v1/nodes/{node_id}/integrity-violations: a batch of the tamper-evidence divergences the agent detected locally. The endpoint takes a batch even when the agent has a single violation to report, so a lone finding travels as a one-entry array rather than as a bare object.
type IntegrityViolationsResponse ¶ added in v0.4.0
type IntegrityViolationsResponse struct {
// AcceptedAt is the server-side commit timestamp.
AcceptedAt time.Time `json:"accepted_at"`
// ViolationCount echoes the number of rows persisted, matching the length
// of the violations array on input.
ViolationCount int `json:"violation_count"`
}
IntegrityViolationsResponse is the 200 body of POST /v1/nodes/{node_id}/integrity-violations. The work is synchronous — every row and the integrity_alert outbox event are committed before the response is written — so the status is 200 rather than 202.
type K8sActivity ¶ added in v0.2.0
type K8sActivity struct {
Verb string `json:"verb"`
ResourceKind string `json:"resource_kind,omitempty"`
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
StatusCode int `json:"status_code,omitempty"`
DurationMS int64 `json:"duration_ms,omitempty"`
}
K8sActivity records a single Kubernetes API action proxied through the session. Verb is the API verb; the remaining fields describe the target object and the outcome.
type KeyRotateRequest ¶
type KeyRotateRequest struct {
NewPublicKey string `json:"new_public_key"`
}
type KeyRotateResponse ¶
type LocalEndpointConfig ¶
type LocalEndpointConfig struct {
// URL is the HTTPS endpoint URL. Must use the https:// scheme when set.
URL string `yaml:"url"`
// SecretKey is the authentication credential for the local endpoint.
// Required when URL is non-empty.
SecretKey string `yaml:"secret_key"`
// TLSInsecureSkipVerify disables TLS certificate verification.
TLSInsecureSkipVerify bool `yaml:"tls_insecure_skip_verify"`
// TLSCAFile names a PEM file whose certificates are trusted for the
// endpoint in addition to the host's system roots, so an endpoint behind
// a private CA needs neither that CA in the host's trust store nor
// TLSInsecureSkipVerify. TLSClientConfig reads it on each call.
TLSCAFile string `yaml:"tls_ca_file"`
}
LocalEndpointConfig holds the configuration for a local data-plane endpoint that a pipeline can send data to in addition to the platform. A zero-valued LocalEndpointConfig means "not configured" and passes validation.
func (*LocalEndpointConfig) TLSClientConfig ¶ added in v0.38.0
TLSClientConfig returns the TLS settings for a client of the endpoint, or nil when the endpoint sets neither TLS option and the transport's defaults apply.
func (*LocalEndpointConfig) Validate ¶
func (c *LocalEndpointConfig) Validate(prefix string) error
Validate checks that the local endpoint configuration is well-formed. The prefix is prepended to error messages for context (e.g. "metrics").
type LogBatch ¶
type LogBatch = []LogEntry
LogBatch is the internal pipeline and local-endpoint payload for a batch of log entries. The control-plane leg of POST /v1/nodes/{node_id}/logs sends LogLine instead.
type LogEntry ¶
type LogEntry struct {
Timestamp time.Time `json:"timestamp"`
Source string `json:"source"`
Unit string `json:"unit"`
Message string `json:"message"`
Severity string `json:"severity"`
Hostname string `json:"hostname"`
}
LogEntry is the internal pipeline and local-endpoint format for a single log record. The control-plane leg sends LogLine instead.
type LogLine ¶ added in v0.2.0
type LogLine struct {
Severity string `json:"severity"`
Unit string `json:"unit,omitempty"`
Hostname string `json:"hostname,omitempty"`
Message string `json:"message"`
Timestamp time.Time `json:"timestamp"`
}
LogLine is the control-plane wire format for a single log record in the body of POST /v1/nodes/{node_id}/logs. Unit and Hostname are absent when unknown.
type MetricBatch ¶
type MetricBatch = []MetricPoint
MetricBatch is the internal pipeline and local-endpoint payload for a batch of metric points. The control-plane leg of POST /v1/nodes/{node_id}/metrics sends MetricSample instead.
type MetricPoint ¶
type MetricPoint struct {
Timestamp time.Time `json:"timestamp"`
Group string `json:"group"`
PeerID string `json:"peer_id,omitempty"`
Data json.RawMessage `json:"data"`
}
MetricPoint is the internal pipeline and local-endpoint format for a single metric. The control-plane leg sends MetricSample instead.
type MetricSample ¶ added in v0.2.0
type MetricSample struct {
Group string `json:"group"`
Name string `json:"name"`
Value float64 `json:"value"`
Labels map[string]string `json:"labels,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
MetricSample is the control-plane wire format for a single metric in the body of POST /v1/nodes/{node_id}/metrics. Group is one of the MetricGroup* values; Labels is absent when the sample carries no dimensions.
type NoOpVerifier ¶
type NoOpVerifier struct{}
NoOpVerifier is an EventVerifier that accepts all envelopes without verification.
type NodeHookVersion ¶ added in v0.28.0
type NodeHookVersion struct {
Envelope Envelope `json:"envelope"`
ScriptBase64 string `json:"script_base64"`
}
NodeHookVersion is the 200 body of the hook version fetch: the signed envelope that describes one published hook version, and the script itself in standard base64. The script sits outside the envelope, so the signature covers its checksum in the payload rather than its bytes. Nothing here is verified on decode: the envelope's payload decodes into HookVersionPayload, and the installer checks the signature, the pair it fetched, and the script's digest before it writes anything.
type NodeStateBlock ¶ added in v0.2.0
type NodeStateBlock struct {
Metadata []StateEntry `json:"metadata"`
Data []StateEntry `json:"data"`
Reports []StateEntry `json:"reports"`
}
NodeStateBlock is a three-bucket state block. Each bucket is a required array (never null when the block is populated), with entries ordered by key ascending.
type NodeStateDNS ¶ added in v0.29.0
type NodeStateDNS struct {
SearchDomain string `json:"search_domain"`
Zones []string `json:"zones"`
Hosts []NodeStateDNSHost `json:"hosts"`
Records []NodeStateDNSRecord `json:"records"`
ReverseZones []string `json:"reverse_zones"`
// Forwarding is a pointer because the member is the full setting and its
// absence says something else: a nil value, the wire's null or a key a
// control plane predating forwarding never wrote, means the control plane
// did not say this time, and the node keeps the forwarding it holds. Two
// empty lists say the node forwards nothing. omitempty lets the mock
// control plane, which marshals this type, serve a block without it.
Forwarding *NodeStateDNSForwarding `json:"forwarding,omitempty"`
}
NodeStateDNS is the dns block of the state pull, as the "Mesh DNS names" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. SearchDomain is the zone of the node's own Project. Zones are the Domain's default domain and every Project zone, ascending. Hosts are every node of the Domain, the pulling node included, ordered by FQDN. Records are the DNS records of the Domain and of every Project, ordered by FQDN, then by type. A nil Records, the wire's null or a key a control plane predating records never wrote, means the Domain has no records: the block is the full set, so it is no signal to keep the records held. ReverseZones are the in-addr.arpa or ip6.arpa zones that cover the Domain's mesh CIDR and nothing wider. Forwarding is the DNS forwarding setting that applies to the pulling node. The control plane sends every name in lower case without a trailing dot, and an empty list as [].
type NodeStateDNSForwardZone ¶ added in v0.29.0
type NodeStateDNSForwardZone struct {
Zone string `json:"zone"`
Resolvers []string `json:"resolvers"`
}
NodeStateDNSForwardZone is one entry of the forwarding member's forward_zones, as the "Mesh DNS names" section of plexsphere's agent contract describes it: a zone outside the mesh and the resolvers that answer the names under it, in the order they are asked.
type NodeStateDNSForwarding ¶ added in v0.29.0
type NodeStateDNSForwarding struct {
ForwardZones []NodeStateDNSForwardZone `json:"forward_zones"`
CatchAll []string `json:"catch_all"`
}
NodeStateDNSForwarding is the forwarding member of the dns block, as the "Mesh DNS names" section of plexsphere's agent contract describes it: the Project's setting when the node's Project holds one, otherwise its Domain's, otherwise two empty lists. ForwardZones are ascending by zone, each with 1 to 3 resolvers. CatchAll holds 0 to 3 resolvers, which answer every name outside the mesh zones, the reverse zones and the forward zones. A resolver is an IPv4 or IPv6 address in text form, asked in list order on port 53 over plain DNS. A nil list, the wire's null or a missing key, is an empty one.
type NodeStateDNSHost ¶ added in v0.29.0
type NodeStateDNSHost struct {
NodeID string `json:"node_id"`
FQDN string `json:"fqdn"`
MeshIP string `json:"mesh_ip"`
}
NodeStateDNSHost is one entry of the dns block's hosts, as the "Mesh DNS names" section of plexsphere's agent contract describes it: a node of the Domain, its fully qualified name, and its mesh IP, IPv4 or IPv6 by the family of the Domain's mesh CIDR.
type NodeStateDNSRecord ¶ added in v0.29.0
type NodeStateDNSRecord struct {
FQDN string `json:"fqdn"`
Type string `json:"type"`
Address string `json:"address,omitempty"`
Target string `json:"target,omitempty"`
Priority *int `json:"priority,omitempty"`
Weight *int `json:"weight,omitempty"`
Port *int `json:"port,omitempty"`
Text []string `json:"text,omitempty"`
}
NodeStateDNSRecord is one entry of the dns block's records, as the "Mesh DNS names" section of plexsphere's agent contract describes it: a record's fully qualified name, its type (A, AAAA, CNAME, TXT, SRV or MX) and the data members of that type, and no other member. Address belongs to A and AAAA, Target to CNAME, SRV and MX, Priority to SRV and MX (the preference of an MX), Weight and Port to SRV, and Text to TXT.
The numbers are pointers because the contract sends a priority or a weight of 0 as 0 and leaves out every member a type does not take, which the mock control plane marshals this type for. They are int rather than uint16, so a number out of range costs the one record it belongs to, which the resolver skips, rather than the decode of the whole snapshot.
type NodeStateExecution ¶ added in v0.3.0
type NodeStateExecution struct {
ExecutionID string `json:"execution_id"`
Action string `json:"action"`
Type string `json:"type"`
Parameters map[string]json.RawMessage `json:"parameters"`
Status string `json:"status"`
RequestedAt time.Time `json:"requested_at"`
ExpiresAt time.Time `json:"expires_at"`
CancelRequestedAt *time.Time `json:"cancel_requested_at,omitempty"`
}
NodeStateExecution is one pending action dispatch in the executions block of GET /v1/nodes/{node_id}/state. That block is the delivery channel for action dispatches: it is always present ([] when empty, never null) and ordered by RequestedAt, then ExecutionID. An entry keeps reappearing on every pull until its execution reaches a terminal status through the execution callback, so a consumer must tolerate re-observing the same ExecutionID.
Type is one of the ActionKind* values; Status is ExecutionStatusPending, ExecutionStatusAck, or ExecutionStatusStarted. ExpiresAt is an absolute UTC deadline, not a relative timeout. Parameters is nullable: a JSON null decodes to a nil map. The entry carries no callback URL and no hook checksum.
A parameter value is held as raw JSON, not decoded into any: the state response is decoded with a plain decoder, so a JSON number would land in an any as a float64 and every integer beyond 2^53 would reach the action rewritten. The raw form hands the value to the action exactly as the control plane sent it.
CancelRequestedAt is present only on a started entry, once an operator cancelled the Execution: the control plane ends a pending or ack target at once, and such an entry leaves the block. Its presence is the signal to stop the run; plexd never compares its value with its own clock. A JSON null and an absent key both decode to nil. A value that is not an RFC 3339 string fails the decode of the whole state response, as a malformed expires_at does.
type NodeStateFailureDetection ¶ added in v0.38.0
type NodeStateFailureDetection struct {
DetectAfterSeconds int64 `json:"detect_after_seconds"`
}
NodeStateFailureDetection is the failure_detection block of the state pull, as the "Failure detection" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. DetectAfterSeconds is how long a path the node watches on its own, today a relay, may stay silent before the node moves: a whole number of seconds from 5 to 180, and 15 for a Domain that never set it. It is int64 rather than int so a value out of range decodes on 32-bit builds too, and is clamped rather than refused as malformed.
type NodeStateHook ¶ added in v0.28.0
type NodeStateHook struct {
Name string `json:"name"`
Version int `json:"version"`
Checksum string `json:"checksum"`
}
NodeStateHook is one entry of the hooks block of the state pull, a published hook version a rollout assigns the node, as the "Published hooks" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it. It never carries the script, which the node fetches through GET /v1/nodes/{node_id}/hooks/{name}/versions/{version}. Checksum is the SHA-256 of that script as 32 raw bytes in standard-padded base64, the encoding of a DeclaredHook's Checksum, so the fetched version is checked against the digest the pull named.
type NodeStateReportRequest ¶ added in v0.2.0
type NodeStateReportRequest struct {
Value string `json:"value"`
WorkloadTag string `json:"workload_tag,omitempty"`
}
NodeStateReportRequest is the control-plane wire format for the body of PUT /v1/nodes/{id}/state/reports/{key}. Value is the opaque report payload; WorkloadTag attributes the report to a workload and is absent when the report is unattributed.
type NodeStateReportResponse ¶ added in v0.2.0
type NodeStateReportResponse struct {
AcceptedAt time.Time `json:"accepted_at"`
Key string `json:"key"`
}
NodeStateReportResponse is the control-plane wire format for the 200 body of PUT /v1/nodes/{id}/state/reports/{key} (and DELETE /v1/nodes/{id}/state/ reports/{key}). Key echoes the report key the operation addressed.
type NodeStateSecret ¶ added in v0.16.0
NodeStateSecret is one entry of the secrets block of the state pull, a Secret the node may read as the "Secret inventory" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it: its name and current version, never its value, which the node fetches through GET /v1/nodes/{node_id}/secrets/{name}. The node API maps Name onto the key of its secret index (SecretRef.Key).
type NodeStateSession ¶ added in v0.3.0
type NodeStateSession struct {
SessionID string `json:"session_id"`
JTI string `json:"jti"`
Kind string `json:"kind"`
Target SessionTarget `json:"target"`
ExpiresAt time.Time `json:"expires_at"`
IdleTimeoutSeconds int `json:"idle_timeout_seconds,omitempty"`
}
NodeStateSession is one live mediated-access session in the sessions block of GET /v1/nodes/{node_id}/state. That block is desired state, not a queue: it is always present on the wire ([] when empty, never null). An entry appears when the control plane issues the session and disappears on revocation or hard expiry — the disappearance is the teardown signal, there is no separate teardown event. A response that violates the contract by omitting or nulling the block decodes to a nil NodeStateSnapshot.Sessions and is not read as an empty block.
Kind is one of the SessionKind* values and selects which member of Target is set. JTI equals the session id: it is carried as an opaque value and never evaluated. ExpiresAt is an absolute UTC timestamp, not a relative timeout. IdleTimeoutSeconds 0 or absent means the session has no idle window.
type NodeStateSigningKey ¶ added in v0.15.0
type NodeStateSigningKey struct {
KeyID string `json:"key_id"`
PublicKey string `json:"public_key"`
}
NodeStateSigningKey is the signing_key block of the state pull, the Domain signing key as the "Domain signing key" section of plexsphere's agent contract (docs/reference/api/plexd-agent-contract.md) describes it: the id the key signs under and its 32-byte Ed25519 public key in standard base64, the same encodings POST /v1/register uses.
type NodeStateSnapshot ¶ added in v0.2.0
type NodeStateSnapshot struct {
Peers []SnapshotPeer `json:"peers"`
Reachability json.RawMessage `json:"reachability"`
Policy *PolicySnapshot `json:"policy"`
Bridge *BridgeSnapshot `json:"bridge"`
State *NodeStateBlock `json:"state"`
Reports *NodeStateBlock `json:"reports"`
Executions []NodeStateExecution `json:"executions"`
// Sessions is a pointer for the same reason the block fields above are: the
// sessions block is desired state whose emptiness is destructive — an empty
// block tears every live session down — so "the control plane says you have
// no sessions" ([]) has to stay distinguishable from "the control plane did
// not populate the block" (null, or a key a build predating the block never
// wrote). A nil pointer is the second case and is not a teardown signal.
Sessions *[]NodeStateSession `json:"sessions"`
// Secrets is the node's secret inventory, ordered by name. It is a pointer
// for the reason Sessions is: [] says the node may read nothing and empties
// the node API's secret index, while a nil value, the wire's null or a key a
// control plane predating the block never wrote, means the control plane did
// not say this time, and the index is kept.
Secrets *[]NodeStateSecret `json:"secrets"`
// SigningKey is the key the node's Domain signs envelopes and session
// tokens with. A nil value, the wire's null or a key a control plane
// predating the block never wrote, means the control plane could not say
// this time: the node keeps the key it holds, and never drops it.
SigningKey *NodeStateSigningKey `json:"signing_key"`
// Hooks is the node's desired set of published hook versions, ordered by
// name. It is a pointer for the reason Secrets is: [] says the node should
// run no rolled-out hook and removes every one it installed, while a nil
// value, the wire's null or a key a control plane predating the block
// never wrote, means the control plane could not compute the set this
// time, and every rolled-out hook is kept.
Hooks *[]NodeStateHook `json:"hooks"`
// DNS is the mesh DNS names of the node's Domain. A block is the full set,
// never a delta: it replaces the names the node answers. A nil value, the
// wire's null or a key a control plane predating the block never wrote,
// means the control plane did not say this time, and the node keeps the
// names it holds.
DNS *NodeStateDNS `json:"dns"`
// FailureDetection is the Domain's failure-detection time, a
// NodeStateFailureDetection. It is carried raw, as Reachability is, so
// its consumer decodes it leniently and a malformed tuning value never
// fails the pull that carries the peers and the policy. A nil value, the
// wire's null or a key a control plane predating the block never wrote,
// means the control plane did not say this time, and the node keeps the
// value it holds.
FailureDetection json.RawMessage `json:"failure_detection"`
}
NodeStateSnapshot is the desired-state envelope returned by GET /v1/nodes/{node_id}/state. Every block key is always present on the wire: a null value means "block not populated", never "field absent". The differ therefore distinguishes a nil pointer from a populated block, so none of the thirteen fields carry omitempty.
type Peer ¶
type Peer struct {
ID string `json:"id"`
PublicKey string `json:"public_key"`
MeshIP string `json:"mesh_ip"`
// Endpoint is the first entry of Endpoints, or empty when the peer has no
// endpoint to dial.
Endpoint string `json:"endpoint"`
// Endpoints is the peer's dial order: the endpoints the WireGuard manager
// tries one after another until a handshake completes.
Endpoints []string `json:"endpoints,omitempty"`
// Fallbacks is the peer's relay set as it ends Endpoints, in dial order:
// the relay of its assigned bridge first, then its standby relays, and nil
// when the peer has no relay. Endpoint selection holds each relay as long
// as the entries before the first one took together, and only a peer that
// connected over a relay dials the standbys.
Fallbacks []string `json:"fallbacks,omitempty"`
// AllowedIPs is the peer's mesh address as a /32 followed by
// RoutedSubnets.
AllowedIPs []string `json:"allowed_ips"`
PSK string `json:"psk"`
// RoutedSubnets are the subnets of the peer's routed_subnets this node
// accepted, in the list's order, and nil when it accepted none. The
// WireGuard manager routes each of them through the mesh interface.
RoutedSubnets []string `json:"routed_subnets,omitempty"`
}
Peer is the internal WireGuard programming shape built by peerFromSnapshot.
type PolicyRevisionRef ¶ added in v0.31.0
type PolicyRevisionRef struct {
PolicyID string `json:"policy_id"`
RevisionID string `json:"revision_id"`
}
PolicyRevisionRef names one revision of one Policy. Both ids are UUIDs that plexd passes through as strings.
type PolicyRule ¶
type PolicyRule struct {
Protocol string `json:"protocol"`
SourceCIDR string `json:"source_cidr"`
DestinationCIDR string `json:"destination_cidr"`
Ports *PortRange `json:"ports,omitempty"`
Log bool `json:"log,omitempty"`
// LegacyAction is the action key of the format before
// plexsphere/plexsphere#1058; nil when the key is absent. The engine reads
// a rule carrying "allow" as an allow and rejects any other value, so a
// control plane that still sends deny rules cannot have them enforced as
// allows.
LegacyAction *string `json:"action,omitempty"`
}
PolicyRule allows the traffic from SourceCIDR to DestinationCIDR that its protocol and port range match. Both prefixes are IPv4 or both IPv6. Ports is present iff Protocol is tcp or udp and is absent for icmp/any. Log asks for the rule's traffic to be logged.
type PolicySnapshot ¶ added in v0.2.0
type PolicySnapshot struct {
RevisionID string `json:"revision_id"`
Fingerprint string `json:"fingerprint"`
Rules []PolicyRule `json:"rules"`
// Revisions names the (Policy, revision) pair of every compiled row the
// block merges, in ascending policy_id, the order Fingerprint covers. A
// control plane before plexsphere/plexsphere#1059 sends none. plexd echoes
// the pairs in its policy status report and never parses them.
Revisions []PolicyRevisionRef `json:"revisions,omitempty"`
}
PolicySnapshot is the single merged policy block. Every rule is an allow and rule order carries no meaning: traffic no rule allows is dropped. Fingerprint is a 44-char base64 SHA-256 over the server's canonical rule byte stream; plexd treats it as an opaque comparison key and never re-derives it from Rules.
func (*PolicySnapshot) Clone ¶ added in v0.31.0
func (p *PolicySnapshot) Clone() *PolicySnapshot
Clone returns a deep copy of p: its Rules, each rule's Ports and LegacyAction, and its Revisions share no memory with p. A nil p yields nil.
type PolicyStatusApplied ¶ added in v0.31.0
type PolicyStatusApplied struct {
Fingerprint string `json:"fingerprint,omitempty"`
Revisions []PolicyRevisionRef `json:"revisions"`
}
PolicyStatusApplied echoes the policy block a node applied. Fingerprint is empty, and so absent on the wire, when the pull carried policy: null. Revisions is required; ReportPolicyStatus sends a nil one as [].
type PolicyStatusDrops ¶ added in v0.31.0
PolicyStatusDrops counts what the node's default deny dropped since its agent last installed the ruleset. A counter below its previous report tells the control plane that the count restarted.
type PolicyStatusRejected ¶ added in v0.31.0
type PolicyStatusRejected struct {
Fingerprint string `json:"fingerprint"`
Revisions []PolicyRevisionRef `json:"revisions"`
Reason string `json:"reason"`
}
PolicyStatusRejected echoes the policy block a node's latest apply failed on, and why. Every member is required; ReportPolicyStatus sends a nil Revisions as []. Reason holds 1 to 1024 bytes of UTF-8 without control characters.
type PolicyStatusRequest ¶ added in v0.31.0
type PolicyStatusRequest struct {
// Enforcement is one of the PolicyEnforcement* constants.
Enforcement string `json:"enforcement"`
// Applied is the ruleset the node applied last; nil when it applied none
// since its agent started.
Applied *PolicyStatusApplied `json:"applied,omitempty"`
// Rejected is the ruleset the node's latest apply failed on; nil when the
// latest apply did not fail.
Rejected *PolicyStatusRejected `json:"rejected,omitempty"`
// Drops are the default deny's counters; nil when the firewall backend
// does not count drops.
Drops *PolicyStatusDrops `json:"drops,omitempty"`
}
PolicyStatusRequest is the body of PUT /v1/nodes/{node_id}/policy-status: what the node did with the policy block of its pulls. The control plane decodes it with unknown members refused, refuses a missing or null required member with 400 invalid_policy_status, and a member of the wrong JSON type with 400 malformed_policy_status.
type PolicyStatusResponse ¶ added in v0.31.0
type PolicyStatusResponse struct {
// AcceptedAt is the server receive time the report is stored with.
AcceptedAt time.Time `json:"accepted_at"`
// Status is the policy status the report derives against the ruleset the
// pull serves: applied, pending, rejected or not_enforced.
Status string `json:"status"`
}
PolicyStatusResponse is the 200 body of PUT /v1/nodes/{node_id}/policy-status.
type PortRange ¶ added in v0.2.0
PortRange is a single inclusive destination port range (from <= to).
type ReachabilitySnapshot ¶ added in v0.7.0
type ReachabilitySnapshot struct {
State string `json:"state"`
LastHeartbeatAt *time.Time `json:"last_heartbeat_at,omitempty"`
ChangedAt time.Time `json:"changed_at"`
}
ReachabilitySnapshot is the interior of the snapshot's reachability block: the control plane's own verdict about this node, derived from the heartbeats it has admitted. It is a diagnostic projection, never desired state.
State is a plain string and is never validated against the constants below. The verdict vocabulary belongs to the control plane and grows there — never_reported was added after plexd shipped — so a value this build does not know must keep flowing to the log rather than be rejected. LastHeartbeatAt is absent until the first heartbeat is accepted; ChangedAt is always present.
type ReconcileTrigger ¶ added in v0.2.0
type ReconcileTrigger interface {
TriggerReconcile()
}
ReconcileTrigger requests a full state reconcile. *reconcile.Reconciler satisfies it.
type ReconnectEngine ¶
type ReconnectEngine struct {
// contains filtered or unexported fields
}
ReconnectEngine manages SSE reconnection with backoff and polling fallback.
func NewReconnectEngine ¶
func NewReconnectEngine(logger *slog.Logger) *ReconnectEngine
NewReconnectEngine creates a new ReconnectEngine with default settings.
func (*ReconnectEngine) Mode ¶ added in v0.2.0
func (r *ReconnectEngine) Mode() DeliveryMode
Mode returns the delivery mode currently reported by the engine.
func (*ReconnectEngine) Run ¶
func (r *ReconnectEngine) Run(ctx context.Context, connectFn ConnectFunc, pollFn PollFunc) error
Run is the main state machine loop that manages SSE reconnection.
States: Connecting -> Connected | Backoff
Backoff -> Connecting | Polling Polling -> Connecting (periodic SSE retry)
Context cancellation exits from any state.
func (*ReconnectEngine) SetBaseInterval ¶
func (r *ReconnectEngine) SetBaseInterval(d time.Duration)
SetBaseInterval updates the base backoff interval. This is called when the SSE retry: field is received from the server.
func (*ReconnectEngine) SetClock ¶
func (r *ReconnectEngine) SetClock(c Clock)
SetClock sets a custom clock implementation for testing.
func (*ReconnectEngine) SetIntervals ¶
func (r *ReconnectEngine) SetIntervals(base, max time.Duration)
SetIntervals configures the base and max backoff intervals and resets the current interval to the new base. Useful for testing with fast intervals.
func (*ReconnectEngine) SetOnModeChange ¶ added in v0.2.0
func (r *ReconnectEngine) SetOnModeChange(fn func(DeliveryMode))
SetOnModeChange sets the callback invoked on every delivery-mode transition. The callback is fired outside the engine's lock and may be nil.
func (*ReconnectEngine) SetPollInterval ¶
func (r *ReconnectEngine) SetPollInterval(d time.Duration)
SetPollInterval sets how often to poll during polling fallback mode.
func (*ReconnectEngine) SetPollingFallbackConfig ¶
func (r *ReconnectEngine) SetPollingFallbackConfig(fallbackAfter, pollInterval time.Duration)
SetPollingFallbackConfig configures when to enter polling mode and how often to poll.
func (*ReconnectEngine) SetReprobeInterval ¶ added in v0.2.0
func (r *ReconnectEngine) SetReprobeInterval(d time.Duration)
SetReprobeInterval sets how often pull-only mode re-probes the SSE endpoint. A non-positive duration is ignored.
type RegisterPeer ¶ added in v0.2.0
type RegisterPeer struct {
NodeID string `json:"node_id"`
MeshIP string `json:"mesh_ip"`
PublicKey string `json:"public_key"`
FallbackEndpoint string `json:"fallback_endpoint,omitempty"`
}
RegisterPeer is the initial peer snapshot entry returned by POST /v1/register. It is deliberately narrow: it carries NO psk, allowed_ips, or endpoint. The reconciliation peer shape is SnapshotPeer.
type RegisterRequest ¶
type RegisterResponse ¶
type RegisterResponse struct {
NodeID string `json:"node_id"`
MeshIP string `json:"mesh_ip"`
SigningPublicKey string `json:"signing_public_key"`
SigningKeyID string `json:"signing_key_id"`
NSK string `json:"nsk"`
PeerSnapshot []RegisterPeer `json:"peer_snapshot"`
DomainMeshCIDR string `json:"domain_mesh_cidr"`
}
type RelayAssignment ¶ added in v0.19.0
type RelayAssignment struct {
PeerNodeID string `json:"peer_node_id"`
FallbackEndpoint string `json:"fallback_endpoint"`
FallbackEndpointPort int `json:"fallback_endpoint_port"`
}
RelayAssignment is one entry of RelayConfig.Assignments: a peer whose fallback names this bridge, and the fallback that peer dials.
type RelayConfig ¶
type RelayConfig struct {
Enabled bool `json:"enabled"`
ListenPort int `json:"listen_port"`
Assignments []RelayAssignment `json:"assignments"`
}
RelayConfig is the bridge.relay block of the state pull, the control plane's NodeStateBridgeRelay. When Enabled is true and local consent (bridge.relay_enabled) allows it, the bridge relays WireGuard on UDP ListenPort among the peers the same pull lists. Assignments is carried as the control plane sends it, and the relay does not read it.
type RelayStatusRequest ¶ added in v0.23.0
type RelayStatusRequest struct {
// State is one of the RelayState* constants.
State string `json:"state"`
// ListenPort is the relay's UDP port, in 1..65535. It stays a plain int:
// 0 is never a valid port, and the two states that forbid the member leave
// it 0, so omitempty drops it exactly where it must be absent.
ListenPort int `json:"listen_port,omitempty"`
// BoundSeconds is the whole seconds since the relay socket was bound, in
// 0..MaxRelayStatusBoundSeconds. It is a pointer because 0 is a valid
// value, for a socket bound less than a second ago: a plain int64 with
// omitempty would drop it, and the control plane would refuse the running
// report with 400 invalid_relay_status. nil omits the member, as every
// state but running requires.
BoundSeconds *int64 `json:"bound_seconds,omitempty"`
}
RelayStatusRequest is the body of PUT /v1/nodes/{node_id}/relay-status: the state of the bridge's relay as the node reports it. ListenPort accompanies running and bind_failed, BoundSeconds only running. A member the state requires or forbids is refused with 400 invalid_relay_status, and an out-of-range value or a null member with 400 malformed_relay_status. The handler decodes with DisallowUnknownFields, so the struct carries the contract's fields and nothing else.
The control plane anchors BoundSeconds on its own receive time, so a body is only true for the attempt it was assembled for, and the agent builds a fresh one for every attempt.
type RelayStatusResponse ¶ added in v0.23.0
type RelayStatusResponse struct {
// AcceptedAt is the server receive time BoundSeconds was anchored on.
AcceptedAt time.Time `json:"accepted_at"`
}
RelayStatusResponse is the 200 body of PUT /v1/nodes/{node_id}/relay-status.
type RetryCallback ¶
RetryCallback is called when the SSE server sends a retry: field.
type SSEEvent ¶
type SSEEvent struct {
Type string // from "event:" field, defaults to "message"
Data string // concatenated data fields
ID string // from "id:" field
}
SSEEvent represents a single parsed SSE event.
type SSEManager ¶
type SSEManager struct {
// contains filtered or unexported fields
}
SSEManager is the top-level orchestrator that wires SSEStream, ReconnectEngine, EventVerifier, and EventDispatcher together.
func NewSSEManager ¶
func NewSSEManager(client *ControlPlane, verifier EventVerifier, logger *slog.Logger) *SSEManager
NewSSEManager creates a new SSEManager. If verifier is nil, NoOpVerifier is used.
func (*SSEManager) Mode ¶ added in v0.2.0
func (m *SSEManager) Mode() DeliveryMode
Mode returns the delivery mode currently reported by the reconnect engine.
func (*SSEManager) RegisterHandler ¶
func (m *SSEManager) RegisterHandler(eventType string, handler EventHandler)
RegisterHandler adds a handler for the given event type. Must be called before Start.
func (*SSEManager) SetIdleTimeout ¶ added in v0.2.0
func (m *SSEManager) SetIdleTimeout(d time.Duration)
SetIdleTimeout sets the SSE idle timeout used for connections opened by Start. A zero duration falls back to DefaultSSEIdleTimeout.
func (*SSEManager) SetOnModeChange ¶ added in v0.2.0
func (m *SSEManager) SetOnModeChange(fn func(DeliveryMode))
SetOnModeChange registers a callback invoked on every delivery-mode transition. The callback may be nil.
func (*SSEManager) SetPollFunc ¶
func (m *SSEManager) SetPollFunc(fn PollFunc)
SetPollFunc sets the function called during polling fallback to fetch full state.
func (*SSEManager) SetPollingFallback ¶
func (m *SSEManager) SetPollingFallback(fallbackAfter, pollInterval time.Duration)
SetPollingFallback configures when to enter polling mode and how often to poll.
func (*SSEManager) SetReconcileTrigger ¶ added in v0.2.0
func (m *SSEManager) SetReconcileTrigger(t ReconcileTrigger)
SetReconcileTrigger sets the trigger fired once after every successful SSE connect so the client covers replay gaps with a full reconcile pull. A nil trigger disables the pull.
func (*SSEManager) SetReconnectIntervals ¶
func (m *SSEManager) SetReconnectIntervals(base, max time.Duration)
SetReconnectIntervals configures the base and max backoff intervals. Useful for testing with fast intervals.
func (*SSEManager) SetReprobeInterval ¶ added in v0.2.0
func (m *SSEManager) SetReprobeInterval(d time.Duration)
SetReprobeInterval sets how often pull-only mode re-probes the SSE endpoint. It delegates to the reconnect engine.
func (*SSEManager) Shutdown ¶
func (m *SSEManager) Shutdown()
Shutdown gracefully stops the manager by cancelling its context.
type SSEParser ¶
type SSEParser struct {
// contains filtered or unexported fields
}
SSEParser reads from an io.Reader and emits parsed SSE events.
func NewSSEParser ¶
NewSSEParser creates a parser reading from the given reader.
func (*SSEParser) LastEventID ¶
LastEventID returns the most recently received event ID.
func (*SSEParser) Next ¶
Next reads lines until a complete event is found. Returns the event and true, or a zero event and false when the reader is exhausted.
func (*SSEParser) SetRetryCallback ¶
func (p *SSEParser) SetRetryCallback(cb RetryCallback)
SetRetryCallback sets the function called when a retry: field is received.
type SSEStream ¶
type SSEStream struct {
// contains filtered or unexported fields
}
SSEStream connects to the SSE endpoint, parses events, verifies envelopes, and dispatches them to registered handlers.
func NewSSEStream ¶
func NewSSEStream(client *ControlPlane, verifier EventVerifier, dispatcher *EventDispatcher, idleTimeout time.Duration, logger *slog.Logger) *SSEStream
NewSSEStream creates a new SSEStream.
func (*SSEStream) Connect ¶
Connect establishes the SSE connection and processes events until the connection drops or context is cancelled. Returns nil when the connection closes cleanly, or an error.
func (*SSEStream) LastEventID ¶
LastEventID returns the last received event ID (for reconnection).
func (*SSEStream) SetOnConnected ¶ added in v0.2.0
func (s *SSEStream) SetOnConnected(fn func())
SetOnConnected registers a hook invoked once after every ConnectSSE that returns HTTP 200, before the parse loop begins.
type SSHActivity ¶ added in v0.2.0
type SSHActivity struct {
Command string `json:"command,omitempty"`
ExitCode *int `json:"exit_code,omitempty"`
StartedAt *time.Time `json:"started_at,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Phase string `json:"phase,omitempty"`
ListenerEndpoint string `json:"listener_endpoint,omitempty"`
TerminatedBy string `json:"terminated_by,omitempty"`
}
SSHActivity records one row of an SSH session. It takes one of two shapes.
A command row carries Command, the command line of an exec request, capped at 1 KiB, optionally with ExitCode, StartedAt and CompletedAt (RFC 3339 timestamps). plexd posts it twice per command: once with StartedAt before the command runs, and once with ExitCode and CompletedAt after it exited.
A lifecycle row carries Phase, one of the SSHPhase* values, plus TerminatedBy (one of the TerminatedBy* values) on session_ended, and no command fields. An ssh session binds no listener, so plexd sends no ListenerEndpoint; the field stays for the session_started rows older agents post with one, which the control plane still admits.
plexd never posts an empty Command; the control plane refuses a row that mixes the two shapes.
type SecretEnvelope ¶ added in v0.2.0
SecretEnvelope is the raw AES-256-GCM envelope served by GET /v1/nodes/{id}/secrets/{name}: Data is <12-byte nonce> || <ciphertext + 16-byte GCM tag>, Version and KID come from the X-Plexsphere-Secret-Version and X-Plexsphere-Secret-KID headers. It is parsed from headers and body, never from JSON.
type SecretRef ¶
SecretRef is one entry of the local node API's secret index, the list GET /v1/state/secrets serves. It is fed from the NodeStateSecret entries of the state pull, whose name becomes Key.
type SessionActivityRequest ¶ added in v0.2.0
type SessionActivityRequest struct {
SSH *SSHActivity `json:"ssh,omitempty"`
K8s *K8sActivity `json:"k8s,omitempty"`
TCP *TCPActivity `json:"tcp,omitempty"`
}
SessionActivityRequest is the one-of activity record a node posts to POST /v1/nodes/{node_id}/sessions/{session_id}. Exactly one member is set, selecting the session kind: SSH, K8s, or TCP.
type SessionConnectRequest ¶ added in v0.20.0
type SessionConnectRequest struct {
SessionID string `json:"session_id"`
ConnectionID string `json:"connection_id"`
ExpiresAt time.Time `json:"expires_at"`
}
SessionConnectRequest is the payload of the session_connect event: the ssh session a client attached to, the one-time id of the connection the node is asked to open for it, and the instant after which the control plane no longer accepts that connection. Its shape is the control plane's access.SessionConnectRequested event, whose event_id and occurred_at header members plexd does not read.
type SessionRevocation ¶ added in v0.18.0
type SessionRevocation struct {
SessionID string `json:"session_id"`
JTI string `json:"jti"`
RevokedAt time.Time `json:"revoked_at"`
RevokeReason string `json:"revoke_reason"`
}
SessionRevocation is the payload of the session_revoked event: the revoked session, the revoked token's jti (equal to the session id), and when and why the control plane revoked it. Its shape is the control plane's SSEEventSessionRevoked schema.
type SessionTarget ¶ added in v0.3.0
type SessionTarget struct {
SSH *SessionTargetSSH `json:"ssh,omitempty"`
K8s *SessionTargetK8s `json:"k8s,omitempty"`
TCP *SessionTargetTCP `json:"tcp,omitempty"`
}
SessionTarget is the target of a NodeStateSession. Exactly one member is set, selecting the session kind: SSH, K8s, or TCP.
type SessionTargetK8s ¶ added in v0.3.0
type SessionTargetK8s struct {
User string `json:"user"`
ImpersonateGroups []string `json:"impersonate_groups,omitempty"`
}
SessionTargetK8s is the target of a k8s session. User is the impersonated Kubernetes user; ImpersonateGroups are the groups impersonated alongside it.
type SessionTargetSSH ¶ added in v0.3.0
type SessionTargetSSH struct {
User string `json:"user"`
AllowedCommands []string `json:"allowed_commands,omitempty"`
}
SessionTargetSSH is the target of an ssh session. User is the local account the session logs in as; AllowedCommands, when set, is the closed set of command lines the session may run.
type SessionTargetTCP ¶ added in v0.3.0
SessionTargetTCP is the target of a tcp session: the host and port the node forwards the session's connections to.
type SigningKeyRotation ¶ added in v0.2.0
type SigningKeyRotation struct {
KeyID string `json:"key_id"`
PublicKey string `json:"public_key"`
PreviousKeyID string `json:"previous_key_id"`
TransitionExpires time.Time `json:"transition_expires"`
}
SigningKeyRotation is the payload of the signing_key_rotated event: the new current signing key and, optionally, the previous key id kept valid until a transition deadline. Its shape is an author-approved assumption until the platform taxonomy documents it.
type SiteToSiteConfig ¶
type SiteToSiteConfig struct {
Enabled bool `json:"enabled"`
Tunnels []SiteToSiteTunnel `json:"tunnels"`
}
SiteToSiteConfig is the bridge.site_to_site block of the state pull, the control plane's NodeStateBridgeSiteToSite: every site-to-site tunnel of the bridge Resource, ordered by slug. A bridge serves Tunnels only when Enabled is true and its local configuration does not opt out; a block with Enabled false, and an absent or null block, serve no tunnel. The block is whole: a tunnel a later pull no longer lists is torn down. A block in the shape before plexsphere/plexsphere#1107 (tunnel_id, remote_endpoint, local_subnets, remote_subnets, psk, interface_name, provider_type) decodes to tunnels without an id, which a bridge neither serves nor reports.
type SiteToSiteInfo ¶
type SiteToSiteInfo struct {
Enabled bool `json:"enabled"`
Tunnels []SiteToSiteTunnelInfo `json:"tunnels,omitempty"`
}
SiteToSiteInfo is the site-to-site status a node publishes under the node API report key status.site-to-site: whether the last applied block enabled site-to-site tunnels, and one entry per tunnel the bridge holds, in block order.
type SiteToSiteStatusRequest ¶ added in v0.36.0
type SiteToSiteStatusRequest struct {
// State is one of the SiteToSiteState* constants.
State string `json:"state"`
// Tunnels holds one entry per reported tunnel, in the order of the pull;
// nil omits the member, which the contract reads as no entries.
Tunnels []SiteToSiteStatusTunnel `json:"tunnels,omitempty"`
}
SiteToSiteStatusRequest is the body of PUT /v1/nodes/{node_id}/site-to-site-status: whether the bridge's local configuration serves site-to-site tunnels, and whether each tunnel of its pull is up and answered by its remote site. The control plane keeps the latest state per node and never ages it, and refuses tunnel creates and updates on the bridge while it reads opted_out. The tunnel entries age after three heartbeat intervals. Each report replaces the tunnel entries of the one before it.
A missing, null or unknown state, an unknown member, data after the report, more than MaxSiteToSiteStatusTunnels entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed_site_to_site_status, and so does an entry that breaks the presence rules of SiteToSiteStatusTunnel. An opted-out report with entries and an id that repeats an earlier entry answer 400 invalid_site_to_site_status. A body over 64 KiB answers 413 site_to_site_status_body_too_large.
type SiteToSiteStatusResponse ¶ added in v0.36.0
type SiteToSiteStatusResponse struct {
// AcceptedAt is the server receive time of the report.
AcceptedAt time.Time `json:"accepted_at"`
}
SiteToSiteStatusResponse is the 200 body of PUT /v1/nodes/{node_id}/site-to-site-status.
type SiteToSiteStatusTunnel ¶ added in v0.36.0
type SiteToSiteStatusTunnel struct {
// ID is the tunnel's id from the pull, a UUID other than the zero UUID.
ID string `json:"id"`
// Health is one of the SiteToSiteHealth* constants.
Health string `json:"health"`
// Reason is a token of the grammar ^[a-z][a-z0-9_]{0,62}$.
Reason string `json:"reason,omitempty"`
// Established says whether the remote site answers: for a wireguard
// tunnel the latest handshake with the remote peer is at most 180
// seconds old, for an ipsec tunnel the IKE and child security
// associations stand, and for an openvpn tunnel the peer is connected.
// It is a pointer because false is a value the contract requires on a
// tunnel that is up, and an entry that is down must not carry it.
Established *bool `json:"established,omitempty"`
// PublicKey is the public half of the key of a wireguard tunnel's
// interface: 44 characters of standard base64 that decode to 32 bytes.
PublicKey string `json:"public_key,omitempty"`
}
SiteToSiteStatusTunnel is one entry of tunnels, the control plane's SiteToSiteStatusReportTunnel. Reason is sent exactly when Health is down, Established exactly when it is up, and PublicKey only when it is up: the bridge sends it for a wireguard tunnel that is up and never for an ipsec or openvpn one. omitempty drops an empty member, so a caller leaves every member it must not send empty, and Established nil.
type SiteToSiteTunnel ¶
type SiteToSiteTunnel struct {
// ID is a UUID; ValidSiteToSiteTunnelID checks it.
ID string `json:"id"`
Slug string `json:"slug"`
// Kind is one of the SiteToSiteKind* constants.
Kind string `json:"kind"`
// RemoteHost is the remote site's host name of at most 253 characters
// or its IP address.
RemoteHost string `json:"remote_host"`
// RemotePort is the remote site's port, 1 to 65535.
RemotePort int `json:"remote_port"`
// AllowedSubnets are the 1 to 64 networks behind the remote site, in
// CIDR notation and in the order the operator wrote them.
AllowedSubnets []string `json:"allowed_subnets"`
// ListenPort is the UDP port of a wireguard tunnel's interface.
ListenPort int `json:"listen_port,omitempty"`
// RemotePublicKey is the remote site's WireGuard public key of a
// wireguard tunnel: 44 characters of standard base64 that decode to 32
// bytes.
RemotePublicKey string `json:"remote_public_key,omitempty"`
// AuthSecretName names the Secret that holds the tunnel's key as plain
// text: the preshared key of a wireguard tunnel, absent when it uses
// none, the IKE pre-shared key of an ipsec tunnel, or the static key of
// an openvpn tunnel.
AuthSecretName string `json:"auth_secret_name,omitempty"`
}
SiteToSiteTunnel is one tunnel of the block, the control plane's NodeStateBridgeSiteToSiteTunnel. Every tunnel carries ID, Slug, Kind, RemoteHost, RemotePort and AllowedSubnets; the other members follow from its Kind: ListenPort, RemotePublicKey and an optional AuthSecretName for wireguard, AuthSecretName alone for ipsec and openvpn. No member is a private key or the value of a Secret.
type SiteToSiteTunnelInfo ¶ added in v0.36.0
type SiteToSiteTunnelInfo struct {
ID string `json:"id"`
Slug string `json:"slug"`
Kind string `json:"kind"`
// Interface is the tunnel's link; empty while it has none.
Interface string `json:"interface,omitempty"`
// Health is one of the SiteToSiteHealth* constants.
Health string `json:"health"`
// Reason says why a tunnel is down; empty while it is up.
Reason string `json:"reason,omitempty"`
// Established says whether the remote site of a tunnel that is up
// answers; it is false for a tunnel that is down.
Established bool `json:"established"`
// ListenPort is a wireguard tunnel's UDP port.
ListenPort int `json:"listen_port,omitempty"`
RemoteHost string `json:"remote_host"`
RemotePort int `json:"remote_port"`
AllowedSubnets []string `json:"allowed_subnets"`
}
SiteToSiteTunnelInfo is one tunnel of a SiteToSiteInfo.
type SnapshotPeer ¶ added in v0.2.0
type SnapshotPeer struct {
NodeID string `json:"node_id"`
MeshIP string `json:"mesh_ip"`
PublicKey string `json:"public_key"`
// Endpoint is the peer's direct WireGuard endpoint as host:port (an IPv6
// host in brackets), the address it last reported through PUT
// /v1/nodes/{node_id}/endpoint. It is absent while the peer has no fresh
// observation.
//
// FallbackEndpoints is the peer's relays as host:port in dial order, at
// most 4 by the contract: the relay of the peer's assigned bridge first,
// then its standby relays. They end the dial order the WireGuard manager
// tries. FallbackEndpoint is the first entry, and the only relay a
// control plane that predates the set sends. Both are absent while the
// peer has no relay, and the list never names this node.
Endpoint string `json:"endpoint,omitempty"`
FallbackEndpoint string `json:"fallback_endpoint,omitempty"`
FallbackEndpoints []string `json:"fallback_endpoints,omitempty"`
// EndpointCandidates are the peer's endpoint candidates as host:port
// strings, at most MaxEndpointCandidates. The control plane lists first
// the peer's peer-observed endpoints: each address and port at which at
// least two live nodes of the Domain reported, through
// POST /v1/nodes/{node_id}/handshakes, a direct handshake with the peer
// within the Domain's endpoint TTL. The peer's last accepted, unexpired
// local candidates (PUT /v1/nodes/{node_id}/endpoint-candidates) follow,
// in the order the peer sent them. The wire does not mark which entry is
// which, and plexd orders them alike. The field is absent when the peer
// has none, and on every control plane that does not deliver them.
EndpointCandidates []string `json:"endpoint_candidates,omitempty"`
// RoutedSubnets are the IPv4 networks the control plane routes through
// the peer as CIDRs: the networks behind the site-to-site tunnels of a
// peer that is a bridge. A node adds the ones it accepts to the peer's
// allowed IPs and routes them through the mesh interface. The field is
// absent for a peer that routes no network, and the registration
// response never carries it.
RoutedSubnets []string `json:"routed_subnets,omitempty"`
}
SnapshotPeer is a reconciliation peer entry in NodeStateSnapshot. It is a separate type from RegisterPeer (one Go type per contract schema) and carries the peer's direct endpoint but NO psk or allowed_ips: AllowedIPs are derived locally as mesh_ip/32 followed by the entries of RoutedSubnets the node accepts, and the pairwise edge PSK is fetched per edge from GET /v1/nodes/{node_id}/peers/{peer_node_id}/psk, never projected.
type StateEntry ¶ added in v0.2.0
type StateEntry struct {
Key string `json:"key"`
Value string `json:"value"`
WorkloadTag string `json:"workload_tag,omitempty"`
}
StateEntry is a single state entry. Value is an opaque string; WorkloadTag is absent/empty when the entry is unattributed.
type TCPActivity ¶ added in v0.2.0
type TCPActivity struct {
Phase string `json:"phase"`
TargetHost string `json:"target_host,omitempty"`
TargetPort int `json:"target_port,omitempty"`
ListenerEndpoint string `json:"listener_endpoint,omitempty"`
BytesIn *int64 `json:"bytes_in,omitempty"`
BytesOut *int64 `json:"bytes_out,omitempty"`
TerminatedBy string `json:"terminated_by,omitempty"`
}
TCPActivity records a TCP session lifecycle event. Phase is one of the TCPPhase* values. ListenerEndpoint is the node's bound listener address and is set only on session_started rows. BytesIn (operator to target) and BytesOut (target to operator) are pointers so a session_ended row carries explicit zeros while a session_started row omits the byte counters. TerminatedBy, when set, is one of the TerminatedBy* values. A session_active row carries Phase alone.
type UserAccessConfig ¶
type UserAccessConfig struct {
Enabled bool `json:"enabled"`
Providers []UserAccessProvider `json:"providers"`
}
UserAccessConfig is the bridge.user_access block of the state pull, the control plane's NodeStateBridgeUserAccess: every user access provider of the bridge Resource, ordered by slug. A bridge serves Providers only when Enabled is true and its local configuration does not opt out; a block with Enabled false, and an absent or null block, serve no provider. The block is whole: a provider a later pull no longer lists is torn down. A block in the shape before plexsphere/plexsphere#1108 (interface_name, listen_port, peers) decodes to no providers.
type UserAccessDevice ¶ added in v0.36.0
type UserAccessDevice struct {
ID string `json:"id"`
Slug string `json:"slug"`
PublicKey string `json:"public_key"`
Address string `json:"address"`
}
UserAccessDevice is one device of a wireguard provider, the control plane's NodeStateBridgeUserAccessDevice: a WireGuard peer of the provider's interface with PublicKey, and Address as its one allowed IP, a /32.
type UserAccessInfo ¶
type UserAccessInfo struct {
Enabled bool `json:"enabled"`
Providers []UserAccessProviderInfo `json:"providers,omitempty"`
}
UserAccessInfo is the user access status a node publishes under the node API report key status.user-access: whether the last applied block enabled user access, and one entry per provider the bridge holds, in block order.
type UserAccessProvider ¶ added in v0.36.0
type UserAccessProvider struct {
// ID is a UUID; ValidUserAccessProviderID checks it.
ID string `json:"id"`
Slug string `json:"slug"`
// Kind is one of the UserAccessKind* constants.
Kind string `json:"kind"`
// ListenPort is the UDP port of a wireguard provider's interface.
ListenPort int `json:"listen_port,omitempty"`
// AddressPool is the IPv4 network, in CIDR notation, a wireguard
// provider's interface and devices take their addresses from. The
// interface takes the first host address with the pool's prefix length.
AddressPool string `json:"address_pool,omitempty"`
// MaxDevices is the most devices a wireguard provider admits. The control
// plane holds the ceiling; the bridge does not enforce it.
MaxDevices int `json:"max_devices,omitempty"`
// Devices are the devices a wireguard provider admits.
Devices []UserAccessDevice `json:"devices,omitempty"`
// AuthSecretName names the Secret that holds the key a tailscale or
// netbird provider joins with, a Tailscale auth key or a NetBird setup
// key as plain text.
AuthSecretName string `json:"auth_secret_name,omitempty"`
}
UserAccessProvider is one provider of the block, the control plane's NodeStateBridgeUserAccessProvider. It carries the members of its Kind and no others: ListenPort, AddressPool, MaxDevices and Devices for wireguard, AuthSecretName for tailscale and netbird.
type UserAccessProviderInfo ¶ added in v0.36.0
type UserAccessProviderInfo struct {
ID string `json:"id"`
Slug string `json:"slug"`
Kind string `json:"kind"`
// Interface is the provider's network interface; empty while it has none.
Interface string `json:"interface,omitempty"`
// Health is one of the UserAccessHealth* constants.
Health string `json:"health"`
// Reason says why a provider is down; empty while it is up.
Reason string `json:"reason,omitempty"`
// ListenPort is a wireguard provider's UDP port.
ListenPort int `json:"listen_port,omitempty"`
// Devices counts the devices configured on a wireguard provider's
// interface.
Devices int `json:"devices"`
// ConnectedDevices counts those of them with a recent handshake.
ConnectedDevices int `json:"connected_devices"`
}
UserAccessProviderInfo is one provider of a UserAccessInfo.
type UserAccessStatusProvider ¶ added in v0.36.0
type UserAccessStatusProvider struct {
// ID is the provider's id from the pull, a UUID other than the zero UUID.
ID string `json:"id"`
// Health is one of the UserAccessHealth* constants.
Health string `json:"health"`
// Reason is a token of the grammar ^[a-z][a-z0-9_]{0,62}$.
Reason string `json:"reason,omitempty"`
// PublicKey is the public half of the key of a wireguard provider's
// interface: 44 characters of standard base64 that decode to 32 bytes.
PublicKey string `json:"public_key,omitempty"`
// ConnectedDevices is the number of the provider's devices whose latest
// WireGuard handshake is at most 180 seconds old, in 0..1024. It is a
// pointer because 0 is a valid count, for a provider no device reaches.
ConnectedDevices *int `json:"connected_devices,omitempty"`
}
UserAccessStatusProvider is one entry of providers, the control plane's UserAccessStatusReportProvider. Reason is sent exactly when Health is down; PublicKey and ConnectedDevices only when it is up, and the bridge sends both for a wireguard provider that is up and neither for a vendor one. omitempty drops an empty member, so a caller leaves every member it must not send empty.
type UserAccessStatusRequest ¶ added in v0.36.0
type UserAccessStatusRequest struct {
// State is one of the UserAccessState* constants.
State string `json:"state"`
// Providers holds one entry per reported provider, in the order of the
// pull; nil omits the member, which the contract reads as no entries.
Providers []UserAccessStatusProvider `json:"providers,omitempty"`
}
UserAccessStatusRequest is the body of PUT /v1/nodes/{node_id}/user-access-status: whether the bridge's local configuration serves user access, and whether each user access provider of its pull is up. The control plane keeps the latest state per node and never ages it, and refuses provider creates and updates and device admissions on the bridge while it reads opted_out. The provider entries age after three heartbeat intervals. Each report replaces the provider entries of the one before it.
A missing, null or unknown state, an unknown member, data after the report, more than MaxUserAccessStatusProviders entries, and an entry with a malformed id or a value outside its member's rule answer 400 malformed_user_access_status, and so does an entry that breaks the presence rules of UserAccessStatusProvider. An opted-out report with entries and an id that repeats an earlier entry answer 400 invalid_user_access_status. A body over 64 KiB answers 413 user_access_status_body_too_large.
type UserAccessStatusResponse ¶ added in v0.36.0
type UserAccessStatusResponse struct {
// AcceptedAt is the server receive time of the report.
AcceptedAt time.Time `json:"accepted_at"`
}
UserAccessStatusResponse is the 200 body of PUT /v1/nodes/{node_id}/user-access-status.