sdk

package module
v0.5.3 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 22 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Power Manage SDK

Shared protocol definitions, generated code, and client libraries for Power Manage. Used by the Control Server, Gateway, Agent, and Web UI.

Contents

sdk/
├── proto/pm/v1/           Protocol Buffer source definitions
│   ├── common.proto         Base types, enums, error codes
│   ├── actions.proto        Action types, parameters, scheduling
│   ├── agent.proto          Bidirectional streaming (Agent ↔ Gateway)
│   ├── control.proto        Control API (164 RPCs)
│   ├── device_auth.proto    Agent enrollment via local unix socket
│   └── internal.proto       Gateway-to-control proxy for credential operations
│
├── gen/go/pm/v1/           Generated Go code (protobuf + Connect RPC)
│   ├── *.pb.go               Message types with injected validation tags
│   └── pmv1connect/          Connect RPC client and server interfaces
│
├── go/
│   ├── client.go            Agent streaming client (mTLS, heartbeat, action dispatch)
│   ├── crypto/              CSR generation and certificate utilities
│   ├── logging/             Structured logging setup (slog)
│   ├── pkg/                 Package manager abstraction library
│   │   ├── apt.go             APT (Debian/Ubuntu)
│   │   ├── dnf.go             DNF (Fedora/RHEL)
│   │   ├── pacman.go          Pacman (Arch Linux)
│   │   ├── zypper.go          Zypper (openSUSE)
│   │   └── flatpak.go         Flatpak (cross-distro)
│   ├── sys/                 Linux system management libraries
│   │   ├── exec/              Command execution with pluggable PrivilegeBackend (sudo/doas)
│   │   ├── fs/                Filesystem operations (read, write, atomic, permissions)
│   │   ├── service/           Service manager — pluggable ServiceBackend (systemd/openrc/runit/s6)
│   │   ├── encryption/        Disk encryption — pluggable Backend (luks/geli/cgd)
│   │   ├── network/           WiFi connection profiles — pluggable WifiBackend (nm/connman/wpa/iwd)
│   │   ├── firewall/          Packet filter — pluggable Backend (nftables/iptables/firewalld/ufw/pf)
│   │   ├── dns/               Resolver config — pluggable Backend (resolved/resolvconf/dnsmasq/nm)
│   │   ├── netconfig/         IP / routing / DHCP — pluggable Backend (nm/networkd/netplan/dhcpcd/ifupdown)
│   │   ├── notify/            Desktop notification utilities
│   │   ├── osquery/           osquery integration (lazy-init, system queries)
│   │   ├── reboot/            Reboot scheduling
│   │   ├── terminal/          PTY session management
│   │   └── user/              User & group management, password generation
│   ├── validate/            Input validation (struct tag validator + ULID rule)
│   └── verify/              Action payload signature verification
│
├── ts/                      TypeScript SDK (framework-agnostic browser utilities)
│   ├── client.ts              Connect-RPC client with all API methods
│   ├── auth.ts                JWT token management, persistent auth storage
│   ├── errors.ts              Error code extraction from Connect-RPC errors
│   ├── action-types.ts        Action type constants and display helpers
│   ├── config.ts              Configuration utilities
│   ├── offline.ts             Offline support utilities
│   └── index.ts               Package exports
│
├── test/                    Integration test infrastructure
│   ├── Dockerfile.integration  Test container (systemd + sudo)
│   └── run-tests.sh           Test runner script
│
└── Makefile                Proto generation commands

Proto Definitions

Six proto files define the entire API surface:

File Purpose
common.proto ULID identifiers, execution status, assignment modes, error detail codes
actions.proto Action types (package, update, repository, app_image, deb, rpm, flatpak, shell, service, file, directory, user, group, ssh, sshd, admin_policy, lps, encryption, wifi, agent_update), parameters, scheduling. Several capability areas are modelled with a backend enum so the same action type can target multiple implementations (e.g. `AdminPolicyParams.backend = sudo
agent.proto AgentService — bidirectional streaming RPC + action sync, heartbeat, output streaming, OS queries, log queries. Hello includes arch for platform detection.
control.proto ControlService — full RPC surface (~164 methods) covering users, devices, groups, actions, sets, definitions, assignments, tokens, executions, roles, user groups, identity providers, SCIM, TOTP, audit, compliance policies, certificate renewal, search, server settings, and more
device_auth.proto DeviceAuthService — agent enrollment via local unix socket
internal.proto InternalService — gateway-to-control proxy for credential-bearing operations (LUKS keys, LPS passwords) and agent auto-update info

Go SDK

Streaming Client

go/client.go provides the agent-side streaming client:

import sdk "github.com/manchtools/power-manage-sdk"

client, _ := sdk.NewClient(gatewayURL,
    sdk.WithMTLS(certFile, keyFile, caFile),
)
client.Run(ctx, handler)

Features: mTLS authentication, automatic heartbeat, action result reporting, live output streaming, security alerts.

Stream-loop robustness

The receive loop is hardened against a compromised or buggy gateway:

  • Inbound size bound. NewClient wires connect.WithReadMaxBytes(maxInboundMessageBytes) (16 MiB). An over-large ServerMessage is refused with a resource-exhausted error and Run returns cleanly; the caller's reconnect loop (the agent connection loop) re-establishes the stream, instead of allocating the frame — closing an OOM/DoS vector.
  • Per-message panic isolation. dispatchServerMessage runs each message under a scoped recover(): a panic inside any handler method is caught, logged, and turned into a non-fatal dropped frame so one bad handler invocation cannot crash-loop the whole agent (fleet DoS). Genuine fatal stream send/receive errors still propagate (they return from Run, leaving reconnection to the caller).
  • Bounded, panic-safe goroutine fan-out. The server-originated RequestInventory and RevokeLuksDeviceKey legs (and the inventory ticker) run through safeGo — a spawned goroutine with its own deferred recover() — and are gated behind bounded semaphores so a flood of frames cannot spawn unbounded goroutines or crash the process from a goroutine panic.
  • Malformed-oneof nil-guards. A ServerMessage whose inner oneof payload is nil (e.g. a ServerMessage_Action with a nil ActionDispatch) is logged and dropped, never dereferenced.
  • Context-honoring sends. Every Send* method observes its ctx for both the send-lock acquisition and the underlying stream.Send. A stalled peer (a full HTTP/2 flow-control window) can no longer wedge a sender — or every sender queued behind it — past its deadline; a deadline surfaces as a ctx error. At most one stream.Send is ever in flight, so on-wire ordering is preserved.

The sys/exec wrappers SIGKILL-escalate a cancelled child's process group after a bounded grace (then read the final status under a second bounded grace), so a SIGTERM-ignoring child cannot pin the reaping goroutine past the action's deadline.

Certificate Renewal

go/client.go also provides a standalone RenewCertificate function for certificate rotation:

result, _ := sdk.RenewCertificate(ctx, controlURL, csrPEM, currentCertPEM)
// result.Certificate — new signed certificate (PEM)
// result.NotAfter    — certificate expiry time
// result.CACert      — active CA certificate (PEM), for CA rotation

The agent presents its current (still valid) certificate and a new CSR. The Control Server verifies the certificate, checks the fingerprint against the database, signs the new CSR, and returns the active CA certificate. If the CA has been rotated, the agent should update its stored CA certificate.

Bootstrap transport hardening. RegisterAgent and RenewCertificate are the unauthenticated bootstrap calls; their default HTTP client is bounded (request timeout + TLS 1.3 floor) so a hung or malicious control endpoint cannot wedge enrollment/renewal. Proxy support is retained for enterprise deployments (the channel is TLS-authenticated and the optional enrollment CA-pin catches a wrong-CA outcome). A ClientOption (the mTLS variants) overrides the client entirely.

Enrollment trust helpers (crypto):

fp, _ := crypto.CAFingerprintFromPEM(caPEM)        // lowercase-hex SHA-256 of the CA DER
err := crypto.VerifyCAContinuity(oldCAPEM, newCAPEM) // accept only an identical or cross-signed CA

CAFingerprintFromPEM is byte-identical to the control server's ca.FingerprintFromPEM, so an operator-supplied out-of-band pin (e.g. openssl x509 -in ca.crt -outform DER | sha256sum) matches what the agent derives from the registration-returned CA. VerifyCAContinuity guards certificate rotation: a returned CA is adopted only when it is byte-identical to, or cross-signed by, the enrolled CA — refusing an unrelated trust-anchor swap.

Package Manager Library

pkg/ abstracts five Linux package managers behind a unified interface with a builder API:

import "github.com/manchtools/power-manage-sdk/pkg"

pm, _ := pkg.New()                          // auto-detect
pm.Install("nginx").Version("1.24.0").Run() // fluent builder
updates, _ := pm.ListUpgradable()           // query methods

See the package manager README for the full API.

System Management Libraries

sys/ provides opinionated Linux system management utilities. All privileged operations run through the configured privilege backend (sudo or doas, see exec.SetPrivilegeBackend), so the calling process does not need to be root.

sys/exec — Command Execution
import "github.com/manchtools/power-manage-sdk/sys/exec"

result, err := exec.Run(ctx, "ls", "-la")                               // basic command
result, err := exec.Privileged(ctx, "systemctl", "restart", "nginx")     // through sudo/doas
stdout, err := exec.Query("hostname")                                    // quick query
ok := exec.Check("which", "nginx")                                       // boolean check

Key features:

  • Streaming output via RunStreaming with per-line callbacks
  • Automatic path resolution for the privileged commands
  • Output truncation at 1 MiB to prevent memory issues
sys/fs — Filesystem Operations
import "github.com/manchtools/power-manage-sdk/sys/fs"

content, err := fs.ReadFile(ctx, "/etc/hostname")
err := fs.WriteFileAtomic(ctx, "/etc/nginx/nginx.conf", content, "0644", "root", "root")
exists := fs.FileExists(ctx, "/etc/motd")
err := fs.MkdirWithPermissions(ctx, "/opt/app", "0755", "app", "app", true)

All operations escalate via the configured privilege backend (sudo or doas). WriteFileAtomic uses a write-then-rename sequence so concurrent readers see either the old or new file, never a half-written one. For fsync-level durability + an unguessable temp suffix, use AtomicWriteFile in atomic_write.go.

sys/user — User & Group Management
import "github.com/manchtools/power-manage-sdk/sys/user"

info, err := user.Get("deploy")              // get user info (UID, GID, shell, groups, locked)
err := user.Create(ctx, "deploy", "-m", "-s", "/bin/bash")
err := user.GroupCreate(ctx, "developers")
err := user.GroupAddUser(ctx, "deploy", "developers")
password, err := user.GeneratePassword(24, true)  // 24 chars, complex
err := user.SetPassword(ctx, "deploy", password)
sys/osquery — OS Query Integration
import "github.com/manchtools/power-manage-sdk/sys/osquery"

oq := osquery.New()                                // lazy-init, detects installs without restart
rows, err := oq.Query(ctx, "os_version", nil, 0)   // query a table

The convenience table path (Query/QueryTable with a table name) refuses a curated deny-list of credential-bearing tables — shadow, process_envs, crontab, shell_history, sudoers — before any SQL is built or run, so a compromised control server cannot exfiltrate them through the agent's privileged osquery. The deny-list is defense-in-depth on top of the CA-signed osquery RPC; the signed RawSql path is the operator's explicit escape hatch and is intentionally not gated.

sys/encryption — Disk Encryption
import "github.com/manchtools/power-manage-sdk/sys/encryption"

err := encryption.AddKey(ctx, devicePath, existingKey, newKey)
err := encryption.AddKeyToSlot(ctx, devicePath, slot, existingKey, newKey)

encryption exposes a pluggable Backend (LUKS today; geli/cgd planned). Call encryption.SetBackend(encryption.BackendLUKS) once at startup.

sys/service — Service Manager
import "github.com/manchtools/power-manage-sdk/sys/service"

status, err := service.Status("nginx.service")  // {Enabled, Active, Masked, Static}
err := service.EnableNow(ctx, "nginx.service")
err := service.WriteUnit(ctx, "myapp.service", unitContent)
err := service.DaemonReload(ctx)

service selects between systemd / openrc / runit / s6 via service.SetServiceBackend(...).

Action Signature Verification

verify/ provides action payload signature verification for agents:

import "github.com/manchtools/power-manage-sdk/verify"

signer := verify.NewActionSigner(caKey)        // server-side signing
verifier := verify.NewActionVerifier(caCert)   // agent-side verification
err := verifier.Verify(action)                 // verify action signature

Beyond actions, the same CA key signs the four root stream-RPCs (osquery, log query, LUKS revoke, inventory) under per-surface disjoint domains so a signature for one surface can never be replayed against another:

// Control server signs the canonical bytes of each message (signature field
// cleared) under that surface's domain; the agent verifies before any root work.
canonical, _ := verify.OSQueryCanonical(q)                       // also LogQueryCanonical / RevokeLuksDeviceKeyCanonical / RequestInventoryCanonical
sig, _  := signer.SignDomain(verify.OSQuerySignatureDomain, canonical)
err     := verifier.VerifyDomain(verify.OSQuerySignatureDomain, canonical, sig)
Input Validation

validate/ wraps the go-playground/validator library with the project's custom rules (today: a ulid tag for ULID identifiers). RPC handlers and other server code use it via:

import "github.com/manchtools/power-manage-sdk/validate"

v := validate.NewValidator()                       // returns a *validator.Validate with rules registered
msg, ok := validate.Struct(v, request)             // returns a formatted error message
text := validate.FormatFieldError(fieldErr)        // single-field formatter

Field rules are declared via validate:"..." struct tags injected into the generated proto types (@gotags: validate:"required,ulid" etc.).

Running SDK Tests

The sys/ packages include integration tests that run inside a systemd-enabled container:

./sdk/test/run-tests.sh

This builds a test image, boots systemd, and runs all tests as a non-root user with sudo access.

TypeScript SDK

The ts/ directory contains framework-agnostic browser utilities used by the web frontend:

File Purpose
client.ts Connect-RPC client wrapping the full ControlService surface (~164 RPCs)
auth.ts JWT token management with persistent auth storage ("keep me signed in")
errors.ts Error code extraction from ConnectError details (getErrorCode())
action-types.ts Action type constants, display names, and icon mappings
config.ts Configuration utilities
offline.ts Offline support utilities

Generated TypeScript types (protobuf messages) are produced separately via Buf:

cd ../web && npx buf generate   # outputs to web/src/lib/gen/pm/v1/

Or download the ts-sdk.tar.gz from the latest release and extract into your project.

Regenerating Code

# Go (protobuf + Connect RPC + validation tags)
make generate

# TypeScript (from the web directory)
cd ../web && npx buf generate

# Install Go proto tools
make install-tools

Release coordination

Downstream repos (agent, server) pin the SDK to a specific commit via a Go pseudo-version. SDK main can change without breaking downstream builds; bumps are explicit PRs. For the full release flow — pinning, cross-cutting development with go.work, tagging conventions, and the separation between human-readable GitHub Release tags and Go module pins — see docs/release-coordination.md.

License

MIT — see LICENSE.

Documentation

Overview

Package sdk provides a client library for communicating with the power-manage server.

Index

Constants

View Source
const (
	MinHeartbeatInterval = 5 * time.Second
	MaxHeartbeatInterval = 5 * time.Minute
)

Heartbeat interval bounds. The SDK clamps server-supplied values from Welcome.heartbeat_interval into this range before applying them, so a misconfigured or malicious server can never push the cadence outside what's safe for both sides (too fast = stream spam, too slow = agent looks dead to the gateway's liveness tracking).

Variables

This section is empty.

Functions

func NewULID

func NewULID() string

NewULID generates a new ULID string.

func ValidateHTTPSURL

func ValidateHTTPSURL(raw string) error

ValidateHTTPSURL returns a non-nil error unless raw is a well-formed https://host URL. It parses rather than prefix-checks so every corner a bare "starts with https://" test misses fails closed:

  • non-https schemes (http, ftp, h2c, the empty scheme)
  • case variants (HTTP://, Https://) and leading whitespace
  • opaque forms (https:foo — Opaque != "")
  • hostless URLs (https:)
  • embedded user info (https://user:pass@host) and fragments

It is the single source for the agent's https-only trust boundaries — the enrollment server_url and the gateway URL — so a cleartext or malformed endpoint is refused before any network call.

Types

type Client

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

Client provides methods to communicate with the power-manage server.

func NewClient

func NewClient(serverURL string, opts ...ClientOption) *Client

NewClient creates a new SDK client.

func (*Client) AuthToken

func (c *Client) AuthToken() string

AuthToken returns the current auth token.

func (*Client) Close

func (c *Client) Close() error

Close closes the stream connection and cancels any pending LUKS requests.

func (*Client) CloseIdleConnections

func (c *Client) CloseIdleConnections()

CloseIdleConnections releases idle keep-alive connections held by this client's transport. The agent calls it when tearing down a connection session before reconnecting (WS13 #8): without it, each reconnect builds a fresh client whose mTLS transport keeps its own idle-connection pool, leaking sockets/file-descriptors across a long-lived reconnect loop. Safe to call on a client with no custom transport (http.DefaultClient.Transport) or a nil client.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context) error

Connect establishes a bidirectional stream with the server.

func (*Client) DeviceID

func (c *Client) DeviceID() string

DeviceID returns the current device ID.

func (*Client) GetLuksKey

func (c *Client) GetLuksKey(ctx context.Context, actionID string) (string, error)

GetLuksKey sends a GetLuksKeyRequest on the stream and waits for the correlated response. The response is matched by the message ID.

func (*Client) Receive

func (c *Client) Receive(ctx context.Context) (*pm.ServerMessage, error)

Receive receives the next message from the server.

func (*Client) Run

func (c *Client) Run(ctx context.Context, hostname, agentVersion string, heartbeatInterval time.Duration, handler StreamHandler) error

Run connects to the server and processes messages using the provided handler.

heartbeatInterval is the initial cadence used until the server's Welcome message arrives. If Welcome.heartbeat_interval is set and falls within [MinHeartbeatInterval, MaxHeartbeatInterval], the SDK resets the heartbeat ticker to that value — both on the initial connect and on every subsequent reconnect (each reconnect is a fresh Run() call that receives a fresh Welcome). Out-of-range values are clamped; zero / unset keeps the caller-supplied interval.

func (*Client) SendActionResult

func (c *Client) SendActionResult(ctx context.Context, result *pm.ActionResult) error

SendActionResult sends an action result to the server.

func (*Client) SendHeartbeat

func (c *Client) SendHeartbeat(ctx context.Context, hb *pm.Heartbeat) error

SendHeartbeat sends a heartbeat message to the server.

func (*Client) SendHello

func (c *Client) SendHello(ctx context.Context, hostname, agentVersion string) error

SendHello sends a hello message to the server.

func (*Client) SendInventory

func (c *Client) SendInventory(ctx context.Context, inventory *pm.DeviceInventory) error

SendInventory sends device inventory to the server.

func (*Client) SendLogQueryResult

func (c *Client) SendLogQueryResult(ctx context.Context, result *pm.LogQueryResult) error

SendLogQueryResult sends a log query result to the server.

func (*Client) SendOutputChunk

func (c *Client) SendOutputChunk(ctx context.Context, chunk *pm.OutputChunk) error

SendOutputChunk sends an output chunk during action execution.

func (*Client) SendQueryResult

func (c *Client) SendQueryResult(ctx context.Context, result *pm.OSQueryResult) error

SendQueryResult sends an OS query result to the server.

func (*Client) SendRevokeLuksDeviceKeyResult

func (c *Client) SendRevokeLuksDeviceKeyResult(ctx context.Context, actionID string, success bool, errMsg string) error

SendRevokeLuksDeviceKeyResult sends the result of a LUKS device key revocation back to the server.

func (*Client) SendSecurityAlert

func (c *Client) SendSecurityAlert(ctx context.Context, alert *pm.SecurityAlert) error

SendSecurityAlert sends a security alert to the server for audit logging.

func (*Client) SendTerminalOutput

func (c *Client) SendTerminalOutput(ctx context.Context, out *pm.TerminalOutput) error

SendTerminalOutput sends a stdout/stderr chunk from a remote terminal session back to the server. The TerminalHandler is responsible for chunking PTY reads to fit the proto's 64KB max data size.

func (*Client) SendTerminalStateChange

func (c *Client) SendTerminalStateChange(ctx context.Context, change *pm.TerminalStateChange) error

SendTerminalStateChange reports a terminal session lifecycle event (started, exited with code, error). Send STARTED immediately after the PTY is allocated, EXITED when the shell process exits cleanly, and ERROR for any failure that ends the session before STARTED or in flight.

func (*Client) StartReceiver

func (c *Client) StartReceiver(ctx context.Context) context.CancelFunc

StartReceiver starts a background goroutine that receives stream messages and delivers them to pending request channels (for GetLuksKey/StoreLuksKey responses). Returns a cancel function to stop the receiver. This is useful for CLI tools that need request-response correlation without the full Run() loop. The caller must call Connect() and SendHello() before calling this.

func (*Client) StoreLuksKey

func (c *Client) StoreLuksKey(ctx context.Context, actionID, devicePath, passphrase string, reason pm.RotationReason) error

StoreLuksKey sends a StoreLuksKeyRequest on the stream and waits for the server confirmation.

func (*Client) SyncActions

func (c *Client) SyncActions(ctx context.Context) (*SyncActionsResult, error)

SyncActions fetches all actions currently assigned to this device from the server. This should be called after a successful connection to sync the local action store. The returned actions should replace the agent's local action store entirely. Also returns the effective sync interval for this device.

func (*Client) ValidateLuksToken

func (c *Client) ValidateLuksToken(ctx context.Context, token string) (*ValidateLuksTokenResult, error)

ValidateLuksToken validates a one-time LUKS token via the gateway's unary RPC. The token is consumed (marked as used) atomically by the server.

type ClientOption

type ClientOption interface {
	// contains filtered or unexported methods
}

ClientOption configures the client.

func WithAuth

func WithAuth(deviceID, authToken string) ClientOption

WithAuth sets the device ID and auth token.

func WithH2C

func WithH2C() ClientOption

WithH2C configures the client to use HTTP/2 cleartext (h2c) without TLS. This is useful for development/testing when connecting to servers that use h2c instead of HTTPS. WARNING: Only use this for development/testing - data is not encrypted!

func WithHTTPClient

func WithHTTPClient(hc *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithLogger

func WithLogger(l *slog.Logger) ClientOption

WithLogger sets a custom structured logger for the client.

func WithMTLS

func WithMTLS(certFile, keyFile, caFile string) (ClientOption, error)

WithMTLS configures the client to use mTLS authentication. certFile and keyFile are the paths to the client certificate and key. caFile is the path to the CA certificate for server verification.

func WithMTLSFromPEM

func WithMTLSFromPEM(certPEM, keyPEM, caPEM []byte) (ClientOption, error)

WithMTLSFromPEM configures mTLS using PEM-encoded certificate data.

Trust is strict: the returned TLS config verifies the server ONLY against caPEM. This is the correct setup for talking to the internal-CA-signed gateway over mTLS — system roots are NOT consulted, so a cert signed by any public CA cannot impersonate the gateway even if its SNI matches.

For reaching servers whose public-facing HTTPS cert is signed by a public CA (typically a Traefik reverse proxy with Let's Encrypt in front of the control server), pair the client certificate with system roots via WithMTLSFromPEMAndSystemRoots instead.

func WithMTLSFromPEMAndSystemRoots

func WithMTLSFromPEMAndSystemRoots(certPEM, keyPEM, caPEM []byte) (ClientOption, error)

WithMTLSFromPEMAndSystemRoots is like WithMTLSFromPEM but the server-verification root pool contains caPEM PLUS the host's system roots. Use this when the server sits behind a public CA (e.g. a Traefik reverse proxy terminating TLS with Let's Encrypt) and the client cert must still authenticate the agent's identity at the application layer — for example the ControlService.RenewCertificate RPC, which can travel over a public-LE-fronted HTTPS endpoint and also passes the current certificate in the request body.

Do NOT use this for the agent-to-gateway mTLS connection: the gateway is internal-CA only, and broadening its trust to system roots lets any publicly-trusted cert with a matching SNI impersonate the gateway.

func WithTLSConfig

func WithTLSConfig(tlsConfig *tls.Config) ClientOption

WithTLSConfig configures the client with a custom TLS configuration.

type InventoryHandler

type InventoryHandler interface {
	StreamHandler
	// CollectInventory gathers hardware/software inventory from the device on
	// the agent's OWN schedule (on connect + every 24h). This is the
	// agent-initiated path: no server command is involved, so no signature is
	// required. Returns nil if collection is unavailable (e.g. osquery not
	// installed).
	CollectInventory(ctx context.Context) *pm.DeviceInventory
	// OnRequestInventory handles a SERVER-originated RequestInventory. Because
	// a compromised gateway could forge this message, the handler verifies the
	// CA signature that binds it before running osquery as root, then collects
	// the same inventory. Returns nil on verification failure or when
	// collection is unavailable.
	OnRequestInventory(ctx context.Context, req *pm.RequestInventory) *pm.DeviceInventory
}

InventoryHandler extends StreamHandler with device inventory collection support. Handlers that implement this interface can collect and send hardware/software inventory.

type LogQueryHandler

type LogQueryHandler interface {
	StreamHandler
	// OnLogQuery is called when the server sends a log query request.
	OnLogQuery(ctx context.Context, query *pm.LogQuery) (*pm.LogQueryResult, error)
}

LogQueryHandler extends StreamHandler with remote log query support. Handlers that implement this interface can execute journalctl queries on the device.

type LuksHandler

type LuksHandler interface {
	StreamHandler
	// OnRevokeLuksDeviceKey is called when the server requests revocation of a
	// LUKS device-bound key. The full message is delivered (not just the
	// action_id) so the handler can verify the CA signature that binds it
	// before performing the destructive, irreversible slot-7 wipe.
	// Returns (success, errorMessage).
	OnRevokeLuksDeviceKey(ctx context.Context, req *pm.RevokeLuksDeviceKey) (bool, string)
}

LuksHandler extends StreamHandler with LUKS device-key revocation support. Handlers that implement this interface will receive revoke requests from the server.

type RegisterAgentResult

type RegisterAgentResult struct {
	DeviceID    string
	CACert      []byte
	Certificate []byte
	GatewayURL  string
}

RegisterAgentResult contains the result of agent registration.

func RegisterAgent

func RegisterAgent(ctx context.Context, controlURL string, token, hostname, agentVersion string, csr []byte, opts ...ClientOption) (*RegisterAgentResult, error)

RegisterAgent registers an agent with the control server. This is a standalone function that uses ControlServiceClient (not AgentServiceClient). The controlURL is the control server URL (where the web UI connects). Returns the gateway URL that the agent should use for streaming.

type RenewCertificateResult

type RenewCertificateResult struct {
	Certificate []byte
	NotAfter    time.Time
	CACert      []byte // Active CA certificate (non-empty when CA has been rotated)
}

RenewCertificateResult contains the result of certificate renewal.

func RenewCertificate

func RenewCertificate(ctx context.Context, controlURL string, csr, currentCert []byte, opts ...ClientOption) (*RenewCertificateResult, error)

RenewCertificate renews a device certificate via the control server. The agent presents its current certificate for identity verification.

type StreamHandler

type StreamHandler interface {
	// OnWelcome is called when the server sends a welcome message.
	OnWelcome(ctx context.Context, welcome *pm.Welcome) error
	// OnAction is called when the server dispatches an action. The handler
	// receives the signed envelope bytes and the CA signature: it MUST
	// verify the signature over `envelope` and unmarshal THOSE SAME bytes
	// (a pm.SignedActionEnvelope) to execute — the executed action is the
	// verified action (sdk#82).
	OnAction(ctx context.Context, envelope []byte, signature []byte) (*pm.ActionResult, error)
	// OnQuery is called when the server sends an OS query.
	OnQuery(ctx context.Context, query *pm.OSQuery) (*pm.OSQueryResult, error)
	// OnError is called when the server sends an error.
	OnError(ctx context.Context, err *pm.Error) error
}

StreamHandler handles messages received from the server.

type StreamingHandler

type StreamingHandler interface {
	StreamHandler
	// OnActionWithStreaming is called when the server dispatches an action.
	// It receives the signed envelope bytes and CA signature (verify-then-
	// unmarshal-then-execute the SAME bytes; see OnAction). The sendChunk
	// callback streams output chunks during execution.
	OnActionWithStreaming(ctx context.Context, envelope []byte, signature []byte, sendChunk func(*pm.OutputChunk) error) (*pm.ActionResult, error)
}

StreamingHandler extends StreamHandler with streaming action support. Handlers that implement this interface will receive a callback to stream output chunks during action execution.

type SyncActionsResult

type SyncActionsResult struct {
	// StandaloneActions are actions assigned at the action layer (not absorbed
	// by a reached set or definition). Each fires on its own schedule.
	StandaloneActions []*pm.Action
	// GroupedActions are sets/definitions reaching this device, expressed as
	// groups that share a single schedule. Members run in declared order when
	// the group's schedule fires.
	GroupedActions []*pm.ActionGroup
	// SyncIntervalMinutes is the effective sync interval for this device.
	// 0 means use the default (30 minutes).
	SyncIntervalMinutes int32
	// MaintenanceWindow is the server-resolved union of every reaching
	// group's window (device groups + user groups assigned to the
	// device). nil means "no constraint" — the agent dispatches at any
	// time. The agent evaluates this against time.Now().Local() before
	// firing scheduler-driven dispatches; pushed actions (REBOOT,
	// SYNC, ad-hoc) bypass the gate. See manchtools/power-manage-server#58.
	MaintenanceWindow *pm.MaintenanceWindow
	// LpsPublicKey is the control server's CA-signed X25519 key the agent
	// seals LPS passwords to (spec 18). nil when the control instance has no
	// keypair configured; the agent MUST verify the signature against its
	// enrollment CA and refuse the key on mismatch before sealing to it.
	LpsPublicKey *pm.LpsPublicKey
}

SyncActionsResult contains the result of a sync actions call.

type TerminalHandler

type TerminalHandler interface {
	StreamHandler
	// OnTerminalStart is called when the server requests a new PTY.
	// The handler should validate tty_user, allocate the PTY, kick off
	// I/O goroutines, and send a TERMINAL_SESSION_STATE_STARTED state
	// change. If allocation fails, it MUST send a STATE_ERROR instead.
	OnTerminalStart(ctx context.Context, req *pm.TerminalStart) error
	// OnTerminalInput is called for every stdin frame from the server.
	// The handler should write the bytes to the PTY of the matching
	// session_id and ignore (with a debug log) frames for unknown
	// sessions.
	OnTerminalInput(ctx context.Context, req *pm.TerminalInput) error
	// OnTerminalResize forwards a TIOCSWINSZ to the session's PTY.
	// Unknown sessions are ignored.
	OnTerminalResize(ctx context.Context, req *pm.TerminalResize) error
	// OnTerminalStop terminates the session and reverts any side effects
	// (shell unmask, temp home cleanup, etc.). Unknown sessions are
	// idempotent no-ops so the server can fire and forget on disconnect.
	OnTerminalStop(ctx context.Context, req *pm.TerminalStop) error
}

TerminalHandler extends StreamHandler with remote terminal (PTY) session support. Handlers that implement this interface receive the four server-initiated session control messages from manchtools/power-manage-sdk#16 and are responsible for allocating PTYs, relaying I/O, and reporting state back via Client.SendTerminalOutput / Client.SendTerminalStateChange.

All four methods MUST return promptly: the SDK invokes them on the receive loop, so a slow handler will stall delivery of every other ServerMessage variant. Implementations should hand off to a per-session goroutine for any blocking I/O.

A nil error from these methods means the request was accepted; the handler is expected to surface terminal-level failures via SendTerminalStateChange with a TERMINAL_SESSION_STATE_ERROR payload. Returning a non-nil error from OnTerminalStart/Input/Resize/Stop is treated as a fatal stream error and tears down the agent connection.

type ValidateLuksTokenResult

type ValidateLuksTokenResult struct {
	ActionID   string
	DevicePath string
	MinLength  int32
	Complexity pm.LpsPasswordComplexity
}

ValidateLuksTokenResult contains the result of a LUKS token validation.

Directories

Path Synopsis
Package archtest holds architectural fitness functions for the SDK: self-discovering, module-wide invariant tests that fail the build when a known code smell is reintroduced or a good pattern is broken.
Package archtest holds architectural fitness functions for the SDK: self-discovering, module-wide invariant tests that fail the build when a known code smell is reintroduced or a good pattern is broken.
Package crypto provides cryptographic utilities for certificate management.
Package crypto provides cryptographic utilities for certificate management.
Package cryptotest provides shared X.509 test fixtures so the sdk and agent test suites do not each re-implement ECDSA P-256 certificate construction (WS16b DRY).
Package cryptotest provides shared X.509 test fixtures so the sdk and agent test suites do not each re-implement ECDSA P-256 certificate construction (WS16b DRY).
gen
Package maintenance hosts the canonical parser, validator, union resolver and evaluator for pm.v1.MaintenanceWindow.
Package maintenance hosts the canonical parser, validator, union resolver and evaluator for pm.v1.MaintenanceWindow.
Package pkg provides a uniform package-manager abstraction for Linux.
Package pkg provides a uniform package-manager abstraction for Linux.
sys
antivirus
Package antivirus manages an on-host antivirus engine through an injected exec.Runner.
Package antivirus manages an on-host antivirus engine through an injected exec.Runner.
catrust
Package catrust manages the host's system-wide CA trust anchors through an injected exec.Runner (plus the fs.Manager for the privileged file writes).
Package catrust manages the host's system-wide CA trust anchors through an injected exec.Runner (plus the fs.Manager for the privileged file writes).
desktop
Package desktop discovers active graphical desktop sessions on the host so user-scoped actions (Flatpak --user installs, shell scripts that need a real $HOME and DBus session bus, etc.) can fan out to every currently-signed-in user instead of running under the agent's own root context.
Package desktop discovers active graphical desktop sessions on the host so user-scoped actions (Flatpak --user installs, shell scripts that need a real $HOME and DBus session bus, etc.) can fan out to every currently-signed-in user instead of running under the agent's own root context.
dns
Package dns manages a host's DNS resolver configuration through an injected exec.Runner.
Package dns manages a host's DNS resolver configuration through an injected exec.Runner.
encryption
Package encryption manages disk encryption through an injected exec.Runner.
Package encryption manages disk encryption through an injected exec.Runner.
exec
Package exec provides command execution utilities for Linux system management.
Package exec provides command execution utilities for Linux system management.
exec/exectest
Package exectest provides a fake exec.Runner for unit-testing capability packages with no host, no sudo, and no container.
Package exectest provides a fake exec.Runner for unit-testing capability packages with no host, no sudo, and no container.
firewall
Package firewall is a cross-backend abstraction for host packet-filter management.
Package firewall is a cross-backend abstraction for host packet-filter management.
fs
Package fs provides privileged filesystem operations for Linux system management, driven by an injected exec.Runner rather than a process-global privilege backend.
Package fs provides privileged filesystem operations for Linux system management, driven by an injected exec.Runner rather than a process-global privilege backend.
inventory
Package inventory provides lightweight system inventory collection using standard Linux interfaces (/proc, /etc, standard tools) without requiring osquery.
Package inventory provides lightweight system inventory collection using standard Linux interfaces (/proc, /etc, standard tools) without requiring osquery.
log
Package log reads system logs through an injected exec.Runner.
Package log reads system logs through an injected exec.Runner.
netconfig
Package netconfig manages a host's per-interface IP / routing / MTU configuration through an injected exec.Runner.
Package netconfig manages a host's per-interface IP / routing / MTU configuration through an injected exec.Runner.
network
Package network manages WiFi connection profiles through an injected exec.Runner.
Package network manages WiFi connection profiles through an injected exec.Runner.
notify
Package notify sends system-wide notifications to logged-in users through an injected exec.Runner.
Package notify sends system-wide notifications to logged-in users through an injected exec.Runner.
osquery
Package osquery integrates the osquery binary for system queries through an injected exec.Runner.
Package osquery integrates the osquery binary for system queries through an injected exec.Runner.
reboot
Package reboot provides system reboot detection and scheduling through an injected exec.Runner.
Package reboot provides system reboot detection and scheduling through an injected exec.Runner.
remote
Package remote pulls files or directory trees onto a managed machine from one of three sources: a public HTTP URL, a version-controlled repository (Git in v1, with a pluggable interface for future drivers), or an anonymous S3-compatible endpoint.
Package remote pulls files or directory trees onto a managed machine from one of three sources: a public HTTP URL, a version-controlled repository (Git in v1, with a pluggable interface for future drivers), or an anonymous S3-compatible endpoint.
repo
Package repo configures external package-manager repositories through an injected exec.Runner, the same dependency-injected idiom as pkg/fs/network.
Package repo configures external package-manager repositories through an injected exec.Runner, the same dependency-injected idiom as pkg/fs/network.
service
Package service manages init/service units through an injected exec.Runner.
Package service manages init/service units through an injected exec.Runner.
smart
Package smart reads S.M.A.R.T. disk health via smartctl (smartmontools) through an injected exec.Runner.
Package smart reads S.M.A.R.T. disk health via smartctl (smartmontools) through an injected exec.Runner.
terminal
Package terminal provides PTY-based shell session management for remote terminal access.
Package terminal provides PTY-based shell session management for remote terminal access.
timesync
Package timesync reads a host's clock-synchronization status through an injected exec.Runner.
Package timesync reads a host's clock-synchronization status through an injected exec.Runner.
user
Package user manages Linux user accounts and groups through an injected exec.Runner.
Package user manages Linux user accounts and groups through an injected exec.Runner.
test
protovalidatecoverage command
Command protovalidatecoverage scans .proto files under the supplied directory and prints a human-readable summary of fields that lack a `validate:` constraint declared via the @gotags marker (protoc-go-inject-tag convention), across ALL messages (requests AND responses) for triage.
Command protovalidatecoverage scans .proto files under the supplied directory and prints a human-readable summary of fields that lack a `validate:` constraint declared via the @gotags marker (protoc-go-inject-tag convention), across ALL messages (requests AND responses) for triage.
Package verify provides action signature signing and verification.
Package verify provides action signature signing and verification.

Jump to

Keyboard shortcuts

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