apiclient

package
v0.5.81 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ConfigKey is the top-level JSON key the API configuration lives under
	// in the on-disk config file (osctrl-api.json). Previously read from
	// cmd/cli's projectName const; inlined here so the package stands alone.
	ConfigKey = "osctrl"
	// APIPath for the generic API path in osctrl
	APIPath = "/api/v1"
	// APINodes for the nodes path
	APINodes = "/nodes"
	// APIQueries for the queries path
	APIQueries = "/queries"
	// APICarves for the carves path
	APICarves = "/carves"
	// APIUsers for the users path
	APIUSers = "/users"
	// APIEnvironments for the environments path
	APIEnvironments = "/environments"
	// APITags for the tags path
	APITags = "/tags"
	// APILogin for the login path
	APILogin = "/login"
	// APIAuditLogs for the audit logs path
	APIAuditLogs = "/audit-logs"
	// APIStats for the fleet statistics path
	APIStats = "/stats"
	// APIOsquery for the osquery schema path
	APIOsquery = "/osquery"
	// APIChecksNoAuth for the unauthenticated checks path
	APIChecksNoAuth = "/checks-no-auth"
	// APIChecksAuth for the authenticated checks path
	APIChecksAuth = "/checks-auth"
	// JSONApplication for Content-Type headers
	JSONApplication = "application/json"
	// JSONApplicationUTF8 for Content-Type headers, UTF charset
	JSONApplicationUTF8 = JSONApplication + "; charset=UTF-8"
	// ContentType for header key
	ContentType = "Content-Type"
	// UserAgent for header key
	UserAgent = "User-Agent"
	// Authorization for header key
	Authorization = "Authorization"
)

Variables

This section is empty.

Functions

func WriteConfiguration

func WriteConfiguration(file string, apiConf JSONConfigurationAPI) error

WriteConfiguration to write the API configuration file and update values

Types

type AlertChannelJSON

type AlertChannelJSON struct {
	ID            uint            `json:"id"`
	Name          string          `json:"name"`
	EnvironmentID uint            `json:"environment_id"`
	Type          string          `json:"type"`
	Enabled       bool            `json:"enabled"`
	Config        json.RawMessage `json:"config"`
	Info          string          `json:"info"`
}

AlertChannelJSON mirrors the API DTO (config decoded).

type AlertRuleJSON

type AlertRuleJSON struct {
	ID              uint   `json:"id"`
	Name            string `json:"name"`
	EnvironmentID   uint   `json:"environment_id"`
	Source          string `json:"source"`
	MatchType       string `json:"match_type"`
	MatchField      string `json:"match_field"`
	MatchValue      string `json:"match_value"`
	StatusSeverity  string `json:"status_severity"`
	CooldownMinutes int    `json:"cooldown_minutes"`
	ChannelIDs      []uint `json:"channel_ids"`
	Enabled         bool   `json:"enabled"`
	Info            string `json:"info"`
}

AlertRuleJSON mirrors the API DTO.

type ConsoleCommandResponse

type ConsoleCommandResponse struct {
	Command console.Command       `json:"command"`
	Parsed  console.ParsedCommand `json:"parsed"`
}

ConsoleCommandResponse mirrors the submit-command response.

type ConsoleNodeInfo

type ConsoleNodeInfo struct {
	IPAddress       string `json:"ip_address"`
	OsqueryUser     string `json:"osquery_user"`
	OsqueryVersion  string `json:"osquery_version"`
	Platform        string `json:"platform"`
	PlatformVersion string `json:"platform_version"`
}

ConsoleNodeInfo mirrors the API's node_info projection for a console session.

type ConsoleSessionResponse

type ConsoleSessionResponse struct {
	Session  console.Session        `json:"session"`
	History  []console.HistoryEntry `json:"history"`
	NodeInfo ConsoleNodeInfo        `json:"node_info"`
}

ConsoleSessionResponse mirrors the create-session response (session + history + node info).

type EnvStats

type EnvStats struct {
	UUID           string         `json:"uuid"`
	Name           string         `json:"name"`
	TotalNodes     int64          `json:"total_nodes"`
	ActiveNodes    int64          `json:"active_nodes"`
	InactiveNodes  int64          `json:"inactive_nodes"`
	PlatformCounts PlatformCounts `json:"platform_counts"`
}

EnvStats is the per-environment slice of the stats response.

type FeaturesResponse

type FeaturesResponse struct {
	Posture       bool `json:"posture"`
	ServiceConfig bool `json:"service_config"`
	LogSinks      bool `json:"log_sinks"`
	AuthProviders bool `json:"auth_providers"`
	Accelerated   bool `json:"accelerated"`
	Console       bool `json:"console"`
	FileExplorer  bool `json:"file_explorer"`
}

FeaturesResponse mirrors the /features deployment switches.

type FileExplorerSessionResponse

type FileExplorerSessionResponse struct {
	Session  fileexplorer.Session `json:"session"`
	NodeInfo ConsoleNodeInfo      `json:"node_info"`
}

FileExplorerSessionResponse mirrors the create-session response.

type JSONConfigurationAPI

type JSONConfigurationAPI struct {
	URL   string `json:"url"`
	Token string `json:"token"`
}

JSONConfigurationAPI to hold all API configuration values

func LoadConfiguration

func LoadConfiguration(file string) (JSONConfigurationAPI, error)

LoadConfiguration to load the API configuration file and assign to variables

type OsctrlAPI

type OsctrlAPI struct {
	Configuration JSONConfigurationAPI
	Client        *http.Client
	Headers       map[string]string
}

OsctrlAPI to keep the struct for the API client

func CreateAPI

func CreateAPI(config JSONConfigurationAPI, insecure bool) (*OsctrlAPI, error)

CreateAPI to initialize the API client and handlers.

Returns an error rather than calling log.Fatal on bad input: as a library this is called by long-lived processes (and by tests) where killing the process on a malformed URL is not an acceptable failure mode. Callers that genuinely want to abort should log.Fatal on the returned error themselves.

func CreateAPIWithTransport

func CreateAPIWithTransport(config JSONConfigurationAPI, rt http.RoundTripper) (*OsctrlAPI, error)

CreateAPIWithTransport builds a client that issues its requests through rt instead of the network.

This exists so osctrl-api can host an MCP server against its own handlers: the transport dispatches straight into the service's mux, so tool calls run the real handler chain — same authentication, same per-endpoint permission checks, same audit logging — without a socket. The alternative, reaching into the managers directly, would mean restating authorization policy that is deliberately non-uniform across endpoints, and any drift there over-grants silently.

config.URL still has to parse; the transport is free to ignore its host and route on the path alone.

func (*OsctrlAPI) ActionEnrollmentRemove

func (api *OsctrlAPI) ActionEnrollmentRemove(identifier, action, target string, data io.Reader) (string, error)

ExtendEnrollment to extend in time the enrollment URL of an environment

func (*OsctrlAPI) AddTag

func (api *OsctrlAPI) AddTag(env, name, color, icon, description string, tagType uint, custom string) (types.ApiGenericResponse, error)

AddTag to add a tag to osctrl

func (*OsctrlAPI) ApplyAlerts

func (api *OsctrlAPI) ApplyAlerts() error

ApplyAlerts queues the reload-alerts service command for osctrl-tls.

func (*OsctrlAPI) CheckAPI

func (api *OsctrlAPI) CheckAPI() error

CheckApiAuth to check if API authentication is working

func (*OsctrlAPI) CloseConsoleSession

func (api *OsctrlAPI) CloseConsoleSession(env string, sessionID uint) error

CloseConsoleSession closes a console session.

func (*OsctrlAPI) CloseFileExplorerSession

func (api *OsctrlAPI) CloseFileExplorerSession(env string, sessionID uint) error

CloseFileExplorerSession closes a file explorer session.

func (*OsctrlAPI) CompleteCarve

func (api *OsctrlAPI) CompleteCarve(env, name string) (types.ApiGenericResponse, error)

CompleteCarve to complete a carve from osctrl

func (*OsctrlAPI) CompleteQuery

func (api *OsctrlAPI) CompleteQuery(env, name string) (types.ApiGenericResponse, error)

CompleteQuery to complete a query from osctrl

func (*OsctrlAPI) CreateAlertChannel

func (api *OsctrlAPI) CreateAlertChannel(name, typ, configJSON string, envID uint, enabled bool) error

CreateAlertChannel creates a notification channel.

func (*OsctrlAPI) CreateAlertRule

func (api *OsctrlAPI) CreateAlertRule(rule alerts.AlertRule) error

CreateAlertRule creates an alert rule.

func (*OsctrlAPI) CreateConsoleSession

func (api *OsctrlAPI) CreateConsoleSession(env, uuid string) (ConsoleSessionResponse, error)

CreateConsoleSession opens a console session against a node.

func (*OsctrlAPI) CreateFileExplorerSession

func (api *OsctrlAPI) CreateFileExplorerSession(env, uuid string) (FileExplorerSessionResponse, error)

CreateFileExplorerSession opens a file explorer session against a node.

func (*OsctrlAPI) CreateSavedQuery

func (api *OsctrlAPI) CreateSavedQuery(env, name, query string) error

CreateSavedQuery saves a new query in an environment.

func (*OsctrlAPI) CreateUser

func (api *OsctrlAPI) CreateUser(username, password, email, fullname, environment string, admin, service bool) error

CreateUser to create user in osctrl, it also creates permissions

func (*OsctrlAPI) DeleteAlertChannel

func (api *OsctrlAPI) DeleteAlertChannel(id uint) error

DeleteAlertChannel removes a channel by ID.

func (*OsctrlAPI) DeleteAlertRule

func (api *OsctrlAPI) DeleteAlertRule(id uint) error

DeleteAlertRule removes an alert rule by ID.

func (*OsctrlAPI) DeleteCarve

func (api *OsctrlAPI) DeleteCarve(env, name string) (types.ApiGenericResponse, error)

DeleteCarve to delete carve from osctrl

func (*OsctrlAPI) DeleteNode

func (api *OsctrlAPI) DeleteNode(env, identifier string) error

DeleteNode to delete node from osctrl

func (*OsctrlAPI) DeleteQuery

func (api *OsctrlAPI) DeleteQuery(env, name string) (types.ApiGenericResponse, error)

DeleteQuery to delete query from osctrl

func (*OsctrlAPI) DeleteSavedQuery

func (api *OsctrlAPI) DeleteSavedQuery(env, name string) error

DeleteSavedQuery removes a saved query by name.

func (*OsctrlAPI) DeleteTag

func (api *OsctrlAPI) DeleteTag(env, name string) (types.ApiGenericResponse, error)

DeleteTag to delete a tag from osctrl

func (*OsctrlAPI) DeleteUser

func (api *OsctrlAPI) DeleteUser(username string) error

DeleteUser to delete user from osctrl

func (*OsctrlAPI) EditTag

func (api *OsctrlAPI) EditTag(env, name, color, icon, description string, tagType uint, custom string) (types.ApiGenericResponse, error)

EditTag to edit a tag from osctrl

func (*OsctrlAPI) EditUser

func (api *OsctrlAPI) EditUser(username, password, email, fullname, environment string, admin, service bool) error

EditUser to edit a user in osctrl, it takes individual parameters as input

func (*OsctrlAPI) EditUserReq

func (api *OsctrlAPI) EditUserReq(u types.ApiUserRequest) error

EditUserReq to edit a user in osctrl, it takes a ApiUserRequest as input

func (*OsctrlAPI) ExpireCarve

func (api *OsctrlAPI) ExpireCarve(env, name string) (types.ApiGenericResponse, error)

ExpireCarve to expire carve from osctrl

func (*OsctrlAPI) ExpireEnrollment

func (api *OsctrlAPI) ExpireEnrollment(identifier string) (string, error)

ExpireEnrollment to expire the enrollment URL of an environment

func (*OsctrlAPI) ExpireQuery

func (api *OsctrlAPI) ExpireQuery(env, name string) (types.ApiGenericResponse, error)

ExpireQuery to expire query from osctrl

func (*OsctrlAPI) ExpireRemove

func (api *OsctrlAPI) ExpireRemove(identifier string) (string, error)

ExpireRemove to expire the remove URL of an environment

func (*OsctrlAPI) ExtendEnrollment

func (api *OsctrlAPI) ExtendEnrollment(identifier string) (string, error)

ExtendEnrollment to extend in time the enrollment URL of an environment

func (*OsctrlAPI) ExtendRemove

func (api *OsctrlAPI) ExtendRemove(identifier string) (string, error)

ExtendRemove to extend in time the remove URL of an environment

func (*OsctrlAPI) GetAlertChannels

func (api *OsctrlAPI) GetAlertChannels() ([]AlertChannelJSON, error)

GetAlertChannels lists alert channels.

func (*OsctrlAPI) GetAlertRules

func (api *OsctrlAPI) GetAlertRules() ([]AlertRuleJSON, error)

GetAlertRules lists alert rules.

func (*OsctrlAPI) GetAllTags

func (api *OsctrlAPI) GetAllTags() ([]tags.AdminTag, error)

GetAllTags to retrieve all tags from osctrl

func (*OsctrlAPI) GetAuditLogs

func (api *OsctrlAPI) GetAuditLogs() ([]auditlog.AuditLog, error)

GetAuditLogs to retrieve all audit logs from osctrl

func (*OsctrlAPI) GetCarve

func (api *OsctrlAPI) GetCarve(env, name string) (carves.CarvedFile, error)

GetCarve to retrieve one carve from osctrl

func (*OsctrlAPI) GetCarveQueries

func (api *OsctrlAPI) GetCarveQueries(target, env string) ([]queries.DistributedQuery, error)

GetCarveQueries to retrieve carves from osctrl

func (*OsctrlAPI) GetCarves

func (api *OsctrlAPI) GetCarves(env string) ([]carves.CarvedFile, error)

GetCarves to retrieve carves from osctrl

func (*OsctrlAPI) GetConsoleCommand

func (api *OsctrlAPI) GetConsoleCommand(env string, sessionID, commandID uint) (console.Command, error)

GetConsoleCommand retrieves the current state of a console command.

func (*OsctrlAPI) GetConsoleCommandResults

func (api *OsctrlAPI) GetConsoleCommandResults(env string, sessionID, commandID uint) ([]map[string]any, error)

GetConsoleCommandResults retrieves the rows produced by a completed console command.

func (*OsctrlAPI) GetConsoleSession

func (api *OsctrlAPI) GetConsoleSession(env string, sessionID uint) (console.Session, error)

GetConsoleSession retrieves the current state of a console session.

func (*OsctrlAPI) GetEnvMap

func (api *OsctrlAPI) GetEnvMap() (environments.MapEnvByID, error)

GetEnvMap to retrieve a map of environments by ID

func (*OsctrlAPI) GetEnvironment

func (api *OsctrlAPI) GetEnvironment(identifier string) (environments.TLSEnvironment, error)

GetEnvironment to retrieve users from osctrl

func (*OsctrlAPI) GetEnvironments

func (api *OsctrlAPI) GetEnvironments() ([]environments.TLSEnvironment, error)

GetEnvironments to retrieve all environments from osctrl

func (*OsctrlAPI) GetFeatures

func (api *OsctrlAPI) GetFeatures() (FeaturesResponse, error)

GetFeatures retrieves the deployment feature switches.

func (*OsctrlAPI) GetFileExplorerRequest

func (api *OsctrlAPI) GetFileExplorerRequest(env string, sessionID, requestID uint) (fileexplorer.Request, error)

GetFileExplorerRequest retrieves the current state of a file explorer request.

func (*OsctrlAPI) GetFileExplorerResults

func (api *OsctrlAPI) GetFileExplorerResults(env string, sessionID, requestID uint) ([]fileexplorer.Entry, error)

GetFileExplorerResults retrieves entries produced by a completed request.

func (*OsctrlAPI) GetGeneric

func (api *OsctrlAPI) GetGeneric(url string, body io.Reader) ([]byte, error)

GetGeneric - Helper function to implement generic retrieval from API with a GET request

func (*OsctrlAPI) GetNode

func (api *OsctrlAPI) GetNode(env, identifier string) (nodes.OsqueryNode, error)

GetNode to retrieve one node from osctrl

func (*OsctrlAPI) GetNodeLogs

func (api *OsctrlAPI) GetNodeLogs(env, logType, uuid string) (string, error)

GetNodeLogs retrieves recent result or status logs for a node. logType is "result" or "status".

func (*OsctrlAPI) GetNodePosture

func (api *OsctrlAPI) GetNodePosture(env, uuid string) ([]posture.NodePosture, error)

GetNodePosture retrieves all posture categories for a node.

func (*OsctrlAPI) GetNodePostureScore

func (api *OsctrlAPI) GetNodePostureScore(env, uuid string) (posture.PostureScore, error)

GetNodePostureScore retrieves the SOC2/ISO27001 risk score for a node.

func (*OsctrlAPI) GetNodes

func (api *OsctrlAPI) GetNodes(env, target string) ([]nodes.OsqueryNode, error)

GetNodes to retrieve nodes from osctrl

func (*OsctrlAPI) GetOsqueryTables

func (api *OsctrlAPI) GetOsqueryTables() ([]types.OsqueryTable, error)

GetOsqueryTables to retrieve the osquery schema osctrl was configured with

func (*OsctrlAPI) GetPostureProfiles

func (api *OsctrlAPI) GetPostureProfiles() ([]posture.PostureProfile, error)

GetPostureProfiles lists the predefined posture profile templates.

func (*OsctrlAPI) GetQueries

func (api *OsctrlAPI) GetQueries(target, env string) ([]queries.DistributedQuery, error)

GetQueries to retrieve queries from osctrl

func (*OsctrlAPI) GetQuery

func (api *OsctrlAPI) GetQuery(env, name string) (queries.DistributedQuery, error)

GetQuery to retrieve one query from osctrl

func (*OsctrlAPI) GetQueryResults

func (api *OsctrlAPI) GetQueryResults(env, name string, page, pageSize int) (types.QueryResultsResponse, error)

GetQueryResults to retrieve the results collected so far for a query.

Distributed queries are asynchronous: RunQuery returns as soon as the query is scheduled, and rows arrive over the following seconds or minutes as nodes check in. Callers poll this until TotalItems stops growing — there is no "query finished" signal beyond the query's own expiration.

page starts at 1; pageSize is clamped server-side to 1000 (default 100). Requires QueryLevel on the environment, not merely UserLevel.

func (*OsctrlAPI) GetQuerySamples

func (api *OsctrlAPI) GetQuerySamples() ([]queries.QuerySample, error)

GetQuerySamples lists the built-in query sample templates.

func (*OsctrlAPI) GetSavedQueries

func (api *OsctrlAPI) GetSavedQueries(env string) ([]types.SavedQueryView, error)

GetSavedQueries lists saved queries for an environment.

func (*OsctrlAPI) GetStats

func (api *OsctrlAPI) GetStats() (StatsResponse, error)

GetStats to retrieve fleet-wide counts from osctrl

func (*OsctrlAPI) GetTag

func (api *OsctrlAPI) GetTag(env, name string) (tags.AdminTag, error)

GetTag to retrieve a tag from osctrl by environment and name

func (*OsctrlAPI) GetTags

func (api *OsctrlAPI) GetTags(env string) ([]tags.AdminTag, error)

GetTags to retrieve tags from osctrl by environment

func (*OsctrlAPI) GetUser

func (api *OsctrlAPI) GetUser(username string) (users.AdminUser, error)

GetUser to retrieve one user from osctrl

func (*OsctrlAPI) GetUsers

func (api *OsctrlAPI) GetUsers() ([]users.AdminUser, error)

GetUsers to retrieve users from osctrl

func (*OsctrlAPI) LookupNode

func (api *OsctrlAPI) LookupNode(identifier string) (nodes.OsqueryNode, error)

LookupNode to look up node from osctrl by identifier (UUID, localname or hostname)

func (*OsctrlAPI) NotexpireEnrollment

func (api *OsctrlAPI) NotexpireEnrollment(identifier string) (string, error)

NotexpireEnrollment to disable expiration for the enrollment URL of an environment

func (*OsctrlAPI) NotexpireRemove

func (api *OsctrlAPI) NotexpireRemove(identifier string) (string, error)

NotexpireRemove to disable expiration for the remove URL of an environment

func (*OsctrlAPI) PostGeneric

func (api *OsctrlAPI) PostGeneric(url string, body io.Reader) ([]byte, error)

PostGeneric - Helper function to implement generic retrieval from API with a POST request

func (*OsctrlAPI) PostLogin

func (api *OsctrlAPI) PostLogin(env, username, password string, expHours int) (types.ApiLoginResponse, error)

PostLogin to login into API to retrieve a token

func (*OsctrlAPI) ReqGeneric

func (api *OsctrlAPI) ReqGeneric(reqType string, url string, body io.Reader) ([]byte, error)

ReqGeneric - Helper function to implement generic retrieval from API with a POST request

func (*OsctrlAPI) RotateEnrollment

func (api *OsctrlAPI) RotateEnrollment(identifier string) (string, error)

RotateEnrollment to rotate the enrollment URL of an environment

func (*OsctrlAPI) RotateRemove

func (api *OsctrlAPI) RotateRemove(identifier string) (string, error)

RotateEnrollment to rotate the remove URL of an environment

func (*OsctrlAPI) RunCarve

func (api *OsctrlAPI) RunCarve(env, fPath string, uuids, hosts, platforms, tags []string, hidden bool, exp int) (types.ApiQueriesResponse, error)

RunCarve to initiate a carve in osctrl

func (*OsctrlAPI) RunQuery

func (api *OsctrlAPI) RunQuery(env, query string, uuids, hosts, platforms, tags []string, hidden bool, exp int) (types.ApiQueriesResponse, error)

RunQuery to initiate a query in osctrl

func (*OsctrlAPI) SubmitConsoleCommand

func (api *OsctrlAPI) SubmitConsoleCommand(env string, sessionID uint, input string, osqueryMode bool) (ConsoleCommandResponse, error)

SubmitConsoleCommand sends a console command within a session.

func (*OsctrlAPI) SubmitFileExplorerList

func (api *OsctrlAPI) SubmitFileExplorerList(env string, sessionID uint, target string) (fileexplorer.Request, error)

SubmitFileExplorerList lists a directory path on the node.

func (*OsctrlAPI) SubmitFileExplorerStat

func (api *OsctrlAPI) SubmitFileExplorerStat(env string, sessionID uint, target string) (fileexplorer.Request, error)

SubmitFileExplorerStat stats a path on the node.

func (*OsctrlAPI) TagNode

func (api *OsctrlAPI) TagNode(env, identifier, tag string, tagType uint, custom string) error

TagNode to tag node in osctrl

func (*OsctrlAPI) UpdateSavedQuery

func (api *OsctrlAPI) UpdateSavedQuery(env, name, query string) error

UpdateSavedQuery replaces the SQL body of an existing saved query.

type PlatformCounts

type PlatformCounts struct {
	Linux   int64 `json:"linux"`
	Darwin  int64 `json:"darwin"`
	Windows int64 `json:"windows"`
	Other   int64 `json:"other"`
}

PlatformCounts mirrors the per-platform node tallies the stats endpoint returns for each environment.

type StatsResponse

type StatsResponse struct {
	TotalNodes         int64          `json:"total_nodes"`
	ActiveNodes        int64          `json:"active_nodes"`
	InactiveNodes      int64          `json:"inactive_nodes"`
	InactiveHours      int64          `json:"inactive_hours"`
	TotalActiveQueries int            `json:"total_active_queries"`
	TotalActiveCarves  int            `json:"total_active_carves"`
	Platforms          PlatformCounts `json:"platform_counts"`
	Environments       []EnvStats     `json:"environments"`
}

StatsResponse mirrors GET /api/v1/stats.

Hand-typed here rather than imported: the canonical struct lives in cmd/api/handlers, and importing that package would drag the whole server (database, settings, logger sinks) into every client. The API only ever adds fields to this response, and unknown fields decode away silently, so the duplication is cheap to keep in sync.

Note the response is already scoped to what the caller may see — the handler filters environments through Users.CheckPermissions, so a restricted token gets a smaller Environments slice, not a 403.

Jump to

Keyboard shortcuts

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